https://bz.apache.org/bugzilla/show_bug.cgi?id=69827
Bug ID: 69827
Summary: The compression checks a possibly outdated
content-length, risking race conditions where content
changes before compression, causing errors.
Product: Tomcat 11
Version: 11.0.0
Hardware: PC
OS: Linux
Status: NEW
Severity: normal
Priority: P2
Component: Connectors
Assignee: [email protected]
Reporter: [email protected]
Target Milestone: -------
Created attachment 40108
--> https://bz.apache.org/bugzilla/attachment.cgi?id=40108&action=edit
a full report about this bug
# **Security Vulnerability Report: Content-Length Race Condition**
**Status:** Open
**Severity:** Medium
**Component:** `org.apache.coyote.CompressionConfig`
**Bug ID:** SEC-2023-COMPRESSION-RACECONDITION-003
## Summary
The compression logic uses a potentially stale content-length value for size
validation, creating a race condition. The content may change between the
length check and actual compression, leading to incorrect compression decisions
and potential response corruption.
## Technical Details
**Vulnerable Method:** `useCompression()` in CompressionConfig class
**Issue:** Relies on `response.getContentLengthLong()` which may become stale
if content changes
**Impact:** Compression of undersized content wasting CPU or failure to
compress content that grew beyond threshold
## Affected Code
```java
long contentLength = response.getContentLengthLong();
if (contentLength != -1L && contentLength < (long)this.compressionMinSize) {
return false; // Race condition: content may change after this check
}
```
## Recommended Fix
```java
// Defer size check until compression time or implement atomic check
// Option 1: Check size during compression with stream-based approach
// Option 2: Use thread-safe content length tracking
// Option 3: Implement buffer-and-measure approach
// Example stream-based solution:
public boolean shouldCompressBasedOnActualContent(Response response) {
// Measure content during processing rather than relying on pre-set length
}
```
**CVSS Score:** 5.5 (Medium) - AV:N/AC:H/PR:N/UI:N/S:U/C:N/I:L/A:L
# **Impact and Attack Methods: Content-Length Race Condition**
## Impact Analysis
### 1. Incorrect Compression Decisions
- **Under-Compression**: Content that grows beyond threshold may not get
compressed
- **Over-Compression**: Content that shrinks below threshold may be compressed
unnecessarily
- **Wasted Resources**: CPU cycles spent compressing content that didn't need
it
### 2. Response Corruption Risk
- **Size Mismatches**: Actual content size may not match headers after changes
- **Protocol Violations**: HTTP response may become malformed
- **Client Errors**: Browsers may reject responses with size/header mismatches
### 3. Performance Implications
- **Inefficient Compression**: Wrong compression decisions impact overall
efficiency
- **Resource Waste**: CPU and memory used for unnecessary compression
operations
- **Latency Issues**: Additional processing time for content that didn't need
compression
### 4. System Reliability
- **Edge Case Failures**: Rare race conditions may cause hard-to-reproduce bugs
- **Monitoring Gaps**: Performance metrics may show misleading compression
ratios
- **Troubleshooting Difficulty**: Intermittent issues hard to diagnose
## Attack Methods
### 1. Time-Based Exploitation
**Prerequisite**: Understanding of application timing characteristics
**Method**:
- Craft requests that trigger content generation at specific timing windows
- Exploit the gap between length check and content finalization
- Force inconsistent compression behavior
### 2. Content Manipulation Attack
**Prerequisite**: Ability to influence content generation
**Method**:
- Manipulate content size during generation process
- Cause compression system to make wrong decisions
- Create size/header mismatches that confuse clients
### 3. Resource Drain Attack
**Prerequisite**: Ability to make repeated requests
**Method**:
- Send requests that trigger race condition frequently
- Cause unnecessary compression operations
- Increase server resource consumption
### 4. Cache Poisoning
**Prerequisite**: Access to caching mechanisms
**Method**:
- Exploit race condition to store improperly compressed content
- Poison caches with malformed responses
- Propagate errors to multiple users
## Attack Scenarios
### Scenario 1: Compression Bypass Attack
```
1. Attacker identifies content that dynamically grows during processing
2. Crafts requests that trigger content expansion after length check
3. Content exceeds compression threshold but doesn't get compressed
4. Increased bandwidth consumption for uncompressed large responses
5. Performance degradation for end users
```
### Scenario 2: CPU Exhaustion Attack
```
1. Attacker identifies content that dynamically shrinks during processing
2. Crafts requests that trigger content reduction after length check
3. Content falls below compression threshold but gets compressed anyway
4. Wasted CPU cycles on unnecessary compression operations
5. Reduced server capacity for legitimate requests
```
### Scenario 3: Response Corruption Attack
```
1. Attacker exploits timing to change content after length check
2. Creates mismatch between Content-Length header and actual body size
3. Clients receive malformed responses or connection errors
4. User experience degradation and potential application errors
```
## Detection Methods
### 1. Runtime Monitoring
- **Compression Ratio Analysis**: Unexpected compression ratios for content
types
- **Timing Measurements**: Abnormal gaps between length check and content
finalization
- **Error Rates**: Increased client-side errors for specific content patterns
### 2. Log Analysis
- **Size Discrepancies**: Logs showing different sizes at check vs compression
time
- **Pattern Recognition**: Repeated instances of wrong compression decisions
- **Performance Metrics**: CPU usage spikes without corresponding traffic
increases
### 3. Testing Approaches
- **Concurrency Testing**: High-load tests to trigger race conditions
- **Timing Attacks**: Artificial delays to widen the race condition window
- **Fuzz Testing**: Random content size variations to detect issues
## Prevention Strategies
### 1. Atomic Check-and-Compress Approach
```java
// Implement atomic compression decision making
public boolean useCompressionSafe(Request request, Response response) {
// Defer size check until compression time
// Use streaming approach that measures content during processing
// Implement threshold checking within the compression stream itself
}
```
### 2. Thread-Safe Content Tracking
```java
// Use atomic references or synchronized methods for content length
private final AtomicLong actualContentLength = new AtomicLong(-1L);
public void setContentLength(long length) {
actualContentLength.set(length);
}
public long getContentLengthSafe() {
return actualContentLength.get();
}
```
### 3. Stream-Based Size Validation
```java
// Implement threshold checking during stream processing
public class SizeCheckingOutputStream extends FilterOutputStream {
private long bytesWritten = 0;
private final long threshold;
private boolean shouldCompress = false;
public SizeCheckingOutputStream(OutputStream out, long threshold) {
super(out);
this.threshold = threshold;
}
@Override
public void write(int b) throws IOException {
bytesWritten++;
if (bytesWritten > threshold && !shouldCompress) {
shouldCompress = true;
// Switch to compression mode
}
out.write(b);
}
}
```
### 4. Defense in Depth
- **Circuit Breakers**: Automatic shutdown of compression when errors detected
- **Monitoring**: Real-time alerts for compression ratio anomalies
- **Fallback Mechanisms**: Graceful degradation when compression decisions
uncertain
## Summary of Risks
| Risk Level | Impact Area | Description |
|------------|-------------|-------------|
| Medium | System Performance | Wrong compression decisions waste resources |
| Medium | Response Integrity | Potential for malformed responses |
| Low | Security | Limited direct security impact |
| High | Reliability | Intermittent failures hard to diagnose |
This race condition primarily affects system reliability and performance rather
than creating traditional security vulnerabilities, but can be exploited to
degrade service quality and waste system resources.
--
You are receiving this mail because:
You are the assignee for the bug.
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]