Files

141 lines
5.4 KiB
Python

#!/usr/bin/env python3
"""Read-only PE32 import/export/RTTI evidence inventory, no third-party modules.
Addresses are preferred-base VAs, not relocation-adjusted runtime addresses.
Usage: python3 tools/binary/pe_inspect.py ../Original/OMT2.dll --symbols 'render|timer'
"""
import argparse
import hashlib
import json
from pathlib import Path
import re
import struct
class PE:
def __init__(self, path):
self.path = Path(path)
self.data = self.path.read_bytes()
if self.data[:2] != b'MZ':
raise ValueError('Missing MZ signature')
nt = self.u32(0x3c)
if self.data[nt:nt+4] != b'PE\0\0':
raise ValueError('Missing PE signature')
self.machine, count = struct.unpack_from('<HH', self.data, nt+4)
self.timestamp = self.u32(nt+8)
optsize = self.u16(nt+20)
opt = nt+24
if self.u16(opt) != 0x10b:
raise ValueError('This inspector supports PE32 only')
self.base = self.u32(opt+28)
self.entry = self.base+self.u32(opt+16)
self.header_size = self.u32(opt+60)
self.linker = list(self.data[opt+2:opt+4])
self.directories = [struct.unpack_from('<II', self.data, opt+96+8*i)
for i in range(min(16, self.u32(opt+92)))]
self.sections = []
for i in range(count):
off = opt+optsize+i*40
name = self.data[off:off+8].split(b'\0', 1)[0].decode('ascii')
vs, rva, size, raw = struct.unpack_from('<IIII', self.data, off+8)
self.sections.append(dict(name=name, virtual_size=vs, rva=rva,
raw_size=size, file_offset=raw))
def u16(self, off):
return struct.unpack_from('<H', self.data, off)[0]
def u32(self, off):
return struct.unpack_from('<I', self.data, off)[0]
def offset(self, rva):
if 0 <= rva < self.header_size:
return rva
for s in self.sections:
delta = rva-s['rva']
if 0 <= delta < s['raw_size']:
return s['file_offset']+delta
raise ValueError(f'RVA {rva:#x} has no file data')
def va(self, off):
if 0 <= off < self.header_size:
return self.base+off
for s in self.sections:
delta = off-s['file_offset']
if 0 <= delta < s['raw_size']:
return self.base+s['rva']+delta
raise ValueError(f'Offset {off:#x} has no virtual address')
def cstr(self, off):
end = self.data.index(0, off)
return self.data[off:end].decode('ascii', 'replace')
def exports(self):
rva, size = self.directories[0]
if not rva:
return []
off = self.offset(rva)
ordinal_base, count, names, functions, nameptrs, ordinals = struct.unpack_from(
'<IIIIII', self.data, off+16)
result = []
for i in range(names):
idx = self.u16(self.offset(ordinals)+2*i)
target = self.u32(self.offset(functions)+4*idx)
name = self.cstr(self.offset(self.u32(self.offset(nameptrs)+4*i)))
result.append(dict(name=name, ordinal=ordinal_base+idx,
va=f'0x{self.base+target:08x}', rva=target))
return result
def imports(self):
rva, _ = self.directories[1]
result = []
if not rva:
return result
off = self.offset(rva)
while any(self.data[off:off+20]):
original, _, _, name, first = struct.unpack_from('<IIIII', self.data, off)
dll = self.cstr(self.offset(name))
thunk = self.offset(original or first)
i = 0
while (v := self.u32(thunk+4*i)):
n = f'ordinal:{v & 0xffff}' if v & 0x80000000 else self.cstr(self.offset(v)+2)
result.append(dict(dll=dll, name=n, iat=f'0x{self.base+first+4*i:08x}'))
i += 1
off += 20
return result
def strings(self, pattern):
result = []
regex = re.compile(pattern, re.I)
for m in re.finditer(rb'[\x20-\x7e]{4,}', self.data):
value = m.group().decode('ascii')
if regex.search(value):
result.append(dict(value=value, offset=f'0x{m.start():x}',
va=f'0x{self.va(m.start()):08x}'))
return result
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('binary', type=Path)
parser.add_argument('--symbols', help='Regex filter for imports and exports')
parser.add_argument('--strings', help='Regex filter for ASCII strings with VAs')
args = parser.parse_args()
pe = PE(args.binary)
imports, exports = pe.imports(), pe.exports()
if args.symbols:
regex = re.compile(args.symbols, re.I)
imports = [x for x in imports if regex.search(x['name'])]
exports = [x for x in exports if regex.search(x['name'])]
out = dict(path=str(args.binary), sha256=hashlib.sha256(pe.data).hexdigest(),
machine=hex(pe.machine), linker=pe.linker, timestamp=pe.timestamp,
image_base=hex(pe.base), entry_point=hex(pe.entry),
clr_directory=pe.directories[14], sections=pe.sections,
imports=imports, exports=exports)
if args.strings:
out['strings'] = pe.strings(args.strings)
print(json.dumps(out, indent=2))
if __name__ == '__main__':
main()