Course contentsShow
← Node.js
Lesson 540 of 1,9806. Networking and HTTP FundamentalsFree lesson

Header Injection Vulnerabilities

Sanitize user input to prevent HTTP header injection attacks via CRLF sequence insertion.

In this lesson, you will learn how to prevent HTTP header injection by neutralizing CRLF sequences in user-provided input.

Understanding the CRLF Sequence

When an HTTP message is parsed, the server relies on specific line-ending sequences to determine where one header ends and the next begins. This sequence is \r\n (Carriage Return + Line Feed), often referred to as CRLF.

An HTTP header injection vulnerability occurs when your application takes untrusted user input—like a username or a redirect URL—and inserts it directly into an HTTP response header without checking its contents. If an attacker includes \r\n characters in their input, they can effectively "break out" of the intended header field and inject their own malicious headers or even an entirely new response body.

The Anatomy of an Injection

Imagine you have a feature that reflects a user's chosen "Display Name" in a header:

// DANGEROUS: Do not do this
response.setHeader('X-User-Name', userInput);

If a user provides the input: Guest\r\nSet-Cookie: session=evil, the raw HTTP response sent to the browser becomes:

X-User-Name: Guest
Set-Cookie: session=evil
...

The browser now believes the server intentionally set an extra cookie, allowing the attacker to hijack sessions or perform cross-site scripting (XSS) by injecting headers like Content-Type: text/html.

The Solution: Sanitization

To secure your application, you must treat all user input as tainted. Before setting a header, you must strip or reject any input containing \r or \n. A simple approach is to use a regular expression to validate or clean the string:

const safeHeader = userInput.replace(/[\r\n]/g, '');
response.setHeader('X-User-Name', safeHeader);

By removing the CRLF characters, you ensure that the input remains safely contained within the value of the intended header, preventing the attacker from manipulating the structure of the HTTP response. Always validate inputs at the application boundary before they touch any networking logic.

Key Takeaway: Never pass raw user input directly into HTTP headers; always sanitize input by removing \r and \n characters to prevent CRLF injection attacks.