"""Compare the release's shared-library interface to its package-owned replacement.""" import argparse import csv import hashlib from pathlib import Path import re import shutil import subprocess import tarfile import tempfile def interface(path, arch): report = subprocess.check_output(["readelf", "-W", "-h", "-d", "--dyn-syms", path], text=True) machine = "AArch64" if arch == "aarch64" else "Advanced Micro Devices X86-64" fields = [line.strip() for line in report.splitlines()] if not any(line.startswith("Machine:") and line.split(":", 1)[1].strip() == machine for line in fields): raise ValueError(f"unexpected ELF target in {path}") names = [line.split("[", 1)[1].split("]", 1)[0] for line in fields if "(SONAME)" in line] if len(names) > 1: raise ValueError(f"multiple SONAME entries in {path}") soname = names[0] if names else "" exports = set() for line in fields: row = line.split() if (len(row) >= 8 and row[0].endswith(":") and row[0][:-1].isdigit() and row[4] in ("GLOBAL", "WEAK", "UNIQUE") and row[5] in ("DEFAULT", "PROTECTED") and row[6] not in ("UND", "ABS")): kind = "FUNC" if row[3] in ("FUNC", "IFUNC") else row[3] exports.add((row[7], kind, row[2] if kind in ("OBJECT", "TLS") else "")) if not exports: raise ValueError(f"no exported dynamic symbols in {path}") return soname, exports def package_owners(client): owners = {} for desc in (client / "db/local").glob("*/desc"): name, = [block.splitlines()[1] for block in desc.read_text().split("\n\n") if block.startswith("%NAME%\n")] records = desc.with_name("files").read_text().split("\n\n") for path in next((b.splitlines()[1:] for b in records if b.startswith("%FILES%\n")), []): if not path.endswith("/"): if path in owners: raise ValueError(f"duplicate owner for {path}") owners[path] = name return owners def run(args): with args.initramfs.open("rb") as source: if hashlib.file_digest(source, "sha256").hexdigest() != args.sha256: raise ValueError("release initramfs checksum mismatch") subprocess.run([args.auditor, args.arch, args.client], check=True) root = (args.client / "root").resolve() owners = package_owners(args.client) expected = {path: (package, soname) for package, path, soname in args.library or []} if len(expected) != len(args.library or []): raise ValueError("each release path must occur only once") results = {} coverage = {} installed_interfaces = {} with tempfile.TemporaryDirectory() as temp, tarfile.open(args.initramfs, "r|gz") as contents: for entry in contents: path = entry.name.removeprefix("./") if args.system_providers: original = Path(path) if (not entry.isfile() or original.parent.as_posix() not in ("lib", "usr/lib") or not re.search(r"\.so($|\.)", original.name)): continue elif path not in expected: continue if not entry.isfile() or path in coverage: raise ValueError(f"expected one regular release library at {path}") reference = Path(temp) / "reference" with contents.extractfile(entry) as source: magic = source.read(4) if args.system_providers and magic != b"\x7fELF": continue with reference.open("wb") as copy: copy.write(magic) shutil.copyfileobj(source, copy) old_name, old = interface(reference, args.arch) if args.system_providers and not old_name: coverage[path] = ("", "", "no SONAME") continue package, name = expected.get(path, ("", old_name)) if not name or Path(name).name != name or old_name != name: raise ValueError(f"{path}: expected {name}, found {old_name}") alias = Path(path).with_name(name) alias_owner = owners.get(alias.as_posix()) if args.system_providers: if not alias_owner: coverage[path] = (name, "", "provider absent") continue package = alias_owner current = (root / alias).resolve() current_path = current.relative_to(root) if package != alias_owner or package != owners.get(current_path.as_posix()): raise ValueError(f"{package} must own both {alias} and {current_path}") if current not in installed_interfaces: installed_interfaces[current] = interface(current, args.arch) new_name, new = installed_interfaces[current] if new_name != name: raise ValueError(f"{current_path}: expected {name}, found {new_name}") missing = sorted(old - new) results[path] = (package, name, current_path, len(old), len(new), len(missing), ",".join(symbol for symbol, _, _ in missing)) coverage[path] = (name, package, "missing exports" if missing else "compared") if expected and set(results) != set(expected): raise ValueError(f"missing release libraries: {sorted(set(expected) - set(results))}") if args.system_providers: if not coverage: raise ValueError("no release system libraries found") with args.system_providers.open("x") as stream: table = csv.writer(stream, delimiter="\t", lineterminator="\n") table.writerow(("release_path", "soname", "installed_owner", "status")) table.writerows((path, *record) for path, record in sorted(coverage.items())) with args.output.open("x") as stream: table = csv.writer(stream, delimiter="\t", lineterminator="\n") table.writerow(("release_path", "package", "soname", "installed_path", "old_exports", "new_exports", "missing_count", "missing_symbols")) for path, result in sorted(results.items()): table.writerow((path, *result)) if any(row[-2] for row in results.values()): return 1 return 2 if len(coverage) > len(results) else 0 if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("arch", choices=("aarch64", "x86_64")) for arg in ("client", "auditor", "initramfs", "output"): parser.add_argument(arg, type=Path) parser.add_argument("sha256", help="published initramfs digest") selection = parser.add_mutually_exclusive_group(required=True) selection.add_argument("--library", nargs=3, action="append", metavar=("PACKAGE", "RELEASE_PATH", "SONAME")) selection.add_argument("--system-providers", type=Path, metavar="REPORT", help="compare all regular shared libraries in /lib and /usr/lib and record every provider") raise SystemExit(run(parser.parse_args()))