diff --git a/src/Microsoft.IdentityModel.Tokens.Saml/InternalAPI.Unshipped.txt b/src/Microsoft.IdentityModel.Tokens.Saml/InternalAPI.Unshipped.txt index 8ff2618628..057dee7277 100644 --- a/src/Microsoft.IdentityModel.Tokens.Saml/InternalAPI.Unshipped.txt +++ b/src/Microsoft.IdentityModel.Tokens.Saml/InternalAPI.Unshipped.txt @@ -10,6 +10,8 @@ Microsoft.IdentityModel.Tokens.Saml.SamlSecurityTokenHandler.ValidateTokenAsync( Microsoft.IdentityModel.Tokens.Saml2.Saml2SecurityTokenHandler.StackFrames Microsoft.IdentityModel.Tokens.Saml2.Saml2SecurityTokenHandler.ValidateTokenAsync(Microsoft.IdentityModel.Tokens.Saml2.Saml2SecurityToken samlToken, Microsoft.IdentityModel.Tokens.ValidationParameters validationParameters, Microsoft.IdentityModel.Tokens.CallContext callContext, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task> static Microsoft.IdentityModel.Tokens.Saml.SamlSecurityTokenHandler.StackFrames.IssuerValidationFailed -> System.Diagnostics.StackFrame +static Microsoft.IdentityModel.Tokens.Saml.SamlSecurityTokenHandler.StackFrames.SignatureValidationFailed -> System.Diagnostics.StackFrame +static Microsoft.IdentityModel.Tokens.Saml.SamlSecurityTokenHandler.ValidateSignature(Microsoft.IdentityModel.Tokens.Saml.SamlSecurityToken samlToken, Microsoft.IdentityModel.Tokens.ValidationParameters validationParameters, Microsoft.IdentityModel.Tokens.CallContext callContext) -> Microsoft.IdentityModel.Tokens.ValidationResult static Microsoft.IdentityModel.Tokens.Saml.SamlTokenUtilities.PopulateValidationParametersWithCurrentConfigurationAsync(Microsoft.IdentityModel.Tokens.ValidationParameters validationParameters, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task Microsoft.IdentityModel.Tokens.Saml2.SamlSecurityTokenHandler.ValidateTokenAsync(SamlSecurityToken samlToken, Microsoft.IdentityModel.Tokens.ValidationParameters validationParameters, Microsoft.IdentityModel.Tokens.CallContext callContext, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task> static Microsoft.IdentityModel.Tokens.Saml.SamlSecurityTokenHandler.StackFrames.AssertionConditionsNull -> System.Diagnostics.StackFrame @@ -20,6 +22,7 @@ static Microsoft.IdentityModel.Tokens.Saml.SamlSecurityTokenHandler.StackFrames. static Microsoft.IdentityModel.Tokens.Saml.SamlSecurityTokenHandler.StackFrames.OneTimeUseValidationFailed -> System.Diagnostics.StackFrame static Microsoft.IdentityModel.Tokens.Saml.SamlSecurityTokenHandler.StackFrames.TokenNull -> System.Diagnostics.StackFrame static Microsoft.IdentityModel.Tokens.Saml.SamlSecurityTokenHandler.StackFrames.TokenValidationParametersNull -> System.Diagnostics.StackFrame +static Microsoft.IdentityModel.Tokens.Saml.SamlTokenUtilities.ResolveTokenSigningKey(Microsoft.IdentityModel.Xml.KeyInfo tokenKeyInfo, Microsoft.IdentityModel.Tokens.ValidationParameters validationParameters) -> Microsoft.IdentityModel.Tokens.SecurityKey static Microsoft.IdentityModel.Tokens.Saml2.Saml2SecurityTokenHandler.StackFrames.AssertionConditionsNull -> System.Diagnostics.StackFrame static Microsoft.IdentityModel.Tokens.Saml2.Saml2SecurityTokenHandler.StackFrames.AssertionConditionsValidationFailed -> System.Diagnostics.StackFrame static Microsoft.IdentityModel.Tokens.Saml2.Saml2SecurityTokenHandler.StackFrames.AssertionNull -> System.Diagnostics.StackFrame diff --git a/src/Microsoft.IdentityModel.Tokens.Saml/Saml/SamlSecurityTokenHandler.ValidateSignature.cs b/src/Microsoft.IdentityModel.Tokens.Saml/Saml/SamlSecurityTokenHandler.ValidateSignature.cs new file mode 100644 index 0000000000..99e50582c3 --- /dev/null +++ b/src/Microsoft.IdentityModel.Tokens.Saml/Saml/SamlSecurityTokenHandler.ValidateSignature.cs @@ -0,0 +1,167 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// 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; + +#nullable enable +namespace Microsoft.IdentityModel.Tokens.Saml +{ + public partial class SamlSecurityTokenHandler : SecurityTokenHandler + { + internal static ValidationResult ValidateSignature( + SamlSecurityToken samlToken, + ValidationParameters validationParameters, +#pragma warning disable CA1801 // Review unused parameters + CallContext callContext) +#pragma warning restore CA1801 // Review unused parameters + { + if (samlToken is null) + { + return ValidationError.NullParameter( + nameof(samlToken), + new StackFrame(true)); + } + + if (validationParameters is null) + { + return ValidationError.NullParameter( + nameof(validationParameters), + new StackFrame(true)); + } + + // 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 implement the delegate + if (samlToken.Assertion.Signature is null) + return new XmlValidationError( + new MessageDetail( + TokenLogMessages.IDX10504, + samlToken.Assertion.CanonicalString), + ValidationFailureType.SignatureValidationFailed, + typeof(SecurityTokenValidationException), + new StackFrame(true)); + + IList? keys = null; + 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); + } + + if (resolvedKey is null) + { + if (validationParameters.TryAllIssuerSigningKeys) + keys = validationParameters.IssuerSigningKeys; + } + else + { + keys = [resolvedKey]; + keyMatched = true; + } + + bool canMatchKey = samlToken.Assertion.Signature.KeyInfo != null; + List errors = new(); + StringBuilder keysAttempted = new(); + + if (keys is not null) + { + for (int i = 0; i < keys.Count; i++) + { + SecurityKey key = keys[i]; + ValidationResult algorithmValidationResult = validationParameters.AlgorithmValidator( + samlToken.Assertion.Signature.SignedInfo.SignatureMethod, + key, + samlToken, + validationParameters, + callContext); + + if (!algorithmValidationResult.IsValid) + { + errors.Add(algorithmValidationResult.UnwrapError()); + } + else + { + var validationError = samlToken.Assertion.Signature.Verify( + key, + validationParameters.CryptoProviderFactory ?? key.CryptoProviderFactory, + callContext); + + if (validationError is null) + { + samlToken.SigningKey = key; + + return key; + } + else + { + errors.Add(validationError.AddStackFrame(new StackFrame())); + } + } + + keysAttempted.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(errors), + samlToken), + ValidationFailureType.SignatureValidationFailed, + typeof(SecurityTokenInvalidSignatureException), + new StackFrame(true)); + + if (keysAttempted.Length > 0) + return new XmlValidationError( + new MessageDetail( + TokenLogMessages.IDX10512, + keysAttempted.ToString(), + GetErrorStrings(errors), + samlToken), + ValidationFailureType.SignatureValidationFailed, + typeof(SecurityTokenSignatureKeyNotFoundException), + new StackFrame(true)); + + return new XmlValidationError( + new MessageDetail(TokenLogMessages.IDX10500), + ValidationFailureType.SignatureValidationFailed, + typeof(SecurityTokenSignatureKeyNotFoundException), + new StackFrame(true)); + } + + private static string GetErrorStrings(List errors) + { + StringBuilder sb = new(); + for (int i = 0; i < errors.Count; i++) + { + sb.AppendLine(errors[i].ToString()); + } + + return sb.ToString(); + } + } +} +#nullable restore diff --git a/src/Microsoft.IdentityModel.Tokens.Saml/Saml/SamlSecurityTokenHandler.ValidateToken.Internal.cs b/src/Microsoft.IdentityModel.Tokens.Saml/Saml/SamlSecurityTokenHandler.ValidateToken.Internal.cs index ab24f3fa52..04a2d3c92e 100644 --- a/src/Microsoft.IdentityModel.Tokens.Saml/Saml/SamlSecurityTokenHandler.ValidateToken.Internal.cs +++ b/src/Microsoft.IdentityModel.Tokens.Saml/Saml/SamlSecurityTokenHandler.ValidateToken.Internal.cs @@ -61,6 +61,13 @@ internal async Task> ValidateTokenAsync( return issuerValidationResult.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/Saml/SamlSecurityTokenHandler.ValidateToken.StackFrames.cs b/src/Microsoft.IdentityModel.Tokens.Saml/Saml/SamlSecurityTokenHandler.ValidateToken.StackFrames.cs index 93a91b2bc8..faa6aad0a6 100644 --- a/src/Microsoft.IdentityModel.Tokens.Saml/Saml/SamlSecurityTokenHandler.ValidateToken.StackFrames.cs +++ b/src/Microsoft.IdentityModel.Tokens.Saml/Saml/SamlSecurityTokenHandler.ValidateToken.StackFrames.cs @@ -24,6 +24,7 @@ internal static class StackFrames internal static StackFrame? OneTimeUseValidationFailed; internal static StackFrame? IssuerValidationFailed; + internal static StackFrame? SignatureValidationFailed; } } } diff --git a/src/Microsoft.IdentityModel.Tokens.Saml/Saml/SamlTokenUtilities.cs b/src/Microsoft.IdentityModel.Tokens.Saml/Saml/SamlTokenUtilities.cs index 525edc6e21..06842c5f3c 100644 --- a/src/Microsoft.IdentityModel.Tokens.Saml/Saml/SamlTokenUtilities.cs +++ b/src/Microsoft.IdentityModel.Tokens.Saml/Saml/SamlTokenUtilities.cs @@ -47,6 +47,29 @@ internal static SecurityKey ResolveTokenSigningKey(KeyInfo tokenKeyInfo, TokenVa return null; } + /// + /// Returns a to use when validating the signature of a token. + /// + /// The field of the token being validated + /// The to be used for validating the token. + /// Returns a to use for signature validation. + /// If key fails to resolve, then null is returned + internal static SecurityKey ResolveTokenSigningKey(KeyInfo tokenKeyInfo, ValidationParameters validationParameters) + { + if (tokenKeyInfo is null || validationParameters.IssuerSigningKeys is null) + return null; + + for (int i = 0; i < validationParameters.IssuerSigningKeys.Count; i++) + { + if (tokenKeyInfo.MatchesKey(validationParameters.IssuerSigningKeys[i])) + return validationParameters.IssuerSigningKeys[i]; + } + + return null; + } + + + /// /// Creates 's from . /// diff --git a/src/Microsoft.IdentityModel.Tokens/InternalAPI.Unshipped.txt b/src/Microsoft.IdentityModel.Tokens/InternalAPI.Unshipped.txt index 5816053a79..e50d151726 100644 --- a/src/Microsoft.IdentityModel.Tokens/InternalAPI.Unshipped.txt +++ b/src/Microsoft.IdentityModel.Tokens/InternalAPI.Unshipped.txt @@ -32,3 +32,4 @@ static Microsoft.IdentityModel.Tokens.Utility.SerializeAsSingleCommaDelimitedStr static readonly Microsoft.IdentityModel.Tokens.ValidationFailureType.NoTokenAudiencesProvided -> Microsoft.IdentityModel.Tokens.ValidationFailureType 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.XmlValidationFailed -> Microsoft.IdentityModel.Tokens.ValidationFailureType diff --git a/src/Microsoft.IdentityModel.Tokens/Validation/Results/Details/ValidationError.cs b/src/Microsoft.IdentityModel.Tokens/Validation/Results/Details/ValidationError.cs index 302476db22..8dec8466a0 100644 --- a/src/Microsoft.IdentityModel.Tokens/Validation/Results/Details/ValidationError.cs +++ b/src/Microsoft.IdentityModel.Tokens/Validation/Results/Details/ValidationError.cs @@ -118,6 +118,8 @@ internal Exception GetException(Type exceptionType, Exception innerException) exception = new SecurityTokenException(MessageDetail.Message); else if (exceptionType == typeof(SecurityTokenKeyWrapException)) exception = new SecurityTokenKeyWrapException(MessageDetail.Message); + else if (ExceptionType == typeof(SecurityTokenValidationException)) + exception = new SecurityTokenValidationException(MessageDetail.Message); else { // Exception type is unknown @@ -175,6 +177,8 @@ internal Exception GetException(Type exceptionType, Exception innerException) exception = new SecurityTokenException(MessageDetail.Message, actualException); else if (exceptionType == typeof(SecurityTokenKeyWrapException)) exception = new SecurityTokenKeyWrapException(MessageDetail.Message, actualException); + else if (exceptionType == typeof(SecurityTokenValidationException)) + exception = new SecurityTokenValidationException(MessageDetail.Message, actualException); else { // Exception type is unknown diff --git a/src/Microsoft.IdentityModel.Tokens/Validation/ValidationFailureType.cs b/src/Microsoft.IdentityModel.Tokens/Validation/ValidationFailureType.cs index 7a5b3939c2..6cf24dc28c 100644 --- a/src/Microsoft.IdentityModel.Tokens/Validation/ValidationFailureType.cs +++ b/src/Microsoft.IdentityModel.Tokens/Validation/ValidationFailureType.cs @@ -110,5 +110,11 @@ private class TokenDecryptionFailure : ValidationFailureType { internal TokenDec /// public static readonly ValidationFailureType InvalidSecurityToken = new InvalidSecurityTokenFailure("InvalidSecurityToken"); private class InvalidSecurityTokenFailure : ValidationFailureType { internal InvalidSecurityTokenFailure(string name) : base(name) { } } + + /// + /// Defines a type that represents that an XML validation failed. + /// + public static readonly ValidationFailureType XmlValidationFailed = new XmlValidationFailure("XmlValidationFailed"); + private class XmlValidationFailure : ValidationFailureType { internal XmlValidationFailure(string name) : base(name) { } } } } diff --git a/src/Microsoft.IdentityModel.Xml/Exceptions/XmlValidationError.cs b/src/Microsoft.IdentityModel.Xml/Exceptions/XmlValidationError.cs new file mode 100644 index 0000000000..6374d3edb8 --- /dev/null +++ b/src/Microsoft.IdentityModel.Xml/Exceptions/XmlValidationError.cs @@ -0,0 +1,34 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using System.Diagnostics; +using Microsoft.IdentityModel.Tokens; + +namespace Microsoft.IdentityModel.Xml +{ + internal class XmlValidationError : ValidationError + { + public XmlValidationError( + MessageDetail messageDetail, + ValidationFailureType validationFailureType, + Type exceptionType, + StackFrame stackFrame) : + base(messageDetail, validationFailureType, exceptionType, stackFrame) + { + + } + + internal override Exception GetException() + { + if (ExceptionType == typeof(XmlValidationException)) + { + XmlValidationException exception = new(MessageDetail.Message, InnerException); + exception.SetValidationError(this); + return exception; + } + + return base.GetException(); + } + } +} diff --git a/src/Microsoft.IdentityModel.Xml/Exceptions/XmlValidationException.cs b/src/Microsoft.IdentityModel.Xml/Exceptions/XmlValidationException.cs index 4e26c2f44c..702ff103bc 100644 --- a/src/Microsoft.IdentityModel.Xml/Exceptions/XmlValidationException.cs +++ b/src/Microsoft.IdentityModel.Xml/Exceptions/XmlValidationException.cs @@ -2,7 +2,12 @@ // Licensed under the MIT License. using System; +using System.Diagnostics; using System.Runtime.Serialization; +#pragma warning disable IDE0005 // Using directive is unnecessary. +using System.Text; +#pragma warning restore IDE0005 // Using directive is unnecessary. +using Microsoft.IdentityModel.Tokens; namespace Microsoft.IdentityModel.Xml { @@ -12,6 +17,11 @@ namespace Microsoft.IdentityModel.Xml [Serializable] public class XmlValidationException : XmlException { + [NonSerialized] + private string _stackTrace; + + private ValidationError _validationError; + /// /// Initializes a new instance of the class. /// @@ -49,5 +59,43 @@ protected XmlValidationException(SerializationInfo info, StreamingContext contex : base(info, context) { } + + /// + /// Sets the that caused the exception. + /// + /// + internal void SetValidationError(ValidationError validationError) + { + _validationError = validationError; + } + + /// + /// Gets the stack trace that is captured when the exception is created. + /// + public override string StackTrace + { + get + { + if (_stackTrace == null) + { + if (_validationError == null) + return base.StackTrace; +#if NET8_0_OR_GREATER + _stackTrace = new StackTrace(_validationError.StackFrames).ToString(); +#else + StringBuilder sb = new(); + foreach (StackFrame frame in _validationError.StackFrames) + { + sb.Append(frame.ToString()); + sb.Append(Environment.NewLine); + } + + _stackTrace = sb.ToString(); +#endif + } + + return _stackTrace; + } + } } } diff --git a/src/Microsoft.IdentityModel.Xml/InternalAPI.Unshipped.txt b/src/Microsoft.IdentityModel.Xml/InternalAPI.Unshipped.txt index e69de29bb2..fb30836a8b 100644 --- a/src/Microsoft.IdentityModel.Xml/InternalAPI.Unshipped.txt +++ b/src/Microsoft.IdentityModel.Xml/InternalAPI.Unshipped.txt @@ -0,0 +1,7 @@ +Microsoft.IdentityModel.Xml.Reference.Verify(Microsoft.IdentityModel.Tokens.CryptoProviderFactory cryptoProviderFactory, Microsoft.IdentityModel.Tokens.CallContext callContext) -> Microsoft.IdentityModel.Tokens.ValidationError +Microsoft.IdentityModel.Xml.Signature.Verify(Microsoft.IdentityModel.Tokens.SecurityKey key, Microsoft.IdentityModel.Tokens.CryptoProviderFactory cryptoProviderFactory, Microsoft.IdentityModel.Tokens.CallContext callContext) -> Microsoft.IdentityModel.Tokens.ValidationError +Microsoft.IdentityModel.Xml.SignedInfo.Verify(Microsoft.IdentityModel.Tokens.CryptoProviderFactory cryptoProviderFactory, Microsoft.IdentityModel.Tokens.CallContext callContext) -> Microsoft.IdentityModel.Tokens.ValidationError +Microsoft.IdentityModel.Xml.XmlValidationError +Microsoft.IdentityModel.Xml.XmlValidationError.XmlValidationError(Microsoft.IdentityModel.Tokens.MessageDetail messageDetail, Microsoft.IdentityModel.Tokens.ValidationFailureType validationFailureType, System.Type exceptionType, System.Diagnostics.StackFrame stackFrame) -> void +Microsoft.IdentityModel.Xml.XmlValidationException.SetValidationError(Microsoft.IdentityModel.Tokens.ValidationError validationError) -> void +override Microsoft.IdentityModel.Xml.XmlValidationError.GetException() -> System.Exception \ No newline at end of file diff --git a/src/Microsoft.IdentityModel.Xml/PublicAPI.Unshipped.txt b/src/Microsoft.IdentityModel.Xml/PublicAPI.Unshipped.txt index e69de29bb2..2d773dfa55 100644 --- a/src/Microsoft.IdentityModel.Xml/PublicAPI.Unshipped.txt +++ b/src/Microsoft.IdentityModel.Xml/PublicAPI.Unshipped.txt @@ -0,0 +1 @@ +override Microsoft.IdentityModel.Xml.XmlValidationException.StackTrace.get -> string diff --git a/src/Microsoft.IdentityModel.Xml/Reference.cs b/src/Microsoft.IdentityModel.Xml/Reference.cs index dcae13c9b2..2a1f6870af 100644 --- a/src/Microsoft.IdentityModel.Xml/Reference.cs +++ b/src/Microsoft.IdentityModel.Xml/Reference.cs @@ -126,6 +126,36 @@ public void Verify(CryptoProviderFactory cryptoProviderFactory) throw LogValidationException(LogMessages.IDX30201, Uri ?? Id); } +#nullable enable + /// + /// Verifies that the equals the hashed value of the after + /// have been applied. + /// + /// supplies the . + /// contextual information for diagnostics. + /// if is null. + internal ValidationError? Verify( + CryptoProviderFactory cryptoProviderFactory, +#pragma warning disable CA1801 // Review unused parameters + CallContext callContext) +#pragma warning restore CA1801 + { + if (cryptoProviderFactory == null) + return ValidationError.NullParameter(nameof(cryptoProviderFactory), new System.Diagnostics.StackFrame()); + + if (!Utility.AreEqual(ComputeDigest(cryptoProviderFactory), Convert.FromBase64String(DigestValue))) + return new XmlValidationError( + new MessageDetail( + LogMessages.IDX30201, + Uri ?? Id), + ValidationFailureType.XmlValidationFailed, + typeof(XmlValidationException), + new System.Diagnostics.StackFrame()); + + return null; + } +#nullable restore + /// /// Writes into a stream and then hashes the bytes. /// @@ -194,4 +224,4 @@ protected byte[] ComputeDigest(CryptoProviderFactory cryptoProviderFactory) } } } -} \ No newline at end of file +} diff --git a/src/Microsoft.IdentityModel.Xml/Signature.cs b/src/Microsoft.IdentityModel.Xml/Signature.cs index 717422ca87..8c36911800 100644 --- a/src/Microsoft.IdentityModel.Xml/Signature.cs +++ b/src/Microsoft.IdentityModel.Xml/Signature.cs @@ -2,6 +2,7 @@ // Licensed under the MIT License. using System; +using System.Diagnostics; using System.IO; using Microsoft.IdentityModel.Tokens; using static Microsoft.IdentityModel.Logging.LogHelper; @@ -124,5 +125,77 @@ public void Verify(SecurityKey key, CryptoProviderFactory cryptoProviderFactory) cryptoProviderFactory.ReleaseSignatureProvider(signatureProvider); } } + +#nullable enable + internal ValidationError? Verify( + SecurityKey key, + CryptoProviderFactory cryptoProviderFactory, +#pragma warning disable CA1801 // Review unused parameters + CallContext callContext) +#pragma warning restore CA1801 + { + if (key is null) + return ValidationError.NullParameter(nameof(key), new StackFrame()); + + if (cryptoProviderFactory is null) + return ValidationError.NullParameter(nameof(cryptoProviderFactory), new StackFrame()); + + if (SignedInfo is null) + return new XmlValidationError( + new MessageDetail(LogMessages.IDX30212), + ValidationFailureType.XmlValidationFailed, + typeof(XmlValidationException), + new StackFrame()); + + if (!cryptoProviderFactory.IsSupportedAlgorithm(SignedInfo.SignatureMethod, key)) + return new XmlValidationError( + new MessageDetail(LogMessages.IDX30207, SignedInfo.SignatureMethod, cryptoProviderFactory.GetType()), + ValidationFailureType.XmlValidationFailed, + typeof(XmlValidationException), + new StackFrame()); + + var signatureProvider = cryptoProviderFactory.CreateForVerifying(key, SignedInfo.SignatureMethod); + if (signatureProvider is null) + return new XmlValidationError( + new MessageDetail(LogMessages.IDX30203, cryptoProviderFactory, key, SignedInfo.SignatureMethod), + ValidationFailureType.XmlValidationFailed, + typeof(XmlValidationException), + new StackFrame()); + + ValidationError? validationError = null; + + try + { + using (var memoryStream = new MemoryStream()) + { + SignedInfo.GetCanonicalBytes(memoryStream); + if (!signatureProvider.Verify(memoryStream.ToArray(), Convert.FromBase64String(SignatureValue))) + { + validationError = new XmlValidationError( + new MessageDetail(LogMessages.IDX30200, cryptoProviderFactory, key), + ValidationFailureType.XmlValidationFailed, + typeof(XmlValidationException), + new StackFrame()); + } + } + + if (validationError is null) + { + validationError = SignedInfo.Verify(cryptoProviderFactory, callContext); + validationError?.AddStackFrame(new StackFrame()); + } + } + finally + { + if (signatureProvider is not null) + cryptoProviderFactory.ReleaseSignatureProvider(signatureProvider); + } + + if (validationError is not null) + return validationError; + + return null; // no error + } +#nullable restore } } diff --git a/src/Microsoft.IdentityModel.Xml/SignedInfo.cs b/src/Microsoft.IdentityModel.Xml/SignedInfo.cs index 50c59ccf3a..7f18cdad4b 100644 --- a/src/Microsoft.IdentityModel.Xml/SignedInfo.cs +++ b/src/Microsoft.IdentityModel.Xml/SignedInfo.cs @@ -112,6 +112,39 @@ public void Verify(CryptoProviderFactory cryptoProviderFactory) reference.Verify(cryptoProviderFactory); } +#nullable enable + /// + /// Verifies the digest of all + /// + /// supplies any required cryptographic operators. + /// contextual information for diagnostics. + internal ValidationError? Verify( + CryptoProviderFactory cryptoProviderFactory, +#pragma warning disable CA1801 + CallContext callContext) +#pragma warning restore CA1801 + { + if (cryptoProviderFactory == null) + return ValidationError.NullParameter(nameof(cryptoProviderFactory), new System.Diagnostics.StackFrame()); + + ValidationError? validationError = null; + + for (int i = 0; i < References.Count; i++) + { + var reference = References[i]; + validationError = reference.Verify(cryptoProviderFactory, callContext); + + if (validationError is not null) + { + validationError.AddStackFrame(new System.Diagnostics.StackFrame()); + break; + } + } + + return validationError; + } +#nullable restore + /// /// Writes the Canonicalized bytes into a stream. /// diff --git a/test/Microsoft.IdentityModel.Tokens.Saml.Tests/SamlSecurityTokenHandlerTests.ValidateTokenAsyncTests.Signature.cs b/test/Microsoft.IdentityModel.Tokens.Saml.Tests/SamlSecurityTokenHandlerTests.ValidateTokenAsyncTests.Signature.cs new file mode 100644 index 0000000000..d3714f73b4 --- /dev/null +++ b/test/Microsoft.IdentityModel.Tokens.Saml.Tests/SamlSecurityTokenHandlerTests.ValidateTokenAsyncTests.Signature.cs @@ -0,0 +1,210 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.IdentityModel.TestUtils; +using Xunit; + +namespace Microsoft.IdentityModel.Tokens.Saml.Tests +{ +#nullable enable + public partial class SamlSecurityTokenHandlerTests + { + [Theory, MemberData(nameof(ValidateTokenAsync_Signature_TestCases), DisableDiscoveryEnumeration = true)] + public async Task ValidateTokenAsync_SignatureComparison(ValidateTokenAsyncSignatureTheoryData theoryData) + { + var context = TestUtilities.WriteHeader($"{this}.ValidateTokenAsync_SignatureComparison", theoryData); + + SamlSecurityTokenHandler samlTokenHandler = new SamlSecurityTokenHandler(); + + var samlToken = CreateTokenForSignatureValidation(theoryData.SigningCredentials); + + // Validate the token using TokenValidationParameters + TokenValidationResult tokenValidationResult = + await samlTokenHandler.ValidateTokenAsync(samlToken.Assertion.CanonicalString, theoryData.TokenValidationParameters); + + // Validate the token using ValidationParameters. + ValidationResult validationResult = + await samlTokenHandler.ValidateTokenAsync( + samlToken, + 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(); + + if (theoryData.TestId == "Invalid_TokenSignedWithDifferentKey_KeyIdPresent_TryAllKeysFalse") + Console.WriteLine($"tokenValidationResultException: {tokenValidationResultException}"); + + theoryData.ExpectedException.ProcessException(tokenValidationResult.Exception, context); + theoryData.ExpectedExceptionValidationParameters!.ProcessException(validationResult.UnwrapError().GetException(), 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 SamlSecurityToken CreateTokenForSignatureValidation(SigningCredentials? signingCredentials) + { + SamlSecurityTokenHandler samlTokenHandler = new SamlSecurityTokenHandler(); + + SecurityTokenDescriptor securityTokenDescriptor = new SecurityTokenDescriptor + { + Subject = Default.SamlClaimsIdentity, + SigningCredentials = signingCredentials, + Issuer = Default.Issuer, + }; + + SamlSecurityToken samlToken = (SamlSecurityToken)samlTokenHandler.CreateToken(securityTokenDescriptor); + + return samlTokenHandler.ReadSamlToken(samlToken.Assertion.CanonicalString); + } + } +} +#nullable restore