Fix NoSQL Injection in Yii
NoSQL injection in Yii2 typically manifests when using the yii2-mongodb extension. The flaw occurs because PHP's superglobals like $_POST can handle nested arrays. If an application passes raw input directly into a query filter, an attacker can inject MongoDB operators such as $ne (not equal), $gt (greater than), or $regex to bypass authentication or dump data. As a Senior AppSec Researcher, I see this most often when developers assume input is always a scalar string.
The Vulnerable Pattern
// Vulnerable: Directly passing unsanitized user input into the query filter $username = Yii::$app->request->post('username'); $password = Yii::$app->request->post('password');
// If an attacker sends password[$ne]=1, the query becomes [‘password’ => [‘$ne’ => ‘1’]] $user = User::find()->where([ ‘username’ => $username, ‘password’ => $password ])->one();
The Secure Implementation
The exploit leverages the way Yii's MongoDB Query Builder handles arrays. When the 'password' parameter is provided as an array (e.g., via a crafted POST request), the query builder interprets the keys as NoSQL operators. By casting the input to a string, you force the query engine to treat the payload as a literal value rather than a command. Additionally, implementing Model validation rules using 'yii\validators\StringValidator' ensures that input conforms to expected types before it ever reaches the database layer.
// Secure: Explicitly cast input to expected types or use strict attribute matching $username = (string)Yii::$app->request->post('username'); $password = (string)Yii::$app->request->post('password');// 1. Casting to string prevents array-based operator injection $user = User::find()->where([ ‘username’ => $username, ‘password’ => $password ])->one();
// 2. Alternative: Use findOne() which is safer for primary key lookups // $user = User::findOne([‘username’ => $username, ‘password’ => $password]);
Your Yii API
might be exposed to NoSQL 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.