MongoDB Injection Example



Below is a example on how MongoDB Injection works:

For example you have a PHP code like this.

<?php
$m = new \MongoDB\Driver\Manager();
if(isset($_POST['u']) && isset($_POST['p'])) {
    $c = new \MongoDB\Driver\Query(array('username' => $_POST['u'], 'password' => $_POST['p']), array('limit' => 10));
    $user = $m->executeQuery('mydb.user', $c);
    echo '<pre>';
    print_r($user);
    exit;
}
?>
<form method="post">
    <input type="text" placeholder="Enter Username" name="u" /><br>
    <input type="password" placeholder="Enter Password" name="p"/><br>
    <input type="submit" />
</form>

In this example, the code will search for a user in the user collection inside mydb database. It will search for a user with the same username and password on the form fields.

If you run the PHP script above, you will see this.

Now here are the entries on the user collection.

The script will retrieve the user information as long as we enter a correct combination of username and password right? But, what if we change the form fields to this.
mongo3

As you can see, we change the name of the fields on the form and convert it into array with $ne key, which is used as a condition for mongo filter.

What will happen if we leave the username and password field blank and submit this?

If you have used mongodb, you will notice that $ne is a condition used for NOT queries. So if you submit the form, It will search for a username that is NOT empty and a password that is NOT empty. This means it will select everything on your user collection.

To avoid this kind of vulnerability, always check the data type of any variables that is being submitted by the users.