cybersecurity · intermediate · ~15 min · safe pentest lab

Sanitize HTTP header values against CRLF injection

Eliminate HTTP response splitting by stripping CRLF injection sequences from header values.

Challenge

HTTP Response Splitting occurs when user input containing \r\n (CRLF) is included in an outgoing HTTP response header. An attacker can inject arbitrary headers (e.g. Set-Cookie: admin=1) or inject an entire rogue response body.

Your Task

Implement:

int sanitize_header_value(const char *val, char *out, size_t out_cap);

Strip \r and \n characters from val, outputting a clean single-line header.

Rules

  1. If val == NULL, out == NULL, or out_cap == 0, return -1.
  2. Strip any \r (0x0D) and \n (0x0A) from val.
  3. Write the sanitized NUL-terminated string into out.
  4. If the output string would exceed out_cap - 1, return -1.
  5. Return the count of CRLF characters stripped on success (>= 0).

Example

char out[64];
sanitize_header_value("user\r\nSet-Cookie: admin=1", out, sizeof out); // returns 2, out = "userSet-Cookie: admin=1"
sanitize_header_value("clean_val", out, sizeof out); // returns 0, out = "clean_val"

Input format

val: untrusted header value; out: destination buffer; out_cap: capacity of out buffer.

Output format

Returns count of stripped CRLF characters on success, or -1 on error/overflow.

Constraints

C11 freestanding. Never write past out_cap.

Starter code

#include <stddef.h>

/* Strip \r and \n characters from val into out (capacity out_cap).
   Return count of stripped CRLF characters on success, or -1 on invalid inputs
   or if the result does not fit in out_cap. */
int sanitize_header_value(const char *val, char *out, size_t out_cap) {
    (void)val; (void)out; (void)out_cap;
    return -1;
}

Common mistakes

Forgetting to NUL-terminate out; returning -1 when 0 characters are stripped; off-by-one capacity check.

Edge cases to handle

val with no CRLF returns 0; val composed solely of CRLF returns count and empty string out; out_cap too small returns -1.

Background lessons

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