#!/usr/bin/env python3 """sign-manifest: sign manifest.json with the skills release key (ed25519, RFC 8032). Run by infra at skills-repo release time, never in a web pod; the key is in infra's sops (secrets/secrets.yaml .skills."signing-key", a nix-style ':'): SKILLS_SIGNING_KEY="$(sops -d --extract '["skills"]["signing-key"]' secrets/secrets.yaml)" \\ tools/sign-manifest # writes manifest.json.sig tools/sign-manifest --verify [PUB] # checks manifest.json.sig against PUB (default: the published key) tools/sign-manifest --selftest manifest.json.sig is one line, ':', over the exact bytes of manifest.json (the SEP-2640 digests of every file; tools/manifest.py writes it). A client checks it with the public key published at https://solnix.io/security (and in this file): solnix-skills-1:aFFBL7b8vVvGAi0TpHh/Yj4WiHS3Ts/eGKtKRynae4A= The key is separate from the cache key (cache.solnix.io-1) and the advisories key (solnix-advisories-1). Stdlib only: the arithmetic is the cache signer's (slow, a few signatures per release). """ import base64, hashlib, os, re, sys PUBLISHED = 'solnix-skills-1:aFFBL7b8vVvGAi0TpHh/Yj4WiHS3Ts/eGKtKRynae4A=' REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MANIFEST = os.path.join(REPO, 'manifest.json') SIG = MANIFEST + '.sig' # ---- RFC 8032 Ed25519 (affine) ---- p = 2**255 - 19 L = 2**252 + 27742317777372353535851937790883648493 def _inv(x): return pow(x, p - 2, p) d = (-121665 * _inv(121666)) % p I = pow(2, (p - 1) // 4, p) def _xrecover(y): xx = (y * y - 1) * _inv(d * y * y + 1) x = pow(xx, (p + 3) // 8, p) if (x * x - xx) % p != 0: x = (x * I) % p if x % 2 != 0: x = p - x return x By = 4 * _inv(5) % p B = (_xrecover(By) % p, By % p) def _add(P, Q): x1, y1 = P; x2, y2 = Q return ((x1 * y2 + x2 * y1) * _inv(1 + d * x1 * x2 * y1 * y2) % p, (y1 * y2 + x1 * x2) * _inv(1 - d * x1 * x2 * y1 * y2) % p) def _mul(P, e): Q = (0, 1) for bit in bin(e)[2:]: Q = _add(Q, Q) if bit == '1': Q = _add(Q, P) return Q def _enc(P): x, y = P b = bytearray(y.to_bytes(32, 'little')); b[31] |= (x & 1) << 7 return bytes(b) def _dec(s): y = int.from_bytes(s, 'little') & ((1 << 255) - 1) if y >= p: raise ValueError('bad point') x = _xrecover(y) if (x & 1) != (s[31] >> 7): x = p - x P = (x, y) if (-x * x + y * y - 1 - d * x * x * y * y) % p != 0: raise ValueError('not on curve') return P def _H(m): return hashlib.sha512(m).digest() def _a(seed): h = _H(seed) return 2**254 + sum(2**i * ((h[i // 8] >> (i % 8)) & 1) for i in range(3, 254)), h[32:] def public(seed): return _enc(_mul(B, _a(seed)[0])) def sign(seed, msg): a, prefix = _a(seed) A = _enc(_mul(B, a)) r = int.from_bytes(_H(prefix + msg), 'little') % L R = _enc(_mul(B, r)) k = int.from_bytes(_H(R + A + msg), 'little') % L return R + ((r + k * a) % L).to_bytes(32, 'little') def verify(pub, msg, sig): if len(sig) != 64 or len(pub) != 32: return False try: A, R = _dec(pub), _dec(sig[:32]) except ValueError: return False S = int.from_bytes(sig[32:], 'little') if S >= L: return False k = int.from_bytes(_H(sig[:32] + pub + msg), 'little') % L return _mul(B, S) == _add(R, _mul(A, k)) KEYNAME = re.compile(r'^[a-z0-9][a-z0-9.-]{0,63}$') def parse_key(line, size): name, b64 = line.strip().split(':', 1) raw = base64.b64decode(b64, validate=True) if not KEYNAME.match(name) or len(raw) != size: raise SystemExit(f'sign-manifest: a key must be :') return name, raw def check_sig(publine, body, sigline): pname, pub = parse_key(publine, 32) sname, sig = parse_key(sigline, 64) return sname == pname and verify(pub, body, sig) def main(): args = sys.argv[1:] if args[:1] == ['--selftest']: return selftest() body = open(MANIFEST, 'rb').read() if args[:1] == ['--verify']: pub = args[1] if len(args) > 1 else PUBLISHED ok = check_sig(pub, body, open(SIG).read()) print(f'manifest.json.sig: {"verifies" if ok else "DOES NOT VERIFY"} with {pub.split(":")[0]}') sys.exit(0 if ok else 1) key = os.environ.get('SKILLS_SIGNING_KEY') if not key: raise SystemExit('sign-manifest: SKILLS_SIGNING_KEY is not set (infra sops .skills."signing-key")') name, raw = parse_key(key, 64) seed, pub = raw[:32], raw[32:] if public(seed) != pub: raise SystemExit('sign-manifest: the seed does not derive its embedded public key') if f'{name}:{base64.b64encode(pub).decode()}' != PUBLISHED: raise SystemExit('sign-manifest: this key is not the published one; update PUBLISHED (and the site) first') sig = sign(seed, body) if not verify(pub, body, sig): raise SystemExit('sign-manifest: the signature does not verify') line = f'{name}:{base64.b64encode(sig).decode()}\n' open(SIG, 'w').write(line) print(f'wrote manifest.json.sig ({name}, manifest sha256 {hashlib.sha256(body).hexdigest()[:16]})') def selftest(): # RFC 8032 section 7.1, tests 1 and 2 for sk, pk, msg, sg in [ ('9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60', 'd75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a', '', 'e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b'), ('4ccd089b28ff96da9db6c346ec114e0f5b8a319f35aba624da8cf6ed4fb8a6fb', '3d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c', '72', '92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c00')]: seed, m = bytes.fromhex(sk), bytes.fromhex(msg) assert public(seed).hex() == pk and sign(seed, m).hex() == sg and verify(bytes.fromhex(pk), m, bytes.fromhex(sg)) seed = hashlib.sha256(b'selftest').digest(); pub = public(seed) body = b'{"version": 1}\n' publine = 't-1:' + base64.b64encode(pub).decode() sigline = 't-1:' + base64.b64encode(sign(seed, body)).decode() assert check_sig(publine, body, sigline) assert not check_sig(publine, body + b' ', sigline), 'a changed manifest verified' assert not check_sig('t-2:' + publine[4:], body, sigline), 'a signature verified under another key name' print('sign-manifest selftest: PASS') if __name__ == '__main__': main()