Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
25 changes: 25 additions & 0 deletions src/Neo.Extensions/StringExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,5 +43,30 @@ public static int GetVarSize(this string value)
var size = Utility.StrictUTF8.GetByteCount(value);
return UnsafeData.GetVarSize(size) + size;
}

/// <summary>
/// Compares two <see cref="string"/>s for equality in constant time.
/// </summary>
/// <param name="left">The left <see cref="string"/>.</param>
/// <param name="right">The right <see cref="string"/>.</param>
/// <returns>True if the two <see cref="string"/>s are equal, false otherwise.</returns>
public static bool ConstantTimeEquals(this string left, string right)
{
if (left == null && right == null)
return true;

if (left == null || right == null)
return false;

if (left.Length != right.Length)
return false;

var lhs = left.AsSpan();
var rhs = right.AsSpan();
var result = 0;
for (var i = 0; i < lhs.Length; i++)
result |= lhs[i] ^ rhs[i];
return result == 0;
}
}
}
3 changes: 2 additions & 1 deletion src/Plugins/RpcServer/RpcServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
using Microsoft.AspNetCore.ResponseCompression;
using Microsoft.AspNetCore.Server.Kestrel.Https;
using Microsoft.Extensions.DependencyInjection;
using Neo.Extensions;
using Neo.Json;
using Neo.Network.P2P;
using System;
Expand Down Expand Up @@ -79,7 +80,7 @@ internal bool CheckAuth(HttpContext context)
if (authvalues.Length < 2)
return false;

return authvalues[0] == settings.RpcUser && authvalues[1] == settings.RpcPass;
return authvalues[0].ConstantTimeEquals(settings.RpcUser) && authvalues[1].ConstantTimeEquals(settings.RpcPass);
}

private static JObject CreateErrorResponse(JToken id, RpcError rpcError)
Expand Down
24 changes: 24 additions & 0 deletions tests/Neo.Extensions.Tests/UT_StringExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,5 +42,29 @@ public void TestGetVarSizeString()
int result = "AA".GetVarSize();
Assert.AreEqual(3, result);
}

[TestMethod]
public void TestConstantTimeEquals()
{
string str1 = "AA";
string str2 = "AA";
str1.ConstantTimeEquals(str2).Should().BeTrue();

str1 = "AB";
str2 = "AA";
str1.ConstantTimeEquals(str2).Should().BeFalse();

str1 = "AB";
str2 = null;
str1.ConstantTimeEquals(str2).Should().BeFalse();

str1 = null;
str2 = "AA";
str1.ConstantTimeEquals(str2).Should().BeFalse();

str1 = null;
str2 = null;
str1.ConstantTimeEquals(str2).Should().BeTrue();
}
}
}
Loading