﻿# V5337\. OWASP\. Possible NoSQL injection\. Potentially tainted data is used to create query\.

The analyzer has detected that unverified external data is used to create a query to a NoSQL database\. This can lead to a NoSQL injection if the data is compromised\.

This vulnerability can be categorized under the OWASP Top 10 Application Security Risks 2021 classification as follows:

* [A3:2021\-Injection\.](https://owasp.org/Top10/A03_2021-Injection/)

The example:

```cpp
public List<Document> getFoo(String bar) {
  BasicDBObject query = new BasicDBObject();
  query.put(
      "$where",
      "this.bar == \"" + bar + "\""
  );

  MongoCursor<Document> cursor = collection.find(query).iterator();
  // ....
}
```

When creating a NoSQL query, unverified data from a public method parameter is passed to the `$where` operator\. Since the method is public, it may receive unverified external data from controllers, forms, or others\. The `$where` operator interprets the JavaScript code from the second argument of the `put` method, which enables attackers to inject arbitrary commands into the query\.

Instead of the expected search predicate, attackers can write a special command\. As a result, the database outputs all data, which will be processed further\.

The example of the compromised string for the `bar` parameter:

```cpp
" || "1" != "2
```

To protect against such attacks, use a parameterization:

```cpp
public List<Document> getFoo(String bar) {
  BasicDBObject query = new BasicDBObject();
  query.append("bar", bar);

  MongoCursor<Document> cursor = collection.find(query).iterator();
    // ....
}
```

Or create a query in BSON format using the special `Filters` class:

```cpp
public List<Document> getFoo(String bar) {
  Bson filter = Filters.and(
      Filters.eq("bar", bar)
  );

  MongoCursor<Document> cursor = collection.find(filter).iterator();
  // ....
}
```

If script operations are not used in the project, it is recommended to completely [disable server script execution](https://www.mongodb.com/docs/manual/reference/operator/query/where/#javascript-enablement)\. Learn more about NoSQL injections on the [OWASP website](https://cheatsheetseries.owasp.org/cheatsheets/NoSQL_Security_Cheat_Sheet.html)\.