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

Read the machine type from a PE header — Windows malware triage starts by following the MZ stub to the PE signature, then reading the machine field.

Task

Implement int pe_machine(const uint8_t *buf, size_t n) that returns the PE machine value, or -1 on any malformed header.

Input

  • buf, n: a fixture byte buffer shaped like a PE header and its length, baked into the harness. A PE file starts with MZ; the little-endian 4-byte value at offset 0x3C (e_lfanew) points to the PE\0\0 signature; the little-endian 2-byte machine type follows at signature+4.

Output

Returns int: the machine value on success, or -1 on failure.

Example

header with e_lfanew=0x40, "PE\0\0", machine 0x8664   ->   0x8664
bad MZ / e_lfanew past end / bad signature             ->   -1

Edge cases

  • Returns -1 on NULL, n < 0x40, a bad MZ, an e_lfanew that runs past n, or a bad PE\0\0.

Rules

  • Build e_lfanew little-endian from bytes 0x3C..0x3F.
  • Bounds-check off + 6 <= n before reading the signature and 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.

Input format

A fixture byte buffer buf (a PE header) and its length n.

Output format

An int: the little-endian machine value, or -1 on a malformed header.

Constraints

Validate MZ and PE\0\0; bounds-check the followed e_lfanew offset.

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.