From 127bd649b37cb574fb6b2b9ab781e75af91dec42 Mon Sep 17 00:00:00 2001 From: support Date: Mon, 23 Nov 2026 06:04:05 +0100 Subject: [PATCH 1/2] Limit the wrong two-factor codes one sign-in may try After the password step, the second step accepted any number of codes in the same session, so a six-digit code could be guessed by trying them in turn, in the storefront and in the panels. After five wrong codes the waiting sign-in is dropped and the customer signs in with the password again. The count starts again on each password step and after a code passes. --- .../LoginControllerTwoFactorTests.cs | 36 ++++++++++++++++++ .../Controllers/BaseLoginController.cs | 7 +++- .../Extensions/SessionExtensions.cs | 34 +++++++++++++++++ .../App_Data/Resources/DefaultLanguage.xml | Bin 1838394 -> 1838696 bytes .../App_Data/Resources/Upgrade/en_250.xml | 3 ++ .../Controllers/AccountController.cs | 8 +++- 6 files changed, 85 insertions(+), 3 deletions(-) diff --git a/src/Tests/Grand.Web.Admin.Tests/Controllers/LoginControllerTwoFactorTests.cs b/src/Tests/Grand.Web.Admin.Tests/Controllers/LoginControllerTwoFactorTests.cs index ef497e5158..3cc09a01b6 100644 --- a/src/Tests/Grand.Web.Admin.Tests/Controllers/LoginControllerTwoFactorTests.cs +++ b/src/Tests/Grand.Web.Admin.Tests/Controllers/LoginControllerTwoFactorTests.cs @@ -137,4 +137,40 @@ public async Task SecondStep_WithoutPasswordStep_BackToThePanelLogin() Assert.AreEqual("AdminLogin", result.RouteName); _authentication.Verify(x => x.SignIn(It.IsAny(), It.IsAny()), Times.Never); } + + [TestMethod] + public async Task SecondStep_TooManyWrongCodes_SignInMustStartAgain() + { + await PasswordStep(); + var twoFactor = new Mock(); + twoFactor.Setup(x => x.AuthenticateTwoFactor(It.IsAny(), "123456", _customer, It.IsAny())) + .ReturnsAsync(true); + + for (var i = 0; i < Grand.Web.Common.Extensions.SessionExtensions.MaxWrongTwoFactorCodes; i++) + Assert.IsInstanceOfType(await _controller.TwoFactorAuthorization("000000", twoFactor.Object)); + + //the right code no longer helps: the password step has to be done again + var result = (RedirectToRouteResult)await _controller.TwoFactorAuthorization("123456", twoFactor.Object); + + Assert.AreEqual("AdminLogin", result.RouteName); + _authentication.Verify(x => x.SignIn(It.IsAny(), It.IsAny()), Times.Never); + } + + [TestMethod] + public async Task SecondStep_WrongCodesBelowTheLimit_RightCodeStillSignsIn() + { + await PasswordStep(); + var twoFactor = new Mock(); + twoFactor.Setup(x => x.AuthenticateTwoFactor(It.IsAny(), "123456", _customer, It.IsAny())) + .ReturnsAsync(true); + + for (var i = 1; i < Grand.Web.Common.Extensions.SessionExtensions.MaxWrongTwoFactorCodes; i++) + await _controller.TwoFactorAuthorization("000000", twoFactor.Object); + + await _controller.TwoFactorAuthorization("123456", twoFactor.Object); + + _authentication.Verify(x => x.SignIn(_customer, false), Times.Once); + Assert.IsFalse(_session.Keys.Any()); + } } + diff --git a/src/Web/Grand.Web.AdminShared/Controllers/BaseLoginController.cs b/src/Web/Grand.Web.AdminShared/Controllers/BaseLoginController.cs index 4b9f6e0f93..3e44729ff5 100644 --- a/src/Web/Grand.Web.AdminShared/Controllers/BaseLoginController.cs +++ b/src/Web/Grand.Web.AdminShared/Controllers/BaseLoginController.cs @@ -12,6 +12,7 @@ using Grand.Web.AdminShared.Models.Common; using Grand.Web.Common.Controllers; using Grand.Mediator; +using Grand.Web.Common.Extensions; using Grand.Web.Common.Security.Authentication; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; @@ -122,6 +123,7 @@ await _customerManagerService.LoginCustomer( var userName = _customerSettings.UsernamesEnabled ? model.Username : model.Email; //the panel's own second step: the storefront's page would sign in on the storefront HttpContext.Session.SetString(TwoFactorSessionKey, userName!); + HttpContext.Session.ResetWrongTwoFactorCodes(TwoFactorSessionKey); return RedirectToAction(nameof(TwoFactorAuthorization), "Login", new { area = GetCurrentArea() }); } } @@ -295,12 +297,15 @@ public async Task TwoFactorAuthorization(string token, { //remove session HttpContext.Session.Remove(TwoFactorSessionKey); + HttpContext.Session.ResetWrongTwoFactorCodes(TwoFactorSessionKey); //sign in return await SignInAction(customer, false); } - ModelState.AddModelError("", _translationService.GetResource("Account.TwoFactorAuth.WrongSecurityCode")); + ModelState.AddModelError("", HttpContext.Session.CountWrongTwoFactorCode(TwoFactorSessionKey) + ? _translationService.GetResource("Account.TwoFactorAuth.TooManyWrongCodes") + : _translationService.GetResource("Account.TwoFactorAuth.WrongSecurityCode")); } await _mediator.Publish(new CustomerLoginFailedEvent(customer, diff --git a/src/Web/Grand.Web.Common/Extensions/SessionExtensions.cs b/src/Web/Grand.Web.Common/Extensions/SessionExtensions.cs index bf20dbfba7..f7d0bbca10 100644 --- a/src/Web/Grand.Web.Common/Extensions/SessionExtensions.cs +++ b/src/Web/Grand.Web.Common/Extensions/SessionExtensions.cs @@ -32,4 +32,38 @@ public static T Get(this ISession session, string key) var value = session.GetString(key); return value == null ? default : JsonSerializer.Deserialize(value); } + + /// + /// Wrong codes one password sign-in may try before it has to start again + /// + public const int MaxWrongTwoFactorCodes = 5; + + /// + /// Counts a wrong code for the sign-in waiting under the key; at the limit the waiting sign-in is dropped + /// + /// Session + /// Key that holds the sign-in waiting for its code + /// Whether the waiting sign-in was dropped + public static bool CountWrongTwoFactorCode(this ISession session, string key) + { + var countKey = key + "WrongCodes"; + var count = (session.GetInt32(countKey) ?? 0) + 1; + if (count < MaxWrongTwoFactorCodes) + { + session.SetInt32(countKey, count); + return false; + } + + session.Remove(key); + session.Remove(countKey); + return true; + } + + /// + /// Starts the count of wrong codes again, for a new sign-in or one that has passed + /// + public static void ResetWrongTwoFactorCodes(this ISession session, string key) + { + session.Remove(key + "WrongCodes"); + } } \ No newline at end of file diff --git a/src/Web/Grand.Web/App_Data/Resources/DefaultLanguage.xml b/src/Web/Grand.Web/App_Data/Resources/DefaultLanguage.xml index 889fadc80c7b4b6acf3dc631e2955ef43b42e05e..1b82379be080d08e12e1f85c138f504ebb3f6574 100644 GIT binary patch delta 215 zcmdlrtKh|)f`%=Oe(K^S4EaEq%aF*B$56>o&QJv80pLThIF7t1t6U_+3;uKbO$*`nRY*QMj&PaVrC#_0b*7lW&>h& zAm#vKP9Ww2Vs0Sj0b*Vt<^y7WAQk{(K_C_aVqqW_0b)@g76W2&AeI1PNg$Tm?x!yO G<|zPst2!e9 delta 121 zcmWN=#|eNi06 Cycle + + Too many wrong security codes. Sign in again. + diff --git a/src/Web/Grand.Web/Controllers/AccountController.cs b/src/Web/Grand.Web/Controllers/AccountController.cs index 13d0b146fd..e000724673 100644 --- a/src/Web/Grand.Web/Controllers/AccountController.cs +++ b/src/Web/Grand.Web/Controllers/AccountController.cs @@ -32,6 +32,7 @@ using Microsoft.AspNetCore.Mvc; using System.Security.Cryptography; using Grand.Web.Common.Localization; +using static Grand.Web.Common.Extensions.SessionExtensions; namespace Grand.Web.Controllers; @@ -256,6 +257,7 @@ await _customerManagerService.LoginCustomer( { var userName = _customerSettings.UsernamesEnabled ? model.Username : model.Email; HttpContext.Session.SetString("RequiresTwoFactor", userName); + HttpContext.Session.ResetWrongTwoFactorCodes("RequiresTwoFactor"); //the sign-in that follows the code must still go where the login was asked to go if (!string.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl)) HttpContext.Session.SetString("RequiresTwoFactorReturnUrl", returnUrl); @@ -340,6 +342,7 @@ public async Task TwoFactorAuthorization(string token, { //remove session HttpContext.Session.Remove("RequiresTwoFactor"); + HttpContext.Session.ResetWrongTwoFactorCodes("RequiresTwoFactor"); var returnUrl = HttpContext.Session.GetString("RequiresTwoFactorReturnUrl"); HttpContext.Session.Remove("RequiresTwoFactorReturnUrl"); @@ -347,8 +350,9 @@ public async Task TwoFactorAuthorization(string token, return await SignInAction(customer, false, returnUrl); } - ModelState.AddModelError("", - _translationService.GetResource("Account.TwoFactorAuth.WrongSecurityCode")); + ModelState.AddModelError("", HttpContext.Session.CountWrongTwoFactorCode("RequiresTwoFactor") + ? _translationService.GetResource("Account.TwoFactorAuth.TooManyWrongCodes") + : _translationService.GetResource("Account.TwoFactorAuth.WrongSecurityCode")); } await _mediator.Publish(new CustomerLoginFailedEvent(customer, From 6eae24327dbe61832d0c1055f489a0ec06b7c12a Mon Sep 17 00:00:00 2001 From: support Date: Mon, 23 Nov 2026 07:38:25 +0100 Subject: [PATCH 2/2] Count wrong two-factor codes on the customer and lock out, not in the session The limit lived in the session: parallel requests of one sign-in each read the same count, and each password step started it again, so with an authenticator app the guessing went on in rounds of five. The second step also never looked at the login lockout. A new ITwoFactorSignInService checks the code under a lock on the customer, reads the customer again, refuses a locked-out one and counts wrong codes on the customer, where a new password step does not clear them. The fifth wrong code locks the customer out for the store's lockout length (30 minutes when none is set) and drops the waiting sign-in; the password step already refuses a locked-out customer. A code that passes clears the count. The storefront and the panels use it, and the session counter and its resource are gone. --- .../Services/TwoFactorSignInService.cs | 67 +++++++++ .../Startup/StartupApplication.cs | 1 + .../Authentication/ITwoFactorSignInService.cs | 15 ++ .../Authentication/TwoFactorSignInResult.cs | 15 ++ .../Customers/SystemCustomerFieldNames.cs | 1 + .../Services/TwoFactorSignInServiceTests.cs | 134 ++++++++++++++++++ .../LoginControllerTwoFactorTests.cs | 52 +++---- ...ccountControllerTwoFactorReturnUrlTests.cs | 7 +- .../Controllers/BaseLoginController.cs | 36 ++--- .../Extensions/SessionExtensions.cs | 34 ----- .../App_Data/Resources/DefaultLanguage.xml | Bin 1838696 -> 1838394 bytes .../App_Data/Resources/Upgrade/en_250.xml | 3 - .../Controllers/AccountController.cs | 37 ++--- 13 files changed, 287 insertions(+), 115 deletions(-) create mode 100644 src/Business/Grand.Business.Authentication/Services/TwoFactorSignInService.cs create mode 100644 src/Business/Grand.Business.Core/Interfaces/Authentication/ITwoFactorSignInService.cs create mode 100644 src/Business/Grand.Business.Core/Utilities/Authentication/TwoFactorSignInResult.cs create mode 100644 src/Tests/Grand.Business.Authentication.Tests/Services/TwoFactorSignInServiceTests.cs diff --git a/src/Business/Grand.Business.Authentication/Services/TwoFactorSignInService.cs b/src/Business/Grand.Business.Authentication/Services/TwoFactorSignInService.cs new file mode 100644 index 0000000000..50fea675dc --- /dev/null +++ b/src/Business/Grand.Business.Authentication/Services/TwoFactorSignInService.cs @@ -0,0 +1,67 @@ +using Grand.Business.Core.Events.Customers; +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.Mediator; + +namespace Grand.Business.Authentication.Services; + +public class TwoFactorSignInService( + ITwoFactorAuthenticationService twoFactorAuthenticationService, + ICustomerService customerService, + IResourceLock resourceLock, + IMediator mediator, + CustomerSettings customerSettings) : ITwoFactorSignInService +{ + /// + /// Wrong codes a customer may try before the second step locks them out + /// + public const int MaxWrongCodes = 5; + + //the installer's lockout length, for a store that set none + private const int DefaultLockoutMinutes = 30; + + public async Task CheckCode(Customer customer, string token, + TwoFactorAuthenticationType twoFactorAuthenticationType) + { + ArgumentNullException.ThrowIfNull(customer); + + //parallel requests of one sign-in would each read the same count + await using var _ = await resourceLock.Acquire([$"TwoFactorSignIn:{customer.Id}"]); + + var current = await customerService.GetCustomerById(customer.Id); + if (current == null || current.CannotLoginUntilDateUtc > DateTime.UtcNow) + return TwoFactorSignInResult.LockedOut; + + var wrongCodes = current.GetUserFieldFromEntity(SystemCustomerFieldNames.TwoFactorWrongCodes); + if (!string.IsNullOrEmpty(token) && await twoFactorAuthenticationService.AuthenticateTwoFactor( + current.GetUserFieldFromEntity(SystemCustomerFieldNames.TwoFactorSecretKey), token, current, + twoFactorAuthenticationType)) + { + if (wrongCodes > 0) + await customerService.UpdateUserField(current, SystemCustomerFieldNames.TwoFactorWrongCodes, 0); + return TwoFactorSignInResult.Passed; + } + + var lockedOut = ++wrongCodes >= MaxWrongCodes; + await customerService.UpdateUserField(current, SystemCustomerFieldNames.TwoFactorWrongCodes, + lockedOut ? 0 : wrongCodes); + if (lockedOut) + { + current.CannotLoginUntilDateUtc = DateTime.UtcNow.AddMinutes( + customerSettings.FailedPasswordLockoutMinutes > 0 + ? customerSettings.FailedPasswordLockoutMinutes + : DefaultLockoutMinutes); + await customerService.UpdateCustomerLastLoginDate(current); + } + + //published with the customer read under the lock: its handler writes the lockout fields back + await mediator.Publish(new CustomerLoginFailedEvent(current, + string.IsNullOrEmpty(token) ? "two-factor code missing" : "wrong two-factor code")); + + return lockedOut ? TwoFactorSignInResult.LockedOut : TwoFactorSignInResult.WrongCode; + } +} diff --git a/src/Business/Grand.Business.Authentication/Startup/StartupApplication.cs b/src/Business/Grand.Business.Authentication/Startup/StartupApplication.cs index c5886eb669..03d909f84c 100644 --- a/src/Business/Grand.Business.Authentication/Startup/StartupApplication.cs +++ b/src/Business/Grand.Business.Authentication/Startup/StartupApplication.cs @@ -15,6 +15,7 @@ public void ConfigureServices(IServiceCollection services, IConfiguration config { services.AddScoped(); services.AddScoped(); + services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); diff --git a/src/Business/Grand.Business.Core/Interfaces/Authentication/ITwoFactorSignInService.cs b/src/Business/Grand.Business.Core/Interfaces/Authentication/ITwoFactorSignInService.cs new file mode 100644 index 0000000000..38a7bbfc04 --- /dev/null +++ b/src/Business/Grand.Business.Core/Interfaces/Authentication/ITwoFactorSignInService.cs @@ -0,0 +1,15 @@ +using Grand.Business.Core.Utilities.Authentication; +using Grand.Domain.Customers; + +namespace Grand.Business.Core.Interfaces.Authentication; + +public interface ITwoFactorSignInService +{ + /// + /// Checks the code of a sign-in waiting for its second step. Checks of one customer run one at a time, a locked-out + /// customer is refused, and wrong codes are counted on the customer, so a new password step does not start the + /// count again: the last one allowed locks the customer out. + /// + Task CheckCode(Customer customer, string token, + TwoFactorAuthenticationType twoFactorAuthenticationType); +} diff --git a/src/Business/Grand.Business.Core/Utilities/Authentication/TwoFactorSignInResult.cs b/src/Business/Grand.Business.Core/Utilities/Authentication/TwoFactorSignInResult.cs new file mode 100644 index 0000000000..29e01dc12d --- /dev/null +++ b/src/Business/Grand.Business.Core/Utilities/Authentication/TwoFactorSignInResult.cs @@ -0,0 +1,15 @@ +namespace Grand.Business.Core.Utilities.Authentication; + +/// +/// The answer to the code of a sign-in waiting for its second step +/// +public enum TwoFactorSignInResult +{ + Passed, + WrongCode, + + /// + /// The customer is locked out, also when this code was the last wrong one allowed: the sign-in starts again later + /// + LockedOut +} diff --git a/src/Core/Grand.Domain/Customers/SystemCustomerFieldNames.cs b/src/Core/Grand.Domain/Customers/SystemCustomerFieldNames.cs index acf337638e..735bb1d8a5 100644 --- a/src/Core/Grand.Domain/Customers/SystemCustomerFieldNames.cs +++ b/src/Core/Grand.Domain/Customers/SystemCustomerFieldNames.cs @@ -34,6 +34,7 @@ public static class SystemCustomerFieldNames public static string TwoFactorSecretKey => "TwoFactorSecretKey"; public static string TwoFactorValidCode => "TwoFactorValidCode"; public static string TwoFactorCodeValidUntil => "TwoFactorValidCodeUntil"; + public static string TwoFactorWrongCodes => "TwoFactorWrongCodes"; public static string CurrencyId => "CurrencyId"; public static string LanguageId => "LanguageId"; diff --git a/src/Tests/Grand.Business.Authentication.Tests/Services/TwoFactorSignInServiceTests.cs b/src/Tests/Grand.Business.Authentication.Tests/Services/TwoFactorSignInServiceTests.cs new file mode 100644 index 0000000000..897090aec9 --- /dev/null +++ b/src/Tests/Grand.Business.Authentication.Tests/Services/TwoFactorSignInServiceTests.cs @@ -0,0 +1,134 @@ +using Grand.Business.Authentication.Services; +using Grand.Business.Core.Events.Customers; +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.Mediator; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Moq; + +namespace Grand.Business.Authentication.Tests.Services; + +[TestClass] +public class TwoFactorSignInServiceTests +{ + private const TwoFactorAuthenticationType Type = TwoFactorAuthenticationType.AppVerification; + + private Customer _stored; + private Mock _customerService; + private Mock _twoFactor; + private Mock _resourceLock; + private Mock _mediator; + private CustomerSettings _settings; + private TwoFactorSignInService _service; + + [TestInitialize] + public void Init() + { + _stored = new Customer { Id = "c1" }; + _customerService = new Mock(); + _customerService.Setup(x => x.GetCustomerById("c1")).ReturnsAsync(() => _stored); + //stores the field on the customer, as the real service does + _customerService.Setup(x => x.UpdateUserField(It.IsAny(), It.IsAny(), It.IsAny(), + It.IsAny())) + .Callback((Customer c, string key, int value, string _) => + { + foreach (var field in c.UserFields.Where(f => f.Key == key).ToList()) + c.UserFields.Remove(field); + c.UserFields.Add(new UserField { Key = key, Value = value.ToString(), StoreId = "" }); + }) + .Returns(Task.CompletedTask); + _twoFactor = new Mock(); + _twoFactor.Setup(x => x.AuthenticateTwoFactor(It.IsAny(), "123456", It.IsAny(), Type)) + .ReturnsAsync(true); + _resourceLock = new Mock(); + _resourceLock.Setup(x => x.Acquire(It.IsAny>(), It.IsAny())) + .ReturnsAsync(Mock.Of()); + _mediator = new Mock(); + _settings = new CustomerSettings { FailedPasswordLockoutMinutes = 30 }; + _service = new TwoFactorSignInService(_twoFactor.Object, _customerService.Object, _resourceLock.Object, + _mediator.Object, _settings); + } + + //the request's own copy, loaded before the check: the service must not trust it + private static Customer Loaded() => new() { Id = "c1" }; + + private int WrongCodes() => _stored.GetUserFieldFromEntity(SystemCustomerFieldNames.TwoFactorWrongCodes); + + [TestMethod] + public async Task RightCode_Passes() + { + Assert.AreEqual(TwoFactorSignInResult.Passed, await _service.CheckCode(Loaded(), "123456", Type)); + } + + [TestMethod] + public async Task WrongCode_CountedOnTheCustomer_AndReportedAsAFailedLogin() + { + Assert.AreEqual(TwoFactorSignInResult.WrongCode, await _service.CheckCode(Loaded(), "000000", Type)); + + Assert.AreEqual(1, WrongCodes()); + _mediator.Verify(x => x.Publish(It.Is(e => e.Customer == _stored), + It.IsAny()), Times.Once); + } + + [TestMethod] + public async Task LastWrongCodeAllowed_LocksTheCustomerOut() + { + for (var i = 1; i < TwoFactorSignInService.MaxWrongCodes; i++) + Assert.AreEqual(TwoFactorSignInResult.WrongCode, await _service.CheckCode(Loaded(), "000000", Type)); + + Assert.AreEqual(TwoFactorSignInResult.LockedOut, await _service.CheckCode(Loaded(), "000000", Type)); + + Assert.IsTrue(_stored.CannotLoginUntilDateUtc > DateTime.UtcNow.AddMinutes(29)); + _customerService.Verify(x => x.UpdateCustomerLastLoginDate(_stored), Times.Once); + Assert.AreEqual(0, WrongCodes()); + } + + [TestMethod] + public async Task LockedOutCustomer_RefusedEvenWithTheRightCode() + { + _stored.CannotLoginUntilDateUtc = DateTime.UtcNow.AddMinutes(5); + + Assert.AreEqual(TwoFactorSignInResult.LockedOut, await _service.CheckCode(Loaded(), "123456", Type)); + _twoFactor.Verify(x => x.AuthenticateTwoFactor(It.IsAny(), It.IsAny(), + It.IsAny(), It.IsAny()), Times.Never); + } + + [TestMethod] + public async Task CountSurvivesANewPasswordStep_OnlyAPassingCodeClearsIt() + { + //wrong codes of an earlier sign-in, kept on the customer + _stored.UserFields.Add(new UserField { + Key = SystemCustomerFieldNames.TwoFactorWrongCodes, Value = "3", StoreId = "" + }); + + Assert.AreEqual(TwoFactorSignInResult.WrongCode, await _service.CheckCode(Loaded(), "000000", Type)); + Assert.AreEqual(4, WrongCodes()); + + Assert.AreEqual(TwoFactorSignInResult.Passed, await _service.CheckCode(Loaded(), "123456", Type)); + Assert.AreEqual(0, WrongCodes()); + } + + [TestMethod] + public async Task NoLockoutLengthSet_StillLocksOut() + { + _settings.FailedPasswordLockoutMinutes = 0; + + for (var i = 0; i < TwoFactorSignInService.MaxWrongCodes; i++) + await _service.CheckCode(Loaded(), "000000", Type); + + Assert.IsTrue(_stored.CannotLoginUntilDateUtc > DateTime.UtcNow); + } + + [TestMethod] + public async Task CheckedUnderTheCustomersLock() + { + await _service.CheckCode(Loaded(), "123456", Type); + + _resourceLock.Verify(x => x.Acquire(It.Is>(k => k.Single() == "TwoFactorSignIn:c1"), + It.IsAny()), Times.Once); + } +} diff --git a/src/Tests/Grand.Web.Admin.Tests/Controllers/LoginControllerTwoFactorTests.cs b/src/Tests/Grand.Web.Admin.Tests/Controllers/LoginControllerTwoFactorTests.cs index 3cc09a01b6..e8a385deac 100644 --- a/src/Tests/Grand.Web.Admin.Tests/Controllers/LoginControllerTwoFactorTests.cs +++ b/src/Tests/Grand.Web.Admin.Tests/Controllers/LoginControllerTwoFactorTests.cs @@ -1,6 +1,7 @@ using Grand.Business.Core.Interfaces.Authentication; using Grand.Business.Core.Interfaces.Customers; using Grand.Business.Core.Interfaces.Messages; +using Grand.Business.Core.Utilities.Authentication; using Grand.Domain.Common; using Grand.Domain.Customers; using Grand.Domain.Stores; @@ -102,15 +103,21 @@ public async Task SecondStep_Get_ShowsTheForm() Assert.IsInstanceOfType(result); } + private static Mock CodeAnswers(TwoFactorSignInResult result) + { + var twoFactor = new Mock(); + twoFactor.Setup(x => x.CheckCode(It.IsAny(), It.IsAny(), It.IsAny())) + .ReturnsAsync(result); + return twoFactor; + } + [TestMethod] public async Task SecondStep_ValidCode_SignsInToThePanel() { await PasswordStep(); - var twoFactor = new Mock(); - twoFactor.Setup(x => x.AuthenticateTwoFactor(It.IsAny(), "123456", _customer, It.IsAny())) - .ReturnsAsync(true); - var result = (RedirectToRouteResult)await _controller.TwoFactorAuthorization("123456", twoFactor.Object); + var result = (RedirectToRouteResult)await _controller.TwoFactorAuthorization("123456", + CodeAnswers(TwoFactorSignInResult.Passed).Object); Assert.AreEqual("AdminIndex", result.RouteName); _authentication.Verify(x => x.SignIn(_customer, false), Times.Once); @@ -122,7 +129,8 @@ public async Task SecondStep_WrongCode_NotSignedIn() { await PasswordStep(); - var result = await _controller.TwoFactorAuthorization("000000", new Mock().Object); + var result = await _controller.TwoFactorAuthorization("000000", + CodeAnswers(TwoFactorSignInResult.WrongCode).Object); Assert.IsInstanceOfType(result); _authentication.Verify(x => x.SignIn(It.IsAny(), It.IsAny()), Times.Never); @@ -132,45 +140,25 @@ public async Task SecondStep_WrongCode_NotSignedIn() public async Task SecondStep_WithoutPasswordStep_BackToThePanelLogin() { var result = (RedirectToRouteResult)await _controller.TwoFactorAuthorization("123456", - new Mock().Object); + CodeAnswers(TwoFactorSignInResult.Passed).Object); Assert.AreEqual("AdminLogin", result.RouteName); _authentication.Verify(x => x.SignIn(It.IsAny(), It.IsAny()), Times.Never); } [TestMethod] - public async Task SecondStep_TooManyWrongCodes_SignInMustStartAgain() + public async Task SecondStep_LockedOut_SignInMustStartAgain() { await PasswordStep(); - var twoFactor = new Mock(); - twoFactor.Setup(x => x.AuthenticateTwoFactor(It.IsAny(), "123456", _customer, It.IsAny())) - .ReturnsAsync(true); - for (var i = 0; i < Grand.Web.Common.Extensions.SessionExtensions.MaxWrongTwoFactorCodes; i++) - Assert.IsInstanceOfType(await _controller.TwoFactorAuthorization("000000", twoFactor.Object)); + Assert.IsInstanceOfType(await _controller.TwoFactorAuthorization("000000", + CodeAnswers(TwoFactorSignInResult.LockedOut).Object)); - //the right code no longer helps: the password step has to be done again - var result = (RedirectToRouteResult)await _controller.TwoFactorAuthorization("123456", twoFactor.Object); + //the waiting sign-in is gone: even a code that passes goes back to the password step + var result = (RedirectToRouteResult)await _controller.TwoFactorAuthorization("123456", + CodeAnswers(TwoFactorSignInResult.Passed).Object); Assert.AreEqual("AdminLogin", result.RouteName); _authentication.Verify(x => x.SignIn(It.IsAny(), It.IsAny()), Times.Never); } - - [TestMethod] - public async Task SecondStep_WrongCodesBelowTheLimit_RightCodeStillSignsIn() - { - await PasswordStep(); - var twoFactor = new Mock(); - twoFactor.Setup(x => x.AuthenticateTwoFactor(It.IsAny(), "123456", _customer, It.IsAny())) - .ReturnsAsync(true); - - for (var i = 1; i < Grand.Web.Common.Extensions.SessionExtensions.MaxWrongTwoFactorCodes; i++) - await _controller.TwoFactorAuthorization("000000", twoFactor.Object); - - await _controller.TwoFactorAuthorization("123456", twoFactor.Object); - - _authentication.Verify(x => x.SignIn(_customer, false), Times.Once); - Assert.IsFalse(_session.Keys.Any()); - } } - diff --git a/src/Tests/Grand.Web.Tests/Controllers/AccountControllerTwoFactorReturnUrlTests.cs b/src/Tests/Grand.Web.Tests/Controllers/AccountControllerTwoFactorReturnUrlTests.cs index 8854f2b0a2..1990fb8569 100644 --- a/src/Tests/Grand.Web.Tests/Controllers/AccountControllerTwoFactorReturnUrlTests.cs +++ b/src/Tests/Grand.Web.Tests/Controllers/AccountControllerTwoFactorReturnUrlTests.cs @@ -1,5 +1,6 @@ using Grand.Business.Core.Events.Customers; using Grand.Business.Core.Interfaces.Authentication; +using Grand.Business.Core.Utilities.Authentication; using Grand.Business.Core.Interfaces.Common.Directory; using Grand.Business.Core.Interfaces.Customers; using Grand.Business.Core.Interfaces.Messages; @@ -68,9 +69,9 @@ private async Task PassTwoFactor(string returnUrl) { _manager.Setup(x => x.LoginCustomer("a@b.c", "p", It.IsAny(), SignInSurface.Storefront)).ReturnsAsync(CustomerLoginResults.RequiresTwoFactor); await _controller.Login(new LoginModel { Email = "a@b.c", Password = "p" }, returnUrl); - var twoFactor = new Mock(); - twoFactor.Setup(x => x.AuthenticateTwoFactor(It.IsAny(), "123", _customer, It.IsAny())) - .ReturnsAsync(true); + var twoFactor = new Mock(); + twoFactor.Setup(x => x.CheckCode(_customer, "123", It.IsAny())) + .ReturnsAsync(TwoFactorSignInResult.Passed); return await _controller.TwoFactorAuthorization("123", twoFactor.Object); } diff --git a/src/Web/Grand.Web.AdminShared/Controllers/BaseLoginController.cs b/src/Web/Grand.Web.AdminShared/Controllers/BaseLoginController.cs index 3e44729ff5..f9ef0166de 100644 --- a/src/Web/Grand.Web.AdminShared/Controllers/BaseLoginController.cs +++ b/src/Web/Grand.Web.AdminShared/Controllers/BaseLoginController.cs @@ -3,6 +3,7 @@ using Grand.Business.Core.Interfaces.Common.Directory; using Grand.Business.Core.Interfaces.Customers; using Grand.Business.Core.Interfaces.Messages; +using Grand.Business.Core.Utilities.Authentication; using Grand.Domain.Common; using Grand.Domain.Customers; using Grand.Infrastructure; @@ -12,7 +13,6 @@ using Grand.Web.AdminShared.Models.Common; using Grand.Web.Common.Controllers; using Grand.Mediator; -using Grand.Web.Common.Extensions; using Grand.Web.Common.Security.Authentication; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; @@ -123,7 +123,6 @@ await _customerManagerService.LoginCustomer( var userName = _customerSettings.UsernamesEnabled ? model.Username : model.Email; //the panel's own second step: the storefront's page would sign in on the storefront HttpContext.Session.SetString(TwoFactorSessionKey, userName!); - HttpContext.Session.ResetWrongTwoFactorCodes(TwoFactorSessionKey); return RedirectToAction(nameof(TwoFactorAuthorization), "Login", new { area = GetCurrentArea() }); } } @@ -269,7 +268,7 @@ await _customerMessageProviderService.SendCustomerEmailTokenValidationMessage(cu [HttpPost] public async Task TwoFactorAuthorization(string token, - [FromServices] ITwoFactorAuthenticationService twoFactorAuthenticationService) + [FromServices] ITwoFactorSignInService twoFactorSignInService) { if (!_customerSettings.TwoFactorAuthenticationEnabled) return RedirectToRoute($"{GetCurrentArea()}Login"); @@ -284,32 +283,27 @@ public async Task TwoFactorAuthorization(string token, if (customer == null) return RedirectToRoute($"{GetCurrentArea()}Login"); - if (string.IsNullOrEmpty(token)) - { - ModelState.AddModelError("", - _translationService.GetResource("Account.TwoFactorAuth.SecurityCodeIsRequired")); - } - else + switch (await twoFactorSignInService.CheckCode(customer, token, _customerSettings.TwoFactorAuthenticationType)) { - var secretKey = customer.GetUserFieldFromEntity(SystemCustomerFieldNames.TwoFactorSecretKey); - if (await twoFactorAuthenticationService.AuthenticateTwoFactor(secretKey, token, customer, - _customerSettings.TwoFactorAuthenticationType)) - { + case TwoFactorSignInResult.Passed: //remove session HttpContext.Session.Remove(TwoFactorSessionKey); - HttpContext.Session.ResetWrongTwoFactorCodes(TwoFactorSessionKey); //sign in return await SignInAction(customer, false); - } - - ModelState.AddModelError("", HttpContext.Session.CountWrongTwoFactorCode(TwoFactorSessionKey) - ? _translationService.GetResource("Account.TwoFactorAuth.TooManyWrongCodes") - : _translationService.GetResource("Account.TwoFactorAuth.WrongSecurityCode")); + case TwoFactorSignInResult.LockedOut: + //the waiting sign-in is dropped: it starts again with the password once the lockout ends + HttpContext.Session.Remove(TwoFactorSessionKey); + ModelState.AddModelError("", + _translationService.GetResource("Account.Login.WrongCredentials.LockedOut")); + break; + default: + ModelState.AddModelError("", _translationService.GetResource(string.IsNullOrEmpty(token) + ? "Account.TwoFactorAuth.SecurityCodeIsRequired" + : "Account.TwoFactorAuth.WrongSecurityCode")); + break; } - await _mediator.Publish(new CustomerLoginFailedEvent(customer, - string.IsNullOrEmpty(token) ? "two-factor code missing" : "wrong two-factor code")); return View(); } } \ No newline at end of file diff --git a/src/Web/Grand.Web.Common/Extensions/SessionExtensions.cs b/src/Web/Grand.Web.Common/Extensions/SessionExtensions.cs index f7d0bbca10..bf20dbfba7 100644 --- a/src/Web/Grand.Web.Common/Extensions/SessionExtensions.cs +++ b/src/Web/Grand.Web.Common/Extensions/SessionExtensions.cs @@ -32,38 +32,4 @@ public static T Get(this ISession session, string key) var value = session.GetString(key); return value == null ? default : JsonSerializer.Deserialize(value); } - - /// - /// Wrong codes one password sign-in may try before it has to start again - /// - public const int MaxWrongTwoFactorCodes = 5; - - /// - /// Counts a wrong code for the sign-in waiting under the key; at the limit the waiting sign-in is dropped - /// - /// Session - /// Key that holds the sign-in waiting for its code - /// Whether the waiting sign-in was dropped - public static bool CountWrongTwoFactorCode(this ISession session, string key) - { - var countKey = key + "WrongCodes"; - var count = (session.GetInt32(countKey) ?? 0) + 1; - if (count < MaxWrongTwoFactorCodes) - { - session.SetInt32(countKey, count); - return false; - } - - session.Remove(key); - session.Remove(countKey); - return true; - } - - /// - /// Starts the count of wrong codes again, for a new sign-in or one that has passed - /// - public static void ResetWrongTwoFactorCodes(this ISession session, string key) - { - session.Remove(key + "WrongCodes"); - } } \ No newline at end of file diff --git a/src/Web/Grand.Web/App_Data/Resources/DefaultLanguage.xml b/src/Web/Grand.Web/App_Data/Resources/DefaultLanguage.xml index 1b82379be080d08e12e1f85c138f504ebb3f6574..889fadc80c7b4b6acf3dc631e2955ef43b42e05e 100644 GIT binary patch delta 121 zcmWN=#|eNi06o&QJv80pLThIF7t1t6U_+3;uKbO$*`nRY*QMj&PaVrC#_0b*7lW&>h& zAm#vKP9Ww2Vs0Sj0b*Vt<^y7WAQk{(K_C_aVqqW_0b)@g76W2&AeI1PNg$Tm?x!yO G<|zPst2!e9 diff --git a/src/Web/Grand.Web/App_Data/Resources/Upgrade/en_250.xml b/src/Web/Grand.Web/App_Data/Resources/Upgrade/en_250.xml index cb0c2fa73a..071964f37f 100644 --- a/src/Web/Grand.Web/App_Data/Resources/Upgrade/en_250.xml +++ b/src/Web/Grand.Web/App_Data/Resources/Upgrade/en_250.xml @@ -2817,7 +2817,4 @@ Cycle - - Too many wrong security codes. Sign in again. - diff --git a/src/Web/Grand.Web/Controllers/AccountController.cs b/src/Web/Grand.Web/Controllers/AccountController.cs index e000724673..540d2a4ce0 100644 --- a/src/Web/Grand.Web/Controllers/AccountController.cs +++ b/src/Web/Grand.Web/Controllers/AccountController.cs @@ -32,7 +32,6 @@ using Microsoft.AspNetCore.Mvc; using System.Security.Cryptography; using Grand.Web.Common.Localization; -using static Grand.Web.Common.Extensions.SessionExtensions; namespace Grand.Web.Controllers; @@ -257,7 +256,6 @@ await _customerManagerService.LoginCustomer( { var userName = _customerSettings.UsernamesEnabled ? model.Username : model.Email; HttpContext.Session.SetString("RequiresTwoFactor", userName); - HttpContext.Session.ResetWrongTwoFactorCodes("RequiresTwoFactor"); //the sign-in that follows the code must still go where the login was asked to go if (!string.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl)) HttpContext.Session.SetString("RequiresTwoFactorReturnUrl", returnUrl); @@ -314,7 +312,7 @@ await _mediator.Send(new GetTwoFactorAuthentication { [IgnoreApi] [HttpPost] public async Task TwoFactorAuthorization(string token, - [FromServices] ITwoFactorAuthenticationService twoFactorAuthenticationService) + [FromServices] ITwoFactorSignInService twoFactorSignInService) { if (!_customerSettings.TwoFactorAuthenticationEnabled) return RedirectToRoute("Login"); @@ -329,35 +327,30 @@ public async Task TwoFactorAuthorization(string token, if (customer == null) return RedirectToRoute("Login"); - if (string.IsNullOrEmpty(token)) + switch (await twoFactorSignInService.CheckCode(customer, token, _customerSettings.TwoFactorAuthenticationType)) { - ModelState.AddModelError("", - _translationService.GetResource("Account.TwoFactorAuth.SecurityCodeIsRequired")); - } - else - { - var secretKey = customer.GetUserFieldFromEntity(SystemCustomerFieldNames.TwoFactorSecretKey); - if (await twoFactorAuthenticationService.AuthenticateTwoFactor(secretKey, token, customer, - _customerSettings.TwoFactorAuthenticationType)) - { + case TwoFactorSignInResult.Passed: //remove session HttpContext.Session.Remove("RequiresTwoFactor"); - HttpContext.Session.ResetWrongTwoFactorCodes("RequiresTwoFactor"); var returnUrl = HttpContext.Session.GetString("RequiresTwoFactorReturnUrl"); HttpContext.Session.Remove("RequiresTwoFactorReturnUrl"); //sign in return await SignInAction(customer, false, returnUrl); - } - - ModelState.AddModelError("", HttpContext.Session.CountWrongTwoFactorCode("RequiresTwoFactor") - ? _translationService.GetResource("Account.TwoFactorAuth.TooManyWrongCodes") - : _translationService.GetResource("Account.TwoFactorAuth.WrongSecurityCode")); + case TwoFactorSignInResult.LockedOut: + //the waiting sign-in is dropped: it starts again with the password once the lockout ends + HttpContext.Session.Remove("RequiresTwoFactor"); + HttpContext.Session.Remove("RequiresTwoFactorReturnUrl"); + ModelState.AddModelError("", + _translationService.GetResource("Account.Login.WrongCredentials.LockedOut")); + break; + default: + ModelState.AddModelError("", _translationService.GetResource(string.IsNullOrEmpty(token) + ? "Account.TwoFactorAuth.SecurityCodeIsRequired" + : "Account.TwoFactorAuth.WrongSecurityCode")); + break; } - await _mediator.Publish(new CustomerLoginFailedEvent(customer, - string.IsNullOrEmpty(token) ? "two-factor code missing" : "wrong two-factor code")); - return View(); }