| 1 | import argparse |
| 2 | import hashlib |
| 3 | import json |
| 4 | import os |
| 5 | from pathlib import Path |
| 6 | import re |
| 7 | import shutil |
| 8 | import struct |
| 9 | import subprocess |
| 10 | import sys |
| 11 | |
| 12 | |
| 13 | MACHINES = {0x014C: "windows-x86", 0x8664: "windows-x64", 0xAA64: "windows-arm64"} |
| 14 | |
| 15 | |
| 16 | def pe_identity(data): |
| 17 | if len(data) < 64 or data[:2] != b"MZ": |
| 18 | raise ValueError("expected a Windows PE executable") |
| 19 | offset = struct.unpack_from("<I", data, 60)[0] |
| 20 | if offset + 24 > len(data) or data[offset:offset + 4] != b"PE\0\0": |
| 21 | raise ValueError("invalid PE signature or COFF header") |
| 22 | machine, _, _, _, _, optional_size, characteristics = struct.unpack_from("<HHIIIHH", data, offset + 4) |
| 23 | if machine not in MACHINES or not characteristics & 0x0002: |
| 24 | raise ValueError("unsupported machine or non-executable PE image") |
| 25 | optional = offset + 24 |
| 26 | if optional_size < 2 or optional + optional_size > len(data): |
| 27 | raise ValueError("truncated PE optional header") |
| 28 | magic = struct.unpack_from("<H", data, optional)[0] |
| 29 | if magic == 0x010B: |
| 30 | count_offset, directories_offset = 92, 96 |
| 31 | elif magic == 0x020B: |
| 32 | count_offset, directories_offset = 108, 112 |
| 33 | else: |
| 34 | raise ValueError("unsupported PE optional-header format") |
| 35 | if count_offset + 4 > optional_size: |
| 36 | raise ValueError("truncated PE data-directory count") |
| 37 | count = struct.unpack_from("<I", data, optional + count_offset)[0] |
| 38 | if directories_offset + count * 8 > optional_size: |
| 39 | raise ValueError("truncated PE data-directory table") |
| 40 | delay_rva, delay_size = (0, 0) |
| 41 | if count > 13: |
| 42 | delay_rva, delay_size = struct.unpack_from("<II", data, optional + directories_offset + 13 * 8) |
| 43 | return MACHINES[machine], delay_rva, delay_size |
| 44 | |
| 45 | |
| 46 | def parse_imports(raw): |
| 47 | if not re.search(r"file format (coff|pei)-(x86-64|arm64|aarch64|i386)", raw, flags=re.I): |
| 48 | raise ValueError("unrecognized Windows object-dumper format") |
| 49 | if "The Import Tables:" not in raw: |
| 50 | raise ValueError("no readable static import table") |
| 51 | table = raw.split("The Import Tables:", 1)[1] |
| 52 | table = re.split(r"^(?:The )?(?:Export|Delay Import) Tables?:", table, maxsplit=1, flags=re.M)[0] |
| 53 | imports = set() |
| 54 | dll = None |
| 55 | for line in table.splitlines(): |
| 56 | if not line.strip(): |
| 57 | continue |
| 58 | if re.fullmatch(r"\s*lookup [0-9a-fA-F]+ time [0-9a-fA-F]+ fwd [0-9a-fA-F]+ name [0-9a-fA-F]+ addr [0-9a-fA-F]+\s*", line): |
| 59 | dll = None |
| 60 | continue |
| 61 | if dll and re.fullmatch(r"\s*Hint/Ord\s+Name\s*", line): |
| 62 | continue |
| 63 | match = re.fullmatch(r"\s*DLL Name: (\S+)\s*", line) |
| 64 | if match: |
| 65 | dll = match[1].lower() |
| 66 | continue |
| 67 | match = re.fullmatch(r"\s+(\d+)\s+(\S+)\s*", line) |
| 68 | if dll and match: |
| 69 | imports.add((dll, match[2])) |
| 70 | elif dll and re.fullmatch(r"\s+\d+\s*", line): |
| 71 | imports.add((dll, "#" + line.strip())) |
| 72 | else: |
| 73 | raise ValueError(f"unrecognized import-table row: {line.strip()}") |
| 74 | if not imports: |
| 75 | raise ValueError("zero static imports parsed") |
| 76 | return imports |
| 77 | |
| 78 | |
| 79 | def main(): |
| 80 | parser = argparse.ArgumentParser(description="Qualify PE static imports against a reviewed OS and architecture baseline.") |
| 81 | parser.add_argument("binaries", nargs="+", type=Path) |
| 82 | parser.add_argument("--baseline", type=Path, default=Path(__file__).with_name("windows-import-floor.json")) |
| 83 | parser.add_argument("--output", type=Path, required=True) |
| 84 | parser.add_argument("--objdump") |
| 85 | parser.add_argument("--expected-machine", choices=tuple(MACHINES.values())) |
| 86 | args = parser.parse_args() |
| 87 | args.output.mkdir(parents=True, exist_ok=True) |
| 88 | receipts = [] |
| 89 | try: |
| 90 | baseline = json.loads(args.baseline.read_text(encoding="utf-8")) |
| 91 | profiles = baseline["profiles"] |
| 92 | objdump = args.objdump or shutil.which("llvm-objdump") |
| 93 | if not objdump: |
| 94 | candidate = Path(os.environ.get("ProgramFiles", "C:/Program Files")) / "LLVM/bin/llvm-objdump.exe" |
| 95 | if candidate.is_file(): |
| 96 | objdump = str(candidate) |
| 97 | if not objdump: |
| 98 | raise ValueError("llvm-objdump is required; no import check was performed") |
| 99 | except (OSError, ValueError, KeyError) as error: |
| 100 | (args.output / "receipt.json").write_text(json.dumps({"result": "FAIL", "error": str(error)}, indent=2) + "\n", encoding="utf-8") |
| 101 | print(f"Windows import check failed: {error}", file=sys.stderr) |
| 102 | return 1 |
| 103 | for index, binary in enumerate(args.binaries): |
| 104 | receipt = {"binary": str(binary), "result": "FAIL"} |
| 105 | receipts.append(receipt) |
| 106 | try: |
| 107 | data = binary.read_bytes() |
| 108 | receipt["sha256"] = hashlib.sha256(data).hexdigest() |
| 109 | machine, delay_rva, delay_size = pe_identity(data) |
| 110 | receipt.update(machine=machine, delayImportRva=delay_rva, delayImportSize=delay_size) |
| 111 | result = subprocess.run([objdump, "-p", str(binary)], check=False, capture_output=True, text=True) |
| 112 | (args.output / f"{index}-{binary.name}.imports.txt").write_text(result.stdout, encoding="utf-8") |
| 113 | (args.output / f"{index}-{binary.name}.stderr.txt").write_text(result.stderr, encoding="utf-8") |
| 114 | receipt["objdumpExitCode"] = result.returncode |
| 115 | if result.returncode: |
| 116 | raise ValueError("object dumper failed; raw output is retained") |
| 117 | if args.expected_machine and machine != args.expected_machine: |
| 118 | raise ValueError(f"expected {args.expected_machine}, got {machine}") |
| 119 | if delay_rva or delay_size: |
| 120 | raise ValueError("delay-load imports require explicit qualification; no table was silently excluded") |
| 121 | imports = parse_imports(result.stdout) |
| 122 | profile = profiles.get(machine) |
| 123 | if not profile: |
| 124 | raise ValueError(f"no reviewed baseline profile for {machine}") |
| 125 | receipt.update(baselineFloor=profile["floor"], qualification=profile["qualification"]) |
| 126 | allowed = {(dll.lower(), symbol) for dll, symbols in profile["imports"].items() for symbol in symbols} |
| 127 | unknown = sorted(imports - allowed) |
| 128 | receipt.update(imports=sorted(imports), unqualified=unknown) |
| 129 | if profile["qualification"]["result"] != "PASS": |
| 130 | raise ValueError(f"baseline profile is not qualified for {machine}") |
| 131 | if unknown: |
| 132 | raise ValueError(f"{len(unknown)} import pairs are unqualified") |
| 133 | receipt.update(result="PASS", floor=profile["floor"]) |
| 134 | except (OSError, ValueError, KeyError, struct.error) as error: |
| 135 | receipt["error"] = str(error) |
| 136 | finally: |
| 137 | (args.output / "receipt.json").write_text(json.dumps(receipts, indent=2) + "\n", encoding="utf-8") |
| 138 | print(f"{receipt['result']}: {binary}: {len(receipt.get('imports', []))} static imports: {receipt.get('error', receipt.get('floor', 'unqualified profile'))}") |
| 139 | for library, symbol in receipt.get("unqualified", []): |
| 140 | print(f" {library}!{symbol}") |
| 141 | return int(any(receipt["result"] != "PASS" for receipt in receipts)) |
| 142 | |
| 143 | |
| 144 | if __name__ == "__main__": |
| 145 | sys.exit(main()) |
| 146 |