cybersecurity · intermediate · ~20 min

Parse a mock ELF64 header — extract version, machine, entry

Robust binary-header parsing with bounds + sentinel checks.

Challenge

Extract three identity fields from a mock ELF64 header — the universal Linux binary fingerprint that every reverse-engineering tool reads first.

Task

Implement int parse_elf64_ident(const unsigned char *buf, int len, int *class_, int *data, int *machine) that fills the three output fields from the header.

Input

  • buf, len: a fixture byte buffer (the header's first bytes) and its length, baked into the harness. Fields:
    • class = buf[4]: 1 = 32-bit, 2 = 64-bit
    • data = buf[5]: 1 = little-endian (LSB), 2 = big-endian (MSB)
    • machine = buf[18..19] little-endian (only LSB binaries are tested)
  • class_, data, machine: output pointers, written only on success.

Output

Returns int: 1 on success (filling the three outputs), or 0 on failure.

Example

ELF64 LSB x86_64 header   ->   1, class=2, data=1, machine=0x3E
short buffer / bad magic  ->   0

Edge cases

  • Returns 0 if buf is NULL, len < 20, the first 4 bytes are not the ELF magic, or any output pointer is NULL.

Rules

  • Bounds-check every read before indexing.

Why this matters

The ELF header is the universal Linux binary fingerprint. Knowing how to extract its fields makes you fluent in any reverse-engineering tool.

Input format

A byte buffer buf (>= 20 bytes) and its length, plus three output int pointers.

Output format

An int: 1 on success with class_/data/machine filled, else 0.

Constraints

Bounds-check every read. Validate the ELF magic and non-NULL outputs.

Starter code

#include <stddef.h>
int parse_elf64_ident(const unsigned char *buf, int len, int *class_, int *data, int *machine) { /* TODO */ (void)buf; (void)len; (void)class_; (void)data; (void)machine; return 0; }

Common mistakes

Indexing buf[18] without confirming len >= 20.

Edge cases to handle

Magic mismatch; short buffer; NULL outputs.

Complexity

O(1).

Background lessons

Up next

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