CWE-835 in APIs
- CWE ID
- CWE-835
- Category
- Resource Consumption
- Severity
- HIGH
- Short Name
- Infinite Loop
What is Cwe 835?
CWE-835, also known as Loop with Unreachable Exit Condition ('Infinite Loop'), is a critical software weakness where a loop's exit condition can never be satisfied, causing the program to enter an infinite loop. This weakness occurs when the loop's termination logic is flawed, missing, or dependent on conditions that can never be met during execution.
The official CWE description states: 'The program contains an iteration or loop that does not have a valid end condition. This may result in an infinite loop that wastes CPU cycles or produces unintended side effects.' Infinite loops can lead to denial of service, resource exhaustion, and in some cases, security vulnerabilities if they allow attackers to consume system resources.
Common causes include:
- Missing or incorrect loop termination conditions
- Conditions that depend on external state that never changes
- Mathematical operations that never reach the exit threshold
- Logical errors in comparison operators or boundary conditions
- Race conditions where the exit condition is modified by concurrent processes
Infinite loops are particularly dangerous in API contexts because they can tie up server resources, prevent other requests from being processed, and potentially crash the entire service if not properly handled.
Cwe 835 in API Contexts
In API development, CWE-835 manifests in several critical ways that can compromise service availability and security. API endpoints often process data in loops, and when these loops lack proper termination conditions, they can create severe performance issues or denial of service conditions.
Common API scenarios:
- Pagination loops: An API endpoint that processes paginated data but fails to check for the end of the dataset, causing it to request pages indefinitely.
- Recursive API calls: Functions that call themselves or other endpoints without proper base cases, creating infinite recursion chains.
- Stream processing: APIs that read from data streams but never detect end-of-stream conditions, causing continuous processing attempts.
- Polling mechanisms: Background processes that poll external services but lack timeout or retry limits.
- Queue processing: Worker processes that dequeue items but fail to detect empty queue states.
Security implications: Attackers can exploit infinite loops in APIs to cause denial of service by triggering endpoints that enter unrecoverable loops. This is particularly dangerous in serverless architectures where each function instance consumes allocated resources. An infinite loop in a Lambda function, for example, will continue consuming CPU time and memory until the timeout is reached, potentially exhausting the account's concurrency limits.
Real-world example: A REST API endpoint that processes user-generated content might contain a loop that validates or transforms data. If the validation logic contains a flaw where the exit condition depends on a property that's never set correctly, the API could enter an infinite loop when processing malicious or malformed input, effectively making the endpoint unavailable to legitimate users.
Detection
Detecting CWE-835 requires both static code analysis and dynamic runtime testing. Static analysis tools can identify suspicious loop patterns, but dynamic testing is crucial for catching runtime-specific infinite loop scenarios that only manifest with certain inputs.
Static analysis techniques:
- Code review patterns: Look for loops without clear exit conditions, especially those depending on external state or complex conditions.
- Complexity analysis: Identify functions with high cyclomatic complexity where loop logic is difficult to reason about.
- Dead code detection: Find code paths that could prevent loop termination under specific conditions.
Dynamic testing approaches:
- Timeout-based testing: Run API endpoints with various inputs and monitor for operations that exceed reasonable time limits.
- Resource monitoring: Track CPU and memory usage during API calls to detect unusual consumption patterns.
- Input fuzzing: Test endpoints with malformed, boundary, and edge-case inputs to trigger unexpected loop behaviors.
middleBrick API security scanning: middleBrick includes automated detection for CWE-835 patterns through its comprehensive black-box scanning approach. The scanner tests API endpoints by:
- Submitting boundary and edge-case inputs that might trigger infinite loops
- Monitoring response times and detecting timeouts or hanging requests
- Analyzing error responses for patterns indicating loop-related issues
- Testing pagination and recursive endpoints with various parameters
When middleBrick detects potential infinite loop vulnerabilities, it reports them with severity ratings, the specific endpoint affected, and recommendations for reproducing and fixing the issue. The scanner's 5-15 second test window is particularly effective at catching loops that would otherwise run indefinitely, as it can identify endpoints that fail to respond within normal processing timeframes.
Manual testing checklist:
for each API endpoint do:
test with minimal valid input
test with maximum valid input
test with boundary values (0, -1, max int, empty strings)
test with malformed or unexpected input
monitor response times and resource usage
verify all loops have clear exit conditionsRemediation
Fixing CWE-835 requires implementing proper loop termination conditions and defensive programming practices. The key is to ensure every loop has a guaranteed exit path regardless of input or external conditions.
Core remediation strategies:
- Always implement explicit exit conditions: Every loop must have a clear, verifiable condition that will eventually be met.
- Set maximum iteration limits: Implement hard limits on loop iterations as a safety mechanism.
- Validate external dependencies: Ensure conditions depending on external state include timeout or fallback mechanisms.
- Use defensive programming: Assume inputs might be malformed and design loops to handle unexpected cases gracefully.
Code examples:
Problematic pattern:
// Vulnerable - no exit condition if data is malformed
function processItems(items) {
let i = 0;
while (true) { // Infinite loop risk
if (items[i] && items[i].valid) {
process(items[i]);
}
i++;
}
}
Fixed version:
// Secure - proper exit conditions and limits
function processItems(items) {
const maxIterations = 1000;
let i = 0;
while (i < items.length && i < maxIterations) {
if (items[i] && items[i].valid) {
process(items[i]);
}
i++;
}
if (i === maxIterations) {
console.warn('ProcessItems reached iteration limit');
}
}
API endpoint example:
// Vulnerable pagination endpoint
app.get('/api/process-data', async (req, res) => {
let page = 1;
const data = await fetchPage(page);
await processData(data.items);
Secure pagination with timeout:
app.get('/api/process-data', async (req, res) => {
const maxPages = 100;
const maxTimeMs = 30000;
const startTime = Date.now();
let page = 1;
let totalProcessed = 0;
try {
while (page <= maxPages) {
const data = await fetchPage(page);
if (data.items.length === 0) break;
await processData(data.items);
totalProcessed += data.items.length;
page++;
if (Date.now() - startTime > maxTimeMs) {
console.warn('Process-data reached time limit');
break;
}
}
res.json({
success: true,
pagesProcessed: page,
totalItems: totalProcessed,
completed: page <= maxPages
});
} catch (error) {
res.status(500).json({
success: false,
error: error.message,
partial: totalProcessed > 0
});
}
Best practices for API development:
- Always validate input data before processing in loops
- Implement circuit breakers for external service calls
- Use timeout mechanisms for long-running operations
- Log iteration counts and processing times for monitoring
- Include comprehensive error handling that doesn't depend on loop state
- Test with malformed and edge-case inputs specifically targeting loop logic
middleBrick integration: After implementing fixes, use middleBrick's continuous monitoring capabilities to verify that your remediation works. The scanner will retest your endpoints and provide updated security scores, ensuring that infinite loop vulnerabilities are properly resolved before deployment.
Frequently Asked Questions
How can I tell if my API has an infinite loop vulnerability?
Look for API endpoints that process data in loops without clear exit conditions, especially those handling pagination, batch processing, or recursive operations. Signs include endpoints that occasionally hang, consume excessive CPU, or fail to respond within normal timeframes. Use middleBrick's black-box scanning to automatically detect these issues by testing with various inputs and monitoring for timeouts or hanging requests.
What's the difference between CWE-835 and a simple performance issue?
CWE-835 is a specific security weakness where a loop's exit condition is fundamentally flawed, causing it to run indefinitely under certain conditions. This is different from general performance issues, which might be slow but still terminate correctly. Infinite loops can be exploited by attackers to cause denial of service, while performance issues typically just result in slow responses. CWE-835 represents a critical security vulnerability that can crash services, whereas performance issues are operational concerns.