HIGH cors wildcardaspnethmac signatures

Cors Wildcard in Aspnet with Hmac Signatures

Cors Wildcard in Aspnet with Hmac Signatures — how this specific combination creates or exposes the vulnerability

In ASP.NET, enabling CORS with a wildcard origin (AllowAnyOrigin) while also using HMAC-based request signatures can unintentionally weaken integrity guarantees and expose sensitive endpoints to cross-origin abuse. A wildcard CORS policy permits any web origin to make requests to your API, and when those requests include HMAC signatures, the signature is only as trustworthy as the origin that generated it.

HMAC signatures are typically computed with a shared secret known to the client and the server. The server validates the signature to ensure the request has not been tampered with and originates from an authorized client. However, CORS is a browser-enforced mechanism; it does not affect non-browser clients. If a wildcard origin is allowed, any webpage served from any domain can instruct a browser to call your API with valid credentials (such as cookies or tokens) and include an HMAC signature that the server will accept.

This combination creates a cross-origin attack surface where an attacker can leverage the browser’s ability to make cross-origin requests with credentials. Even though HMAC protects request integrity, the server may treat the request as legitimate because the signature matches. The vulnerability is not in HMAC itself but in the permissive CORS configuration that allows any origin to invoke signed endpoints. Attack patterns such as CSRF or unauthorized data exfiltration become more plausible when a trusted signature path is combined with an untrusted origin policy.

Additionally, preflight requests triggered by browsers for certain CORS scenarios can cause the server to handle unsigned, exploratory requests, which may reveal whether specific endpoints respond differently based on headers. When HMAC is required, inconsistent enforcement across endpoints can lead to scenarios where some routes accept wildcard origins while others do not, increasing the risk of accidental exposure. OWASP API Security Top 10 categories such as Broken Object Level Authorization (BOLA) and Security Misconfiguration are relevant when access controls are not consistently aligned with origin policies.

Real-world implications include unauthorized actions performed on behalf of authenticated users and exposure of sensitive data. For example, a malicious site could embed an image tag or script that triggers a state-changing request signed by a compromised client. The server validates the HMAC and processes the request because it assumes the origin is implicitly trusted, even though CORS was too permissive. This highlights the need to tightly control which origins are allowed and to avoid AllowAnyOrigin when HMAC signatures are used for authorization-sensitive operations.

Tools like middleBrick can detect overly permissive CORS configurations and flag inconsistencies between spec-defined security schemes and runtime behavior. Its OpenAPI/Swagger spec analysis resolves $ref definitions and cross-references them with runtime findings, helping identify whether HMAC-secured routes incorrectly allow wildcard origins. By scanning unauthenticated attack surfaces, it surfaces misconfigurations without requiring credentials, providing prioritized findings and remediation guidance to tighten CORS and HMAC integration.

Hmac Signatures-Specific Remediation in Aspnet — concrete code fixes

To secure ASP.NET APIs that use HMAC signatures, align CORS policy with the principle of least privilege and enforce strict origin validation. Avoid services.AddCors(options => options.AddPolicy("AllowAll", builder => builder.AllowAnyOrigin())) when HMAC is required. Instead, specify exact origins and ensure that HMAC validation is applied consistently across all endpoints, including those exposed to browser-based clients.

Below are concrete code examples demonstrating secure configuration. The first example shows how to define a restricted CORS policy and apply it selectively, while the second illustrates HMAC signature generation and validation in middleware.

Secure CORS Policy with Explicit Origins

// Program.cs
builder.Services.AddCors(options =>
{
    options.AddPolicy("TrustedOrigins",
        policy =>
        {
            policy.WithOrigins(
                "https://app.yourdomain.com",
                "https://admin.yourdomain.com"
            );
            policy.AllowAnyHeader();
            policy.AllowAnyMethod();
            // Avoid AllowCredentials() unless necessary, and never combine with AllowAnyOrigin()
            policy.SetIsOriginAllowed(origin => new Uri(origin).Host == "api.yourdomain.com");
        });
});

app.UseCors("TrustedOrigins");

HMAC Signature Validation Middleware

// HmacValidationMiddleware.cs
public class HmacValidationMiddleware
{
    private readonly RequestDelegate _next;
    private readonly string _apiSecret;

    public HmacValidationMiddleware(RequestDelegate next, IConfiguration config)
    {
        _next = next;
        _apiSecret = config["Hmac:Secret"] ?? throw new ArgumentException("HMAC secret is missing");
    }

    public async Task InvokeAsync(HttpContext context)
    {
        if (context.Request.Headers.TryGetValue("X-API-Signature", out var signatureHeader))
        {
            var computedHash = ComputeHmac(context.Request);
            if (string.Equals(computedHash, signatureHeader, StringComparison.Ordinal))
            {
                await _next(context);
                return;
            }
        }

        context.Response.StatusCode = StatusCodes.Status401Unauthorized;
        await context.Response.WriteAsync("Invalid HMAC signature");
    }

    private string ComputeHmac(HttpRequest request)
    {
        using var sha256 = System.Security.Cryptography.SHA256.Create();
        var body = string.Empty;
        if (request.Body.CanSeek)
        {
            request.Body.Seek(0, SeekOrigin.Begin);
            using var reader = new StreamReader(request.Body);
            body = reader.ReadToEnd();
            request.Body.Seek(0, SeekOrigin.Begin);
        }

        var payload = $"{request.Method}:{request.Path}:{body}";
        var hash = sha256.ComputeHash(System.Text.Encoding.UTF8.GetBytes(payload + _apiSecret));
        return Convert.ToBase64String(hash);
    }
}

// Extension method for easy registration
public static class HmacValidationExtensions
{
    public static IApplicationBuilder UseHmacValidation(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<HmacValidationMiddleware>();
    }
}

Register the middleware early in the pipeline, before routing and authorization, to ensure every request is verified. Combine this with endpoint-specific CORS policies rather than a global wildcard. The middleBrick CLI can be used to validate that HMAC-required endpoints do not inadvertently allow unrestricted origins, and its GitHub Action can enforce these checks in CI/CD pipelines to prevent regressions.

For production use, rotate secrets periodically and consider adding nonce or timestamp headers to mitigate replay attacks. The MCP Server allows you to run these validations directly from development environments like Claude or Cursor, integrating security checks into the coding workflow without disrupting productivity.

Related CWEs: dataExposure

CWE IDNameSeverity
CWE-200Exposure of Sensitive Information HIGH
CWE-209Error Information Disclosure MEDIUM
CWE-213Exposure of Sensitive Information Due to Incompatible Policies HIGH
CWE-215Insertion of Sensitive Information Into Debugging Code MEDIUM
CWE-312Cleartext Storage of Sensitive Information HIGH
CWE-359Exposure of Private Personal Information (PII) HIGH
CWE-522Insufficiently Protected Credentials CRITICAL
CWE-532Insertion of Sensitive Information into Log File MEDIUM
CWE-538Insertion of Sensitive Information into Externally-Accessible File HIGH
CWE-540Inclusion of Sensitive Information in Source Code HIGH

Frequently Asked Questions

Can I use AllowAnyOrigin with HMAC if I also validate signatures?
No. AllowAnyOrigin permits any web origin to make requests, which can enable cross-origin abuse even when HMAC signatures are validated. Use explicit origins and avoid combining AllowAnyOrigin with credentials or HMAC-sensitive endpoints.
Does HMAC protect against all cross-origin attacks?
HMAC protects request integrity but does not prevent a browser from making cross-origin requests. CORS controls which origins are allowed to interact with your API. A permissive CORS policy can allow malicious sites to trigger signed requests, so CORS and HMAC must be aligned.