rspec/rules/S5147/csharp/how-to-fix-it/mongodb-csharp-driver.adoc

78 lines
2.1 KiB
Plaintext
Raw Normal View History

== How to fix it in MongoDB
=== Code examples
The following code is vulnerable to NoSQL injections because untrusted data is
used to find data in a database.
Such cases can be encountered when client-side code crafts the query, such as
``++[{ '$match': { 'Username': 'John Doe' } }]++``.
Note that `Find` and `FindAsync` are not the only constructs whose input should be
verified. Multiple
https://mongodb.github.io/mongo-csharp-driver/2.4/reference/driver/definitions/[definitions]
can be built from a string and allow attackers to leak or tamper with data.
==== Noncompliant code example
[source,csharp,diff-id=1,diff-type=noncompliant]
----
using MongoDB.Driver;
using MongoDB.Bson;
[ApiController]
[Route("Example")]
public class ExampleController: ControllerBase
{
private string connectionString;
[Route("Example")]
public async Task<string> Example()
{
var client = new MongoClient(connectionString);
var database = client.GetDatabase("example");
var collection = database.GetCollection<Message>("messages");
var filterDefinition = Request.Query["filterDefinition"];
await collection.FindAsync(filter)
}
}
----
==== Compliant solution
[source,csharp,diff-id=1,diff-type=compliant]
----
using MongoDB.Driver;
using MongoDB.Bson;
[ApiController]
[Route("Example")]
public class ExampleController: ControllerBase
{
private string connectionString;
[Route("Example")]
public async Task<string> Example()
{
var client = new MongoClient(connectionString);
var database = client.GetDatabase("example");
var collection = database.GetCollection<Message>("messages");
var filterDefinition = Builders<BsonDocument>.Filter.Eq("Username", "Example");
await collection.FindAsync(filter)
}
}
----
=== How does this work?
include::../../common/fix/builder-pattern.adoc[]
If using a builder pattern is not possible, follow the instructions below:
include::../../common/fix/pre-approved-list.adoc[]
include::../../common/fix/dangerous-operators.adoc[]