cybersecurity · beginner · ~10 min

Reject a Host header with CR / LF / NUL / space

Strict allow-list validation for an HTTP header value.

Challenge

Strictly validate a Host header value so a smuggled \r\n can't be used to forge extra headers (CRLF injection).

Task

Implement int valid_host_header(const char *h) that returns 1 if h is an acceptable Host value, else 0.

h is valid when ALL of the following hold:

  • non-NULL and non-empty;
  • length <= 255;
  • every character is in the allowed set: A-Z, a-z, 0-9, ., -, : (port), [, ] (IPv6 literal);
  • it contains no whitespace, CR, LF, or NUL.

Input

  • h: the Host-header value, or NULL. The grader passes fixed strings.

Output

Returns int: 1 if valid, else 0.

Example

valid_host_header("example.com")          ->   1
valid_host_header("api.example.com:8443") ->   1
valid_host_header("[::1]:80")             ->   1   (IPv6 literal + port)
valid_host_header("example.com\r\nX: y")  ->   0   (CRLF injection)
valid_host_header("example com")          ->   0   (space)
valid_host_header("")                     ->   0
valid_host_header(NULL)                   ->   0

Edge cases

  • NULL and empty return 0.
  • A value longer than 255 bytes returns 0.
  • Any byte outside the allowed set (including space) rejects the whole value.

Rules

  • Per-byte allow-list scan; this checks bytes only, not DNS/port semantics.

Why this matters

A Host header with a smuggled \r\n lets an attacker forge additional headers — the foundation of CRLF injection. Strict validation refuses everything that looks weird.

Input format

A Host-header value string h, or NULL.

Output format

An int: 1 if h passes the allow-list and length checks, else 0.

Constraints

Per-byte allow-list scan; length cap 255; reject whitespace/CR/LF/NUL.

Starter code

int valid_host_header(const char *h) { /* TODO */ (void)h; return 0; }

Common mistakes

Allowing space (some clients send it; refuse anyway).

Edge cases to handle

IPv6 literal [::1]. Port number. Empty. Length 256.

Complexity

O(strlen).

Background lessons

Up next

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