#!/usr/bin/env python3 """Validate a relocatable Linux ELF closure without executing its binaries.""" from __future__ import annotations import argparse import os from pathlib import Path, PurePosixPath import re import shutil import subprocess import tempfile SYSTEM_DEPENDENCIES = tuple( re.compile(pattern) for pattern in ( r"^linux-vdso\.so\.1$", r"^ld-linux-x86-64\.so\.2$", r"^libc\.so\.6$", r"^libm\.so\.6$", r"^libmvec\.so\.1$", r"^libdl\.so\.2$", r"^libpthread\.so\.0$", r"^librt\.so\.1$", r"^libresolv\.so\.2$", r"^libutil\.so\.1$", r"^libanl\.so\.1$", r"^libBrokenLocale\.so\.1$", r"^libthread_db\.so\.1$", ) ) NEEDED_PATTERN = re.compile(r"\(NEEDED\).*Shared library: \[([^]]+)]") RUNPATH_PATTERN = re.compile(r"\((?:RPATH|RUNPATH)\).*Library r(?:un)?path: \[([^]]*)]") INTERPRETER_PATTERN = re.compile(r"Requesting program interpreter: ([^]]+)]") GLIBC_NAME_PATTERN = re.compile(r"\bName: (GLIBC_[A-Za-z0-9_.]+)\b") GLIBC_VERSION_PATTERN = re.compile(r"^GLIBC_(\d+)\.(\d+)(?:\.(\d+))?$") GLIBC_ABI_MINIMUMS = {"GLIBC_ABI_DT_RELR": (2, 36)} def parse_version(value: str) -> tuple[int, ...]: if not re.fullmatch(r"\d+(?:\.\d+){1,2}", value): raise ValueError(f"invalid ABI version: {value!r}") return tuple(int(component) for component in value.split(".")) def required_glibc_versions(version_info: str) -> set[tuple[int, ...]]: versions: set[tuple[int, ...]] = set() in_needs = False for line in version_info.splitlines(): if line.startswith("Version needs section"): in_needs = True continue if in_needs and line.startswith("Version "): break if not in_needs: continue name_match = GLIBC_NAME_PATTERN.search(line) if name_match is None: continue name = name_match.group(1) if name in GLIBC_ABI_MINIMUMS: versions.add(GLIBC_ABI_MINIMUMS[name]) elif name.startswith("GLIBC_ABI_"): raise ValueError(f"unknown GLIBC ABI requirement: {name}") elif version_match := GLIBC_VERSION_PATTERN.fullmatch(name): versions.add( tuple( int(component) for component in version_match.groups() if component is not None ) ) return versions def command_output(arguments: list[str]) -> str: environment = os.environ.copy() environment["LC_ALL"] = "C" completed = subprocess.run( arguments, check=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, env=environment, ) if completed.returncode != 0: message = completed.stderr.strip() or completed.stdout.strip() raise ValueError(f"{' '.join(arguments)} failed: {message}") return completed.stdout def is_elf(path: Path) -> bool: with path.open("rb") as stream: return stream.read(4) == b"\x7fELF" def is_system_dependency(name: str) -> bool: return any(pattern.fullmatch(name) for pattern in SYSTEM_DEPENDENCIES) def ensure_inside(path: Path, directory: Path, description: str) -> None: try: path.resolve(strict=True).relative_to(directory) except (FileNotFoundError, RuntimeError, ValueError) as error: raise ValueError(f"{description} escapes the bundle or is dangling: {path}") from error def validate_symlinks(library_dir: Path) -> None: for path in sorted(library_dir.iterdir()): if not path.is_symlink(): continue target = os.readlink(path) pure_target = PurePosixPath(target) if not target or pure_target.is_absolute() or ".." in pure_target.parts: raise ValueError(f"unsafe library symlink: {path.name} -> {target}") ensure_inside(path, library_dir, "library symlink") def validate(root: Path, maximum_glibc: tuple[int, ...] | None = None) -> list[str]: executable = root / "bin/echoiond" core = root / "lib/Echoion.ts" library_dir = (root / "lib").resolve(strict=True) for required in (executable, core): if not required.is_file() or required.is_symlink() or not is_elf(required): raise ValueError(f"missing regular ELF payload: {required}") validate_symlinks(library_dir) elf_files: list[Path] = [executable] for path in sorted(library_dir.iterdir()): if path.is_symlink(): continue if not path.is_file() or not is_elf(path): raise ValueError(f"unexpected non-ELF entry in lib/: {path}") elf_files.append(path) report: list[str] = [] for path in elf_files: relative = path.relative_to(root).as_posix() header = command_output(["readelf", "-hW", os.fspath(path)]) if not re.search(r"^\s*Class:\s+ELF64\s*$", header, re.MULTILINE): raise ValueError(f"{relative} is not a 64-bit ELF") if not re.search( r"^\s*Machine:\s+Advanced Micro Devices X86-64\s*$", header, re.MULTILINE, ): raise ValueError(f"{relative} is not an x86-64 ELF") dynamic = command_output(["readelf", "-dW", os.fspath(path)]) runpaths = RUNPATH_PATTERN.findall(dynamic) expected_runpath = "$ORIGIN/../lib" if path == executable else "$ORIGIN" if runpaths != [expected_runpath]: raise ValueError( f"{relative} RUNPATH must be {expected_runpath!r}, got {runpaths!r}" ) report.append(f"ELF\t{relative}\tRUNPATH={expected_runpath}") for needed in NEEDED_PATTERN.findall(dynamic): if "/" in needed or needed in ("", ".", ".."): raise ValueError(f"unsafe DT_NEEDED entry in {relative}: {needed!r}") if is_system_dependency(needed): location = "system" else: dependency = library_dir / needed if not dependency.exists(): raise ValueError(f"unresolved DT_NEEDED in {relative}: {needed}") ensure_inside(dependency, library_dir, "DT_NEEDED dependency") location = "bundled" report.append(f"NEEDED\t{relative}\t{needed}\t{location}") version_info = command_output( ["readelf", "--version-info", "-W", os.fspath(path)] ) glibc_versions = required_glibc_versions(version_info) if maximum_glibc is not None: incompatible = sorted( version for version in glibc_versions if version > maximum_glibc ) if incompatible: rendered = ", ".join( ".".join(map(str, version)) for version in incompatible ) maximum = ".".join(map(str, maximum_glibc)) raise ValueError( f"{relative} requires GLIBC newer than {maximum}: {rendered}" ) if glibc_versions: newest = ".".join(map(str, max(glibc_versions))) report.append(f"ABI\t{relative}\tGLIBC_MAX={newest}") program_headers = command_output(["readelf", "-lW", os.fspath(executable)]) interpreter_match = INTERPRETER_PATTERN.search(program_headers) if interpreter_match is None: raise ValueError("echoiond has no ELF interpreter") interpreter = interpreter_match.group(1) if not re.fullmatch( r"/(?:[^/]+/)*(?:ld-linux[^/]*\.so[^/]*|ld64\.so[^/]*)", interpreter, ): raise ValueError(f"unexpected ELF interpreter: {interpreter}") report.append(f"INTERPRETER\tbin/echoiond\t{interpreter}\tsystem") return sorted(report) def write_report(lines: list[str], output: Path) -> None: output.parent.mkdir(parents=True, exist_ok=True) descriptor, temporary_name = tempfile.mkstemp( prefix=f".{output.name}.", dir=output.parent ) try: with os.fdopen(descriptor, "w", encoding="utf-8", newline="\n") as stream: stream.write("# Echoion runtime dependency report\n") stream.write("# Generated with readelf; no payload executable was run.\n") for line in lines: stream.write(f"{line}\n") os.chmod(temporary_name, 0o644) os.replace(temporary_name, output) except BaseException: try: os.unlink(temporary_name) except FileNotFoundError: pass raise def main() -> int: parser = argparse.ArgumentParser() parser.add_argument("--root", required=True, type=Path) parser.add_argument("--report", type=Path) parser.add_argument("--max-glibc", type=parse_version) arguments = parser.parse_args() if shutil.which("readelf") is None: parser.error("readelf is required") try: root = arguments.root.resolve(strict=True) report = validate(root, arguments.max_glibc) except (OSError, ValueError) as error: parser.error(str(error)) if arguments.report: write_report(report, arguments.report) else: print("\n".join(report)) return 0 if __name__ == "__main__": raise SystemExit(main())