vinix-ports / tools / stage-image.py
226 lines · 206 sloc · 10.46 KB · 6dc096b518cce26d030bba4732f54ac980a54cc9
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, seed_roots=()):
53 hard_links = {}
54
55 def walk(directory, destination):
56 for origin in sorted(directory.iterdir()):
57 target = destination / origin.name
58 relative = target.relative_to(root)
59 if any(relative.is_relative_to(path) for path in NATIVE_RESERVED):
60 raise ValueError(f"native layer touches a reserved path: /{relative}")
61 info = origin.lstat()
62 mode = info.st_mode
63 directory_entry = stat.S_ISDIR(mode)
64 for seed_root in seed_roots:
65 seeded = seed_root / relative
66 if os.path.lexists(seeded) and (not directory_entry or seeded.is_symlink() or not seeded.is_dir()):
67 raise ValueError(f"native layer conflicts with the seed client's /{relative}")
68 exists = os.path.lexists(target)
69 if directory_entry:
70 if exists and (target.is_symlink() or not target.is_dir()):
71 raise ValueError(f"native directory shadows a staged file: /{relative}")
72 if not exists:
73 target.mkdir()
74 walk(origin, target)
75 if not exists:
76 shutil.copystat(origin, target)
77 continue
78 if exists:
79 raise ValueError(f"native file shadows a staged path: /{relative}")
80 if stat.S_ISLNK(mode):
81 link = os.readlink(origin)
82 native_link_target(relative, link)
83 target.symlink_to(link)
84 table.writerow((relative, "link", "", link))
85 elif stat.S_ISREG(mode):
86 inode = (info.st_dev, info.st_ino)
87 if inode in hard_links:
88 staged, digest = hard_links[inode]
89 os.link(staged, target)
90 else:
91 shutil.copy2(origin, target)
92 with target.open("rb") as stream:
93 digest = hashlib.file_digest(stream, "sha256").hexdigest()
94 if info.st_nlink > 1:
95 hard_links[inode] = (target, digest)
96 table.writerow((relative, "file", f"{stat.S_IMODE(mode):04o}", digest))
97 else:
98 raise ValueError(f"unsupported native file type: /{relative}")
99
100 walk(source, root)
101
102
103def snapshot(repo, dest, ring, arch, gpg_home):
104 def verify(path):
105 subprocess.run(["gpgv", "--homedir", gpg_home, "--keyring", ring, str(path) + ".sig", path],
106 check=True, stdout=subprocess.DEVNULL)
107
108 def copy(name):
109 if Path(name).name != name or not name or name in (".", ".."):
110 raise ValueError(f"invalid repository filename {name!r}")
111 source = repo / name
112 if source.resolve().parent != repo or not source.is_file():
113 raise ValueError(f"missing or external repository file: {name}")
114 target = dest / name
115 if target.exists():
116 raise ValueError(f"duplicate repository filename: {name}")
117 shutil.copyfile(source, target)
118 target.chmod(0o644)
119 return target
120
121 for index in ("vinix.db", "vinix.files"):
122 file = copy(index)
123 copy(index + ".sig")
124 verify(file)
125 indexed = {}
126 with tarfile.open(dest / "vinix.db", "r:gz") as database:
127 for entry in database:
128 if not entry.isfile() or Path(entry.name).name != "desc":
129 continue
130 info = package_fields(database.extractfile(entry).read().decode())
131 name, version, package_arch = (info[field] for field in ("NAME", "VERSION", "ARCH"))
132 filename = info["FILENAME"]
133 if (name in indexed or package_arch not in (arch, "any") or
134 filename != f"{name}-{version}-{package_arch}.pkg.tar.zst"):
135 raise ValueError(f"invalid database record for {name}")
136 archive = copy(filename)
137 copy(filename + ".sig")
138 with archive.open("rb") as stream:
139 if hashlib.file_digest(stream, "sha256").hexdigest() != info["SHA256SUM"]:
140 raise ValueError(f"archive differs from signed index: {filename}")
141 verify(archive)
142 indexed[name] = version
143 if not indexed:
144 raise ValueError("empty signed package index")
145 return indexed
146
147
148def stage(args):
149 client, repo, output = args.client.resolve(), args.repo.resolve(), args.output.resolve()
150 native = args.native_layer.resolve(strict=True) if args.native_layer else None
151 sources = (client, repo, native) if native else (client, repo)
152 if any(output.is_relative_to(path) for path in sources):
153 raise ValueError("put image output outside its input directories")
154 if native and not native.is_dir():
155 raise ValueError("expected a staging directory for the native layer")
156 output.mkdir()
157 audit = subprocess.check_output([args.auditor, args.arch, client], text=True)
158 (output / "audited-root.log").write_text(audit)
159 with tempfile.TemporaryDirectory(dir=output) as directory:
160 staging = Path(directory)
161 root = staging / "image"
162 subprocess.run(["cp", "-a", "--reflink=auto", client / "root", root], check=True)
163 # This compares the installed certificate with the independently supplied pin.
164 seed = Path(__file__).resolve().with_name("keyring.py")
165 subprocess.run([sys.executable, seed, "seed", root, args.fingerprint], check=True)
166 package_dir = write_directory(root, "var/lib/vinix/repository/" + args.arch)
167 if any(package_dir.iterdir()):
168 raise ValueError("seed repository directory is already populated")
169 with tempfile.TemporaryDirectory() as gpg_home:
170 indexed = snapshot(repo / args.arch, package_dir, root / "usr/share/vpac/keyrings/vinix.gpg",
171 args.arch, gpg_home)
172 records = client / "db/local"
173 for database in [records, *(root / "db/local" for root in args.seed_client)]:
174 descriptions = sorted(database.glob("*/desc"))
175 if not descriptions:
176 raise ValueError(f"client has no package records at {database}")
177 for description in descriptions:
178 info = package_fields(description.read_text())
179 if indexed.get(info["NAME"]) != info["VERSION"]:
180 raise ValueError(f"installed package missing from seed at its exact version: {info['NAME']}")
181 db = write_directory(root, "var/lib/vpac")
182 if any(db.iterdir()):
183 raise ValueError("package database directory is already populated")
184 local = db / "local"
185 shutil.copytree(records, local)
186 local.chmod(0o755)
187 sync = write_directory(root, "var/lib/vpac/sync")
188 for name in ("vinix.db", "vinix.db.sig"):
189 shutil.copy(package_dir / name, sync / name)
190 if native:
191 manifest = staging / "native-layer.tsv"
192 with manifest.open("x", newline="") as records:
193 table = csv.writer(records, delimiter="\t", lineterminator="\n")
194 table.writerow(("path", "type", "mode", "sha256_or_link"))
195 install_native_layer(native, root, table, [client / "root" for client in args.seed_client])
196 if args.release:
197 release_file = write_directory(root, "etc") / "vinix-release"
198 with release_file.open("x") as output_file:
199 output_file.write(args.release + "\n")
200 release_file.chmod(0o644)
201 if args.initramfs:
202 if os.path.lexists(root / ".vinix-image-id"):
203 raise ValueError("the ISO builder assigns the image identity")
204 image = staging / "initramfs.tar"
205 subprocess.run(["tar", "--format=ustar", "--sort=name", "--numeric-owner",
206 "--owner=0", "--group=0", "-cf", image, "-C", root, "."], check=True)
207 for artifact in ("native-layer.tsv", "initramfs.tar"):
208 if (staging / artifact).exists():
209 (staging / artifact).rename(output / artifact)
210 root.rename(output / "root")
211 print(audit, end="")
212 print(f"staged {len(indexed)} signed seed packages and the installed database")
213
214
215if __name__ == "__main__":
216 parser = argparse.ArgumentParser(description=__doc__)
217 parser.add_argument("arch", choices=("x86_64", "aarch64"))
218 for arg in ("client", "repo", "output", "auditor"):
219 parser.add_argument(arg, type=Path)
220 parser.add_argument("fingerprint", help="trusted distributor fingerprint from outside the feed")
221 parser.add_argument("--native-layer", type=Path, help="Vinix-built programs and assets to add to the image")
222 parser.add_argument("--release", default="", help="release tag stored in /etc/vinix-release")
223 parser.add_argument("--seed-client", type=Path, action="append", default=[],
224 help="require the installed versions from another audited client in the seed")
225 parser.add_argument("--initramfs", action="store_true", help="write a root-owned USTAR archive for the ISO builder")
226 stage(parser.parse_args())
227