Server Side Template Injection in Aspnet with Mongodb
Server Side Template Injection in Aspnet with Mongodb — how this specific combination creates or exposes the vulnerability
Server Side Template Injection (SSTI) occurs when an attacker can inject template expressions that are evaluated on the server. In ASP.NET applications that render dynamic content using templates—such as Razor or string-formatting approaches—unsanitized user input can lead to unintended code execution or data exposure. When the rendered output is subsequently used to build queries for a database like MongoDB, the combination can amplify the impact.
Consider an endpoint that accepts a user-controlled filter value and uses it to construct a MongoDB query via a template. If the template embeds the input directly into a JSON-like structure without proper validation or encoding, an attacker might inject characters that alter the query structure. For example, input such as { "username": { "$ne": "" } } could change the intended filtering logic, leading to over-permissive data retrieval.
In ASP.NET, this often surfaces in scenarios where developers concatenate user input into JSON strings or BSON documents before passing them to the MongoDB driver. The MongoDB C# driver does not evaluate Razor-like expressions, but if the application builds a JSON string using interpolation and then deserializes it with BsonDocument.Parse, untrusted input can introduce operators like $gt, $regex, or $where that change query semantics.
An illustrative vulnerable pattern:
var filterJson = $"{{ \"name\": \"{userInput}\" }}";
var filterDoc = BsonDocument.Parse(filterJson);
var result = collection.Find(filterDoc).ToList();
If userInput contains { "$ne": "" }, the resulting document becomes { "name": "{ "$ne": "" }" } as a literal string, but if the parsing or concatenation is done differently—such as building a BsonDocument with nested elements—the attacker may supply { "$ne": { } } and affect matching behavior. This can expose more documents than intended, leading to Insecure Direct Object References (IDOR) or excessive data exposure.
The risk is compounded when the application exposes an API endpoint that returns sensitive fields or when the query result is further processed in templates that render HTML. Attackers may chain SSTI-like techniques with MongoDB operators to probe data structures, enumerate fields, or trigger error messages that reveal schema details, aiding further attacks.
middleBrick detects such patterns during unauthenticated scans by analyzing OpenAPI specifications and runtime behavior for indicators of unsafe input usage in MongoDB query construction. Findings include severity ratings and remediation guidance mapped to OWASP API Top 10 and related frameworks.
Mongodb-Specific Remediation in Aspnet — concrete code fixes
To mitigate SSTI risks when working with MongoDB in ASP.NET, focus on strict input validation, avoiding string-based query construction, and using the driver’s type-safe builders. Never directly interpolate user input into JSON or BSON documents.
Use FilterDefinition<T> with the strongly-typed Builders<T> API. This approach prevents injection because operators are expressed as type-safe constructs rather than raw strings.
Safe example using the MongoDB C# driver:
var filter = Builders<MyEntity>.Filter.Eq(x => x.Username, userInput);
var result = collection.Find(filter).ToList();
For dynamic queries where multiple criteria may be supplied, build the filter programmatically without string interpolation:
var filterDef = Builders<MyEntity>.Filter.Empty;
if (!string.IsNullOrEmpty(username))
{
filterDef &= Builders<MyEntity>.Filter.Eq(x => x.Username, username);
}
if (!string.IsNullOrEmpty(status))
{
filterDef &= Builders<MyEntity>.Filter.Eq(x => x.Status, status);
}
var result = collection.Find(filterDef).ToList();
If you must construct JSON from external input, validate and sanitize each component, and prefer BsonDocument creation via its methods instead of parsing raw strings:
var doc = new BsonDocument
{
{ "username", userInput.Trim() } // enforce constraints
};
var result = collection.Find(doc).ToList();
Additionally, enforce schema validation on the server side using JSON Schema or MongoDB Schema Validation rules to reject unexpected operators. Combine this with output encoding in any template rendering to prevent reflected attacks that could aid in data exfiltration.
middleBrick’s Pro plan supports continuous monitoring for such patterns, integrating with CI/CD pipelines via GitHub Actions to flag risky query construction before deployment. The MCP Server allows AI coding assistants to scan API definitions and highlight unsafe data flows in real time.