cybersecurity · beginner · ~15 min
Defensive scan for NUL-byte smuggling.
Catch a NUL-byte smuggling attempt, where a buffer like safe.txt\0/etc/passwd shows one filename to a NUL-terminated API and hides another for a downstream raw read.
Implement int has_nul_smuggle(const char *buf, int allocated_len). Treating buf as exactly allocated_len bytes, return 1 if any non-NUL byte appears at an index after the first NUL, else 0.
buf: a byte buffer the grader passes (may contain embedded NULs).allocated_len: the number of bytes actually allocated in buf.Returns int: 1 if there is a non-NUL byte somewhere after the first NUL, else 0.
"safe.txt" then zeros (len 16) -> 0 (only NULs after the first)
"safe.txt\0/etc/passwd" (len 32) -> 1 (bytes smuggled past the NUL)
"all-good" with no NUL in 8 bytes (len 8) -> 0 (no NUL at all)
single NUL byte (len 1) -> 0
allocated_len bytes — do not use strlen (that is the very bug being defended against).Some attacker-controlled input crosses a NUL byte through legacy APIs, smuggling one filename and reading another. Detecting it is a defensive first pass.
A byte buffer buf and its allocated size allocated_len.
An int: 1 if any non-NUL byte follows the first NUL, else 0.
Read exactly allocated_len bytes; do not use strlen.
int has_nul_smuggle(const char *buf, int allocated_len) { /* TODO */ (void)buf; (void)allocated_len; return 0; }
Using strlen — that's the bug being defended against.
No NUL anywhere. NUL at the last byte (no follow-on). All-NUL.
O(allocated_len).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.