cybersecurity · beginner · ~12 min · safe pentest lab
Magic-byte file type detection with bounds checks.
Implement:
#include <stdint.h>
#include <stddef.h>
int detect_firmware_type(const uint8_t *buf, size_t n);
Return:
1 PE (4D 5A)2 ELF (7F 45 4C 46)3 U-Boot uImage (27 05 19 56, big-endian)4 Squashfs (68 73 71 73 — ASCII hsqs)5 JFFS2 (19 85)0 unknown-1 buf == NULLIf n is too short to check a given magic, skip it.
memcmp against constant byte arrays.27 05 19 56 in that order.Before you mount or unpack a firmware image, you need to know what it is. Magic-byte sniffing answers the question in 8 bytes.
A const byte buffer + its length.
Type tag (0..5) or -1 on NULL.
Bounds-check before every memcmp. Buf-NULL handling explicit.
#include <stdint.h>
#include <stddef.h>
int detect_firmware_type(const uint8_t *buf, size_t n) {
/* TODO */
(void)buf; (void)n;
return -1;
}
Letting PE's 2-byte prefix match before ELF's 4-byte prefix is checked. Reading past n. Treating uImage as little-endian.
Buffer exactly 2 bytes (PE / JFFS2 only). NULL buf.
O(1) — bounded number of memcmps.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.