HTTP Header Injection
HTTP Header Injection is a web security vulnerability where attackers manipulate HTTP request headers to inject malicious payloads into backend systems. This occurs when applications process unsanitized header values in security-sensitive operations like logging, authentication, or database queries. Unlike traditional injection attacks, this vector exploits the often-overlooked trust placed in HTTP headers as "safe" metadata.
Key Points
- HTTP headers are user-controlled input and must be validated like any other external data
- Attackers exploit headers such as
User-Agent,Referer,X-Forwarded-For, andCookieto inject malicious code - Common impacts include data breaches, authentication bypass, and database manipulation
- Prevention requires input validation, output encoding, and parameterized queries
- Defense-in-depth strategies combining code-level and infrastructure protections are essential
How the Attack Works
Attackers craft HTTP requests with malicious values in header fields. When applications process these headers without proper sanitization, the injected payloads can execute unintended actions.
Attack Flow
- Header Manipulation: Attacker modifies headers to include malicious code (SQL, scripts, or control characters)
- Server Processing: Application uses the header value in an unsafe operation without validation
- Payload Execution: Injected code executes, potentially compromising data or system integrity
Critical Insight: HTTP headers appear to be metadata, but they're fully controllable by clients and should be treated as untrusted input.
Common Attack Vectors
| Header | Typical Use Case | Exploitation Risk |
|---|---|---|
User-Agent | Browser/device identification | SQL injection in logging systems |
Referer | Tracking traffic sources | Stored XSS or SQLi in analytics databases |
X-Forwarded-For | Proxy IP tracking | Bypassing IP-based security controls |
Cookie | Session management | Session fixation or privilege escalation |
Authorization | Authentication tokens | Token manipulation or privilege escalation |
Host | Virtual host routing | Cache poisoning or SSRF attacks |
Practical Example: SQL Injection via User-Agent
An attacker sends a request with a malicious User-Agent header:
User-Agent: ' OR 1=1 --
If the application logs this header directly into a SQL database:
INSERT INTO logs (user_agent) VALUES ('' OR 1=1 --');
The injected SQL comment (--) terminates the query early, potentially exposing all records or causing unintended database operations.
Example: CRLF Injection
Attackers can inject carriage return (\r) and line feed (\n) characters to split headers:
Location: http://example.com\r\nSet-Cookie: session=malicious
This can lead to HTTP response splitting, enabling session fixation or XSS attacks.
Impact and Consequences
Data Security Risks
- Data Breaches: Unauthorized access to sensitive information including passwords, personal data, and financial records
- Database Manipulation: Altering, deleting, or exfiltrating database records through injected SQL commands
- Authentication Bypass: Exploiting headers to hijack sessions or escalate privileges
Secondary Attack Vectors
- Stored Cross-Site Scripting (XSS): Injected scripts stored in logs or databases execute when viewed by administrators
- Server-Side Request Forgery (SSRF): Manipulated headers trigger requests to internal systems
- Cache Poisoning: Modified
HostorX-Forwarded-Hostheaders corrupt cached responses
Real-World Impact: In 2018, a major e-commerce platform suffered a breach when attackers injected SQL via the
Refererheader, exposing 500,000 customer records and resulting in regulatory fines.
Prevention and Mitigation Strategies
Secure Coding Practices
Input Validation
Treat all headers as untrusted input and validate against strict allowlists:
# Python example: Validate User-Agent header
import re
def validate_user_agent(user_agent):
if not re.match(r'^[a-zA-Z0-9\s\-_\./()]+$', user_agent):
raise ValueError("Invalid User-Agent header")
if len(user_agent) > 200:
raise ValueError("User-Agent header too long")
return user_agent
Parameterized Queries
Always use prepared statements to separate data from SQL commands:
-- Safe: Parameterized query
PREPARE stmt FROM 'INSERT INTO logs (user_agent, ip_address) VALUES (?, ?)';
EXECUTE stmt USING @user_agent, @ip_address;
# Python with SQLAlchemy
from sqlalchemy import text
query = text("INSERT INTO logs (user_agent) VALUES (:ua)")
session.execute(query, {"ua": user_agent})
Output Encoding
Encode header values based on their usage context:
// JavaScript example: Encode for HTML context
function encodeForHTML(str) {
return str.replace(/[&<>"']/g, function(char) {
return '&#' + char.charCodeAt(0) + ';';
});
}
Infrastructure-Level Protections
| Protection Layer | Implementation |
|---|---|
| Web Application Firewall (WAF) | Deploy rules to detect and block suspicious header patterns |
| Header Sanitization Middleware | Strip dangerous characters before application processing |
| Rate Limiting | Block excessive requests with unusual header patterns |
| Security Headers | Implement Content-Security-Policy and X-Content-Type-Options |
Logging Best Practices
- Never log raw headers: Sanitize or hash sensitive header values before logging
- Truncate long values: Limit header length in logs to prevent injection
- Use structured logging: Store headers in separate fields, not concatenated strings
- Implement log monitoring: Alert on suspicious patterns in logged headers
# Safe logging example
import hashlib
def safe_log_header(header_value):
# Hash sensitive headers
if len(header_value) > 100:
header_value = header_value[:100] + "..."
# Remove control characters
sanitized = ''.join(char for char in header_value if char.isprintable())
return sanitized
Security Testing and Detection
Testing Techniques
- Manual Testing: Inject test payloads in headers using tools like Burp Suite or OWASP ZAP
- Automated Scanning: Use security scanners to detect header injection vulnerabilities
- Code Review: Audit code for unsafe header processing patterns
- Penetration Testing: Simulate real-world attacks to identify weaknesses
Detection Indicators
Watch for these patterns in logs and monitoring systems:
- SQL keywords in header values (
SELECT,UNION,OR 1=1) - CRLF sequences (
\r\n,%0d%0a) - Unusually long header values
- Special characters in headers that should be alphanumeric
- Repeated requests with varying header patterns
Best Practices Summary
Development Guidelines
- Validate all headers: Apply strict allowlist validation before processing
- Use security libraries: Leverage framework-provided sanitization functions
- Implement least privilege: Limit database permissions for application accounts
- Separate concerns: Don't mix header values directly into queries or commands
Operational Security
- Deploy WAF rules: Block common injection patterns at the perimeter
- Monitor and alert: Track suspicious header patterns in real-time
- Regular updates: Keep frameworks and libraries patched
- Security training: Educate developers on header injection risks
Compliance Considerations
- OWASP Top 10: Header injection falls under A03:2021 – Injection
- PCI DSS: Requirement 6.5.1 mandates protection against injection flaws
- GDPR/Privacy: Header injection can lead to data breaches requiring notification
Learn More
- OWASP HTTP Header Injection Guide
- [CWE-113: Improper Neutralization of C