vinix-ports / tools / keyring.py
98 lines · 86 sloc · 4.71 KB
Raw
1"""Package a pinned public certificate or seed a new image's vpac verification keyring."""
2import argparse
3import hashlib
4import os
5import re
6import shutil
7import subprocess
8import tempfile
9from pathlib import Path
10
11
12def gpg(home, *arguments, data=None):
13 return subprocess.run(["gpg", "--homedir", home, "--no-options", "--batch", "--no-tty",
14 "--no-autostart", *arguments], check=True, input=data, stdout=subprocess.PIPE).stdout
15
16
17def fingerprint(value):
18 value = value.upper()
19 if not re.fullmatch(r"(?:[0-9A-F]{40}|[0-9A-F]{64})", value):
20 raise argparse.ArgumentTypeError("expected the full OpenPGP fingerprint")
21 return value
22
23
24def import_certificate(home, public_key, expected):
25 records = gpg(home, "--with-colons", "--import-options", "show-only", "--import", public_key)
26 types = [line.split(b":", 1)[0] for line in records.splitlines()]
27 if types.count(b"pub") != 1 or b"sec" in types or b"ssb" in types:
28 raise ValueError("expected one public OpenPGP certificate")
29 first = next((line.split(b":")[9].decode() for line in records.splitlines() if line.startswith(b"fpr:")), "")
30 if first != expected:
31 raise ValueError("certificate fingerprint differs from the trusted release fingerprint")
32 gpg(home, "--import", public_key)
33 if any(line.startswith((b"sec:", b"ssb:")) for line in gpg(home, "--with-colons", "--list-secret-keys").splitlines()):
34 raise ValueError("secret key found in verification keyring")
35
36
37def prepare(args):
38 if not re.fullmatch(r"[0-9]+(?:\.[0-9]+)*", args.version):
39 raise ValueError("expected a numeric keyring package version")
40 with tempfile.TemporaryDirectory() as directory:
41 home = Path(directory)
42 import_certificate(home, args.public_key, args.fingerprint)
43 public = gpg(home, "--export", args.fingerprint)
44 if not public:
45 raise ValueError("could not export public certificate")
46 pin = (args.fingerprint + "\n").encode()
47 template = Path(__file__).resolve().parent.parent / "vinix-keyring/PKGBUILD.vile.in"
48 recipe = (template.read_text().replace("@VERSION@", args.version)
49 .replace("@PUBLIC_SHA256@", hashlib.sha256(public).hexdigest())
50 .replace("@FINGERPRINT_SHA256@", hashlib.sha256(pin).hexdigest()))
51 args.output.mkdir()
52 (args.output / "vinix.gpg").write_bytes(public)
53 (args.output / "vinix.fingerprint").write_bytes(pin)
54 (args.output / "PKGBUILD.vile").write_text(recipe)
55
56
57def seed(args):
58 # For freshly assembled roots. Upgrading live trust state requires a key rotation policy.
59 root = args.root.resolve(strict=True)
60 if root == Path("/") or not root.is_dir():
61 raise ValueError("expected a staged image directory")
62 certificates = root / "usr/share/vpac/keyrings"
63 parent = root / "etc/vpac.d"
64 for path in (parent, certificates / "vinix.gpg", certificates / "vinix.fingerprint"):
65 if path.resolve() != path:
66 raise ValueError(f"unexpected symlink in image keyring path: {path}")
67 if (certificates / "vinix.fingerprint").read_text().strip() != args.fingerprint:
68 raise ValueError("installed keyring fingerprint differs from the trusted release fingerprint")
69 parent.mkdir(parents=True, exist_ok=True)
70 dest = parent / "gnupg"
71 if os.path.lexists(dest):
72 raise ValueError(f"verification keyring already exists: {dest}")
73 # Long image paths can exceed the Unix socket limit used by GnuPG.
74 with tempfile.TemporaryDirectory() as directory, tempfile.TemporaryDirectory(dir=parent) as staging:
75 home = Path(directory)
76 import_certificate(home, certificates / "vinix.gpg", args.fingerprint)
77 gpg(home, "--import-ownertrust", data=(args.fingerprint + ":6:\n").encode())
78 gpg(home, "--check-trustdb")
79 keybox = "pubring.kbx" if (home / "pubring.kbx").is_file() else "pubring.gpg"
80 for name in (keybox, "trustdb.gpg"):
81 shutil.copyfile(home / name, Path(staging) / name)
82 (Path(staging) / name).chmod(0o600)
83 Path(staging).rename(dest)
84
85
86if __name__ == "__main__":
87 parser = argparse.ArgumentParser(description=__doc__)
88 sub = parser.add_subparsers(dest="command", required=True)
89 make = sub.add_parser("prepare", help="materialize a reproducible Vile port outside Git")
90 make.add_argument("public_key", type=Path)
91 make.add_argument("fingerprint", type=fingerprint)
92 make.add_argument("version")
93 make.add_argument("output", type=Path)
94 image = sub.add_parser("seed", help="initialize trust in a new, signed-package-installed root")
95 image.add_argument("root", type=Path)
96 image.add_argument("fingerprint", type=fingerprint)
97 args = parser.parse_args()
98 (prepare if args.command == "prepare" else seed)(args)
99