"""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 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 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) interp = interpreter(program) if interp is None: continue 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" with program.open("rb") as source: kind, = struct.unpack_from("/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("--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") raise SystemExit(main(options))