cybersecurity · beginner · ~10 min

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

Strict allow-list validation for an HTTP header value.

Challenge

Implement int valid_host_header(const char *h) returning 1 if h is a valid Host-header value:

  • Non-NULL and non-empty.
  • Length <= 255.
  • Contains only: A-Z, a-z, 0-9, ., -, : (for port), and [ / ] for IPv6 literals.
  • No whitespace, CR, LF, or NUL.

Else return 0.

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

The header value string.

Output format

0/1.

Constraints

Per-byte allow-list scan.

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.