| 1 | """Assemble an offline image root from a signed vpac client and its package repository.""" |
| 2 | import argparse |
| 3 | import csv |
| 4 | import hashlib |
| 5 | import os |
| 6 | import shutil |
| 7 | import stat |
| 8 | import subprocess |
| 9 | import sys |
| 10 | import tarfile |
| 11 | import tempfile |
| 12 | from pathlib import Path, PurePosixPath |
| 13 | |
| 14 | |
| 15 | NATIVE_RESERVED = tuple(PurePosixPath(path) for path in ( |
| 16 | ".vinix-image-id", "etc/alpine-release", "etc/apk", "lib/apk", "sbin/apk", |
| 17 | "usr/bin/apk", "usr/sbin/apk", "etc/vpac.d", "var/lib/vpac", "var/lib/vinix/repository", |
| 18 | )) |
| 19 | |
| 20 | |
| 21 | def package_fields(data): |
| 22 | fields = {} |
| 23 | for block in data.strip().split("\n\n"): |
| 24 | name, _, value = block.partition("\n") |
| 25 | if name.startswith("%") and name.endswith("%"): |
| 26 | fields[name.strip("%")] = value |
| 27 | return fields |
| 28 | |
| 29 | |
| 30 | def write_directory(root, relative): |
| 31 | directory = root / relative |
| 32 | if directory.resolve() != directory: |
| 33 | raise ValueError(f"unexpected guest symlink at {relative}") |
| 34 | current = root |
| 35 | for name in Path(relative).parts: |
| 36 | current /= name |
| 37 | if not current.is_dir(): |
| 38 | current.mkdir() |
| 39 | current.chmod(0o755) |
| 40 | return directory |
| 41 | |
| 42 | |
| 43 | def native_link_target(relative, link): |
| 44 | target = PurePosixPath(link) |
| 45 | depth = 0 if target.is_absolute() else len(relative.parent.parts) |
| 46 | for name in target.parts[1:] if target.is_absolute() else target.parts: |
| 47 | depth += -1 if name == ".." else 1 |
| 48 | if depth < 0: |
| 49 | raise ValueError(f"native link leaves the guest root: /{relative}") |
| 50 | |
| 51 | |
| 52 | def install_native_layer(source, root, table): |
| 53 | def walk(directory, destination): |
| 54 | for origin in sorted(directory.iterdir()): |
| 55 | target = destination / origin.name |
| 56 | relative = target.relative_to(root) |
| 57 | if any(relative.is_relative_to(path) for path in NATIVE_RESERVED): |
| 58 | raise ValueError(f"native layer touches a reserved path: /{relative}") |
| 59 | mode = origin.lstat().st_mode |
| 60 | exists = os.path.lexists(target) |
| 61 | if stat.S_ISDIR(mode): |
| 62 | if exists and (target.is_symlink() or not target.is_dir()): |
| 63 | raise ValueError(f"native directory shadows a staged file: /{relative}") |
| 64 | if not exists: |
| 65 | target.mkdir() |
| 66 | walk(origin, target) |
| 67 | if not exists: |
| 68 | shutil.copystat(origin, target) |
| 69 | continue |
| 70 | if exists: |
| 71 | raise ValueError(f"native file shadows a staged path: /{relative}") |
| 72 | if stat.S_ISLNK(mode): |
| 73 | link = os.readlink(origin) |
| 74 | native_link_target(relative, link) |
| 75 | target.symlink_to(link) |
| 76 | table.writerow((relative, "link", "", link)) |
| 77 | elif stat.S_ISREG(mode): |
| 78 | shutil.copy2(origin, target) |
| 79 | with target.open("rb") as stream: |
| 80 | digest = hashlib.file_digest(stream, "sha256").hexdigest() |
| 81 | table.writerow((relative, "file", f"{stat.S_IMODE(mode):04o}", digest)) |
| 82 | else: |
| 83 | raise ValueError(f"unsupported native file type: /{relative}") |
| 84 | |
| 85 | walk(source, root) |
| 86 | |
| 87 | |
| 88 | def snapshot(repo, dest, ring, arch, gpg_home): |
| 89 | def verify(path): |
| 90 | subprocess.run(["gpgv", "--homedir", gpg_home, "--keyring", ring, str(path) + ".sig", path], |
| 91 | check=True, stdout=subprocess.DEVNULL) |
| 92 | |
| 93 | def copy(name): |
| 94 | if Path(name).name != name or not name or name in (".", ".."): |
| 95 | raise ValueError(f"invalid repository filename {name!r}") |
| 96 | source = repo / name |
| 97 | if source.resolve().parent != repo or not source.is_file(): |
| 98 | raise ValueError(f"missing or external repository file: {name}") |
| 99 | target = dest / name |
| 100 | if target.exists(): |
| 101 | raise ValueError(f"duplicate repository filename: {name}") |
| 102 | shutil.copyfile(source, target) |
| 103 | target.chmod(0o644) |
| 104 | return target |
| 105 | |
| 106 | for index in ("vinix.db", "vinix.files"): |
| 107 | file = copy(index) |
| 108 | copy(index + ".sig") |
| 109 | verify(file) |
| 110 | indexed = {} |
| 111 | with tarfile.open(dest / "vinix.db", "r:gz") as database: |
| 112 | for entry in database: |
| 113 | if not entry.isfile() or Path(entry.name).name != "desc": |
| 114 | continue |
| 115 | info = package_fields(database.extractfile(entry).read().decode()) |
| 116 | name, version, package_arch = (info[field] for field in ("NAME", "VERSION", "ARCH")) |
| 117 | filename = info["FILENAME"] |
| 118 | if (name in indexed or package_arch not in (arch, "any") or |
| 119 | filename != f"{name}-{version}-{package_arch}.pkg.tar.zst"): |
| 120 | raise ValueError(f"invalid database record for {name}") |
| 121 | archive = copy(filename) |
| 122 | copy(filename + ".sig") |
| 123 | with archive.open("rb") as stream: |
| 124 | if hashlib.file_digest(stream, "sha256").hexdigest() != info["SHA256SUM"]: |
| 125 | raise ValueError(f"archive differs from signed index: {filename}") |
| 126 | verify(archive) |
| 127 | indexed[name] = version |
| 128 | if not indexed: |
| 129 | raise ValueError("empty signed package index") |
| 130 | return indexed |
| 131 | |
| 132 | |
| 133 | def stage(args): |
| 134 | client, repo, output = args.client.resolve(), args.repo.resolve(), args.output.resolve() |
| 135 | native = args.native_layer.resolve(strict=True) if args.native_layer else None |
| 136 | sources = (client, repo, native) if native else (client, repo) |
| 137 | if any(output.is_relative_to(path) for path in sources): |
| 138 | raise ValueError("put image output outside its input directories") |
| 139 | if native and not native.is_dir(): |
| 140 | raise ValueError("expected a staging directory for the native layer") |
| 141 | output.mkdir() |
| 142 | audit = subprocess.check_output([args.auditor, args.arch, client], text=True) |
| 143 | (output / "audited-root.log").write_text(audit) |
| 144 | with tempfile.TemporaryDirectory(dir=output) as directory: |
| 145 | staging = Path(directory) |
| 146 | root = staging / "image" |
| 147 | subprocess.run(["cp", "-a", "--reflink=auto", client / "root", root], check=True) |
| 148 | # This compares the installed certificate with the independently supplied pin. |
| 149 | seed = Path(__file__).resolve().with_name("keyring.py") |
| 150 | subprocess.run([sys.executable, seed, "seed", root, args.fingerprint], check=True) |
| 151 | package_dir = write_directory(root, "var/lib/vinix/repository/" + args.arch) |
| 152 | if any(package_dir.iterdir()): |
| 153 | raise ValueError("seed repository directory is already populated") |
| 154 | with tempfile.TemporaryDirectory() as gpg_home: |
| 155 | indexed = snapshot(repo / args.arch, package_dir, root / "usr/share/vpac/keyrings/vinix.gpg", |
| 156 | args.arch, gpg_home) |
| 157 | records = client / "db/local" |
| 158 | for description in records.glob("*/desc"): |
| 159 | info = package_fields(description.read_text()) |
| 160 | if indexed.get(info["NAME"]) != info["VERSION"]: |
| 161 | raise ValueError(f"installed package missing from seed at its exact version: {info['NAME']}") |
| 162 | db = write_directory(root, "var/lib/vpac") |
| 163 | if any(db.iterdir()): |
| 164 | raise ValueError("package database directory is already populated") |
| 165 | local = db / "local" |
| 166 | shutil.copytree(records, local) |
| 167 | local.chmod(0o755) |
| 168 | sync = write_directory(root, "var/lib/vpac/sync") |
| 169 | for name in ("vinix.db", "vinix.db.sig"): |
| 170 | shutil.copy(package_dir / name, sync / name) |
| 171 | if native: |
| 172 | manifest = staging / "native-layer.tsv" |
| 173 | with manifest.open("x", newline="") as records: |
| 174 | table = csv.writer(records, delimiter="\t", lineterminator="\n") |
| 175 | table.writerow(("path", "type", "mode", "sha256_or_link")) |
| 176 | install_native_layer(native, root, table) |
| 177 | if args.initramfs: |
| 178 | if os.path.lexists(root / ".vinix-image-id"): |
| 179 | raise ValueError("the ISO builder assigns the image identity") |
| 180 | image = staging / "initramfs.tar" |
| 181 | subprocess.run(["tar", "--format=ustar", "--sort=name", "--numeric-owner", |
| 182 | "--owner=0", "--group=0", "-cf", image, "-C", root, "."], check=True) |
| 183 | for artifact in ("native-layer.tsv", "initramfs.tar"): |
| 184 | if (staging / artifact).exists(): |
| 185 | (staging / artifact).rename(output / artifact) |
| 186 | root.rename(output / "root") |
| 187 | print(audit, end="") |
| 188 | print(f"staged {len(indexed)} signed seed packages and the installed database") |
| 189 | |
| 190 | |
| 191 | if __name__ == "__main__": |
| 192 | parser = argparse.ArgumentParser(description=__doc__) |
| 193 | parser.add_argument("arch", choices=("x86_64", "aarch64")) |
| 194 | for arg in ("client", "repo", "output", "auditor"): |
| 195 | parser.add_argument(arg, type=Path) |
| 196 | parser.add_argument("fingerprint", help="trusted distributor fingerprint from outside the feed") |
| 197 | parser.add_argument("--native-layer", type=Path, help="Vinix-built programs and assets to add to the image") |
| 198 | parser.add_argument("--initramfs", action="store_true", help="write a root-owned USTAR archive for the ISO builder") |
| 199 | stage(parser.parse_args()) |
| 200 | |