1

I was trying to find out how to prevent MongoDB injections, and I came across this. So, the vulnerable code here is

app.post('/', function (req, res) {
        db.users.find({username: req.body.username, password: req.body.password}, function (err, users) { // This line!
            // TODO: handle the rest
        });
});

Could I protect against a MongoDB injection by verifying that the POST body username and password are both strings, and not objects?

Are there any other ways to inject data into a MongoDB database?

  • 1
    Possible duplicate of How to secure a MongoDB instance? – crovers Jul 20 '17 at 21:17
  • 1
    @crovers that doesn't answer the question - does verifying that the input is a string sanitize inputs completely – Bennett Jul 20 '17 at 21:36
1

Yes, verifying the input is a string will sanitize it.

MongoDB doesn't parse strings, only JSON. A common attack on MongoDB is:

{"$gte":""}

When put in a query, this will return all objects. An attacker can pass this as a parameter, and some parsers will automatically expand it into an object, which will make your JSON look like this

{
    username: "root",
    password: { $gte: ""}
}

When this find command is run, it'll return the root user even though a password wasn't supplied. (Note: Do not verify passwords like this)

Now here's an example where we ensure that the input is a string

{
    username: "root",
    password: "{\"$gte\":\"\"}"
}

As you can see, there's no injection, and we're literally looking for that password.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.