Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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 @@ -60,12 +60,15 @@ internal ValidationResult<string, ValidationError> DecryptToken(

if (result.ContentEncryptionKeys == null || result.ContentEncryptionKeys.Count == 0)
{
return new ValidationError(
ValidationError validationError = new(
new MessageDetail(
TokenLogMessages.IDX10609,
LogHelper.MarkAsSecurityArtifact(jwtToken, JwtTokenUtilities.SafeLogJwtToken)),
ValidationFailureType.TokenDecryptionFailed,
ValidationError.GetCurrentStackFrame());

LogHelper.LogExceptionMessage(validationError.GetException());
return validationError;
}

var decryptionParameters = CreateJwtTokenDecryptionParameters(jwtToken, result.ContentEncryptionKeys);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -130,8 +130,10 @@ private static ValidationError GetDecryptionError(
CallContext callContext)
#pragma warning restore CA1801 // Review unused parameters
{
ValidationError validationError;

if (keysAttempted is not null)
return new ValidationError(
validationError = new ValidationError(
new MessageDetail(
TokenLogMessages.IDX10603,
LogHelper.MarkAsNonPII(keysAttempted.ToString()),
Expand All @@ -141,7 +143,7 @@ private static ValidationError GetDecryptionError(
ValidationError.GetCurrentStackFrame());

else if (algorithmNotSupportedByCryptoProvider)
return new ValidationError(
validationError = new ValidationError(
new MessageDetail(
TokenLogMessages.IDX10619,
LogHelper.MarkAsNonPII(decryptionParameters.Alg),
Expand All @@ -150,12 +152,15 @@ private static ValidationError GetDecryptionError(
ValidationError.GetCurrentStackFrame());

else
return new ValidationError(
validationError = new ValidationError(
new MessageDetail(
TokenLogMessages.IDX10609,
LogHelper.MarkAsSecurityArtifact(decryptionParameters.EncodedToken, SafeLogJwtToken)),
ValidationFailureType.TokenDecryptionFailed,
ValidationError.GetCurrentStackFrame());

LogHelper.LogExceptionMessage(validationError.GetException());
return validationError;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// Licensed under the MIT License.

using System;
using System.Diagnostics.Tracing;
using System.IO;
using System.Security.Cryptography;
using Microsoft.IdentityModel.Logging;
Expand Down Expand Up @@ -180,7 +181,12 @@ private byte[] DecryptWithAesCbc(byte[] ciphertext, byte[] authenticatedData, by
Array.Copy(ciphertext, 0, macBytes, authenticatedData.Length + iv.Length, ciphertext.Length);
Array.Copy(al, 0, macBytes, authenticatedData.Length + iv.Length + ciphertext.Length, al.Length);
if (!_symmetricSignatureProvider.Value.Verify(macBytes, 0, macBytes.Length, authenticationTag, 0, _authenticatedkeys.Value.HmacKey.Key.Length, Algorithm))
throw LogHelper.LogExceptionMessage(new SecurityTokenDecryptionFailedException(LogHelper.FormatInvariant(LogMessages.IDX10650, Base64UrlEncoder.Encode(authenticatedData), Base64UrlEncoder.Encode(iv), Base64UrlEncoder.Encode(authenticationTag))));
// Verifying the authentication tag can legitimately fail while probing multiple candidate
// decryption keys (JsonWebTokenHandler tries all keys when it cannot resolve one by kid/x5t).
// Log this per-key failure below Error so it is not surfaced as noise during otherwise-successful
// decryption; the terminal all-keys-failed case is still reported at Error via IDX10603/IDX10609,
// which aggregates each attempted key's exception detail.
throw LogHelper.LogExceptionMessage(EventLevel.Informational, new SecurityTokenDecryptionFailedException(LogHelper.FormatInvariant(LogMessages.IDX10650, Base64UrlEncoder.Encode(authenticatedData), Base64UrlEncoder.Encode(iv), Base64UrlEncoder.Encode(authenticationTag))));
Comment thread
RojaEnnam marked this conversation as resolved.
Resolved

using Aes aes = Aes.Create();
aes.Mode = CipherMode.CBC;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -454,6 +454,67 @@ public void DecryptJwtToken_WhenDecryptionFails_ThrowsException()
Assert.Contains(partialExceptionMessage, exception.Message);
}

[Fact]
public void DecryptJwtTokenResult_WhenDecryptionFails_LogsAggregateError()
{
var securityKey = NotDefault.SymmetricSigningKey256;
var jsonWebTokenHandler = new JsonWebTokenHandler();
var securityToken = new JsonWebToken(jsonWebTokenHandler.CreateToken(
Default.PayloadString,
Default.SymmetricSigningCredentials,
Default.SymmetricEncryptingCredentials));

using var listener = new EventCaptureListener(EventLevel.Error);
var decryptionParameters = new JwtTokenDecryptionParameters
{
Alg = securityToken.Alg,
AuthenticationTagBytes = securityToken.AuthenticationTagBytes,
CipherTextBytes = securityToken.CipherTextBytes,
DecompressionFunction = JwtTokenUtilities.DecompressToken,
Enc = securityToken.Enc,
EncodedToken = securityToken.EncodedToken,
HeaderAsciiBytes = securityToken.HeaderAsciiBytes,
InitializationVectorBytes = securityToken.InitializationVectorBytes,
MaximumDeflateSize = jsonWebTokenHandler.MaximumTokenSizeInBytes,
Keys = new List<SecurityKey> { securityKey },
Zip = securityToken.Zip,
};
var validationParameters = new ValidationParameters();

ValidationResult<string, ValidationError> result = JwtTokenUtilities.DecryptJwtToken(
securityToken,
validationParameters,
decryptionParameters,
new CallContext());

Assert.False(result.Succeeded);
Assert.Contains("IDX10603:", result.Error.Message);
string errorEvent = Assert.Single(listener.Events);
Assert.Contains("IDX10603:", errorEvent);
}

[Fact]
public void DecryptTokenResult_WhenNoKeys_LogsAggregateError()
{
var securityToken = new JsonWebToken(new JsonWebTokenHandler().CreateToken(
Default.PayloadString,
Default.SymmetricSigningCredentials,
Default.SymmetricEncryptingCredentials));

using var listener = new EventCaptureListener(EventLevel.Error);
var validationParameters = new ValidationParameters();

ValidationResult<string, ValidationError> result = new JsonWebTokenHandler().DecryptToken(
securityToken,
validationParameters,
null,
new CallContext());

Assert.False(result.Succeeded);
Assert.Contains("IDX10609:", result.Error.Message);
Assert.Contains("IDX10609:", Assert.Single(listener.Events));
}

[Theory, MemberData(nameof(DecompressionFailTheoryData), DisableDiscoveryEnumeration = true)]
public void DecryptJwtToken_WhenDecompressionFails_ThrowsException(DecompressionFailureTheoryData theoryData)
{
Expand Down Expand Up @@ -573,5 +634,37 @@ private BaseConfiguration GetConfigurationNoMatchingKeyMock()

return config;
}

private sealed class EventCaptureListener : EventListener
{
private readonly EventLevel _originalLogLevel;

public EventCaptureListener(EventLevel eventLevel)
{
_originalLogLevel = IdentityModelEventSource.Logger.LogLevel;
IdentityModelEventSource.Logger.LogLevel = eventLevel;
EnableEvents(IdentityModelEventSource.Logger, eventLevel);
}

public List<string> Events { get; } = new();

public override void Dispose()
{
try
{
base.Dispose();
}
finally
{
IdentityModelEventSource.Logger.LogLevel = _originalLogLevel;
}
}

protected override void OnEventWritten(EventWrittenEventArgs eventData)
{
if (eventData?.Level == EventLevel.Error && eventData.Payload?.Count > 0)
Events.Add(eventData.Payload[0]?.ToString() ?? string.Empty);
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@

using System;
using System.Collections.Generic;
using System.Diagnostics.Tracing;
using System.Runtime.InteropServices;
using Microsoft.IdentityModel.Logging;
using Microsoft.IdentityModel.TestUtils;
using Xunit;
#pragma warning disable CS3016 // Arrays as attribute arguments is not CLS-compliant
Expand Down Expand Up @@ -195,6 +197,55 @@ public void Decrypt(AuthenticatedEncryptionTheoryData theoryData)
TestUtilities.AssertFailIfErrors(context);
}

// Regression test: a per-key authentication-tag verification failure (IDX10650) is expected noise while
// JsonWebTokenHandler probes multiple candidate decryption keys, and must not be logged at Error. It must
// still be retrievable at a lower level for diagnostics. See AuthenticatedEncryptionProvider.DecryptWithAesCbc.
[Fact]
public void DecryptAuthTagFailureIsNotLoggedAtError()
{
var context = new CompareContext($"{this}.DecryptAuthTagFailureIsNotLoggedAtError");

var key = Default.SymmetricEncryptionKey256;
var algorithm = SecurityAlgorithms.Aes128CbcHmacSha256;
var authenticatedData = Guid.NewGuid().ToByteArray();
var plainText = Guid.NewGuid().ToByteArray();
var provider = new AuthenticatedEncryptionProvider(key, algorithm);
var results = provider.Encrypt(plainText, authenticatedData);

// Tamper the authentication tag so verification fails with IDX10650.
TestUtilities.XORBytes(results.AuthenticationTag);

EventLevel originalLogLevel = IdentityModelEventSource.Logger.LogLevel;
try
{
// With the listener at Error level, IDX10650 must NOT be logged (it is below Error).
using (var errorListener = SampleListener.CreateLoggerListener(EventLevel.Error))
{
Assert.Throws<SecurityTokenDecryptionFailedException>(() =>
provider.Decrypt(results.Ciphertext, authenticatedData, results.IV, results.AuthenticationTag));

if (errorListener.TraceBuffer.Contains("IDX10650"))
context.AddDiff("IDX10650 was logged at Error level; per-key decryption-tag failures must be logged below Error.");
}

// With the listener at Informational level, IDX10650 MUST still be logged for diagnostics.
using (var infoListener = SampleListener.CreateLoggerListener(EventLevel.Informational))
{
Assert.Throws<SecurityTokenDecryptionFailedException>(() =>
provider.Decrypt(results.Ciphertext, authenticatedData, results.IV, results.AuthenticationTag));

if (!infoListener.TraceBuffer.Contains("IDX10650"))
context.AddDiff("IDX10650 was not logged at Informational level; the per-key failure detail should remain available for diagnostics.");
}
}
finally
{
IdentityModelEventSource.Logger.LogLevel = originalLogLevel;
}

TestUtilities.AssertFailIfErrors(context);
}

public static TheoryData<AuthenticatedEncryptionTheoryData> DecryptTheoryData()
{
var theoryData = new TheoryData<AuthenticatedEncryptionTheoryData>();
Expand Down