Fix Command Injection in Laravel
Command injection occurs when an application passes unvalidated user input to a system shell. In Laravel, this typically happens when developers use functions like `exec()`, `system()`, or the `Process` facade with raw string concatenation. A malicious actor can use shell metacharacters like `;`, `&&`, or `|` to execute arbitrary code with the privileges of the web server user.
The Vulnerable Pattern
public function checkStatus(Request $request) {
$ip = $request->input('ip');
// CRITICAL VULNERABILITY: Raw concatenation allows shell breakout
// Input: '8.8.8.8; cat /etc/passwd'
$output = shell_exec('ping -c 1 ' . $ip);
return response($output);
}
The Secure Implementation
The vulnerable code is susceptible because `shell_exec` invokes a shell to parse the string, allowing command chaining. The secure implementation mitigates this by: 1. Strict Validation: Using Laravel's validator to ensure the input is a valid IP address. 2. Array-based Execution: Using the `Process` facade with an array of arguments. When arguments are passed as a list, Laravel (and underlying Symfony components) handles the escaping or uses system calls that do not invoke a shell interpreter, making it impossible for user input to be interpreted as a command.
use Illuminate \Support\Facades\Process; use Illuminate\Support\Facades\Validator;public function checkStatus(Request $request) { $request->validate([ ‘ip’ => ‘required|ip’ ]);
// SECURE: Pass arguments as an array to the Process facade. // This uses execve() style execution, bypassing the shell and preventing injection. $result = Process::run(['ping', '-c', '1', $request->input('ip')]); if ($result->successful()) { return $result->output(); } return response('Ping failed', 500);
}
Your Laravel API
might be exposed to Command Injection
74% of Laravel 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.