From 195d9796841eb30e4370b71e3ec4e691a4c4d746 Mon Sep 17 00:00:00 2001 From: support Date: Mon, 23 Nov 2026 05:54:50 +0100 Subject: [PATCH 1/2] Two-factor e-mail code: draw it from a secure source and accept it once The e-mail sign-in code came from System.Random, was compared with string equality and stayed valid for its whole 30 minutes after it had been used. The code is now drawn with RandomNumberGenerator, compared in constant time, and cleared once it signs in, so the same code cannot sign in again. --- .../TwoFactorAuthenticationService.cs | 21 +++++-- .../TwoFactorAuthenticationServiceTests.cs | 58 ++++++++++++++++++- 2 files changed, 74 insertions(+), 5 deletions(-) diff --git a/src/Business/Grand.Business.Authentication/Services/TwoFactorAuthenticationService.cs b/src/Business/Grand.Business.Authentication/Services/TwoFactorAuthenticationService.cs index 19826e36f..95fa7037f 100644 --- a/src/Business/Grand.Business.Authentication/Services/TwoFactorAuthenticationService.cs +++ b/src/Business/Grand.Business.Authentication/Services/TwoFactorAuthenticationService.cs @@ -6,6 +6,8 @@ using Grand.Domain.Customers; using Grand.Domain.Localization; using Grand.Domain.Stores; +using System.Security.Cryptography; +using System.Text; namespace Grand.Business.Authentication.Services; @@ -35,11 +37,17 @@ public virtual async Task AuthenticateTwoFactor(string secretKey, string t case TwoFactorAuthenticationType.EmailVerification: var customerToken = customer.GetUserFieldFromEntity(SystemCustomerFieldNames.TwoFactorValidCode); - if (customerToken != token?.Trim()) + if (string.IsNullOrEmpty(customerToken) || !CodesMatch(customerToken, token?.Trim())) return false; var validUntil = customer.GetUserFieldFromEntity(SystemCustomerFieldNames.TwoFactorCodeValidUntil); - return validUntil >= DateTime.UtcNow; + if (validUntil < DateTime.UtcNow) + return false; + + //a code signs in once + await _customerService.UpdateUserField(customer, SystemCustomerFieldNames.TwoFactorValidCode, + string.Empty); + return true; case TwoFactorAuthenticationType.SMSVerification: if (!_smsVerificationService.Any()) @@ -88,7 +96,12 @@ await _customerService.UpdateUserField(customer, SystemCustomerFieldNames.TwoFac private static string PrepareRandomCode() { - var generator = new Random(); - return generator.Next(0, 999999).ToString("D6"); + return RandomNumberGenerator.GetInt32(1_000_000).ToString("D6"); + } + + private static bool CodesMatch(string expected, string given) + { + return given != null && + CryptographicOperations.FixedTimeEquals(Encoding.UTF8.GetBytes(expected), Encoding.UTF8.GetBytes(given)); } } \ No newline at end of file diff --git a/src/Tests/Grand.Business.Authentication.Tests/Services/TwoFactorAuthenticationServiceTests.cs b/src/Tests/Grand.Business.Authentication.Tests/Services/TwoFactorAuthenticationServiceTests.cs index 4e2b978b6..0beb33bf5 100644 --- a/src/Tests/Grand.Business.Authentication.Tests/Services/TwoFactorAuthenticationServiceTests.cs +++ b/src/Tests/Grand.Business.Authentication.Tests/Services/TwoFactorAuthenticationServiceTests.cs @@ -1,9 +1,11 @@ using Grand.Business.Authentication.Services; using Grand.Business.Core.Interfaces.Authentication; using Grand.Business.Core.Interfaces.Customers; +using Grand.Domain.Common; using Grand.Domain.Customers; using Grand.Domain.Localization; using Grand.Domain.Stores; +using Grand.SharedKernel.Extensions; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; @@ -47,4 +49,58 @@ public async Task GenerateCodeSetupTest_Email() //Assert Assert.IsTrue(result.CustomValues.ContainsKey("Token")); } -} \ No newline at end of file + + private static Customer CustomerWithCode(string code, DateTime validUntil) + { + var customer = new Customer(); + customer.UserFields.Add(new UserField { Key = SystemCustomerFieldNames.TwoFactorValidCode, Value = code, StoreId = "" }); + customer.UserFields.Add(new UserField { + Key = SystemCustomerFieldNames.TwoFactorCodeValidUntil, //stored the way UpdateUserField stores it + Value = CommonHelper.To(validUntil), StoreId = "" + }); + return customer; + } + + [TestMethod] + public async Task EmailCode_Correct_SignsIn_AndIsUsedUp() + { + var customer = CustomerWithCode("123456", DateTime.UtcNow.AddMinutes(10)); + + Assert.IsTrue(await _twoFactorAuthenticationService.AuthenticateTwoFactor(null, " 123456 ", customer, + TwoFactorAuthenticationType.EmailVerification)); + _customerServiceMock.Verify(x => x.UpdateUserField(customer, SystemCustomerFieldNames.TwoFactorValidCode, + string.Empty, It.IsAny()), Times.Once); + } + + [TestMethod] + [DataRow("654321")] + [DataRow("")] + [DataRow(null)] + public async Task EmailCode_Wrong_Refused(string given) + { + var customer = CustomerWithCode("123456", DateTime.UtcNow.AddMinutes(10)); + + Assert.IsFalse(await _twoFactorAuthenticationService.AuthenticateTwoFactor(null, given, customer, + TwoFactorAuthenticationType.EmailVerification)); + _customerServiceMock.Verify(x => x.UpdateUserField(It.IsAny(), It.IsAny(), + It.IsAny(), It.IsAny()), Times.Never); + } + + [TestMethod] + public async Task EmailCode_UsedUp_Refused() + { + var customer = CustomerWithCode("", DateTime.UtcNow.AddMinutes(10)); + + Assert.IsFalse(await _twoFactorAuthenticationService.AuthenticateTwoFactor(null, "", customer, + TwoFactorAuthenticationType.EmailVerification)); + } + + [TestMethod] + public async Task EmailCode_Expired_Refused() + { + var customer = CustomerWithCode("123456", DateTime.UtcNow.AddMinutes(-1)); + + Assert.IsFalse(await _twoFactorAuthenticationService.AuthenticateTwoFactor(null, "123456", customer, + TwoFactorAuthenticationType.EmailVerification)); + } +} From 347eb9a08134d6e9367cb22e4f2d396bb06262b3 Mon Sep 17 00:00:00 2001 From: support Date: Mon, 23 Nov 2026 07:25:00 +0100 Subject: [PATCH 2/2] Two-factor e-mail code: read it again and clear it under a lock The code was checked against the customer the request had loaded and cleared afterwards, so two requests with the same code that arrived together could both pass before either cleared it. The check now takes a lock on the customer's code, reads the code again from the database and clears it before letting go, so only one of them signs in. --- .../TwoFactorAuthenticationService.cs | 40 +++++++++++------ .../TwoFactorAuthenticationServiceTests.cs | 45 +++++++++++++++++-- 2 files changed, 68 insertions(+), 17 deletions(-) diff --git a/src/Business/Grand.Business.Authentication/Services/TwoFactorAuthenticationService.cs b/src/Business/Grand.Business.Authentication/Services/TwoFactorAuthenticationService.cs index 95fa7037f..f8ea4aa56 100644 --- a/src/Business/Grand.Business.Authentication/Services/TwoFactorAuthenticationService.cs +++ b/src/Business/Grand.Business.Authentication/Services/TwoFactorAuthenticationService.cs @@ -2,6 +2,7 @@ using Grand.Business.Core.Interfaces.Authentication; using Grand.Business.Core.Interfaces.Customers; using Grand.Business.Core.Utilities.Authentication; +using Grand.Data; using Grand.Domain.Common; using Grand.Domain.Customers; using Grand.Domain.Localization; @@ -16,13 +17,16 @@ public class TwoFactorAuthenticationService : ITwoFactorAuthenticationService private readonly IEnumerable _smsVerificationService; private readonly TwoFactorAuthenticator _twoFactorAuthentication; private readonly ICustomerService _customerService; + private readonly IResourceLock _resourceLock; public TwoFactorAuthenticationService( ICustomerService customerService, - IEnumerable smsVerificationService) + IEnumerable smsVerificationService, + IResourceLock resourceLock) { _customerService = customerService; _smsVerificationService = smsVerificationService; + _resourceLock = resourceLock; _twoFactorAuthentication = new TwoFactorAuthenticator(); } @@ -35,19 +39,7 @@ public virtual async Task AuthenticateTwoFactor(string secretKey, string t return _twoFactorAuthentication.ValidateTwoFactorPIN(secretKey, token.Trim()); case TwoFactorAuthenticationType.EmailVerification: - var customerToken = - customer.GetUserFieldFromEntity(SystemCustomerFieldNames.TwoFactorValidCode); - if (string.IsNullOrEmpty(customerToken) || !CodesMatch(customerToken, token?.Trim())) - return false; - var validUntil = - customer.GetUserFieldFromEntity(SystemCustomerFieldNames.TwoFactorCodeValidUntil); - if (validUntil < DateTime.UtcNow) - return false; - - //a code signs in once - await _customerService.UpdateUserField(customer, SystemCustomerFieldNames.TwoFactorValidCode, - string.Empty); - return true; + return await UseEmailCode(customer, token?.Trim()); case TwoFactorAuthenticationType.SMSVerification: if (!_smsVerificationService.Any()) @@ -94,6 +86,26 @@ await _customerService.UpdateUserField(customer, SystemCustomerFieldNames.TwoFac return model; } + //a code signs in once: it is read again and cleared under a lock, so two requests with it cannot both pass + private async Task UseEmailCode(Customer customer, string token) + { + await using var _ = await _resourceLock.Acquire([$"TwoFactorCode:{customer.Id}"]); + + var current = await _customerService.GetCustomerById(customer.Id); + if (current == null) + return false; + + var customerToken = current.GetUserFieldFromEntity(SystemCustomerFieldNames.TwoFactorValidCode); + if (string.IsNullOrEmpty(customerToken) || !CodesMatch(customerToken, token)) + return false; + var validUntil = current.GetUserFieldFromEntity(SystemCustomerFieldNames.TwoFactorCodeValidUntil); + if (validUntil < DateTime.UtcNow) + return false; + + await _customerService.UpdateUserField(current, SystemCustomerFieldNames.TwoFactorValidCode, string.Empty); + return true; + } + private static string PrepareRandomCode() { return RandomNumberGenerator.GetInt32(1_000_000).ToString("D6"); diff --git a/src/Tests/Grand.Business.Authentication.Tests/Services/TwoFactorAuthenticationServiceTests.cs b/src/Tests/Grand.Business.Authentication.Tests/Services/TwoFactorAuthenticationServiceTests.cs index 0beb33bf5..9c87594c3 100644 --- a/src/Tests/Grand.Business.Authentication.Tests/Services/TwoFactorAuthenticationServiceTests.cs +++ b/src/Tests/Grand.Business.Authentication.Tests/Services/TwoFactorAuthenticationServiceTests.cs @@ -1,6 +1,7 @@ using Grand.Business.Authentication.Services; using Grand.Business.Core.Interfaces.Authentication; using Grand.Business.Core.Interfaces.Customers; +using Grand.Data; using Grand.Domain.Common; using Grand.Domain.Customers; using Grand.Domain.Localization; @@ -17,14 +18,18 @@ public class TwoFactorAuthenticationServiceTests private Mock> _sMsVerificationService; private TwoFactorAuthenticationService _twoFactorAuthenticationService; private Mock _customerServiceMock; + private Mock _resourceLockMock; [TestInitialize] public void Init() { _customerServiceMock = new Mock(); _sMsVerificationService = new Mock>(); + _resourceLockMock = new Mock(); + _resourceLockMock.Setup(x => x.Acquire(It.IsAny>(), It.IsAny())) + .ReturnsAsync(Mock.Of()); _twoFactorAuthenticationService = new TwoFactorAuthenticationService( - _customerServiceMock.Object, _sMsVerificationService.Object); + _customerServiceMock.Object, _sMsVerificationService.Object, _resourceLockMock.Object); } [TestMethod] @@ -50,9 +55,17 @@ public async Task GenerateCodeSetupTest_Email() Assert.IsTrue(result.CustomValues.ContainsKey("Token")); } - private static Customer CustomerWithCode(string code, DateTime validUntil) + //the service reads the code again from the database, so the stored customer is what the mock returns + private Customer CustomerWithCode(string code, DateTime validUntil) { - var customer = new Customer(); + var stored = NewCustomerWithCode(code, validUntil); + _customerServiceMock.Setup(x => x.GetCustomerById(stored.Id)).ReturnsAsync(stored); + return stored; + } + + private static Customer NewCustomerWithCode(string code, DateTime validUntil) + { + var customer = new Customer { Id = "c1" }; customer.UserFields.Add(new UserField { Key = SystemCustomerFieldNames.TwoFactorValidCode, Value = code, StoreId = "" }); customer.UserFields.Add(new UserField { Key = SystemCustomerFieldNames.TwoFactorCodeValidUntil, //stored the way UpdateUserField stores it @@ -103,4 +116,30 @@ public async Task EmailCode_Expired_Refused() Assert.IsFalse(await _twoFactorAuthenticationService.AuthenticateTwoFactor(null, "123456", customer, TwoFactorAuthenticationType.EmailVerification)); } + + [TestMethod] + public async Task EmailCode_UsedUpByAnotherRequest_Refused() + { + //the request still holds the customer it loaded before another request used the code + var loaded = NewCustomerWithCode("123456", DateTime.UtcNow.AddMinutes(10)); + _customerServiceMock.Setup(x => x.GetCustomerById(loaded.Id)) + .ReturnsAsync(NewCustomerWithCode("", DateTime.UtcNow.AddMinutes(10))); + + Assert.IsFalse(await _twoFactorAuthenticationService.AuthenticateTwoFactor(null, "123456", loaded, + TwoFactorAuthenticationType.EmailVerification)); + _customerServiceMock.Verify(x => x.UpdateUserField(It.IsAny(), It.IsAny(), + It.IsAny(), It.IsAny()), Times.Never); + } + + [TestMethod] + public async Task EmailCode_CheckedAndUsedUpUnderTheCustomersLock() + { + var customer = CustomerWithCode("123456", DateTime.UtcNow.AddMinutes(10)); + + await _twoFactorAuthenticationService.AuthenticateTwoFactor(null, "123456", customer, + TwoFactorAuthenticationType.EmailVerification); + + _resourceLockMock.Verify(x => x.Acquire(It.Is>(k => k.Single() == "TwoFactorCode:c1"), + It.IsAny()), Times.Once); + } }