Denial Of Service with Bearer Tokens
How Denial Of Service Manifests in Bearer Tokens
Denial of Service (DoS) attacks targeting Bearer Token authentication systems exploit the stateless nature of token validation and the computational overhead of cryptographic operations. Unlike session-based authentication where servers maintain state, Bearer Token systems must validate each request independently, creating specific DoS vectors.
The most common Bearer Token DoS vector involves token validation loops. When attackers submit malformed tokens or tokens with invalid signatures, servers must perform expensive cryptographic operations to verify them. Each failed validation consumes CPU cycles, and attackers can amplify this by sending thousands of requests per second. For JWT tokens specifically, the signature verification process involves multiple cryptographic operations that can become a bottleneck under high load.
Token size amplification attacks represent another significant threat. Attackers can craft tokens with excessive claims, nested objects, or base64-encoded payloads that expand dramatically during processing. A 2KB token might decompress to 10KB or more of JSON data, forcing the server to allocate memory and parse large structures for every request. This becomes particularly problematic when token parsers aren't properly bounded.
Revocation list exhaustion attacks target systems that maintain token blacklists. Attackers can submit numerous tokens for revocation, causing the revocation list to grow until it consumes excessive memory or degrades lookup performance. Since Bearer Tokens are stateless by design, many implementations maintain these lists in memory, making them vulnerable to memory exhaustion.
// Vulnerable token validation code showing DoS potential
const validateToken = async (token) => {
try {
// Expensive cryptographic operation on every request
const decoded = await jwt.verify(token, publicKey);
return decoded;
} catch (error) {
// No rate limiting on failed attempts
return null;
}
};
// Attacker sends malformed tokens to consume CPU
for (let i = 0; i < 10000; i++) {
await fetch('/api/protected', {
headers: { 'Authorization': 'Bearer ' + generateMalformedToken() }
});
}Time-based token validation attacks exploit clock skew between servers. Attackers can submit tokens with expiration times that force servers to perform complex time calculations or trigger edge cases in date parsing libraries. This becomes especially problematic in distributed systems where servers have slightly different system clocks.
Bearer Tokens-Specific Detection
Detecting DoS vulnerabilities in Bearer Token systems requires specialized scanning that understands token validation workflows. Traditional load testing tools often miss these subtle DoS vectors because they don't understand the cryptographic operations involved.
middleBrick's Bearer Token-specific scanning includes token validation timing analysis. The scanner submits both valid and malformed tokens, measuring the time difference between successful and failed validations. If failed validations take nearly as long as successful ones, it indicates the system is performing expensive operations even on invalid input—a classic DoS vulnerability.
The scanner also tests token size limits by submitting progressively larger tokens until the server rejects them or performance degrades. It specifically looks for lack of maximum token size enforcement, which allows attackers to submit arbitrarily large tokens. middleBrick's size analysis includes base64 decoding overhead and JSON parsing costs.
Rate limiting bypass detection is crucial for Bearer Token systems. The scanner tests whether failed token validations are subject to the same rate limits as successful requests. Many implementations apply rate limiting only after successful authentication, leaving the validation endpoint completely exposed to DoS attacks.
middleBrick's LLM/AI security module also tests for prompt injection in AI-powered authentication systems that might use Bearer Tokens. This includes testing for system prompt leakage that could reveal token validation logic or secret keys used in the verification process.
# middleBrick CLI scan for Bearer Token DoS vulnerabilities
middlebrick scan https://api.example.com --token-test --size-limit --rate-limit
# Output includes:
# - Token validation timing analysis
# - Maximum token size enforcement check
# - Rate limiting bypass detection
# - Cryptographic operation cost analysis
# - Memory usage patterns during token processingThe scanner's continuous monitoring feature can track token validation performance over time, alerting when validation times increase or when the system shows signs of degradation under load. This helps identify gradual performance issues that might indicate a DoS attack in progress.
Bearer Tokens-Specific Remediation
Securing Bearer Token systems against DoS attacks requires implementing multiple defensive layers that address the specific vulnerabilities of stateless token validation.
Input validation and size limits are the first line of defense. Implement strict maximum token sizes and validate token structure before attempting cryptographic operations. Reject tokens that exceed reasonable size limits or contain suspicious patterns.
// Secure token validation with DoS protection
const MAX_TOKEN_SIZE = 8192; // 8KB maximum
const MAX_CLAIMS = 20;
const validateToken = async (token) => {
if (!token || token.length > MAX_TOKEN_SIZE) {
throw new Error('Token size invalid');
}
try {
// Fast pre-validation before expensive crypto
const [header, payload] = token.split('.');
if (!header || !payload) {
throw new Error('Malformed token');
}
// Early exit for obviously invalid tokens
if (header.length < 20 || payload.length < 20) {
throw new Error('Token too short');
}
// Perform cryptographic validation
const decoded = await jwt.verify(token, publicKey, {
algorithms: ['RS256', 'HS256'],
maxAge: '24h'
});
// Validate payload structure
if (Object.keys(decoded).length > MAX_CLAIMS) {
throw new Error('Too many claims');
}
return decoded;
} catch (error) {
// Log but don't crash on invalid tokens
console.warn('Token validation failed:', error.message);
throw new Error('Invalid token');
}
};
Rate limiting at the validation layer is critical. Apply rate limits to all token validation attempts, not just successful authentications. Use token bucket or sliding window algorithms that can handle burst traffic without becoming CPU-intensive themselves.
Caching is an effective mitigation for repeated token validation. Implement a cache for valid tokens that allows quick rejection of previously seen invalid tokens without re-running expensive cryptographic operations. Use a time-based cache with appropriate TTL values.
// Token validation with caching and rate limiting
const LRU = require('lru-cache');
const rateLimit = require('express-rate-limit');
const invalidTokenCache = new LRU({
max: 10000,
maxAge: 1000 * 60 * 5 // 5 minutes
});
const validationRateLimiter = rateLimit({
windowMs: 1 * 60 * 1000, // 1 minute
max: 100, // limit each IP to 100 requests per windowMs
message: 'Too many token validation attempts'
});
app.use('/api/protected', validationRateLimiter, async (req, res) => {
const token = extractToken(req);
// Check cache first
if (invalidTokenCache.has(token)) {
return res.status(401).json({ error: 'Invalid token' });
}
try {
const decoded = await validateToken(token);
req.user = decoded;
next();
} catch (error) {
invalidTokenCache.set(token, true);
return res.status(401).json({ error: 'Invalid token' });
}
});
Implement circuit breakers for token validation services. When validation failures exceed a threshold, temporarily reject all token validation requests to prevent cascading failures. This protects the system during active DoS attacks.
Consider using asymmetric cryptography where verification is computationally cheaper than signing. This reduces the cost of the most common operation (verification) while maintaining security. Also implement proper error handling that doesn't leak information about why validation failed, preventing attackers from optimizing their attacks.
Related CWEs: resourceConsumption
| CWE ID | Name | Severity |
|---|---|---|
| CWE-400 | Uncontrolled Resource Consumption | HIGH |
| CWE-770 | Allocation of Resources Without Limits | MEDIUM |
| CWE-799 | Improper Control of Interaction Frequency | MEDIUM |
| CWE-835 | Infinite Loop | HIGH |
| CWE-1050 | Excessive Platform Resource Consumption | MEDIUM |