"""Use the installed musl loader to relocate each dynamic executable in a signed root.""" import argparse import os from pathlib import Path import shlex import struct import subprocess def interpreter(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}") if struct.unpack_from(" path.stat().st_size: raise ValueError(f"invalid ELF program headers in {path}") stream.seek(offset) for _ in range(count): kind, _, 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]) 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 loader = interpreter(path) if loader is not None: if loader != expected: raise ValueError(f"unexpected interpreter {loader} in {path}") yield [loader, "--list", "/" + path.relative_to(root).as_posix()] def main(args): subprocess.run([args.auditor, args.arch, args.client], check=True) entries = sorted(commands(args.arch, args.client)) if not entries: raise ValueError("root has no dynamically linked executables") 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") 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") main(options)