cybersecurity · intermediate · ~15 min · safe pentest lab

Read the machine type from a PE header

Follow an offset pointer inside a binary header, with bounds checks.

Challenge

Your job

#include <stdint.h>
#include <stddef.h>
int pe_machine(const uint8_t *buf, size_t n);

A PE file starts with MZ. The 4-byte little-endian value at offset 0x3C (e_lfanew) points to the PE\0\0 signature; the 2-byte little-endian machine type follows at signature+4. Return the machine value, or -1 on: NULL, n < 0x40, bad MZ, an e_lfanew that runs past n, or a bad PE\0\0.

Hints

  1. Build e_lfanew little-endian from bytes 0x3C..0x3F.
  2. Check off+6 <= n before reading the signature + machine.

Why this matters

Windows malware triage starts by reading the PE header: the MZ stub points to the PE signature, which is followed by the machine type. Bounds-checked parsing is the skill.

Starter code

#include <stdint.h>
#include <stddef.h>
int pe_machine(const uint8_t *buf, size_t n) {
    /* TODO */
    (void)buf; (void)n;
    return -1;
}

Common mistakes

Reading e_lfanew big-endian. Not bounds-checking the followed offset. Forgetting the two NUL bytes in the PE signature.

Edge cases to handle

e_lfanew pointing past the buffer. Missing signature. Short buffer.

Complexity

O(1).

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.