Measure exported interfaces and dynamic imports across the release
@@ -111,3 +111,7 @@ The arm64 desktop init uses the Vinix V generator and freestanding syscall imple
111111`tests/library-upgrades.py` reads the actual shared libraries in the checksum-pinned release initramfs and the replacement files in an audited root. It checks the ELF target, SONAME, provider ownership and dynamic exports, including symbol versions and exported data sizes. PCRE2's two x86_64 libraries retained all 77 and 6 compared exports, and zlib retained all 95. Their new implementation filenames are in `foundation/release-library-interfaces-01/interfaces.tsv`, receipt SHA-256 `11ddb4daf9f4b2d231c512b3b9e16f92dd2ccdb1192fff0130a6be5037fa971b`. OpenSSL 3.5.9-3 retained all 580 libssl exports. Its libcrypto lacked the three published NIST prime-field method symbols for 224, 256 and 521 bits. See `foundation/release-ssl-interfaces-01/known-differences.sha256`, SHA-256 `679aab5f1a2d7d4beb4853872ba45b30a4b875c27fb70b5ca6ffa708340105ce`.
112112
113113OpenSSL 3.5.9-4 on x86_64 enables those three methods. Its recipe creates and frees an EC group with each method. The fresh signed installation supplies all 5,426 published libcrypto exports and all 580 libssl exports. See `foundation/openssl-ec-04/interfaces.tsv` and its receipt manifest, SHA-256 `269a3326b99eacb2691fd370bf17f828750b28d5feaff4be6c48217c4a7134b3`.
114+
115+To survey the whole release initramfs, pass `--system-providers providers.tsv` to `tests/library-upgrades.py` in place of individual library arguments. It examines every regular shared-library ELF in `/lib` and `/usr/lib`, resolves its SONAME to an installed owner, and records absent providers and differing exports. The 129-package x86_64 root fully covered the exports for 51 of 69 regular library paths. Twelve had no installed provider and six had export differences, including the earlier OpenSSL build. Multiple paths in the release contain the same library. The nine-package arm64 bootstrap root covered its loader, had 68 missing providers and contained no replacement for the release's native OBS module without a SONAME. See `foundation/system-library-interfaces-01`, receipt SHA-256 `cdf961b747c2abcf7c90f0a5d011c783a16ad97e8aedb091f317c76628870381`.
116+
117+`tests/release-imports.py ARCHIVE SHA256 REPORT SYMBOL...` searches undefined dynamic symbols in the original binaries. Across 240 amd64 image files, 114 amd64 X11 files, 221 arm64 image files and 120 arm64 X11 files, no binary imported `_dlstart` or Zstd's deprecated experimental `ZSTD_copyCCtx` and `ZSTD_copyDCtx`, removed upstream in 1.6.0. The same scan found no direct imports of the five differing GMP helpers or the nine MPFR cache and default-state symbols. It found `ZSTD_decompress` in all four layers and `mpfr_init2` in both images. The scan measures link-time imports. MPFR's per-thread defaults need a runtime test independently. See `foundation/release-dynamic-imports-01`, receipt SHA-256 `2e5ff31cdbc7c255a15ba8b8da25749c1633e102245f89a95fe8dcdcdd9072a5`.
@@ -3,6 +3,7 @@ import argparse
33import csv
44import hashlib
55from pathlib import Path
6+import re
67import shutil
78import subprocess
89import tarfile
@@ -15,7 +16,10 @@ def interface(path, arch):
1516 fields = [line.strip() for line in report.splitlines()]
1617 if not any(line.startswith("Machine:") and line.split(":", 1)[1].strip() == machine for line in fields):
1718 raise ValueError(f"unexpected ELF target in {path}")
18- soname, = [line.split("[", 1)[1].split("]", 1)[0] for line in fields if "(SONAME)" in line]
19+ names = [line.split("[", 1)[1].split("]", 1)[0] for line in fields if "(SONAME)" in line]
20+ if len(names) > 1:
21+ raise ValueError(f"multiple SONAME entries in {path}")
22+ soname = names[0] if names else ""
1923 exports = set()
2024 for line in fields:
2125 row = line.split()
@@ -29,52 +33,97 @@ def interface(path, arch):
2933 return soname, exports
3034
3135
36+def package_owners(client):
37+ owners = {}
38+ for desc in (client / "db/local").glob("*/desc"):
39+ name, = [block.splitlines()[1] for block in desc.read_text().split("\n\n") if block.startswith("%NAME%\n")]
40+ records = desc.with_name("files").read_text().split("\n\n")
41+ for path in next((b.splitlines()[1:] for b in records if b.startswith("%FILES%\n")), []):
42+ if not path.endswith("/"):
43+ if path in owners:
44+ raise ValueError(f"duplicate owner for {path}")
45+ owners[path] = name
46+ return owners
47+
48+
3249def run(args):
3350 with args.initramfs.open("rb") as source:
3451 if hashlib.file_digest(source, "sha256").hexdigest() != args.sha256:
3552 raise ValueError("release initramfs checksum mismatch")
3653 subprocess.run([args.auditor, args.arch, args.client], check=True)
3754 root = (args.client / "root").resolve()
38- expected = {path: (package, soname) for package, path, soname in args.library}
39- if len(expected) != len(args.library):
55+ owners = package_owners(args.client)
56+ expected = {path: (package, soname) for package, path, soname in args.library or []}
57+ if len(expected) != len(args.library or []):
4058 raise ValueError("each release path must occur only once")
4159 results = {}
60+ coverage = {}
61+ installed_interfaces = {}
4262 with tempfile.TemporaryDirectory() as temp, tarfile.open(args.initramfs, "r|gz") as contents:
4363 for entry in contents:
4464 path = entry.name.removeprefix("./")
45- if path not in expected:
65+ if args.system_providers:
66+ original = Path(path)
67+ if (not entry.isfile() or original.parent.as_posix() not in ("lib", "usr/lib") or
68+ not re.search(r"\.so($|\.)", original.name)):
69+ continue
70+ elif path not in expected:
4671 continue
47- package, name = expected[path]
48- if not entry.isfile() or path in results or Path(name).name != name:
72+ if not entry.isfile() or path in coverage:
4973 raise ValueError(f"expected one regular release library at {path}")
5074 reference = Path(temp) / "reference"
51- with contents.extractfile(entry) as source, reference.open("wb") as copy:
52- shutil.copyfileobj(source, copy)
75+ with contents.extractfile(entry) as source:
76+ magic = source.read(4)
77+ if args.system_providers and magic != b"\x7fELF":
78+ continue
79+ with reference.open("wb") as copy:
80+ copy.write(magic)
81+ shutil.copyfileobj(source, copy)
5382 old_name, old = interface(reference, args.arch)
83+ if args.system_providers and not old_name:
84+ coverage[path] = ("", "", "no SONAME")
85+ continue
86+ package, name = expected.get(path, ("", old_name))
87+ if not name or Path(name).name != name or old_name != name:
88+ raise ValueError(f"{path}: expected {name}, found {old_name}")
5489 alias = Path(path).with_name(name)
90+ alias_owner = owners.get(alias.as_posix())
91+ if args.system_providers:
92+ if not alias_owner:
93+ coverage[path] = (name, "", "provider absent")
94+ continue
95+ package = alias_owner
5596 current = (root / alias).resolve()
5697 current_path = current.relative_to(root)
57- records = [d for d in (args.client / "db/local").glob("*/desc")
58- if f"\n%NAME%\n{package}\n" in "\n" + d.read_text()]
59- record, = records
60- owned = set(record.with_name("files").read_text().splitlines())
61- if alias.as_posix() not in owned or current_path.as_posix() not in owned:
98+ if package != alias_owner or package != owners.get(current_path.as_posix()):
6299 raise ValueError(f"{package} must own both {alias} and {current_path}")
63- new_name, new = interface(current, args.arch)
64- if old_name != name or new_name != name:
65- raise ValueError(f"{path}: expected {name}, found {old_name} and {new_name}")
100+ if current not in installed_interfaces:
101+ installed_interfaces[current] = interface(current, args.arch)
102+ new_name, new = installed_interfaces[current]
103+ if new_name != name:
104+ raise ValueError(f"{current_path}: expected {name}, found {new_name}")
66105 missing = sorted(old - new)
67106 results[path] = (package, name, current_path, len(old), len(new), len(missing),
68107 ",".join(symbol for symbol, _, _ in missing))
69- if set(results) != set(expected):
108+ coverage[path] = (name, package, "missing exports" if missing else "compared")
109+ if expected and set(results) != set(expected):
70110 raise ValueError(f"missing release libraries: {sorted(set(expected) - set(results))}")
111+ if args.system_providers:
112+ if not coverage:
113+ raise ValueError("no release system libraries found")
114+ with args.system_providers.open("x") as stream:
115+ table = csv.writer(stream, delimiter="\t", lineterminator="\n")
116+ table.writerow(("release_path", "soname", "installed_owner", "status"))
117+ table.writerows((path, *record) for path, record in sorted(coverage.items()))
71118 with args.output.open("x") as stream:
72119 table = csv.writer(stream, delimiter="\t", lineterminator="\n")
73120 table.writerow(("release_path", "package", "soname", "installed_path", "old_exports",
74121 "new_exports", "missing_count", "missing_symbols"))
75122 for path, result in sorted(results.items()):
76123 table.writerow((path, *result))
77- return int(any(row[-2] for row in results.values()))
124+ if any(row[-2] for row in results.values()):
125+ return 1
126+ return 2 if len(coverage) > len(results) else 0
78127
79128
80129if __name__ == "__main__":
@@ -83,6 +132,8 @@ if __name__ == "__main__":
83132 for arg in ("client", "auditor", "initramfs", "output"):
84133 parser.add_argument(arg, type=Path)
85134 parser.add_argument("sha256", help="published initramfs digest")
86- parser.add_argument("--library", nargs=3, action="append", metavar=("PACKAGE", "RELEASE_PATH", "SONAME"),
87- required=True)
135+ selection = parser.add_mutually_exclusive_group(required=True)
136+ selection.add_argument("--library", nargs=3, action="append", metavar=("PACKAGE", "RELEASE_PATH", "SONAME"))
137+ selection.add_argument("--system-providers", type=Path, metavar="REPORT",
138+ help="compare all regular shared libraries in /lib and /usr/lib and record every provider")
88139 raise SystemExit(run(parser.parse_args()))
@@ -0,0 +1,59 @@
1+"""Find dynamic imports of specified symbols in a checksum-pinned release archive."""
2+import argparse
3+import csv
4+import hashlib
5+from pathlib import Path
6+import re
7+import shutil
8+import subprocess
9+import tarfile
10+import tempfile
11+
12+
13+def scan(args):
14+ symbols = set(args.symbol)
15+ with args.archive.open("rb") as stream:
16+ if hashlib.file_digest(stream, "sha256").hexdigest() != args.sha256:
17+ raise ValueError("release archive checksum mismatch")
18+ results = []
19+ files = 0
20+ with tempfile.TemporaryDirectory() as temp, tarfile.open(args.archive, "r|gz") as archive:
21+ elf = Path(temp) / "member"
22+ for entry in archive:
23+ if not entry.isfile():
24+ continue
25+ with archive.extractfile(entry) as stream:
26+ header = stream.read(4)
27+ if header != b"\x7fELF":
28+ continue
29+ with elf.open("wb") as copy:
30+ copy.write(header)
31+ shutil.copyfileobj(stream, copy)
32+ files += 1
33+ report = subprocess.check_output(["readelf", "-Wd", "--dyn-syms", elf], text=True)
34+ needed = ",".join(re.findall(r"\(NEEDED\)[^\n]*?\[([^\]]+)\]", report))
35+ for line in report.splitlines():
36+ cols = line.split()
37+ if len(cols) < 8 or cols[6] != "UND" or not cols[0].removesuffix(":").isdigit():
38+ continue
39+ if cols[7].split("@", 1)[0] in symbols:
40+ results.append((entry.name.removeprefix("./"), cols[7], cols[4], needed))
41+ if not files:
42+ raise ValueError("release archive contains no regular ELF files")
43+ with args.output.open("x") as out:
44+ table = csv.writer(out, delimiter="\t", lineterminator="\n")
45+ table.writerow(("release_path", "import", "binding", "needed"))
46+ table.writerows(sorted(results))
47+ for name in sorted(symbols):
48+ count = sum(symbol.split("@", 1)[0] == name for _, symbol, _, _ in results)
49+ print(f"{name}\t{count}")
50+ print(f"Scanned {files} regular ELF files")
51+
52+
53+if __name__ == "__main__":
54+ parser = argparse.ArgumentParser(description=__doc__)
55+ parser.add_argument("archive", type=Path)
56+ parser.add_argument("sha256")
57+ parser.add_argument("output", type=Path)
58+ parser.add_argument("symbol", nargs="+")
59+ scan(parser.parse_args())