HIGH header injectionbearer tokens

Header Injection with Bearer Tokens

How Header Injection Manifests in Bearer Tokens

Header injection in Bearer token contexts occurs when an attacker manipulates HTTP headers to inject malicious tokens or alter authentication flows. This manifests in several specific ways:

Authorization Header Manipulation - Attackers exploit poorly validated Authorization headers to inject multiple tokens or malformed values. Consider this vulnerable pattern:

Authorization: Bearer valid_token
Authorization: Bearer injected_token

Some servers process only the first header, others the last, creating ambiguity. Attackers leverage this inconsistency to bypass authentication.

Header Splitting via CRLF Injection - When user input is reflected in headers without proper sanitization:

Authorization: Bearer {{user_input}}

An attacker submitting Bearer evil_token creates two headers:

Authorization: Bearer 
Bearer evil_token

Token Concatenation Attacks - Some implementations concatenate multiple Bearer tokens:

Authorization: Bearer valid_token evil_token

Servers that split on spaces rather than strict parsing may treat this as valid, allowing token chaining attacks.

Case-Sensitivity Exploitation - Authorization header variations:

authorization: Bearer token
Authorization: bearer token
AUTHORIZATION: Bearer token

Mixed-case handling can create bypass opportunities in case-insensitive servers.

Header Injection via Proxy Forwards - When APIs trust X-Forwarded-* headers:

X-Forwarded-Authorization: Bearer injected_token

Misconfigured proxies may forward these headers to backend services, creating authentication bypass chains.

Bearer Tokens-Specific Detection

Detecting header injection in Bearer token implementations requires examining both request construction and server parsing logic.

Static Analysis Patterns - Look for these vulnerable patterns in your codebase:

// VULNERABLE: Direct header concatenation
const authHeader = 'Bearer ' + token + '
' + 'Bearer ' + maliciousToken;
# VULNERABLE: Unsafe header construction
headers = {
    'Authorization': f'Bearer {user_token}\r\nBearer {attacker_token}'
}

Runtime Detection with middleBrick - The scanner specifically tests Bearer token endpoints for header injection:

middlebrick scan https://api.example.com/protected --tests=authentication

middleBrick probes for:

  • Multiple Authorization headers with varying case
  • CRLF injection attempts in token values
  • Header splitting via newline characters
  • Token concatenation with space separators
  • X-Forwarded-Authorization header injection

The scanner returns findings like:

Authentication Risk: High
- Multiple Authorization headers accepted (Severity: Critical)
- CRLF injection in Authorization header detected (Severity: High)
- Case-insensitive Authorization header processing (Severity: Medium)

Manual Testing Methodology - Test your Bearer token endpoints with:

# Multiple headers
curl -H "Authorization: Bearer valid" -H "Authorization: Bearer evil" https://api.test
# CRLF injection
curl -H "Authorization: Bearer valid\nBearer evil" https://api.test
# Case variations
curl -H "authorization: Bearer valid" https://api.test

Bearer Tokens-Specific Remediation

Secure Bearer token implementation requires strict header handling and validation.

Strict Header Parsing - Implement single-header enforcement:

// Node.js Express middleware
app.use((req, res, next) => {
  const authHeader = req.headers.authorization;
  
  if (!authHeader) {
    return next(new Error('Missing Authorization header'));
  }
  
  // Ensure exactly one Authorization header
  if (Object.keys(req.headers).filter(k => k.toLowerCase() === 'authorization').length > 1) {
    return res.status(400).json({ error: 'Multiple Authorization headers not allowed' });
  }
  
  // Strict Bearer token format validation
  const match = authHeader.match(/^Bearer\s+([a-zA-Z0-9\-\._~+\/]+=*)\s*$/);
  if (!match) {
    return res.status(400).json({ error: 'Invalid Authorization header format' });
  }
  
  req.token = match[1];
  next();
});

Header Sanitization - Remove dangerous characters before processing:

import re

def validate_bearer_header(header_value):
    # Remove CRLF and other control characters
    sanitized = re.sub(r'[
\x00-\x1F]', '', header_value)
    
    # Strict format: "Bearer <token>"
    parts = sanitized.split()
    if len(parts) != 2 or parts[0].lower() != 'bearer':
        raise ValueError('Invalid Bearer token format')
    
    return parts[1]

Framework-Specific Safeguards - Use built-in protections:

// Go: Strict Bearer token validation
func validateBearerToken(authHeader string) (string, error) {
    const prefix = "Bearer "
    if !strings.HasPrefix(authHeader, prefix) {
        return "", fmt.Errorf("missing Bearer prefix")
    }
    
    token := strings.TrimSpace(authHeader[len(prefix):])
    if token == "" || strings.ContainsAny(token, "\r\n") {
        return "", fmt.Errorf("invalid token format")
    }
    
    return token, nil
}

Proxy Configuration - Prevent header forwarding:

# nginx: Block forwarded Authorization headers
proxy_set_header X-Forwarded-Authorization "";
proxy_hide_header Authorization;

# Alternatively, reject requests with multiple Authorization headers
if ($http_authorization_2) {
    return 400;
}

Testing Your Fix - Verify remediation with middleBrick's continuous monitoring:

middlebrick scan --continuous --schedule=daily --webhook=https://hooks.slack.com/services/... https://api.example.com

This ensures your Bearer token endpoints remain protected against evolving header injection techniques.

Frequently Asked Questions

Can header injection bypass JWT validation?
Yes. If a server accepts multiple Authorization headers or malformed Bearer tokens, an attacker can inject tokens that bypass signature validation. The server might process only the injected token while the valid token remains unprocessed, or concatenate tokens creating a valid-but-malicious payload.
Does middleBrick detect header injection in all authentication schemes?
middleBrick specifically tests Bearer token endpoints for header injection patterns including multiple headers, CRLF injection, case variations, and token concatenation. The scanner's authentication module focuses on these Bearer-specific vulnerabilities that commonly appear in API authentication flows.