rb5189_sscs_assignment 0.1.0__tar.gz
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.
- rb5189_sscs_assignment-0.1.0/LICENSE +21 -0
- rb5189_sscs_assignment-0.1.0/PKG-INFO +53 -0
- rb5189_sscs_assignment-0.1.0/README.md +37 -0
- rb5189_sscs_assignment-0.1.0/pyproject.toml +38 -0
- rb5189_sscs_assignment-0.1.0/src/rb5189_sscs_assignment/__init__.py +0 -0
- rb5189_sscs_assignment-0.1.0/src/rb5189_sscs_assignment/main.py +236 -0
- rb5189_sscs_assignment-0.1.0/src/rb5189_sscs_assignment/merkle_proof.py +164 -0
- rb5189_sscs_assignment-0.1.0/src/rb5189_sscs_assignment/util.py +60 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Bezbakri
|
|
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.
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: rb5189_sscs_assignment
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Assignment work for NYU CS-GY 9223
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Author: Bezbakri
|
|
8
|
+
Requires-Python: >=3.13
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
13
|
+
Requires-Dist: cryptography (>=51.0.1,<52.0.0)
|
|
14
|
+
Requires-Dist: requests (>=2.34.2,<3.0.0)
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
|
|
17
|
+
# Python Rekor Monitor Template
|
|
18
|
+
|
|
19
|
+
Assignment code for NYU CS-GY 9223 Software Supply Chain Security.
|
|
20
|
+
|
|
21
|
+
This program allows you to verify Rekor Transparency logs. You can check if a certain file matches a Rekor log index, get the latest checkpoint, or verify the consistency of a given checkpoint with the latest checkpoint.
|
|
22
|
+
|
|
23
|
+
## Installation:
|
|
24
|
+
|
|
25
|
+
Install all the project dependancies with ``poetry install``
|
|
26
|
+
|
|
27
|
+
## Usage:
|
|
28
|
+
|
|
29
|
+
```
|
|
30
|
+
usage: main.py [-h] [-d] [-c] [--inclusion INCLUSION] [--artifact ARTIFACT] [--consistency] [--tree-id TREE_ID]
|
|
31
|
+
[--tree-size TREE_SIZE] [--root-hash ROOT_HASH]
|
|
32
|
+
|
|
33
|
+
Rekor Verifier
|
|
34
|
+
|
|
35
|
+
options:
|
|
36
|
+
-h, --help show this help message and exit
|
|
37
|
+
-d, --debug Debug mode
|
|
38
|
+
-c, --checkpoint Obtain latest checkpoint from Rekor Server public instance
|
|
39
|
+
--inclusion INCLUSION
|
|
40
|
+
Verify inclusion of an entry in the Rekor Transparency Log using log index and artifact
|
|
41
|
+
filename. Usage: --inclusion 126574567
|
|
42
|
+
--artifact ARTIFACT Artifact filepath for verifying signature
|
|
43
|
+
--consistency Verify consistency of a given checkpoint with the latest checkpoint.
|
|
44
|
+
--tree-id TREE_ID Tree ID for consistency proof
|
|
45
|
+
--tree-size TREE_SIZE
|
|
46
|
+
Tree size for consistency proof
|
|
47
|
+
--root-hash ROOT_HASH
|
|
48
|
+
Root hash for consistency proof
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## Development Instructions
|
|
52
|
+
|
|
53
|
+
In order to add features to this project, please create a fork and use a pull request in order to push changes to the project.
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
# Python Rekor Monitor Template
|
|
2
|
+
|
|
3
|
+
Assignment code for NYU CS-GY 9223 Software Supply Chain Security.
|
|
4
|
+
|
|
5
|
+
This program allows you to verify Rekor Transparency logs. You can check if a certain file matches a Rekor log index, get the latest checkpoint, or verify the consistency of a given checkpoint with the latest checkpoint.
|
|
6
|
+
|
|
7
|
+
## Installation:
|
|
8
|
+
|
|
9
|
+
Install all the project dependancies with ``poetry install``
|
|
10
|
+
|
|
11
|
+
## Usage:
|
|
12
|
+
|
|
13
|
+
```
|
|
14
|
+
usage: main.py [-h] [-d] [-c] [--inclusion INCLUSION] [--artifact ARTIFACT] [--consistency] [--tree-id TREE_ID]
|
|
15
|
+
[--tree-size TREE_SIZE] [--root-hash ROOT_HASH]
|
|
16
|
+
|
|
17
|
+
Rekor Verifier
|
|
18
|
+
|
|
19
|
+
options:
|
|
20
|
+
-h, --help show this help message and exit
|
|
21
|
+
-d, --debug Debug mode
|
|
22
|
+
-c, --checkpoint Obtain latest checkpoint from Rekor Server public instance
|
|
23
|
+
--inclusion INCLUSION
|
|
24
|
+
Verify inclusion of an entry in the Rekor Transparency Log using log index and artifact
|
|
25
|
+
filename. Usage: --inclusion 126574567
|
|
26
|
+
--artifact ARTIFACT Artifact filepath for verifying signature
|
|
27
|
+
--consistency Verify consistency of a given checkpoint with the latest checkpoint.
|
|
28
|
+
--tree-id TREE_ID Tree ID for consistency proof
|
|
29
|
+
--tree-size TREE_SIZE
|
|
30
|
+
Tree size for consistency proof
|
|
31
|
+
--root-hash ROOT_HASH
|
|
32
|
+
Root hash for consistency proof
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## Development Instructions
|
|
36
|
+
|
|
37
|
+
In order to add features to this project, please create a fork and use a pull request in order to push changes to the project.
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "rb5189_sscs_assignment"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Assignment work for NYU CS-GY 9223"
|
|
5
|
+
authors = [
|
|
6
|
+
{name = "Bezbakri"}
|
|
7
|
+
]
|
|
8
|
+
license = "MIT"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.13"
|
|
11
|
+
dependencies = [
|
|
12
|
+
"requests (>=2.34.2,<3.0.0)",
|
|
13
|
+
"cryptography (>=51.0.1,<52.0.0)"
|
|
14
|
+
|
|
15
|
+
]
|
|
16
|
+
|
|
17
|
+
[tool.poetry]
|
|
18
|
+
exclude = ["tests/*"]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
[build-system]
|
|
22
|
+
requires = ["poetry-core>=2.0.0,<3.0.0"]
|
|
23
|
+
build-backend = "poetry.core.masonry.api"
|
|
24
|
+
|
|
25
|
+
[tool.coverage.run]
|
|
26
|
+
patch = ["subprocess"]
|
|
27
|
+
|
|
28
|
+
[dependency-groups]
|
|
29
|
+
dev = [
|
|
30
|
+
"black (>=26.10.1,<27.0.0)",
|
|
31
|
+
"flake8 (>=7.4.1,<8.0.0)",
|
|
32
|
+
"mypy (>=2.4.1,<3.0.0)",
|
|
33
|
+
"bandit (>=1.9.4,<2.0.0)",
|
|
34
|
+
"pytest (>=9.1.1,<10.0.0)",
|
|
35
|
+
"pytest-cov (>=7.1.0,<8.0.0)",
|
|
36
|
+
"pre-commit (>=4.7.0,<5.0.0)",
|
|
37
|
+
"jsonschema (>=4.26.0,<5.0.0)"
|
|
38
|
+
]
|
|
File without changes
|
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
|
|
3
|
+
from rb5189_sscs_assignment.util import extract_public_key, verify_artifact_signature
|
|
4
|
+
from rb5189_sscs_assignment.merkle_proof import (
|
|
5
|
+
DefaultHasher,
|
|
6
|
+
verify_consistency,
|
|
7
|
+
verify_inclusion,
|
|
8
|
+
compute_leaf_hash,
|
|
9
|
+
)
|
|
10
|
+
import requests
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import base64
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def get_log_entry(log_index, debug=False):
|
|
17
|
+
# TODO: verify that log index value is sane
|
|
18
|
+
# Get the request data
|
|
19
|
+
try:
|
|
20
|
+
log_index_int = int(log_index)
|
|
21
|
+
if log_index_int < 1:
|
|
22
|
+
raise ValueError("Needs a positive log index")
|
|
23
|
+
except Exception:
|
|
24
|
+
raise
|
|
25
|
+
rekor_url = "https://rekor.sigstore.dev/api/v1/log/entries"
|
|
26
|
+
check_log_index = requests.get(
|
|
27
|
+
rekor_url, params={"logIndex": log_index}, timeout=30
|
|
28
|
+
)
|
|
29
|
+
if check_log_index.status_code == 200:
|
|
30
|
+
log_json_data = check_log_index.json()
|
|
31
|
+
log_uuid = list(log_json_data.keys())[0]
|
|
32
|
+
if debug is True:
|
|
33
|
+
print("Got a 200")
|
|
34
|
+
# print(log_uuid)
|
|
35
|
+
# print(log_json_data[log_uuid]['body'])
|
|
36
|
+
return log_uuid, log_json_data[log_uuid]
|
|
37
|
+
else:
|
|
38
|
+
# didn't get what i wanted
|
|
39
|
+
return "No log index found"
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def get_verification_proof(log_index, debug=False):
|
|
43
|
+
# TODO: verify that log index value is sane
|
|
44
|
+
log_entry = get_log_entry(log_index, debug)
|
|
45
|
+
if log_entry == "No log index found":
|
|
46
|
+
return log_entry
|
|
47
|
+
log_uuid, log_json_data = log_entry
|
|
48
|
+
verification_data = log_json_data["verification"]
|
|
49
|
+
index = verification_data["inclusionProof"]["logIndex"]
|
|
50
|
+
hashes = verification_data["inclusionProof"]["hashes"]
|
|
51
|
+
root_hash = verification_data["inclusionProof"]["rootHash"]
|
|
52
|
+
tree_size = verification_data["inclusionProof"]["treeSize"]
|
|
53
|
+
return index, tree_size, hashes, root_hash
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def inclusion(log_index, artifact_filepath, debug=False):
|
|
57
|
+
# TODO::
|
|
58
|
+
# verify that log index and artifact filepath values are sane
|
|
59
|
+
log_entry = get_log_entry(log_index, debug)
|
|
60
|
+
if log_entry == "No log index found":
|
|
61
|
+
print(log_entry)
|
|
62
|
+
return
|
|
63
|
+
log_uuid, log_json_data = log_entry
|
|
64
|
+
if not os.path.exists(artifact_filepath):
|
|
65
|
+
print("Invalid file path")
|
|
66
|
+
return
|
|
67
|
+
log_body_b64 = log_json_data["body"]
|
|
68
|
+
log_body = base64.b64decode(log_body_b64)
|
|
69
|
+
log_body_json = json.loads(log_body.decode())
|
|
70
|
+
# if debug:
|
|
71
|
+
# print(log_body)
|
|
72
|
+
# print(log_body_json)
|
|
73
|
+
if "spec" not in log_body_json:
|
|
74
|
+
print("Given log index does not have a signature")
|
|
75
|
+
return
|
|
76
|
+
if "signature" not in log_body_json["spec"]:
|
|
77
|
+
print("Given log index does not have a signature")
|
|
78
|
+
return
|
|
79
|
+
signature_b64 = log_body_json["spec"]["signature"]["content"]
|
|
80
|
+
signature = base64.b64decode(signature_b64)
|
|
81
|
+
public_key_b64 = log_body_json["spec"]["signature"]["publicKey"]["content"]
|
|
82
|
+
certificate = base64.b64decode(public_key_b64)
|
|
83
|
+
public_key = extract_public_key(certificate)
|
|
84
|
+
if debug:
|
|
85
|
+
print(public_key.decode())
|
|
86
|
+
verify_artifact_signature(signature, public_key, artifact_filepath)
|
|
87
|
+
index, tree_size, hashes, root = get_verification_proof(log_index)
|
|
88
|
+
leaf_hash = compute_leaf_hash(log_body_b64)
|
|
89
|
+
verify_inclusion(DefaultHasher, index, tree_size, leaf_hash, hashes, root)
|
|
90
|
+
print("Offline verification successful")
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def get_latest_checkpoint(debug=False):
|
|
94
|
+
# TODO: Fetch the latest checkpoint from rekor
|
|
95
|
+
rekor_url = "https://rekor.sigstore.dev/api/v1/log"
|
|
96
|
+
latest_checkpoint = requests.get(rekor_url, timeout=30)
|
|
97
|
+
if latest_checkpoint.status_code == 200:
|
|
98
|
+
latest_checkpoint_json = latest_checkpoint.json()
|
|
99
|
+
if debug:
|
|
100
|
+
print("Got a 200")
|
|
101
|
+
return latest_checkpoint_json
|
|
102
|
+
else:
|
|
103
|
+
return "Fatal error: no checkpoint found"
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def consistency(prev_checkpoint, debug=False):
|
|
107
|
+
# TODO:
|
|
108
|
+
# verify that prev checkpoint is not empty
|
|
109
|
+
if (
|
|
110
|
+
"treeID" not in prev_checkpoint
|
|
111
|
+
or "treeSize" not in prev_checkpoint
|
|
112
|
+
or "rootHash" not in prev_checkpoint
|
|
113
|
+
):
|
|
114
|
+
print("Empty prev checkpoint!")
|
|
115
|
+
return
|
|
116
|
+
latest_checkpoint = get_latest_checkpoint()
|
|
117
|
+
latest_root_hash = latest_checkpoint["rootHash"]
|
|
118
|
+
latest_tree_size = latest_checkpoint["treeSize"]
|
|
119
|
+
# latest_tree_id = latest_checkpoint["treeID"]
|
|
120
|
+
prev_root_hash = prev_checkpoint["rootHash"]
|
|
121
|
+
prev_tree_size = prev_checkpoint["treeSize"]
|
|
122
|
+
# prev_tree_id = prev_checkpoint["treeID"]
|
|
123
|
+
if prev_tree_size > latest_tree_size:
|
|
124
|
+
print("Previous size cannot be bigger than latest size")
|
|
125
|
+
return
|
|
126
|
+
if prev_tree_size == latest_tree_size:
|
|
127
|
+
proof = []
|
|
128
|
+
else:
|
|
129
|
+
proof_req = requests.get(
|
|
130
|
+
"https://rekor.sigstore.dev/api/v1/log/proof",
|
|
131
|
+
params={"firstSize": prev_tree_size, "lastSize": latest_tree_size},
|
|
132
|
+
timeout=30,
|
|
133
|
+
)
|
|
134
|
+
if proof_req.status_code == 200:
|
|
135
|
+
proof_req_json = proof_req.json()
|
|
136
|
+
if debug:
|
|
137
|
+
print("Got a 200")
|
|
138
|
+
proof = proof_req_json["hashes"]
|
|
139
|
+
else:
|
|
140
|
+
return "Fatal error: no proof found"
|
|
141
|
+
verify_consistency(
|
|
142
|
+
DefaultHasher,
|
|
143
|
+
prev_tree_size,
|
|
144
|
+
latest_tree_size,
|
|
145
|
+
proof,
|
|
146
|
+
prev_root_hash,
|
|
147
|
+
latest_root_hash,
|
|
148
|
+
)
|
|
149
|
+
print("Consistency verification successful")
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def main():
|
|
153
|
+
debug = False
|
|
154
|
+
parser = argparse.ArgumentParser(description="Rekor Verifier")
|
|
155
|
+
parser.add_argument(
|
|
156
|
+
"-d", "--debug", help="Debug mode", required=False, action="store_true"
|
|
157
|
+
) # Default false
|
|
158
|
+
parser.add_argument(
|
|
159
|
+
"-c",
|
|
160
|
+
"--checkpoint",
|
|
161
|
+
help="Obtain latest checkpoint\
|
|
162
|
+
from Rekor Server public instance",
|
|
163
|
+
required=False,
|
|
164
|
+
action="store_true",
|
|
165
|
+
)
|
|
166
|
+
parser.add_argument(
|
|
167
|
+
"--inclusion",
|
|
168
|
+
help="Verify inclusion of an\
|
|
169
|
+
entry in the Rekor Transparency Log using log index\
|
|
170
|
+
and artifact filename.\
|
|
171
|
+
Usage: --inclusion 126574567",
|
|
172
|
+
required=False,
|
|
173
|
+
type=int,
|
|
174
|
+
)
|
|
175
|
+
parser.add_argument(
|
|
176
|
+
"--artifact",
|
|
177
|
+
help="Artifact filepath for verifying\
|
|
178
|
+
signature",
|
|
179
|
+
required=False,
|
|
180
|
+
)
|
|
181
|
+
parser.add_argument(
|
|
182
|
+
"--consistency",
|
|
183
|
+
help="Verify consistency of a given\
|
|
184
|
+
checkpoint with the latest checkpoint.",
|
|
185
|
+
action="store_true",
|
|
186
|
+
)
|
|
187
|
+
parser.add_argument(
|
|
188
|
+
"--tree-id", help="Tree ID for consistency proof", required=False
|
|
189
|
+
)
|
|
190
|
+
parser.add_argument(
|
|
191
|
+
"--tree-size",
|
|
192
|
+
help="Tree size for\
|
|
193
|
+
consistency proof",
|
|
194
|
+
required=False,
|
|
195
|
+
type=int,
|
|
196
|
+
)
|
|
197
|
+
parser.add_argument(
|
|
198
|
+
"--root-hash", help="Root hash for consistency proof", required=False
|
|
199
|
+
)
|
|
200
|
+
args = parser.parse_args()
|
|
201
|
+
if args.debug:
|
|
202
|
+
debug = True
|
|
203
|
+
print("enabled debug mode")
|
|
204
|
+
# # For testing
|
|
205
|
+
# if args.log_index:
|
|
206
|
+
# print(get_log_entry(args.log_index, debug))
|
|
207
|
+
if args.checkpoint:
|
|
208
|
+
# get and print latest checkpoint from server
|
|
209
|
+
# if debug is enabled, store it in a file checkpoint.json
|
|
210
|
+
checkpoint = get_latest_checkpoint(debug)
|
|
211
|
+
print(json.dumps(checkpoint, indent=4))
|
|
212
|
+
if args.inclusion:
|
|
213
|
+
if not args.artifact:
|
|
214
|
+
print("please specify artifact filepath for inclusion")
|
|
215
|
+
inclusion(args.inclusion, args.artifact, debug)
|
|
216
|
+
if args.consistency:
|
|
217
|
+
if not args.tree_id:
|
|
218
|
+
print("please specify tree id for prev checkpoint")
|
|
219
|
+
return
|
|
220
|
+
if not args.tree_size:
|
|
221
|
+
print("please specify tree size for prev checkpoint")
|
|
222
|
+
return
|
|
223
|
+
if not args.root_hash:
|
|
224
|
+
print("please specify root hash for prev checkpoint")
|
|
225
|
+
return
|
|
226
|
+
|
|
227
|
+
prev_checkpoint = {}
|
|
228
|
+
prev_checkpoint["treeID"] = args.tree_id
|
|
229
|
+
prev_checkpoint["treeSize"] = args.tree_size
|
|
230
|
+
prev_checkpoint["rootHash"] = args.root_hash
|
|
231
|
+
|
|
232
|
+
consistency(prev_checkpoint, debug)
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
if __name__ == "__main__":
|
|
236
|
+
main()
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
import hashlib
|
|
2
|
+
import binascii
|
|
3
|
+
import base64
|
|
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 = bin(index >> inner).count('1')
|
|
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()
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
from cryptography import x509
|
|
2
|
+
from cryptography.hazmat.backends import default_backend
|
|
3
|
+
from cryptography.hazmat.primitives import serialization
|
|
4
|
+
|
|
5
|
+
from cryptography.hazmat.primitives import hashes
|
|
6
|
+
from cryptography.hazmat.primitives.asymmetric import ec
|
|
7
|
+
from cryptography.hazmat.primitives.serialization import load_pem_public_key
|
|
8
|
+
from cryptography.exceptions import InvalidSignature
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
# extracts and returns public key from a given cert (in pem format)
|
|
12
|
+
def extract_public_key(cert):
|
|
13
|
+
# read the certificate
|
|
14
|
+
# with open("cert.pem", "rb") as cert_file:
|
|
15
|
+
# cert_data = cert_file.read()
|
|
16
|
+
|
|
17
|
+
# load the certificate
|
|
18
|
+
certificate = x509.load_pem_x509_certificate(cert, default_backend())
|
|
19
|
+
|
|
20
|
+
# extract the public key
|
|
21
|
+
public_key = certificate.public_key()
|
|
22
|
+
|
|
23
|
+
# save the public key to a PEM file
|
|
24
|
+
# with open("cert_public.pem", "wb") as pub_key_file:
|
|
25
|
+
# pub_key_file.write(public_key.public_bytes(
|
|
26
|
+
# encoding=serialization.Encoding.PEM,
|
|
27
|
+
# format=serialization.PublicFormat.SubjectPublicKeyInfo
|
|
28
|
+
# ))
|
|
29
|
+
pem_public_key = public_key.public_bytes(
|
|
30
|
+
encoding=serialization.Encoding.PEM,
|
|
31
|
+
format=serialization.PublicFormat.SubjectPublicKeyInfo
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
return pem_public_key
|
|
35
|
+
|
|
36
|
+
def verify_artifact_signature(signature, public_key, artifact_filename):
|
|
37
|
+
# load the public key
|
|
38
|
+
# with open("cert_public.pem", "rb") as pub_key_file:
|
|
39
|
+
# public_key = load_pem_public_key(pub_key_file.read())
|
|
40
|
+
|
|
41
|
+
# load the signature
|
|
42
|
+
# with open("hello.sig", "rb") as sig_file:
|
|
43
|
+
# signature = sig_file.read()
|
|
44
|
+
|
|
45
|
+
public_key = load_pem_public_key(public_key)
|
|
46
|
+
# load the data to be verified
|
|
47
|
+
with open(artifact_filename, "rb") as data_file:
|
|
48
|
+
data = data_file.read()
|
|
49
|
+
|
|
50
|
+
# verify the signature
|
|
51
|
+
try:
|
|
52
|
+
public_key.verify(
|
|
53
|
+
signature,
|
|
54
|
+
data,
|
|
55
|
+
ec.ECDSA(hashes.SHA256())
|
|
56
|
+
)
|
|
57
|
+
except InvalidSignature as e:
|
|
58
|
+
print("Signature is invalid")
|
|
59
|
+
except Exception as e:
|
|
60
|
+
print("Exception in verifying artifact signature:", e)
|