CWE-942 in APIs
What is CWE-942?
CWE-942 describes a weakness where software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources. This typically manifests as a resource leak or uncontrolled resource consumption that can be triggered by an attacker to degrade system performance or cause denial of service.
CWE-942 in API Contexts
In API environments, CWE-942 commonly appears through several attack vectors. One frequent scenario involves unbounded database queries that return excessive results without pagination. For example, an endpoint that allows clients to request all user records without limits can consume significant memory and processing power. Another manifestation is connection pool exhaustion, where APIs fail to properly close database connections or HTTP connections after use, eventually depleting the available connection pool.
File handle leaks represent another critical form of CWE-942 in APIs. When endpoints process file uploads or downloads without properly closing file streams, they can exhaust the operating system's file descriptor limit. Similarly, memory leaks occur when APIs allocate memory for processing requests but fail to release it, particularly in long-running processes or serverless functions with improper cleanup.
Rate limiting bypass scenarios also fall under CWE-942. When APIs don't properly track or enforce rate limits across distributed systems, attackers can exploit this to consume disproportionate resources. This weakness becomes especially dangerous in microservices architectures where resource consumption patterns are harder to track across service boundaries.
Detection
Detecting CWE-942 requires both static analysis and runtime monitoring. Static code analysis tools can identify patterns like missing connection.close() calls, unclosed file streams, or unbounded queries. However, runtime detection is crucial since resource leaks may only manifest under specific load conditions.
middleBrick's scanning approach includes automated detection of resource exhaustion vulnerabilities through its black-box scanning methodology. The scanner tests API endpoints under controlled load conditions to identify potential resource leaks. For database-related CWE-942 issues, middleBrick analyzes query patterns and checks for proper pagination implementation. The scanner also examines rate limiting effectiveness by testing for bypass conditions.
Key detection indicators include: monitoring response times degradation under load, tracking connection pool utilization, observing memory usage patterns, and analyzing error logs for resource-related failures. middleBrick's comprehensive scanning covers 12 security categories, including input validation and rate limiting checks that help identify CWE-942 vulnerabilities before they impact production systems.
Remediation
Effective remediation of CWE-942 requires systematic resource management practices. For database connections, always use connection pooling with proper timeout configurations and ensure connections are returned to the pool promptly. Implement try-with-resources patterns or equivalent constructs that guarantee resource cleanup even when exceptions occur.
try (Connection conn = dataSource.getConnection()) {
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
try (ResultSet rs = stmt.executeQuery()) {
// process results
}
}
} catch (SQLException e) {
// handle exception
}For API endpoints handling large datasets, always implement pagination with reasonable limits. Never allow unlimited result sets.
@app.route('/users')
def get_users():
page = request.args.get('page', 1, type=int)
limit = min(request.args.get('limit', 50, type=int), 100)
offset = (page - 1) * limit
return db.query("SELECT * FROM users LIMIT ? OFFSET ?", (limit, offset))File handling requires explicit stream closure and proper error handling to prevent descriptor leaks.
func handleUpload(w http.ResponseWriter, r *http.Request) {
file, _, err := r.FormFile("upload")
if err != nil {
http.Error(w, "Upload failed", http.StatusBadRequest)
return
}
defer file.Close()
// process file
defer os.Remove(tmpPath) // cleanup temp files
}Rate limiting implementation should use distributed counters with sliding windows to prevent bypass attacks. Implement circuit breakers for downstream services to prevent cascading failures.
Memory management in APIs requires careful attention to object lifecycle. Avoid holding references to large objects longer than necessary, and use appropriate data structures that release memory when no longer needed. For serverless functions, implement proper cleanup in finally blocks or equivalent constructs.