2022-09-01 17:51:40 +02:00
|
|
|
=== 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.
|
|
|
|
|
2022-09-15 10:28:08 +02:00
|
|
|
==== Non-compliant code example
|
|
|
|
|
|
|
|
[source,java,diff-id=1,diff-type=noncompliant]
|
2022-09-01 17:51:40 +02:00
|
|
|
----
|
|
|
|
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();
|
|
|
|
|
2022-09-15 10:28:08 +02:00
|
|
|
query.append("$where", "this.field == \"" + input + "\"");
|
2022-09-01 17:51:40 +02:00
|
|
|
|
|
|
|
collection.find(query);
|
|
|
|
}
|
|
|
|
----
|
2022-09-15 10:28:08 +02:00
|
|
|
|
|
|
|
==== Compliant solution
|
|
|
|
|
|
|
|
[source,java,diff-id=1,diff-type=compliant]
|
2022-09-01 17:51:40 +02:00
|
|
|
----
|
|
|
|
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.
|
|
|
|
|