TExcelTAD
Home › Reverse Engineering & Binary Analysis › PE: DOS and NT Headers and the Section Table

PE: DOS and NT Headers and the Section Table

Windows executables (.exe), libraries (.dll), drivers (.sys) and UEFI firmware images use the Portable Executable (PE) format, a descendant of the COFF object format with a 1980s DOS header still glued to the front. Most malware an analyst meets is PE, and the headers alone answer many triage questions: 32 or 64-bit, GUI or console, when it was linked (or claims to be), whether ASLR and DEP are enabled, which section the code starts in, whether a section is both writable and executable. This lesson builds a minimal synthetic PE image in Python (no real Windows binary is involved) and parses it the way pefile, dumpbin or PE-bear do.

The layout

DOS header: "MZ" ... e_lfanew @0x3C DOS stub (message) "PE\0\0" signature COFF file header (20 bytes) optional header (PE32+: 240 B)... 16 data directories section table (40 B each) .text, .rdata, .data ...(raw data, FileAlignment) e_lfanew points to "PE\0\0" Machine, NumberOfSections, TimeDateStamp,SizeOfOptionalHeader, Characteristics Magic 0x20B, AddressOfEntryPoint, ImageBase,Subsystem, DllCharacteristics Name, VirtualAddress, VirtualSize,PointerToRawData, SizeOfRawData, flags

Definitions

  • DOS header (64 bytes): starts with MZ; the only field that matters today is e_lfanew at offset 0x3C, the file offset of the PE signature. A short DOS stub program follows (it prints a message when run under DOS).
  • PE signature PE\0\0, then the COFF file header: Machine (0x8664 x64, 0x14c x86, 0xAA64 ARM64), NumberOfSections, TimeDateStamp (link time as Unix seconds, often fake or a hash in reproducible builds), SizeOfOptionalHeader, Characteristics (0x0002 executable image, 0x2000 DLL, 0x0020 large-address aware).
  • Optional header (not optional for images): Magic (0x10B PE32, 0x20B PE32+ for 64-bit), AddressOfEntryPoint (an RVA), ImageBase (preferred load address), SectionAlignment (in memory, usually 0x1000) and FileAlignment (on disk, usually 0x200), Subsystem (2 GUI, 3 console), DllCharacteristics (0x0040 DYNAMIC_BASE = ASLR, 0x0100 NX_COMPAT = DEP, 0x0020 HIGH_ENTROPY_VA, 0x4000 GUARD_CF = Control Flow Guard), and 16 data directories (RVA and size of the export table, import table, resources, exceptions, certificates, relocations, debug data, TLS, IAT...).
  • RVA (relative virtual address): an address relative to the image base. To read the bytes at an RVA in the file, find the section whose [VirtualAddress, VirtualAddress + VirtualSize) contains it: offset = rva - VirtualAddress + PointerToRawData.
  • Section characteristics: 0x20 code, 0x40 initialised data, 0x20000000 execute, 0x40000000 read, 0x80000000 write.

A synthetic PE, built and parsed

The example builds a 64-bit console image with three sections and a three-byte entry point (xor eax, eax; ret), then parses every header back, converts the entry RVA to a file offset, and runs triage checks. The header values are typical of a modern linker; nothing here comes from a real program.

python · try it yourself
import struct, datetime

def build_pe():
    lfanew, falign, salign = 0x80, 0x200, 0x1000
    dos = bytearray(64); dos[0:2] = b"MZ"; struct.pack_into("<I", dos, 0x3C, lfanew)
    stub = b"toy PE built by the RE course\r\n
