Header Injection in APIs
What is Header Injection?
Header Injection is a security vulnerability that occurs when an API blindly trusts and incorporates user-supplied input into HTTP response headers without proper validation or sanitization. This allows attackers to manipulate HTTP headers by injecting malicious content through parameters, headers, or other input vectors.
The vulnerability typically manifests when an application uses user input to construct headers like Location, Set-Cookie, Content-Type, or custom headers. If the input contains CRLF (Carriage Return Line Feed) sequences (%0D%0A in URL encoding), an attacker can inject additional headers or split existing ones, potentially leading to HTTP response splitting, cross-site scripting (XSS), or other attacks.
For example, if an API takes a 'redirect' parameter and uses it directly in a Location header:
HTTP/1.1 302 Found
Location: https://example.com/?redirect=[user_input]If [user_input] contains "\nSet-Cookie: session=evil", the server will send two headers instead of one, potentially hijacking sessions or manipulating client behavior.
How Header Injection Affects APIs
Header Injection vulnerabilities in APIs can lead to several serious security consequences. The most common impact is HTTP Response Splitting, where attackers inject arbitrary HTTP headers or even create multiple responses from a single request. This can be exploited for various attacks:
- Session Fixation: Injecting Set-Cookie headers to force victims to use an attacker-controlled session ID
- Cross-Site Scripting (XSS): When injected headers are reflected in the client's browser
- Open Redirect: Manipulating Location headers to redirect users to phishing sites
- Cache Poisoning: Injecting headers that cause caching of sensitive information
In API contexts, Header Injection can be particularly dangerous because APIs often handle authentication tokens, session management, and sensitive data. An attacker might inject headers that cause the API to reveal internal server information, bypass security controls, or manipulate client-side behavior in ways that compromise data integrity.
Consider a REST API that accepts a 'callback' parameter for JSONP responses and constructs headers like:
Content-Type: application/javascript
Content-Length: [calculated_length]If an attacker provides a callback value containing "\nSet-Cookie: debug=true", they could potentially enable debug mode on the client side or manipulate other header-based security mechanisms.
How to Detect Header Injection
Detecting Header Injection requires systematic testing of how user input flows into HTTP headers. The primary technique involves submitting input containing CRLF sequences and observing whether they're reflected in the response headers.
Manual Testing Approach:
curl -H "X-Custom: hello%0d%0aSet-Cookie:%20evil%3dtrue" https://api.example.com/endpointLook for the injected Set-Cookie header in the response. If present, the API is vulnerable.
Automated Scanning with middleBrick: middleBrick's black-box scanning approach tests for Header Injection by sending specially crafted payloads containing CRLF sequences to various API endpoints. The scanner analyzes responses to detect whether injected headers are reflected or whether the server processes the injection as intended.
middleBrick tests multiple injection points including:
- URL parameters that might be used in Location or Content-Type headers
- Custom headers that could be reflected in responses
- Cookie values that might be echoed back in Set-Cookie headers
- Request bodies where header-like content could be injected
The scanner also checks for HTTP response splitting by looking for multiple status lines or unexpected header sequences. middleBrick's parallel testing approach evaluates 12 security categories simultaneously, providing a comprehensive security assessment in 5-15 seconds without requiring any credentials or configuration.
middleBrick's findings include severity ratings, specific injection points, and remediation guidance. For Header Injection, the scanner identifies the exact parameter or header that's vulnerable and provides examples of the injected content that triggered the vulnerability.
Prevention & Remediation
Preventing Header Injection requires strict input validation and proper header construction practices. Here are concrete code-level fixes:
1. Input Validation and Sanitization
// Vulnerable code (Node.js/Express)
app.get('/redirect', (req, res) => {
res.redirect(req.query.url); // Dangerous!
});
// Secure code
app.get('/redirect', (req, res) => {
const url = req.query.url;
// Validate URL - only allow specific domains
const allowedDomains = ['https://myapp.com', 'https://api.myapp.com'];
const parsedUrl = new URL(url);
if (!allowedDomains.includes(parsedUrl.origin)) {
return res.status(400).json({ error: 'Invalid redirect URL' });
}
res.redirect(url);
});2. Header Construction Best Practices
// Vulnerable code
res.setHeader('X-Custom-Header', userInput); // No validation
// Secure code
function safeSetHeader(res, headerName, value) {
// Remove any CRLF characters
const sanitizedValue = String(value).replace(/[
]/g, '');
// Additional validation based on header type
if (headerName.toLowerCase() === 'location') {
// Validate URL for Location header
try {
new URL(sanitizedValue);
} catch (e) {
throw new Error('Invalid URL for Location header');
}
}
res.setHeader(headerName, sanitizedValue);
}
// Usage
safeSetHeader(res, 'X-Custom-Header', userInput);3. Use Framework Security Features
Most modern web frameworks include protections against header injection:
// Express automatically handles header sanitization
// Use res.location() instead of res.setHeader('Location', ...)
res.location(safeUrl).redirect(302);
// Django automatically escapes headers
from django.http import HttpResponse
response = HttpResponse()
response['X-Custom'] = user_input # Django handles sanitization
4. Security Headers
Implement security headers that reduce the impact of potential header injection:
app.use((req, res, next) => {
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('X-Frame-Options', 'DENY');
res.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
next();
});5. Regular Security Testing
Integrate automated security testing into your development workflow. The middleBrick GitHub Action can automatically scan your API endpoints on every pull request, failing the build if Header Injection vulnerabilities are detected. This ensures that security issues are caught early in the development process rather than in production.
Real-World Impact
Header Injection vulnerabilities have caused significant security incidents across the industry. While specific breach details are often confidential, several documented cases highlight the severity of this issue.
In 2010, a major vulnerability in Ruby on Rails' JSON request parsing allowed Header Injection through crafted parameters, leading to potential session fixation attacks. The vulnerability affected numerous high-profile applications built on the framework.
A 2015 incident involving a popular e-commerce platform demonstrated how Header Injection in API endpoints could be combined with other vulnerabilities. Attackers exploited improper header handling to bypass CSRF protections and execute unauthorized transactions.
The OWASP API Top 10 specifically identifies "API1:2019 - Broken Object Level Authorization" and "API6:2019 - Mass Assignment" as critical risks, with Header Injection often being a contributing factor in both categories. When combined with IDOR (Insecure Direct Object Reference) vulnerabilities, Header Injection can enable attackers to escalate privileges or access unauthorized data.
According to CVE data, Header Injection vulnerabilities typically receive CVSS scores between 6.1 (Medium) and 8.8 (High), depending on the impact. The vulnerability becomes Critical (CVSS 9.0+) when it enables remote code execution or complete account takeover.
middleBrick's scanning methodology helps organizations identify these vulnerabilities before attackers can exploit them. By testing the unauthenticated attack surface and providing actionable remediation guidance, middleBrick enables developers to fix Header Injection issues quickly and maintain strong API security posture.