"""Package a pinned public certificate or seed a new image's vpac verification keyring.""" import argparse import hashlib import os import re import shutil import subprocess import tempfile from pathlib import Path def gpg(home, *arguments, data=None): return subprocess.run(["gpg", "--homedir", home, "--no-options", "--batch", "--no-tty", "--no-autostart", *arguments], check=True, input=data, stdout=subprocess.PIPE).stdout def fingerprint(value): value = value.upper() if not re.fullmatch(r"(?:[0-9A-F]{40}|[0-9A-F]{64})", value): raise argparse.ArgumentTypeError("expected the full OpenPGP fingerprint") return value def import_certificate(home, public_key, expected): records = gpg(home, "--with-colons", "--import-options", "show-only", "--import", public_key) types = [line.split(b":", 1)[0] for line in records.splitlines()] if types.count(b"pub") != 1 or b"sec" in types or b"ssb" in types: raise ValueError("expected one public OpenPGP certificate") first = next((line.split(b":")[9].decode() for line in records.splitlines() if line.startswith(b"fpr:")), "") if first != expected: raise ValueError("certificate fingerprint differs from the trusted release fingerprint") gpg(home, "--import", public_key) if any(line.startswith((b"sec:", b"ssb:")) for line in gpg(home, "--with-colons", "--list-secret-keys").splitlines()): raise ValueError("secret key found in verification keyring") def prepare(args): if not re.fullmatch(r"[0-9]+(?:\.[0-9]+)*", args.version): raise ValueError("expected a numeric keyring package version") with tempfile.TemporaryDirectory() as directory: home = Path(directory) import_certificate(home, args.public_key, args.fingerprint) public = gpg(home, "--export", args.fingerprint) if not public: raise ValueError("could not export public certificate") pin = (args.fingerprint + "\n").encode() template = Path(__file__).resolve().parents[1] / "ports/vinix-keyring/PKGBUILD.vile.in" recipe = (template.read_text().replace("@VERSION@", args.version) .replace("@PUBLIC_SHA256@", hashlib.sha256(public).hexdigest()) .replace("@FINGERPRINT_SHA256@", hashlib.sha256(pin).hexdigest())) args.output.mkdir() (args.output / "vinix.gpg").write_bytes(public) (args.output / "vinix.fingerprint").write_bytes(pin) (args.output / "PKGBUILD.vile").write_text(recipe) def seed(args): # For freshly assembled roots. Upgrading live trust state requires a key rotation policy. root = args.root.resolve(strict=True) if root == Path("/") or not root.is_dir(): raise ValueError("expected a staged image directory") certificates = root / "usr/share/vpac/keyrings" parent = root / "etc/vpac.d" for path in (parent, certificates / "vinix.gpg", certificates / "vinix.fingerprint"): if path.resolve() != path: raise ValueError(f"unexpected symlink in image keyring path: {path}") if (certificates / "vinix.fingerprint").read_text().strip() != args.fingerprint: raise ValueError("installed keyring fingerprint differs from the trusted release fingerprint") parent.mkdir(parents=True, exist_ok=True) dest = parent / "gnupg" if os.path.lexists(dest) and (dest.is_symlink() or not dest.is_dir() or any(dest.iterdir())): raise ValueError(f"verification keyring already exists: {dest}") # Long image paths can exceed the Unix socket limit used by GnuPG. with tempfile.TemporaryDirectory() as directory, tempfile.TemporaryDirectory(dir=parent) as staging: home = Path(directory) import_certificate(home, certificates / "vinix.gpg", args.fingerprint) gpg(home, "--import-ownertrust", data=(args.fingerprint + ":6:\n").encode()) gpg(home, "--check-trustdb") keybox = "pubring.kbx" if (home / "pubring.kbx").is_file() else "pubring.gpg" for name in (keybox, "trustdb.gpg"): shutil.copyfile(home / name, Path(staging) / name) (Path(staging) / name).chmod(0o600) Path(staging).rename(dest) if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) sub = parser.add_subparsers(dest="command", required=True) make = sub.add_parser("prepare", help="materialize a reproducible Vile port outside Git") make.add_argument("public_key", type=Path) make.add_argument("fingerprint", type=fingerprint) make.add_argument("version") make.add_argument("output", type=Path) image = sub.add_parser("seed", help="initialize trust in a new, signed-package-installed root") image.add_argument("root", type=Path) image.add_argument("fingerprint", type=fingerprint) args = parser.parse_args() (prepare if args.command == "prepare" else seed)(args)