cybersecurity · beginner · ~15 min

Detect a NUL byte hidden inside argv (within the allocated extent)

Defensive scan for NUL-byte smuggling.

Challenge

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.

Task

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.

Input

  • buf: a byte buffer the grader passes (may contain embedded NULs).
  • allocated_len: the number of bytes actually allocated in buf.

Output

Returns int: 1 if there is a non-NUL byte somewhere after the first NUL, else 0.

Example

"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

Edge cases

  • A buffer with no NUL at all returns 0.
  • A NUL at the very last byte (nothing follows) returns 0.
  • An all-NUL buffer returns 0.

Rules

  • Scan exactly allocated_len bytes — do not use strlen (that is the very bug being defended against).

Why this matters

Some attacker-controlled input crosses a NUL byte through legacy APIs, smuggling one filename and reading another. Detecting it is a defensive first pass.

Input format

A byte buffer buf and its allocated size allocated_len.

Output format

An int: 1 if any non-NUL byte follows the first NUL, else 0.

Constraints

Read exactly allocated_len bytes; do not use strlen.

Starter code

int has_nul_smuggle(const char *buf, int allocated_len) { /* TODO */ (void)buf; (void)allocated_len; return 0; }

Common mistakes

Using strlen — that's the bug being defended against.

Edge cases to handle

No NUL anywhere. NUL at the last byte (no follow-on). All-NUL.

Complexity

O(allocated_len).

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.