Fix Command Injection in Slim
Command injection in Slim Framework applications usually surfaces when developers pass raw PSR-7 request parameters directly into dangerous sinks like system(), exec(), or shell_exec(). Attackers exploit this by injecting shell metacharacters (;, |, &, `) to execute arbitrary OS commands with the privileges of the web server user.
The Vulnerable Pattern
$app->get('/tools/dig', function ($request, $response, $args) {
$target = $request->getQueryParams()['host'];
// VULNERABLE: Direct concatenation of user input into shell command
$result = shell_exec("dig " . $target);
$response->getBody()->write("$result
");
return $response;
});
The Secure Implementation
The fix implements a defense-in-depth strategy. First, it applies a whitelist regex to ensure the 'host' parameter contains only alphanumeric characters, dots, and hyphens, blocking common injection payloads like '; rm -rf /'. Second, it uses escapeshellarg() to wrap the string in single quotes and escape any internal single quotes, ensuring the shell treats the entire input as a single literal argument. Finally, output is passed through htmlspecialchars() to prevent secondary XSS.
$app->get('/tools/dig', function ($request, $response, $args) { $target = $request->getQueryParams()['host'] ?? '';// 1. Strict Validation: Ensure input matches expected format (e.g., domain/IP) if (!preg_match('/^[a-zA-Z0-9.-]+$/', $target)) { return $response->withStatus(400)->withJson(['error' => 'Invalid hostname']); } // 2. Escape arguments to prevent shell metacharacter interpretation $safeTarget = escapeshellarg($target); $result = shell_exec("dig " . $safeTarget); $response->getBody()->write("<pre>" . htmlspecialchars($result) . "</pre>"); return $response;
});
Your Slim API
might be exposed to Command Injection
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.