Search code examples
c#oauth-2.0azure-active-directory.net-6.0asp.net-authorization

Critical vulnerability - Prevent azure ad authorization using algorithm none


We are using Azure Ad authorization in .NET 6.0. Got critical vulnerability where algorithm type cannot be null.

Here's the guide which explains why this is critical vulnerability(Shout out to the author for detailed explanation)

This is our implementation:

    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApi(configuration); 


    app.UseAuthentication();
    app.UseAuthorization();

All the references, we come across is asking to validate the signature. Now we don't use any secret key Or cert to validate the signature by generating a random HSA OR RSA keys. Kind of stuck with this vulnerability.


Solution

  • We have to manually check if the algorithm was none. Below is the implementation for which we got a pass from security team:

                var jwtData = new DataMap<string>();
            if (Request?.Headers != null)
            {
                _ = AuthenticationHeaderValue.TryParse(Request.Headers[HeaderNames.Authorization], out AuthenticationHeaderValue authValue);
                if (authValue?.Scheme == "Bearer")
                {
                    // Decode JWT and extract the claims.
                    string token = authValue.Parameter;
    
                    var jwtHandler = new JwtSecurityTokenHandler();
                    if (jwtHandler.CanReadToken(token))
                    {
                        JwtSecurityToken validJwt = GetValidJWT(jwtHandler, token);
                        var claims = validJwt.Claims;
                        foreach (var claim in claims)
                        {
                            jwtData[claim.Type] = claim.Value;
                        }
                        _jwtData = jwtData;
                    }
                    else
                    {
                        jwtData[authValue.Scheme] = token ?? "";
                    }
                }
            }
    
    
        protected JwtSecurityToken GetValidJWT(JwtSecurityTokenHandler jwtSecurityTokenHandler, string token)
        {
            JwtSecurityToken validJwt = jwtSecurityTokenHandler.ReadJwtToken(token);
            //Validate algorithm
            if (validJwt == null)
            {
                throw new ArgumentException("Invalid JWT");
            }
    
            if (!validJwt.Header.Alg.Equals("RS256"))
            {
                throw new ArgumentException("Algorithm must be RS256");
            }
            return validJwt;
    
        }