sscs-assignment1 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
File without changes
rekor_monitor/main.py ADDED
@@ -0,0 +1,205 @@
1
+ import argparse
2
+ import base64
3
+ import json
4
+ import os
5
+
6
+ import requests
7
+
8
+ from merkle_proof import (
9
+ DefaultHasher,
10
+ compute_leaf_hash,
11
+ verify_consistency,
12
+ verify_inclusion,
13
+ )
14
+ from util import extract_public_key, verify_artifact_signature
15
+
16
+
17
+ def get_log_entry(log_index, debug=False):
18
+ if isinstance(log_index, bool) or not isinstance(log_index, int) or log_index < 0:
19
+ raise ValueError("Log index must be a non-negative integer")
20
+
21
+ endpoint = "https://rekor.sigstore.dev/api/v1/log/entries"
22
+ response = requests.get(endpoint, params={"logIndex": log_index}, timeout=5)
23
+ response.raise_for_status()
24
+ data = response.json()
25
+
26
+ entry = data[next(iter(data.keys()))]
27
+ return entry
28
+
29
+
30
+ def get_verification_proof(entry):
31
+ inclusion_proof = entry["verification"]["inclusionProof"]
32
+ return (
33
+ inclusion_proof["logIndex"],
34
+ inclusion_proof["treeSize"],
35
+ inclusion_proof["hashes"],
36
+ inclusion_proof["rootHash"],
37
+ )
38
+
39
+
40
+ def inclusion(log_index, artifact_filepath, debug=False):
41
+ if isinstance(log_index, bool) or not isinstance(log_index, int) or log_index < 0:
42
+ raise ValueError("Log index must be a non-negative integer")
43
+
44
+ if not artifact_filepath or not os.path.isfile(artifact_filepath):
45
+ raise ValueError("Artifact filepath must point to an existing file")
46
+
47
+ # Fetch the entry once and reuse it throughout verification.
48
+ entry = get_log_entry(log_index, debug)
49
+
50
+ if "code" in entry:
51
+ print(entry["code"])
52
+ return
53
+
54
+ body = json.loads(base64.b64decode(entry["body"]).decode())
55
+
56
+ # Extract signature and certificate.
57
+ spec_sig = body["spec"]["signature"]
58
+ signature = base64.b64decode(spec_sig["content"])
59
+ certificate = base64.b64decode(spec_sig["publicKey"]["content"])
60
+ public_key = extract_public_key(certificate)
61
+
62
+ # Verify the artifact's signature.
63
+ verify_artifact_signature(signature, public_key, artifact_filepath)
64
+
65
+ # Calculate the leaf hash and reuse the fetched entry's proof.
66
+ leaf_hash = str(compute_leaf_hash(entry["body"]))
67
+
68
+ inc_log_index, tree_size, hashes, root_hash = (
69
+ get_verification_proof(entry)
70
+ )
71
+
72
+ verify_inclusion(
73
+ DefaultHasher,
74
+ inc_log_index,
75
+ tree_size,
76
+ leaf_hash,
77
+ hashes,
78
+ root_hash,
79
+ )
80
+
81
+ print("Offline verification successful")
82
+
83
+
84
+ def get_latest_checkpoint(debug=False):
85
+ endpoint = "https://rekor.sigstore.dev/api/v1/log/"
86
+ response = requests.get(endpoint, timeout=5)
87
+ response.raise_for_status()
88
+ return response.json()
89
+
90
+
91
+ def consistency(prev_checkpoint, debug=False):
92
+ if not prev_checkpoint:
93
+ print("prev checkpoint empty")
94
+ return
95
+
96
+ latest_checkpoint = get_latest_checkpoint()
97
+
98
+ latest_size = latest_checkpoint["treeSize"]
99
+ prev_size = prev_checkpoint["treeSize"]
100
+ tree_id = prev_checkpoint["treeID"]
101
+ latest_root = latest_checkpoint["rootHash"]
102
+ prev_root = prev_checkpoint["rootHash"]
103
+
104
+ url = (
105
+ "https://rekor.sigstore.dev/api/v1/log/proof"
106
+ f"?firstSize={prev_size}"
107
+ f"&lastSize={latest_size}"
108
+ f"&treeID={tree_id}"
109
+ )
110
+
111
+ response = requests.get(url, timeout=5)
112
+ response.raise_for_status()
113
+ proof = response.json()["hashes"]
114
+
115
+ verify_consistency(
116
+ DefaultHasher,
117
+ prev_size,
118
+ latest_size,
119
+ proof,
120
+ prev_root,
121
+ latest_root,
122
+ )
123
+
124
+ print("Consistency verification successful")
125
+
126
+
127
+ def main():
128
+ debug = False
129
+ parser = argparse.ArgumentParser(description="Rekor Verifier")
130
+
131
+ parser.add_argument(
132
+ "-d", "--debug",
133
+ help="Debug mode",
134
+ action="store_true",
135
+ )
136
+ parser.add_argument(
137
+ "-c", "--checkpoint",
138
+ help="Obtain latest checkpoint from Rekor Server public instance",
139
+ action="store_true",
140
+ )
141
+ parser.add_argument(
142
+ "--inclusion",
143
+ help="Verify inclusion of an entry using its log index",
144
+ type=int,
145
+ )
146
+ parser.add_argument(
147
+ "--artifact",
148
+ help="Artifact filepath for verifying signature",
149
+ )
150
+ parser.add_argument(
151
+ "--consistency",
152
+ help="Verify consistency of a given checkpoint with the latest checkpoint",
153
+ action="store_true",
154
+ )
155
+ parser.add_argument(
156
+ "--tree-id",
157
+ help="Tree ID for consistency proof",
158
+ )
159
+ parser.add_argument(
160
+ "--tree-size",
161
+ help="Tree size for consistency proof",
162
+ type=int,
163
+ )
164
+ parser.add_argument(
165
+ "--root-hash",
166
+ help="Root hash for consistency proof",
167
+ )
168
+
169
+ args = parser.parse_args()
170
+
171
+ if args.debug:
172
+ debug = True
173
+ print("enabled debug mode")
174
+
175
+ if args.checkpoint:
176
+ checkpoint = get_latest_checkpoint(debug)
177
+ print(json.dumps(checkpoint, indent=4))
178
+
179
+ # Explicitly check for None so log index 0 is valid.
180
+ if args.inclusion is not None:
181
+ if not args.artifact:
182
+ parser.error("--artifact is required with --inclusion")
183
+ inclusion(args.inclusion, args.artifact, debug)
184
+
185
+ if args.consistency:
186
+ if not args.tree_id:
187
+ parser.error("--tree-id is required with --consistency")
188
+ if args.tree_size is None:
189
+ parser.error("--tree-size is required with --consistency")
190
+ if args.tree_size < 0:
191
+ parser.error("--tree-size must be non-negative")
192
+ if not args.root_hash:
193
+ parser.error("--root-hash is required with --consistency")
194
+
195
+ prev_checkpoint = {
196
+ "treeID": args.tree_id,
197
+ "treeSize": args.tree_size,
198
+ "rootHash": args.root_hash,
199
+ }
200
+
201
+ consistency(prev_checkpoint, debug)
202
+
203
+
204
+ if __name__ == "__main__":
205
+ main()
@@ -0,0 +1,164 @@
1
+ import base64
2
+ import binascii
3
+ import hashlib
4
+
5
+ # domain separation prefixes according to the RFC
6
+ RFC6962_LEAF_HASH_PREFIX = 0
7
+ RFC6962_NODE_HASH_PREFIX = 1
8
+
9
+ class Hasher:
10
+ def __init__(self, hash_func=hashlib.sha256):
11
+ self.hash_func = hash_func
12
+
13
+ def new(self):
14
+ return self.hash_func()
15
+
16
+ def empty_root(self):
17
+ return self.new().digest()
18
+
19
+ def hash_leaf(self, leaf):
20
+ h = self.new()
21
+ h.update(bytes([RFC6962_LEAF_HASH_PREFIX]))
22
+ h.update(leaf)
23
+ return h.digest()
24
+
25
+ def hash_children(self, l, r):
26
+ h = self.new()
27
+ b = bytes([RFC6962_NODE_HASH_PREFIX]) + l + r
28
+ h.update(b)
29
+ return h.digest()
30
+
31
+ def size(self):
32
+ return self.new().digest_size
33
+
34
+ # DefaultHasher is a SHA256 based LogHasher
35
+ DefaultHasher = Hasher(hashlib.sha256)
36
+
37
+ def verify_consistency(hasher, size1, size2, proof, root1, root2):
38
+ # change format of args to be bytearray instead of hex strings
39
+ root1 = bytes.fromhex(root1)
40
+ root2 = bytes.fromhex(root2)
41
+ bytearray_proof = []
42
+ for elem in proof:
43
+ bytearray_proof.append(bytes.fromhex(elem))
44
+
45
+ if size2 < size1:
46
+ raise ValueError(f"size2 ({size2}) < size1 ({size1})")
47
+ if size1 == size2:
48
+ if bytearray_proof:
49
+ raise ValueError("size1=size2, but bytearray_proof is not empty")
50
+ verify_match(root1, root2)
51
+ return
52
+ if size1 == 0:
53
+ if bytearray_proof:
54
+ raise ValueError(f"expected empty bytearray_proof, but got {len(bytearray_proof)} components")
55
+ return
56
+ if not bytearray_proof:
57
+ raise ValueError("empty bytearray_proof")
58
+
59
+ inner, border = decomp_incl_proof(size1 - 1, size2)
60
+ shift = (size1 & -size1).bit_length() - 1
61
+ inner -= shift
62
+
63
+ if size1 == 1 << shift:
64
+ seed, start = root1, 0
65
+ else:
66
+ seed, start = bytearray_proof[0], 1
67
+
68
+ if len(bytearray_proof) != start + inner + border:
69
+ raise ValueError(f"wrong bytearray_proof size {len(bytearray_proof)}, want {start + inner + border}")
70
+
71
+ bytearray_proof = bytearray_proof[start:]
72
+
73
+ mask = (size1 - 1) >> shift
74
+ hash1 = chain_inner_right(hasher, seed, bytearray_proof[:inner], mask)
75
+ hash1 = chain_border_right(hasher, hash1, bytearray_proof[inner:])
76
+ verify_match(hash1, root1)
77
+
78
+ hash2 = chain_inner(hasher, seed, bytearray_proof[:inner], mask)
79
+ hash2 = chain_border_right(hasher, hash2, bytearray_proof[inner:])
80
+ verify_match(hash2, root2)
81
+
82
+ def verify_match(calculated, expected):
83
+ if calculated != expected:
84
+ raise RootMismatchError(expected, calculated)
85
+
86
+ def decomp_incl_proof(index, size):
87
+ inner = inner_proof_size(index, size)
88
+ border = (index >> inner).bit_count()
89
+ return inner, border
90
+
91
+ def inner_proof_size(index, size):
92
+ return (index ^ (size - 1)).bit_length()
93
+
94
+ def chain_inner(hasher, seed, proof, index):
95
+ for i, h in enumerate(proof):
96
+ if (index >> i) & 1 == 0:
97
+ seed = hasher.hash_children(seed, h)
98
+ else:
99
+ seed = hasher.hash_children(h, seed)
100
+ return seed
101
+
102
+ def chain_inner_right(hasher, seed, proof, index):
103
+ for i, h in enumerate(proof):
104
+ if (index >> i) & 1 == 1:
105
+ seed = hasher.hash_children(h, seed)
106
+ return seed
107
+
108
+ def chain_border_right(hasher, seed, proof):
109
+ for h in proof:
110
+ seed = hasher.hash_children(h, seed)
111
+ return seed
112
+
113
+ class RootMismatchError(Exception):
114
+ def __init__(self, expected_root, calculated_root):
115
+ self.expected_root = binascii.hexlify(bytearray(expected_root))
116
+ self.calculated_root = binascii.hexlify(bytearray(calculated_root))
117
+
118
+ def __str__(self):
119
+ return f"calculated root:\n{self.calculated_root}\n does not match expected root:\n{self.expected_root}"
120
+
121
+ def root_from_inclusion_proof(hasher, index, size, leaf_hash, proof):
122
+ if index >= size:
123
+ raise ValueError(f"index is beyond size: {index} >= {size}")
124
+
125
+ if len(leaf_hash) != hasher.size():
126
+ raise ValueError(f"leaf_hash has unexpected size {len(leaf_hash)}, want {hasher.size()}")
127
+
128
+ inner, border = decomp_incl_proof(index, size)
129
+ if len(proof) != inner + border:
130
+ raise ValueError(f"wrong proof size {len(proof)}, want {inner + border}")
131
+
132
+ res = chain_inner(hasher, leaf_hash, proof[:inner], index)
133
+ res = chain_border_right(hasher, res, proof[inner:])
134
+ return res
135
+
136
+
137
+ def verify_inclusion(hasher, index, size, leaf_hash, proof, root, debug=False):
138
+ bytearray_proof = []
139
+ for elem in proof:
140
+ bytearray_proof.append(bytes.fromhex(elem))
141
+
142
+ bytearray_root = bytes.fromhex(root)
143
+ bytearray_leaf = bytes.fromhex(leaf_hash)
144
+ calc_root = root_from_inclusion_proof(hasher, index, size, bytearray_leaf, bytearray_proof)
145
+ verify_match(calc_root, bytearray_root)
146
+ if debug:
147
+ print("Calculated root hash", calc_root.hex())
148
+ print("Given root hash", bytearray_root.hex())
149
+
150
+ # requires entry["body"] output for a log entry
151
+ # returns the leaf hash according to the rfc 6962 spec
152
+ def compute_leaf_hash(body):
153
+ entry_bytes = base64.b64decode(body)
154
+
155
+ # create a new sha256 hash object
156
+ h = hashlib.sha256()
157
+ # write the leaf hash prefix
158
+ h.update(bytes([RFC6962_LEAF_HASH_PREFIX]))
159
+
160
+ # write the actual leaf data
161
+ h.update(entry_bytes)
162
+
163
+ # return the computed hash
164
+ return h.hexdigest()
rekor_monitor/util.py ADDED
@@ -0,0 +1,58 @@
1
+ from cryptography import x509
2
+ from cryptography.exceptions import InvalidSignature
3
+ from cryptography.hazmat.backends import default_backend
4
+ from cryptography.hazmat.primitives import hashes, serialization
5
+ from cryptography.hazmat.primitives.asymmetric import ec
6
+ from cryptography.hazmat.primitives.serialization import load_pem_public_key
7
+
8
+
9
+ # extracts and returns public key from a given cert (in pem format)
10
+ def extract_public_key(cert):
11
+ # read the certificate
12
+ # with open("cert.pem", "rb") as cert_file:
13
+ # cert_data = cert_file.read()
14
+
15
+ # load the certificate
16
+ certificate = x509.load_pem_x509_certificate(cert, default_backend())
17
+
18
+ # extract the public key
19
+ public_key = certificate.public_key()
20
+
21
+ # save the public key to a PEM file
22
+ # with open("cert_public.pem", "wb") as pub_key_file:
23
+ # pub_key_file.write(public_key.public_bytes(
24
+ # encoding=serialization.Encoding.PEM,
25
+ # format=serialization.PublicFormat.SubjectPublicKeyInfo
26
+ # ))
27
+ pem_public_key = public_key.public_bytes(
28
+ encoding=serialization.Encoding.PEM,
29
+ format=serialization.PublicFormat.SubjectPublicKeyInfo
30
+ )
31
+
32
+ return pem_public_key
33
+
34
+ def verify_artifact_signature(signature, public_key, artifact_filename):
35
+ # load the public key
36
+ # with open("cert_public.pem", "rb") as pub_key_file:
37
+ # public_key = load_pem_public_key(pub_key_file.read())
38
+
39
+ # load the signature
40
+ # with open("hello.sig", "rb") as sig_file:
41
+ # signature = sig_file.read()
42
+
43
+ public_key = load_pem_public_key(public_key)
44
+ # load the data to be verified
45
+ with open(artifact_filename, "rb") as data_file:
46
+ data = data_file.read()
47
+
48
+ # verify the signature
49
+ try:
50
+ public_key.verify(
51
+ signature,
52
+ data,
53
+ ec.ECDSA(hashes.SHA256())
54
+ )
55
+ except InvalidSignature:
56
+ print("Signature is invalid")
57
+ else:
58
+ print("Exception in verifying artifact signature:")
@@ -0,0 +1,105 @@
1
+ Metadata-Version: 2.4
2
+ Name: sscs-assignment1
3
+ Version: 0.1.0
4
+ Summary:
5
+ License-File: LICENSE
6
+ Author: ghuang2222
7
+ Author-email: gh2222@nyu.edu
8
+ Requires-Python: >=3.10
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Programming Language :: Python :: 3.10
11
+ Classifier: Programming Language :: Python :: 3.11
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Classifier: Programming Language :: Python :: 3.13
14
+ Classifier: Programming Language :: Python :: 3.14
15
+ Classifier: Programming Language :: Python :: 3.15
16
+ Requires-Dist: certifi (==2026.7.22)
17
+ Requires-Dist: cffi (==2.1.1)
18
+ Requires-Dist: charset-normalizer (==3.5.2)
19
+ Requires-Dist: cryptography (==50.0.2)
20
+ Requires-Dist: idna (==3.20)
21
+ Requires-Dist: pycparser (==3.0)
22
+ Requires-Dist: requests (==2.34.2)
23
+ Requires-Dist: typing_extensions (==4.16.0)
24
+ Requires-Dist: urllib3 (==2.8.0)
25
+ Description-Content-Type: text/markdown
26
+
27
+ # Rekor Monitor
28
+
29
+ ## Overview
30
+
31
+ This project implements a Python-based verifier for artifacts recorded in the [Sigstore Rekor transparency log](https://rekor.sigstore.dev/).
32
+
33
+ It supports:
34
+
35
+ - Retrieving entries from the Rekor transparency log.
36
+ - Verifying artifact signatures.
37
+ - Verifying Merkle inclusion proofs.
38
+ - Verifying consistency proofs between transparency log checkpoints.
39
+
40
+ ## Requirements
41
+
42
+ - Python 3.10+
43
+ - `requests`
44
+ - `pytest` (for testing)
45
+
46
+ Install the dependencies:
47
+
48
+ ```bash
49
+ pip install requests pytest
50
+ ```
51
+
52
+ ## Usage
53
+
54
+ Run `main.py` with the desired command-line options.
55
+
56
+ ```bash
57
+ python main.py --help
58
+ ```
59
+
60
+ Verify an artifact's inclusion in the log:
61
+
62
+ ```bash
63
+ python main.py --inclusion LOG_INDEX --artifact PATH_TO_ARTIFACT
64
+ ```
65
+
66
+ Check the latest log checkpoint:
67
+
68
+ ```bash
69
+ python main.py --checkpoint
70
+ ```
71
+
72
+ Verify log consistency:
73
+
74
+ ```bash
75
+ python main.py --consistency
76
+ ```
77
+
78
+ Replace `LOG_INDEX` and `PATH_TO_ARTIFACT` with the appropriate log entry index and local artifact path. Use `python main.py --help` to confirm the exact arguments supported by your version.
79
+
80
+ ## Testing
81
+
82
+ Run the test suite:
83
+
84
+ ```bash
85
+ pytest
86
+ ```
87
+
88
+ If coverage is configured, run:
89
+
90
+ ```bash
91
+ pytest --cov=. --cov-report=term-missing
92
+ ```
93
+
94
+ ## Security
95
+
96
+ This project is intended for educational purposes. Verification results depend on the correctness of the implementation and the trustworthiness of the supplied keys, certificates, checkpoints, and proofs.
97
+
98
+ Do not treat a successful verification as a guarantee that an artifact is safe to execute.
99
+
100
+ Report suspected vulnerabilities privately to the repository maintainer rather than publicly disclosing exploitable details.
101
+
102
+ ## License
103
+
104
+ See [LICENSE](LICENSE).
105
+
@@ -0,0 +1,8 @@
1
+ rekor_monitor/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ rekor_monitor/main.py,sha256=az8nVgngxZx2aD5unD_e7YdEZG1p-NZYDHOdiDx4l2M,5721
3
+ rekor_monitor/merkle_proof.py,sha256=uR7BG5ob4tSnisKjRDYtcHqfHnyartkq9XzKUubIP9A,5333
4
+ rekor_monitor/util.py,sha256=tdhdKYibvfd7cKHFfmVXCki8nEmzc5dVaRqeOed5tYg,1980
5
+ sscs_assignment1-0.1.0.dist-info/METADATA,sha256=C0ykvR9UABIZU7leaSkb575ZyG2Wy2poHBZqyZXgSSA,2572
6
+ sscs_assignment1-0.1.0.dist-info/WHEEL,sha256=L-WvLdSBvJWHXv5zrQxDvNRnIgoBzLUpcbuiw19KCuQ,88
7
+ sscs_assignment1-0.1.0.dist-info/licenses/LICENSE,sha256=e8K1rbfzVvY0JBwakWEvTyv-cINnOdukG_yHBwJUfZk,1096
8
+ sscs_assignment1-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: poetry-core 2.5.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Project Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.