Nosql Injection in Aspnet with Mutual Tls
Nosql Injection in Aspnet with Mutual Tls
Nosql Injection in an ASP.NET context with Mutual TLS (mTLS) enabled involves two layers: the application’s handling of untrusted input to NoSQL queries, and the transport and identity guarantees provided by mTLS. While mTLS ensures that both client and server present valid certificates, it does not sanitize data or validate application logic. Attackers can still send malicious payloads over an authenticated TLS channel if the application directly interpolates user-controlled values into NoSQL queries, such as in string-based filters, JSON path expressions, or OData queries.
In ASP.NET applications that use a NoSQL store like Azure Cosmos DB, MongoDB, or DynamoDB, developers sometimes construct queries by concatenating strings or using dynamic LINQ-like expressions. For example, a search endpoint might accept a filter parameter and embed it directly in a JSON query without parameterization. With mTLS in place, an authenticated client can reliably reach the endpoint, increasing the risk that a compromised or malicious insider can deliver injection payloads. Common NoSQL injection patterns include operator injection (e.g., {"$ne": null}) and nested document traversal to bypass intended access boundaries.
Consider an endpoint that builds a Cosmos DB SQL query from a request parameter:
// UNSAFE: direct string concatenation in a NoSQL query
var query = $"SELECT * FROM c WHERE c.userId = '{userId}' AND c.status = '{status}'";
var iterator = client.CreateQuery(query).GetEnumerator();
If userId or status are drawn from the caller and not validated, an attacker can inject operators like {"$gt": ""} or comment-like syntax (depending on the backend) to change the query semantics. Even with mTLS ensuring the connection is encrypted and the client is authenticated, the application remains vulnerable because the server-side logic does not enforce strict input validation or use parameterized patterns.
mTLS also influences the threat model around credential exposure. Without mTLS, stolen or intercepted credentials might enable replay or impersonation. With mTLS, the attacker must possess a valid client certificate, which raises the bar. However, once an authorized client is compromised (for example, via a developer workstation or CI/CD pipeline leak), the attacker can leverage the authenticated mTLS session to probe the API for NoSQL injection flaws. Therefore, mTLS shifts part of the risk from transport hijacking to application-level injection, reinforcing the need for rigorous input validation and least-privilege data access patterns.
To detect such issues, middleBrick scans unauthenticated attack surfaces and, when provided with authenticated contexts (via supported mechanisms), can exercise endpoints that accept identity tokens over mTLS. It checks for improper handling of user-controlled data in query construction and flags dangerous concatenation patterns. Findings include severity-ranked guidance on encoding, allowlists, and query parameterization, helping teams address NoSQL injection without relying on transport protections alone.
Mutual Tls-Specific Remediation in Aspnet
Securing ASP.NET applications with Mutual TLS requires both correct transport configuration and safe handling of data before it reaches the database. Below are concrete steps and code examples to implement mTLS and mitigate NoSQL injection risks.
1. Configure mTLS in ASP.NET
In Program.cs, require client certificates and validate them:
var builder = WebApplication.CreateBuilder(args);
builder.WebHost.ConfigureKestrel(serverOptions =>
{
serverOptions.ConfigureHttpsDefaults(httpsOptions =>
{
httpsOptions.ClientCertificateMode = ClientCertificateMode.RequireCertificate;
httpsOptions.AllowedCipherSuites = new[] { "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384" };
httpsOptions.ClientCertificateValidation = (cert, chain, errors) =>
{
// Example: validate thumbprint or policy
if (errors != SslPolicyErrors.None) return false;
return cert.Thumbprint == "EXPECTED_THUMBPRINT";
};
});
});
var app = builder.Build();
app.UseHttpsRedirection();
app.Run();
This ensures only clients with a trusted certificate can establish a connection. Combine this with certificate revocation checks (CRL/OCSP) in production for stronger identity assurance.
2. Use Parameterized NoSQL Queries
Avoid string interpolation. Use SDK-native parameterization. For Cosmos DB with the SQL API:
// SAFE: parameterized query
var queryDefinition = new QueryDefinition(
"SELECT * FROM c WHERE c.userId = @userId AND c.status = @status")
.WithParameter("@userId", userId)
.WithParameter("@status", status);
var iterator = client.GetItemQueryIterator<dynamic>(queryDefinition);
For MongoDB, use the filter builder instead of concatenating JSON strings:
// SAFE: filter builder with typed parameters
var filter = Builders<BsonDocument>.Filter.And(
Builders<BsonDocument>.Filter.Eq("userId", userId),
Builders<BsonDocument>.Filter.Eq("status", status)
);
var results = collection.Find(filter).ToList();
These approaches ensure that user input is treated strictly as data, not executable query syntax.
3. Validate and Encode Input
Apply allowlist validation for known-safe values and encode outputs based on the target context. For JSON-based NoSQL fields, use standard JSON encoding and avoid eval-like parsing of untrusted strings.
// Example: basic allowlist validation
if (!Regex.IsMatch(userId, @"^[a-zA-Z0-9_-]{1,64}$"))
{
throw new ArgumentException("Invalid userId");
}
Combine these practices with mTLS to ensure that authenticated sessions remain secure and that NoSQL injection vectors are eliminated.