"""Inspect thin macOS executables without running foreign code.""" import struct def validate_macos(path, target, maximum_minimum=(13, 0, 0)): cpus = {"aarch64-apple-darwin": 0x100000C, "x86_64-apple-darwin": 0x1000007} with path.open("rb") as stream: header = stream.read(32) if len(header) != 32: raise ValueError("Truncated Mach-O header") magic, cpu, _, kind, count, size, _, _ = struct.unpack("<8I", header) if magic != 0xFEEDFACF or cpu != cpus.get(target) or kind != 2: raise ValueError("Expected a matching thin 64-bit Mach-O executable") if size > 16 * 1024 * 1024: raise ValueError("Mach-O load commands exceed limit") commands = stream.read(size) if len(commands) != size: raise ValueError("Truncated Mach-O load commands") offset = 0 minimum = None dependencies = [] for _ in range(count): if offset + 8 > size: raise ValueError("Truncated Mach-O command") command, length = struct.unpack_from("<2I", commands, offset) if length < 8 or offset + length > size: raise ValueError("Invalid Mach-O command size") data = commands[offset:offset + length] if command == 0x32: if length < 24 or struct.unpack_from("> 16, (encoded >> 8) & 255, encoded & 255) elif command in (0xC, 0x80000018, 0x8000001F, 0x80000023): if length < 24: raise ValueError("Truncated Mach-O dependency") start = struct.unpack_from("= length or b"\0" not in data[start:]: raise ValueError("Invalid Mach-O dependency name") name = data[start:].split(b"\0", 1)[0].decode("utf-8") if not name.startswith(("/usr/lib/", "/System/Library/")) or ".." in name.split("/"): raise ValueError(f"Non-system macOS dependency: {name}") dependencies.append(name) offset += length if offset != size or minimum is None or minimum > maximum_minimum or not dependencies: raise ValueError("Invalid or incompatible macOS deployment/load commands") return {"minimum_macos": ".".join(map(str, minimum)), "dependencies": dependencies}