okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221updates: signed feed, Ed25519 verifier, component updater with resume, staged test-start, switch and rollbackc8698f625

main
13.5 KiB330 linesraw
1"""Ed25519 signatures for the update feed and the engine components, with no third-party package.
2
3The packaged Control ships a pinned CPython with hash-locked wheels; adding a crypto wheel for one signature check would
4widen that lock for no gain. Ed25519 (RFC 8032) is small enough to carry here: verification is what every installed PC
5runs, signing is what the owner's release machine runs (`packaging/feed_tool.py`). Both are checked against the RFC's
6test vectors in tests/terminal/test_update_feed.py.
7
8Two kinds of key exist and must not be mixed up:
9
10* the **feed/component key** (this module): an Ed25519 key the owner keeps offline. It signs the update feed index and every
11  engine package manifest. Installed copies of Control carry the public half in ``update_keys.json`` and nothing else
12  can add to it except the explicit, documented override ``STRATA_UPDATE_TRUSTED_KEYS`` (a file of extra public keys;
13  the test suite and a local feed use it, and the CLI says so when it is in effect).
14* the **app updater key** (Tauri's minisign key): signs the desktop installer. ``minisign_verify`` below checks such a
15  signature so the Terminal can verify an app installer it downloads, the same way the Tauri updater does.
16
17A public key is ``{"key_id": "<16 hex>", "alg": "ed25519", "public": "<base64 of the 32 bytes>"}``. ``key_id`` is the first 8 bytes
18of SHA-256 of the public key, so a signature names the key that made it without anyone choosing the name.
19"""
20
21from __future__ import annotations
22
23import base64
24import hashlib
25import json
26import os
27import secrets
28from pathlib import Path
29
30ALG = "ed25519"
31ENV_EXTRA_KEYS = "STRATA_UPDATE_TRUSTED_KEYS"
32BUILTIN_KEYS = Path(__file__).with_name("update_keys.json")
33
34
35class SignatureError(ValueError):
36    """A signature, a key or a signed document is not what it claims to be."""
37
38
39# ---------------------------------------------------------------------------------------------- RFC 8032 Ed25519
40
41_P = 2 ** 255 - 19
42_L = 2 ** 252 + 27742317777372353535851937790883648493
43_D = -121665 * pow(121666, _P - 2, _P) % _P
44_I = pow(2, (_P - 1) // 4, _P)
45
46
47def _inv(x: int) -> int:
48    return pow(x, _P - 2, _P)
49
50
51def _recover_x(y: int, sign: int) -> int | None:
52    if y >= _P:
53        return None
54    xx = (y * y - 1) * _inv(_D * y * y + 1) % _P
55    x = pow(xx, (_P + 3) // 8, _P)
56    if (x * x - xx) % _P != 0:
57        x = x * _I % _P
58    if (x * x - xx) % _P != 0:
59        return None
60    if x == 0 and sign:
61        return None
62    if x & 1 != sign:
63        x = _P - x
64    return x
65
66
67_GY = 4 * _inv(5) % _P
68_GX = _recover_x(_GY, 0)
69_G = (_GX, _GY, 1, _GX * _GY % _P)
70
71
72def _add(a, b):
73    a1 = (a[1] - a[0]) * (b[1] - b[0]) % _P
74    b1 = (a[1] + a[0]) * (b[1] + b[0]) % _P
75    c1 = 2 * a[3] * b[3] * _D % _P
76    d1 = 2 * a[2] * b[2] % _P
77    e, f, g, h = b1 - a1, d1 - c1, d1 + c1, b1 + a1
78    return (e * f % _P, g * h % _P, f * g % _P, e * h % _P)
79
80
81def _mul(scalar: int, point):
82    result = (0, 1, 1, 0)
83    while scalar > 0:
84        if scalar & 1:
85            result = _add(result, point)
86        point = _add(point, point)
87        scalar >>= 1
88    return result
89
90
91def _equal(a, b) -> bool:
92    return (a[0] * b[2] - b[0] * a[2]) % _P == 0 and (a[1] * b[2] - b[1] * a[2]) % _P == 0
93
94
95def _compress(point) -> bytes:
96    zi = _inv(point[2])
97    x, y = point[0] * zi % _P, point[1] * zi % _P
98    return int(y | ((x & 1) << 255)).to_bytes(32, "little")
99
100
101def _decompress(data: bytes):
102    if len(data) != 32:
103        return None
104    value = int.from_bytes(data, "little")
105    y, sign = value & ((1 << 255) - 1), value >> 255
106    x = _recover_x(y, sign)
107    if x is None:
108        return None
109    return (x, y, 1, x * y % _P)
110
111
112def _sha512(*parts: bytes) -> bytes:
113    return hashlib.sha512(b"".join(parts)).digest()
114
115
116def _secret_expand(seed: bytes) -> tuple[int, bytes]:
117    if len(seed) != 32:
118        raise SignatureError("an Ed25519 seed is 32 bytes")
119    h = _sha512(seed)
120    a = int.from_bytes(h[:32], "little")
121    a &= (1 << 254) - 8
122    a |= 1 << 254
123    return a, h[32:]
124
125
126def public_from_seed(seed: bytes) -> bytes:
127    a, _ = _secret_expand(seed)
128    return _compress(_mul(a, _G))
129
130
131def sign_raw(seed: bytes, message: bytes) -> bytes:
132    a, prefix = _secret_expand(seed)
133    public = _compress(_mul(a, _G))
134    r = int.from_bytes(_sha512(prefix, message), "little") % _L
135    big_r = _compress(_mul(r, _G))
136    h = int.from_bytes(_sha512(big_r, public, message), "little") % _L
137    s = (r + h * a) % _L
138    return big_r + int(s).to_bytes(32, "little")
139
140
141def verify_raw(public: bytes, message: bytes, signature: bytes) -> bool:
142    """RFC 8032 verification (cofactorless; non-canonical encodings and s >= L are refused)."""
143    if len(public) != 32 or len(signature) != 64:
144        return False
145    point_a = _decompress(public)
146    point_r = _decompress(signature[:32])
147    if point_a is None or point_r is None:
148        return False
149    s = int.from_bytes(signature[32:], "little")
150    if s >= _L:
151        return False
152    h = int.from_bytes(_sha512(signature[:32], public, message), "little") % _L
153    return _equal(_mul(s, _G), _add(point_r, _mul(h, point_a)))
154
155
156# ---------------------------------------------------------------------------------------------- keys
157
158def key_id_of(public: bytes) -> str:
159    return hashlib.sha256(public).digest()[:8].hex()
160
161
162def generate_key() -> dict:
163    """A new key pair as the dictionary `write_key_files` stores. The seed is the secret: it is never printed."""
164    seed = secrets.token_bytes(32)
165    public = public_from_seed(seed)
166    return {"alg": ALG, "key_id": key_id_of(public),
167            "public": base64.b64encode(public).decode("ascii"), "seed": base64.b64encode(seed).decode("ascii")}
168
169
170def public_part(key: dict) -> dict:
171    return {"alg": ALG, "key_id": key["key_id"], "public": key["public"]}
172
173
174def _b64(value, what: str, length: int) -> bytes:
175    try:
176        raw = base64.b64decode(str(value), validate=True)
177    except (ValueError, TypeError):
178        raise SignatureError(f"{what} is not valid base64") from None
179    if len(raw) != length:
180        raise SignatureError(f"{what} must be {length} bytes")
181    return raw
182
183
184def parse_public(entry: dict) -> tuple[str, bytes]:
185    if not isinstance(entry, dict) or entry.get("alg") != ALG:
186        raise SignatureError("a public key entry needs alg ed25519")
187    public = _b64(entry.get("public"), "a public key", 32)
188    key_id = key_id_of(public)
189    if entry.get("key_id") != key_id:
190        raise SignatureError(f"the key_id {entry.get('key_id')!r} does not belong to that public key")
191    return key_id, public
192
193
194def load_trusted_keys(extra: str | os.PathLike | None = None, *, environ=None) -> dict[str, bytes]:
195    """{key_id: public key bytes}: the keys shipped in ``update_keys.json`` plus a file of extra keys when
196    ``STRATA_UPDATE_TRUSTED_KEYS`` (or `extra`) names one. A malformed entry is an error, never skipped, so a typo cannot
197    quietly turn into "trust nothing" or "trust something else"."""
198    environ = os.environ if environ is None else environ
199    keys: dict[str, bytes] = {}
200    for path in (BUILTIN_KEYS, extra or environ.get(ENV_EXTRA_KEYS)):
201        if not path:
202            continue
203        p = Path(path)
204        if p == BUILTIN_KEYS and not p.exists():
205            continue
206        try:
207            data = json.loads(p.read_text(encoding="utf-8-sig"))
208        except (OSError, ValueError) as exc:
209            raise SignatureError(f"the key file {p} cannot be read ({type(exc).__name__})") from None
210        entries = data.get("keys") if isinstance(data, dict) else data
211        if not isinstance(entries, list):
212            raise SignatureError(f"the key file {p} has no list of keys")
213        for entry in entries:
214            key_id, public = parse_public(entry)
215            keys[key_id] = public
216    return keys
217
218
219def extra_keys_in_effect(environ=None) -> bool:
220    environ = os.environ if environ is None else environ
221    return bool(environ.get(ENV_EXTRA_KEYS))
222
223
224# ---------------------------------------------------------------------------------------------- signing documents
225
226def sign_bytes(key: dict, payload: bytes) -> dict:
227    """``{"alg", "key_id", "value"}`` over exactly `payload`."""
228    seed = _b64(key.get("seed"), "the secret seed", 32)
229    if public_from_seed(seed) != base64.b64decode(key["public"]) or key_id_of(public_from_seed(seed)) != key["key_id"]:
230        raise SignatureError("the secret seed does not match the public key in the key file")
231    return {"alg": ALG, "key_id": key["key_id"], "value": base64.b64encode(sign_raw(seed, payload)).decode("ascii")}
232
233
234def verify_bytes(trusted: dict[str, bytes], payload: bytes, signature: dict) -> str:
235    """The key_id that signed `payload`; raises SignatureError when the signature is missing, from an unknown key, or bad."""
236    if not isinstance(signature, dict) or signature.get("alg") != ALG:
237        raise SignatureError("the signature is not an ed25519 signature")
238    key_id = signature.get("key_id")
239    public = trusted.get(key_id) if isinstance(key_id, str) else None
240    if public is None:
241        raise SignatureError(f"the signature was made by a key this PC does not trust ({key_id!r})")
242    raw = _b64(signature.get("value"), "the signature value", 64)
243    if not verify_raw(public, payload, raw):
244        raise SignatureError("the signature does not match the signed content")
245    return key_id
246
247
248def install_component_verifier(trusted: dict[str, bytes]) -> None:
249    """Hook the engine component's signature check (engine_component.register_signature_verifier) to `trusted`.
250    A manifest then counts as verified only if one of these keys signed its canonical payload."""
251    from strata_control import engine_component
252
253    def verifier(payload: bytes, signature: dict, component) -> None:
254        try:
255            verify_bytes(trusted, payload, signature)
256        except SignatureError as exc:
257            raise engine_component.IntegrityProblem(str(exc)) from None
258
259    engine_component.register_signature_verifier(verifier)
260
261
262def ensure_component_verifier() -> bool:
263    """Register the verifier with the shipped keys (and the explicit extra-keys file) unless one is registered already.
264    Returns False when there are no keys to check against: signed packages are then reported unverified, never verified."""
265    from strata_control import engine_component
266    if engine_component._verifier is not None:
267        return True
268    trusted = load_trusted_keys()
269    if not trusted:
270        return False
271    install_component_verifier(trusted)
272    return True
273
274
275# ---------------------------------------------------------------------------------------------- minisign (Tauri updater)
276
277def minisign_public(text_or_b64: str) -> tuple[bytes, bytes]:
278    """(key id, public key) from a minisign public key: the Tauri ``pubkey`` value (base64 of the .pub file) or the file text."""
279    text = text_or_b64.strip()
280    if "untrusted comment" not in text:
281        try:
282            text = base64.b64decode(text, validate=True).decode("utf-8")
283        except (ValueError, UnicodeError):
284            raise SignatureError("the minisign public key is not valid") from None
285    lines = [line for line in text.splitlines() if line.strip() and not line.startswith("untrusted comment")]
286    if not lines:
287        raise SignatureError("the minisign public key has no key line")
288    raw = _b64(lines[0].strip(), "the minisign public key", 42)
289    if raw[:2] != b"Ed":
290        raise SignatureError("the minisign public key is not an Ed25519 key")
291    return raw[2:10], raw[10:42]
292
293
294def minisign_verify(public_text: str, signature_text: str, data_chunks) -> None:
295    """Check a minisign signature (the Tauri updater's format) over `data_chunks` (an iterable of bytes).
296
297    Legacy ``Ed`` signs the data itself, ``ED`` signs its BLAKE2b-512 digest (what Tauri produces); both are accepted.
298    The signature can be the Tauri updater JSON value (base64 of the .sig file) or the file text."""
299    key_id, public = minisign_public(public_text)
300    text = signature_text.strip()
301    if "untrusted comment" not in text:
302        try:
303            text = base64.b64decode(text, validate=True).decode("utf-8")
304        except (ValueError, UnicodeError):
305            raise SignatureError("the app signature is not valid base64") from None
306    lines = [line for line in text.splitlines() if line.strip()]
307    body = [line for line in lines if not line.startswith(("untrusted comment", "trusted comment"))]
308    if not body:
309        raise SignatureError("the app signature has no signature line")
310    raw = _b64(body[0].strip(), "the app signature", 74)
311    algorithm, signer, signature = raw[:2], raw[2:10], raw[10:74]
312    if signer != key_id:
313        raise SignatureError("the app signature was made by a different key than the one this build trusts")
314    if algorithm == b"ED":
315        digest = hashlib.blake2b(digest_size=64)
316        for chunk in data_chunks:
317            digest.update(chunk)
318        message = digest.digest()
319    elif algorithm == b"Ed":
320        message = b"".join(data_chunks)
321    else:
322        raise SignatureError("the app signature uses an unknown algorithm")
323    if not verify_raw(public, message, signature):
324        raise SignatureError("the app installer does not match its signature")
325    # the global signature covers the trusted comment: it is checked when present so a tampered comment is refused too
326    comment = next((line[len("trusted comment: "):] for line in lines if line.startswith("trusted comment: ")), None)
327    if comment is not None and len(body) > 1:
328        global_sig = _b64(body[1].strip(), "the app signature's global part", 64)
329        if not verify_raw(public, signature + comment.encode("utf-8"), global_sig):
330            raise SignatureError("the app signature's comment was changed")