cybersecurity · beginner · ~15 min · safe pentest lab

Neutralize terminal escape injection in logs

Neutralize log injection and terminal-escape vulnerabilities by sanitizing escape sequences.

Challenge

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.

Your Task

Implement:

int strip_ansi_escapes(const char *input, char *output, size_t out_cap);

Strip ANSI escape sequences from input.

Rules

  1. If input == NULL, output == NULL, or out_cap == 0, return -1.
  2. When ESC (\x1b / 0x1B) followed by '[' is encountered:
    • Skip all parameter characters (0x30 through 0x3F).
    • Skip all intermediate characters (0x20 through 0x2F).
    • Skip the terminating character (0x40 through 0x7E).
  3. Strip any unprintable control character (< 0x20) unless it is a tab (\t) or newline (\n).
  4. Write the clean NUL-terminated text into output.
  5. If output would exceed out_cap - 1, return -1.
  6. Return the number of characters written to output.

Example

char out[32];
strip_ansi_escapes("\033[31mRed Alert\033[0m", out, sizeof out); // returns 9, out = "Red Alert"

Input format

input: untrusted log string; output: sanitized buffer; out_cap: capacity of output.

Output format

Returns count of characters written to output, or -1 on overflow or invalid inputs.

Constraints

C11 freestanding string processing.

Starter code

#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;
}

Common mistakes

Dropping normal printable characters; stripping tabs or newlines; failing to NUL-terminate output.

Edge cases to handle

Log with no escapes; escape sequence at the very end of string; empty string; tabs and newlines preserved.

Background lessons

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