"""Compare published release inputs with package owners in an audited vpac root.""" import argparse import csv import subprocess from collections import Counter, defaultdict from pathlib import Path # Most Alpine split packages are combined under their source name in Vinix. # These are expected owners. Actual ownership comes from the installed database. SOURCE_OWNERS = { "alpine-base": ("vinix-release",), "alpine-baselayout": ("vinix-filesystem", "vinix-accounts", "netbase"), "alpine-keys": ("vinix-keyring",), "apk-tools": ("vpac",), "hwdata": ("hwdata-pci",), "llvm17": ("llvm17-libs",), "llvm19": ("llvm19-libs",), "mpc1": ("mpc",), "mpfr4": ("mpfr",), "openssh": ("openssh-client",), "pax-utils": ("scanelf",), } BINARY_OWNERS = { "ca-certificates-bundle": ("ca-certificates-bundle",), "glu-dev": ("glu-headers",), "libatomic": ("gcc-libs",), "libelf": ("libelf",), "libgcc": ("gcc-libs",), "libgomp": ("gcc-libs",), "libstdc++": ("gcc-libs",), "libuuid": ("libuuid",), "musl-utils": ("musl-utils",), "ssl_client": ("ssl-client",), "mesa-dev": ("mesa", "mesa-platform-headers", "mesa-gallium-sdk"), "mesa-dri-gallium": ("mesa",), "mesa-osmesa": ("mesa-gallium-sdk",), "mesa-xatracker": ("mesa-gallium-sdk",), } def providers(row, path=None): if row["binary"] == "ca-certificates": if path is None: return ("ca-certificates", "ca-certificates-bundle") if Path(path).parent == Path("usr/share/ca-certificates/mozilla") and path.endswith(".crt"): return ("ca-certificates-bundle",) if row["origin"] == "alpine-baselayout": if path is None: return (*SOURCE_OWNERS["alpine-baselayout"], "vinix-release") if path == "etc/motd": return ("vinix-release",) if row["origin"] == "mesa" and row["repository"] == "v3.20/main": return ("mesa-glx-legacy",) return BINARY_OWNERS.get(row["binary"], SOURCE_OWNERS.get(row["origin"], (row["origin"],))) def field(body, name): for group in body.strip().split("\n\n"): marker, _, value = group.partition("\n") if marker == "%" + name + "%": return value.splitlines() return [] def installed(client, arch, auditor): result = subprocess.check_output([auditor, arch, client], text=True) versions = {} owners = {} for description in sorted((client / "db/local").glob("*/desc")): record = description.read_text() name, = field(record, "NAME") version, = field(record, "VERSION") versions[name] = version for path in field(description.with_name("files").read_text(), "FILES"): if not path.endswith("/"): if path in owners: raise ValueError(f"multiple owners for {path}") owners[path] = name return versions, owners, result def relocated(row, path, arch, versions): origin = row["origin"] if origin == "zsh" and origin in versions: old = row["version"].rsplit("-r", 1)[0] new = versions[origin].rsplit("-", 1)[0] if path == f"bin/zsh-{old}": return f"bin/zsh-{new}" for base in ("usr/share/zsh", "usr/lib/zsh"): prefix = f"{base}/{old}/" if path.startswith(prefix): suffix = path.removeprefix(prefix) if base == "usr/share/zsh" and old == "5.9" and new == "5.9.2": suffix = { "functions/Completion/Linux/_pmap": "functions/Completion/Unix/_pmap", "functions/Completion/Linux/_chcon": "functions/Completion/Linux/_selinux", }.get(suffix, suffix) return f"{base}/{new}/{suffix}" if origin in ("font-misc-misc", "font-cursor-misc", "font-alias") and path.startswith("usr/share/fonts/misc/"): return "usr/share/fonts/X11/misc/" + path.removeprefix("usr/share/fonts/misc/") if origin == "ncurses" and path.startswith("etc/terminfo/"): return "usr/share/terminfo/" + path.removeprefix("etc/terminfo/") if origin == "binutils" and path.startswith(f"usr/{arch}-alpine-linux-musl/"): return f"usr/{arch}-linux-musl/" + path.removeprefix(f"usr/{arch}-alpine-linux-musl/") return None def replacement(row, path): if row["binary"] == "alpine-keys" and path.endswith(".rsa.pub"): if path.startswith(("etc/apk/keys/", "usr/share/apk/keys/")): return "usr/share/vpac/keyrings/vinix.gpg", "vinix-keyring", "repository trust" if row["binary"] == "alpine-release" and path == "etc/alpine-release": return "etc/os-release", "vinix-release", "operating system identity" if row["binary"] == "apk-tools" and path == "sbin/apk": return "usr/bin/vpac", "vpac", "package management" if row["binary"] == "musl-dev" and path == "usr/include/bits/posix.h": return "usr/include/unistd.h", "musl", "POSIX LP64/OFF64 feature macros" if row["binary"] == "ca-certificates" and path == "etc/apk/protected_paths.d/ca-certificates.list": return "usr/sbin/update-ca-certificates", "ca-certificates", "regeneration of CA bundle and hash links" if row["binary"] == "alpine-baselayout-data" and path == "etc/inittab": return "sbin/init", "vinix-desktop-init", "default desktop startup" return None def rows(path): with path.open() as stream: yield from csv.DictReader(stream, delimiter="\t") def key(row): return row["binary"], row["version"], row["repository"] def owner_requirement(value): path, separator, owner = value.rpartition("=") if not separator or not path.lstrip("/") or not owner: raise argparse.ArgumentTypeError("expected PATH=PACKAGE") return path.removeprefix("/"), owner def action(row, state, names, expected, has_client): if int(row["unavailable"]): return "obtain and compare original source input" if not state: if int(row["different"]): return "review changed published paths and identify their owner" if row["profiles"] == "x11-index-dependency": return "check whether native X11 builds require this index dependency" return "verify as a build or staging input" if not has_client: return "install and audit the target packages" if row["origin"] in ("alpine-keys", "apk-tools"): return "verify the Vinix trust and package-management replacements in the image" if not names.intersection(expected): return "build and install the expected packages" if state["unowned"] or state["other_owner"]: return "resolve missing paths, alternate owners and intentional replacements" return "verify the package behavior in the release image" def compare(args): versions, owners, audit = installed(args.client, args.arch, args.auditor) if args.client else ({}, {}, "") for path, expected in args.require_owner: actual = owners.get(path) if actual != expected: raise ValueError(f"{args.arch}: /{path} belongs to {actual or 'no package'}, expected {expected}") names = set(versions) packages = {key(row): row for row in rows(args.comparison / "packages.tsv")} details = defaultdict(Counter) seen = set() moved = [] replacements = [] args.output.mkdir() if audit: (args.output / "installed-root.log").write_text(audit) if args.require_owner: with (args.output / "required-owners.tsv").open("x") as stream: writer = csv.writer(stream, delimiter="\t", lineterminator="\n") writer.writerow(["path", "owner", "version"]) writer.writerows((path, owner, versions[owner]) for path, owner in args.require_owner) with (args.output / "paths.tsv").open("x") as stream: writer = csv.writer(stream, delimiter="\t", lineterminator="\n") writer.writerow(["binary", "version", "repository", "layer", "published_path", "original_comparison", "candidate_path", "installed_owner", "ownership"]) for row in rows(args.comparison / "package-files.tsv"): k = key(row) path = row["published_path"] owner = owners.get(path, "") known = row["comparison"] != "different" expected = providers(packages[k], path) match = ("unmeasured" if not args.client else "unowned" if not owner else "expected_owner" if owner in expected else "other_owner") writer.writerow([*k, row["layer"], path, row["comparison"], row["candidate_path"], owner, match]) observation = k, row["layer"], path if known and observation not in seen: seen.add(observation) details[k][match] += 1 if match == "unowned": target = relocated(packages[k], path, args.arch, versions) if target and owners.get(target) in expected: moved.append((*k, row["layer"], path, target, owners[target])) change = replacement(packages[k], path) if change: native, package, function = change replacements.append((*k, row["layer"], path, native, package, owners.get(native, ""), function)) with (args.output / "relocations.tsv").open("x") as stream: writer = csv.writer(stream, delimiter="\t", lineterminator="\n") writer.writerow(["binary", "version", "repository", "layer", "published_path", "installed_path", "owner"]) writer.writerows(sorted(moved)) with (args.output / "replacements.tsv").open("x") as stream: writer = csv.writer(stream, delimiter="\t", lineterminator="\n") writer.writerow(["binary", "version", "repository", "layer", "published_path", "native_path", "expected_owner", "installed_owner", "function"]) writer.writerows(sorted(replacements)) with (args.output / "packages.tsv").open("x") as stream: writer = csv.writer(stream, delimiter="\t", lineterminator="\n") writer.writerow(["binary", "version", "repository", "origin", "profiles", "expected_packages", "installed_expected_packages", "published_matching_paths", "expected_owner", "other_owner", "unowned", "unmeasured", "next_check"]) for k, row in packages.items(): expected = providers(row) state = details[k] writer.writerow([*k, row["origin"], row["profiles"], ",".join(expected), ",".join(sorted(names.intersection(expected))), sum(state.values()), *[state[s] for s in ("expected_owner", "other_owner", "unowned", "unmeasured")], action(row, state, names, expected, args.client is not None)]) print(f"{args.arch}: {len(packages)} release input rows, {len(names)} installed packages, " f"{len(seen)} matching input/layer/path observations") if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("arch", choices=("x86_64", "aarch64")) parser.add_argument("comparison", type=Path) parser.add_argument("output", type=Path) parser.add_argument("--client", type=Path, help="fresh signed vpac client to audit") parser.add_argument("--auditor", type=Path, help="compiled tests/installed-root.v") parser.add_argument("--require-owner", action="append", type=owner_requirement, default=[], metavar="PATH=PACKAGE", help="require an installed owner for a specific path") args = parser.parse_args() if bool(args.client) != bool(args.auditor): parser.error("--client and --auditor must be used together") if args.require_owner and args.client is None: parser.error("--require-owner needs an installed client") compare(args)