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 000000000..50fea675d --- /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 c5886eb66..03d909f84 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 000000000..38a7bbfc0 --- /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 000000000..29e01dc12 --- /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 acf337638..735bb1d8a 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 000000000..897090aec --- /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 ef497e515..e8a385dea 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,7 +140,23 @@ 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_LockedOut_SignInMustStartAgain() + { + await PasswordStep(); + + Assert.IsInstanceOfType(await _controller.TwoFactorAuthorization("000000", + CodeAnswers(TwoFactorSignInResult.LockedOut).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); diff --git a/src/Tests/Grand.Web.Tests/Controllers/AccountControllerTwoFactorReturnUrlTests.cs b/src/Tests/Grand.Web.Tests/Controllers/AccountControllerTwoFactorReturnUrlTests.cs index 8854f2b0a..1990fb856 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 4b9f6e0f9..f9ef0166d 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; @@ -267,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"); @@ -282,29 +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); //sign in return await SignInAction(customer, false); - } - - ModelState.AddModelError("", _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/Controllers/AccountController.cs b/src/Web/Grand.Web/Controllers/AccountController.cs index 13d0b146f..540d2a4ce 100644 --- a/src/Web/Grand.Web/Controllers/AccountController.cs +++ b/src/Web/Grand.Web/Controllers/AccountController.cs @@ -312,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"); @@ -327,17 +327,9 @@ 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"); var returnUrl = HttpContext.Session.GetString("RequiresTwoFactorReturnUrl"); @@ -345,15 +337,20 @@ public async Task TwoFactorAuthorization(string token, //sign in return await SignInAction(customer, false, returnUrl); - } - - ModelState.AddModelError("", - _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(); }