extrafemi-seal 0.1.1__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.
- extrafemi_seal-0.1.1/PKG-INFO +32 -0
- extrafemi_seal-0.1.1/README.md +19 -0
- extrafemi_seal-0.1.1/extrafemi_seal/__init__.py +395 -0
- extrafemi_seal-0.1.1/extrafemi_seal/keys.py +49 -0
- extrafemi_seal-0.1.1/extrafemi_seal.egg-info/PKG-INFO +32 -0
- extrafemi_seal-0.1.1/extrafemi_seal.egg-info/SOURCES.txt +10 -0
- extrafemi_seal-0.1.1/extrafemi_seal.egg-info/dependency_links.txt +1 -0
- extrafemi_seal-0.1.1/extrafemi_seal.egg-info/requires.txt +1 -0
- extrafemi_seal-0.1.1/extrafemi_seal.egg-info/top_level.txt +1 -0
- extrafemi_seal-0.1.1/pyproject.toml +20 -0
- extrafemi_seal-0.1.1/setup.cfg +4 -0
- extrafemi_seal-0.1.1/tests/test_vectors.py +83 -0
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: extrafemi-seal
|
|
3
|
+
Version: 0.1.1
|
|
4
|
+
Summary: Check seals made by Seal, certificates, batch receipts and transparency log checkpoints.
|
|
5
|
+
License: MIT
|
|
6
|
+
Project-URL: Homepage, https://seal.extrafemi.com
|
|
7
|
+
Project-URL: Source, https://github.com/obasaolorunfemi-ai/seal
|
|
8
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
9
|
+
Classifier: Topic :: Security :: Cryptography
|
|
10
|
+
Requires-Python: >=3.9
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
Requires-Dist: cryptography>=42
|
|
13
|
+
|
|
14
|
+
# extrafemi-seal (Python)
|
|
15
|
+
|
|
16
|
+
Check seals made by [Seal](https://seal.extrafemi.com) in Python, offline if you hold the public keys.
|
|
17
|
+
|
|
18
|
+
```python
|
|
19
|
+
import extrafemi_seal as seal
|
|
20
|
+
|
|
21
|
+
keys = seal.fetch_keys() # current keys from the registry, or seal.builtin_keys() to stay offline
|
|
22
|
+
result = seal.scan(open("contract.pdf", "rb").read(), keys, seal.make_lookup())
|
|
23
|
+
print(result["status"], result["message"]) # genuine, altered, revoked, unknown-key or no-seal
|
|
24
|
+
|
|
25
|
+
seal.scan_sidecar(data, json.load(open("photo.jpg.seal.json")), keys) # a file with its certificate
|
|
26
|
+
seal.verify_batch_receipt(receipt, keys) # was an item in a sealed batch?
|
|
27
|
+
seal.verify_note(checkpoint_text, "seal.extrafemi.com", log_public_key) # a log checkpoint
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Works for file seals in PDF, Word, Excel, EPUB, ZIP, PNG, JPEG, GIF and MP4, for sidecar certificates and batch
|
|
31
|
+
receipts. Not yet: the hidden text seals products put in their own PDFs. Tested against vectors made by the
|
|
32
|
+
JavaScript library (`python3 -m unittest discover tests`). Needs `cryptography`.
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
# extrafemi-seal (Python)
|
|
2
|
+
|
|
3
|
+
Check seals made by [Seal](https://seal.extrafemi.com) in Python, offline if you hold the public keys.
|
|
4
|
+
|
|
5
|
+
```python
|
|
6
|
+
import extrafemi_seal as seal
|
|
7
|
+
|
|
8
|
+
keys = seal.fetch_keys() # current keys from the registry, or seal.builtin_keys() to stay offline
|
|
9
|
+
result = seal.scan(open("contract.pdf", "rb").read(), keys, seal.make_lookup())
|
|
10
|
+
print(result["status"], result["message"]) # genuine, altered, revoked, unknown-key or no-seal
|
|
11
|
+
|
|
12
|
+
seal.scan_sidecar(data, json.load(open("photo.jpg.seal.json")), keys) # a file with its certificate
|
|
13
|
+
seal.verify_batch_receipt(receipt, keys) # was an item in a sealed batch?
|
|
14
|
+
seal.verify_note(checkpoint_text, "seal.extrafemi.com", log_public_key) # a log checkpoint
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
Works for file seals in PDF, Word, Excel, EPUB, ZIP, PNG, JPEG, GIF and MP4, for sidecar certificates and batch
|
|
18
|
+
receipts. Not yet: the hidden text seals products put in their own PDFs. Tested against vectors made by the
|
|
19
|
+
JavaScript library (`python3 -m unittest discover tests`). Needs `cryptography`.
|
|
@@ -0,0 +1,395 @@
|
|
|
1
|
+
"""Seal: check seals, certificates, batch receipts, Merkle proofs and log checkpoints in Python.
|
|
2
|
+
|
|
3
|
+
Needs only the `cryptography` package. Checking works offline with the published public keys.
|
|
4
|
+
Payload seals (the hidden text products put in their own PDFs) are not supported here; file seals, JWS seals,
|
|
5
|
+
sidecar certificates and batch receipts are.
|
|
6
|
+
"""
|
|
7
|
+
import base64
|
|
8
|
+
import hashlib
|
|
9
|
+
import json
|
|
10
|
+
import re
|
|
11
|
+
from datetime import datetime, timezone
|
|
12
|
+
|
|
13
|
+
from cryptography.exceptions import InvalidSignature
|
|
14
|
+
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
|
|
15
|
+
|
|
16
|
+
__version__ = "0.1.1"
|
|
17
|
+
FILE_MARK = b"EXTRAFEMI-SEAL-V2 "
|
|
18
|
+
DEFAULT_SITE = "https://seal.extrafemi.com"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
# ---- encodings ----
|
|
22
|
+
def b64u_decode(s):
|
|
23
|
+
s = s.replace("-", "+").replace("_", "/")
|
|
24
|
+
return base64.b64decode(s + "=" * (-len(s) % 4))
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def b64u_encode(b):
|
|
28
|
+
return base64.urlsafe_b64encode(b).rstrip(b"=").decode()
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def sha256_hex(data):
|
|
32
|
+
return hashlib.sha256(data).hexdigest()
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _num(x):
|
|
36
|
+
"""A number the way ECMAScript writes it (RFC 8785)."""
|
|
37
|
+
if isinstance(x, bool):
|
|
38
|
+
return "true" if x else "false"
|
|
39
|
+
if isinstance(x, int):
|
|
40
|
+
return str(x)
|
|
41
|
+
if x == int(x) and abs(x) < 1e21:
|
|
42
|
+
return str(int(x))
|
|
43
|
+
r = repr(x)
|
|
44
|
+
m = re.match(r"^(-?[0-9.]+)e([+-])0*([0-9]+)$", r)
|
|
45
|
+
return f"{m.group(1)}e{m.group(2)}{m.group(3)}" if m else r
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def canonicalize(v):
|
|
49
|
+
"""RFC 8785 JSON Canonicalization Scheme."""
|
|
50
|
+
if v is None:
|
|
51
|
+
return "null"
|
|
52
|
+
if isinstance(v, (bool, int, float)):
|
|
53
|
+
return _num(v)
|
|
54
|
+
if isinstance(v, str):
|
|
55
|
+
return json.dumps(v, ensure_ascii=False)
|
|
56
|
+
if isinstance(v, (list, tuple)):
|
|
57
|
+
return "[" + ",".join(canonicalize(x) for x in v) + "]"
|
|
58
|
+
return "{" + ",".join(json.dumps(k, ensure_ascii=False) + ":" + canonicalize(v[k]) for k in sorted(v, key=lambda k: k.encode("utf-16-be"))) + "}"
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
# ---- JWS seals ----
|
|
62
|
+
def parse_jws(token):
|
|
63
|
+
parts = token.split(".")
|
|
64
|
+
if len(parts) != 3:
|
|
65
|
+
raise ValueError("Not a JWS.")
|
|
66
|
+
return {
|
|
67
|
+
"header": json.loads(b64u_decode(parts[0])),
|
|
68
|
+
"payload": json.loads(b64u_decode(parts[1])),
|
|
69
|
+
"signing_input": (parts[0] + "." + parts[1]).encode(),
|
|
70
|
+
"sig": b64u_decode(parts[2]),
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def verify_jws(token, jwk):
|
|
75
|
+
"""True if the compact JWS is a valid EdDSA signature by this public JWK."""
|
|
76
|
+
try:
|
|
77
|
+
p = parse_jws(token)
|
|
78
|
+
if p["header"].get("alg") != "EdDSA":
|
|
79
|
+
return False
|
|
80
|
+
Ed25519PublicKey.from_public_bytes(b64u_decode(jwk["x"])).verify(p["sig"], p["signing_input"])
|
|
81
|
+
return True
|
|
82
|
+
except (InvalidSignature, ValueError, KeyError, json.JSONDecodeError):
|
|
83
|
+
return False
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def seal_from_jws(token):
|
|
87
|
+
"""The seal as a dict. Every field comes from the signed payload."""
|
|
88
|
+
p = parse_jws(token)
|
|
89
|
+
pl = p["payload"]
|
|
90
|
+
seal = {"v": 3, "jws": token, "p": pl.get("p"), "id": pl.get("id"), "h": pl.get("h"), "t": pl.get("t"),
|
|
91
|
+
"kid": p["header"].get("kid"), "by": pl.get("by", ""), "k": pl.get("k")}
|
|
92
|
+
if "n" in pl:
|
|
93
|
+
seal["n"] = pl["n"]
|
|
94
|
+
return seal
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
_HASH = re.compile(r"^[a-f0-9]{64}$")
|
|
98
|
+
_ID = re.compile(r"^[A-Za-z0-9:_.-]{3,80}$")
|
|
99
|
+
_PRODUCTS = ("fieldstone", "whetstone", "inkstone", "signsecure")
|
|
100
|
+
_SYSTEM = ("seal",)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _valid_shape(s):
|
|
104
|
+
return (isinstance(s, dict) and s.get("v") == 3 and bool(_ID.match(str(s.get("id") or ""))) and bool(_HASH.match(str(s.get("h") or "")))
|
|
105
|
+
and (s.get("p") in _PRODUCTS or s.get("p") in _SYSTEM or s.get("p") == "user") and s.get("k") in ("file", "payload", "batch")
|
|
106
|
+
and isinstance(s.get("by"), str) and isinstance(s.get("t"), str))
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _ts(t):
|
|
110
|
+
return datetime.fromisoformat(t.replace("Z", "+00:00")).astimezone(timezone.utc)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _resolve(token, keys):
|
|
114
|
+
"""-> (seal, signature_ok) or a result dict when it can go no further."""
|
|
115
|
+
try:
|
|
116
|
+
seal = seal_from_jws(token)
|
|
117
|
+
except (ValueError, json.JSONDecodeError):
|
|
118
|
+
return {"status": "altered", "message": "The seal in this document is damaged."}
|
|
119
|
+
if not _valid_shape(seal):
|
|
120
|
+
return {"status": "altered", "message": "The seal in this document is damaged."}
|
|
121
|
+
key = next((k for k in keys if k.get("kid") == seal["kid"]), None)
|
|
122
|
+
if key is None:
|
|
123
|
+
return {"status": "unknown-key", "message": "This seal was made with a key we do not recognise.", "seal": seal}
|
|
124
|
+
if key.get("notAfter") and _ts(seal["t"]) > _ts(key["notAfter"]):
|
|
125
|
+
return {"status": "altered", "message": "This seal says it was made after its signing key was withdrawn.", "seal": seal}
|
|
126
|
+
return seal, verify_jws(token, key["jwk"])
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _finish(seal, checks, lookup, note=""):
|
|
130
|
+
if lookup:
|
|
131
|
+
try:
|
|
132
|
+
r = lookup(seal["p"], seal["id"])
|
|
133
|
+
if r:
|
|
134
|
+
if not r.get("registered"):
|
|
135
|
+
checks["registry"] = "unregistered"
|
|
136
|
+
elif r.get("h") != seal["h"]:
|
|
137
|
+
return {"status": "altered", "message": "The registry holds a different hash for this seal.", "seal": seal, "checks": {**checks, "registry": "mismatch"}}
|
|
138
|
+
elif r.get("revoked"):
|
|
139
|
+
return {"status": "revoked", "message": "The sealer has withdrawn this seal.", "seal": seal, "checks": {**checks, "registry": "revoked"}}
|
|
140
|
+
else:
|
|
141
|
+
checks["registry"] = "registered"
|
|
142
|
+
except Exception: # offline: the signature and content checks still stand
|
|
143
|
+
pass
|
|
144
|
+
tail = " The registry has no record of it, so treat it with care." if checks["registry"] == "unregistered" else (" The registry could not be reached." if checks["registry"] == "unchecked" else "")
|
|
145
|
+
return {"status": "genuine", "message": "The seal is genuine and the sealed content is unchanged." + note + tail, "seal": seal, "checks": checks}
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def read_file_seal(data):
|
|
149
|
+
"""The seal appended to a file (PDF, Word, image, video...), or None. -> {"seal": jws, "len": n, "at": offset}"""
|
|
150
|
+
at = data.rfind(FILE_MARK)
|
|
151
|
+
if at < 0:
|
|
152
|
+
return None
|
|
153
|
+
m = re.match(rb"[A-Za-z0-9_-]+", data[at + len(FILE_MARK): at + len(FILE_MARK) + 400000])
|
|
154
|
+
if not m:
|
|
155
|
+
return None
|
|
156
|
+
try:
|
|
157
|
+
obj = json.loads(b64u_decode(m.group(0).decode()))
|
|
158
|
+
return {"seal": obj["seal"], "len": obj["len"], "at": at}
|
|
159
|
+
except (ValueError, KeyError, json.JSONDecodeError):
|
|
160
|
+
return {"seal": None, "len": 0, "at": at}
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def scan(data, keys, lookup=None):
|
|
164
|
+
"""Check the seal inside a file. status: genuine, altered, revoked, unknown-key, no-seal."""
|
|
165
|
+
found = read_file_seal(data)
|
|
166
|
+
if not found:
|
|
167
|
+
return {"status": "no-seal", "message": "This file carries no seal inside it."}
|
|
168
|
+
if not isinstance(found["seal"], str):
|
|
169
|
+
return {"status": "altered", "message": "The seal in this document is damaged."}
|
|
170
|
+
r = _resolve(found["seal"], keys)
|
|
171
|
+
if isinstance(r, dict):
|
|
172
|
+
return r
|
|
173
|
+
seal, ok = r
|
|
174
|
+
checks = {"signature": ok, "content": None, "registry": "unchecked"}
|
|
175
|
+
if seal["k"] != "file":
|
|
176
|
+
return {"status": "altered", "message": "The seal in this document is damaged.", "seal": seal}
|
|
177
|
+
if not ok:
|
|
178
|
+
return {"status": "altered", "message": "The signature does not match. The seal was changed or forged.", "seal": seal, "checks": checks}
|
|
179
|
+
n = found["len"]
|
|
180
|
+
if not (isinstance(n, int) and 0 < n <= len(data)):
|
|
181
|
+
return {"status": "altered", "message": "The seal does not fit this file. The document was changed after it was sealed.", "seal": seal, "checks": checks}
|
|
182
|
+
checks["content"] = sha256_hex(data[:n]) == seal["h"]
|
|
183
|
+
if not checks["content"]:
|
|
184
|
+
return {"status": "altered", "message": "The document no longer matches what was sealed. It was changed after it was sealed.", "seal": seal, "checks": checks}
|
|
185
|
+
return _finish(seal, checks, lookup)
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def scan_sidecar(data, sidecar, keys, lookup=None):
|
|
189
|
+
"""Check a file against its .seal.json certificate."""
|
|
190
|
+
if not isinstance(sidecar, dict) or sidecar.get("type") != "extrafemi-seal-sidecar" or not isinstance(sidecar.get("seal"), str):
|
|
191
|
+
return {"status": "unreadable", "message": "That is not a seal certificate."}
|
|
192
|
+
r = _resolve(sidecar["seal"], keys)
|
|
193
|
+
if isinstance(r, dict):
|
|
194
|
+
return r
|
|
195
|
+
seal, ok = r
|
|
196
|
+
checks = {"signature": ok, "content": None, "registry": "unchecked"}
|
|
197
|
+
if seal["k"] != "file":
|
|
198
|
+
return {"status": "altered", "message": "This certificate is not for a single file.", "seal": seal}
|
|
199
|
+
if not ok:
|
|
200
|
+
return {"status": "altered", "message": "The signature does not match. The certificate was changed or forged.", "seal": seal, "checks": checks}
|
|
201
|
+
checks["content"] = sha256_hex(data) == seal["h"]
|
|
202
|
+
if not checks["content"]:
|
|
203
|
+
return {"status": "altered", "message": "This file is not the one the certificate was made for.", "seal": seal, "checks": checks}
|
|
204
|
+
return _finish(seal, checks, lookup)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
# ---- Merkle trees (RFC 9162) ----
|
|
208
|
+
def leaf_hash(data):
|
|
209
|
+
return hashlib.sha256(b"\x00" + data).hexdigest()
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def node_hash(left, right):
|
|
213
|
+
return hashlib.sha256(b"\x01" + bytes.fromhex(left) + bytes.fromhex(right)).hexdigest()
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def _is_pow2(n):
|
|
217
|
+
return n > 0 and (n & (n - 1)) == 0
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def verify_inclusion(leaf, index, size, path, root):
|
|
221
|
+
if index >= size:
|
|
222
|
+
return False
|
|
223
|
+
fn, sn, r = index, size - 1, leaf
|
|
224
|
+
for p in path:
|
|
225
|
+
if sn == 0:
|
|
226
|
+
return False
|
|
227
|
+
if (fn & 1) == 1 or fn == sn:
|
|
228
|
+
r = node_hash(p, r)
|
|
229
|
+
if (fn & 1) == 0:
|
|
230
|
+
while (fn & 1) == 0 and fn != 0:
|
|
231
|
+
fn >>= 1
|
|
232
|
+
sn >>= 1
|
|
233
|
+
else:
|
|
234
|
+
r = node_hash(r, p)
|
|
235
|
+
fn >>= 1
|
|
236
|
+
sn >>= 1
|
|
237
|
+
return sn == 0 and r == root
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def verify_consistency(size1, size2, path, root1, root2):
|
|
241
|
+
if size1 > size2 or size1 == 0:
|
|
242
|
+
return False
|
|
243
|
+
if size1 == size2:
|
|
244
|
+
return len(path) == 0 and root1 == root2
|
|
245
|
+
proof = ([root1] + list(path)) if _is_pow2(size1) else list(path)
|
|
246
|
+
if not proof:
|
|
247
|
+
return False
|
|
248
|
+
fn, sn = size1 - 1, size2 - 1
|
|
249
|
+
while (fn & 1) == 1:
|
|
250
|
+
fn >>= 1
|
|
251
|
+
sn >>= 1
|
|
252
|
+
fr = sr = proof[0]
|
|
253
|
+
for c in proof[1:]:
|
|
254
|
+
if sn == 0:
|
|
255
|
+
return False
|
|
256
|
+
if (fn & 1) == 1 or fn == sn:
|
|
257
|
+
fr, sr = node_hash(c, fr), node_hash(c, sr)
|
|
258
|
+
while (fn & 1) == 0 and fn != 0:
|
|
259
|
+
fn >>= 1
|
|
260
|
+
sn >>= 1
|
|
261
|
+
else:
|
|
262
|
+
sr = node_hash(sr, c)
|
|
263
|
+
fn >>= 1
|
|
264
|
+
sn >>= 1
|
|
265
|
+
return sn == 0 and fr == root1 and sr == root2
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def verify_batch_receipt(receipt, keys):
|
|
269
|
+
"""A batch receipt {seal, index, size, h, path}: was this item in the sealed batch? -> {"ok": bool, ...}"""
|
|
270
|
+
try:
|
|
271
|
+
seal = seal_from_jws(receipt["seal"])
|
|
272
|
+
if seal["k"] != "batch" or seal.get("n") != receipt["size"]:
|
|
273
|
+
return {"ok": False, "reason": "This seal is not a batch of that size."}
|
|
274
|
+
key = next((k for k in keys if k.get("kid") == seal["kid"]), None)
|
|
275
|
+
if key is None:
|
|
276
|
+
return {"ok": False, "reason": "Unknown key."}
|
|
277
|
+
if not verify_jws(receipt["seal"], key["jwk"]):
|
|
278
|
+
return {"ok": False, "reason": "The seal signature is not valid."}
|
|
279
|
+
leaf = leaf_hash(bytes.fromhex(receipt["h"]))
|
|
280
|
+
if verify_inclusion(leaf, receipt["index"], receipt["size"], receipt["path"], seal["h"]):
|
|
281
|
+
return {"ok": True, "seal": seal}
|
|
282
|
+
return {"ok": False, "reason": "This item is not in the sealed batch.", "seal": seal}
|
|
283
|
+
except Exception:
|
|
284
|
+
return {"ok": False, "reason": "This receipt could not be read."}
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
# ---- signed notes: log checkpoints and witness cosignatures (C2SP) ----
|
|
288
|
+
_SIG_LINE = re.compile("^\u2014 (\\S+) (\\S+)$")
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def _split_note(note):
|
|
292
|
+
at = note.rfind("\n\n")
|
|
293
|
+
if at < 0:
|
|
294
|
+
return None
|
|
295
|
+
return note[: at + 1], [l for l in note[at + 2:].split("\n") if l]
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def _key_hash(name, pub, alg):
|
|
299
|
+
return hashlib.sha256(name.encode() + b"\n" + bytes([alg]) + pub).digest()[:4]
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def verify_note(note, name, pub):
|
|
303
|
+
"""A log checkpoint signed by the log key. -> {"origin", "size", "root"} or None. `pub` is the raw 32 byte key."""
|
|
304
|
+
sp = _split_note(note)
|
|
305
|
+
if not sp:
|
|
306
|
+
return None
|
|
307
|
+
body, lines = sp
|
|
308
|
+
want = _key_hash(name, pub, 1)
|
|
309
|
+
for line in lines:
|
|
310
|
+
m = _SIG_LINE.match(line)
|
|
311
|
+
if not m or m.group(1) != name:
|
|
312
|
+
continue
|
|
313
|
+
try:
|
|
314
|
+
raw = base64.b64decode(m.group(2))
|
|
315
|
+
except ValueError:
|
|
316
|
+
continue
|
|
317
|
+
if len(raw) != 68 or raw[:4] != want:
|
|
318
|
+
continue
|
|
319
|
+
try:
|
|
320
|
+
Ed25519PublicKey.from_public_bytes(pub).verify(raw[4:], body.encode())
|
|
321
|
+
except InvalidSignature:
|
|
322
|
+
continue
|
|
323
|
+
origin, size, root = body.rstrip("\n").split("\n")
|
|
324
|
+
return {"origin": origin, "size": int(size), "root": base64.b64decode(root).hex()}
|
|
325
|
+
return None
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def verify_cosignatures(note, witnesses):
|
|
329
|
+
"""witnesses: [{"name", "pub"}] (raw keys). -> [{"name", "time"}] for the cosignatures that verify."""
|
|
330
|
+
sp = _split_note(note)
|
|
331
|
+
if not sp:
|
|
332
|
+
return []
|
|
333
|
+
body, lines = sp
|
|
334
|
+
out = []
|
|
335
|
+
for w in witnesses:
|
|
336
|
+
want = _key_hash(w["name"], w["pub"], 4)
|
|
337
|
+
for line in lines:
|
|
338
|
+
m = _SIG_LINE.match(line)
|
|
339
|
+
if not m or m.group(1) != w["name"]:
|
|
340
|
+
continue
|
|
341
|
+
try:
|
|
342
|
+
raw = base64.b64decode(m.group(2))
|
|
343
|
+
except ValueError:
|
|
344
|
+
continue
|
|
345
|
+
if len(raw) != 76 or raw[:4] != want:
|
|
346
|
+
continue
|
|
347
|
+
t = int.from_bytes(raw[4:12], "big")
|
|
348
|
+
try:
|
|
349
|
+
Ed25519PublicKey.from_public_bytes(w["pub"]).verify(raw[12:], f"cosignature/v1\ntime {t}\n{body}".encode())
|
|
350
|
+
except InvalidSignature:
|
|
351
|
+
continue
|
|
352
|
+
out.append({"name": w["name"], "time": t})
|
|
353
|
+
break
|
|
354
|
+
return out
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
# ---- keys shipped with this release (work offline) ----
|
|
358
|
+
def builtin_keys():
|
|
359
|
+
"""The seal keys that were current when this version was released. Newer keys need fetch_keys()."""
|
|
360
|
+
from .keys import SEAL_KEYS
|
|
361
|
+
return list(SEAL_KEYS)
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
def builtin_keys_sha256():
|
|
365
|
+
"""SHA 256 of the keys document the registry served at release. That document is sealed in the public log: look the hash up with by_hash()."""
|
|
366
|
+
from .keys import KEYS_SHA256
|
|
367
|
+
return KEYS_SHA256
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
# ---- the registry (needs the network) ----
|
|
371
|
+
def _get_json(url):
|
|
372
|
+
import urllib.request
|
|
373
|
+
with urllib.request.urlopen(url, timeout=15) as r: # nosec - fixed https endpoints
|
|
374
|
+
return json.loads(r.read())
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
def fetch_keys(site=DEFAULT_SITE):
|
|
378
|
+
return _get_json(site + "/.well-known/seal-keys.json")["keys"]
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def make_lookup(site=DEFAULT_SITE):
|
|
382
|
+
return lambda p, i: _get_json(f"{site}/v1/lookup?p={p}&id={i}")
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def by_hash(h, site=DEFAULT_SITE):
|
|
386
|
+
"""Every seal over a file fingerprint, for any file type."""
|
|
387
|
+
return _get_json(f"{site}/v1/by-hash?h={h}")["seals"]
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
def verify_file(path, site=DEFAULT_SITE, offline_keys=None):
|
|
391
|
+
"""Convenience: check a file on disk. With offline_keys (for example builtin_keys()) it never touches the network."""
|
|
392
|
+
with open(path, "rb") as fh:
|
|
393
|
+
data = fh.read()
|
|
394
|
+
keys = offline_keys or fetch_keys(site)
|
|
395
|
+
return scan(data, keys, None if offline_keys else make_lookup(site))
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""Generated by scripts/embed-keys.mjs from keys.json. Do not edit.
|
|
2
|
+
|
|
3
|
+
The public keys when this version was released, and the SHA 256 of the keys document the registry served then.
|
|
4
|
+
"""
|
|
5
|
+
KEYS = [
|
|
6
|
+
{
|
|
7
|
+
"kid": "k1",
|
|
8
|
+
"alg": "Ed25519",
|
|
9
|
+
"jwk": {
|
|
10
|
+
"kty": "OKP",
|
|
11
|
+
"crv": "Ed25519",
|
|
12
|
+
"x": "lvOOBXcwN_2annLVBeEZAvFZcwQNNUztUa4S10Dwbgs",
|
|
13
|
+
},
|
|
14
|
+
"purpose": "seal",
|
|
15
|
+
},
|
|
16
|
+
{
|
|
17
|
+
"kid": "log1",
|
|
18
|
+
"alg": "Ed25519",
|
|
19
|
+
"purpose": "log",
|
|
20
|
+
"jwk": {
|
|
21
|
+
"kty": "OKP",
|
|
22
|
+
"crv": "Ed25519",
|
|
23
|
+
"x": "rcTYCfjD-zueDSRsZEU6J4eFxUQI2R-iNLfIxSSnG1k",
|
|
24
|
+
},
|
|
25
|
+
},
|
|
26
|
+
{
|
|
27
|
+
"kid": "slh1",
|
|
28
|
+
"alg": "SLH-DSA-SHA2-128f",
|
|
29
|
+
"purpose": "log-pq-backup",
|
|
30
|
+
"jwk": {
|
|
31
|
+
"kty": "AKP",
|
|
32
|
+
"alg": "SLH-DSA-SHA2-128f",
|
|
33
|
+
"pub": "lzAc7b2ge6WXCjH3d3i22Ck3OkSk2Nu7qpT6XEvLCv4",
|
|
34
|
+
},
|
|
35
|
+
},
|
|
36
|
+
{
|
|
37
|
+
"kid": "pq1",
|
|
38
|
+
"alg": "ML-DSA-65",
|
|
39
|
+
"purpose": "seal-pq",
|
|
40
|
+
"jwk": {
|
|
41
|
+
"kty": "AKP",
|
|
42
|
+
"alg": "ML-DSA-65",
|
|
43
|
+
"pub": "qTv79KAwokOkWmIf330QNGNzQkCToavBXXE3uF3bb5onQNTiLlzd3l0yYDKOrznLgCsl-DA1ljK0Kp0j9w5Om3KOsrtKA9tr3_Jz3psUC0_RoZUUv0QBevGL5LEUqc_oeB2fiRdO-DDqy5D47dc4ZQ9DzUtNyChyY-3Z9VJCptuUDtgZl31rHjm6YRGqEt7fjJUw1fnTHtg_FOpDnsX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Car5ATM95OlnNUu9T-CqsADqSA_lHBjHZaPvQkMjNLPdvzcsTqqZeCRVx8ESsuRYUtsKeN56sLVyG7rKT13ENuDvz7XRlneCSs7838xkf3gJIBqrEN5-439db13g8tzWl9AQIJloH5w7KoESHnAwHUKj0LSFFWMHZjyVGwGGWqi0sVekrEl-hMy29gZJ4d9jQ_1DeIa_YkplTiOEGzPl4nwx3FQe83RiPwNAmkFA1VkHVVeSmIizZ1Jz11n908E",
|
|
44
|
+
},
|
|
45
|
+
},
|
|
46
|
+
]
|
|
47
|
+
KEYS_SHA256 = "52ad27eeeeeb26790aa20e8e27d915929da7eaf52c3be58cd5016972d5662202"
|
|
48
|
+
# the keys that sign seals (the log key signs only transparency log checkpoints)
|
|
49
|
+
SEAL_KEYS = [k for k in KEYS if k.get("purpose", "seal") == "seal"]
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: extrafemi-seal
|
|
3
|
+
Version: 0.1.1
|
|
4
|
+
Summary: Check seals made by Seal, certificates, batch receipts and transparency log checkpoints.
|
|
5
|
+
License: MIT
|
|
6
|
+
Project-URL: Homepage, https://seal.extrafemi.com
|
|
7
|
+
Project-URL: Source, https://github.com/obasaolorunfemi-ai/seal
|
|
8
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
9
|
+
Classifier: Topic :: Security :: Cryptography
|
|
10
|
+
Requires-Python: >=3.9
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
Requires-Dist: cryptography>=42
|
|
13
|
+
|
|
14
|
+
# extrafemi-seal (Python)
|
|
15
|
+
|
|
16
|
+
Check seals made by [Seal](https://seal.extrafemi.com) in Python, offline if you hold the public keys.
|
|
17
|
+
|
|
18
|
+
```python
|
|
19
|
+
import extrafemi_seal as seal
|
|
20
|
+
|
|
21
|
+
keys = seal.fetch_keys() # current keys from the registry, or seal.builtin_keys() to stay offline
|
|
22
|
+
result = seal.scan(open("contract.pdf", "rb").read(), keys, seal.make_lookup())
|
|
23
|
+
print(result["status"], result["message"]) # genuine, altered, revoked, unknown-key or no-seal
|
|
24
|
+
|
|
25
|
+
seal.scan_sidecar(data, json.load(open("photo.jpg.seal.json")), keys) # a file with its certificate
|
|
26
|
+
seal.verify_batch_receipt(receipt, keys) # was an item in a sealed batch?
|
|
27
|
+
seal.verify_note(checkpoint_text, "seal.extrafemi.com", log_public_key) # a log checkpoint
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Works for file seals in PDF, Word, Excel, EPUB, ZIP, PNG, JPEG, GIF and MP4, for sidecar certificates and batch
|
|
31
|
+
receipts. Not yet: the hidden text seals products put in their own PDFs. Tested against vectors made by the
|
|
32
|
+
JavaScript library (`python3 -m unittest discover tests`). Needs `cryptography`.
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
README.md
|
|
2
|
+
pyproject.toml
|
|
3
|
+
extrafemi_seal/__init__.py
|
|
4
|
+
extrafemi_seal/keys.py
|
|
5
|
+
extrafemi_seal.egg-info/PKG-INFO
|
|
6
|
+
extrafemi_seal.egg-info/SOURCES.txt
|
|
7
|
+
extrafemi_seal.egg-info/dependency_links.txt
|
|
8
|
+
extrafemi_seal.egg-info/requires.txt
|
|
9
|
+
extrafemi_seal.egg-info/top_level.txt
|
|
10
|
+
tests/test_vectors.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
cryptography>=42
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
extrafemi_seal
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "extrafemi-seal"
|
|
7
|
+
version = "0.1.1"
|
|
8
|
+
description = "Check seals made by Seal, certificates, batch receipts and transparency log checkpoints."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = { text = "MIT" }
|
|
11
|
+
requires-python = ">=3.9"
|
|
12
|
+
dependencies = ["cryptography>=42"]
|
|
13
|
+
classifiers = ["License :: OSI Approved :: MIT License", "Topic :: Security :: Cryptography"]
|
|
14
|
+
|
|
15
|
+
[project.urls]
|
|
16
|
+
Homepage = "https://seal.extrafemi.com"
|
|
17
|
+
Source = "https://github.com/obasaolorunfemi-ai/seal"
|
|
18
|
+
|
|
19
|
+
[tool.setuptools]
|
|
20
|
+
packages = ["extrafemi_seal"]
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
"""Tests against vectors/vectors.json, which the JavaScript library produced. python3 -m unittest discover python/tests"""
|
|
2
|
+
import base64
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import unittest
|
|
6
|
+
|
|
7
|
+
import extrafemi_seal as s
|
|
8
|
+
|
|
9
|
+
V = json.load(open(os.path.join(os.path.dirname(__file__), "..", "..", "vectors", "vectors.json")))
|
|
10
|
+
KEYS = V["keys"]
|
|
11
|
+
unb = base64.b64decode
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class Vectors(unittest.TestCase):
|
|
15
|
+
def test_files(self):
|
|
16
|
+
for c in V["cases"]:
|
|
17
|
+
with self.subTest(c["name"]):
|
|
18
|
+
data = unb(c["file"])
|
|
19
|
+
r = s.scan_sidecar(data, c["sidecar"], KEYS) if "sidecar" in c else s.scan(data, KEYS)
|
|
20
|
+
self.assertEqual(r["status"], c["expect"]["status"], r.get("message"))
|
|
21
|
+
if "id" in c["expect"]:
|
|
22
|
+
self.assertEqual(r["seal"]["id"], c["expect"]["id"])
|
|
23
|
+
self.assertEqual(r["seal"]["h"], c["expect"]["h"] if "h" in c["expect"] else r["seal"]["h"])
|
|
24
|
+
if "by" in c["expect"]:
|
|
25
|
+
self.assertEqual(r["seal"]["by"], c["expect"]["by"])
|
|
26
|
+
|
|
27
|
+
def test_registry_states(self):
|
|
28
|
+
c = next(c for c in V["cases"] if c["name"] == "pdf sealed")
|
|
29
|
+
data = unb(c["file"])
|
|
30
|
+
seal = s.scan(data, KEYS)["seal"]
|
|
31
|
+
self.assertEqual(s.scan(data, KEYS, lambda p, i: {"registered": True, "h": seal["h"], "revoked": True})["status"], "revoked")
|
|
32
|
+
self.assertEqual(s.scan(data, KEYS, lambda p, i: {"registered": True, "h": "0" * 64, "revoked": False})["status"], "altered")
|
|
33
|
+
self.assertEqual(s.scan(data, KEYS, lambda p, i: {"registered": False})["checks"]["registry"], "unregistered")
|
|
34
|
+
self.assertEqual(s.scan(data, KEYS, lambda p, i: {"registered": True, "h": seal["h"], "revoked": False})["checks"]["registry"], "registered")
|
|
35
|
+
|
|
36
|
+
def test_jws(self):
|
|
37
|
+
j = V["jws"]
|
|
38
|
+
self.assertTrue(s.verify_jws(j["token"], KEYS[0]["jwk"]))
|
|
39
|
+
self.assertFalse(s.verify_jws(j["token"], KEYS[1]["jwk"]))
|
|
40
|
+
self.assertFalse(s.verify_jws(j["tampered"], KEYS[0]["jwk"]))
|
|
41
|
+
self.assertEqual(s.parse_jws(j["token"])["payload"], j["payload"])
|
|
42
|
+
self.assertEqual(s.canonicalize(json.loads('{"b":[1,{"z":null,"a":"\u00e9"}],"a":1e21}')), j["canonicalExpected"])
|
|
43
|
+
self.assertEqual(s.canonicalize({"\r": 1, "1": 2, "\u00f6": 3, "\u20ac": 4, "\ufb33": 5}), '{"\\r":1,"1":2,"\u00f6":3,"\u20ac":4,"\ufb33":5}')
|
|
44
|
+
|
|
45
|
+
def test_batch(self):
|
|
46
|
+
for r in V["batch"]["receipts"]:
|
|
47
|
+
self.assertTrue(s.verify_batch_receipt(r, KEYS)["ok"])
|
|
48
|
+
for r in V["batch"]["bad"]:
|
|
49
|
+
self.assertFalse(s.verify_batch_receipt(r, KEYS)["ok"])
|
|
50
|
+
|
|
51
|
+
def test_merkle(self):
|
|
52
|
+
for p in V["merkle"]["inclusion"]:
|
|
53
|
+
self.assertTrue(s.verify_inclusion(p["leaf"], p["index"], p["size"], p["path"], p["root"]))
|
|
54
|
+
self.assertFalse(s.verify_inclusion(s.leaf_hash(b"x"), p["index"], p["size"], p["path"], p["root"]))
|
|
55
|
+
for p in V["merkle"]["consistency"]:
|
|
56
|
+
self.assertTrue(s.verify_consistency(p["size1"], p["size2"], p["path"], p["root1"], p["root2"]))
|
|
57
|
+
if p["size1"] != p["size2"]:
|
|
58
|
+
self.assertFalse(s.verify_consistency(p["size1"], p["size2"], p["path"], s.leaf_hash(b"x"), p["root2"]))
|
|
59
|
+
|
|
60
|
+
def test_notes(self):
|
|
61
|
+
n = V["notes"]
|
|
62
|
+
pub = unb(n["logKey"])
|
|
63
|
+
got = s.verify_note(n["note"], n["name"], pub)
|
|
64
|
+
self.assertEqual((got["size"], got["root"], got["origin"]), (n["size"], n["root"], "vectors.example/log"))
|
|
65
|
+
self.assertIsNone(s.verify_note(n["tampered"], n["name"], pub))
|
|
66
|
+
self.assertIsNone(s.verify_note(n["note"], "other.example", pub))
|
|
67
|
+
w = [{"name": n["witness"]["name"], "pub": unb(n["witness"]["key"])}]
|
|
68
|
+
co = s.verify_cosignatures(n["cosigned"], w)
|
|
69
|
+
self.assertEqual(co, [{"name": "witness.example", "time": n["cosignTime"]}])
|
|
70
|
+
self.assertEqual(s.verify_cosignatures(n["note"], w), [])
|
|
71
|
+
self.assertEqual(s.verify_cosignatures(n["cosigned"], [{"name": "witness.example", "pub": pub}]), [])
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class BuiltIn(unittest.TestCase):
|
|
75
|
+
def test_builtin_keys(self):
|
|
76
|
+
keys = s.builtin_keys()
|
|
77
|
+
self.assertTrue(len(keys) >= 1 and all(k.get("purpose", "seal") == "seal" for k in keys))
|
|
78
|
+
self.assertEqual(len(s.builtin_keys_sha256()), 64)
|
|
79
|
+
self.assertEqual(s.scan(b"nothing sealed here", keys)["status"], "no-seal")
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
if __name__ == "__main__":
|
|
83
|
+
unittest.main()
|