"""Assemble an offline image root from a signed vpac client and its package repository.""" import argparse import hashlib import shutil import subprocess import sys import tarfile import tempfile from pathlib import Path def package_fields(data): fields = {} for block in data.strip().split("\n\n"): name, _, value = block.partition("\n") if name.startswith("%") and name.endswith("%"): fields[name.strip("%")] = value return fields def write_directory(root, relative): directory = root / relative if directory.resolve() != directory: raise ValueError(f"unexpected guest symlink at {relative}") directory.mkdir(parents=True, exist_ok=True) return directory def snapshot(repo, dest, ring, arch, gpg_home): def verify(path): subprocess.run(["gpgv", "--homedir", gpg_home, "--keyring", ring, str(path) + ".sig", path], check=True, stdout=subprocess.DEVNULL) def copy(name): if Path(name).name != name or not name or name in (".", ".."): raise ValueError(f"invalid repository filename {name!r}") source = repo / name if source.resolve().parent != repo or not source.is_file(): raise ValueError(f"missing or external repository file: {name}") target = dest / name if target.exists(): raise ValueError(f"duplicate repository filename: {name}") shutil.copyfile(source, target) return target for index in ("vinix.db", "vinix.files"): file = copy(index) copy(index + ".sig") verify(file) indexed = {} with tarfile.open(dest / "vinix.db", "r:gz") as database: for entry in database: if not entry.isfile() or Path(entry.name).name != "desc": continue info = package_fields(database.extractfile(entry).read().decode()) name, version, package_arch = (info[field] for field in ("NAME", "VERSION", "ARCH")) filename = info["FILENAME"] if (name in indexed or package_arch not in (arch, "any") or filename != f"{name}-{version}-{package_arch}.pkg.tar.zst"): raise ValueError(f"invalid database record for {name}") archive = copy(filename) copy(filename + ".sig") with archive.open("rb") as stream: if hashlib.file_digest(stream, "sha256").hexdigest() != info["SHA256SUM"]: raise ValueError(f"archive differs from signed index: {filename}") verify(archive) indexed[name] = version if not indexed: raise ValueError("empty signed package index") return indexed def stage(args): client, repo, output = args.client.resolve(), args.repo.resolve(), args.output.resolve() if any(output.is_relative_to(path) for path in (client, repo)): raise ValueError("put image output outside the client and repository") output.mkdir() audit = subprocess.check_output([args.auditor, args.arch, client], text=True) (output / "audited-root.log").write_text(audit) with tempfile.TemporaryDirectory(dir=output) as directory: root = Path(directory) / "image" subprocess.run(["cp", "-a", "--reflink=auto", client / "root", root], check=True) # This compares the installed certificate with the independently supplied pin. seed = Path(__file__).resolve().with_name("keyring.py") subprocess.run([sys.executable, seed, "seed", root, args.fingerprint], check=True) package_dir = write_directory(root, "var/lib/vinix/repository/" + args.arch) if any(package_dir.iterdir()): raise ValueError("seed repository directory is already populated") with tempfile.TemporaryDirectory() as gpg_home: indexed = snapshot(repo / args.arch, package_dir, root / "usr/share/vpac/keyrings/vinix.gpg", args.arch, gpg_home) records = client / "db/local" for description in records.glob("*/desc"): info = package_fields(description.read_text()) if indexed.get(info["NAME"]) != info["VERSION"]: raise ValueError(f"installed package missing from seed at its exact version: {info['NAME']}") db = write_directory(root, "var/lib/vpac") if any(db.iterdir()): raise ValueError("package database directory is already populated") shutil.copytree(records, db / "local") sync = write_directory(root, "var/lib/vpac/sync") for name in ("vinix.db", "vinix.db.sig"): shutil.copyfile(package_dir / name, sync / name) root.rename(output / "root") print(audit, end="") print(f"staged {len(indexed)} signed seed packages and the installed database") if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("arch", choices=("x86_64", "aarch64")) for arg in ("client", "repo", "output", "auditor"): parser.add_argument(arg, type=Path) parser.add_argument("fingerprint", help="trusted distributor fingerprint from outside the feed") stage(parser.parse_args())