HIGH server side template injectionaspnetmutual tls

Server Side Template Injection in Aspnet with Mutual Tls

Server Side Template Injection in Aspnet with Mutual Tls

Server Side Template Injection (SSTI) in an ASP.NET application protected by Mutual TLS (mTLS) can occur when user-controlled input reaches the server-side template engine despite the presence of strong transport-layer authentication. mTLS ensures the client is who they claim to be, but it does not validate or sanitize data once the request is accepted. If an endpoint binds JSON or form values directly to a template — for example using Razor syntax or a third-party templating library — attacker-controlled data can lead to arbitrary code execution or information disclosure.

Consider an ASP.NET Core endpoint that builds a status message for display using a Razor-like inline template:

@{
    var name = Request.Query["name"];
    var greeting = $"Hello, {name}!";
}
@greeting

If name is not validated, an attacker can supply {{7*7}} (for a compatible templating engine) or other injection patterns. With mTLS in place, the request includes a valid client certificate, so the connection is accepted and processed, potentially bypassing IP-based or perimeter defenses that assume untrusted networks. The presence of a client certificate may also mislead developers into assuming end-to-end trust, causing them to skip input validation and output encoding.

An attacker with a valid certificate can probe for template injection to achieve:

  • Arbitrary code execution via server-side expressions
  • Local file inclusion through template context pollution
  • Information leakage by reading configuration or environment variables exposed in the template scope

Because mTLS operates at the transport layer, it does not mitigate logic flaws in application code. The server must treat all data from authenticated clients as untrusted and apply context-aware encoding and strict input validation. The combination of mTLS and SSTI is particularly dangerous because the trusted channel may encourage less scrutiny of payloads, increasing the likelihood of a successful exploit.

middleBrick detects this risk by correlating OpenAPI/Swagger spec definitions with runtime behavior. When a spec defines security schemes such as mutual TLS and endpoints accept user input into template-like fields or parameters, scans flag missing validation and provide prioritized findings with severity and remediation guidance. This helps teams understand how authenticated channels can still be abused when data is not handled safely.

Mutual Tls-Specific Remediation in Aspnet

Remediation focuses on never trusting data from authenticated clients and applying defense-in-depth. Even with mTLS, validate and sanitize all inputs, use strongly typed models, and avoid dynamic template evaluation. Prefer built-in HTML encoding and avoid constructing output with raw strings that include unchecked placeholders.

Example of unsafe code that concatenates user input into a response without validation:

// UNSAFE: directly embedding query parameter into output
app.MapGet("/hello", (HttpRequest request) =>
{
    var name = request.Query["name"];
    return $"Hello, {name}!";
});

Secure alternative using model binding and HTML encoding:

// SAFE: use model binding and encoded output
public class GreetingRequest
{
    public string Name { get; set; } = string.Empty;
}

app.MapPost("/hello", (GreetingRequest req) =>
{
    // Encode output to prevent injection in HTML context
    var safeName = System.Net.WebUtility.HtmlEncode(req.Name);
    return $"Hello, {safeName}!";
});

For mTLS-enabled endpoints, keep the certificate validation strict and do not relax input rules because a certificate is present. Here is how to enforce client certificates in ASP.NET Core:

// Enforce client certificate in Program.cs
builder.WebHost.ConfigureKestrel(serverOptions =>
{
    serverOptions.ConfigureHttpsDefaults(httpsOptions =>
    {
        httpsOptions.ClientCertificateMode = ClientCertificateMode.RequireCertificate;
        httpsOptions.ClientCertificateValidation = (cert, chain, errors) =>
        {
            // Add custom validation as needed (e.g., thumbprint or issuer checks)
            return errors == SslPolicyErrors.None;
        };
    });
});

var app = builder.Build();
app.UseHttpsRedirection();
app.MapGet("/", () => "OK");
app.Run();

Additional measures include using allowlists for known values, applying the principle of least privilege to application identities, and monitoring for anomalous requests even when mTLS is enforced. middleBrick’s scans can surface missing validation in authenticated flows and map findings to frameworks such as OWASP API Top 10 to guide remediation.

For continuous assurance, the middleBrick Pro plan provides ongoing monitoring and can integrate as a GitHub Action to fail builds when security scores drop below a defined threshold. The CLI allows quick local checks with middlebrick scan <url>, and the MCP server enables scanning directly from AI coding assistants within your IDE.

Frequently Asked Questions

Does mutual TLS prevent server side template injection?
No. Mutual TLS authenticates the client but does not validate or sanitize data. Server side template injection must be addressed through input validation, output encoding, and strict model binding regardless of transport security.
How can I test my ASP.NET endpoints for SSTI when mTLS is enforced?
Use a client certificate that matches the server’s CA and send payloads designed to trigger template evaluation in authenticated requests. middleBrick scans support authenticated contexts and can test unauthenticated attack surfaces; for deeper validation, combine automated scans with manual testing under mTLS.