cybersecurity · beginner · ~15 min
Per-format magic-byte allow-list.
Given the first 64 bytes of a file, return the file format as an integer:
1 = PNG (\x89PNG\r\n\x1a\n)2 = JPEG (\xff\xd8\xff)3 = GIF (GIF87a or GIF89a)4 = PDF (%PDF-)0 = unknownImplement int sniff_format(const unsigned char *buf, int len).
Upload pipelines that trust the file extension get owned. Magic-byte sniffing is the second line of defence.
Byte buffer + length.
Format code 0-4.
Read at most the first 8 bytes; bound-check len.
int sniff_format(const unsigned char *buf, int len) { /* TODO */ (void)buf; (void)len; return 0; }
Matching PDF anywhere instead of at offset 0.
Very short buffer; len < 4.
O(1).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.