-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfinalize_pe.py
More file actions
56 lines (44 loc) · 1.95 KB
/
Copy pathfinalize_pe.py
File metadata and controls
56 lines (44 loc) · 1.95 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
#!/usr/bin/env python3
"""Set and verify the PE checksum without third-party packages."""
from __future__ import annotations
import argparse
import struct
from pathlib import Path
def checksum_offset(data: bytes) -> int:
pe_offset = struct.unpack_from("<I", data, 0x3C)[0]
if data[pe_offset:pe_offset + 4] != b"PE\0\0":
raise ValueError("invalid PE signature")
optional_offset = pe_offset + 24
if struct.unpack_from("<H", data, optional_offset)[0] != 0x20B:
raise ValueError("expected PE32+")
return optional_offset + 64
def timestamp_offset(data: bytes) -> int:
pe_offset = struct.unpack_from("<I", data, 0x3C)[0]
return pe_offset + 8
def pe_checksum(data: bytes, field_offset: int) -> int:
total = 0
padded = data + (b"\0" if len(data) & 1 else b"")
for offset in range(0, len(padded), 2):
word = 0 if field_offset <= offset < field_offset + 4 else struct.unpack_from("<H", padded, offset)[0]
total = (total + word) & 0xFFFFFFFF
total = (total & 0xFFFF) + (total >> 16)
total = (total & 0xFFFF) + (total >> 16)
return (total + len(data)) & 0xFFFFFFFF
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("executable", type=Path)
args = parser.parse_args()
data = bytearray(args.executable.read_bytes())
# Fixed UTC build epoch (2026-08-23) makes identical sources reproducible.
struct.pack_into("<I", data, timestamp_offset(data), 1787443200)
field_offset = checksum_offset(data)
struct.pack_into("<I", data, field_offset, 0)
checksum = pe_checksum(data, field_offset)
struct.pack_into("<I", data, field_offset, checksum)
args.executable.write_bytes(data)
final = args.executable.read_bytes()
if struct.unpack_from("<I", final, field_offset)[0] != pe_checksum(final, field_offset):
raise SystemExit("checksum verification failed")
print(f"checksum=0x{checksum:08x}")
if __name__ == "__main__":
main()