cybersecurity · beginner · ~15 min · safe pentest lab
Neutralize log injection and terminal-escape vulnerabilities by sanitizing escape sequences.
Log injection attacks embed ANSI terminal escape sequences into usernames or user agents. When administrators view logs using cat or less, escape codes can clear screens, rewrite log entries, or execute arbitrary terminal commands.
Implement:
int strip_ansi_escapes(const char *input, char *output, size_t out_cap);
Strip ANSI escape sequences from input.
input == NULL, output == NULL, or out_cap == 0, return -1.\x1b / 0x1B) followed by '[' is encountered:0x30 through 0x3F).0x20 through 0x2F).0x40 through 0x7E).\t) or newline (\n).output.out_cap - 1, return -1.output.char out[32];
strip_ansi_escapes("\033[31mRed Alert\033[0m", out, sizeof out); // returns 9, out = "Red Alert"
input: untrusted log string; output: sanitized buffer; out_cap: capacity of output.
Returns count of characters written to output, or -1 on overflow or invalid inputs.
C11 freestanding string processing.
#include <stddef.h>
/* Strip ANSI terminal escape sequences and non-printable control characters
(except \t and \n) from input into output. Return characters written, or -1 on error/overflow. */
int strip_ansi_escapes(const char *input, char *output, size_t out_cap) {
(void)input; (void)output; (void)out_cap;
return -1;
}
Dropping normal printable characters; stripping tabs or newlines; failing to NUL-terminate output.
Log with no escapes; escape sequence at the very end of string; empty string; tabs and newlines preserved.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.