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
|
#!/usr/bin/env python3
"""fix_pe_simple.py — PE header fixup for PIE-built UEFI bootloader
The -fPIE-built bootloader uses only PC-relative addressing, so it needs
zero absolute fixups. This script just sets proper PE flags:
- ImageBase (env IMAGE_BASE, default 0x10000000)
- Characteristics = 0x022e (RELOCS_STRIPPED)
- DllChar = 0x0160 (NX | DYNAMIC_BASE | HIGH_ENTROPY_VA)
- Clears .reloc DD (no relocations needed)
- Clears checksum (not signed)
"""
import struct, os, sys
def fix_pe(path):
try:
with open(path, 'rb') as f:
d = bytearray(f.read())
except IOError as e:
print(f" ERROR: cannot read {path}: {e}")
return False
po = struct.unpack('<I', d[0x3C:0x40])[0]
if d[po:po+4] != b'PE\x00\x00':
print(f" Not a PE file")
return False
coff = po + 4
opt = po + 24
magic = struct.unpack('<H', d[opt:opt+2])[0]
if magic != 0x20b:
print(f" Not PE32+")
return False
ib_env = os.environ.get('IMAGE_BASE', '0x10000000')
img_base = int(ib_env, 16) if ib_env.startswith('0x') else 0x10000000
struct.pack_into('<Q', d, opt+24, img_base)
struct.pack_into('<H', d, coff+18, 0x022e)
struct.pack_into('<H', d, opt+70, 0x0160)
struct.pack_into('<I', d, coff+8, 0)
struct.pack_into('<I', d, coff+12, 0)
struct.pack_into('<I', d, opt+64, 0)
dd = opt + 112
struct.pack_into('<II', d, dd + 5*8, 0, 0)
try:
with open(path, 'wb') as f:
f.write(d)
except IOError as e:
print(f" ERROR: cannot write {path}: {e}")
return False
print(f" Fixed: ImageBase={img_base:#010x} char=0x022e dll=0x0160 reloc=cleared")
return True
if __name__ == '__main__':
if len(sys.argv) < 2:
print(f"Usage: IMAGE_BASE=0x... {sys.argv[0]} <pe-path>")
sys.exit(1)
if not fix_pe(sys.argv[1]):
sys.exit(1)
|