HIGH sql injectionaspnetmutual tls

Sql Injection in Aspnet with Mutual Tls

Sql Injection in Aspnet with Mutual Tls — how this specific combination creates or exposes the vulnerability

SQL injection in an ASP.NET application protected by mutual TLS (mTLS) remains a classic application-layer injection risk. mTLS ensures that both client and server present valid certificates during the TLS handshake, which strongly authenticates the client and protects transport confidentiality and integrity. However, mTLS does not change how the application handles untrusted input once the request reaches the server. If the application builds SQL commands by concatenating user-controlled data such as query parameters, headers, or certificate-derived claims, the attacker can still inject malicious SQL.

Consider an ASP.NET endpoint that uses the client certificate subject or serial number as a key to look up user data. Developers might assume mTLS makes the client trustworthy and therefore skip proper validation or parameterization. For example, extracting a value from the client certificate and embedding it into a SQL string is hazardous:

// UNSAFE: concatenating certificate claim into SQL
var subject = context.Connection.ClientCertificateSubject;
var sql = $"SELECT * FROM Users WHERE Subject = '{subject}'";
using var cmd = new SqlCommand(sql, connection);
using var reader = cmd.ExecuteReader();

An attacker who can influence or spoof a certificate attribute (or trick an admin into installing a malicious certificate) can manipulate the query. Even when mTLS is enforced, common SQL injection patterns remain relevant: error-based extraction, UNION attacks, and boolean-based blind injection. The OWASP API Top 10 and CWE-89 classify this as injection despite strong transport authentication because the flaw is in query construction, not in TLS.

In a black-box scan without authentication, middleBrick tests endpoints that accept parameters and headers, including those derived from mTLS client claims. It checks whether inputs are properly parameterized and whether strict allowlists are applied to certificate metadata used in queries. The presence of mTLS may reduce the attack surface by ensuring only authorized clients connect, but it does not eliminate the need for parameterized queries, least-privilege database permissions, and strict input validation.

Additionally, mTLS can complicate logging and monitoring: sensitive certificate fields might be inadvertently logged, increasing data exposure risk. The scanner evaluates Data Exposure and Encryption checks to ensure certificate material is not persisted or echoed in responses. Overall, SQL injection with mTLS is about trusting the wrong layer — transport identity does not imply data safety — and the remediation must focus on query design and runtime input handling rather than the handshake itself.

Mutual Tls-Specific Remediation in Aspnet — concrete code fixes

Remediation centers on never letting certificate-derived data directly touch SQL strings. Use parameterized queries or an ORM with strict parameterization, and treat certificate claims as untrusted input. Enforce allowlists for expected values and avoid dynamic SQL construction.

Example of safe code using parameterized queries with certificate subject validation in ASP.NET:

// SAFE: parameterization + allowlist validation
var subject = context.Connection.ClientCertificateSubject;
if (!IsValidSubject(subject))
{
    return Results.Forbid();
}

// Use parameterized query
var sql = "SELECT * FROM Users WHERE Subject = @subject";
using var cmd = new SqlCommand(sql, connection);
cmd.Parameters.AddWithValue("@subject", subject);
using var reader = cmd.ExecuteReader();

Implement IsValidSubject against an allowlist or a trusted mapping instead of a raw pattern match:

bool IsValidSubject(string subject)
{
    var allowedSubjects = new HashSet<string> {
        "CN=api-client-01,O=Example",
        "CN=api-client-02,O=Example"
    };
    return allowedSubjects.Contains(subject);
}

If you must extract data from certificates, map them to internal IDs via a trusted store rather than using raw certificate values in SQL:

// Map certificate thumbprint to user ID safely
var thumbprint = context.Connection.ClientCertificateThumbprint?.Replace(" ", "")?.ToLowerInvariant();
if (thumbprint == null || !CertificateMapping.TryMap(thumbprint, out var userId))
{
    return Results.Unauthorized();
}

var sql = "SELECT * FROM Users WHERE Id = @userId";
using var cmd = new SqlCommand(sql, connection);
cmd.Parameters.AddWithValue("@userId", userId);
using var reader = cmd.ExecuteReader();

In addition to code fixes, use middleware to enforce mTLS and reject requests with invalid or missing certificates before they reach application logic. The scanner’s Authentication and BOLA/IDOR checks validate that endpoints do not rely solely on mTLS for authorization and that access controls are applied per request.

For production, combine these practices with the middleBrick CLI to scan from terminal and integrate scans into scripts, or use the GitHub Action to add API security checks to your CI/CD pipeline and fail builds if risk scores drop below your threshold. The Pro plan supports continuous monitoring so that regressions are caught early. The MCP Server lets you scan APIs directly from your AI coding assistant while you develop, helping you keep parameterized queries and strict certificate handling consistent across the codebase.

Related CWEs: inputValidation

CWE IDNameSeverity
CWE-20Improper Input Validation HIGH
CWE-22Path Traversal HIGH
CWE-74Injection CRITICAL
CWE-77Command Injection CRITICAL
CWE-78OS Command Injection CRITICAL
CWE-79Cross-site Scripting (XSS) HIGH
CWE-89SQL Injection CRITICAL
CWE-90LDAP Injection HIGH
CWE-91XML Injection HIGH
CWE-94Code Injection CRITICAL

Frequently Asked Questions

Does mutual TLS prevent SQL injection in ASP.NET?
No. Mutual TLS authenticates the client at the transport layer but does not affect how the application constructs SQL queries. If the application concatenates certificate-derived data into SQL strings, injection is still possible. Use parameterized queries and strict allowlists regardless of mTLS.
What checks does middleBrick perform for SQL injection with mTLS?
middleBrick tests endpoints for injection using unauthenticated black-box probes and validates that inputs are parameterized. It also checks whether certificate metadata is used unsafely and whether findings map to frameworks like OWASP API Top 10 and PCI-DSS.