#!/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)} PLUGIN_IDENTIFIER_PATTERN = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$") PLUGIN_VERSION_PATTERN = re.compile( r"^(?:0|[1-9][0-9]*)\." r"(?:0|[1-9][0-9]*)\." r"(?:0|[1-9][0-9]*)" r"(?:-(?:0|[1-9][0-9]*|[0-9A-Za-z-]*[A-Za-z-][0-9A-Za-z-]*)" r"(?:\.(?:0|[1-9][0-9]*|[0-9A-Za-z-]*[A-Za-z-][0-9A-Za-z-]*))*)?$" ) PLUGIN_RUNPATH = "$ORIGIN/../../../../../lib" 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 bootstrap_plugin_libraries(root: Path) -> list[Path]: plugin_root = root / "share/echoion/bootstrap-plugins" if not plugin_root.exists() and not plugin_root.is_symlink(): return [] if plugin_root.is_symlink() or not plugin_root.is_dir(): raise ValueError( f"bootstrap plugin root is not a real directory: {plugin_root}" ) libraries: list[Path] = [] for plugin_directory in sorted(plugin_root.iterdir()): plugin_id = plugin_directory.name if ( plugin_directory.is_symlink() or not plugin_directory.is_dir() or PLUGIN_IDENTIFIER_PATTERN.fullmatch(plugin_id) is None ): raise ValueError(f"invalid bootstrap plugin directory: {plugin_directory}") versions = sorted(plugin_directory.iterdir()) if len(versions) != 1: raise ValueError( f"bootstrap plugin {plugin_id!r} must contain exactly one version" ) version_directory = versions[0] if ( version_directory.is_symlink() or not version_directory.is_dir() or len(version_directory.name) > 64 or PLUGIN_VERSION_PATTERN.fullmatch(version_directory.name) is None ): raise ValueError( f"invalid bootstrap plugin version: {version_directory}" ) expected = version_directory / f"{plugin_id}.so" entries = sorted(version_directory.iterdir()) if entries != [expected]: raise ValueError( f"bootstrap plugin {plugin_id!r} version " f"{version_directory.name!r} has unexpected files" ) if expected.is_symlink() or not expected.is_file() or not is_elf(expected): raise ValueError(f"missing regular bootstrap plugin ELF: {expected}") libraries.append(expected) return libraries def validate( root: Path, maximum_glibc: tuple[int, ...] | None = None, forbidden_content_prefixes: tuple[bytes, ...] = (), ) -> list[str]: executable = root / "bin/echoiond" updater = root / "bin/echoion-updater" core = root / "lib/Echoion.ts" executable_dir = (root / "bin").resolve(strict=True) library_dir = (root / "lib").resolve(strict=True) for required in (executable, updater, 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] = [] for path in sorted(executable_dir.iterdir()): if path.is_symlink() or not path.is_file() or not is_elf(path): raise ValueError(f"unexpected non-ELF entry in bin/: {path}") elf_files.append(path) 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) plugin_files = set(bootstrap_plugin_libraries(root)) elf_files.extend(sorted(plugin_files)) report: list[str] = [] for path in elf_files: relative = path.relative_to(root).as_posix() contents = path.read_bytes() for prefix in forbidden_content_prefixes: if prefix in contents: rendered = os.fsdecode(prefix) raise ValueError( f"{relative} embeds forbidden build/source path: {rendered}" ) 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) if path in plugin_files: expected_runpath = PLUGIN_RUNPATH elif path.parent == executable_dir: expected_runpath = "$ORIGIN/../lib" else: expected_runpath = "$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}") if path.parent == executable_dir: program_headers = command_output(["readelf", "-lW", os.fspath(path)]) interpreter_match = INTERPRETER_PATTERN.search(program_headers) if interpreter_match is None: raise ValueError(f"{relative} 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 in {relative}: {interpreter}") report.append(f"INTERPRETER\t{relative}\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) parser.add_argument( "--forbid-content-prefix", action="append", default=[], help="reject ELF files containing this build/source path (repeatable)", ) arguments = parser.parse_args() if shutil.which("readelf") is None: parser.error("readelf is required") try: root = arguments.root.resolve(strict=True) forbidden_content_prefixes = tuple( os.fsencode(prefix) for prefix in arguments.forbid_content_prefix if prefix ) report = validate( root, arguments.max_glibc, forbidden_content_prefixes, ) 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())