Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Return unwrapped keys if able #2812

Merged
merged 3 commits into from
Sep 9, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -1422,7 +1422,7 @@ internal IEnumerable<SecurityKey> GetContentEncryptionKeys(JsonWebToken jwtToken
(keysAttempted ??= new StringBuilder()).AppendLine(key.ToString());
}

if (unwrappedKeys.Count > 0 && exceptionStrings is null)
if (unwrappedKeys.Count > 0 || exceptionStrings is null)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do we care about exceptionStrings if we have found any possible keys?

return unwrappedKeys;
else
throw LogHelper.LogExceptionMessage(new SecurityTokenKeyWrapException(LogHelper.FormatInvariant(TokenLogMessages.IDX10618, (object)keysAttempted ?? "", (object)exceptionStrings ?? "", jwtToken)));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ internal Result<string> DecryptToken(
(keysAttempted ??= new StringBuilder()).AppendLine(key.ToString());
}

if (unwrappedKeys.Count > 0 && exceptionStrings is null)
if (unwrappedKeys.Count > 0 || exceptionStrings is null)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do we care about exceptionStrings if we have some keys?

return (unwrappedKeys, null);
else
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ public static TheoryData<TokenDecryptingTheoryData> JsonWebTokenHandlerDecryptTo
var jsonWebTokenHandler = new JsonWebTokenHandler();
var ecdsaToken = new JsonWebToken(jsonWebTokenHandler.CreateToken(ecdsaTokenDescriptor));
#endif
var configurationThatThrows = CreateCustomConfigurationThatThrows();

return new TheoryData<TokenDecryptingTheoryData>
{
Expand Down Expand Up @@ -193,10 +194,42 @@ public static TheoryData<TokenDecryptingTheoryData> JsonWebTokenHandlerDecryptTo
ValidationFailureType.TokenDecryptionFailed,
typeof(SecurityTokenDecryptionFailedException),
null),
},
new TokenDecryptingTheoryData
keegan-caruso marked this conversation as resolved.
Show resolved Hide resolved
{
TestId = "OneKeyThrowsOnUnwrap_DecryptionSucceeds",
keegan-caruso marked this conversation as resolved.
Show resolved Hide resolved
SecurityTokenDescriptor = new SecurityTokenDescriptor
{
SigningCredentials = KeyingMaterial.JsonWebKeyRsa256SigningCredentials,
EncryptingCredentials = new EncryptingCredentials(KeyingMaterial.RsaSecurityKey_2048, SecurityAlgorithms.RsaPKCS1, SecurityAlgorithms.Aes128CbcHmacSha256),
Claims = Default.PayloadDictionary
},
ValidationParameters = new ValidationParameters(),
Configuration = configurationThatThrows,
Result = "eyJhbGciOiJSUzI1NiIsImtpZCI6Ikpzb25XZWJLZXlSc2FfMjA0OCIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJodHRwOi8vRGVmYXVsdC5BdWRpZW5jZS5jb20iLCJhenAiOiJodHRwOi8vRGVmYXVsdC5BenAuY29tIiwiZW1haWwiOiJCb2JAY29udG9zby5jb20iLCJleHAiOiIyNTM0MDIzMDA3OTkiLCJnaXZlbl9uYW1lIjoiQm9iIiwiaXNzIjoiaHR0cDovL0RlZmF1bHQuSXNzdWVyLmNvbSIsImlhdCI6IjE0ODk3NzU2MTciLCJqdGkiOiJKdGkiLCJuYmYiOiIxNDg5Nzc1NjE3In0.Et69LAC4sn6nNm_HNz_AnJ8siLT6LRTjDSb1aY8APcwJmPn-TxU-8GG5_bmNkoVukR7hkYG2JuWPxJKbjDd73BlmelaiyZBoPUyU0S-GX3XgyC2v_CkOq4yYbtD-kq5s7kNNj5QJjZDq0oJeqcUMrq4xRWATPtUMkIZ0GpEhO_C5MFxT8jAWe_a2gyUA4KoibalKtkYgFvgLcvyZJhUx7AERbli6b7OkUksFp9zIwmc_jZZCXJ_F_wASyj9KgHQKN9VHER3bB2zQeWHR0q32ODYC4ggsan-Nkm-jIsATi2tgkKzROzK55dy8ZdFArXUYJRpI_raYkTUHRK_wP3GqtQ",
}
};
}
}

