cybersecurity · beginner · ~10 min
Strict allow-list validation for an HTTP header value.
Strictly validate a Host header value so a smuggled \r\n can't be used to forge extra headers (CRLF injection).
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:
<= 255;A-Z, a-z, 0-9, ., -, : (port), [, ] (IPv6 literal);h: the Host-header value, or NULL. The grader passes fixed strings.Returns int: 1 if valid, else 0.
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
NULL and empty return 0.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.
A Host-header value string h, or NULL.
An int: 1 if h passes the allow-list and length checks, else 0.
Per-byte allow-list scan; length cap 255; reject whitespace/CR/LF/NUL.
int valid_host_header(const char *h) { /* TODO */ (void)h; return 0; }
Allowing space (some clients send it; refuse anyway).
IPv6 literal [::1]. Port number. Empty. Length 256.
O(strlen).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.