# 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.

The example:

    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:

    " || "1" != "2

To protect against such attacks, use a parameterization:

    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:

    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. Learn more about NoSQL injections on the OWASP website.

This diagnostic is classified as:

CWE-943 OWASP-5.3.4