TExcelTAD
Home › Reverse Engineering & Binary Analysis › PE Imports, Exports and the IAT, and Mach-O in Brief

PE Imports, Exports and the IAT, and Mach-O in Brief

A Windows program does almost everything through the Windows API: opening files, creating processes, talking to the network, writing the registry. Every API function it calls by name is listed in its import table, which makes that table the fastest behaviour summary a PE file offers (the next section's Imports as Behaviour Hints uses it). At load time the loader writes the real function addresses into the Import Address Table (IAT), the PE counterpart of the ELF GOT, and code calls through it. This lesson parses an import table that the example builds itself, simulates the loader filling the IAT, detects a hooked entry, and ends with the macOS format, Mach-O.

Definitions

  • Import directory (data directory 1): an array of 20-byte IMAGE_IMPORT_DESCRIPTORs, one per DLL, ended by an all-zero entry. Fields: OriginalFirstThunk (RVA of the Import Lookup Table, ILT), TimeDateStamp, ForwarderChain, Name (RVA of the DLL name, e.g. KERNEL32.dll), FirstThunk (RVA of the IAT).
  • ILT / IAT entries (8 bytes in PE32+): either an RVA of a hint/name entry (a 2-byte hint, the index the linker expected in the DLL's export table, then the ASCII name), or, with the top bit set, an import by ordinal (just a number, no name: harder to read, sometimes used to hide intent).
  • On disk the IAT is a copy of the ILT; the loader overwrites the IAT with the resolved addresses. Code calls call [rip+IAT slot] (or through a small thunk jmp [IAT slot]).
  • Export directory (data directory 0): a DLL's table of functions it offers, by name and ordinal, with RVAs. A forwarded export points to another DLL's function (NTDLL.RtlAllocateHeap style strings instead of an RVA).
  • Delay-load imports (data directory 13) are resolved on first use, so they don't appear in the normal import table; dynamic resolution with LoadLibrary + GetProcAddress doesn't appear in any table, only as strings, or not at all if the names are hashed.

An import table from bytes

The example builds the import data of a fictional lab tool as one section placed at RVA 0x2000: two DLLs, five functions by name and one import by ordinal. It then walks the structures as a parser does.

python · try it yourself
import struct

BASE_RVA = 0x2000
IMPORTS = {"KERNEL32.dll": ["CreateFileW", "ReadFile", "CloseHandle", "ExitProcess"],
           "LABUTIL.dll": ["lab_checksum", 7]}          # 7 = import by ordinal

def build_idata():
    """Lay out descriptors, ILTs, IATs, names; return (bytes, iat_slots)."""
    ndll = len(IMPORTS)
    desc_size = 20 * (ndll + 1)
    blob = bytearray(desc_size)
    def add(data, align=2):
        while len(blob) % align: blob.append(0)
        rva = BASE_RVA + len(blob); blob.extend(data); return rva
    descs, slots = [], []
    for dll, funcs in IMPORTS.items():
        entries = []
        for f in funcs:
            if isinstance(f, int):
                entries.append((1 << 63) | f)                       # ordinal import
            else:
                entries.append(add(struct.pack("<H", 0) + f.encode() + b"\0"))
        thunk = b"".join(struct.pack("<Q", e) for e in entries) + bytes(8)
        ilt = add(thunk, 8)
        iat = add(thunk, 8)                                         # identical on disk
        name = add(dll.encode() + b"\0")
        descs.append((ilt, 0, 0, name, iat))
        slots += [(dll, f, iat + 8 * i) for i, f in enumerate(funcs)]
    for i, d in enumerate(descs):
        struct.pack_into("<IIIII", blob, 20 * i, *d)
    return bytes(blob), slots

def read_cstr(blob, rva):
    off = rva - BASE_RVA
    return blob[off:blob.index(b"\0", off)].decode()

def parse_imports(blob):
    off, result = 0, {}
    while True:
        ilt, _, _, name_rva, iat = struct.unpack_from("<IIIII", blob, off)
        if (ilt, name_rva, iat) == (0, 0, 0):
            break
        dll, funcs, t = read_cstr(blob, name_rva), [], ilt - BASE_RVA
        while (entry := struct.unpack_from("<Q", blob, t)[0]) != 0:
            if entry >> 63:
                funcs.append(f"ordinal #{entry & 0xFFFF}")
            else:
                funcs.append(read_cstr(blob, (entry & 0x7FFFFFFF) + 2))   # skip the 2-byte hint
            t += 8
        result[dll] = (funcs, iat)
        off += 20
    return result

blob, slots = build_idata()
print(f".idata: {len(blob)} bytes at RVA {BASE_RVA:#x}")
for dll, (funcs, iat) in parse_imports(blob).items():
    print(f"{dll:<13} IAT at RVA {iat:#x}: {', '.join(funcs)}")

# Simulate the loader: each DLL is "loaded" at a fake base; the IAT receives addresses inside it.
modules = {"KERNEL32.dll": (0x7FF800000000, 0x100000), "LABUTIL.dll": (0x7FF810000000, 0x10000)}
iat = {}
for n, (dll, func, slot) in enumerate(slots):
    base, _ = modules[dll]
    iat[slot] = (dll, func, base + 0x1000 + 0x40 * n)
# Something overwrites one IAT slot to point into a private memory region (a hook).
hooked = slots[1][2]
iat[hooked] = (iat[hooked][0], iat[hooked][1], 0x000001D2C0001000)
print("--- IAT check: does every slot point into the DLL it was imported from?")
for slot, (dll, func, addr) in iat.items():
    base, size = modules[dll]
    ok = base <= addr < base + size
    print(f"  {slot:#x} {dll}!{func}: {addr:#x} {'ok' if ok else 'OUTSIDE ' + dll + ' -> hooked?'}")
.idata: 292 bytes at RVA 0x2000
KERNEL32.dll  IAT at RVA 0x20a0: CreateFileW, ReadFile, CloseHandle, ExitProcess
LABUTIL.dll   IAT at RVA 0x2100: lab_checksum, ordinal #7
--- IAT check: does every slot point into the DLL it was imported from?
  0x20a0 KERNEL32.dll!CreateFileW: 0x7ff800001000 ok
  0x20a8 KERNEL32.dll!ReadFile: 0x1d2c0001000 OUTSIDE KERNEL32.dll -> hooked?
  0x20b0 KERNEL32.dll!CloseHandle: 0x7ff800001080 ok
  0x20b8 KERNEL32.dll!ExitProcess: 0x7ff8000010c0 ok
  0x2100 LABUTIL.dll!lab_checksum: 0x7ff810001100 ok
  0x2108 LABUTIL.dll!7: 0x7ff810001140 ok

The parser recovers both DLLs and all six imports, including the nameless ordinal. The check at the end is the core of IAT-hook detection, as memory-forensics tools (Volatility's apihooks-style plugins) and EDR integrity checks do it: every IAT slot should point into the module it was imported from. ReadFile now points into an anonymous region, which in a real investigation means "someone is intercepting this program's file reads", whether a legitimate monitoring tool or malware.

Mach-O in brief

macOS and iOS executables use Mach-O. A header names the CPU and file type, then a list of load commands describes everything else: segments (LC_SEGMENT_64, with sections such as __TEXT,__text), the entry point (LC_MAIN), linked libraries (LC_LOAD_DYLIB, the counterpart of PE imports), and the code signature (LC_CODE_SIGNATURE). Universal ("fat") binaries wrap several Mach-O files for different CPUs behind a big-endian header with magic 0xCAFEBABE, which Java class files also start with. On macOS, otool -hl, otool -L (libraries), nm, codesign -dv and lipo -info are the triage tools.

The example identifies files by their first bytes, as file does, and walks the load commands of a small synthetic Mach-O header.

python · try it yourself
import struct

def identify(data):
    m4 = data[:4]
    if m4 == b"\x7fELF":
        return "ELF"
    if m4[:2] == b"MZ":
        return "PE/DOS (MZ)"
    if struct.unpack("<I", m4)[0] == 0xFEEDFACF:
        return "Mach-O 64-bit, little-endian"
    if struct.unpack(">I", m4)[0] == 0xCAFEBABE:
        second = struct.unpack(">I", data[4:8])[0]
        # A fat header's next field is the number of architectures (small);
        # a Java class has minor_version (2 bytes) + major_version (2 bytes, 45 or more).
        return f"Mach-O universal, {second} architectures" if second < 30 else "Java class file"
    return "unknown"

LC = {0x19: "LC_SEGMENT_64", 0x80000028: "LC_MAIN", 0xC: "LC_LOAD_DYLIB", 0x1D: "LC_CODE_SIGNATURE"}
def synthetic_macho():
    cmds = [(0x19, 72), (0x19, 72), (0x80000028, 24), (0xC, 56), (0x1D, 16)]
    body = b"".join(struct.pack("<II", c, size) + bytes(size - 8) for c, size in cmds)
    hdr = struct.pack("<IIIIIIII", 0xFEEDFACF, 0x0100000C, 0, 2, len(cmds), len(body), 0x00200085, 0)
    return hdr + body                                     # arm64, MH_EXECUTE, flags incl. MH_PIE

def walk_macho(data):
    magic, cpu, _, ftype, ncmds, sizeofcmds, flags, _ = struct.unpack_from("<IIIIIIII", data, 0)
    cpus = {0x01000007: "x86_64", 0x0100000C: "arm64"}
    print(f"cpu={cpus.get(cpu, hex(cpu))} filetype={'MH_EXECUTE' if ftype == 2 else ftype} "
          f"ncmds={ncmds} PIE={bool(flags & 0x200000)}")
    off = 32
    for _ in range(ncmds):
        cmd, size = struct.unpack_from("<II", data, off)
        if size < 8 or off + size > 32 + sizeofcmds:
            raise ValueError("bad load command size")
        print(f"  {LC.get(cmd, hex(cmd)):<18} size {size}")
        off += size

samples = {
    "elf":   b"\x7fELF\x02\x01\x01\x00" + bytes(8),
    "pe":    b"MZ\x90\x00" + bytes(12),
    "macho": synthetic_macho(),
    "fat":   struct.pack(">II", 0xCAFEBABE, 2) + bytes(8),
    "class": struct.pack(">IHH", 0xCAFEBABE, 0, 65) + bytes(8),
}
for name, data in samples.items():
    print(f"{name:<6} {identify(data)}")
walk_macho(samples["macho"])
elf    ELF
pe     PE/DOS (MZ)
macho  Mach-O 64-bit, little-endian
fat    Mach-O universal, 2 architectures
class  Java class file
cpu=arm64 filetype=MH_EXECUTE ncmds=5 PIE=True
  LC_SEGMENT_64      size 72
  LC_SEGMENT_64      size 72
  LC_MAIN            size 24
  LC_LOAD_DYLIB      size 56
  LC_CODE_SIGNATURE  size 16

The fat binary and the Java class file share their first four bytes; the next field tells them apart. Checking more than the magic is what separates a robust identifier from one that a crafted file can fool.

How import-based tricks are detected

  • Very few imports (only LoadLibraryA and GetProcAddress, or nothing but kernel32 basics) in a program that clearly does much more: functions are resolved at run time, typical of packers and malware. Look for the names as strings, or for hashing loops near the GetProcAddress call.
  • Ordinal-only imports from system DLLs are unusual in compiler output and worth a note.
  • IAT slots that point outside their module at run time, as above, or inline hooks (a jmp written over the first bytes of the API function itself).
  • Import hash (imphash): an MD5 of the normalised import list, used to cluster samples built from the same code; useful but easy to perturb.

How it is done right

  • For developers: import what you use by name, keep the IAT read-only after load (the default with modern linkers), enable Control Flow Guard, and sign the binary so tampering is visible.
  • For analysts: always compare the static import list with what the program does at run time (API monitor, tracer); a mismatch is itself a finding.

Pitfalls

  • The hint is only a hint: the loader verifies the name; don't treat the hint value as the ordinal.
  • Bound imports (an old optimisation) pre-fill the IAT on disk with addresses for a specific DLL version.
  • API sets: imports from api-ms-win-core-... DLLs are redirected by Windows to the real implementation DLL; they are normal in modern binaries.
  • .NET assemblies import only mscoree.dll!_CorExeMain (_CorDllMain for DLLs); their real code is in CIL metadata, read with dnSpy or ILSpy, not with PE import tools.

Practice

1. An ILT entry is 0x8000000000000010. What is imported?

The top bit is set, so it is an import by ordinal: ordinal 16 (0x10), with no name.

2. Why does the parser add 2 to the hint/name RVA before reading the name?

The first 2 bytes of a hint/name entry are the hint (a 16-bit index); the ASCII name follows.

3. A sample imports only LoadLibraryA, GetProcAddress and VirtualAlloc. What do you suspect and what do you look for next?

Run-time resolution of the real API set (and possibly unpacking into allocated memory). Look for API names as strings (possibly encoded), hashing loops, and run it in a lab under an API monitor to see what it resolves.

Test yourself

What does the Windows loader write into the IAT?

  1. The names of imported functions
  2. The resolved addresses of the imported functions
  3. The DLL's file path
  4. The export table

How is an import by ordinal marked in a PE32+ ILT entry?

  1. The name starts with #
  2. The top bit (bit 63) is set
  3. The hint is 0xFFFF
  4. It is in the export table

An IAT slot for ReadFile points into an anonymous memory region, not kernel32.dll. What does it suggest?

  1. Normal behaviour
  2. The import was hooked by something
  3. The file is a DLL
  4. ASLR is off

Which file formats start with 0xCAFEBABE?

  1. ELF and PE
  2. Mach-O universal binaries and Java class files
  3. Only Mach-O 64-bit
  4. PDF