Fix Unrestricted Resource Consumption in Slim
Unrestricted Resource Consumption in Slim Framework apps occurs when endpoints lack constraints on request size, execution time, or frequency. This allows attackers to trigger Denial of Service (DoS) by exhausting memory, CPU cycles, or disk space. To harden the application, we must enforce strict middleware-level limits and validate input sizes before processing.
The Vulnerable Pattern
$app->post('/process-data', function ($request, $response) { $data = $request->getParsedBody(); // VULNERABILITY: No check on the size of the input array or string. // A massive JSON body can cause memory exhaustion during processing. $result = some_expensive_computation($data); return $response->withJson(['status' => 'done']); });
$app->post(‘/upload’, function ($request, $response) { $files = $request->getUploadedFiles(); $file = $files[‘avatar’]; // VULNERABILITY: No size validation. Attackers can fill the disk. $file->moveTo(‘/uploads/’ . $file->getClientFilename()); return $response->withStatus(200); });
The Secure Implementation
The secure implementation mitigates resource exhaustion at three levels: First, ContentLengthMiddleware rejects requests that exceed the server's 'post_max_size' or lack a length header. Second, RateLimitMiddleware prevents attackers from spamming the endpoint to consume CPU or connection slots. Third, explicit size validation via '$file->getSize()' ensures that even if the web server allows large uploads, the application logic rejects them before they are moved to permanent storage. For heavy computation, always offload tasks to an asynchronous queue (like RabbitMQ or Redis) to avoid blocking PHP-FPM workers.
use Slim\Middleware\ContentLengthMiddleware; use Tuupola\Middleware\RateLimitMiddleware;// 1. Enforce global Content-Length limits $app->add(new ContentLengthMiddleware());
// 2. Rate limiting to prevent request flooding $app->add(new RateLimitMiddleware([ ‘limit’ => 50, ‘timeout’ => 3600 ]));
$app->post(‘/upload’, function ($request, $response) { $files = $request->getUploadedFiles(); $file = $files[‘avatar’] ?? null;
if (!$file || $file->getError() !== UPLOAD_ERR_OK) { return $response->withStatus(400); } // 3. Explicit file size check (e.g., 2MB limit) if ($file->getSize() > 2097152) { return $response->withStatus(413)->write('Payload Too Large'); } $dest = '/secure/uploads/' . bin2hex(random_bytes(16)); $file->moveTo($dest); return $response->withStatus(201);
});
Your Slim API
might be exposed to Unrestricted Resource Consumption
74% of Slim apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.
Free Tier • No Credit Card • Instant Report
Verified by Ghost Labs Security Team
This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.