cybersecurity · intermediate · ~15 min · safe pentest lab
Follow an offset pointer inside a binary header, with bounds checks.
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.
Implement int pe_machine(const uint8_t *buf, size_t n) that returns the PE machine value, or -1 on any malformed header.
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.Returns int: the machine value on success, or -1 on failure.
header with e_lfanew=0x40, "PE\0\0", machine 0x8664 -> 0x8664
bad MZ / e_lfanew past end / bad signature -> -1
n < 0x40, a bad MZ, an e_lfanew that runs past n, or a bad PE\0\0.e_lfanew little-endian from bytes 0x3C..0x3F.off + 6 <= n before reading the signature and machine.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.
A fixture byte buffer buf (a PE header) and its length n.
An int: the little-endian machine value, or -1 on a malformed header.
Validate MZ and PE\0\0; bounds-check the followed e_lfanew offset.
#include <stdint.h>
#include <stddef.h>
int pe_machine(const uint8_t *buf, size_t n) {
/* TODO */
(void)buf; (void)n;
return -1;
}
Reading e_lfanew big-endian. Not bounds-checking the followed offset. Forgetting the two NUL bytes in the PE signature.
e_lfanew pointing past the buffer. Missing signature. Short buffer.
O(1).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.