Skip to content

Avoid byte[] allocations as part of byte[] comparisons #2158

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

Merged
merged 3 commits into from
Jul 26, 2023
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
1 change: 1 addition & 0 deletions build/dependencies.props
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
<SystemSecurityCryptographyCngVersion>4.5.0</SystemSecurityCryptographyCngVersion>
<SystemTextJson>4.7.2</SystemTextJson>
<SystemTextEncodingsWeb>4.7.2</SystemTextEncodingsWeb>
<SystemMemoryVersion>4.5.5</SystemMemoryVersion>
</PropertyGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
<Reference Include="Microsoft.CSharp" />
<Reference Include="System" />
<Reference Include="System.Core" />
<PackageReference Include="System.Memory" Version="$(SystemMemoryVersion)" />
</ItemGroup>

<ItemGroup Condition="'$(TargetFrameworkIdentifier)' != 'NETCoreApp'">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using Microsoft.IdentityModel.Logging;

Expand Down Expand Up @@ -289,6 +291,9 @@ public override bool Verify(byte[] input, int inputOffset, int inputLength, byte
/// <param name="signatureLength">how many bytes to verfiy.</param>
/// <param name="algorithm">algorithm passed by AuthenticatedEncryptionProvider.</param>
/// <returns>true if computed signature matches the signature parameter, false otherwise.</returns>
#if NET6_0_OR_GREATER
[SkipLocalsInit]
#endif
internal bool Verify(byte[] input, int inputOffset, int inputLength, byte[] signature, int signatureOffset, int signatureLength, string algorithm)
{
if (input == null || input.Length == 0)
Expand Down Expand Up @@ -377,7 +382,17 @@ internal bool Verify(byte[] input, int inputOffset, int inputLength, byte[] sign
try
{
keyedHashAlgorithm = GetKeyedHashAlgorithm(GetKeyBytes(Key), Algorithm);
return Utility.AreEqual(signature, keyedHashAlgorithm.ComputeHash(input, inputOffset, inputLength), signatureLength);

scoped Span<byte> hash;
#if NET6_0_OR_GREATER
hash = stackalloc byte[keyedHashAlgorithm.HashSize / 8]; // only known algorithms are used, all of which have a small enough hash size to stackalloc
keyedHashAlgorithm.TryComputeHash(input.AsSpan(inputOffset, inputLength), hash, out int bytesWritten);
Debug.Assert(bytesWritten == hash.Length);
#else
hash = keyedHashAlgorithm.ComputeHash(input, inputOffset, inputLength).AsSpan();
#endif

return Utility.AreEqual(signature, hash, signatureLength);
}
catch
{
Expand Down
52 changes: 21 additions & 31 deletions src/Microsoft.IdentityModel.Tokens/Utility.cs
Original file line number Diff line number Diff line change
Expand Up @@ -133,27 +133,25 @@ public static bool IsHttps(Uri uri)
/// <returns>
/// true if the bytes are equal, false otherwise.
/// </returns>
[MethodImpl(MethodImplOptions.NoOptimization | MethodImplOptions.NoInlining)]
[MethodImpl(MethodImplOptions.NoInlining)]
public static bool AreEqual(byte[] a, byte[] b)
{
byte[] s_bytesA = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 };
byte[] s_bytesB = new byte[] { 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 };

int result = 0;
byte[] a1, a2;
ReadOnlySpan<byte> a1, a2;

if (((a == null) || (b == null))
|| (a.Length != b.Length))
{
a1 = s_bytesA;
a2 = s_bytesB;
// Non-allocating. The direct assignment into a ReadOnlySpan<byte> causes the C# compiler to emit these as pointers into the assembly's data section.
a1 = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 };
a2 = new byte[] { 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 };
}
else
{
a1 = a;
a2 = b;
a1 = a.AsSpan();
a2 = b.AsSpan();
}

int result = 0;
for (int i = 0; i < a1.Length; i++)
{
result |= a1[i] ^ a2[i];
Expand All @@ -163,7 +161,7 @@ public static bool AreEqual(byte[] a, byte[] b)
}

/// <summary>
/// Compares two byte arrays for equality. Hash size is fixed normally it is 32 bytes.
/// Compares two byte spans for equality. Hash size is fixed normally it is 32 bytes.
/// The attempt here is to take the same time if an attacker shortens the signature OR changes some of the signed contents.
/// </summary>
/// <param name="a">
Expand All @@ -172,37 +170,29 @@ public static bool AreEqual(byte[] a, byte[] b)
/// <param name="b">
/// The other set of bytes to compare with.
/// </param>
/// <param name="length">length of array to check</param>
/// <param name="length">length of spans to check</param>
/// <returns>
/// true if the bytes are equal, false otherwise.
/// </returns>
[MethodImpl(MethodImplOptions.NoOptimization | MethodImplOptions.NoInlining)]
internal static bool AreEqual(byte[] a, byte[] b, int length)
[MethodImpl(MethodImplOptions.NoInlining)]
internal static bool AreEqual(ReadOnlySpan<byte> a, ReadOnlySpan<byte> b, int length)
{
byte[] s_bytesA = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 };
byte[] s_bytesB = new byte[] { 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 };

int result = 0;
int lenToUse = 0;
byte[] a1, a2;

if (((a == null) || (b == null))
|| (a.Length < length || b.Length < length))
if ((a.Length < length || b.Length < length))
{
a1 = s_bytesA;
a2 = s_bytesB;
lenToUse = a1.Length;
// Non-allocating. The direct assignment into a ReadOnlySpan<byte> causes the C# compiler to emit these as pointers into the assembly's data section.
a = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 };
b = new byte[] { 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 };
}
else
{
a1 = a;
a2 = b;
lenToUse = length;
a = a.Slice(0, length);
b = b.Slice(0, length);
}

for (int i = 0; i < lenToUse; i++)
int result = 0;
for (int i = 0; i < a.Length; i++)
{
result |= a1[i] ^ a2[i];
result |= a[i] ^ b[i];
}

return result == 0;
Expand Down