=== How to fix it in Legacy Mongo Java API

The following code is vulnerable to NoSQL injections because untrusted data is
concatenated to the `$where` operator. This operator indicates to the backend
that the expression needs to be interpreted, resulting in code injection.

[cols="a"]
|===
h| Non-compliant code example
|
[source,java]
----
import com.mongodb.MongoClient;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws UnknownHostException
{
    String input = req.getParameter("input");

    MongoClient mongoClient = new MongoClient();
    DB database             = mongoClient.getDB("exampleDatabase");
    DBCollection collection = database.getCollection("exampleCollection");
    BasicDBObject query     = new BasicDBObject();

    query.append("$where", "this.field == \"" + input + "\""); // Noncompliant

    collection.find(query);
}
----
h| Compliant solution
|
[source,java]
----
import com.mongodb.MongoClient;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws UnknownHostException
{
    String input = req.getParameter("input");

    MongoClient mongoClient = new MongoClient();
    DB database             = mongoClient.getDB("ExampleDatabase");
    DBCollection collection = database.getCollection("exampleCollection");
    BasicDBObject query     = new BasicDBObject();

    query.append("field", input);

    collection.find(query);
}
----
|===

=== How does this work?

include::../../common/fix/pre-approved-list.adoc[]

include::../../common/fix/dangerous-operators.adoc[]

In the previous example, the untrusted data doesn't need validation for its use
case. Moving it out of a `$where` expression into a proper field query is
enough.

