vinix-ports / tools / stage-image.py
123 lines · 111 sloc · 5.27 KB · fa26ff765d4c92538bf0a0a58e8cb52f2074191c
Raw
1"""Assemble an offline image root from a signed vpac client and its package repository."""
2import argparse
3import hashlib
4import shutil
5import subprocess
6import sys
7import tarfile
8import tempfile
9from pathlib import Path
10
11
12def package_fields(data):
13 fields = {}
14 for block in data.strip().split("\n\n"):
15 name, _, value = block.partition("\n")
16 if name.startswith("%") and name.endswith("%"):
17 fields[name.strip("%")] = value
18 return fields
19
20
21def write_directory(root, relative):
22 directory = root / relative
23 if directory.resolve() != directory:
24 raise ValueError(f"unexpected guest symlink at {relative}")
25 current = root
26 for name in Path(relative).parts:
27 current /= name
28 if not current.is_dir():
29 current.mkdir()
30 current.chmod(0o755)
31 return directory
32
33
34def snapshot(repo, dest, ring, arch, gpg_home):
35 def verify(path):
36 subprocess.run(["gpgv", "--homedir", gpg_home, "--keyring", ring, str(path) + ".sig", path],
37 check=True, stdout=subprocess.DEVNULL)
38
39 def copy(name):
40 if Path(name).name != name or not name or name in (".", ".."):
41 raise ValueError(f"invalid repository filename {name!r}")
42 source = repo / name
43 if source.resolve().parent != repo or not source.is_file():
44 raise ValueError(f"missing or external repository file: {name}")
45 target = dest / name
46 if target.exists():
47 raise ValueError(f"duplicate repository filename: {name}")
48 shutil.copyfile(source, target)
49 target.chmod(0o644)
50 return target
51
52 for index in ("vinix.db", "vinix.files"):
53 file = copy(index)
54 copy(index + ".sig")
55 verify(file)
56 indexed = {}
57 with tarfile.open(dest / "vinix.db", "r:gz") as database:
58 for entry in database:
59 if not entry.isfile() or Path(entry.name).name != "desc":
60 continue
61 info = package_fields(database.extractfile(entry).read().decode())
62 name, version, package_arch = (info[field] for field in ("NAME", "VERSION", "ARCH"))
63 filename = info["FILENAME"]
64 if (name in indexed or package_arch not in (arch, "any") or
65 filename != f"{name}-{version}-{package_arch}.pkg.tar.zst"):
66 raise ValueError(f"invalid database record for {name}")
67 archive = copy(filename)
68 copy(filename + ".sig")
69 with archive.open("rb") as stream:
70 if hashlib.file_digest(stream, "sha256").hexdigest() != info["SHA256SUM"]:
71 raise ValueError(f"archive differs from signed index: {filename}")
72 verify(archive)
73 indexed[name] = version
74 if not indexed:
75 raise ValueError("empty signed package index")
76 return indexed
77
78
79def stage(args):
80 client, repo, output = args.client.resolve(), args.repo.resolve(), args.output.resolve()
81 if any(output.is_relative_to(path) for path in (client, repo)):
82 raise ValueError("put image output outside the client and repository")
83 output.mkdir()
84 audit = subprocess.check_output([args.auditor, args.arch, client], text=True)
85 (output / "audited-root.log").write_text(audit)
86 with tempfile.TemporaryDirectory(dir=output) as directory:
87 root = Path(directory) / "image"
88 subprocess.run(["cp", "-a", "--reflink=auto", client / "root", root], check=True)
89 # This compares the installed certificate with the independently supplied pin.
90 seed = Path(__file__).resolve().with_name("keyring.py")
91 subprocess.run([sys.executable, seed, "seed", root, args.fingerprint], check=True)
92 package_dir = write_directory(root, "var/lib/vinix/repository/" + args.arch)
93 if any(package_dir.iterdir()):
94 raise ValueError("seed repository directory is already populated")
95 with tempfile.TemporaryDirectory() as gpg_home:
96 indexed = snapshot(repo / args.arch, package_dir, root / "usr/share/vpac/keyrings/vinix.gpg",
97 args.arch, gpg_home)
98 records = client / "db/local"
99 for description in records.glob("*/desc"):
100 info = package_fields(description.read_text())
101 if indexed.get(info["NAME"]) != info["VERSION"]:
102 raise ValueError(f"installed package missing from seed at its exact version: {info['NAME']}")
103 db = write_directory(root, "var/lib/vpac")
104 if any(db.iterdir()):
105 raise ValueError("package database directory is already populated")
106 local = db / "local"
107 shutil.copytree(records, local)
108 local.chmod(0o755)
109 sync = write_directory(root, "var/lib/vpac/sync")
110 for name in ("vinix.db", "vinix.db.sig"):
111 shutil.copy(package_dir / name, sync / name)
112 root.rename(output / "root")
113 print(audit, end="")
114 print(f"staged {len(indexed)} signed seed packages and the installed database")
115
116
117if __name__ == "__main__":
118 parser = argparse.ArgumentParser(description=__doc__)
119 parser.add_argument("arch", choices=("x86_64", "aarch64"))
120 for arg in ("client", "repo", "output", "auditor"):
121 parser.add_argument(arg, type=Path)
122 parser.add_argument("fingerprint", help="trusted distributor fingerprint from outside the feed")
123 stage(parser.parse_args())
124