HTTP Header Injection
What is HTTP Header Injection?
HTTP Header Injection is a web security vulnerability that occurs when an attacker can inject malicious data into HTTP response headers. This vulnerability allows attackers to manipulate server responses, potentially leading to cross-site scripting (XSS), session fixation, cache poisoning, and other attacks.
Key Characteristics
- Header manipulation: Attacker controls HTTP response headers
- Response splitting: Can split HTTP responses into multiple parts
- Injection point: Typically occurs in user-controlled input reflected in headers
- Multiple attack vectors: Various ways to exploit header injection
- Common in web applications: Frequently found in custom header implementations
- Authentication bypass: Can lead to session hijacking and other attacks
- Information disclosure: May expose sensitive server information
HTTP Header Injection vs Other Web Attacks
| Attack | Method | Primary Target | Typical Impact | User Awareness |
|---|---|---|---|---|
| HTTP Header Injection | Malicious header injection | HTTP responses | Response manipulation, XSS | Usually unaware |
| HTTP Response Splitting | CRLF injection | HTTP responses | Cache poisoning, 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 |
| Server-Side Request Forgery (SSRF) | Server-side request manipulation | Internal systems | Internal network access | Usually unaware |
How HTTP Header Injection Works
Technical Mechanism
graph TD
A[Attacker] -->|1. Sends malicious request| B[Web Application]
B -->|2. Processes user input| C[Server Logic]
C -->|3. Includes user input in headers| B
B -->|4. Returns poisoned response| D[Victim Browser]
D -->|5. Processes malicious headers| E[Malicious Effects]
Common HTTP Header Injection Process
- Input identification: Attacker finds user input reflected in headers
- Injection point discovery: Identifies where input is included in headers
- Malicious payload crafting: Creates payload to exploit header injection
- Request submission: Sends request with malicious payload
- Header injection: Server includes payload in response headers
- Response processing: Browser processes malicious headers
- Attack execution: Malicious effects are triggered
HTTP Header Injection Attack Vectors
Common Attack Methods
| Vector | Description | Example |
|---|---|---|
| Location Header Injection | Injecting malicious redirects | Location: javascript:alert(1) |
| Set-Cookie Injection | Injecting malicious cookies | Set-Cookie: sessionid=malicious; HttpOnly |
| Content-Type Injection | Changing response content type | Content-Type: text/html; charset=UTF-7 |
| CRLF Injection | Injecting new headers via CRLF | %0d%0aX-Malicious: value |
| Cache-Control Injection | Manipulating caching behavior | Cache-Control: max-age=3600, public |
| Refresh Header Injection | Injecting malicious refresh | Refresh: 0; url=http://attacker.com |
| Content-Disposition Injection | Manipulating file downloads | Content-Disposition: attachment; filename="malicious.exe" |
| X-Forwarded-For Injection | Spoofing client IP | X-Forwarded-For: 127.0.0.1 |
| Custom Header Injection | Injecting custom headers | X-Api-Key: malicious_value |
| Authentication Header Injection | Manipulating auth headers | Authorization: Bearer malicious_token |
HTTP Header Injection Exploitation Techniques
1. Cross-Site Scripting (XSS) via Header Injection
Attack Scenario: Injecting JavaScript via HTTP headers.
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=javascript:alert(document.cookie) - Victim visits malicious URL
- Server includes JavaScript in Location header
- Browser processes Location header and executes JavaScript
- XSS attack is executed in victim's browser
Prevention:
- Input validation: Validate all user input
- Output encoding: Encode data in headers
- Header whitelisting: Only allow specific header values
- Redirect validation: Validate redirect URLs
- Content Security Policy: Restrict script sources
2. Session Fixation via Set-Cookie Injection
Attack Scenario: Injecting malicious session cookies.
Vulnerable Code (Node.js):
// Vulnerable code - user input in Set-Cookie header
app.get('/set-lang', (req, res) => {
const lang = req.query.lang;
res.setHeader('Set-Cookie', `lang=${lang}; Path=/`);
res.send('Language set');
});
Attack Process:
- Attacker identifies vulnerable language endpoint
- Crafts malicious URL:
/set-lang?lang=en;%20sessionid=attacker123 - Victim visits malicious URL
- Server sets cookie with 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
- Input sanitization: Sanitize user input in headers
- Header encoding: Properly encode header values
- Security headers: Use HttpOnly, Secure, SameSite flags
3. Cache Poisoning via Header Injection
Attack Scenario: Injecting malicious cache headers.
Vulnerable Code (Python Flask):
@app.route('/search')
def search():
query = request.args.get('q', '')
response = make_response(render_template('search.html', query=query))
response.headers['X-Search-Query'] = query # Vulnerable header
return response
Attack Process:
- Attacker identifies vulnerable search endpoint
- Crafts malicious URL:
/search?q=test%0d%0aCache-Control:max-age=3600 - Victim visits malicious URL
- Server includes malicious cache header
- Proxy caches poisoned response
- Subsequent users receive poisoned content
Prevention:
- Header validation: Validate all header values
- Input sanitization: Sanitize user input in headers
- Cache controls: Set proper cache headers server-side
- Header encoding: Properly encode header values
- Security testing: Test for cache poisoning vulnerabilities
4. Open Redirect via Location Header Injection
Attack Scenario: Injecting malicious redirect URLs.
Vulnerable Code (Java):
// Vulnerable code - user input in Location header
@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=https://attacker.com/phishing - Victim visits malicious URL
- Server includes attacker's URL in Location header
- Browser redirects victim to attacker's site
- Attacker performs phishing attack
Prevention:
- URL validation: Validate redirect URLs
- Whitelist domains: Only allow specific domains
- Relative URLs: Use relative URLs when possible
- Redirect encoding: Encode redirect URLs
- User confirmation: Require confirmation for external redirects
HTTP Header Injection Prevention Methods
1. Input Validation and Sanitization
Implementation Strategies:
- Input validation: Validate all user input
- Header whitelisting: Only allow specific header values
- Character filtering: Remove dangerous characters
- Length restrictions: Limit input length
- Type checking: Validate input types
Example (Secure Input Validation in PHP):
<?php
// Secure redirect implementation
function isValidUrl($url) {
// Validate URL format
if (!filter_var($url, FILTER_VALIDATE_URL)) {
return false;
}
// Check against whitelist
$allowedDomains = ['example.com', 'trusted-partner.com'];
$host = parse_url($url, 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: " . $redirectUrl);
header("Location: /error?code=invalid_redirect");
exit;
}
?>
2. Output Encoding for Headers
Implementation Strategies:
- Header encoding: Encode data in headers
- CRLF protection: Prevent header 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 { header } = require('express-validator');
const app = express();
// Middleware for secure header setting
function setSecureHeader(res, name, value) {
// Remove CRLF characters
const cleanValue = 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', [
header('x-custom').trim().escape()
], (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 header 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(`Header 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 {
// Validate URL
const parsedUrl = new URL(url);
// 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(url);
} 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();
});
// Secure endpoint with nonce
app.get('/secure-page', (req, res) => {
const nonce = res.locals.cspNonce;
res.send(`
<!DOCTYPE html>
<html>
<head>
<title>Secure Page</title>
</head>
<body>
<h1>Secure Content</h1>
<script nonce="${nonce}">
// Trusted script with nonce
console.log('This script is allowed by CSP');
</script>
</body>
</html>
`);
});
HTTP Header Injection 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
- CORS configuration: Secure CORS settings
- Token security: Secure authentication tokens
- 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 headers
const responseHeaders = Object.fromEntries(response.headers.entries());
if (this.hasMaliciousHeaders(responseHeaders)) {
throw new Error('Malicious headers detected in response');
}
return response;
}
hasMaliciousHeaders(headers) {
const maliciousPatterns = [
/\r/, /\n/, /%0d/, /%0a/, /javascript:/i, /data:/i
];
for (const [name, value] of Object.entries(headers)) {
if (maliciousPatterns.some(pattern => pattern.test(value))) {
console.warn(`Malicious header detected: ${name}: ${value}`);
return true;
}
}
return false;
}
}
// Usage
const api = new ApiService();
api.request('/data', {
headers: {
'X-Custom-Header': 'safe-value'
}
}).then(response => response.json())
.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
- Service isolation: Isolate sensitive services
- Token validation: Validate authentication tokens
- Logging security: Secure header logging
Example (Kubernetes Ingress with Header Security):
# Secure ingress configuration
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: secure-ingress
annotations:
nginx.ingress.kubernetes.io/configuration-snippet: |
# Block malicious headers
if ($http_user_agent ~* (\r|\n|%0d|%0a|javascript:|data:)) {
return 403 "Malicious header detected";
}
# Validate Content-Type
if ($content_type !~* ^(application/json|application/x-www-form-urlencoded|multipart/form-data)$) {
return 415 "Unsupported Media Type";
}
# 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
- Header security: Secure header processing
- Logging: Secure header logging
- Monitoring: Monitor for suspicious activity
Example (AWS Lambda with Secure Headers):
const { URL } = require('url');
exports.handler = async (event) => {
// Validate request
if (!event.headers) {
return {
statusCode: 400,
body: JSON.stringify({ error: 'Missing headers' })
};
}
// Check for malicious headers
const maliciousPatterns = [/\r/, /\n/, /%0d/, /%0a/, /javascript:/i, /data:/i];
for (const [name, value] of Object.entries(event.headers)) {
if (maliciousPatterns.some(pattern => pattern.test(value))) {
console.warn(`Malicious header detected: ${name}: ${value}`);
return {
statusCode: 400,
body: JSON.stringify({ error: 'Malicious header detected' })
};
}
}
// Secure redirect example
if (event.path === '/redirect') {
try {
const redirectUrl = event.queryStringParameters?.url;
if (!redirectUrl) {
return {
statusCode: 400,
body: JSON.stringify({ error: 'URL parameter required' })
};
}
// Validate URL
const parsedUrl = new URL(redirectUrl);
// Check against whitelist
const allowedDomains = ['example.com', 'trusted-partner.com'];
if (!allowedDomains.includes(parsedUrl.hostname)) {
throw new Error('Domain not allowed');
}
// Return secure redirect
return {
statusCode: 302,
headers: {
'Location': parsedUrl.toString(),
'Strict-Transport-Security': 'max-age=31536000; includeSubDomains; preload',
'X-Content-Type-Options': 'nosniff',
'X-Frame-Options': 'DENY',
'Content-Security-Policy': "default-src 'self'"
},
body: ''
};
} catch (e) {
console.warn(`Invalid redirect attempt: ${event.queryStringParameters?.url}`);
return {
statusCode: 302,
headers: {
'Location': '/error?code=invalid_redirect'
},
body: ''
};
}
}
// Default 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 Header Injection Testing and Detection
Manual Testing Techniques
- Header injection testing:
- Test with CRLF characters (
%0d%0a) - Test with newline characters (
\n,\r) - Test with URL-encoded CRLF (
%0d%0a) - Test with various header injection payloads
- Test with CRLF characters (
- Redirect testing:
- Test Location header injection
- Test Refresh header injection
- Test JavaScript in redirect URLs
- Test data URIs in redirect URLs
- Cookie testing:
- Test Set-Cookie header injection
- Test cookie attribute injection
- Test session fixation via cookies
- Test cookie overflow
- Content type testing:
- Test Content-Type header injection
- Test charset injection
- Test MIME type manipulation
- Test content sniffing
- Cache testing:
- Test Cache-Control header injection
- Test cache poisoning
- Test ETag manipulation
- Test Last-Modified header injection
Automated Testing Tools
- Burp Suite:
- Scanner: Automated header injection detection
- Repeater: Manual header testing
- Intruder: Header injection fuzzing
- Proxy: Header inspection and modification
- OWASP ZAP:
- Active Scan: Header injection vulnerabilities
- Fuzzer: Header injection testing
- Forced User Mode: Header injection simulation
- Scripting: Custom header injection tests
- Browser Developer Tools:
- Network tab: Inspect response headers
- Console: Test header-based attacks
- Overrides: Test header manipulation
- Security tab: Check security headers
- Custom Scripts:
- Header analysis: Scripts to analyze headers
- Injection testing: Scripts to test header injection
- Vulnerability scanning: Custom scanners for header injection
Example (Python Script for Header Injection Testing):
import requests
import re
def test_header_injection(url, param):
results = {
'url': url,
'param': param,
'vulnerable': False,
'issues': [],
'headers': {}
}
# Test payloads
payloads = [
'%0d%0aX-Injected: malicious',
'\r\nX-Injected: malicious',
'%0aX-Injected: malicious',
'%0dX-Injected: malicious',
'javascript:alert(1)',
'data:text/html,<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 XSS via Location header
if 'location' in response.headers:
location = response.headers['location'].lower()
if 'javascript:' in location or 'data:' in location:
results['issues'].append(f"XSS via Location header with payload: {payload}")
results['vulnerable'] = True
# Check for cache poisoning
cache_headers = ['cache-control', 'etag', 'last-modified']
for header in cache_headers:
if header in response.headers:
if re.search(r'[\r\n]', response.headers[header]):
results['issues'].append(f"Cache header injection 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_header_injection(
url="https://example.com/redirect",
param="url"
)
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 headers
- Taint analysis: Track untrusted input to header output
- Dynamic Analysis (DAST):
- Runtime monitoring: Monitor header handling at runtime
- Fuzz testing: Test header injection payloads
- Behavioral analysis: Analyze header manipulation
- Interactive Analysis (IAST):
- Runtime instrumentation: Monitor header handling during execution
- Input tracking: Track user input to headers
- Vulnerability detection: Identify header injection vulnerabilities
Example (Semgrep Rule for Header Injection):
rules:
- id: unsafe-header-usage
pattern: |
$RESPONSE.setHeader($NAME, $$USER_INPUT)
message: "Unsafe header usage - user input directly used in header without validation"
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-location-header
pattern: |
$RESPONSE.redirect($$USER_INPUT)
message: "Unsafe redirect - user input used in Location header without validation"
languages: [javascript, java, csharp, python]
severity: ERROR
metadata:
cwe: "CWE-601: URL Redirection to Untrusted Site ('Open Redirect')"
owasp: "A01:2021 - Broken Access Control"
- id: crlf-injection
pattern: |
$HEADER_VALUE = $$USER_INPUT
...
$RESPONSE.setHeader($NAME, $HEADER_VALUE)
message: "Potential CRLF injection - 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-cookie-setting
pattern: |
$RESPONSE.setCookie($NAME, $$USER_INPUT)
message: "Unsafe cookie setting - user input used in Set-Cookie header without validation"
languages: [javascript, java, csharp, python]
severity: ERROR
metadata:
cwe: "CWE-1021: Improper Restriction of Rendered UI Layers or Frames"
owasp: "A05:2021 - Security Misconfiguration"
- id: missing-header-validation
pattern: |
$RESPONSE.setHeader($NAME, $VALUE)
...
// no validation of $VALUE
message: "Missing header value validation - header values should be validated before use"
languages: [javascript, java, csharp, python]
severity: WARNING
metadata:
cwe: "CWE-20: Improper Input Validation"
owasp: "A03:2021 - Injection"
HTTP Header Injection Case Studies
Case Study 1: Major E-Commerce Platform (2018)
Incident: HTTP header injection leading to account takeover.
Attack Details:
- Vulnerability: User input reflected in Set-Cookie header
- Attack method: Session fixation via cookie injection
- Impact: Thousands of accounts compromised
- Discovery: Security researcher during bug bounty
- Exploitation: Phishing emails with malicious links
Technical Flow:
- E-commerce site had vulnerable password reset endpoint
- User email parameter reflected in Set-Cookie header
- Attacker crafted malicious password reset link:
https://ecommerce.com/reset?email=victim@example.com%0d%0aSet-Cookie:sessionid=attacker123 - Victim clicked link to reset password
- Server set attacker's session ID in victim's browser
- Victim completed password reset
- Attacker used fixed session ID to access victim's account
- Attacker made unauthorized purchases
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
- Bug bounty programs: Value of security research programs
- Incident response: Need for rapid vulnerability patching
Case Study 2: Social Media Platform (2019)
Incident: HTTP header injection leading to XSS.
Attack Details:
- Vulnerability: User input reflected in Location header
- Attack method: JavaScript injection in redirect
- Impact: Widespread XSS attacks
- Discovery: Security researcher
- Exploitation: Malicious posts with injected headers
Technical Flow:
- Social media platform had vulnerable share endpoint
- User URL parameter reflected in Location header
- Attacker created malicious post with link:
https://social.com/share?url=javascript:alert(document.cookie) - Victims clicked link to share content
- Server included JavaScript in Location header
- Browsers executed JavaScript from Location header
- XSS payload stole session cookies
- Attacker hijacked victim accounts
Lessons Learned:
- Redirect security: Need for secure redirect handling
- Header encoding: Importance of proper header encoding
- Content Security Policy: Need for CSP to prevent XSS
- User education: Teaching users about malicious links
- Security testing: Need for comprehensive security testing
Case Study 3: Government Portal (2020)
Incident: HTTP header injection leading to cache poisoning.
Attack Details:
- Vulnerability: User input reflected in Cache-Control header
- Attack method: Cache header manipulation
- Impact: Sensitive data exposure
- Discovery: Security audit
- Exploitation: Malicious requests to poison cache
Technical Flow:
- Government portal had vulnerable search endpoint
- Search query reflected in X-Search-Query header
- Attacker sent request:
https://gov-portal.com/search?q=test%0d%0aCache-Control:max-age=3600 - Server included malicious cache header
- Proxy cached response with sensitive data
- Subsequent users received cached sensitive data
- Attacker accessed sensitive citizen information
- Data breach exposed personal information
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: Online Banking (2021)
Incident: HTTP header injection leading to open redirect.
Attack Details:
- Vulnerability: User input reflected in Location header
- Attack method: Malicious redirect injection
- Impact: Phishing attacks on banking users
- Discovery: Security monitoring
- Exploitation: Phishing emails with malicious redirects
Technical Flow:
- Banking site had vulnerable redirect endpoint
- User URL parameter reflected in Location header
- Attacker created phishing email with link:
https://bank.com/redirect?url=https://fake-bank.com/login - Victims clicked link in phishing email
- Server included attacker's URL in Location header
- Browsers redirected victims to fake banking site
- Victims entered credentials on fake site
- Attacker collected banking 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 Header Injection and Compliance
Regulatory Implications
HTTP header injection vulnerabilities can lead to severe compliance violations with various regulations:
- GDPR: General Data Protection Regulation
- Data protection: Header injection 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: Header injection 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: Header injection 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: Header injection 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 Header Injection 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 headers, validate input |
| NIST SP 800-53 | System integrity | Validate headers, monitor systems, secure data |
HTTP Header Injection in the OWASP Top 10
OWASP Top 10 2021: HTTP header injection is primarily related to:
- A03:2021 - Injection: Header injection as a form of injection attack
- A01:2021 - Broken Access Control: Header manipulation bypassing access controls
- A05:2021 - Security Misconfiguration: Missing security headers and controls
- A07:2021 - Identification and Authentication Failures: Header 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 headers
- Header whitelisting: Only allow specific header values
- 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 header injection
Advanced HTTP Header Injection Techniques
1. HTTP Request Smuggling with Header Injection
Technique: Combining header injection with HTTP request smuggling.
Attack Scenario:
- Attacker injects malicious headers in request
- Front-end server processes headers differently than back-end
- Request smuggling occurs due to header injection
- Attacker can poison cache or hijack sessions
Process:
- Attacker sends request with injected headers:
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
- Request smuggling occurs
- Attacker gains unauthorized access
Prevention:
- Consistent header parsing: Ensure consistent header parsing
- Request validation: Validate all HTTP requests
- Header sanitization: Sanitize all headers
- Protocol enforcement: Enforce HTTP protocol compliance
- Security testing: Test for request smuggling vulnerabilities
2. Web Cache Deception with Header Injection
Technique: Using header injection to manipulate cache behavior.
Attack Scenario:
- Attacker injects cache headers in request
- Server includes sensitive data in response
- Response is cached with sensitive data
- Attacker accesses cached sensitive data
Process:
- Attacker sends request with injected cache headers:
GET /profile.php/nonexistent.css HTTP/1.1Host: example.comCache-Control: public, max-age=3600 - Server processes request and includes sensitive data
- Proxy caches response with sensitive data
- Attacker requests same URL and gets cached sensitive data
- Sensitive information is exposed
Prevention:
- Cache controls: Implement proper cache controls
- Header validation: Validate all cache headers
- 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 Header Injection
Technique: Using header injection to manipulate server-side requests.
Attack Scenario:
- Attacker injects malicious headers in request
- Server processes headers and makes internal requests
- Attacker gains access to internal systems
Process:
- Attacker identifies vulnerable endpoint that makes internal requests
- Injects malicious headers:
GET /proxy?url=http://internal-server HTTP/1.1Host: example.comX-Forwarded-Host: attacker.com - Server processes X-Forwarded-Host header and makes request to attacker.com
- Attacker receives internal server information
- Attacker gains access to internal systems
Prevention:
- Header validation: Validate all headers
- Internal request security: Secure internal requests
- Network segmentation: Isolate internal systems
- Request validation: Validate all external requests
- Security testing: Test for SSRF vulnerabilities
4. Cross-Origin Resource Sharing (CORS) Misconfiguration via Header Injection
Technique: Using header injection to manipulate CORS headers.
Attack Scenario:
- Attacker injects malicious CORS headers
- 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 endpoint
- Injects malicious CORS headers:
GET /api/data HTTP/1.1Host: example.comOrigin: https://attacker.com - Server reflects Origin header in Access-Control-Allow-Origin
- 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
- Header sanitization: Sanitize all headers
- Security testing: Test for CORS misconfigurations
- Content Security Policy: Implement CSP
5. HTTP/2 Header Injection
Technique: Exploiting HTTP/2 header compression and multiplexing.
Attack Scenario:
- Attacker injects malicious headers in HTTP/2 requests
- HTTP/2 header compression allows header injection
- Server processes malicious headers
- Attacker exploits vulnerability
Process:
- Attacker establishes HTTP/2 connection
- Injects malicious headers using HPACK compression
- Server processes headers and includes them in responses
- Attacker exploits header injection vulnerability
- Malicious effects are triggered
Prevention:
- HTTP/2 security: Secure HTTP/2 implementations
- Header validation: Validate all HTTP/2 headers
- Protocol enforcement: Enforce HTTP/2 protocol compliance
- Security testing: Test for HTTP/2 vulnerabilities
- Regular updates: Keep HTTP/2 implementations updated
HTTP Header Injection Mitigation Strategies
Defense in Depth Approach
- Input Layer:
- Validate all user input
- Sanitize all input data
- Implement input whitelisting
- Use parameterized interfaces
- Processing Layer:
- Encode data for headers
- Validate header values
- Use secure header libraries
- Implement header whitelisting
- Output Layer:
- Sanitize all output headers
- Implement security headers
- Use Content Security Policy
- Validate all response headers
- Transport Layer:
- Always use HTTPS
- Implement HSTS
- Use secure protocols
- Implement certificate pinning
- Monitoring Layer:
- Log all header manipulations
- Monitor for suspicious headers
- Alert on header injection attempts
- Implement incident response
Secure Development Lifecycle
- Design Phase:
- Threat modeling for header security
- Security requirements definition
- Secure architecture design
- Data flow analysis
- Development Phase:
- Secure coding standards
- Code reviews
- Static analysis
- Dependency scanning
- Testing Phase:
- Penetration testing
- Dynamic analysis
- Fuzz testing
- Vulnerability scanning
- Deployment Phase:
- Secure configuration
- Security headers
- Monitoring setup
- Access controls
- Maintenance Phase:
- Patch management
- Security updates
- Continuous monitoring
- Incident response
Emerging Technologies
- AI-Powered Security:
- Behavioral analysis: Analyze header patterns
- Anomaly detection: Detect unusual header behavior
- Automated response: Block suspicious headers
- Predictive security: Identify potential vulnerabilities
- Automated Security Testing:
- Continuous scanning: Regular vulnerability scanning
- Automated fuzzing: Automated header injection testing
- Integration testing: Security testing in CI/CD
- Regression testing: Ensure fixes don't break security
- Secure Header Frameworks:
- Standardized security: Standard security header implementations
- Automated protection: Automatic header security
- Framework integration: Security integrated into frameworks
- Regular updates: Updated security controls
- Runtime Application Self-Protection (RASP):
- Real-time protection: Protect against header injection at runtime
- Behavioral analysis: Analyze header behavior
- Automated response: Block malicious headers
- Integration: Seamless integration with applications
- Zero Trust Architecture:
- Continuous authentication: Authenticate every request
- Least privilege: Grant minimal necessary access
- Micro-segmentation: Isolate sensitive components
- Continuous monitoring: Monitor all header activity
Conclusion
HTTP Header Injection represents a critical but often underestimated web security vulnerability that enables attackers to manipulate server responses and exploit browser behavior. Unlike more well-known injection attacks like SQL injection or XSS, header injection targets the communication protocol itself, making it particularly dangerous as it can bypass traditional security controls and enable a wide range of attacks.
The unique characteristics of HTTP header injection make it particularly insidious:
- Protocol-level attack: Exploits HTTP protocol vulnerabilities
- Multiple attack vectors: Various ways to inject malicious headers
- Wide impact: Can affect any web application
- Authentication bypass: Can lead to session hijacking and data theft
- Information disclosure: Can expose sensitive server information
- Cache manipulation: Can poison caches and serve malicious content
- Redirect manipulation: Can redirect users to malicious sites
- XSS enablement: Can enable cross-site scripting attacks
Effective HTTP header injection 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
- Output encoding: Encode data properly for headers
- Header whitelisting: Only allow specific, safe header values
- Security headers: Implement proper security headers (CSP, X-Frame-Options, etc.)
- Content Security Policy: Implement comprehensive CSP
- Redirect validation: Validate all redirect URLs
- Cookie security: Secure all cookie handling
- Cache controls: Implement proper cache controls
- Regular testing: Conduct regular security testing
- Developer education: Train developers on header 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 header injection 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 header injection 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 header injection, organizations can significantly reduce their risk and protect their systems from this versatile and damaging attack vector.
Remember: HTTP header injection 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 even business closure. Taking header security seriously and implementing proper security controls at every layer is essential for protecting your organization, your customers, your data, and your future.
The cost of prevention is always less than the cost of recovery - invest in header security now to avoid catastrophic consequences later. Validate all inputs, encode all outputs, implement security headers, and deploy comprehensive security measures to protect against HTTP header injection 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.
HTTP/2
The second major version of the HTTP protocol that improves web performance through multiplexing, header compression, and server push.
HTTP Response Splitting
HTTP Response Splitting is a web security vulnerability that allows attackers to inject malicious data into HTTP responses, enabling cache poisoning, cross-site scripting (XSS), and other attacks by exploiting improper handling of CRLF sequences.
