What is NoSQL Injection?

NoSQL Injection is security vulnerability that lets attackers take control of database queries through the unsafe use of user input. It can be used by an attacker to:

  • Expose unauthorized information
  • Modify data
  • Escalate privileges
  • Take down your entire application

Over the past few years, we’ve worked with many teams building amazing software with Meteor and MongoDB. But to our shock and dismay, we’ve found NoSQL Injection vulnerabilities in nearly all of these projects.

An Example Application

Let’s make things more real by introducing an example to help us visualize how NoSQL Injection can occur, and the impact it can have on your application.

Imagine that our application accepts a username and a password hash from users attempting to log into the system. We check if the provided username/password combination is valid by searching for a user with both fields in our MongoDB database:

    login(username, hashedPassword) {
        return Meteor.users.findOne({ username, hashedPassword });

If the user provided a valid username, and that user’s corresponding hashedPassword, the login method will return that user’s document.

Exploiting Our Application

In this example, we’re assuming that username and hashedPassword are strings, but we’re not explicitly making that assertion anywhere in our code. A user could potentially pass up any type of data from the client, such as a string, a number, or even an object.

A particularly clever user might pass up "admin" as their username, and {$gte: ""} as their password. This combination would result in our login method making the following query:

db.users.findOne({ username: "admin", hashedPassword: {$gte: ""}})

This query will return the first document it finds with a username of "admin" and a hashed password that is greater an empty string. Regardless of the admin user’s password, their user document will be returned by this query.

Our clever user has successfully bypassed out authentication scheme by exploiting a NoSQL Injection vulnerability.