cybersecurity · intermediate · ~15 min · safe pentest lab
Validate file uploads by verifying file signature magic bytes against executable signatures.
Attackers upload malicious executables disguised with benign file extensions (e.g. resume.pdf.exe or avatar.png). File validation must inspect magic header bytes rather than trusting file extensions.
Implement:
int is_executable_blob(const unsigned char *buf, size_t len);
Inspect buf to detect executable magic signatures.
len >= 4 and starts with 0x7F, 'E', 'L', 'F'len >= 2 and starts with 'M', 'Z'len >= 4 and starts with 0xCA, 0xFE, 0xBA, 0xBElen >= 4 and starts with 0xFE, 0xED, 0xFA, 0xCE or 0xFE, 0xED, 0xFA, 0xCF (or reverse endian 0xCE/0xCF, 0xFA, 0xED, 0xFE)len >= 2 and starts with '#', '!'buf == NULL, return -1.1.len is too short to match, return 0.buf: byte buffer; len: byte count.
Returns 1 if executable, 0 if non-executable, -1 on NULL pointer.
Freestanding C11. Read-only buffer inspection.
#include <stddef.h>
/* Inspect buf for executable magic (ELF, PE, Mach-O, Java class, shebang).
Return 1 if executable, 0 if safe/non-executable, or -1 if buf is NULL. */
int is_executable_blob(const unsigned char *buf, size_t len) {
(void)buf; (void)len;
return -1;
}
Reading past len when checking 4-byte signatures; ignoring script shebang (#!).
len < 2 returns 0; buffer with ELF prefix but len == 3 returns 0; NULL pointer returns -1.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.