vinix-ports / tools / stage-image.py
211 lines · 192 sloc · 9.7 KB · 7f608e7c598a36c9e4d491b034047aee5046269e
Raw
1"""Assemble an offline image root from a signed vpac client and its package repository."""
2import argparse
3import csv
4import hashlib
5import os
6import shutil
7import stat
8import subprocess
9import sys
10import tarfile
11import tempfile
12from pathlib import Path, PurePosixPath
13
14
15NATIVE_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
21def 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
30def 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
43def 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
52def 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
88def 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
133def 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 database in [records, *(root / "db/local" for root in args.seed_client)]:
159 descriptions = sorted(database.glob("*/desc"))
160 if not descriptions:
161 raise ValueError(f"client has no package records at {database}")
162 for description in descriptions:
163 info = package_fields(description.read_text())
164 if indexed.get(info["NAME"]) != info["VERSION"]:
165 raise ValueError(f"installed package missing from seed at its exact version: {info['NAME']}")
166 db = write_directory(root, "var/lib/vpac")
167 if any(db.iterdir()):
168 raise ValueError("package database directory is already populated")
169 local = db / "local"
170 shutil.copytree(records, local)
171 local.chmod(0o755)
172 sync = write_directory(root, "var/lib/vpac/sync")
173 for name in ("vinix.db", "vinix.db.sig"):
174 shutil.copy(package_dir / name, sync / name)
175 if native:
176 manifest = staging / "native-layer.tsv"
177 with manifest.open("x", newline="") as records:
178 table = csv.writer(records, delimiter="\t", lineterminator="\n")
179 table.writerow(("path", "type", "mode", "sha256_or_link"))
180 install_native_layer(native, root, table)
181 if args.release:
182 release_file = write_directory(root, "etc") / "vinix-release"
183 with release_file.open("x") as output_file:
184 output_file.write(args.release + "\n")
185 release_file.chmod(0o644)
186 if args.initramfs:
187 if os.path.lexists(root / ".vinix-image-id"):
188 raise ValueError("the ISO builder assigns the image identity")
189 image = staging / "initramfs.tar"
190 subprocess.run(["tar", "--format=ustar", "--sort=name", "--numeric-owner",
191 "--owner=0", "--group=0", "-cf", image, "-C", root, "."], check=True)
192 for artifact in ("native-layer.tsv", "initramfs.tar"):
193 if (staging / artifact).exists():
194 (staging / artifact).rename(output / artifact)
195 root.rename(output / "root")
196 print(audit, end="")
197 print(f"staged {len(indexed)} signed seed packages and the installed database")
198
199
200if __name__ == "__main__":
201 parser = argparse.ArgumentParser(description=__doc__)
202 parser.add_argument("arch", choices=("x86_64", "aarch64"))
203 for arg in ("client", "repo", "output", "auditor"):
204 parser.add_argument(arg, type=Path)
205 parser.add_argument("fingerprint", help="trusted distributor fingerprint from outside the feed")
206 parser.add_argument("--native-layer", type=Path, help="Vinix-built programs and assets to add to the image")
207 parser.add_argument("--release", default="", help="release tag stored in /etc/vinix-release")
208 parser.add_argument("--seed-client", type=Path, action="append", default=[],
209 help="require the installed versions from another audited client in the seed")
210 parser.add_argument("--initramfs", action="store_true", help="write a root-owned USTAR archive for the ISO builder")
211 stage(parser.parse_args())
212