Skip to content

NoSQL Injection (ARCH7140)

Key php.security.nosql-injection · Severity error · Category security · CWE CWE-943

Placing user input directly into a MongoDB query lets an attacker inject operator objects such as {"$ne": null} to bypass authentication.

<?php
// password=array('$ne' => null) → matches any password
$user = $collection->findOne([
'user' => $_POST['user'],
'password' => $_POST['password'],
]);
<?php
$user = $collection->findOne(['user' => (string) $_POST['user']]);
if ($user && password_verify((string) $_POST['password'], $user['password'])) {
// login succeeds
}

Coerce query values to the expected primitive types (string/int); never let operator objects flow in from user input.