private static CustomConfiguration CreateCustomConfigurationThatThrows()
{
var customCryptoProviderFactory = new DerivedCryptoProviderFactory
{
IsSupportedAlgImpl = (alg, key) => true,
CreateKeyWrapProviderForUnwrapImpl = (key, alg) => throw new InvalidOperationException("Test exception")
};

var sym512Hey = new SymmetricSecurityKey(KeyingMaterial.DefaultSymmetricKeyBytes_512) { KeyId = "CustomSymmetricSecurityKey_512" };
sym512Hey.CryptoProviderFactory = customCryptoProviderFactory;

var rsaKey = new RsaSecurityKey(KeyingMaterial.RsaParameters_2048) { KeyId = "CustomRsaSecurityKey_2048" };

var configurationWithCustomCryptoProviderFactory = new CustomConfiguration(rsaKey);
configurationWithCustomCryptoProviderFactory.TokenDecryptionKeys.Add(sym512Hey);

return configurationWithCustomCryptoProviderFactory;
}
}

public class TokenDecryptingTheoryData : TheoryDataBase
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -696,6 +696,8 @@ public static TheoryData<CreateTokenTheoryData> SecurityTokenDecryptionTheoryDat
configurationWithDecryptionKeys.TokenDecryptionKeys.Add(KeyingMaterial.DefaultSymmetricSecurityKey_256);
configurationWithDecryptionKeys.TokenDecryptionKeys.Add(KeyingMaterial.DefaultSymmetricSecurityKey_512);

var configurationThatThrows = CreateCustomConfigurationThatThrows();

tokenHandler.InboundClaimTypeMap.Clear();
return new TheoryData<CreateTokenTheoryData>
{
Expand All @@ -710,7 +712,6 @@ public static TheoryData<CreateTokenTheoryData> SecurityTokenDecryptionTheoryDat
EncryptingCredentials = KeyingMaterial.DefaultSymmetricEncryptingCreds_Aes128_Sha2,
Claims = Default.PayloadDictionary
},
JsonWebTokenHandler = new JsonWebTokenHandler(),
keegan-caruso marked this conversation as resolved.
Show resolved Hide resolved
ValidationParameters = new TokenValidationParameters
{
IssuerSigningKey = KeyingMaterial.JsonWebKeyRsa256SigningCredentials.Key,
Expand All @@ -719,8 +720,6 @@ public static TheoryData<CreateTokenTheoryData> SecurityTokenDecryptionTheoryDat
},
Configuration = configurationWithDecryptionKeys,
ExpectedDecryptionKeys = new List<SecurityKey>(){ KeyingMaterial.DefaultSymmetricSecurityKey_256 },
Algorithm = JwtConstants.DirectKeyUseAlg,
EncryptingCredentials = KeyingMaterial.DefaultSymmetricEncryptingCreds_Aes128_Sha2_NoKeyId
},
new CreateTokenTheoryData
{
Expand All @@ -732,7 +731,6 @@ public static TheoryData<CreateTokenTheoryData> SecurityTokenDecryptionTheoryDat
EncryptingCredentials = KeyingMaterial.DefaultSymmetricEncryptingCreds_Aes128_Sha2,
Claims = Default.PayloadDictionary
},
JsonWebTokenHandler = new JsonWebTokenHandler(),
ValidationParameters = new TokenValidationParameters
{
IssuerSigningKey = KeyingMaterial.JsonWebKeyRsa256SigningCredentials.Key,
Expand All @@ -742,8 +740,6 @@ public static TheoryData<CreateTokenTheoryData> SecurityTokenDecryptionTheoryDat
},
Configuration = configurationWithDecryptionKeys,
ExpectedDecryptionKeys = new List<SecurityKey>(){ KeyingMaterial.DefaultSymmetricSecurityKey_256 },
Algorithm = JwtConstants.DirectKeyUseAlg,
EncryptingCredentials = KeyingMaterial.DefaultSymmetricEncryptingCreds_Aes128_Sha2_NoKeyId
},
new CreateTokenTheoryData
{
Expand All @@ -755,7 +751,6 @@ public static TheoryData<CreateTokenTheoryData> SecurityTokenDecryptionTheoryDat
EncryptingCredentials = KeyingMaterial.DefaultSymmetricEncryptingCreds_Aes128_Sha2,
Claims = Default.PayloadDictionary
},
JsonWebTokenHandler = new JsonWebTokenHandler(),
ValidationParameters = new TokenValidationParameters
{
IssuerSigningKey = KeyingMaterial.JsonWebKeyRsa256SigningCredentials.Key,
Expand All @@ -764,35 +759,71 @@ public static TheoryData<CreateTokenTheoryData> SecurityTokenDecryptionTheoryDat
ValidIssuer = Default.Issuer
},
ExpectedDecryptionKeys = new List<SecurityKey>(){ KeyingMaterial.DefaultSymmetricSecurityKey_256 },
Algorithm = JwtConstants.DirectKeyUseAlg,
EncryptingCredentials = KeyingMaterial.DefaultSymmetricEncryptingCreds_Aes128_Sha2_NoKeyId
},
new CreateTokenTheoryData
{
TestId = "AlgorithmMisMatch",
TestId = "AlgorithmMismatch",
Payload = Default.PayloadString,
ExpectedException = ExpectedException.KeyWrapException("IDX10618:"),
// There is no error, just no decryption keys are returned.
ExpectedException = ExpectedException.NoExceptionExpected,
ExpectedDecryptionKeys = new List<SecurityKey>(),
TokenDescriptor = new SecurityTokenDescriptor
{
SigningCredentials = KeyingMaterial.JsonWebKeyRsa256SigningCredentials,
EncryptingCredentials = new EncryptingCredentials(KeyingMaterial.DefaultX509Key_2048, SecurityAlgorithms.RsaPKCS1, SecurityAlgorithms.Aes128CbcHmacSha256),
Claims = Default.PayloadDictionary
},
JsonWebTokenHandler = new JsonWebTokenHandler(),
ValidationParameters = new TokenValidationParameters
{
IssuerSigningKey = KeyingMaterial.JsonWebKeyRsa256SigningCredentials.Key,
TokenDecryptionKeys = new List<SecurityKey>(){ KeyingMaterial.DefaultSymmetricSecurityKey_256 },
ValidAudience = Default.Audience,
ValidIssuer = Default.Issuer
},
Algorithm = SecurityAlgorithms.Aes256CbcHmacSha512,
EncryptingCredentials = KeyingMaterial.DefaultSymmetricEncryptingCreds_Aes128_Sha2_NoKeyId
},
new CreateTokenTheoryData
{
TestId = "EncryptionKeyInConfig_OneKeysThrows_SuccessfulKeyReturned",
Payload = Default.PayloadString,
TokenDescriptor = new SecurityTokenDescriptor
{
SigningCredentials = KeyingMaterial.JsonWebKeyRsa256SigningCredentials,
EncryptingCredentials = new EncryptingCredentials(KeyingMaterial.RsaSecurityKey_2048, SecurityAlgorithms.RsaPKCS1, SecurityAlgorithms.Aes128CbcHmacSha256),
Claims = Default.PayloadDictionary
},
ValidationParameters = new TokenValidationParameters
{
IssuerSigningKey = KeyingMaterial.JsonWebKeyRsa256SigningCredentials.Key,
ValidAudience = Default.Audience,
ValidIssuer = Default.Issuer
},
Configuration = configurationThatThrows,
ExpectedDecryptionKeys = new List<SecurityKey>(){ KeyingMaterial.DefaultSymmetricSecurityKey_256 },
}
};
}
}

