CRLF Injection: Injecting New Lines, Hijacking Responses 📝

CRLF Injection: Injecting New Lines, Hijacking Responses 📝
Understanding the Silent Threat in HTTP Headers
In the complex landscape of web application security, CRLF injection stands as a particularly insidious vulnerability that exploits the fundamental building blocks of HTTP communication. This attack vector, which manipulates carriage return and line feed characters, enables attackers to compromise response integrity, poison logs, and bypass critical security controls. Recent vulnerabilities, including the critical CVE-2024-52875 affecting GFI KerioControl firewalls and CVE-2024-20337 in Cisco Secure Client, demonstrate that CRLF injection remains a relevant threat in 2025.
What is CRLF Injection?
CRLF injection is a web application vulnerability that occurs when an attacker successfully inserts Carriage Return (CR, ASCII 13, \r) and Line Feed (LF, ASCII 10, \n) characters into user input that gets processed by a web application. These special characters serve as End of Line (EOL) markers in various operating systems and internet protocols, particularly HTTP.
The HTTP protocol relies on CRLF sequences to structure communications between servers and clients. Headers are separated from each other by a single CRLF sequence, while a double CRLF (two consecutive sequences) marks the boundary between HTTP headers and the message body. When applications fail to properly sanitize user input containing these characters, attackers can manipulate the structure of HTTP responses, logs, and other text-based streams.
The Anatomy of CRLF Characters
In technical terms:
- Carriage Return (CR): Represented as \r or %0D in URL encoding, moves the cursor to the beginning of the current line
- Line Feed (LF): Represented as \n or %0A in URL encoding, moves the cursor down to the next line
- CRLF Sequence: The combination \r\n or %0D%0A creates a complete line termination
Different operating systems handle these characters differently. Windows uses both CR and LF (\r\n) to denote line endings, while Linux and Unix systems use only LF (\n). However, the HTTP protocol specification consistently requires CRLF sequences for line termination, making this the standard for web communications.
How CRLF Injection Attacks Work
The attack mechanism is deceptively simple yet devastatingly effective. When a web application accepts user input and incorporates it into HTTP headers or log files without proper validation, attackers can inject CRLF sequences to manipulate the application’s behavior.
The Injection Mechanism
Consider a vulnerable web application that accepts a redirect parameter:
http://example.com/redirect?url=http://legitimate-site.com
If the application doesn’t sanitize the input, an attacker can craft a malicious URL:
http://example.com/redirect?url=http://evil.com%0D%0ASet-Cookie:%20sessionid=attacker_value
When the server processes this request, the injected CRLF characters cause the HTTP response to be structured as:
HTTP/1.1 302 Found
Location: http://evil.com
Set-Cookie: sessionid=attacker_value
The server interprets the injected content as legitimate HTTP headers, potentially compromising user sessions or enabling further attacks.
Primary Attack Vectors
1. HTTP Response Splitting
HTTP Response Splitting represents the most dangerous manifestation of CRLF injection. In this attack, the adversary injects a complete HTTP response into the application’s output, effectively creating two separate responses from a single server interaction.
The attack unfolds in stages. First, the attacker identifies a vulnerable parameter that gets reflected in HTTP headers. Then, they inject a double CRLF sequence to prematurely terminate the first response and begin crafting a second, malicious response entirely under their control.
For example, a crafted payload might look like:
?page=foobar%0D%0AContent-Length:%200%0D%0A%0D%0AHTTP/1.1%20200%20OK%0D%0AContent-Type:%20text/html%0D%0AContent-Length:%2019%0D%0A%0D%0A<html>Attack</html>
This creates a scenario where the server returns what appears to be two legitimate responses. The first response terminates early with a Content-Length of zero, while the second contains attacker-controlled content that gets cached or processed by intermediaries.
2. Log Injection and Poisoning
Log injection exploits the same CRLF mechanism but targets application logging systems rather than HTTP responses. When applications log user-supplied data without sanitization, attackers can inject fake log entries to cover their tracks, frame innocent parties, or create false audit trails.
A practical example demonstrates the severity. Suppose an application logs failed login attempts:
2025-11-18 10:45:23 - Failed login attempt for user: legitimate_user
An attacker could inject CRLF characters in the username field:
attacker%0D%0A2025-11-18%2010:45:23%20-%20Successful%20login%20for%20user:%20admin%0D%0A2025-11-18%2010:45:24%20-%20Failed%20login%20attempt%20for%20user:
This results in fabricated log entries that appear authentic:
2025-11-18 10:45:23 - Failed login attempt for user: attacker
2025-11-18 10:45:23 - Successful login for user: admin
2025-11-18 10:45:24 - Failed login attempt for user: legitimate_user
System administrators analyzing these logs would see what appears to be a legitimate admin login, potentially misdirecting investigations and concealing the actual breach.
3. Cross-Site Scripting (XSS) via Header Injection
CRLF injection can escalate to Cross-Site Scripting when attackers inject malicious JavaScript into HTTP response bodies. By terminating headers prematurely and injecting script content, attackers can execute arbitrary code in victims’ browsers.
The attack works because the double CRLF sequence signals the end of headers and the beginning of the response body. An attacker might inject:
%0D%0AContent-Length:%2035%0D%0A%0D%0A<script>alert('XSS')</script>
Modern browsers process this injected content as part of the legitimate response, executing the malicious script with the context and privileges of the target domain.
4. Cookie Injection and Session Fixation
CRLF injection enables sophisticated session hijacking through cookie manipulation. Attackers can inject Set-Cookie headers to establish predetermined session identifiers, facilitating session fixation attacks.
The attack pattern involves crafting a URL with an injected cookie:
?redirect=/home%0D%0ASet-Cookie:%20sessionid=attacker_controlled_value;%20Path=/;%20HttpOnly
When victims click this link, the server’s response includes the injected cookie. The victim’s browser stores this cookie, and when they subsequently log in, they use the session identifier already known to the attacker. The attacker can then hijack the authenticated session without needing to steal credentials.
5. Security Control Bypass
Perhaps most concerning is CRLF injection’s ability to bypass security mechanisms like Cross-Origin Resource Sharing (CORS) policies, Content Security Policies (CSP), and Cross-Site Scripting (XSS) filters.
Attackers can inject permissive CORS headers:
%0D%0AAccess-Control-Allow-Origin:%20*%0D%0AAccess-Control-Allow-Credentials:%20true
This bypass allows JavaScript from attacker-controlled domains to access sensitive resources protected by same-origin policies, potentially exposing authentication tokens, personal data, or other confidential information.
Real-World Vulnerabilities and Impact
CVE-2024-52875: GFI KerioControl Critical RCE
In January 2025, researchers disclosed a critical CRLF injection vulnerability in GFI KerioControl firewalls affecting versions 9.2.5 through 9.4.5. The vulnerability stemmed from improper sanitization of the ‘dest’ GET parameter, which allowed attackers to inject line feed characters into Location headers.
The exploitation chain was particularly severe. Attackers could craft malicious URLs that, when clicked by administrators, triggered HTTP response splitting. This led to Cross-Site Scripting, which could then be chained to upload malicious firmware images, ultimately granting root access to the firewall. With over 23,800 internet-exposed instances globally, the vulnerability represented a significant threat to enterprise network security.
CVE-2024-20337: Cisco Secure Client SAML Authentication
Cisco disclosed a CRLF injection vulnerability in its Secure Client’s SAML authentication process. The flaw allowed unauthenticated remote attackers to conduct attacks against targeted users by persuading them to click crafted links during VPN session establishment.
Successful exploitation enabled attackers to execute arbitrary script code in browsers or access sensitive browser-based information, including valid SAML tokens. With these tokens, attackers could establish remote access VPN sessions with the privileges of affected users, potentially compromising enterprise networks.
Historical Context: Twitter and Industry-Wide Impact
In previous years, security researchers discovered CRLF injection vulnerabilities in major platforms including Twitter’s advertising endpoint. These real-world examples demonstrate that even well-resourced organizations with sophisticated security teams can fall victim to CRLF injection when input validation lapses occur.
The vulnerability class carries a P3 (medium) severity rating according to Bugcrowd’s Vulnerability Rating Taxonomy, but its ability to escalate to Remote Code Execution, as demonstrated in the KerioControl case, shows that contextual factors can elevate risk significantly.
Web Cache Poisoning Through CRLF
Web cache poisoning represents an advanced exploitation technique where attackers leverage CRLF injection to contaminate shared caches used by Content Delivery Networks (CDNs), proxy servers, or browser caches.
The attack mechanism exploits how caching systems store and serve responses. When an attacker successfully injects a malicious response that gets cached, all subsequent users requesting the same resource receive the poisoned content. This amplifies the attack’s impact from affecting individual users to compromising entire user populations.
For cache poisoning to succeed, attackers must: 1. Identify cacheable endpoints with CRLF vulnerabilities 2. Craft requests that inject malicious responses with appropriate cache headers 3. Time the attack so the malicious response gets stored in the cache 4. Ensure the poisoned cache entry serves malicious content to subsequent users
The persistence of cached entries makes this attack particularly damaging, as the malicious content continues affecting users until the cache expires or is manually purged.
Detection and Testing Methodologies
Manual Testing Approaches
Security researchers and penetration testers identify CRLF injection vulnerabilities through systematic testing. The process involves injecting various CRLF sequences into user-controllable parameters and observing application behavior.
Common test payloads include:
- %0D%0A (URL-encoded CRLF)
- %0D or %0A (individual components)
- %0D%0ASet-Cookie: test=value
- %0D%0A%0D%0A<html>test</html> (double CRLF for response splitting)
- Unicode variations: %E5%98%8A%E5%98%8D (alternative encodings)
Testers focus on parameters that influence HTTP headers, particularly: - Redirect parameters (url, redirect, dest, return) - Referrer values - User-Agent modifications - Cookie names and values - Custom header parameters
Automated Scanning Tools
Modern security testing benefits from specialized tools designed to detect CRLF injection vulnerabilities:
CRLFsuite: A fast, active scanner written in Go that systematically tests endpoints for CRLF injection vulnerabilities with comprehensive payload sets.
crlfuzz: A wordlist-based fuzzer supporting Unicode newline payloads, particularly effective for discovering edge cases and encoding bypasses.
crlfix: A 2024 utility that patches HTTP requests generated by Go programs and can test internal services for CRLF vulnerabilities.
Comprehensive web application security scanners like Acunetix and Invicti include CRLF detection modules within their broader vulnerability assessment capabilities, enabling organizations to identify these issues during regular security testing cycles.
Comprehensive Prevention Strategies
Input Validation and Sanitization
The primary defense against CRLF injection involves treating all user-supplied input as potentially malicious. Applications should never directly incorporate untrusted data into HTTP headers, log files, or other text streams without rigorous validation.
Effective input validation includes:
- Whitelisting acceptable characters: Define strict patterns for expected input and reject anything that doesn’t conform
- Removing CRLF sequences: Strip \r, \n, and their encoded variants from all user input before processing
- Length restrictions: Limit input length to reasonable values, preventing excessively long injection attempts
- Type enforcement: Ensure inputs match expected data types (numbers, emails, URLs) before processing
Output Encoding
When removing CRLF characters isn’t feasible, output encoding provides an alternative defense. Encoding transforms special characters into representations that don’t affect HTTP structure or log formatting.
For HTTP headers, use framework-specific encoding functions that handle CRLF sequences:
- Java: StringEscapeUtils.escapeJava() or OWASP ESAPI encoding methods
- PHP: htmlspecialchars() or filter_var() with appropriate flags
- Python: Built-in URL encoding functions or framework-specific header validators
- .NET: HttpUtility.UrlEncode() or framework sanitization methods
Framework-Level Protections
Modern web frameworks increasingly include built-in CRLF injection protections. Developers should: - Keep frameworks updated to benefit from latest security patches - Enable automatic header validation where available - Avoid disabling security features for convenience - Use framework-provided methods for header manipulation rather than manual string concatenation
For example, many recent framework versions automatically validate header values and reject those containing CRLF sequences, providing defense-in-depth even if application-level validation fails.
Secure Logging Practices
Protecting logs from injection requires specific measures:
OWASP ESAPI Logger: The Enterprise Security API provides a logging interface that automatically removes CRLF characters and can encode non-alphanumeric data. This library integrates seamlessly with Log4j and native Java logging.
Structured Logging with JSON: Converting logs to JSON format encapsulates each entry as a discrete object, making injection impossible. While this requires log management systems like the ELK stack (Elasticsearch, Logstalk, Kibana) for effective analysis, it eliminates log injection vulnerabilities.
Encoding before logging: Apply encoding functions to user data before writing to logs:
logger.info("User login: " + ESAPI.encoder().encodeForHTML(username));
Logback configuration: For Spring Boot applications, Logback can be configured with JSON encoders that automatically escape special characters, preventing log injection while maintaining structured log data.
Security Headers and Configuration
Implement defense-in-depth measures: - Content Security Policy (CSP): While CRLF injection can potentially bypass CSP, defining policies in both HTTP headers and HTML provides redundancy - Disable unnecessary headers: Remove or disable HTTP headers not required for application functionality - HTTP Strict Transport Security (HSTS): Enforce HTTPS to prevent man-in-the-middle attacks that could leverage CRLF vulnerabilities - Cache-Control directives: Properly configure caching behavior to limit cache poisoning impact
Code Review and Security Testing
Organizations should integrate CRLF injection detection into their software development lifecycle: - Conduct regular code reviews focusing on header manipulation and logging code - Include CRLF injection tests in automated security testing pipelines - Perform penetration testing specifically targeting injection vulnerabilities - Train developers on secure coding practices and common vulnerability patterns
Framework-Specific Considerations
Java Applications
Java applications should leverage OWASP ESAPI for encoding and validation:
String sanitized = ESAPI.encoder().encodeForURL(userInput);
For logging, integrate ESAPI Logger to automatically handle CRLF sequences:
Logger logger = ESAPI.getLogger("SecurityLogger");
logger.info(Logger.SECURITY_SUCCESS, "User action: " + userAction);
The DefaultHttpHeaders class in Netty enables or disables header validation via its constructor parameter. Always use new DefaultHttpHeaders(true) to enable validation.
PHP Applications
PHP developers should use built-in filtering and validation:
$cleaned = filter_var($input, FILTER_SANITIZE_STRING);
$encoded = urlencode($input);
For headers, use header() function with proper validation and avoid manual string concatenation when building responses.
Python/Django Applications
Django automatically validates header values in recent versions. For manual header manipulation:
from django.utils.http import urlencode
from urllib.parse import quote
sanitized = quote(user_input, safe='')
For logging, use Python’s standard logging module with formatters that escape special characters.
Node.js/Express Applications
Express applications should validate and sanitize input:
const validator = require('validator');
const sanitized = validator.escape(userInput);
For headers, use Express’s built-in methods rather than manual header construction:
res.redirect(301, validator.escape(userUrl));
The Future of CRLF Protection
As web technologies evolve, so do defenses against CRLF injection. HTTP/2 and HTTP/3 introduce binary framing that eliminates reliance on CRLF sequences for protocol structure, potentially reducing vulnerability surfaces. However, many applications continue operating over HTTP/1.1, maintaining the relevance of CRLF injection defenses.
Modern API frameworks increasingly adopt JSON-based communication, which naturally resists CRLF injection due to its structured format. However, applications must still protect traditional HTTP headers and logging systems that remain vulnerable.
Security automation and AI-powered code analysis tools increasingly detect CRLF injection vulnerabilities during development, shifting security left in the development lifecycle. These tools identify vulnerable code patterns before deployment, reducing the likelihood of production vulnerabilities.
Conclusion
CRLF injection remains a significant web application security concern in 2025, as evidenced by recent critical vulnerabilities in enterprise products. While conceptually simple—injecting newline characters into HTTP streams—the attack enables sophisticated exploitation chains leading to response hijacking, log tampering, session compromise, and security control bypass.
Organizations must implement comprehensive defenses including rigorous input validation, output encoding, framework-level protections, and secure logging practices. The combination of developer education, automated security testing, and defense-in-depth strategies provides the most effective protection against CRLF injection attacks.
As web technologies evolve, new protocol versions may reduce CRLF injection risks, but legacy systems and traditional HTTP communications ensure this vulnerability class will remain relevant for years to come. Security teams must maintain vigilance, continuously test for CRLF injection vulnerabilities, and ensure development practices incorporate robust defenses against this enduring threat.
Keywords: CRLF injection, HTTP response splitting, log injection, web application security, header manipulation, security control bypass, input validation, output encoding, XSS, cookie injection, cache poisoning, web vulnerability, cybersecurity 2025