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