diff --git a/src/Microsoft.IdentityModel.Tokens.Saml/InternalAPI.Unshipped.txt b/src/Microsoft.IdentityModel.Tokens.Saml/InternalAPI.Unshipped.txt index ec74043d3d..748018b3ab 100644 --- a/src/Microsoft.IdentityModel.Tokens.Saml/InternalAPI.Unshipped.txt +++ b/src/Microsoft.IdentityModel.Tokens.Saml/InternalAPI.Unshipped.txt @@ -41,8 +41,10 @@ static Microsoft.IdentityModel.Tokens.Saml2.Saml2SecurityTokenHandler.StackFrame static Microsoft.IdentityModel.Tokens.Saml2.Saml2SecurityTokenHandler.StackFrames.IssuerValidationFailed -> System.Diagnostics.StackFrame static Microsoft.IdentityModel.Tokens.Saml2.Saml2SecurityTokenHandler.StackFrames.LifetimeValidationFailed -> System.Diagnostics.StackFrame static Microsoft.IdentityModel.Tokens.Saml2.Saml2SecurityTokenHandler.StackFrames.OneTimeUseValidationFailed -> System.Diagnostics.StackFrame +static Microsoft.IdentityModel.Tokens.Saml2.Saml2SecurityTokenHandler.StackFrames.SignatureValidationFailed -> System.Diagnostics.StackFrame static Microsoft.IdentityModel.Tokens.Saml2.Saml2SecurityTokenHandler.StackFrames.TokenNull -> System.Diagnostics.StackFrame static Microsoft.IdentityModel.Tokens.Saml2.Saml2SecurityTokenHandler.StackFrames.TokenValidationParametersNull -> System.Diagnostics.StackFrame +static Microsoft.IdentityModel.Tokens.Saml2.Saml2SecurityTokenHandler.ValidateSignature(Microsoft.IdentityModel.Tokens.Saml2.Saml2SecurityToken samlToken, Microsoft.IdentityModel.Tokens.ValidationParameters validationParameters, Microsoft.IdentityModel.Tokens.CallContext callContext) -> Microsoft.IdentityModel.Tokens.ValidationResult +virtual Microsoft.IdentityModel.Tokens.Saml2.Saml2SecurityTokenHandler.ReadSaml2Token(string token, Microsoft.IdentityModel.Tokens.CallContext callContext) -> Microsoft.IdentityModel.Tokens.ValidationResult virtual Microsoft.IdentityModel.Tokens.Saml.SamlSecurityTokenHandler.ReadSamlToken(string token, Microsoft.IdentityModel.Tokens.CallContext callContext) -> Microsoft.IdentityModel.Tokens.ValidationResult virtual Microsoft.IdentityModel.Tokens.Saml.SamlSecurityTokenHandler.ValidateConditions(Microsoft.IdentityModel.Tokens.Saml.SamlSecurityToken samlToken, Microsoft.IdentityModel.Tokens.ValidationParameters validationParameters, Microsoft.IdentityModel.Tokens.CallContext callContext) -> Microsoft.IdentityModel.Tokens.ValidationResult -virtual Microsoft.IdentityModel.Tokens.Saml2.Saml2SecurityTokenHandler.ReadSaml2Token(string token, Microsoft.IdentityModel.Tokens.CallContext callContext) -> Microsoft.IdentityModel.Tokens.ValidationResult diff --git a/src/Microsoft.IdentityModel.Tokens.Saml/Saml/SamlSecurityTokenHandler.ValidateSignature.cs b/src/Microsoft.IdentityModel.Tokens.Saml/Saml/SamlSecurityTokenHandler.ValidateSignature.cs index 99e50582c3..3691a62159 100644 --- a/src/Microsoft.IdentityModel.Tokens.Saml/Saml/SamlSecurityTokenHandler.ValidateSignature.cs +++ b/src/Microsoft.IdentityModel.Tokens.Saml/Saml/SamlSecurityTokenHandler.ValidateSignature.cs @@ -2,7 +2,6 @@ // Licensed under the MIT License. using System.Collections.Generic; -using System.Diagnostics; using System.Text; using Microsoft.IdentityModel.Xml; using TokenLogMessages = Microsoft.IdentityModel.Tokens.LogMessages; @@ -23,14 +22,14 @@ internal static ValidationResult ValidateSignature( { return ValidationError.NullParameter( nameof(samlToken), - new StackFrame(true)); + ValidationError.GetCurrentStackFrame()); } if (validationParameters is null) { return ValidationError.NullParameter( nameof(validationParameters), - new StackFrame(true)); + ValidationError.GetCurrentStackFrame()); } // Delegate is set by the user, we call it and return the result. @@ -43,11 +42,10 @@ internal static ValidationResult ValidateSignature( new MessageDetail( TokenLogMessages.IDX10504, samlToken.Assertion.CanonicalString), - ValidationFailureType.SignatureValidationFailed, + ValidationFailureType.TokenIsNotSigned, typeof(SecurityTokenValidationException), - new StackFrame(true)); + ValidationError.GetCurrentStackFrame()); - IList? keys = null; SecurityKey? resolvedKey = null; bool keyMatched = false; @@ -66,57 +64,39 @@ internal static ValidationResult ValidateSignature( resolvedKey = SamlTokenUtilities.ResolveTokenSigningKey(samlToken.Assertion.Signature.KeyInfo, validationParameters); } - if (resolvedKey is null) - { - if (validationParameters.TryAllIssuerSigningKeys) - keys = validationParameters.IssuerSigningKeys; - } - else + ValidationError? error = null; + + if (resolvedKey is not null) { - keys = [resolvedKey]; keyMatched = true; + var result = ValidateSignatureUsingKey(resolvedKey, samlToken, validationParameters, callContext); + if (result.IsValid) + return result; + + error = result.UnwrapError(); } bool canMatchKey = samlToken.Assertion.Signature.KeyInfo != null; - List errors = new(); - StringBuilder keysAttempted = new(); + List? errors = null; + StringBuilder? keysAttempted = null; - if (keys is not null) + if (!keyMatched && validationParameters.TryAllIssuerSigningKeys && validationParameters.IssuerSigningKeys is not null) { - for (int i = 0; i < keys.Count; i++) + // Control reaches here only if the key could not be resolved and TryAllIssuerSigningKeys is set to true. + // We try all the keys in the list and return the first valid key. This is the degenerate case. + for (int i = 0; i < validationParameters.IssuerSigningKeys.Count; i++) { - SecurityKey key = keys[i]; - ValidationResult algorithmValidationResult = validationParameters.AlgorithmValidator( - samlToken.Assertion.Signature.SignedInfo.SignatureMethod, - key, - samlToken, - validationParameters, - callContext); + SecurityKey key = validationParameters.IssuerSigningKeys[i]; + if (key is null) + continue; - if (!algorithmValidationResult.IsValid) - { - errors.Add(algorithmValidationResult.UnwrapError()); - } - else - { - var validationError = samlToken.Assertion.Signature.Verify( - key, - validationParameters.CryptoProviderFactory ?? key.CryptoProviderFactory, - callContext); + var result = ValidateSignatureUsingKey(key, samlToken, validationParameters, callContext); + if (result.IsValid) + return result; - if (validationError is null) - { - samlToken.SigningKey = key; + (errors ??= new()).Add(result.UnwrapError()); - return key; - } - else - { - errors.Add(validationError.AddStackFrame(new StackFrame())); - } - } - - keysAttempted.Append(key.ToString()); + (keysAttempted ??= new()).Append(key.ToString()); if (canMatchKey && !keyMatched && key.KeyId is not null && samlToken.Assertion.Signature.KeyInfo is not null) keyMatched = samlToken.Assertion.Signature.KeyInfo.MatchesKey(key); } @@ -126,38 +106,88 @@ internal static ValidationResult ValidateSignature( return new XmlValidationError( new MessageDetail( TokenLogMessages.IDX10514, - keysAttempted.ToString(), + keysAttempted?.ToString(), samlToken.Assertion.Signature.KeyInfo, - GetErrorStrings(errors), + GetErrorString(error, errors), samlToken), ValidationFailureType.SignatureValidationFailed, typeof(SecurityTokenInvalidSignatureException), - new StackFrame(true)); + ValidationError.GetCurrentStackFrame()); + + string? keysAttemptedString = null; + if (resolvedKey is not null) + keysAttemptedString = resolvedKey.ToString(); + else if ((keysAttempted?.Length ?? 0) > 0) + keysAttemptedString = keysAttempted!.ToString(); - if (keysAttempted.Length > 0) + if (keysAttemptedString is not null) return new XmlValidationError( new MessageDetail( TokenLogMessages.IDX10512, - keysAttempted.ToString(), - GetErrorStrings(errors), + keysAttemptedString, + GetErrorString(error, errors), samlToken), ValidationFailureType.SignatureValidationFailed, typeof(SecurityTokenSignatureKeyNotFoundException), - new StackFrame(true)); + ValidationError.GetCurrentStackFrame()); return new XmlValidationError( new MessageDetail(TokenLogMessages.IDX10500), ValidationFailureType.SignatureValidationFailed, typeof(SecurityTokenSignatureKeyNotFoundException), - new StackFrame(true)); + ValidationError.GetCurrentStackFrame()); } - private static string GetErrorStrings(List errors) + private static ValidationResult ValidateSignatureUsingKey(SecurityKey key, SamlSecurityToken samlToken, ValidationParameters validationParameters, CallContext callContext) { + ValidationResult algorithmValidationResult = validationParameters.AlgorithmValidator( + samlToken.Assertion.Signature.SignedInfo.SignatureMethod, + key, + samlToken, + validationParameters, + callContext); + + if (!algorithmValidationResult.IsValid) + { + return algorithmValidationResult.UnwrapError().AddCurrentStackFrame(); + } + else + { + var validationError = samlToken.Assertion.Signature.Verify( + key, + validationParameters.CryptoProviderFactory ?? key.CryptoProviderFactory, + callContext); + + if (validationError is null) + { + samlToken.SigningKey = key; + + return key; + } + else + { + return validationError.AddCurrentStackFrame(); + } + } + } + + private static string GetErrorString(ValidationError? error, List? errorList) + { + // This method is called if there are errors in the signature validation process. + // This check is there to account for the optional parameter. + if (error is not null) + return error.MessageDetail.Message; + + if (errorList is null) + return string.Empty; + + if (errorList.Count == 1) + return errorList[0].MessageDetail.Message; + StringBuilder sb = new(); - for (int i = 0; i < errors.Count; i++) + for (int i = 0; i < errorList.Count; i++) { - sb.AppendLine(errors[i].ToString()); + sb.AppendLine(errorList[i].MessageDetail.Message); } return sb.ToString(); diff --git a/src/Microsoft.IdentityModel.Tokens.Saml/Saml2/Saml2SecurityTokenHandler.ValidateSignature.cs b/src/Microsoft.IdentityModel.Tokens.Saml/Saml2/Saml2SecurityTokenHandler.ValidateSignature.cs new file mode 100644 index 0000000000..74d2884b26 --- /dev/null +++ b/src/Microsoft.IdentityModel.Tokens.Saml/Saml2/Saml2SecurityTokenHandler.ValidateSignature.cs @@ -0,0 +1,196 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System.Collections.Generic; +using System.Text; +using Microsoft.IdentityModel.Tokens.Saml; +using Microsoft.IdentityModel.Xml; +using TokenLogMessages = Microsoft.IdentityModel.Tokens.LogMessages; + +#nullable enable +namespace Microsoft.IdentityModel.Tokens.Saml2 +{ + public partial class Saml2SecurityTokenHandler : SecurityTokenHandler + { + internal static ValidationResult ValidateSignature( + Saml2SecurityToken samlToken, + ValidationParameters validationParameters, + CallContext callContext) + { + if (samlToken is null) + { + return ValidationError.NullParameter( + nameof(samlToken), + ValidationError.GetCurrentStackFrame()); + } + + if (validationParameters is null) + { + return ValidationError.NullParameter( + nameof(validationParameters), + ValidationError.GetCurrentStackFrame()); + } + + // Delegate is set by the user, we call it and return the result. + if (validationParameters.SignatureValidator is not null) + return validationParameters.SignatureValidator(samlToken, validationParameters, null, callContext); + + // If the user wants to accept unsigned tokens, they must set validationParameters.SignatureValidator + if (samlToken.Assertion.Signature is null) + return new XmlValidationError( + new MessageDetail( + TokenLogMessages.IDX10504, + samlToken.Assertion.CanonicalString), + ValidationFailureType.TokenIsNotSigned, + typeof(SecurityTokenValidationException), + ValidationError.GetCurrentStackFrame()); + + SecurityKey? resolvedKey = null; + bool keyMatched = false; + + if (validationParameters.IssuerSigningKeyResolver is not null) + { + resolvedKey = validationParameters.IssuerSigningKeyResolver( + samlToken.Assertion.CanonicalString, + samlToken, + samlToken.Assertion.Signature.KeyInfo?.Id, + validationParameters, + null, + callContext); + } + else + { + resolvedKey = SamlTokenUtilities.ResolveTokenSigningKey(samlToken.Assertion.Signature.KeyInfo, validationParameters); + } + + ValidationError? error = null; + + if (resolvedKey is not null) + { + keyMatched = true; + var result = ValidateSignatureUsingKey(resolvedKey, samlToken, validationParameters, callContext); + if (result.IsValid) + return result; + + error = result.UnwrapError(); + } + + bool canMatchKey = samlToken.Assertion.Signature.KeyInfo != null; + List? errors = null; + StringBuilder? keysAttempted = null; + + if (!keyMatched && validationParameters.TryAllIssuerSigningKeys && validationParameters.IssuerSigningKeys is not null) + { + // Control reaches here only if the key could not be resolved and TryAllIssuerSigningKeys is set to true. + // We try all the keys in the list and return the first valid key. This is the degenerate case. + for (int i = 0; i < validationParameters.IssuerSigningKeys.Count; i++) + { + SecurityKey key = validationParameters.IssuerSigningKeys[i]; + if (key is null) + continue; + + var result = ValidateSignatureUsingKey(key, samlToken, validationParameters, callContext); + if (result.IsValid) + return result; + + (errors ??= new()).Add(result.UnwrapError()); + + (keysAttempted ??= new()).Append(key.ToString()); + if (canMatchKey && !keyMatched && key.KeyId is not null && samlToken.Assertion.Signature.KeyInfo is not null) + keyMatched = samlToken.Assertion.Signature.KeyInfo.MatchesKey(key); + } + } + + if (canMatchKey && keyMatched) + return new XmlValidationError( + new MessageDetail( + TokenLogMessages.IDX10514, + keysAttempted?.ToString(), + samlToken.Assertion.Signature.KeyInfo, + GetErrorStrings(error, errors), + samlToken), + ValidationFailureType.SignatureValidationFailed, + typeof(SecurityTokenInvalidSignatureException), + ValidationError.GetCurrentStackFrame()); + + string? keysAttemptedString = null; + if (resolvedKey is not null) + keysAttemptedString = resolvedKey.ToString(); + else if ((keysAttempted?.Length ?? 0) > 0) + keysAttemptedString = keysAttempted!.ToString(); + + if (keysAttemptedString is not null) + return new XmlValidationError( + new MessageDetail( + TokenLogMessages.IDX10512, + keysAttemptedString, + GetErrorStrings(error, errors), + samlToken), + ValidationFailureType.SignatureValidationFailed, + typeof(SecurityTokenSignatureKeyNotFoundException), + ValidationError.GetCurrentStackFrame()); + + return new XmlValidationError( + new MessageDetail(TokenLogMessages.IDX10500), + ValidationFailureType.SignatureValidationFailed, + typeof(SecurityTokenSignatureKeyNotFoundException), + ValidationError.GetCurrentStackFrame()); + } + + private static ValidationResult ValidateSignatureUsingKey(SecurityKey key, Saml2SecurityToken samlToken, ValidationParameters validationParameters, CallContext callContext) + { + ValidationResult algorithmValidationResult = validationParameters.AlgorithmValidator( + samlToken.Assertion.Signature.SignedInfo.SignatureMethod, + key, + samlToken, + validationParameters, + callContext); + + if (!algorithmValidationResult.IsValid) + { + return algorithmValidationResult.UnwrapError().AddCurrentStackFrame(); + } + else + { + var validationError = samlToken.Assertion.Signature.Verify( + key, + validationParameters.CryptoProviderFactory ?? key.CryptoProviderFactory, + callContext); + + if (validationError is null) + { + samlToken.SigningKey = key; + + return key; + } + else + { + return validationError.AddCurrentStackFrame(); + } + } + } + + private static string GetErrorStrings(ValidationError? error, List? errors) + { + // This method is called if there are errors in the signature validation process. + // This check is there to account for the optional parameter. + if (error is not null) + return error.MessageDetail.Message; + + if (errors is null) + return string.Empty; + + if (errors.Count == 1) + return errors[0].MessageDetail.Message; + + StringBuilder sb = new(); + for (int i = 0; i < errors.Count; i++) + { + sb.AppendLine(errors[i].MessageDetail.Message); + } + + return sb.ToString(); + } + } +} +#nullable restore diff --git a/src/Microsoft.IdentityModel.Tokens.Saml/Saml2/Saml2SecurityTokenHandler.ValidateToken.Internal.cs b/src/Microsoft.IdentityModel.Tokens.Saml/Saml2/Saml2SecurityTokenHandler.ValidateToken.Internal.cs index 5291cde721..d806f6a453 100644 --- a/src/Microsoft.IdentityModel.Tokens.Saml/Saml2/Saml2SecurityTokenHandler.ValidateToken.Internal.cs +++ b/src/Microsoft.IdentityModel.Tokens.Saml/Saml2/Saml2SecurityTokenHandler.ValidateToken.Internal.cs @@ -82,6 +82,13 @@ internal async Task> ValidateTokenAsync( return validatedIssuerResult.UnwrapError().AddStackFrame(StackFrames.IssuerValidationFailed); } + var signatureValidationResult = ValidateSignature(samlToken, validationParameters, callContext); + if (!signatureValidationResult.IsValid) + { + StackFrames.SignatureValidationFailed ??= new StackFrame(true); + return signatureValidationResult.UnwrapError().AddStackFrame(StackFrames.SignatureValidationFailed); + } + return new ValidatedToken(samlToken, this, validationParameters); } diff --git a/src/Microsoft.IdentityModel.Tokens.Saml/Saml2/Saml2SecurityTokenHandler.ValidateToken.StackFrames.cs b/src/Microsoft.IdentityModel.Tokens.Saml/Saml2/Saml2SecurityTokenHandler.ValidateToken.StackFrames.cs index dcd253940a..5638bf2f11 100644 --- a/src/Microsoft.IdentityModel.Tokens.Saml/Saml2/Saml2SecurityTokenHandler.ValidateToken.StackFrames.cs +++ b/src/Microsoft.IdentityModel.Tokens.Saml/Saml2/Saml2SecurityTokenHandler.ValidateToken.StackFrames.cs @@ -14,12 +14,13 @@ internal static class StackFrames // Stack frames from ValidateTokenAsync using SecurityToken internal static StackFrame? TokenNull; internal static StackFrame? TokenValidationParametersNull; + internal static StackFrame? IssuerValidationFailed; + internal static StackFrame? SignatureValidationFailed; // Stack frames from ValidateConditions internal static StackFrame? AudienceValidationFailed; internal static StackFrame? AssertionNull; internal static StackFrame? AssertionConditionsNull; - internal static StackFrame? IssuerValidationFailed; internal static StackFrame? AssertionConditionsValidationFailed; internal static StackFrame? LifetimeValidationFailed; internal static StackFrame? OneTimeUseValidationFailed; diff --git a/src/Microsoft.IdentityModel.Tokens/InternalAPI.Unshipped.txt b/src/Microsoft.IdentityModel.Tokens/InternalAPI.Unshipped.txt index 2ec92b086f..e7eaf3cd7f 100644 --- a/src/Microsoft.IdentityModel.Tokens/InternalAPI.Unshipped.txt +++ b/src/Microsoft.IdentityModel.Tokens/InternalAPI.Unshipped.txt @@ -35,4 +35,5 @@ static readonly Microsoft.IdentityModel.Tokens.ValidationFailureType.NoTokenAudi static readonly Microsoft.IdentityModel.Tokens.ValidationFailureType.NoValidationParameterAudiencesProvided -> Microsoft.IdentityModel.Tokens.ValidationFailureType static readonly Microsoft.IdentityModel.Tokens.ValidationFailureType.SignatureAlgorithmValidationFailed -> Microsoft.IdentityModel.Tokens.ValidationFailureType static readonly Microsoft.IdentityModel.Tokens.ValidationFailureType.TokenExceedsMaximumSize -> Microsoft.IdentityModel.Tokens.ValidationFailureType +static readonly Microsoft.IdentityModel.Tokens.ValidationFailureType.TokenIsNotSigned -> Microsoft.IdentityModel.Tokens.ValidationFailureType static readonly Microsoft.IdentityModel.Tokens.ValidationFailureType.XmlValidationFailed -> Microsoft.IdentityModel.Tokens.ValidationFailureType diff --git a/src/Microsoft.IdentityModel.Tokens/Validation/ValidationFailureType.cs b/src/Microsoft.IdentityModel.Tokens/Validation/ValidationFailureType.cs index 00aba62c6e..cd58d536c7 100644 --- a/src/Microsoft.IdentityModel.Tokens/Validation/ValidationFailureType.cs +++ b/src/Microsoft.IdentityModel.Tokens/Validation/ValidationFailureType.cs @@ -69,6 +69,12 @@ private class TokenTypeValidationFailure : ValidationFailureType { internal Toke public static readonly ValidationFailureType SignatureValidationFailed = new SignatureValidationFailure("SignatureValidationFailed"); private class SignatureValidationFailure : ValidationFailureType { internal SignatureValidationFailure(string name) : base(name) { } } + /// + /// Defines a type that represents that the token is not signed. + /// + public static readonly ValidationFailureType TokenIsNotSigned = new TokenNotSignedFailure("TokenIsNotSigned"); + private class TokenNotSignedFailure : ValidationFailureType { internal TokenNotSignedFailure(string name) : base(name) { } } + /// /// Defines a type that represents that the token's signature algorithm validation failed. /// diff --git a/src/Microsoft.IdentityModel.Xml/Signature.cs b/src/Microsoft.IdentityModel.Xml/Signature.cs index 8c36911800..b7bf6219fa 100644 --- a/src/Microsoft.IdentityModel.Xml/Signature.cs +++ b/src/Microsoft.IdentityModel.Xml/Signature.cs @@ -2,7 +2,6 @@ // Licensed under the MIT License. using System; -using System.Diagnostics; using System.IO; using Microsoft.IdentityModel.Tokens; using static Microsoft.IdentityModel.Logging.LogHelper; @@ -135,24 +134,24 @@ public void Verify(SecurityKey key, CryptoProviderFactory cryptoProviderFactory) #pragma warning restore CA1801 { if (key is null) - return ValidationError.NullParameter(nameof(key), new StackFrame()); + return ValidationError.NullParameter(nameof(key), ValidationError.GetCurrentStackFrame()); if (cryptoProviderFactory is null) - return ValidationError.NullParameter(nameof(cryptoProviderFactory), new StackFrame()); + return ValidationError.NullParameter(nameof(cryptoProviderFactory), ValidationError.GetCurrentStackFrame()); if (SignedInfo is null) return new XmlValidationError( new MessageDetail(LogMessages.IDX30212), ValidationFailureType.XmlValidationFailed, typeof(XmlValidationException), - new StackFrame()); + ValidationError.GetCurrentStackFrame()); if (!cryptoProviderFactory.IsSupportedAlgorithm(SignedInfo.SignatureMethod, key)) return new XmlValidationError( new MessageDetail(LogMessages.IDX30207, SignedInfo.SignatureMethod, cryptoProviderFactory.GetType()), ValidationFailureType.XmlValidationFailed, typeof(XmlValidationException), - new StackFrame()); + ValidationError.GetCurrentStackFrame()); var signatureProvider = cryptoProviderFactory.CreateForVerifying(key, SignedInfo.SignatureMethod); if (signatureProvider is null) @@ -160,7 +159,7 @@ public void Verify(SecurityKey key, CryptoProviderFactory cryptoProviderFactory) new MessageDetail(LogMessages.IDX30203, cryptoProviderFactory, key, SignedInfo.SignatureMethod), ValidationFailureType.XmlValidationFailed, typeof(XmlValidationException), - new StackFrame()); + ValidationError.GetCurrentStackFrame()); ValidationError? validationError = null; @@ -175,14 +174,14 @@ public void Verify(SecurityKey key, CryptoProviderFactory cryptoProviderFactory) new MessageDetail(LogMessages.IDX30200, cryptoProviderFactory, key), ValidationFailureType.XmlValidationFailed, typeof(XmlValidationException), - new StackFrame()); + ValidationError.GetCurrentStackFrame()); } } if (validationError is null) { validationError = SignedInfo.Verify(cryptoProviderFactory, callContext); - validationError?.AddStackFrame(new StackFrame()); + validationError?.AddCurrentStackFrame(); } } finally diff --git a/src/Microsoft.IdentityModel.Xml/SignedInfo.cs b/src/Microsoft.IdentityModel.Xml/SignedInfo.cs index 7f18cdad4b..9f16187e56 100644 --- a/src/Microsoft.IdentityModel.Xml/SignedInfo.cs +++ b/src/Microsoft.IdentityModel.Xml/SignedInfo.cs @@ -125,7 +125,7 @@ public void Verify(CryptoProviderFactory cryptoProviderFactory) #pragma warning restore CA1801 { if (cryptoProviderFactory == null) - return ValidationError.NullParameter(nameof(cryptoProviderFactory), new System.Diagnostics.StackFrame()); + return ValidationError.NullParameter(nameof(cryptoProviderFactory), ValidationError.GetCurrentStackFrame()); ValidationError? validationError = null; @@ -136,7 +136,7 @@ public void Verify(CryptoProviderFactory cryptoProviderFactory) if (validationError is not null) { - validationError.AddStackFrame(new System.Diagnostics.StackFrame()); + validationError.AddCurrentStackFrame(); break; } } diff --git a/test/Microsoft.IdentityModel.Tokens.Saml.Tests/Saml2SecurityTokenHandlerTests.ValidateTokenAsyncTests.Signature.cs b/test/Microsoft.IdentityModel.Tokens.Saml.Tests/Saml2SecurityTokenHandlerTests.ValidateTokenAsyncTests.Signature.cs new file mode 100644 index 0000000000..dbe28f7582 --- /dev/null +++ b/test/Microsoft.IdentityModel.Tokens.Saml.Tests/Saml2SecurityTokenHandlerTests.ValidateTokenAsyncTests.Signature.cs @@ -0,0 +1,207 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System.Threading; +using System.Threading.Tasks; +using Microsoft.IdentityModel.TestUtils; +using Microsoft.IdentityModel.Tokens.Saml2; +using Xunit; + +namespace Microsoft.IdentityModel.Tokens.Saml.Tests +{ +#nullable enable + public partial class Saml2SecurityTokenHandlerTests + { + [Theory, MemberData(nameof(ValidateTokenAsync_Signature_TestCases), DisableDiscoveryEnumeration = true)] + public async Task ValidateTokenAsync_SignatureComparison(ValidateTokenAsyncSignatureTheoryData theoryData) + { + var context = TestUtilities.WriteHeader($"{this}.ValidateTokenAsync_SignatureComparison", theoryData); + + Saml2SecurityTokenHandler saml2TokenHandler = new Saml2SecurityTokenHandler(); + + Saml2SecurityToken saml2Token = CreateTokenForSignatureValidation(theoryData.SigningCredentials); + + // Validate the token using TokenValidationParameters + TokenValidationResult tokenValidationResult = + await saml2TokenHandler.ValidateTokenAsync(saml2Token.Assertion.CanonicalString, theoryData.TokenValidationParameters); + + // Validate the token using ValidationParameters. + ValidationResult validationResult = + await saml2TokenHandler.ValidateTokenAsync( + saml2Token, + theoryData.ValidationParameters!, + theoryData.CallContext, + CancellationToken.None); + + // Ensure the validity of the results match the expected result. + if (tokenValidationResult.IsValid != validationResult.IsValid) + { + context.AddDiff($"tokenValidationResult.IsValid != validationResult.IsSuccess"); + theoryData.ExpectedExceptionValidationParameters!.ProcessException(validationResult.UnwrapError().GetException(), context); + theoryData.ExpectedException.ProcessException(tokenValidationResult.Exception, context); + } + else + { + if (tokenValidationResult.IsValid) + { + // Verify that the validated tokens from both paths match. + ValidatedToken validatedToken = validationResult.UnwrapResult(); + IdentityComparer.AreEqual(validatedToken.SecurityToken, tokenValidationResult.SecurityToken, context); + } + else + { + // Verify the exception provided by both paths match. + var tokenValidationResultException = tokenValidationResult.Exception; + var validationResultException = validationResult.UnwrapError().GetException(); + + theoryData.ExpectedException.ProcessException(tokenValidationResultException, context); + theoryData.ExpectedExceptionValidationParameters!.ProcessException(validationResultException, context); + } + + TestUtilities.AssertFailIfErrors(context); + } + } + + public static TheoryData ValidateTokenAsync_Signature_TestCases + { + get + { + var theoryData = new TheoryData(); + + theoryData.Add(new ValidateTokenAsyncSignatureTheoryData("Valid_SignatureIsValid") + { + SigningCredentials = KeyingMaterial.DefaultX509SigningCreds_2048_RsaSha2_Sha2, + TokenValidationParameters = CreateTokenValidationParameters(KeyingMaterial.DefaultX509SigningCreds_2048_RsaSha2_Sha2.Key), + ValidationParameters = CreateValidationParameters(KeyingMaterial.DefaultX509SigningCreds_2048_RsaSha2_Sha2.Key), + }); + + theoryData.Add(new ValidateTokenAsyncSignatureTheoryData("Invalid_TokenIsNotSigned") + { + SigningCredentials = null, + TokenValidationParameters = CreateTokenValidationParameters(), + ValidationParameters = CreateValidationParameters(), + ExpectedIsValid = false, + ExpectedException = ExpectedException.SecurityTokenValidationException("IDX10504:"), + ExpectedExceptionValidationParameters = ExpectedException.SecurityTokenValidationException("IDX10504:"), + }); + + theoryData.Add(new ValidateTokenAsyncSignatureTheoryData("Invalid_TokenSignedWithDifferentKey_KeyIdPresent_TryAllKeysFalse") + { + SigningCredentials = Default.SymmetricSigningCredentials, + TokenValidationParameters = CreateTokenValidationParameters(Default.AsymmetricSigningKey), + ValidationParameters = CreateValidationParameters(Default.AsymmetricSigningKey), + ExpectedIsValid = false, + ExpectedException = ExpectedException.SecurityTokenSignatureKeyNotFoundException("IDX10500:"), + ExpectedExceptionValidationParameters = ExpectedException.SecurityTokenSignatureKeyNotFoundException("IDX10500:"), + }); + + theoryData.Add(new ValidateTokenAsyncSignatureTheoryData("Invalid_TokenSignedWithDifferentKey_KeyIdPresent_TryAllKeysTrue") + { + SigningCredentials = Default.SymmetricSigningCredentials, + TokenValidationParameters = CreateTokenValidationParameters(Default.AsymmetricSigningKey, tryAllKeys: true), + ValidationParameters = CreateValidationParameters(Default.AsymmetricSigningKey, tryAllKeys: true), + ExpectedIsValid = false, + ExpectedException = ExpectedException.SecurityTokenSignatureKeyNotFoundException("IDX10512:"), + ExpectedExceptionValidationParameters = ExpectedException.SecurityTokenSignatureKeyNotFoundException("IDX10512:"), + }); + + theoryData.Add(new ValidateTokenAsyncSignatureTheoryData("Invalid_TokenSignedWithDifferentKey_KeyIdNotPresent_TryAllKeysFalse") + { + SigningCredentials = KeyingMaterial.DefaultSymmetricSigningCreds_256_Sha2_NoKeyId, + TokenValidationParameters = CreateTokenValidationParameters(Default.AsymmetricSigningKey), + ValidationParameters = CreateValidationParameters(Default.AsymmetricSigningKey), + ExpectedIsValid = false, + ExpectedException = ExpectedException.SecurityTokenSignatureKeyNotFoundException("IDX10500:"), + ExpectedExceptionValidationParameters = ExpectedException.SecurityTokenSignatureKeyNotFoundException("IDX10500:"), + }); + + theoryData.Add(new ValidateTokenAsyncSignatureTheoryData("Invalid_TokenSignedWithDifferentKey_KeyIdNotPresent_TryAllKeysTrue") + { + SigningCredentials = KeyingMaterial.DefaultSymmetricSigningCreds_256_Sha2_NoKeyId, + TokenValidationParameters = CreateTokenValidationParameters(Default.AsymmetricSigningKey, tryAllKeys: true), + ValidationParameters = CreateValidationParameters(Default.AsymmetricSigningKey, tryAllKeys: true), + ExpectedIsValid = false, + ExpectedException = ExpectedException.SecurityTokenSignatureKeyNotFoundException("IDX10512:"), + ExpectedExceptionValidationParameters = ExpectedException.SecurityTokenSignatureKeyNotFoundException("IDX10512:"), + }); + + theoryData.Add(new ValidateTokenAsyncSignatureTheoryData("Invalid_TokenValidationParametersAndValidationParametersAreNull") + { + ExpectedException = ExpectedException.ArgumentNullException("IDX10000:"), + ExpectedExceptionValidationParameters = ExpectedException.SecurityTokenArgumentNullException("IDX10000:"), + ExpectedIsValid = false, + }); + + return theoryData; + + static ValidationParameters CreateValidationParameters( + SecurityKey? issuerSigingKey = null, bool tryAllKeys = false) + { + ValidationParameters validationParameters = new ValidationParameters(); + validationParameters.AudienceValidator = SkipValidationDelegates.SkipAudienceValidation; + validationParameters.AlgorithmValidator = SkipValidationDelegates.SkipAlgorithmValidation; + validationParameters.IssuerSigningKeyValidator = SkipValidationDelegates.SkipIssuerSigningKeyValidation; + validationParameters.IssuerValidatorAsync = SkipValidationDelegates.SkipIssuerValidation; + validationParameters.LifetimeValidator = SkipValidationDelegates.SkipLifetimeValidation; + validationParameters.TokenReplayValidator = SkipValidationDelegates.SkipTokenReplayValidation; + validationParameters.TokenTypeValidator = SkipValidationDelegates.SkipTokenTypeValidation; + validationParameters.TryAllIssuerSigningKeys = tryAllKeys; + + if (issuerSigingKey is not null) + validationParameters.IssuerSigningKeys.Add(issuerSigingKey); + + return validationParameters; + } + + static TokenValidationParameters CreateTokenValidationParameters( + SecurityKey? issuerSigningKey = null, bool tryAllKeys = false) + { + return new TokenValidationParameters + { + ValidateAudience = false, + ValidateIssuer = false, + ValidateLifetime = false, + ValidateTokenReplay = false, + ValidateIssuerSigningKey = false, + RequireSignedTokens = true, + RequireAudience = false, + IssuerSigningKey = issuerSigningKey, + TryAllIssuerSigningKeys = tryAllKeys, + }; + } + } + } + + public class ValidateTokenAsyncSignatureTheoryData : TheoryDataBase + { + public ValidateTokenAsyncSignatureTheoryData(string testId) : base(testId) { } + + internal ExpectedException? ExpectedExceptionValidationParameters { get; set; } = ExpectedException.NoExceptionExpected; + + internal SigningCredentials? SigningCredentials { get; set; } = null; + + internal bool ExpectedIsValid { get; set; } = true; + + internal ValidationParameters? ValidationParameters { get; set; } + + internal TokenValidationParameters? TokenValidationParameters { get; set; } + } + + private static Saml2SecurityToken CreateTokenForSignatureValidation(SigningCredentials? signingCredentials) + { + Saml2SecurityTokenHandler saml2TokenHandler = new Saml2SecurityTokenHandler(); + + SecurityTokenDescriptor securityTokenDescriptor = new SecurityTokenDescriptor + { + Subject = Default.SamlClaimsIdentity, + SigningCredentials = signingCredentials, + Issuer = Default.Issuer, + }; + + Saml2SecurityToken samlToken = (Saml2SecurityToken)saml2TokenHandler.CreateToken(securityTokenDescriptor); + + return saml2TokenHandler.ReadSaml2Token(samlToken.Assertion.CanonicalString); + } + } +} +#nullable restore