quot;.ljust(lfanew - 64, b"\0") sections = [ # name, RVA, raw size, flags, content (b".text", 0x1000, 0x200, 0x60000020, bytes.fromhex("31c0c3")), # code|exec|read (b".rdata", 0x2000, 0x200, 0x40000040, b"lab.test config v1\0"), # data|read (b".data", 0x3000, 0x200, 0xC0000040, b"\0" * 16), # data|read|write ] headers_size = falign # 0x80 + 4 + 20 + 240 + 3*40 = 0x200 exactly coff = struct.pack("<HHIIIHH", 0x8664, len(sections), 1767225600, 0, 0, 240, 0x0022) opt = struct.pack("<HBBIIIIIQIIHHHHHHIIIIHHQQQQII", 0x20B, 14, 40, 0x200, 0x400, 0, 0x1000, 0x1000, # magic, linker 14.40, sizes, entry, base of code 0x140000000, salign, falign, 6, 0, 0, 0, 6, 0, 0, # image base, alignments, versions 0x4000, headers_size, 0, 3, 0x8160, # size of image, headers, checksum, console, flags 0x100000, 0x1000, 0x100000, 0x1000, 0, 16) # stack/heap reserve+commit, loader flags, dirs opt += bytes(16 * 8) # 16 empty data directories table, body = b"", b"" raw_ptr = headers_size for name, rva, raw, flags, content in sections: table += struct.pack("<8sIIIIIIHHI", name, len(content), rva, raw, raw_ptr, 0, 0, 0, 0, flags) body += content.ljust(raw, b"\0") raw_ptr += raw return bytes(dos) + stub + b"PE\0\0" + coff + opt + table + body def parse_pe(data): if data[:2] != b"MZ": raise ValueError("no MZ header") lfanew = struct.unpack_from("<I", data, 0x3C)[0] if lfanew + 24 > len(data) or data[lfanew:lfanew + 4] != b"PE\0\0": raise ValueError(f"e_lfanew {lfanew:#x} does not point to a PE signature") machine, nsec, stamp, _, _, optsize, chars = struct.unpack_from("<HHIIIHH", data, lfanew + 4) o = lfanew + 24 f = struct.unpack_from("<HBBIIIIIQIIHHHHHHIIIIHHQQQQII", data, o) magic, entry, image_base, subsystem, dllchars = f[0], f[6], f[8], f[21], f[22] when = datetime.datetime.fromtimestamp(stamp, datetime.timezone.utc).date() print(f"machine={machine:#x} sections={nsec} linked={when} characteristics={chars:#06x}") print(f"magic={magic:#x} ({'PE32+' if magic == 0x20B else 'PE32'}) entry RVA={entry:#x} " f"image base={image_base:#x} subsystem={'console' if subsystem == 3 else subsystem}") names = {0x0020: "HIGH_ENTROPY_VA", 0x0040: "DYNAMIC_BASE (ASLR)", 0x0100: "NX_COMPAT (DEP)", 0x4000: "GUARD_CF", 0x8000: "TERMINAL_SERVER_AWARE"} print("DllCharacteristics:", ", ".join(n for bit, n in names.items() if dllchars & bit)) secs = [] for i in range(nsec): name, vsize, va, rsize, rptr, *_, sflags = struct.unpack_from("<8sIIIIIIHHI", data, o + optsize + 40 * i) perms = ("R" if sflags & 0x40000000 else "-") + ("W" if sflags & 0x80000000 else "-") + \ ("X" if sflags & 0x20000000 else "-") secs.append((name.rstrip(b"\0").decode(), va, vsize, rptr, perms)) print(f" {secs[-1][0]:<7} RVA={va:#07x} vsize={vsize:#05x} raw@{rptr:#06x} {perms}") def rva_to_offset(rva): for n, va, vs, rp, _ in secs: if va <= rva < va + vs: return n, rva - va + rp return None, None sec, off = rva_to_offset(entry) print(f"entry RVA {entry:#x} -> section {sec}, file offset {off:#x}: {data[off:off + 3].hex(' ')}") sec, off = rva_to_offset(0x2000) print(f"RVA 0x2000 -> {sec} @ {off:#x}: {data[off:off + 18].decode()!r}") print("W+X sections:", [s[0] for s in secs if "W" in s[4] and "X" in s[4]] or "none") pe = build_pe() print(f"image file: {len(pe)} bytes") parse_pe(pe) print("--- e_lfanew pointing past the end") bad = bytearray(pe); struct.pack_into("<I", bad, 0x3C, 0x10000) try: parse_pe(bytes(bad)) except ValueError as e: print("rejected:", e)
image file: 2048 bytes
machine=0x8664 sections=3 linked=2026-01-01 characteristics=0x0022
magic=0x20b (PE32+) entry RVA=0x1000 image base=0x140000000 subsystem=console
DllCharacteristics: HIGH_ENTROPY_VA, DYNAMIC_BASE (ASLR), NX_COMPAT (DEP), TERMINAL_SERVER_AWARE
  .text   RVA=0x01000 vsize=0x003 raw@0x0200 R-X
  .rdata  RVA=0x02000 vsize=0x013 raw@0x0400 R--
  .data   RVA=0x03000 vsize=0x010 raw@0x0600 RW-
entry RVA 0x1000 -> section .text, file offset 0x200: 31 c0 c3
RVA 0x2000 -> .rdata @ 0x400: 'lab.test config v1'
W+X sections: none
--- e_lfanew pointing past the end
rejected: e_lfanew 0x10000 does not point to a PE signature

The entry point RVA 0x1000 lands in .text, at file offset 0x200, where the three code bytes are; RVA 0x2000 maps to the string in .rdata. Notice the two coordinate systems: RVAs are memory layout (sections aligned to 0x1000), file offsets are disk layout (aligned to 0x200). Every PE tool converts between them constantly.

How suspicious PE headers are detected

Triage tools (pefile, PE-bear, PEStudio, Detect It Easy, capa) flag header anomalies like these:

  • Entry point outside the first code section, in a writable section or in the last section: typical of packers and file infectors.
  • Sections that are writable and executable (RWX), or unusual names (UPX0, .aspack, random strings), or a raw size of 0 with a large virtual size (space reserved for unpacked code).
  • Missing DYNAMIC_BASE / NX_COMPAT: no ASLR or DEP, either old tooling or deliberate.
  • TimeDateStamp in the future, in 1992 (Delphi's well-known fake date), or inconsistent with the debug directory's timestamp; also used to cluster samples from one build environment.
  • e_lfanew pointing past the file, overlapping headers, or SizeOfOptionalHeader tricks: malformed files designed to crash or confuse parsers.

How it is fixed and prevented

  • For developers: link with /DYNAMICBASE /NXCOMPAT /HIGHENTROPYVA /guard:cf (MSVC defaults for the first three), keep code and writable data in separate sections, and sign the result (Code Signing).
  • For tool authors: bounds-check every offset, as parse_pe does for e_lfanew, and parse untrusted files in a sandbox.

Pitfalls

  • PE32 vs PE32+ differ in the optional header (PE32 has a BaseOfData field and 4-byte ImageBase); check Magic before unpacking.
  • VirtualSize vs SizeOfRawData: the in-memory size may be larger (zero-filled, like .bss) or smaller (padding on disk).
  • TimeDateStamp is not trustworthy: reproducible builds put a hash there, and malware authors forge it.
  • The DOS stub is ignored by Windows; data hidden there or in the "Rich header" between stub and PE signature (MSVC's toolchain fingerprint) is still worth reading.

Practice

1. An image has SectionAlignment 0x1000. Section .rdata has VirtualAddress 0x5000 and PointerToRawData 0x3400. At which file offset is RVA 0x5123?

0x5123 - 0x5000 + 0x3400 = 0x3523.

2. DllCharacteristics is 0x0100. What is enabled and what is missing?

NX_COMPAT (DEP) is set; DYNAMIC_BASE (ASLR), HIGH_ENTROPY_VA and GUARD_CF are missing.

3. Change the .text flags in build_pe to 0xE0000020. What does the parser print for W+X?

['.text']: the code section is now readable, writable and executable.

Test yourself

Where does a parser find the offset of the PE signature?

  1. At offset 0
  2. In e_lfanew, a 4-byte field at offset 0x3C of the DOS header
  3. In the section table
  4. In the last 4 bytes of the file

What does Optional Header Magic 0x20B mean?

  1. PE32 (32-bit)
  2. PE32+ (64-bit)
  3. A DLL
  4. A .NET assembly

Which DllCharacteristics flag enables ASLR?

  1. NX_COMPAT 0x0100
  2. DYNAMIC_BASE 0x0040
  3. GUARD_CF 0x4000
  4. TERMINAL_SERVER_AWARE 0x8000

Why is an entry point in a writable last section suspicious?

  1. It is always a compiler bug
  2. Packers and file infectors put their stub there, so the real code is unpacked or hidden
  3. Windows forbids it
  4. It means the file is a DLL