okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
c8698f625
main
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 11engine package manifest. Installed copies of Control carry the public half in ``update_keys.json`` and nothing else 12can add to it except the explicit, documented override ``STRATA_UPDATE_TRUSTED_KEYS`` (a file of extra public keys; 13the 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 15signature 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 : 48return pow (x ,_P - 2 ,_P ) 49 50 51def _recover_x (y :int ,sign :int )-> int | None : 52if y >= _P : 53return None 54xx = (y * y - 1 )* _inv (_D * y * y + 1 )% _P 55x = pow (xx , (_P + 3 )// 8 ,_P ) 56if (x * x - xx )% _P != 0 : 57x = x * _I % _P 58if (x * x - xx )% _P != 0 : 59return None 60if x == 0 and sign : 61return None 62if x & 1 != sign : 63x = _P - x 64return 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 ): 73a1 = (a [1 ]- a [0 ])* (b [1 ]- b [0 ])% _P 74b1 = (a [1 ]+ a [0 ])* (b [1 ]+ b [0 ])% _P 75c1 = 2 * a [3 ]* b [3 ]* _D % _P 76d1 = 2 * a [2 ]* b [2 ]% _P 77e ,f ,g ,h = b1 - a1 ,d1 - c1 ,d1 + c1 ,b1 + a1 78return (e * f % _P ,g * h % _P ,f * g % _P ,e * h % _P ) 79 80 81def _mul (scalar :int ,point ): 82result = (0 ,1 ,1 ,0 ) 83while scalar > 0 : 84if scalar & 1 : 85result = _add (result ,point ) 86point = _add (point ,point ) 87scalar >>= 1 88return result 89 90 91def _equal (a ,b )-> bool : 92return (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 : 96zi = _inv (point [2 ]) 97x ,y = point [0 ]* zi % _P ,point [1 ]* zi % _P 98return int (y | ((x & 1 )<< 255 )).to_bytes (32 ,"little" ) 99 100 101def _decompress (data :bytes ): 102if len (data )!= 32 : 103return None 104value = int .from_bytes (data ,"little" ) 105y ,sign = value & ((1 << 255 )- 1 ),value >> 255 106x = _recover_x (y ,sign ) 107if x is None : 108return None 109return (x ,y ,1 ,x * y % _P ) 110 111 112def _sha512 (* parts :bytes )-> bytes : 113return hashlib .sha512 (b"" .join (parts )).digest () 114 115 116def _secret_expand (seed :bytes )-> tuple [int ,bytes ]: 117if len (seed )!= 32 : 118raise SignatureError ("an Ed25519 seed is 32 bytes" ) 119h = _sha512 (seed ) 120a = int .from_bytes (h [:32 ],"little" ) 121a &= (1 << 254 )- 8 122a |= 1 << 254 123return a ,h [32 :] 124 125 126def public_from_seed (seed :bytes )-> bytes : 127a ,_ = _secret_expand (seed ) 128return _compress (_mul (a ,_G )) 129 130 131def sign_raw (seed :bytes ,message :bytes )-> bytes : 132a ,prefix = _secret_expand (seed ) 133public = _compress (_mul (a ,_G )) 134r = int .from_bytes (_sha512 (prefix ,message ),"little" )% _L 135big_r = _compress (_mul (r ,_G )) 136h = int .from_bytes (_sha512 (big_r ,public ,message ),"little" )% _L 137s = (r + h * a )% _L 138return 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).""" 143if len (public )!= 32 or len (signature )!= 64 : 144return False 145point_a = _decompress (public ) 146point_r = _decompress (signature [:32 ]) 147if point_a is None or point_r is None : 148return False 149s = int .from_bytes (signature [32 :],"little" ) 150if s >= _L : 151return False 152h = int .from_bytes (_sha512 (signature [:32 ],public ,message ),"little" )% _L 153return _equal (_mul (s ,_G ),_add (point_r ,_mul (h ,point_a ))) 154 155 156# ---------------------------------------------------------------------------------------------- keys 157 158def key_id_of (public :bytes )-> str : 159return 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.""" 164seed = secrets .token_bytes (32 ) 165public = public_from_seed (seed ) 166return {"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 : 171return {"alg" :ALG ,"key_id" :key ["key_id" ],"public" :key ["public" ]} 172 173 174def _b64 (value ,what :str ,length :int )-> bytes : 175try : 176raw = base64 .b64decode (str (value ),validate = True ) 177except (ValueError ,TypeError ): 178raise SignatureError (f" { what } is not valid base64" )from None 179if len (raw )!= length : 180raise SignatureError (f" { what } must be { length } bytes" ) 181return raw 182 183 184def parse_public (entry :dict )-> tuple [str ,bytes ]: 185if not isinstance (entry ,dict )or entry .get ("alg" )!= ALG : 186raise SignatureError ("a public key entry needs alg ed25519" ) 187public = _b64 (entry .get ("public" ),"a public key" ,32 ) 188key_id = key_id_of (public ) 189if entry .get ("key_id" )!= key_id : 190raise SignatureError (f"the key_id { entry . get ( 'key_id' )!r } does not belong to that public key" ) 191return 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 197quietly turn into "trust nothing" or "trust something else".""" 198environ = os .environ if environ is None else environ 199keys :dict [str ,bytes ]= {} 200for path in (BUILTIN_KEYS ,extra or environ .get (ENV_EXTRA_KEYS )): 201if not path : 202continue 203p = Path (path ) 204if p == BUILTIN_KEYS and not p .exists (): 205continue 206try : 207data = json .loads (p .read_text (encoding = "utf-8-sig" )) 208except (OSError ,ValueError )as exc : 209raise SignatureError (f"the key file { p } cannot be read ( { type ( exc ). __name__ } )" )from None 210entries = data .get ("keys" )if isinstance (data ,dict )else data 211if not isinstance (entries ,list ): 212raise SignatureError (f"the key file { p } has no list of keys" ) 213for entry in entries : 214key_id ,public = parse_public (entry ) 215keys [key_id ]= public 216return keys 217 218 219def extra_keys_in_effect (environ = None )-> bool : 220environ = os .environ if environ is None else environ 221return 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`.""" 228seed = _b64 (key .get ("seed" ),"the secret seed" ,32 ) 229if public_from_seed (seed )!= base64 .b64decode (key ["public" ])or key_id_of (public_from_seed (seed ))!= key ["key_id" ]: 230raise SignatureError ("the secret seed does not match the public key in the key file" ) 231return {"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.""" 236if not isinstance (signature ,dict )or signature .get ("alg" )!= ALG : 237raise SignatureError ("the signature is not an ed25519 signature" ) 238key_id = signature .get ("key_id" ) 239public = trusted .get (key_id )if isinstance (key_id ,str )else None 240if public is None : 241raise SignatureError (f"the signature was made by a key this PC does not trust ( { key_id !r } )" ) 242raw = _b64 (signature .get ("value" ),"the signature value" ,64 ) 243if not verify_raw (public ,payload ,raw ): 244raise SignatureError ("the signature does not match the signed content" ) 245return 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`. 250A manifest then counts as verified only if one of these keys signed its canonical payload.""" 251from strata_control import engine_component 252 253def verifier (payload :bytes ,signature :dict ,component )-> None : 254try : 255verify_bytes (trusted ,payload ,signature ) 256except SignatureError as exc : 257raise engine_component .IntegrityProblem (str (exc ))from None 258 259engine_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. 264Returns False when there are no keys to check against: signed packages are then reported unverified, never verified.""" 265from strata_control import engine_component 266if engine_component ._verifier is not None : 267return True 268trusted = load_trusted_keys () 269if not trusted : 270return False 271install_component_verifier (trusted ) 272return 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.""" 279text = text_or_b64 .strip () 280if "untrusted comment" not in text : 281try : 282text = base64 .b64decode (text ,validate = True ).decode ("utf-8" ) 283except (ValueError ,UnicodeError ): 284raise SignatureError ("the minisign public key is not valid" )from None 285lines = [line for line in text .splitlines ()if line .strip ()and not line .startswith ("untrusted comment" )] 286if not lines : 287raise SignatureError ("the minisign public key has no key line" ) 288raw = _b64 (lines [0 ].strip (),"the minisign public key" ,42 ) 289if raw [:2 ]!= b"Ed" : 290raise SignatureError ("the minisign public key is not an Ed25519 key" ) 291return 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 297Legacy ``Ed`` signs the data itself, ``ED`` signs its BLAKE2b-512 digest (what Tauri produces); both are accepted. 298The signature can be the Tauri updater JSON value (base64 of the .sig file) or the file text.""" 299key_id ,public = minisign_public (public_text ) 300text = signature_text .strip () 301if "untrusted comment" not in text : 302try : 303text = base64 .b64decode (text ,validate = True ).decode ("utf-8" ) 304except (ValueError ,UnicodeError ): 305raise SignatureError ("the app signature is not valid base64" )from None 306lines = [line for line in text .splitlines ()if line .strip ()] 307body = [line for line in lines if not line .startswith (("untrusted comment" ,"trusted comment" ))] 308if not body : 309raise SignatureError ("the app signature has no signature line" ) 310raw = _b64 (body [0 ].strip (),"the app signature" ,74 ) 311algorithm ,signer ,signature = raw [:2 ],raw [2 :10 ],raw [10 :74 ] 312if signer != key_id : 313raise SignatureError ("the app signature was made by a different key than the one this build trusts" ) 314if algorithm == b"ED" : 315digest = hashlib .blake2b (digest_size = 64 ) 316for chunk in data_chunks : 317digest .update (chunk ) 318message = digest .digest () 319elif algorithm == b"Ed" : 320message = b"" .join (data_chunks ) 321else : 322raise SignatureError ("the app signature uses an unknown algorithm" ) 323if not verify_raw (public ,message ,signature ): 324raise 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 326comment = next ((line [len ("trusted comment: " ):]for line in lines if line .startswith ("trusted comment: " )),None ) 327if comment is not None and len (body )> 1 : 328global_sig = _b64 (body [1 ].strip (),"the app signature's global part" ,64 ) 329if not verify_raw (public ,signature + comment .encode ("utf-8" ),global_sig ): 330raise SignatureError ("the app signature's comment was changed" )