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