private static OpenIdConnectConfiguration CreateCustomConfigurationThatThrows()
{
var customCryptoProviderFactory = new DerivedCryptoProviderFactory
{
IsSupportedAlgImpl = (alg, key) => key.KeySize == 512,
CreateKeyWrapProviderForUnwrapImpl = (key, alg) => throw new InvalidOperationException("Test exception")
};

var sym512Hey = new SymmetricSecurityKey(KeyingMaterial.DefaultSymmetricKeyBytes_512) { KeyId = "CustomSymmetricSecurityKey_512" };
sym512Hey.CryptoProviderFactory = customCryptoProviderFactory;

var rsaKey = new RsaSecurityKey(KeyingMaterial.RsaParameters_2048) { KeyId = "CustomRsaSecurityKey_2048" };

var configurationWithCustomCryptoProviderFactory = new OpenIdConnectConfiguration();
configurationWithCustomCryptoProviderFactory.TokenDecryptionKeys.Add(rsaKey);
configurationWithCustomCryptoProviderFactory.TokenDecryptionKeys.Add(sym512Hey);

return configurationWithCustomCryptoProviderFactory;
}

// Tests checks to make sure that the token string (JWE) created by calling
// CreateToken(string payload, SigningCredentials signingCredentials, EncryptingCredentials encryptingCredentials)
// is equivalent to the token string created by calling CreateToken(SecurityTokenDescriptor tokenDescriptor).
Expand Down Expand Up @@ -4486,4 +4517,26 @@ protected override ClaimsIdentity CreateClaimsIdentity(JsonWebToken jwtToken, To
return base.CreateClaimsIdentity(jwtToken, validationParameters, issuer);
}
}

class DerivedCryptoProviderFactory : CryptoProviderFactory
{
internal Func<string, SecurityKey, bool> IsSupportedAlgImpl { get; set; }
internal Func<SecurityKey, string, KeyWrapProvider> CreateKeyWrapProviderForUnwrapImpl { get; set; }

public override bool IsSupportedAlgorithm(string algorithm, SecurityKey key)
{
if (IsSupportedAlgImpl != null)
return IsSupportedAlgImpl(algorithm, key);

return base.IsSupportedAlgorithm(algorithm, key);
}

public override KeyWrapProvider CreateKeyWrapProviderForUnwrap(SecurityKey key, string algorithm)
{
if (CreateKeyWrapProviderForUnwrapImpl != null)
return CreateKeyWrapProviderForUnwrapImpl(key, algorithm);

return base.CreateKeyWrapProviderForUnwrap(key, algorithm);
}
}
}
Loading