Skip to content

Commit

Permalink
SAML2 new model validation: Signature (#2961)
Browse files Browse the repository at this point in the history
* Added XmlValidationError. Added ValidationError property to XmlValidationException to provide custom stack traces

* Added alternative versions using ValidationParameters to XML signature validations

* Added XmlValidationFailure to ValidationFailureType

* Added refactored ValidateSignature method to SamlSecurityTokenHandler.
Updated ValidateTokenAsync to call ValidateSignature.

* Added tests to compare signature validation between the legacy and new path

* Re-added API lost in merge to InternalAPI.Unshipped.txt

* Migrated refactored ValidateSignature from SamlSecurityTokenHandler to Saml2SecurityTokenHandler

* Updated Saml2SecurityTokenHandler's ValidateTokenAsync to validate signatures

* Added tests

* Update src/Microsoft.IdentityModel.Tokens.Saml/Saml2/Saml2SecurityTokenHandler.ValidateSignature.cs

Co-authored-by: msbw2 <brettwhite@microsoft.com>

* Addressed PR feedback in both SAML and SAML2 signature validations to keep the alignment

* Optimised signature validation in SAML and SAML2 for the expected most common scenario

* Removed debug information

* Addressed PR feedback

* Addressed PR feedback

---------

Co-authored-by: msbw2 <brettwhite@microsoft.com>
  • Loading branch information
iNinja and msbw2 authored Nov 8, 2024
1 parent a275ee4 commit dfae4af
Show file tree
Hide file tree
Showing 10 changed files with 518 additions and 69 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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<Microsoft.IdentityModel.Tokens.SecurityKey>
virtual Microsoft.IdentityModel.Tokens.Saml2.Saml2SecurityTokenHandler.ReadSaml2Token(string token, Microsoft.IdentityModel.Tokens.CallContext callContext) -> Microsoft.IdentityModel.Tokens.ValidationResult<Microsoft.IdentityModel.Tokens.Saml2.Saml2SecurityToken>
virtual Microsoft.IdentityModel.Tokens.Saml.SamlSecurityTokenHandler.ReadSamlToken(string token, Microsoft.IdentityModel.Tokens.CallContext callContext) -> Microsoft.IdentityModel.Tokens.ValidationResult<Microsoft.IdentityModel.Tokens.Saml.SamlSecurityToken>
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<Microsoft.IdentityModel.Tokens.Saml.SamlSecurityTokenHandler.ValidatedConditions>
virtual Microsoft.IdentityModel.Tokens.Saml2.Saml2SecurityTokenHandler.ReadSaml2Token(string token, Microsoft.IdentityModel.Tokens.CallContext callContext) -> Microsoft.IdentityModel.Tokens.ValidationResult<Microsoft.IdentityModel.Tokens.Saml2.Saml2SecurityToken>
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -23,14 +22,14 @@ internal static ValidationResult<SecurityKey> 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.
Expand All @@ -43,11 +42,10 @@ internal static ValidationResult<SecurityKey> ValidateSignature(
new MessageDetail(
TokenLogMessages.IDX10504,
samlToken.Assertion.CanonicalString),
ValidationFailureType.SignatureValidationFailed,
ValidationFailureType.TokenIsNotSigned,
typeof(SecurityTokenValidationException),
new StackFrame(true));
ValidationError.GetCurrentStackFrame());

IList<SecurityKey>? keys = null;
SecurityKey? resolvedKey = null;
bool keyMatched = false;

Expand All @@ -66,57 +64,39 @@ internal static ValidationResult<SecurityKey> 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<ValidationError> errors = new();
StringBuilder keysAttempted = new();
List<ValidationError>? 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<string> 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);
}
Expand All @@ -126,38 +106,88 @@ internal static ValidationResult<SecurityKey> 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<ValidationError> errors)
private static ValidationResult<SecurityKey> ValidateSignatureUsingKey(SecurityKey key, SamlSecurityToken samlToken, ValidationParameters validationParameters, CallContext callContext)
{
ValidationResult<string> 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<ValidationError>? 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();
Expand Down
Loading

0 comments on commit dfae4af

Please sign in to comment.