Mongo Injection

Mongo injection or NoSQL injection is the name of the attack used to modify the meaning of a mongo DB query. While SQL and Xpath injection are triggered using specially crafted string, with mongo we need to create a specially crafted object instead. This is commonly found in nodeJS project using express and mongo.
Mongo injection are more limited than other kind of injections because while you can change the meaning of a query, you are limited to the collection the query it run on.


Imagine the following javascript code for a simple admin login.

Line 12 the POST variable pass is inserted in the query without any sanitization, this is vulnerable to NoSQL injection. An attacker could submit this pass[ywh]=test, and bodyParser will parse it as {"ywh": "test"} changing the type from string to object.

To simulate this behavior, we will use the jsonify function of the dojo, this will convert the input to a json object if possible. This is what the actual query look like after the variable substitution:

Now let's look at what happend when we tried to inject some malicious object instead of a string.

When the $pass is set to {"$ne": "a"}the meaning of query change, this is an injection. Here the attacker completly bypass the password check because of the negative password check at the end.
But this is not the only thing an attacker can do in this scenario, by using more advance feature of mongodb it is possible to extract the value of the matched object. If the website answer differently if the returned value is true or false, then you can use this as an oracle to leak the content of the database.

This time, the query will return true only if the first character is an h, by iterating over the alphabet and updating the regex, it is possible to recover the password from the database.


Now that you know the basics of Mongo injection, you can test your skill, you can test your skill on our official challenges: