HIGH cross site request forgeryaspnetmutual tls

Cross Site Request Forgery in Aspnet with Mutual Tls

Cross Site Request Forgery in Aspnet with Mutual Tls

Cross-Site Request Forgery (CSRF) in ASP.NET with Mutual TLS (mTLS) involves a nuanced interaction between transport-layer client authentication and application-layer request validation. mTLS ensures that each client presents a valid client certificate during the TLS handshake, which the server can use to establish identity. In ASP.NET, this often appears as request mapping to a client certificate (e.g., via IClientCertificateMapping or custom middleware) that you might use to identify users or services. However, mTLS does not automatically protect against CSRF because CSRF is about forcing an authenticated user’s browser to make unintended requests to the application using their existing session context. Even with mTLS, if your endpoints rely solely on cookie-based authentication for session management, a malicious site can still trigger requests from the user’s browser that include valid authentication cookies.

Consider an ASP.NET Core application that uses mTLS to map client certificates to user identities but also supports cookie-based authentication for browser clients. An attacker can craft an HTML form on a different origin that targets a state-changing endpoint (e.g., a transfer or update). When the victim’s browser, already authenticated via cookies, submits the form, the request will carry both the cookie and the client certificate (if the server requires it for the TLS handshake). The server may validate the certificate and then process the request as legitimate, because the application logic does not enforce additional anti-forgery checks. This is a CSRF vector despite mTLS, because mTLS binds the connection to a client, but does not prevent the browser from including session cookies in outgoing requests to the same origin.

To detect this combination during scanning, middleBrick runs checks across its 12 security checks, including Authentication, Authorization (BOLA/IDOR), and Input Validation, while also analyzing OpenAPI/Swagger specs (2.0, 3.0, 3.1) with full $ref resolution and correlating findings with runtime behavior. For endpoints that use mTLS, ensure that anti-forgery tokens or explicit origin checks are in place, and verify that your authentication scheme does not rely solely on transport-layer identity. The presence of mTLS should be documented in your spec so scanners can cross-reference expected security boundaries with runtime tests.

Mutual Tls-Specific Remediation in Aspnet

Remediation in ASP.NET focuses on ensuring that mTLS is correctly integrated with application-level authorization and that CSRF protections remain effective. When using mTLS, you typically map the client certificate to a user or role and enforce policies based on that mapping. Always combine mTLS with anti-forgery tokens for browser-based interactions and enforce strict origin checks. Below are concrete code examples that show how to configure mTLS and protect endpoints in ASP.NET Core.

First, configure Kestrel to require client certificates and map them in Program.cs:

// Program.cs
var builder = WebApplication.CreateBuilder(args);

// Require client certificates for mTLS
builder.WebHost.ConfigureKestrel(serverOptions =>
{
    serverOptions.ListenAnyIP(5001, listenOptions =>
    {
        listenOptions.UseHttps(httpsOptions =>
        {
            httpsOptions.ClientCertificateMode = ClientCertificateMode.RequireCertificate;
            httpsOptions.AllowAnyClientCertificate(); // or use a custom validator
        });
    });
});

// Optionally map certificate to claims
builder.Services.AddAuthentication(CertificateAuthenticationDefaults.AuthenticationScheme)
    .AddCertificate(options =>
    {
        options.AllowedCertificateTypes = CertificateTypes.All;
        options.RevocationMode = X509RevocationMode.NoCheck;
        options.Events = new CertificateAuthenticationEvents
        {
            OnCertificateValidated = context =>
            {
                var claims = new[]
                {
                    new Claim(ClaimTypes.NameIdentifier, context.ClientCertificate.Thumbprint)
                };
                context.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, context.Scheme.Name));
                context.Success();
                return Task.CompletedTask;
            }
        };
    });

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

Second, enforce anti-forgery tokens for endpoints that serve browser clients, even when mTLS is used. In controllers or minimal APIs, validate the token explicitly:

// Minimal API with anti-forgery validation
app.MapPost("/transfer", async (HttpRequest request, IAntiforgery antiforgery) =>
{
    var httpContext = request.HttpContext;
    antiforgery.ValidateRequest(httpContext);
    // Handle transfer logic
    return Results.Ok();
}).RequireAuthorization();

// In Startup or Program, add antiforgery services if not already present
builder.Services.AddAntiforgery(options =>
{
    options.HeaderName = "X-XSRF-TOKEN";
});

Third, ensure that your OpenAPI/Swagger definitions reflect the mTLS requirement and that security schemes are correctly referenced. This helps scanners like middleBrick correlate spec-defined protections with runtime behavior:

# openapi.yaml snippets
securitySchemes:
  mTLS:
    type: mutual_tls
    description: mTLS client certificate authentication
    x-stability: stable
paths:
  /transfer:
    post:
      security:
        - mTLS: []
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                amount:
                  type: integer
                toAccount:
                  type: string

By combining mTLS with explicit anti-forgery measures and accurate spec documentation, you reduce the risk of CSRF in scenarios where transport identity alone is insufficient.

Frequently Asked Questions

Does mTLS prevent CSRF in ASP.NET?
No. mTLS authenticates the client at the transport layer but does not stop a browser from sending valid session cookies with forged requests. You still need anti-forgery tokens or explicit origin checks.
How does middleBrick handle CSRF and mTLS during scans?
middleBrick runs parallel security checks including Authentication and Authorization, and it analyzes OpenAPI/Swagger specs with full $ref resolution to cross-reference mTLS requirements and CSRF protections, providing findings and remediation guidance.