"""Assemble an offline image root from a signed vpac client and its package repository.""" import argparse import csv import hashlib import os import shutil import stat import subprocess import sys import tarfile import tempfile from pathlib import Path, PurePosixPath NATIVE_RESERVED = tuple(PurePosixPath(path) for path in ( ".vinix-image-id", "etc/alpine-release", "etc/apk", "lib/apk", "sbin/apk", "usr/bin/apk", "usr/sbin/apk", "etc/vpac.d", "var/lib/vpac", "var/lib/vinix/repository", )) 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}") current = root for name in Path(relative).parts: current /= name if not current.is_dir(): current.mkdir() current.chmod(0o755) return directory def native_link_target(relative, link): target = PurePosixPath(link) depth = 0 if target.is_absolute() else len(relative.parent.parts) for name in target.parts[1:] if target.is_absolute() else target.parts: depth += -1 if name == ".." else 1 if depth < 0: raise ValueError(f"native link leaves the guest root: /{relative}") def install_native_layer(source, root, table): def walk(directory, destination): for origin in sorted(directory.iterdir()): target = destination / origin.name relative = target.relative_to(root) if any(relative.is_relative_to(path) for path in NATIVE_RESERVED): raise ValueError(f"native layer touches a reserved path: /{relative}") mode = origin.lstat().st_mode exists = os.path.lexists(target) if stat.S_ISDIR(mode): if exists and (target.is_symlink() or not target.is_dir()): raise ValueError(f"native directory shadows a staged file: /{relative}") if not exists: target.mkdir() walk(origin, target) if not exists: shutil.copystat(origin, target) continue if exists: raise ValueError(f"native file shadows a staged path: /{relative}") if stat.S_ISLNK(mode): link = os.readlink(origin) native_link_target(relative, link) target.symlink_to(link) table.writerow((relative, "link", "", link)) elif stat.S_ISREG(mode): shutil.copy2(origin, target) with target.open("rb") as stream: digest = hashlib.file_digest(stream, "sha256").hexdigest() table.writerow((relative, "file", f"{stat.S_IMODE(mode):04o}", digest)) else: raise ValueError(f"unsupported native file type: /{relative}") walk(source, root) 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) target.chmod(0o644) 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() native = args.native_layer.resolve(strict=True) if args.native_layer else None sources = (client, repo, native) if native else (client, repo) if any(output.is_relative_to(path) for path in sources): raise ValueError("put image output outside its input directories") if native and not native.is_dir(): raise ValueError("expected a staging directory for the native layer") 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: staging = Path(directory) root = staging / "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 database in [records, *(root / "db/local" for root in args.seed_client)]: descriptions = sorted(database.glob("*/desc")) if not descriptions: raise ValueError(f"client has no package records at {database}") for description in descriptions: 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") local = db / "local" shutil.copytree(records, local) local.chmod(0o755) sync = write_directory(root, "var/lib/vpac/sync") for name in ("vinix.db", "vinix.db.sig"): shutil.copy(package_dir / name, sync / name) if native: manifest = staging / "native-layer.tsv" with manifest.open("x", newline="") as records: table = csv.writer(records, delimiter="\t", lineterminator="\n") table.writerow(("path", "type", "mode", "sha256_or_link")) install_native_layer(native, root, table) if args.release: release_file = write_directory(root, "etc") / "vinix-release" with release_file.open("x") as output_file: output_file.write(args.release + "\n") release_file.chmod(0o644) if args.initramfs: if os.path.lexists(root / ".vinix-image-id"): raise ValueError("the ISO builder assigns the image identity") image = staging / "initramfs.tar" subprocess.run(["tar", "--format=ustar", "--sort=name", "--numeric-owner", "--owner=0", "--group=0", "-cf", image, "-C", root, "."], check=True) for artifact in ("native-layer.tsv", "initramfs.tar"): if (staging / artifact).exists(): (staging / artifact).rename(output / artifact) 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") parser.add_argument("--native-layer", type=Path, help="Vinix-built programs and assets to add to the image") parser.add_argument("--release", default="", help="release tag stored in /etc/vinix-release") parser.add_argument("--seed-client", type=Path, action="append", default=[], help="require the installed versions from another audited client in the seed") parser.add_argument("--initramfs", action="store_true", help="write a root-owned USTAR archive for the ISO builder") stage(parser.parse_args())