| 1 | """Use the installed musl loader to relocate each dynamic executable in a signed root.""" |
| 2 | import argparse |
| 3 | import csv |
| 4 | import hashlib |
| 5 | import os |
| 6 | from pathlib import Path |
| 7 | import shlex |
| 8 | import shutil |
| 9 | import struct |
| 10 | import subprocess |
| 11 | import tarfile |
| 12 | import tempfile |
| 13 | |
| 14 | |
| 15 | def executable(path): |
| 16 | with path.open("rb") as stream: |
| 17 | header = stream.read(64) |
| 18 | if header[:4] != b"\x7fELF": |
| 19 | return None |
| 20 | if len(header) != 64 or header[4:6] != bytes((2, 1)): |
| 21 | raise ValueError(f"unexpected ELF header in {path}") |
| 22 | kind, = struct.unpack_from("<H", header, 16) |
| 23 | if kind not in (2, 3): |
| 24 | return None |
| 25 | offset, = struct.unpack_from("<Q", header, 32) |
| 26 | stride, count = struct.unpack_from("<HH", header, 54) |
| 27 | if stride != 56 or offset + count * stride > path.stat().st_size: |
| 28 | raise ValueError(f"invalid ELF program headers in {path}") |
| 29 | stream.seek(offset) |
| 30 | for _ in range(count): |
| 31 | segment, _, position, _, _, length, _, _ = struct.unpack("<II6Q", stream.read(stride)) |
| 32 | if segment == 3: |
| 33 | if length < 2 or length > 4096: |
| 34 | raise ValueError(f"invalid ELF interpreter in {path}") |
| 35 | stream.seek(position) |
| 36 | raw = stream.read(length) |
| 37 | if len(raw) != length or not raw.endswith(b"\0"): |
| 38 | raise ValueError(f"truncated ELF interpreter in {path}") |
| 39 | return os.fsdecode(raw[:-1]), kind |
| 40 | return None |
| 41 | |
| 42 | |
| 43 | def commands(arch, sdk): |
| 44 | root = sdk / "root" |
| 45 | expected = f"/lib/ld-musl-{arch}.so.1" |
| 46 | for directory, _, files in os.walk(root): |
| 47 | for name in sorted(files): |
| 48 | path = Path(directory) / name |
| 49 | if path.is_symlink() or not path.is_file(): |
| 50 | continue |
| 51 | elf = executable(path) |
| 52 | if elf is not None: |
| 53 | loader, kind = elf |
| 54 | if loader != expected: |
| 55 | raise ValueError(f"unexpected interpreter {loader} in {path}") |
| 56 | yield [loader, "--list", "/" + path.relative_to(root).as_posix()], kind |
| 57 | |
| 58 | |
| 59 | def release_probe(args): |
| 60 | archive, expected, report = args.release |
| 61 | with Path(archive).open("rb") as source: |
| 62 | if hashlib.file_digest(source, "sha256").hexdigest() != expected: |
| 63 | raise ValueError("release archive checksum mismatch") |
| 64 | root = args.client / "root" |
| 65 | loader = f"/lib/ld-musl-{args.arch}.so.1" |
| 66 | rows = [] |
| 67 | with tempfile.TemporaryDirectory() as folder, tarfile.open(archive, "r|gz") as members: |
| 68 | program = Path(folder) / "program" |
| 69 | program.touch(mode=0o755) |
| 70 | for entry in members: |
| 71 | if not entry.isfile(): |
| 72 | continue |
| 73 | with members.extractfile(entry) as member: |
| 74 | magic = member.read(4) |
| 75 | if magic != b"\x7fELF": |
| 76 | continue |
| 77 | with program.open("wb") as out: |
| 78 | out.write(magic) |
| 79 | shutil.copyfileobj(member, out) |
| 80 | elf = executable(program) |
| 81 | if elf is None: |
| 82 | continue |
| 83 | interp, kind = elf |
| 84 | path = Path(entry.name.removeprefix("./")) |
| 85 | if path.is_absolute() or ".." in path.parts or ":" in str(path) or "!" in str(path): |
| 86 | raise ValueError(f"invalid guest bind path: {path}") |
| 87 | if interp != loader: |
| 88 | rows.append((str(path), "other interpreter", interp)) |
| 89 | continue |
| 90 | # Bind only the original program at its release path. Dependencies |
| 91 | # and the interpreter come from the independently audited root. |
| 92 | result = subprocess.run([args.proot, "-r", root, "-w", "/", "-b", f"{program}:/{path}!", |
| 93 | loader, "--list", "/" + str(path)], capture_output=True, text=True) |
| 94 | diagnostic = " | ".join(result.stderr.splitlines()) |
| 95 | status = "failed" if result.returncode else "relocated" |
| 96 | if kind == 2 and result.returncode and "Not a valid dynamic program" in diagnostic: |
| 97 | # The loader's explicit --list entry cannot map some fixed-address |
| 98 | # executables that do start through the kernel's normal ELF entry. |
| 99 | status = "requires direct execution" |
| 100 | rows.append((str(path), status, diagnostic)) |
| 101 | if not rows: |
| 102 | raise ValueError("release contained no executable with an interpreter") |
| 103 | with Path(report).open("x") as output: |
| 104 | table = csv.writer(output, delimiter="\t", lineterminator="\n") |
| 105 | table.writerow(("release_path", "status", "diagnostic")) |
| 106 | table.writerows(sorted(rows)) |
| 107 | passed = sum(status == "relocated" for _, status, _ in rows) |
| 108 | print(f"Relocated {passed} of {len(rows)} original {args.arch} executables") |
| 109 | return int(passed != len(rows)) |
| 110 | |
| 111 | |
| 112 | def main(args): |
| 113 | subprocess.run([args.auditor, args.arch, args.client], check=True) |
| 114 | if args.release: |
| 115 | return release_probe(args) |
| 116 | entries = [] |
| 117 | fixed = [] |
| 118 | for command, kind in sorted(commands(args.arch, args.client)): |
| 119 | if kind == 2 and args.fixed_address_report: |
| 120 | fixed.append(command[-1]) |
| 121 | else: |
| 122 | entries.append(command) |
| 123 | if not entries: |
| 124 | raise ValueError("root has no dynamically linked executables") |
| 125 | if args.fixed_address_report: |
| 126 | with args.fixed_address_report.open("x") as output: |
| 127 | for path in fixed: |
| 128 | output.write(path + "\n") |
| 129 | print(f"{len(fixed)} fixed-address executables require direct execution") |
| 130 | if args.fixture: |
| 131 | with args.fixture.open("x") as output: |
| 132 | output.write("#!/bin/sh\nset -eu\nexport LC_ALL=C\nunset LD_LIBRARY_PATH LD_PRELOAD\n" |
| 133 | "trap '/sbin/poweroff -f' EXIT\n") |
| 134 | for cmd in entries: |
| 135 | output.write(shlex.join(cmd) + " >/dev/null\n") |
| 136 | output.write(f"echo 'Relocated {len(entries)} Vinix executables'\n" |
| 137 | "echo 'VPAC FIXTURE GUEST PASS'\n") |
| 138 | if args.proot: |
| 139 | for cmd in entries: |
| 140 | result = subprocess.run([args.proot, "-r", args.client / "root", "-w", "/", *cmd], |
| 141 | text=True, capture_output=True) |
| 142 | if result.returncode: |
| 143 | raise ValueError(f"{cmd[-1]}: musl exited {result.returncode}\n{result.stderr}") |
| 144 | print(cmd[-1]) |
| 145 | print(f"Relocated {len(entries)} {args.arch} executables in the signed root") |
| 146 | |
| 147 | |
| 148 | if __name__ == "__main__": |
| 149 | parser = argparse.ArgumentParser(description=__doc__) |
| 150 | parser.add_argument("arch", choices=("x86_64", "aarch64")) |
| 151 | for arg in ("client", "auditor"): |
| 152 | parser.add_argument(arg, type=lambda p: Path(p).resolve()) |
| 153 | parser.add_argument("--fixture", type=Path, help="write a guest script for the Vinix boot harness") |
| 154 | parser.add_argument("--proot", type=Path, help="also check a host-architecture root in unprivileged PRoot") |
| 155 | parser.add_argument("--fixed-address-report", type=Path, |
| 156 | help="list fixed-address executables separately for direct execution checks") |
| 157 | parser.add_argument("--release", nargs=3, metavar=("ARCHIVE", "SHA256", "REPORT"), |
| 158 | help="bind each original release executable over its guest path and record relocation results") |
| 159 | options = parser.parse_args() |
| 160 | if not (options.fixture or options.proot): |
| 161 | parser.error("supply --fixture or --proot") |
| 162 | if options.proot and options.arch != os.uname().machine: |
| 163 | parser.error("use the Vinix guest fixture for a foreign architecture") |
| 164 | if options.release and (not options.proot or options.fixture): |
| 165 | parser.error("--release requires --proot and an independent report path") |
| 166 | if options.release and options.fixed_address_report: |
| 167 | parser.error("--release already reports which executables require direct execution") |
| 168 | raise SystemExit(main(options)) |
| 169 | |