PE Triage: Sections, Imports, Imphash and Timestamps
The reverse-engineering course built and parsed PE files field by field: the DOS and NT headers and the section table, imports, exports and the IAT, and imports as behaviour hints. A malware analyst doing triage doesn't read headers field by field. They want a one-screen summary that answers: does this look like a normal program, what can it probably do, and is it like anything we have seen? That summary is what tools such as pestudio, PE-bear, Detect It Easy and Mandiant's capa produce. This lesson builds a small one, on a synthetic PE file built in the browser, and explains each finding.
What triage looks at
| Feature | Normal | Suspicious |
|---|---|---|
| Section names | .text, .rdata, .data, .pdata, .rsrc, .reloc |
unusual names (.lab, UPX0, random strings), or none readable |
| Section permissions | code R-X, data RW-, constants R-- |
a section that is both writable and executable (RWX) |
| Section entropy | code about 5 to 6.5, data lower | above about 7.2 in a large section (entropy) |
| Imports | dozens of functions from several DLLs | very few (only LoadLibraryA/GetProcAddress: resolved at run time), or a telling combination |
| Compile timestamp | plausible build date | in the future, before the compiler existed, or a known fixed value of some toolchains |
| Size of raw vs virtual data | similar | raw size 0 with large virtual size (filled at run time: unpacking) |
| Signature, version info, manifest | present for commercial software | missing, or claiming a vendor while unsigned |
- imphash (import hash, introduced by Mandiant in 2014): the MD5 of the import list, normalised as lowercase
dll.functionentries (DLL name without its extension) joined with commas, in import-table order. Builds of the same source with the same toolchain often share an imphash even when everything else changes, so it clusters samples. - capa: maps features (imports, strings, byte patterns, API call sequences in the disassembly) to readable capabilities ("receive data", "write file", "persist via Run registry key") with ATT&CK IDs.
A triage report from bytes
The example builds a synthetic 64-bit PE: a small .text, an .rdata with a real import table (three DLLs, nine functions) and a configuration string under lab.test, a .data section, and a section called .lab that is readable, writable and executable and holds 4 KiB of random bytes standing in for packed code. Nothing in it runs: the "code" is a few repeated instruction bytes. Then the parser prints a triage report.
import struct, hashlib, math, random, datetime
from collections import Counter
IMPORTS = {"KERNEL32.dll": ["CreateFileW", "WriteFile", "VirtualAlloc", "GetComputerNameW"],
"WININET.dll": ["InternetOpenA", "InternetOpenUrlA", "InternetReadFile"],
"ADVAPI32.dll": ["RegOpenKeyExW", "RegSetValueExW"]}
def build_rdata(base):
"""Import directory, lookup tables, hint/name entries and DLL names, laid out from RVA `base`."""
n = len(IMPORTS)
desc_size = 20 * (n + 1)
tables, names, layout = bytearray(), bytearray(), []
thunk_area = desc_size
total_thunks = sum(len(f) + 1 for f in IMPORTS.values())
name_area = thunk_area + 2 * 8 * total_thunks # ILT + IAT, 8 bytes per entry (PE32+)
ilt, iat, hn = bytearray(), bytearray(), bytearray()
for dll, funcs in IMPORTS.items():
ilt_rva = base + thunk_area + len(ilt)
iat_rva = base + thunk_area + 8 * total_thunks + len(iat)
for f in funcs:
entry = base + name_area + len(hn)
hn += struct.pack("<H", 0) + f.encode() + b"\0"
if len(hn) % 2: hn += b"\0"
ilt += struct.pack("<Q", entry); iat += struct.pack("<Q", entry)
ilt += bytes(8); iat += bytes(8)
layout.append((ilt_rva, iat_rva, dll))
dllnames = bytearray(); name_rvas = []
for _, _, dll in layout:
name_rvas.append(base + name_area + len(hn) + len(dllnames))
dllnames += dll.encode() + b"\0"
desc = b"".join(struct.pack("<IIIII", i, 0, 0, nm, a) for (i, a, _), nm in zip(layout, name_rvas)) + bytes(20)
return bytes(desc + ilt + iat + hn + dllnames), desc_size
def build_pe(stamp):
falign, salign, hdr = 0x200, 0x1000, 0x400
rdata, isize = build_rdata(0x2000)
secs = [(b".text", 0x1000, 0x60000020, bytes.fromhex("4883ec28") + bytes.fromhex("488d0d00000000e8000000004885c0740a") * 24 + bytes.fromhex("4883c428c3")),
(b".rdata", 0x2000, 0x40000040, rdata + b"labagent config v1 server=update.beacon.lab.test\0"),
(b".data", 0x3000, 0xC0000040, bytes(64)),
(b".lab", 0x4000, 0xE0000020, random.Random(13).randbytes(0x1000))] # R W X, random bytes
dos = bytearray(64); dos[0:2] = b"MZ"; struct.pack_into("<I", dos, 0x3C, 0x80)
stub = b"\0" * (0x80 - 64)
coff = struct.pack("<HHIIIHH", 0x8664, len(secs), stamp, 0, 0, 240, 0x0022)
opt = struct.pack("<HBBIIIIIQIIHHHHHHIIIIHHQQQQII", 0x20B, 14, 40, 0x200, 0x1200, 0, 0x1000, 0x1000,
0x140000000, salign, falign, 6, 0, 0, 0, 6, 0, 0, 0x5000, hdr, 0, 2, 0x8160,
0x100000, 0x1000, 0x100000, 0x1000, 0, 16)
dirs = bytearray(16 * 8); struct.pack_into("<II", dirs, 8, 0x2000, isize) # directory 1: imports
table, body, raw = b"", b"", hdr
for name, rva, flags, content in secs:
rsize = -(-len(content) // falign) * falign
table += struct.pack("<8sIIIIIIHHI", name, len(content), rva, rsize, raw, 0, 0, 0, 0, flags)
body += content.ljust(rsize, b"\0"); raw += rsize
head = bytes(dos) + stub + b"PE\0\0" + coff + opt + bytes(dirs) + table
return head.ljust(hdr, b"\0") + body
pe = build_pe(int(datetime.datetime(2030, 5, 1, tzinfo=datetime.timezone.utc).timestamp()))
def entropy(d):
n = len(d)
return abs(-sum(c / n * math.log2(c / n) for c in Counter(d).values())) if n else 0.0
def triage(data):
lfanew = struct.unpack_from("<I", data, 0x3C)[0]
_, nsec, stamp, _, _, optsize, _ = struct.unpack_from("<HHIIIHH", data, lfanew + 4)
opt = lfanew + 24
imp_rva = struct.unpack_from("<I", data, opt + 112 + 8)[0] # data directory 1 (PE32+)
secs = []
for i in range(nsec):
name, vsize, va, rsize, rptr, *_, fl = struct.unpack_from("<8sIIIIIIHHI", data, opt + optsize + 40 * i)
secs.append((name.rstrip(b"\0").decode(), va, vsize, rptr, rsize, fl))
def off(rva):
for _, va, vs, rp, rs, _ in secs:
if va <= rva < va + max(vs, rs):
return rva - va + rp
def cstr(rva):
o = off(rva); return data[o:data.index(b"\0", o)].decode()
when = datetime.datetime.fromtimestamp(stamp, datetime.timezone.utc)
print(f"compile timestamp: {when:%Y-%m-%d %H:%M} UTC")
print("section vsize entropy perms notes")
for name, va, vs, rp, rs, fl in secs:
perms = "".join(c if fl & bit else "-" for c, bit in (("R", 0x40000000), ("W", 0x80000000), ("X", 0x20000000)))
h = entropy(data[rp:rp + min(vs, rs)])
notes = []
if name not in (".text", ".rdata", ".data", ".rsrc", ".reloc", ".pdata"): notes.append("non-standard name")
if "W" in perms and "X" in perms: notes.append("writable AND executable")
if h > 7.2: notes.append("high entropy: packed/encrypted?")
print(f"{name:<8} {vs:6d} {h:7.2f} {perms} {'; '.join(notes)}")
imports, o = {}, off(imp_rva)
while True:
ilt, _, _, name_rva, iat = struct.unpack_from("<IIIII", data, o)
if name_rva == 0:
break
funcs, t = [], off(ilt or iat)
while (entry := struct.unpack_from("<Q", data, t)[0]):
funcs.append(f"#{entry & 0xFFFF}" if entry >> 63 else cstr((entry & 0x7FFFFFFF) + 2))
t += 8
imports[cstr(name_rva)] = funcs
o += 20
return when, imports
when, imports = triage(pe)
imphash_input = ",".join(f"{dll.lower().rsplit('.', 1)[0]}.{f.lower()}" for dll, fs in imports.items() for f in fs)
print("imports:", {dll: len(fs) for dll, fs in imports.items()})
print("imphash:", hashlib.md5(imphash_input.encode()).hexdigest())
HINTS = {"InternetOpenUrlA": "downloads from a URL", "InternetReadFile": "reads data from the network",
"RegSetValueExW": "writes registry values (persistence?)", "VirtualAlloc": "allocates memory (unpacking?)",
"GetComputerNameW": "collects host information", "WriteFile": "writes files"}
for f in (f for fs in imports.values() for f in fs):
if f in HINTS:
print(f" hint: {f:<18} {HINTS[f]}")
now = datetime.datetime(2026, 1, 15, tzinfo=datetime.timezone.utc)
if when > now:
print("anomaly: compile timestamp is in the future (forged or wrong clock)")compile timestamp: 2030-05-01 00:00 UTC
section vsize entropy perms notes
.text 417 2.68 R-X
.rdata 511 3.60 R--
.data 64 0.00 RW-
.lab 4096 7.96 RWX non-standard name; writable AND executable; high entropy: packed/encrypted?
imports: {'KERNEL32.dll': 4, 'WININET.dll': 3, 'ADVAPI32.dll': 2}
imphash: b91aa3bc9567e611fd7937cb4ae0e750
hint: WriteFile writes files
hint: VirtualAlloc allocates memory (unpacking?)
hint: GetComputerNameW collects host information
hint: InternetOpenUrlA downloads from a URL
hint: InternetReadFile reads data from the network
hint: RegSetValueExW writes registry values (persistence?)
anomaly: compile timestamp is in the future (forged or wrong clock)
Each line is a lead:
.labcombines three findings at once: a non-standard name,RWXpermissions (a region that code is written into and then run from), and entropy near 8. Together they say "packed or encrypted payload, unpacked at run time", whichVirtualAllocin the imports supports.- The imports tell a story without any disassembly: read host information, download from a URL, write files and registry values. That is the capability set of a downloader with persistence. Each is also used by legitimate programs; the combination is the signal.
- The imphash,
b91aa3bc…, is exactly what the Python librarypefile(get_imphash()) computes for this file, and what YARA'spe.imphash()returns. Search it in your sample repository to find relatives built from the same code. - The compile timestamp is in 2030. Timestamps are written by the linker and trivially changed afterwards; a future date proves tampering or a broken build clock, and a date that matches other samples can link them.
How PE features are used for detection
- YARA rules on structure:
pe.number_of_sections, section names and characteristics,pe.imphash(),pe.imports()andmath.entropy()of a section (YARA modules). - Clustering by imphash, rich header hash and section hashes in a sample repository.
- Application control and EDR score unsigned executables with
RWXsections and few imports higher.
How developers avoid looking like malware
- Sign releases (Authenticode), include version information, and don't ship
RWXsections (modern linkers don't create them; just-in-time compilers allocate such memory at run time instead). - Don't pack commercial software with packers that malware also uses; false positives cost support time.
- Keep build timestamps honest, or deterministic (the undocumented MSVC switch
/Brepromakes reproducible builds with a hash in place of the date).
Pitfalls
- Import lists lie in both directions. Run-time resolution hides imports; unused imports pulled in by a library look scary. Confirm in code or behaviour.
- imphash collisions by toolchain. Tiny programs from the same compiler and runtime, or installers made with the same framework, share imphashes without being related.
- Ordinals. Imports by ordinal (
#12) have no name; imphash tools map well-known ordinals for a few DLLs and keep the rest asord12. - Timestamps as truth. Use them for clustering and for anomalies, never as proof of when an attack was prepared.
Practice
1. Which single section property is most suspicious in a normal application, and why?
A section that is both writable and executable: code can be written into it and then run, which is what unpackers and self-modifying code need. Ordinary compiled programs keep code read-only.
2. Add ("KERNEL32.dll", "IsDebuggerPresent") to the imports and a hint for it. What does it suggest?
Add the name to the KERNEL32 list in IMPORTS and "IsDebuggerPresent": "checks for a debugger (anti-analysis?)" to HINTS. The imphash changes too, which shows how sensitive it is to the import list. Many legitimate programs call it, so it is a weak hint by itself (anti-debugging).
3. Why does the imphash depend on the order of imports?
It hashes the list as it appears in the import table, which follows the order the linker wrote it. The same source built with the same toolchain gives the same order, which is the point; a different linker or a reordering gives a different imphash.
Test yourself
What does an imphash summarise?
- The whole file
- The normalised list of imported DLLs and functions
- The section entropy
- The digital signature
Which import combination suggests a downloader with persistence?
- printf and malloc
- InternetOpenUrlA, WriteFile and RegSetValueExW
- GetTickCount only
- CreateWindowExW and MessageBoxW
A PE's compile timestamp is in the future. What can you conclude?
- The file is from the future
- The timestamp was forged or the build clock was wrong; it is an anomaly, not a date
- The file is signed
- The file is packed with UPX
Which tool maps PE features to readable capabilities with ATT&CK IDs?
- ssdeep
- capa
- sha256sum
- tcpdump