cybersecurity · intermediate · ~15 min · safe pentest lab

Sanitize a log line

Neutralize control bytes into '.' while copying into a bounded buffer.

Challenge

Make an untrusted line safe to print:

int sanitize_log_line(const char *in, char *out, size_t cap);

Copy in to out, replacing any dangerous control byte (DEL 0x7f, or <0x20 except TAB and newline) with '.'. Write at most cap-1 chars plus a NUL. Return the number of chars written (excluding the NUL). Write nothing when cap==0.

Input format

An untrusted in string and an out buffer of size cap.

Output format

The output length; out holds the sanitized, NUL-terminated line.

Constraints

Never write past cap-1 chars plus the NUL.

Starter code

#include <stddef.h>
/* Copy in -> out, replacing dangerous control bytes (DEL 0x7f, or <0x20 except \t and \n)
   with '.'. Write at most cap-1 chars + a NUL. Return the number of chars written (excl NUL).
   Writes nothing when cap==0. */
int sanitize_log_line(const char *in, char *out, size_t cap){ (void)in;(void)out;(void)cap; return 0; }

Common mistakes

Off-by-one on the NUL; underflow when computing a bound with cap==0.

Edge cases to handle

cap==0 returns 0 and writes nothing; TAB/newline pass through unchanged; truncation is clean.

Background lessons

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