HIGH token leakageaspnetmutual tls

Token Leakage in Aspnet with Mutual Tls

Token Leakage in Aspnet with Mutual Tls — how this specific combination creates or exposes the vulnerability

Token leakage in ASP.NET applications using mutual TLS (mTLS) often occurs when authentication tokens are handled in application code rather than being protected by the transport layer. With mTLS, the server authenticates the client using a client certificate, but this does not automatically prevent the application from inadvertently exposing sensitive tokens in logs, error messages, or insecure serialization formats.

In an ASP.NET Core setup, mTLS is configured via Kestrel or IIS integration, where the server requests and validates client certificates. If the application then issues its own bearer token (e.g., a JWT) and embeds it in URLs, query strings, or custom headers, these tokens can be captured through insecure logging, client-side JavaScript, or misconfigured CORS. For example, logging the full Authorization header without redaction can expose the token alongside the mTLS client certificate metadata, enabling correlation attacks.

Consider a scenario where an ASP.NET Core API uses mTLS for client authentication and subsequently returns a session token in a JSON response body or a cookie without the Secure and HttpOnly flags. An attacker who can observe or intercept the response—perhaps through a compromised browser or a man-in-the-middle proxy on a non-mTLS endpoint—can harvest the token. Even with mTLS ensuring channel-level identity, token leakage at the application layer undermines the trust established by the certificate exchange.

Real-world cases include OWASP API Top 10:2023 broken object level authorization (BOLA) when leaked tokens allow horizontal privilege escalation, and data exposure findings when tokens appear in error traces. A scanned endpoint using OpenAPI 3.0 may reveal that an endpoint returns an access_token field in responses, which, when combined with weak logging practices, can lead to credential exfiltration. middleBrick scans can detect such exposure by correlating spec definitions with runtime responses, flagging endpoints that return tokens without encryption or strict scope controls.

Additionally, token leakage can manifest through SSRF or unsafe consumption patterns where the application forwards requests with inherited credentials. If an ASP.NET service uses mTLS for outbound calls and embeds its client certificate or token in outbound headers, a vulnerable SSRF chain can expose these artifacts to external endpoints. Proper input validation and output encoding remain essential even when mTLS is in place, as certificates do not sanitize data sent to downstream services.

Mutual Tls-Specific Remediation in Aspnet — concrete code fixes

To mitigate token leakage in ASP.NET with mutual TLS, focus on isolating token handling from transport-layer identity and enforcing strict output controls. Below are concrete code examples for configuring mTLS in ASP.NET Core and securing token usage.

1. Configure mTLS in Kestrel (Program.cs)

Ensure the server requests client certificates and validates them without relying on tokens for transport identity:

var builder = WebApplication.CreateBuilder(args);
builder.WebHost.ConfigureKestrel(serverOptions =>
{
    serverOptions.ListenAnyIP(5001, listenOptions =>
    {
        listenOptions.UseHttps(httpsOptions =>
        {
            httpsOptions.ClientCertificateMode = ClientCertificateMode.RequireCertificate;
            httpsOptions.AllowedCipherSuites = new[]
            {
                // Use strong cipher suites that align with your compliance requirements
                System.Security.Authentication.CipherSuiteType.Tls13Aes128GcmSha256,
                System.Security.Authentication.CipherSuiteType.Tls13Aes256GcmSha384
            };
            httpsOptions.Protocols = System.Security.Authentication.SslProtocols.Tls12 | System.Security.Authentication.SslProtocols.Tls13;
        });
    });
});

2. Validate client certificates explicitly

Add middleware to inspect the client certificate and map it to an identity without embedding tokens in responses:

app.Use(async (context, next) =>
{
    var cert = context.Connection.ClientCertificate;
    if (cert == null || !IsValidClientCertificate(cert)) // implement your validation logic
    {
        context.Response.StatusCode = 403;
        await context.Response.WriteAsync("Client certificate required.");
        return;
    }
    // Do not include certificate thumbprint or token in logs or responses
    await next.Invoke();
});

3. Secure token generation and response handling

If your application issues bearer tokens after mTLS authentication, ensure tokens are never reflected in URLs or unencrypted cookies:

var token = new JwtSecurityToken(
    issuer: "https://your-aspnet-api.example.com",
    audience: "https://client.example.com",
    claims: claimsIdentity.Claims,
    expires: DateTime.UtcNow.AddMinutes(30),
    signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256)
);
var tokenString = new JwtSecurityTokenHandler().WriteToken(token);

// Return token only in secure, HttpOnly cookie or Authorization header in request context
context.Response.Headers["Authorization"] = $"Bearer {tokenString}";
// Avoid logging tokenString; use redacted logging instead

4. Disable token leakage in logging and error pages

In appsettings.Production.json, suppress sensitive data in logs:

{ 
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    },
    "ExcludeFromLogging": ["Authorization", "Cookies"]
  }
}

Ensure error responses do not include stack traces or headers that echo tokens:

app.UseExceptionHandler(errorApp =>
{
    errorApp.Run(async context =>
    {
        context.Response.StatusCode = 500;
        await context.Response.WriteAsync("An error occurred.");
        // Avoid exposing tokens or certificate details in error payloads
    });
});

5. Enforce secure transport and cookie flags

When returning tokens in cookies (if required), use strict flags and avoid SameSite=None without Secure:

context.Response.Cookies.Append(
    "session",
    tokenString,
    new CookieOptions
    {
        HttpOnly = true,
        Secure = true,
        SameSite = SameSiteMode.Strict,
        Expires = DateTime.UtcNow.AddMinutes(30)
    });

Frequently Asked Questions

Does mutual TLS prevent token leakage by itself?
No. Mutual TLS authenticates the client at the transport layer but does not stop the application from leaking tokens in logs, responses, or cookies. Application-level handling must still enforce secure token practices.
Can middleBrick detect token leakage in endpoints using mutual TLS?
Yes. middleBrick scans endpoints and correlates OpenAPI spec definitions with runtime responses to identify tokens returned in insecure formats, regardless of mTLS being used.