HTTP Response Splitting
What is HTTP Response Splitting?
HTTP Response Splitting is a web security vulnerability that occurs when an attacker can inject malicious data into HTTP responses by exploiting improper handling of CRLF (Carriage Return Line Feed) sequences. This vulnerability allows attackers to split a single HTTP response into multiple responses, enabling various attacks including cache poisoning, cross-site scripting (XSS), session hijacking, and phishing.
Key Characteristics
- CRLF injection: Exploits improper handling of newline characters
- Response manipulation: Splits single response into multiple responses
- Protocol-level attack: Targets HTTP protocol implementation
- Multiple attack vectors: Various ways to exploit response splitting
- Common in web applications: Frequently found in custom header handling
- Authentication bypass: Can lead to session hijacking
- Information disclosure: May expose sensitive server information
- Cache manipulation: Can poison web caches
HTTP Response Splitting vs Other Web Attacks
| Attack | Method | Primary Target | Typical Impact | User Awareness |
|---|---|---|---|---|
| HTTP Response Splitting | CRLF injection | HTTP responses | Response manipulation, cache poisoning | Usually unaware |
| HTTP Header Injection | Header manipulation | HTTP headers | Header injection, XSS | Usually unaware |
| Cross-Site Scripting (XSS) | Script injection | User browsers | Data theft, session hijacking | May notice effects |
| SQL Injection | Database query manipulation | Database | Data theft, data manipulation | Usually unaware |
| Cache Poisoning | Response manipulation | Web caches | Malicious content delivery | Usually unaware |
How HTTP Response Splitting Works
Technical Mechanism
graph TD
A[Attacker] -->|1. Sends malicious request with CRLF| B[Web Application]
B -->|2. Processes user input| C[Server Logic]
C -->|3. Includes CRLF in response| B
B -->|4. Returns split response| D[Proxy/Cache]
D -->|5. Caches malicious response| E[Victim Browser]
E -->|6. Processes malicious content| F[Malicious Effects]
Common HTTP Response Splitting Process
- Input identification: Attacker finds user input reflected in HTTP responses
- Injection point discovery: Identifies where input is included in headers/body
- Malicious payload crafting: Creates payload with CRLF sequences
- Request submission: Sends request with malicious payload
- Response splitting: Server includes CRLF and splits response
- Cache poisoning: Proxy caches malicious response
- Attack execution: Victims receive malicious content
HTTP Response Splitting Attack Vectors
Common Attack Methods
| Vector | Description | Example |
|---|---|---|
| Cache Poisoning | Injecting malicious content into cache | %0d%0a%0d%0a<script>alert(1)</script> |
| Cross-Site Scripting (XSS) | Injecting JavaScript via split response | %0d%0aContent-Length: 0%0d%0a%0d%0a<script>alert(1)</script> |
| Session Fixation | Injecting malicious session cookies | %0d%0aSet-Cookie: sessionid=attacker123 |
| Open Redirect | Injecting malicious redirect | %0d%0aLocation: https://attacker.com |
| Phishing | Injecting fake login forms | %0d%0aContent-Type: text/html%0d%0a%0d%0a<html>Fake Login</html> |
| Information Disclosure | Injecting sensitive data | %0d%0aX-Secret: confidential-data |
| HTTP Request Smuggling | Combining with request smuggling | %0d%0aTransfer-Encoding: chunked |
| Header Injection | Injecting arbitrary headers | %0d%0aX-Injected: malicious-value |
HTTP Response Splitting Exploitation Techniques
1. Cache Poisoning via Response Splitting
Attack Scenario: Injecting malicious content into web caches.
Vulnerable Code (PHP):
<?php
// Vulnerable code - user input in Location header
$redirectUrl = $_GET['url'];
header("Location: " . $redirectUrl);
exit;
?>
Attack Process:
- Attacker identifies vulnerable redirect endpoint
- Crafts malicious URL:
https://example.com/redirect?url=%0d%0aContent-Length:%200%0d%0a%0d%0aHTTP/1.1%20200%20OK%0d%0aContent-Type:%20text/html%0d%0aContent-Length:%2035%0d%0a%0d%0a<script>alert(document.cookie)</script> - Server processes request and splits response
- Proxy caches the malicious second response
- Subsequent users receive malicious content
- XSS attack is executed in victims' browsers
Prevention:
- Input validation: Validate all user input
- CRLF filtering: Remove CRLF characters from input
- Header encoding: Encode data in headers
- Cache controls: Implement proper cache controls
- Security headers: Use Content Security Policy
2. Cross-Site Scripting (XSS) via Response Splitting
Attack Scenario: Injecting JavaScript via split response.
Vulnerable Code (Node.js):
// Vulnerable code - user input in response
app.get('/search', (req, res) => {
const query = req.query.q;
res.setHeader('X-Search-Query', query);
res.send(`Search results for: ${query}`);
});
Attack Process:
- Attacker identifies vulnerable search endpoint
- Crafts malicious URL:
/search?q=%0d%0aContent-Length:%200%0d%0a%0d%0a<script>alert(1)</script> - Server processes request and splits response
- Victim's browser receives split response
- Browser processes second response as HTML
- XSS payload executes in victim's browser
Prevention:
- Output encoding: Encode all user input in responses
- CRLF sanitization: Remove CRLF characters from input
- Content Security Policy: Implement CSP
- Header validation: Validate all header values
- Response validation: Validate complete response structure
3. Session Fixation via Response Splitting
Attack Scenario: Injecting malicious session cookies.
Vulnerable Code (Python Flask):
@app.route('/set-lang')
def set_lang():
lang = request.args.get('lang', '')
response = make_response(f"Language set to {lang}")
response.headers['Set-Cookie'] = f'lang={lang}; Path=/'
return response
Attack Process:
- Attacker identifies vulnerable language endpoint
- Crafts malicious URL:
/set-lang?lang=en%0d%0aSet-Cookie:%20sessionid=attacker123 - Server processes request and splits response
- Victim's browser receives split response
- Browser sets attacker's session ID
- Victim logs in with attacker's session ID
- Attacker hijacks victim's session
Prevention:
- Cookie validation: Validate cookie values
- Session security: Regenerate session IDs after login
- CRLF filtering: Remove CRLF characters from input
- Header encoding: Encode data in headers
- Security headers: Use HttpOnly, Secure, SameSite flags
4. Open Redirect via Response Splitting
Attack Scenario: Injecting malicious redirect via split response.
Vulnerable Code (Java):
@RequestMapping("/redirect")
public String redirect(@RequestParam String url, HttpServletResponse response) {
response.setHeader("Location", url);
return "redirect:" + url;
}
Attack Process:
- Attacker identifies vulnerable redirect endpoint
- Crafts malicious URL:
/redirect?url=%0d%0aContent-Length:%200%0d%0a%0d%0aHTTP/1.1%20302%20Found%0d%0aLocation:%20https://attacker.com/phishing - Server processes request and splits response
- Victim's browser receives split response
- Browser processes second response as redirect
- Victim is redirected to attacker's phishing site
Prevention:
- URL validation: Validate redirect URLs
- Whitelist domains: Only allow specific domains
- CRLF filtering: Remove CRLF characters from input
- Redirect encoding: Encode redirect URLs
- User confirmation: Require confirmation for external redirects
HTTP Response Splitting Prevention Methods
1. Input Validation and Sanitization
Implementation Strategies:
- Input validation: Validate all user input
- CRLF filtering: Remove CRLF characters from input
- Character whitelisting: Only allow safe characters
- Length restrictions: Limit input length
- Type checking: Validate input types
Example (Secure Input Validation in PHP):
<?php
// Secure redirect implementation
function isValidUrl($url) {
// Remove CRLF characters
$cleanUrl = str_replace(["\r", "\n", "%0d", "%0a"], '', $url);
// Validate URL format
if (!filter_var($cleanUrl, FILTER_VALIDATE_URL)) {
return false;
}
// Check against whitelist
$allowedDomains = ['example.com', 'trusted-partner.com'];
$host = parse_url($cleanUrl, PHP_URL_HOST);
return in_array($host, $allowedDomains);
}
$redirectUrl = $_GET['url'] ?? '/';
// Validate and sanitize
if (isValidUrl($redirectUrl)) {
header("Location: " . $redirectUrl);
exit;
} else {
// Log suspicious activity
error_log("Invalid redirect attempt: " . $_GET['url']);
header("Location: /error?code=invalid_redirect");
exit;
}
?>
2. Output Encoding for Headers
Implementation Strategies:
- Header encoding: Encode data in headers
- CRLF protection: Prevent CRLF injection
- Context-aware encoding: Use appropriate encoding for headers
- Library usage: Use secure header libraries
- Automated encoding: Implement automatic header encoding
Example (Secure Header Encoding in Node.js):
const express = require('express');
const app = express();
// Middleware for secure header setting
function setSecureHeader(res, name, value) {
// Remove CRLF characters
const cleanValue = String(value).replace(/[\r\n]/g, '');
// Encode special characters
const encodedValue = encodeURIComponent(cleanValue)
.replace(/%3A/gi, ':') // Allow colons
.replace(/%2F/gi, '/') // Allow slashes
.replace(/%3F/gi, '?') // Allow question marks
.replace(/%3D/gi, '=') // Allow equals
.replace(/%26/gi, '&'); // Allow ampersands
res.setHeader(name, encodedValue);
}
// Secure endpoint
app.get('/set-custom-header', (req, res) => {
const customValue = req.query.value || '';
// Set header securely
setSecureHeader(res, 'X-Custom-Header', customValue);
res.send('Header set securely');
});
3. Secure Header Libraries
Implementation Strategies:
- Use secure libraries: Leverage well-tested libraries
- Framework integration: Use framework-specific security features
- Automated protection: Implement automatic header security
- Regular updates: Keep libraries updated
- Configuration management: Secure library configuration
Example (Using Helmet.js in Node.js):
const express = require('express');
const helmet = require('helmet');
const app = express();
// Use Helmet for secure headers
app.use(helmet());
// Additional security middleware
app.use((req, res, next) => {
// Prevent CRLF injection
const maliciousPatterns = [/\r/, /\n/, /%0d/, /%0a/];
// Check all request headers for injection attempts
for (const [name, value] of Object.entries(req.headers)) {
if (maliciousPatterns.some(pattern => pattern.test(value))) {
console.warn(`CRLF injection attempt detected in ${name}: ${value}`);
return res.status(400).send('Invalid header value');
}
}
next();
});
// Secure redirect endpoint
app.get('/redirect', (req, res) => {
const url = req.query.url;
try {
// Remove CRLF characters
const cleanUrl = String(url).replace(/[\r\n]/g, '');
// Validate URL
const parsedUrl = new URL(cleanUrl);
// Check against whitelist
const allowedDomains = ['example.com', 'trusted-partner.com'];
if (!allowedDomains.includes(parsedUrl.hostname)) {
throw new Error('Domain not allowed');
}
// Secure redirect
res.redirect(cleanUrl);
} catch (e) {
console.warn(`Invalid redirect attempt: ${url}`);
res.redirect('/error?code=invalid_redirect');
}
});
4. Content Security Policy (CSP)
Implementation Strategies:
- CSP headers: Implement Content Security Policy
- Directive configuration: Configure appropriate directives
- Reporting: Enable CSP violation reporting
- Testing: Test CSP in report-only mode first
- Regular updates: Update CSP as application changes
Example (CSP Implementation):
# HTTP Response Headers
Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline' https://trusted.cdn.com; style-src 'self' 'unsafe-inline'; img-src 'self' data: https://images.example.com; font-src 'self' https://fonts.example.com; connect-src 'self' https://api.example.com; frame-src 'none'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'; report-uri https://example.com/csp-report-endpoint
Content-Security-Policy-Report-Only: default-src 'self'; report-uri https://example.com/csp-report-endpoint
Example (Node.js CSP Implementation):
const express = require('express');
const helmet = require('helmet');
const { v4: uuidv4 } = require('uuid');
const app = express();
// Generate nonce for CSP
app.use((req, res, next) => {
res.locals.cspNonce = uuidv4();
next();
});
// Set CSP headers
app.use(
helmet.contentSecurityPolicy({
directives: {
defaultSrc: ["'self'"],
scriptSrc: [
"'self'",
(req, res) => `'nonce-${res.locals.cspNonce}'`,
'https://trusted.cdn.com'
],
styleSrc: ["'self'", "'unsafe-inline'", 'https://fonts.googleapis.com'],
imgSrc: ["'self'", 'data:', 'https://images.example.com'],
fontSrc: ["'self'", 'https://fonts.gstatic.com'],
connectSrc: ["'self'", 'https://api.example.com'],
frameSrc: ["'none'"],
objectSrc: ["'none'"],
baseUri: ["'self'"],
formAction: ["'self'"],
frameAncestors: ["'none'"],
reportUri: '/csp-report-endpoint'
},
reportOnly: false
})
);
// CSP report endpoint
app.post('/csp-report-endpoint', express.json({ type: 'application/csp-report' }), (req, res) => {
console.warn('CSP Violation:', req.body);
res.status(204).end();
});
HTTP Response Splitting in Modern Architectures
Single Page Applications (SPAs)
Challenges:
- API communication: Headers in API responses
- Client-side routing: Client-side redirect handling
- State management: Client-side state manipulation
- Authentication: JWT and token handling
- CORS: Cross-origin resource sharing
Best Practices:
- API security: Secure all API endpoints
- Header validation: Validate all response headers
- CRLF protection: Prevent CRLF injection in APIs
- Response validation: Validate complete response structure
- Client-side protection: Implement client-side security
Example (Secure SPA with API Protection):
// Secure API service for SPA
class ApiService {
constructor() {
this.baseUrl = '/api';
}
async request(endpoint, options = {}) {
// Validate endpoint
if (!/^[a-zA-Z0-9\-_/]+$/.test(endpoint)) {
throw new Error('Invalid endpoint');
}
// Set default headers
const headers = {
'Content-Type': 'application/json',
...options.headers
};
// Remove potentially dangerous headers
const safeHeaders = {};
for (const [key, value] of Object.entries(headers)) {
if (!/[\r\n]/.test(value)) {
safeHeaders[key] = value;
}
}
// Make request
const response = await fetch(`${this.baseUrl}${endpoint}`, {
...options,
headers: safeHeaders,
credentials: 'same-origin'
});
// Validate response structure
if (!response.headers.get('content-type')?.includes('application/json')) {
throw new Error('Invalid response content type');
}
// Check for CRLF in response
const responseText = await response.text();
if (/[\r\n]/.test(responseText)) {
throw new Error('Potential CRLF injection detected in response');
}
return response.json();
}
}
// Usage
const api = new ApiService();
api.request('/data', {
headers: {
'X-Custom-Header': 'safe-value'
}
}).then(data => console.log(data))
.catch(error => console.error('API Error:', error));
Microservices Architecture
Challenges:
- Service-to-service communication: Headers in inter-service calls
- API gateways: Header handling at gateway level
- Authentication: JWT propagation
- Logging: Header information in logs
- Caching: Header-based caching
Best Practices:
- Gateway security: Secure API gateway
- Header validation: Validate headers at all levels
- CRLF protection: Prevent CRLF injection in all services
- Service isolation: Isolate sensitive services
- Token validation: Validate authentication tokens
Example (Kubernetes Ingress with CRLF Protection):
# Secure ingress configuration
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: secure-ingress
annotations:
nginx.ingress.kubernetes.io/configuration-snippet: |
# Block CRLF injection
if ($request_uri ~* (\r|\n|%0d|%0a)) {
return 403 "CRLF injection detected";
}
# Validate headers
if ($http_user_agent ~* (\r|\n|%0d|%0a)) {
return 403 "Malicious header detected";
}
# Add security headers
add_header X-Content-Type-Options "nosniff";
add_header X-Frame-Options "DENY";
add_header Content-Security-Policy "default-src 'self'";
add_header Referrer-Policy "strict-origin-when-cross-origin";
spec:
rules:
- host: example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: frontend-service
port:
number: 80
Serverless Architectures
Challenges:
- Stateless nature: No persistent server-side state
- Function isolation: Secure function execution
- API security: Securing serverless APIs
- Event sources: Securing event triggers
- Header handling: Secure header processing
Best Practices:
- API gateway security: Secure all API endpoints
- Function validation: Validate all inputs
- CRLF protection: Prevent CRLF injection in functions
- Header security: Secure header processing
- Monitoring: Monitor for suspicious activity
Example (AWS Lambda with CRLF Protection):
const { URL } = require('url');
exports.handler = async (event) => {
// Validate request
if (!event.headers) {
return {
statusCode: 400,
body: JSON.stringify({ error: 'Missing headers' })
};
}
// Check for CRLF in request
const crlfPatterns = [/\r/, /\n/, /%0d/, /%0a/];
for (const [name, value] of Object.entries(event.headers)) {
if (crlfPatterns.some(pattern => pattern.test(value))) {
console.warn(`CRLF injection attempt detected in ${name}: ${value}`);
return {
statusCode: 400,
body: JSON.stringify({ error: 'CRLF injection detected' })
};
}
}
// Check for CRLF in query parameters
if (event.queryStringParameters) {
for (const [name, value] of Object.entries(event.queryStringParameters)) {
if (crlfPatterns.some(pattern => pattern.test(value))) {
console.warn(`CRLF injection attempt detected in ${name}: ${value}`);
return {
statusCode: 400,
body: JSON.stringify({ error: 'CRLF injection detected' })
};
}
}
}
// Secure response
return {
statusCode: 200,
headers: {
'Content-Type': 'application/json',
'Strict-Transport-Security': 'max-age=31536000; includeSubDomains; preload',
'X-Content-Type-Options': 'nosniff',
'X-Frame-Options': 'DENY',
'Content-Security-Policy': "default-src 'self'",
'Referrer-Policy': 'strict-origin-when-cross-origin'
},
body: JSON.stringify({ message: 'Secure response' })
};
};
HTTP Response Splitting Testing and Detection
Manual Testing Techniques
- CRLF injection testing:
- Test with raw CRLF characters (
\r\n) - Test with URL-encoded CRLF (
%0d%0a) - Test with various CRLF combinations
- Test with different HTTP methods
- Test with raw CRLF characters (
- Response splitting testing:
- Test for complete response splitting
- Test for partial response splitting
- Test for cache poisoning
- Test for XSS via response splitting
- Header testing:
- Test Location header injection
- Test Set-Cookie header injection
- Test Content-Type header injection
- Test custom header injection
- Cache testing:
- Test cache poisoning
- Test cache control header injection
- Test ETag manipulation
- Test Last-Modified header injection
- Browser testing:
- Test in different browsers
- Test with JavaScript disabled
- Test with different security settings
- Test with proxy tools
Automated Testing Tools
- Burp Suite:
- Scanner: Automated response splitting detection
- Repeater: Manual CRLF testing
- Intruder: CRLF injection fuzzing
- Proxy: Response inspection
- OWASP ZAP:
- Active Scan: Response splitting vulnerabilities
- Fuzzer: CRLF injection testing
- Forced User Mode: Response splitting simulation
- Scripting: Custom response splitting tests
- Browser Developer Tools:
- Network tab: Inspect response headers
- Console: Test response splitting effects
- Overrides: Test response manipulation
- Security tab: Check security headers
- Custom Scripts:
- CRLF testing: Scripts to test CRLF injection
- Response analysis: Scripts to analyze split responses
- Vulnerability scanning: Custom scanners for response splitting
Example (Python Script for Response Splitting Testing):
import requests
import re
def test_response_splitting(url, param):
results = {
'url': url,
'param': param,
'vulnerable': False,
'issues': [],
'headers': {}
}
# Test payloads
payloads = [
'%0d%0aX-Injected: malicious',
'%0d%0a%0d%0a<script>alert(1)</script>',
'%0d%0aContent-Length: 0%0d%0a%0d%0aHTTP/1.1 200 OK',
'%0d%0aLocation: https://attacker.com',
'%0d%0aSet-Cookie: sessionid=attacker123',
'\r\nX-Injected: malicious',
'\r\n\r\n<script>alert(1)</script>'
]
for payload in payloads:
try {
# Test with parameter
test_url = f"{url}?{param}={payload}"
response = requests.get(test_url, timeout=10)
# Check response headers
results['headers'] = dict(response.headers)
# Check for injected headers
if 'x-injected' in [h.lower() for h in response.headers]:
results['issues'].append(f"Header injection successful with payload: {payload}")
results['vulnerable'] = True
# Check for multiple responses
if len(response.history) > 0:
results['issues'].append(f"Response splitting detected with payload: {payload}")
results['vulnerable'] = True
# Check for XSS via response splitting
if response.text and '<script>' in response.text.lower():
results['issues'].append(f"XSS via response splitting with payload: {payload}")
results['vulnerable'] = True
except Exception as e:
results['issues'].append(f"Error testing payload {payload}: {str(e)}")
return results
# Example usage
result = test_response_splitting(
url="https://example.com/search",
param="q"
)
print(f"URL: {result['url']}")
print(f"Parameter: {result['param']}")
print(f"Vulnerable: {'Yes' if result['vulnerable'] else 'No'}")
print("Issues:")
for issue in result['issues']:
print(f"- {issue}")
print("Headers:")
for header, value in result.get('headers', {}).items():
print(f"- {header}: {value}")
Code Analysis Techniques
- Static Analysis (SAST):
- Pattern matching: Identify unsafe header usage
- Data flow analysis: Trace user input to responses
- Taint analysis: Track untrusted input to output
- CRLF detection: Identify CRLF injection points
- Dynamic Analysis (DAST):
- Runtime monitoring: Monitor response generation
- Fuzz testing: Test CRLF injection payloads
- Behavioral analysis: Analyze response splitting behavior
- Cache testing: Test cache poisoning
- Interactive Analysis (IAST):
- Runtime instrumentation: Monitor response handling
- Input tracking: Track user input to responses
- Vulnerability detection: Identify response splitting vulnerabilities
- Real-time analysis: Analyze during execution
Example (Semgrep Rule for Response Splitting):
rules:
- id: crlf-injection-response
pattern: |
$RESPONSE.setHeader($NAME, $$USER_INPUT)
...
// no CRLF sanitization
message: "Potential HTTP response splitting - user input used in headers without CRLF sanitization"
languages: [javascript, java, csharp, python]
severity: ERROR
metadata:
cwe: "CWE-113: Improper Neutralization of CRLF Sequences in HTTP Headers ('HTTP Response Splitting')"
owasp: "A03:2021 - Injection"
- id: unsafe-response-write
pattern: |
$RESPONSE.write($$USER_INPUT)
...
// no CRLF sanitization
message: "Potential HTTP response splitting - user input written to response without CRLF sanitization"
languages: [javascript, java, csharp, python]
severity: ERROR
metadata:
cwe: "CWE-113: Improper Neutralization of CRLF Sequences in HTTP Headers ('HTTP Response Splitting')"
owasp: "A03:2021 - Injection"
- id: crlf-in-redirect
pattern: |
$RESPONSE.redirect($$USER_INPUT)
...
// no CRLF sanitization
message: "Potential HTTP response splitting - user input used in redirect without CRLF sanitization"
languages: [javascript, java, csharp, python]
severity: ERROR
metadata:
cwe: "CWE-113: Improper Neutralization of CRLF Sequences in HTTP Headers ('HTTP Response Splitting')"
owasp: "A03:2021 - Injection"
- id: crlf-in-cookie
pattern: |
$RESPONSE.setCookie($NAME, $$USER_INPUT)
...
// no CRLF sanitization
message: "Potential HTTP response splitting - user input used in cookie without CRLF sanitization"
languages: [javascript, java, csharp, python]
severity: ERROR
metadata:
cwe: "CWE-113: Improper Neutralization of CRLF Sequences in HTTP Headers ('HTTP Response Splitting')"
owasp: "A03:2021 - Injection"
- id: crlf-in-response-body
pattern: |
$RESPONSE.send($$USER_INPUT)
...
// no CRLF sanitization
message: "Potential HTTP response splitting - user input sent in response body without CRLF sanitization"
languages: [javascript, java, csharp, python]
severity: WARNING
metadata:
cwe: "CWE-113: Improper Neutralization of CRLF Sequences in HTTP Headers ('HTTP Response Splitting')"
owasp: "A03:2021 - Injection"
HTTP Response Splitting Case Studies
Case Study 1: Major Web Server Vulnerability (2004)
Incident: HTTP response splitting vulnerability in multiple web servers.
Attack Details:
- Vulnerability: Web servers improperly handled CRLF sequences
- Attack method: CRLF injection in HTTP headers
- Impact: Widespread cache poisoning and XSS attacks
- Discovery: Security researchers
- Exploitation: Multiple web applications affected
Technical Flow:
- Multiple web servers had CRLF handling vulnerabilities
- Attackers could inject CRLF sequences in HTTP headers
- Servers would split responses at CRLF sequences
- Attackers could inject arbitrary response content
- Proxies would cache malicious responses
- Users would receive malicious content from trusted sites
- Widespread XSS and phishing attacks occurred
Lessons Learned:
- Protocol security: Importance of proper HTTP protocol handling
- Server security: Need for secure web server implementations
- Patch management: Importance of timely security updates
- Vendor coordination: Need for coordinated vulnerability disclosure
- Security awareness: Importance of security in web development
Case Study 2: E-Commerce Platform (2012)
Incident: HTTP response splitting leading to session hijacking.
Attack Details:
- Vulnerability: User input reflected in Set-Cookie header
- Attack method: CRLF injection in cookie values
- Impact: Thousands of accounts compromised
- Discovery: Security researcher
- Exploitation: Phishing emails with malicious links
Technical Flow:
- E-commerce platform had vulnerable search endpoint
- Search query reflected in X-Search-Query header
- Attacker crafted malicious URL with CRLF injection:
/search?q=test%0d%0aSet-Cookie:%20sessionid=attacker123 - Server processed request and split response
- Victim's browser received split response
- Browser set attacker's session ID
- Victim logged in with attacker's session ID
- Attacker hijacked victim's account
Lessons Learned:
- Header validation: Critical importance of validating header values
- Session security: Need for secure session management
- Input sanitization: Importance of sanitizing all user input
- Security testing: Need for comprehensive security testing
- Incident response: Need for rapid vulnerability patching
Case Study 3: Government Website (2015)
Incident: HTTP response splitting leading to cache poisoning.
Attack Details:
- Vulnerability: User input reflected in Cache-Control header
- Attack method: CRLF injection in cache headers
- Impact: Sensitive data exposure
- Discovery: Security audit
- Exploitation: Malicious requests to poison cache
Technical Flow:
- Government website had vulnerable API endpoint
- API parameter reflected in X-API-Response header
- Attacker sent request with CRLF injection:
/api/data?format=json%0d%0aCache-Control:%20max-age=3600%0d%0a%0d%0a<script>alert(1)</script> - Server processed request and split response
- Proxy cached the malicious second response
- Subsequent users received cached malicious content
- Sensitive data was exposed to attackers
Lessons Learned:
- Cache security: Need for secure caching controls
- Header validation: Importance of validating all headers
- Data protection: Need for proper data handling
- Security audits: Need for regular security assessments
- Incident response: Need for rapid breach response
Case Study 4: Social Media Platform (2018)
Incident: HTTP response splitting leading to open redirect.
Attack Details:
- Vulnerability: User input reflected in Location header
- Attack method: CRLF injection in redirect URLs
- Impact: Widespread phishing attacks
- Discovery: Security monitoring
- Exploitation: Malicious posts with injected redirects
Technical Flow:
- Social media platform had vulnerable share endpoint
- Share URL parameter reflected in Location header
- Attacker created malicious post with link:
/share?url=https://example.com%0d%0aContent-Length:%200%0d%0a%0d%0aHTTP/1.1%20302%20Found%0d%0aLocation:%20https://fake-social.com/login - Victims clicked link to share content
- Server processed request and split response
- Victims' browsers processed second response as redirect
- Victims redirected to attacker's phishing site
- Attacker collected credentials
Lessons Learned:
- Redirect validation: Critical need for secure redirects
- Phishing protection: Need for better phishing detection
- User verification: Need for user confirmation of redirects
- Security monitoring: Need for real-time security monitoring
- User education: Teaching users about phishing risks
HTTP Response Splitting and Compliance
Regulatory Implications
HTTP response splitting vulnerabilities can lead to severe compliance violations with various regulations:
- GDPR: General Data Protection Regulation
- Data protection: Response splitting can lead to data exposure
- Breach notification: Requires notification of data breaches
- Fines: Up to 4% of global revenue or €20 million
- User rights: Violations of user data protection rights
- PCI DSS: Payment Card Industry Data Security Standard
- Cardholder data protection: Response splitting can expose payment data
- Requirement 6: Develop and maintain secure systems
- Requirement 10: Track and monitor all access to network resources
- Requirement 11: Regularly test security systems
- HIPAA: Health Insurance Portability and Accountability Act
- PHI protection: Response splitting can expose protected health information
- Security rule: Implement technical safeguards
- Breach notification: Report breaches affecting PHI
- Privacy rule: Protect individual health information
- PSD2: Payment Services Directive 2
- Strong customer authentication: Response splitting can bypass authentication
- Security measures: Requires secure authentication
- Incident reporting: Report security incidents
- User protection: Protect users from fraud
- NIST SP 800-53: Security and Privacy Controls
- Access control: Prevent unauthorized access
- System integrity: Protect system integrity
- Audit logging: Log all security-relevant events
- Incident response: Implement incident response capabilities
Compliance Requirements
| Regulation | Requirement | HTTP Response Splitting Prevention |
|---|---|---|
| GDPR | Protect personal data | Validate headers, sanitize input, secure data |
| PCI DSS | Protect cardholder data | Secure headers, validate input, monitor access |
| HIPAA | Protect health information | Secure headers, validate input, protect PHI |
| PSD2 | Strong authentication | Secure authentication, validate input |
| NIST SP 800-53 | System integrity | Validate headers, monitor systems, secure data |
HTTP Response Splitting in the OWASP Top 10
OWASP Top 10 2021: HTTP response splitting is primarily related to:
- A03:2021 - Injection: Response splitting as a form of injection attack
- A01:2021 - Broken Access Control: Response manipulation bypassing access controls
- A05:2021 - Security Misconfiguration: Missing security controls
- A07:2021 - Identification and Authentication Failures: Response manipulation affecting authentication
Key Points:
- Prevalence: Common in web applications with custom header handling
- Exploitability: Can be exploited with simple techniques
- Impact: Can lead to XSS, session hijacking, data exposure
- Detectability: Often detectable with proper testing
- Business Impact: Can cause data breaches and regulatory fines
OWASP Recommendations:
- Input validation: Validate all user input
- Output encoding: Encode data in responses
- CRLF filtering: Remove CRLF characters from input
- Security headers: Implement proper security headers
- Content Security Policy: Implement CSP
- Secure coding: Follow secure coding practices
- Security testing: Regular vulnerability scanning
- Patch management: Keep all software updated
- Security awareness: Educate developers about response splitting
Advanced HTTP Response Splitting Techniques
1. HTTP Request Smuggling with Response Splitting
Technique: Combining response splitting with HTTP request smuggling.
Attack Scenario:
- Attacker injects CRLF sequences in request
- Front-end server processes request differently than back-end
- Response splitting occurs due to CRLF injection
- Request smuggling enables cache poisoning
Process:
- Attacker sends request with CRLF injection:
POST / HTTP/1.1 Host: example.com Transfer-Encoding: chunked Content-Length: 6 0 GET /admin HTTP/1.1 Host: example.com X-Ignore: X - Front-end server uses Content-Length and processes first request
- Back-end server uses Transfer-Encoding and processes second request
- Response splitting occurs due to CRLF injection
- Cache poisoning enables persistent attack
Prevention:
- Consistent header parsing: Ensure consistent header parsing
- Request validation: Validate all HTTP requests
- CRLF sanitization: Remove CRLF characters from input
- Protocol enforcement: Enforce HTTP protocol compliance
- Security testing: Test for request smuggling vulnerabilities
2. Web Cache Deception with Response Splitting
Technique: Using response splitting to manipulate cache behavior.
Attack Scenario:
- Attacker injects CRLF sequences in request
- Server splits response and includes sensitive data
- Proxy caches malicious response with sensitive data
- Attacker accesses cached sensitive data
Process:
- Attacker sends request with CRLF injection:
GET /profile.php/nonexistent.css HTTP/1.1Host: example.comX-Custom: value%0d%0aCache-Control: public, max-age=3600 - Server processes request and splits response
- Second response includes sensitive user data
- Proxy caches response with sensitive data
- Attacker requests same URL and gets cached sensitive data
Prevention:
- Cache controls: Implement proper cache controls
- CRLF filtering: Remove CRLF characters from input
- Sensitive data protection: Don't include sensitive data in cacheable responses
- Cache key validation: Validate cache keys
- Security testing: Test for cache deception vulnerabilities
3. Server-Side Request Forgery (SSRF) via Response Splitting
Technique: Using response splitting to manipulate server-side requests.
Attack Scenario:
- Attacker injects CRLF sequences in request
- Server processes CRLF and makes internal requests
- Attacker gains access to internal systems
Process:
- Attacker identifies vulnerable proxy endpoint
- Injects CRLF sequences:
GET /proxy?url=http://internal-server%0d%0aX-Forwarded-Host: attacker.com HTTP/1.1 - Server processes CRLF and makes request to attacker.com
- Attacker receives internal server information
- Attacker gains access to internal systems
Prevention:
- Header validation: Validate all headers
- CRLF filtering: Remove CRLF characters from input
- Internal request security: Secure internal requests
- Network segmentation: Isolate internal systems
- Security testing: Test for SSRF vulnerabilities
4. Cross-Origin Resource Sharing (CORS) Misconfiguration via Response Splitting
Technique: Using response splitting to manipulate CORS headers.
Attack Scenario:
- Attacker injects CRLF sequences in request
- Server includes attacker's CORS headers in response
- Browser allows cross-origin requests to attacker's site
- Attacker steals sensitive data
Process:
- Attacker identifies vulnerable API endpoint
- Injects CRLF sequences:
GET /api/data HTTP/1.1Host: example.comOrigin: https://attacker.com%0d%0aAccess-Control-Allow-Origin: * - Server reflects Origin header and splits response
- Browser processes second response with CORS headers
- Browser allows cross-origin request to attacker.com
- Attacker steals sensitive data via XHR
Prevention:
- CORS validation: Validate CORS headers
- Origin whitelisting: Only allow specific origins
- CRLF filtering: Remove CRLF characters from input
- Security testing: Test for CORS misconfigurations
- Content Security Policy: Implement CSP
5. HTTP/2 Response Splitting
Technique: Exploiting HTTP/2 header compression and multiplexing.
Attack Scenario:
- Attacker injects CRLF sequences in HTTP/2 requests
- HTTP/2 header compression allows response splitting
- Server processes malicious headers
- Attacker exploits vulnerability
Process:
- Attacker establishes HTTP/2 connection
- Injects CRLF sequences using HPACK compression
- Server processes headers and splits response
- Attacker exploits response splitting vulnerability
- Malicious effects are triggered
Prevention:
- HTTP/2 security: Secure HTTP/2 implementations
- Header validation: Validate all HTTP/2 headers
- CRLF filtering: Remove CRLF characters from input
- Protocol enforcement: Enforce HTTP/2 protocol compliance
- Security testing: Test for HTTP/2 vulnerabilities
HTTP Response Splitting Mitigation Strategies
Defense in Depth Approach
- Input Layer:
- Validate all user input
- Sanitize all input data
- Filter CRLF characters
- Implement input whitelisting
- Use parameterized interfaces
- Processing Layer:
- Encode data for responses
- Validate header values
- Use secure header libraries
- Implement header whitelisting
- Sanitize all output
- Output Layer:
- Validate complete response structure
- Implement security headers
- Use Content Security Policy
- Validate all response headers
- Encode all output
- Transport Layer:
- Always use HTTPS
- Implement HSTS
- Use secure protocols
- Implement certificate pinning
- Secure all communications
- Monitoring Layer:
- Log all response manipulations
- Monitor for suspicious responses
- Alert on response splitting attempts
- Implement incident response
- Regular security audits
Secure Development Lifecycle
- Design Phase:
- Threat modeling for response security
- Security requirements definition
- Secure architecture design
- Data flow analysis
- Response validation planning
- Development Phase:
- Secure coding standards
- Code reviews
- Static analysis
- Dependency scanning
- CRLF filtering implementation
- Testing Phase:
- Penetration testing
- Dynamic analysis
- Fuzz testing
- Vulnerability scanning
- Response validation testing
- Deployment Phase:
- Secure configuration
- Security headers
- Monitoring setup
- Access controls
- Response validation
- Maintenance Phase:
- Patch management
- Security updates
- Continuous monitoring
- Incident response
- Regular security testing
Emerging Technologies
- AI-Powered Security:
- Behavioral analysis: Analyze response patterns
- Anomaly detection: Detect unusual response behavior
- Automated response: Block suspicious responses
- Predictive security: Identify potential vulnerabilities
- Automated Security Testing:
- Continuous scanning: Regular vulnerability scanning
- Automated fuzzing: Automated response splitting testing
- Integration testing: Security testing in CI/CD
- Regression testing: Ensure fixes don't break security
- Secure Response Frameworks:
- Standardized security: Standard response security implementations
- Automated protection: Automatic response validation
- Framework integration: Security integrated into frameworks
- Regular updates: Updated security controls
- Runtime Application Self-Protection (RASP):
- Real-time protection: Protect against response splitting at runtime
- Behavioral analysis: Analyze response behavior
- Automated response: Block malicious responses
- Integration: Seamless integration with applications
- Zero Trust Architecture:
- Continuous authentication: Authenticate every response
- Least privilege: Grant minimal necessary access
- Micro-segmentation: Isolate sensitive components
- Continuous monitoring: Monitor all response activity
Conclusion
HTTP Response Splitting represents one of the most dangerous and versatile web security vulnerabilities, enabling attackers to manipulate the fundamental HTTP protocol itself. By exploiting improper handling of CRLF (Carriage Return Line Feed) sequences, attackers can split single HTTP responses into multiple responses, creating opportunities for cache poisoning, cross-site scripting (XSS), session hijacking, phishing, and a wide range of other attacks.
The unique characteristics of HTTP response splitting make it particularly insidious:
- Protocol-level attack: Targets the HTTP protocol implementation
- Response manipulation: Splits single response into multiple responses
- Multiple attack vectors: Various ways to exploit response splitting
- Cache poisoning: Can poison web caches with malicious content
- Authentication bypass: Can lead to session hijacking
- Information disclosure: Can expose sensitive server information
- XSS enablement: Can enable cross-site scripting attacks
- Phishing enablement: Can facilitate phishing attacks
- Wide impact: Can affect any web application
Effective HTTP response splitting prevention requires a comprehensive, multi-layered approach that addresses vulnerabilities at every stage of the request-response cycle:
- Input validation: Validate all user input rigorously
- CRLF filtering: Remove CRLF characters from all input
- Output encoding: Encode data properly for responses
- Header validation: Validate all header values
- Response validation: Validate complete response structure
- Security headers: Implement proper security headers
- Content Security Policy: Implement comprehensive CSP
- Cache controls: Implement proper cache controls
- Regular testing: Conduct regular security testing
- Developer education: Train developers on response security
As web technologies continue to evolve with new protocols (HTTP/2, HTTP/3), complex architectures (microservices, serverless), and sophisticated client-side applications, the threat landscape for HTTP response splitting will continue to expand. Developers, security professionals, and organizations must stay vigilant, keep learning, and implement comprehensive security measures to protect against these evolving threats.
The key to effective HTTP response splitting prevention lies in secure design principles, defense-in-depth strategies, continuous monitoring, and proactive security testing. By understanding the mechanisms, techniques, and prevention methods of HTTP response splitting, organizations can significantly reduce their risk and protect their systems from this versatile and damaging attack vector.
Remember: HTTP response splitting is not just a technical vulnerability - it's a serious business risk that can lead to data breaches, regulatory fines, reputational damage, financial losses, and loss of user trust. Taking response splitting security seriously and implementing proper security controls at every layer is essential for protecting your organization, your customers, your data, and your reputation.
The cost of prevention is always less than the cost of recovery - invest in response splitting protection now to avoid catastrophic consequences later. Validate all inputs, filter all CRLF sequences, encode all outputs, implement security headers, and deploy comprehensive security measures to protect against HTTP response splitting vulnerabilities.
Security is not a one-time effort but a continuous process - stay informed about emerging threats, keep your systems updated, and maintain a proactive security posture to ensure the integrity, confidentiality, and availability of your web applications in today's complex threat landscape.
User trust is your most valuable asset - don't let HTTP response splitting attacks erode the trust your users have placed in your applications and services. Secure your responses, protect your users, and maintain the integrity of your digital presence in the face of evolving web security threats.
HTTP Header Injection
HTTP Header Injection is a web security vulnerability that allows attackers to inject malicious headers into HTTP responses, enabling various attacks including XSS, session fixation, and cache poisoning.
HTTP Strict Transport Security (HSTS)
A web security policy that enforces HTTPS connections, preventing protocol downgrade attacks and cookie hijacking.
