cybersecurity · beginner · ~15 min
Magic-byte detection — the universal forensic primitive.
Implement int detect_format(const unsigned char *buf, int len)
returning one of:
1 if it looks like an ELF binary (\x7fELF)2 if it looks like a Mach-O binary (\xfe\xed\xfa\xce or \xfe\xed\xfa\xcf or the reverse for fat headers — accept all 4)3 if it looks like a Windows PE (MZ at offset 0)4 if it looks like a Java class file (\xca\xfe\xba\xbe)5 if it looks like wasm (\x00asm)0 otherwise (or if len < 4)Forensic triage of an unknown file always starts with magic-byte detection. file(1) does it; you'll build the same primitive in 30 lines of C.
Byte buffer + length.
One of 0/1/2/3/4/5.
Read only buf[0..3]; never index past len.
int detect_format(const unsigned char *buf, int len) { /* TODO */ (void)buf; (void)len; return 0; }
Indexing buf[3] without checking len >= 4.
Empty buffer; very short buffer.
O(1).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.