Static analysis (SAST) check · C#

NoSQL injection from request input (C#)

A value read from the HTTP request is parsed as a MongoDB query document.

Why it matters

The caller can add operators such as $ne or $where and change what the query matches.

How to fix it

Build the filter with Builders<T>.Filter (Eq, In, ...) and pass the request value as the compared value, never as query text.

Example

The rule's own test fixtures, verbatim: the test suite requires the rule to report the first and not the second.

Vulnerable: reported (C#)
using MongoDB.Bson;
using MongoDB.Driver;
using Microsoft.AspNetCore.Mvc;

public class UsersController : Controller
{
    private readonly IMongoCollection<BsonDocument> _users;

    public IActionResult Find(string filter)
    {
        var doc = BsonDocument.Parse(filter);
        return Ok(_users.Find(doc).FirstOrDefault());
    }
}
Fixed: not reported (C#)
using MongoDB.Bson;
using MongoDB.Driver;
using Microsoft.AspNetCore.Mvc;

public class UsersController : Controller
{
    private readonly IMongoCollection<BsonDocument> _users;

    public IActionResult Find(string email)
    {
        var filter = Builders<BsonDocument>.Filter.Eq("email", email);
        return Ok(_users.Find(filter).FirstOrDefault());
    }
}

What TrustIvan reads

Runs on repository scans of C# source once static analysis is turned on (SAST_RULES and the separately built analyzer image); it is off by default.

Weakness classes and references

Terms: SAST (static application security testing), Taint analysis, CWE (Common Weakness Enumeration), OWASP Top 10

All static analysis (SAST) checks · The whole catalogue · How this works in TrustIvan · Documentation

See TrustIvan on your own estate.

Book thirty minutes with an engineer and bring an image, a repository or a cloud account, or start free on the hosted service.