HIGH session fixationaspnethmac signatures

Session Fixation in Aspnet with Hmac Signatures

Session Fixation in Aspnet with Hmac Signatures — how this specific combination creates or exposes the vulnerability

Session fixation in ASP.NET occurs when an attacker forces a user to use a known session identifier. When HMAC signatures are used to protect request integrity—commonly for API tokens, anti-forgery tokens, or custom authentication headers—an attacker who knows or predicts the signature material may exploit weak session binding to perform actions on behalf of the authenticated user.

Consider an ASP.NET application that uses HMAC signatures to validate requests. A typical vulnerable pattern is generating the HMAC key once per session and storing it in a cookie or claim without rotating it on authentication. If the session identifier is predictable or reused across authentication boundaries, an attacker who sets the session ID before login can later use the known HMAC key to forge authenticated requests. For example, an attacker might send a link that sets Session["HmacKey"] to a value they control, then trick the victim into authenticating. After login, the server uses the same HMAC key to validate signed requests, allowing the attacker to replay signed API calls.

In the context of the 12 security checks run by middleBrick, this pattern may surface as findings in Authentication, BOLA/IDOR, and Unsafe Consumption checks. The scanner inspects unauthenticated endpoints and OpenAPI/Swagger specs (2.0, 3.0, 3.1 with full $ref resolution) to detect weak binding between session identifiers and cryptographic material. Real-world attack patterns such as session fixation and insecure signature usage are cross-referenced against findings to highlight risks where HMAC-protected endpoints do not re-derive or re-bind signatures after authentication.

To illustrate, a vulnerable ASP.NET controller might look like this, where the HMAC key is set once and never re-bound after login:

// Vulnerable: HMAC key set once and reused across authentication
[ApiController]
[Route("api/[controller]")]
public class PaymentController : ControllerBase
{
    private const string Secret = "insecure-default-key";

    [HttpPost("charge")]
    public IActionResult Charge([FromBody] ChargeRequest request)
    {
        if (!ValidateHmac(request, Request.Headers["X-Hmac"]))
            return Unauthorized();
        // process payment
        return Ok();
    }

    private bool ValidateHmac(ChargeRequest request, StringValues header)
    {
        var computed = ComputeHmac(request, Secret);
        return computed == header;
    }

    private string ComputeHmac(ChargeRequest request, string key)
    {
        var json = JsonSerializer.Serialize(request);
        using var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(key));
        var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(json));
        return Convert.ToBase64String(hash);
    }
}

In this scenario, if the HMAC key is exposed via session or predictable, an attacker can fixate the session and forge valid HMAC-signed requests. middleBrick detects such patterns by analyzing endpoint definitions and runtime behavior for weak session-key binding, helping identify where HMAC usage does not adequately isolate authenticated sessions.

Hmac Signatures-Specific Remediation in Aspnet — concrete code fixes

Remediation focuses on ensuring HMAC signatures are tightly bound to authenticated sessions and are never reused or predictable. Always derive HMAC material after successful authentication and bind it to the user or session context. Avoid storing static secrets in code or cookies, and rotate keys on authentication events.

Below is a secure ASP.NET pattern that re-derives the HMAC key after login and binds it to the user identity, preventing fixation across authentication boundaries:

// Secure: Derive HMAC key post-authentication and bind to user claims
[ApiController]
[Route("api/[controller]")]
public class PaymentController : ControllerBase
{
    [HttpPost("login")]
    public IActionResult Login([FromBody] LoginModel model)
    {
        if (!ValidateCredentials(model.Username, model.Password))
            return Unauthorized();

        var userIdentity = new ClaimsIdentity(new[]
        {
            new Claim(ClaimTypes.Name, model.Username)
        });

        // Derive a per-user HMAC key using a server-side secret + user-specific salt
        var userSalt = Convert.FromBase64String(GenerateUserSalt(model.Username));
        var key = new Rfc2898DeriveBytes(model.Password, userSalt, 10000, HashAlgorithmName.SHA256)
            .GetBytes(32);

        var principal = new ClaimsPrincipal(userIdentity);
        ((ClaimsIdentity)principal.Identity).AddClaim(new Claim("HmacKey", Convert.ToBase64String(key)));

        HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
        return Ok();
    }

    [HttpPost("charge")]
    public IActionResult Charge([FromBody] ChargeRequest request)
    {
        if (!User.HasClaim(c => c.Type == "HmacKey"))
            return Unauthorized();

        var key = Convert.FromBase64String(User.FindFirst("HmacKey")?.Value);
        if (!ValidateHmac(request, Request.Headers["X-Hmac"], key))
            return Unauthorized();

        // process payment
        return Ok();

    private bool ValidateHmac(ChargeRequest request, StringValues header, byte[] key)
    {
        var json = JsonSerializer.Serialize(request);
        using var hmac = new HMACSHA256(key);
        var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(json));
        var computed = Convert.ToBase64String(hash);
        return CryptographicOperations.FixedLengthEquals(Convert.FromBase64String(header), hash);
    }
}

This approach ensures the HMAC key is derived per-user and not stored in cookies or predictable locations. The key is bound to the authenticated identity and validated using constant-time comparison to prevent timing attacks. middleBrick’s Pro plan supports continuous monitoring and CI/CD integration to flag regressions where HMAC keys are not properly scoped to authenticated sessions.

Additional recommendations include rotating server-side secrets periodically, enforcing HTTPS to prevent key leakage, and validating that HMAC signatures are recomputed for each request rather than cached. The GitHub Action can enforce that no endpoint allows unsigned or weakly signed requests, and the MCP Server enables on-demand scans from IDEs to catch insecure HMAC usage during development.

Frequently Asked Questions

How does middleBrick detect session fixation risks involving HMAC signatures?
middleBrick scans unauthenticated attack surfaces and OpenAPI/Swagger specs (2.0, 3.0, 3.1) to identify weak binding between session identifiers and cryptographic keys, flagging patterns where HMAC material is static or predictable across authentication events.
Can middleBrick prevent session fixation attacks?
middleBrick detects and reports findings with remediation guidance; it does not prevent or block attacks. Developers should re-derive HMAC keys post-authentication and bind them to user identity to mitigate session fixation.