-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidate_build.py
More file actions
203 lines (183 loc) · 9.79 KB
/
Copy pathvalidate_build.py
File metadata and controls
203 lines (183 loc) · 9.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
#!/usr/bin/env python3
"""Static integrity/security validation for the portable Windows executable."""
from __future__ import annotations
import argparse
import struct
from pathlib import Path
from finalize_pe import pe_checksum, checksum_offset
def c_string(data: bytes, offset: int) -> str:
end = data.find(b"\0", offset)
if end < 0:
raise ValueError("unterminated PE string")
return data[offset:end].decode("ascii", "strict")
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("executable", type=Path)
args = parser.parse_args()
data = args.executable.read_bytes()
if data[:2] != b"MZ":
raise SystemExit("FAIL: missing DOS header")
pe = struct.unpack_from("<I", data, 0x3C)[0]
if data[pe:pe + 4] != b"PE\0\0":
raise SystemExit("FAIL: missing PE signature")
machine, sections = struct.unpack_from("<HH", data, pe + 4)
if machine != 0x8664:
raise SystemExit("FAIL: executable is not Windows x64")
optional_size = struct.unpack_from("<H", data, pe + 20)[0]
symbol_table, symbol_count = struct.unpack_from("<II", data, pe + 12)
if symbol_table or symbol_count:
raise SystemExit("FAIL: final PE retains a COFF symbol table")
if not (5 <= sections <= 8):
raise SystemExit(f"FAIL: non-canonical PE section count: {sections}")
optional = pe + 24
if struct.unpack_from("<H", data, optional)[0] != 0x20B:
raise SystemExit("FAIL: executable is not PE32+")
entry = struct.unpack_from("<I", data, optional + 16)[0]
subsystem = struct.unpack_from("<H", data, optional + 68)[0]
dll_flags = struct.unpack_from("<H", data, optional + 70)[0]
stored_checksum = struct.unpack_from("<I", data, checksum_offset(data))[0]
if not entry or subsystem != 2:
raise SystemExit("FAIL: missing Windows GUI entry point")
if (dll_flags & 0x140) != 0x140:
raise SystemExit("FAIL: ASLR/NX flags are missing")
if stored_checksum != pe_checksum(data, checksum_offset(data)):
raise SystemExit("FAIL: PE checksum mismatch")
section_table = optional + optional_size
section_rows: list[tuple[int, int, int, int, str, int]] = []
for index in range(sections):
at = section_table + index * 40
name = data[at:at + 8].rstrip(b"\0").decode("ascii", "replace")
virtual_size, rva, raw_size, raw = struct.unpack_from("<IIII", data, at + 8)
characteristics = struct.unpack_from("<I", data, at + 36)[0]
section_rows.append((rva, max(virtual_size, raw_size), raw, raw_size, name,
characteristics))
section_names = {row[4] for row in section_rows}
if ".text" not in section_names or ".rdata" not in section_names or ".pdata" not in section_names:
raise SystemExit(f"FAIL: canonical x64 code/data/unwind sections missing: {sorted(section_names)}")
ordered_virtual = sorted(section_rows)
for left, right in zip(ordered_virtual, ordered_virtual[1:]):
if left[0] + left[1] > right[0]:
raise SystemExit(f"FAIL: overlapping virtual sections {left[4]} and {right[4]}")
ordered_raw = sorted((row for row in section_rows if row[3]), key=lambda row: row[2])
for left, right in zip(ordered_raw, ordered_raw[1:]):
if left[2] + left[3] > right[2]:
raise SystemExit(f"FAIL: overlapping raw sections {left[4]} and {right[4]}")
if not any(start <= entry < start + span and (flags & 0x20000000)
for start, span, _, _, _, flags in section_rows):
raise SystemExit("FAIL: entry point is not inside an executable section")
def rva_to_offset(rva: int) -> int:
for start, span, raw, raw_size, _, _ in section_rows:
if start <= rva < start + span:
delta = rva - start
if delta >= raw_size:
raise ValueError(f"RVA 0x{rva:x} points into uninitialized section data")
return raw + delta
raise ValueError(f"unmapped RVA 0x{rva:x}")
directory_count = struct.unpack_from("<I", data, optional + 108)[0]
if directory_count < 6:
raise SystemExit("FAIL: truncated PE data directories")
imports_rva, imports_size = struct.unpack_from("<II", data, optional + 120)
resources_rva, resources_size = struct.unpack_from("<II", data, optional + 128)
exception_rva, exception_size = struct.unpack_from("<II", data, optional + 136)
security_offset, security_size = struct.unpack_from("<II", data, optional + 144)
if not imports_rva or not resources_rva or not resources_size:
raise SystemExit("FAIL: import/resource directory missing")
if not exception_rva or not exception_size:
raise SystemExit("FAIL: Windows x64 unwind directory missing")
if exception_size % 12:
raise SystemExit("FAIL: malformed Windows x64 runtime-function table")
exception_offset = rva_to_offset(exception_rva)
if not any(name == ".pdata" and raw <= exception_offset < raw + raw_size
for _, _, raw, raw_size, name, _ in section_rows):
raise SystemExit("FAIL: exception directory is not mapped into .pdata")
if security_offset or security_size:
raise SystemExit("FAIL: release expectation changed: Authenticode directory is non-empty")
imports: dict[str, list[str]] = {}
descriptor = rva_to_offset(imports_rva)
while True:
original, timestamp, chain, name_rva, first = struct.unpack_from("<IIIII", data, descriptor)
if not (original or timestamp or chain or name_rva or first):
break
dll = c_string(data, rva_to_offset(name_rva)).upper()
thunk_rva = original or first
thunk = rva_to_offset(thunk_rva)
names: list[str] = []
while True:
value = struct.unpack_from("<Q", data, thunk)[0]
if not value:
break
if value & (1 << 63):
names.append(f"ordinal:{value & 0xffff}")
else:
hint_name = rva_to_offset(value)
names.append(c_string(data, hint_name + 2))
thunk += 8
imports[dll] = names
descriptor += 20
expected_dlls = {"KERNEL32.DLL", "USER32.DLL", "GDI32.DLL"}
if set(imports) != expected_dlls:
raise SystemExit(f"FAIL: unexpected DLL imports: {sorted(imports)}")
forbidden = (
"regopen", "regset", "regcreate", "regdelete", "shellexecute",
"createfile", "writefile", "deletefile", "movefile", "copyfile",
"createprocess", "winexec", "openprocess", "writeprocessmemory",
"createremotethread", "createservice", "startservice"
)
for dll, names in imports.items():
for name in names:
if name.lower().startswith(forbidden):
raise SystemExit(f"FAIL: forbidden persistent/system action import {dll}!{name}")
resource_base = rva_to_offset(resources_rva)
leaves: dict[tuple[int, int], tuple[int, int]] = {}
def walk(directory_relative: int, path: tuple[int, ...]) -> None:
directory = resource_base + directory_relative
named, ids = struct.unpack_from("<HH", data, directory + 12)
entries = directory + 16
for index in range(named + ids):
name_or_id, child = struct.unpack_from("<II", data, entries + index * 8)
if name_or_id & 0x80000000:
continue
item = name_or_id
if child & 0x80000000:
walk(child & 0x7FFFFFFF, path + (item,))
else:
leaf = resource_base + child
payload_rva, size = struct.unpack_from("<II", data, leaf)
if len(path) >= 1:
leaves[(path[0], path[1] if len(path) > 1 else item)] = (
rva_to_offset(payload_rva), size)
walk(0, ())
required = {(10, 101), (14, 1), (16, 1), (24, 1)}
if not required.issubset(leaves):
raise SystemExit(f"FAIL: required embedded resources missing: {sorted(required - set(leaves))}")
if not any(kind == 3 for kind, _ in leaves):
raise SystemExit("FAIL: icon image resources missing")
ptx_offset, ptx_size = leaves[(10, 101)]
ptx = data[ptx_offset:ptx_offset + ptx_size].decode("ascii", "strict")
if ptx.count(".version") != 1:
raise SystemExit("FAIL: malformed combined PTX module header")
kernels = ("mm_relax", "mm_rank_dynamics", "mm_fem_clear_force",
"mm_fem_tie_force", "mm_fem_hex8_force", "mm_fem_integrate")
for kernel in kernels:
if f".entry {kernel}" not in ptx:
raise SystemExit(f"FAIL: embedded PTX missing {kernel}")
if "mm_fem_hex8_force_param_13" not in ptx:
raise SystemExit("FAIL: embedded FEM kernel lacks Maxwell history/update arguments")
if ptx_size < 80000:
raise SystemExit("FAIL: embedded PTX unexpectedly small for audited full-car Maxwell kernels")
manifest_offset, manifest_size = leaves[(24, 1)]
manifest = data[manifest_offset:manifest_offset + manifest_size]
if b'version="3.1.0.0"' not in manifest or b'level="asInvoker"' not in manifest:
raise SystemExit("FAIL: manifest version/privilege policy mismatch")
version_offset, version_size = leaves[(16, 1)]
version = data[version_offset:version_offset + version_size]
if version.count("3.1.0.0".encode("utf-16le")) < 2:
raise SystemExit("FAIL: version resource string mismatch")
print("PASS: Windows x64 GUI entry, checksum, ASLR/NX")
print("PASS: canonical stripped COFF/x64 sections and unwind directory")
print(f"PASS: icon, v3.1.0 manifest/version, {len(kernels)} embedded CUDA kernels")
print("PASS: imports limited to KERNEL32/USER32/GDI32; no persistence, network, process-launch or CRT DLL")
print("INFO: Authenticode security directory is empty (unsigned release)")
print(f"PASS: PTX payload {ptx_size} bytes; executable {len(data)} bytes")
if __name__ == "__main__":
main()