Fix Command Injection in Yii
Command Injection in Yii occurs when untrusted input flows into shell execution sinks like shell_exec, system, or passthru without rigorous sanitization. In a Yii context, this usually happens in Controllers or Console Commands where developers attempt to automate OS-level tasks using user-supplied parameters. Failure to neutralize shell metacharacters allows an attacker to break out of the intended command and execute arbitrary code with the permissions of the web server.
The Vulnerable Pattern
public function actionAnalyze($filename) {
// VULNERABLE: Direct concatenation of user input into a shell command.
// Attacker payload: 'file.txt; cat /etc/passwd'
$target = Yii::$app->request->get('filename');
$output = shell_exec("ls -la /var/www/uploads/" . $target);
return $this->render('analysis', ['data' => $output]);
}
The Secure Implementation
The vulnerability stems from the shell treating characters like ';', '&', '|', and '`' as command separators. The secure implementation employs a 'Defense in Depth' strategy. First, it uses a Regular Expression to whitelist input, ensuring only safe characters are processed. Second, it utilizes 'escapeshellarg()', which is the standard PHP mechanism to neutralize any remaining shell metacharacters by forcing the entire input to be treated as a single literal argument. For maximum security in Yii, avoid shell execution entirely by using native PHP functions like 'scandir()' or 'file_get_contents()' which do not invoke a command interpreter.
public function actionAnalyze($filename) { $target = Yii::$app->request->get('filename');// 1. Strict Whitelisting: Only allow alphanumeric and dots if (!preg_match('/^[a-zA-Z0-9.]+$/', $target)) { throw new \yii\web\BadRequestHttpException('Invalid characters in filename.'); } // 2. Shell Escaping: escapeshellarg() wraps the string in quotes and escapes existing ones $safeTarget = escapeshellarg($target); $output = shell_exec("ls -la /var/www/uploads/" . $safeTarget); return $this->render('analysis', ['data' => $output]);
}
Your Yii API
might be exposed to Command Injection
74% of Yii 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.