"""Use the installed musl loader to relocate each dynamic executable in a signed root.""" import argparse import csv import hashlib import os from pathlib import Path import shlex import shutil import struct import subprocess import tarfile import tempfile def executable(path): with path.open("rb") as stream: header = stream.read(64) if header[:4] != b"\x7fELF": return None if len(header) != 64 or header[4:6] != bytes((2, 1)): raise ValueError(f"unexpected ELF header in {path}") kind, = struct.unpack_from(" path.stat().st_size: raise ValueError(f"invalid ELF program headers in {path}") stream.seek(offset) for _ in range(count): segment, _, position, _, _, length, _, _ = struct.unpack(" 4096: raise ValueError(f"invalid ELF interpreter in {path}") stream.seek(position) raw = stream.read(length) if len(raw) != length or not raw.endswith(b"\0"): raise ValueError(f"truncated ELF interpreter in {path}") return os.fsdecode(raw[:-1]), kind return None def commands(arch, sdk): root = sdk / "root" expected = f"/lib/ld-musl-{arch}.so.1" for directory, _, files in os.walk(root): for name in sorted(files): path = Path(directory) / name if path.is_symlink() or not path.is_file(): continue elf = executable(path) if elf is not None: loader, kind = elf if loader != expected: raise ValueError(f"unexpected interpreter {loader} in {path}") yield [loader, "--list", "/" + path.relative_to(root).as_posix()], kind def release_probe(args): archive, expected, report = args.release with Path(archive).open("rb") as source: if hashlib.file_digest(source, "sha256").hexdigest() != expected: raise ValueError("release archive checksum mismatch") root = args.client / "root" loader = f"/lib/ld-musl-{args.arch}.so.1" rows = [] with tempfile.TemporaryDirectory() as folder, tarfile.open(archive, "r|gz") as members: program = Path(folder) / "program" program.touch(mode=0o755) for entry in members: if not entry.isfile(): continue with members.extractfile(entry) as member: magic = member.read(4) if magic != b"\x7fELF": continue with program.open("wb") as out: out.write(magic) shutil.copyfileobj(member, out) elf = executable(program) if elf is None: continue interp, kind = elf path = Path(entry.name.removeprefix("./")) if path.is_absolute() or ".." in path.parts or ":" in str(path) or "!" in str(path): raise ValueError(f"invalid guest bind path: {path}") if interp != loader: rows.append((str(path), "other interpreter", interp)) continue # Bind only the original program at its release path. Dependencies # and the interpreter come from the independently audited root. result = subprocess.run([args.proot, "-r", root, "-w", "/", "-b", f"{program}:/{path}!", loader, "--list", "/" + str(path)], capture_output=True, text=True) diagnostic = " | ".join(result.stderr.splitlines()) status = "failed" if result.returncode else "relocated" if kind == 2 and result.returncode and "Not a valid dynamic program" in diagnostic: # The loader's explicit --list entry cannot map some fixed-address # executables that do start through the kernel's normal ELF entry. status = "requires direct execution" rows.append((str(path), status, diagnostic)) if not rows: raise ValueError("release contained no executable with an interpreter") with Path(report).open("x") as output: table = csv.writer(output, delimiter="\t", lineterminator="\n") table.writerow(("release_path", "status", "diagnostic")) table.writerows(sorted(rows)) passed = sum(status == "relocated" for _, status, _ in rows) print(f"Relocated {passed} of {len(rows)} original {args.arch} executables") return int(passed != len(rows)) def main(args): subprocess.run([args.auditor, args.arch, args.client], check=True) if args.release: return release_probe(args) entries = [] fixed = [] for command, kind in sorted(commands(args.arch, args.client)): if kind == 2 and args.fixed_address_report: fixed.append(command[-1]) else: entries.append(command) if not entries: raise ValueError("root has no dynamically linked executables") if args.fixed_address_report: with args.fixed_address_report.open("x") as output: for path in fixed: output.write(path + "\n") print(f"{len(fixed)} fixed-address executables require direct execution") if args.fixture: with args.fixture.open("x") as output: output.write("#!/bin/sh\nset -eu\nexport LC_ALL=C\nunset LD_LIBRARY_PATH LD_PRELOAD\n" "trap '/sbin/poweroff -f' EXIT\n") for cmd in entries: output.write(shlex.join(cmd) + " >/dev/null\n") output.write(f"echo 'Relocated {len(entries)} Vinix executables'\n" "echo 'VPAC FIXTURE GUEST PASS'\n") if args.proot: for cmd in entries: result = subprocess.run([args.proot, "-r", args.client / "root", "-w", "/", *cmd], text=True, capture_output=True) if result.returncode: raise ValueError(f"{cmd[-1]}: musl exited {result.returncode}\n{result.stderr}") print(cmd[-1]) print(f"Relocated {len(entries)} {args.arch} executables in the signed root") if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("arch", choices=("x86_64", "aarch64")) for arg in ("client", "auditor"): parser.add_argument(arg, type=lambda p: Path(p).resolve()) parser.add_argument("--fixture", type=Path, help="write a guest script for the Vinix boot harness") parser.add_argument("--proot", type=Path, help="also check a host-architecture root in unprivileged PRoot") parser.add_argument("--fixed-address-report", type=Path, help="list fixed-address executables separately for direct execution checks") parser.add_argument("--release", nargs=3, metavar=("ARCHIVE", "SHA256", "REPORT"), help="bind each original release executable over its guest path and record relocation results") options = parser.parse_args() if not (options.fixture or options.proot): parser.error("supply --fixture or --proot") if options.proot and options.arch != os.uname().machine: parser.error("use the Vinix guest fixture for a foreign architecture") if options.release and (not options.proot or options.fixture): parser.error("--release requires --proot and an independent report path") if options.release and options.fixed_address_report: parser.error("--release already reports which executables require direct execution") raise SystemExit(main(options))