rspec/rules/S5147/csharp/how-to-fix-it/mongodb-csharp-driver.adoc
github-actions[bot] 504835d1bf
Create rule S5147(C#): NoSQL operations should not be vulnerable to injection attacks APPSEC-2024 (#4165)
* Add csharp to rule S5147

* Add the text

* Fixed filename

* Apply suggestions from code review

Co-authored-by: Hendrik Buchwald <64110887+hendrik-buchwald-sonarsource@users.noreply.github.com>

* Apply suggestions from code review

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

* Update rules/S5147/common/fix/builder-pattern.adoc

Co-authored-by: Hendrik Buchwald <64110887+hendrik-buchwald-sonarsource@users.noreply.github.com>

---------

Co-authored-by: loris-s-sonarsource <loris-s-sonarsource@users.noreply.github.com>
Co-authored-by: Loris Sierra <loris.sierra@sonarsource.com>
Co-authored-by: Loris S. <91723853+loris-s-sonarsource@users.noreply.github.com>
Co-authored-by: Hendrik Buchwald <64110887+hendrik-buchwald-sonarsource@users.noreply.github.com>
2024-08-23 12:10:19 +00:00

78 lines
2.1 KiB
Plaintext

== 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[]