diff --git a/src/Core/Grand.Infrastructure/Configuration/SecurityConfig.cs b/src/Core/Grand.Infrastructure/Configuration/SecurityConfig.cs index f3b7dfad6..64f2dcd30 100644 --- a/src/Core/Grand.Infrastructure/Configuration/SecurityConfig.cs +++ b/src/Core/Grand.Infrastructure/Configuration/SecurityConfig.cs @@ -118,4 +118,25 @@ public class SecurityConfig /// goes back to accepting raw, unsanitized HTML the moment this is false. Re-enable as soon as possible. /// public bool EnableHtmlSanitization { get; set; } = true; + + /// + /// How many times one IP address may ask for the link to a guest order within the window. Default 5; 0 = no limit + /// + public int GuestOrderRateLimitPermits { get; set; } = 5; + + /// + /// The window of the guest-order limit, in minutes. Default 10 + /// + public int GuestOrderRateLimitWindowMinutes { get; set; } = 10; + + /// + /// How many times one IP address may send one storefront form (contact, reviews, comments, newsletter, + /// password recovery, attribute uploads) within the window. Default 10; 0 = no limit + /// + public int StorefrontFormRateLimitPermits { get; set; } = 10; + + /// + /// The window of the storefront form limit, in minutes. Default 10 + /// + public int StorefrontFormRateLimitWindowMinutes { get; set; } = 10; } \ No newline at end of file diff --git a/src/Tests/Grand.Web.Common.Tests/Startup/RateLimitPartitionTests.cs b/src/Tests/Grand.Web.Common.Tests/Startup/RateLimitPartitionTests.cs new file mode 100644 index 000000000..5dc223f91 --- /dev/null +++ b/src/Tests/Grand.Web.Common.Tests/Startup/RateLimitPartitionTests.cs @@ -0,0 +1,30 @@ +using Grand.Web.Common.Startup; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace Grand.Web.Common.Tests.Startup; + +[TestClass] +public class RateLimitPartitionTests +{ + [TestMethod] + public void ConfiguredPermits_RefusesTheNextOne() + { + using var limiter = GrandCommonStartup.FixedWindow("key", 2, 10).Factory("key"); + + Assert.IsTrue(limiter.AttemptAcquire().IsAcquired); + Assert.IsTrue(limiter.AttemptAcquire().IsAcquired); + Assert.IsFalse(limiter.AttemptAcquire().IsAcquired); + } + + //the limiter refuses a zero limit or window when it is created, at the first request + [TestMethod] + [DataRow(0, 10)] + [DataRow(5, 0)] + public void Zero_NoLimit(int permits, int windowMinutes) + { + using var limiter = GrandCommonStartup.FixedWindow("key", permits, windowMinutes).Factory("key"); + + for (var i = 0; i < 100; i++) + Assert.IsTrue(limiter.AttemptAcquire().IsAcquired); + } +} \ No newline at end of file diff --git a/src/Tests/Grand.Web.Tests/Controllers/StorefrontFormRateLimitTests.cs b/src/Tests/Grand.Web.Tests/Controllers/StorefrontFormRateLimitTests.cs new file mode 100644 index 000000000..6623fa44d --- /dev/null +++ b/src/Tests/Grand.Web.Tests/Controllers/StorefrontFormRateLimitTests.cs @@ -0,0 +1,43 @@ +using Grand.Web.Common.Startup; +using Grand.Web.Controllers; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.RateLimiting; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Reflection; + +namespace Grand.Web.Tests.Controllers; + +/// +/// The storefront forms that mail the store or keep what a visitor sent, uploads included +/// +[TestClass] +public class StorefrontFormRateLimitTests +{ + public static IEnumerable Forms => + [ + [typeof(ContactController), nameof(ContactController.Index)], + [typeof(ContactController), nameof(ContactController.UploadFileContactAttribute)], + [typeof(VendorController), nameof(VendorController.ContactVendor)], + [typeof(ProductController), nameof(ProductController.ProductEmailAFriend)], + [typeof(ProductController), nameof(ProductController.AskQuestionOnProduct)], + [typeof(ProductController), nameof(ProductController.ProductReviews)], + [typeof(ProductController), nameof(ProductController.UploadFileProductAttribute)], + [typeof(CatalogController), nameof(CatalogController.VendorReviews)], + [typeof(BlogController), nameof(BlogController.BlogPost)], + [typeof(NewsController), nameof(NewsController.NewsCommentAdd)], + [typeof(NewsletterController), nameof(NewsletterController.SubscribeNewsletter)], + [typeof(AccountController), nameof(AccountController.PasswordRecovery)], + [typeof(ShoppingCartController), nameof(ShoppingCartController.UploadFileCheckoutAttribute)] + ]; + + [TestMethod] + [DynamicData(nameof(Forms))] + public void PostOfTheForm_RateLimited(Type controller, string action) + { + var post = controller.GetMethods() + .Single(m => m.Name == action && m.GetCustomAttribute() != null); + + Assert.AreEqual(GrandCommonStartup.StorefrontFormRateLimitPolicy, + post.GetCustomAttribute()?.PolicyName); + } +} \ No newline at end of file diff --git a/src/Web/Grand.Web.Common/Startup/GrandCommonStartup.cs b/src/Web/Grand.Web.Common/Startup/GrandCommonStartup.cs index c57f417ff..a21cad1a8 100644 --- a/src/Web/Grand.Web.Common/Startup/GrandCommonStartup.cs +++ b/src/Web/Grand.Web.Common/Startup/GrandCommonStartup.cs @@ -98,17 +98,35 @@ public void ConfigureServices(IServiceCollection services, IConfiguration config "Too many requests. Please try again later.", cancellationToken)); //a guest asking for the link to an order: guessing order codes and e-mail addresses takes many tries options.AddPolicy(GuestOrderRateLimitPolicy, context => - RateLimitPartition.GetFixedWindowLimiter(context.Connection.RemoteIpAddress?.ToString() ?? "", - _ => new FixedWindowRateLimiterOptions - { PermitLimit = 5, Window = TimeSpan.FromMinutes(10), QueueLimit = 0 })); + FixedWindow(context.Connection.RemoteIpAddress?.ToString() ?? "", + securityConfig.GuestOrderRateLimitPermits, securityConfig.GuestOrderRateLimitWindowMinutes)); + //a visitor sending a form that mails the store or keeps what they sent: counted per form, so a + //customer reviewing several products is not stopped by the contact message they sent before + options.AddPolicy(StorefrontFormRateLimitPolicy, context => + FixedWindow($"{context.Connection.RemoteIpAddress}|{context.GetEndpoint()?.DisplayName}", + securityConfig.StorefrontFormRateLimitPermits, securityConfig.StorefrontFormRateLimitWindowMinutes)); }); } + internal static RateLimitPartition FixedWindow(string key, int permits, int windowMinutes) + { + //the limiter refuses a zero limit or window, so a zero turns the limit off + return permits > 0 && windowMinutes > 0 + ? RateLimitPartition.GetFixedWindowLimiter(key, _ => new FixedWindowRateLimiterOptions + { PermitLimit = permits, Window = TimeSpan.FromMinutes(windowMinutes), QueueLimit = 0 }) + : RateLimitPartition.GetNoLimiter(key); + } + /// /// The rate limiter policy of the page where guests ask for the link to their order /// public const string GuestOrderRateLimitPolicy = "GuestOrder"; + /// + /// The rate limiter policy of the storefront forms that send a message or keep what the visitor sent + /// + public const string StorefrontFormRateLimitPolicy = "StorefrontForm"; + /// /// Configure the using of added middleware /// diff --git a/src/Web/Grand.Web/App_Data/appsettings.json b/src/Web/Grand.Web/App_Data/appsettings.json index 0ca3e0e82..9533ead9c 100644 --- a/src/Web/Grand.Web/App_Data/appsettings.json +++ b/src/Web/Grand.Web/App_Data/appsettings.json @@ -127,7 +127,16 @@ //Operational escape hatch, not a security setting: when [SanitizeHtml]/[NoHtml] wrongly reject legitimate //content in production, set this to false to accept input unsanitized while a fix is prepared, then set it //back to true as soon as possible. Default true. - "EnableHtmlSanitization": true + "EnableHtmlSanitization": true, + //Storefront rate limits, counted per IP address and kept in memory per instance; a post over the limit gets 429. + //Behind a proxy the address is the proxy's unless UseForwardedHeaders is on. Permits 0 = no limit. + //The page where a guest asks for the link to an order: guessing order codes and e-mail addresses takes many tries. + "GuestOrderRateLimitPermits": 5, + "GuestOrderRateLimitWindowMinutes": 10, + //Each form that mails the store or keeps what the visitor sent (contact, vendor contact, e-mail a friend, product question, + //product and vendor reviews, blog and news comments, newsletter, password recovery, attribute uploads), counted per form. + "StorefrontFormRateLimitPermits": 10, + "StorefrontFormRateLimitWindowMinutes": 10 }, "Cache": { //Gets or sets a value indicating for default cache time in minutes" diff --git a/src/Web/Grand.Web/Controllers/AccountController.cs b/src/Web/Grand.Web/Controllers/AccountController.cs index 13d0b146f..b3a85531a 100644 --- a/src/Web/Grand.Web/Controllers/AccountController.cs +++ b/src/Web/Grand.Web/Controllers/AccountController.cs @@ -22,6 +22,7 @@ using Grand.Web.Common.Security.Captcha; using Grand.Web.Common.Security.ExternalRegistration; using Grand.Web.Common.Security.Oidc; +using Grand.Web.Common.Startup; using Grand.Web.Extensions; using Grand.Web.Features.Models.Common; using Grand.Web.Features.Models.Customers; @@ -30,6 +31,7 @@ using Grand.Web.Services; using Grand.Mediator; using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.RateLimiting; using System.Security.Cryptography; using Grand.Web.Common.Localization; @@ -427,6 +429,7 @@ public virtual IActionResult PasswordRecovery([FromServices] OidcLoginConfig oid return View(model); } + [EnableRateLimiting(GrandCommonStartup.StorefrontFormRateLimitPolicy)] [HttpPost] [PublicStore(true)] public virtual async Task> PasswordRecovery(PasswordRecoveryModel model, diff --git a/src/Web/Grand.Web/Controllers/BlogController.cs b/src/Web/Grand.Web/Controllers/BlogController.cs index dffdee74a..95398ed1a 100644 --- a/src/Web/Grand.Web/Controllers/BlogController.cs +++ b/src/Web/Grand.Web/Controllers/BlogController.cs @@ -9,6 +9,7 @@ using Grand.Web.Common.Controllers; using Grand.Web.Common.Filters; using Grand.Web.Common.Security.Authorization; +using Grand.Web.Common.Startup; using Grand.Web.Events; using Grand.Web.Features.Models.Blogs; using Grand.Web.Models.Blogs; @@ -16,6 +17,7 @@ using Microsoft.AspNetCore.Mvc; using Grand.SharedKernel.Attributes; using Grand.Web.Common.Localization; +using Microsoft.AspNetCore.RateLimiting; namespace Grand.Web.Controllers; @@ -141,6 +143,7 @@ await permissionService.Authorize(StandardPermission.ManageBlog)) return View(model); } + [EnableRateLimiting(GrandCommonStartup.StorefrontFormRateLimitPolicy)] [HttpPost] [DenySystemAccount] public virtual async Task> BlogPost(AddBlogCommentModel model, diff --git a/src/Web/Grand.Web/Controllers/CatalogController.cs b/src/Web/Grand.Web/Controllers/CatalogController.cs index 7c3cdc925..9e3fe5e2a 100644 --- a/src/Web/Grand.Web/Controllers/CatalogController.cs +++ b/src/Web/Grand.Web/Controllers/CatalogController.cs @@ -13,6 +13,7 @@ using Grand.Web.Commands.Models.Vendors; using Grand.Web.Common.Controllers; using Grand.Web.Common.Filters; +using Grand.Web.Common.Startup; using Grand.Web.Features.Models.Catalog; using Grand.Web.Features.Models.Vendors; using Grand.Web.Models.Catalog; @@ -21,6 +22,7 @@ using Microsoft.AspNetCore.Mvc; using Grand.SharedKernel.Attributes; using Grand.Web.Common.Localization; +using Microsoft.AspNetCore.RateLimiting; namespace Grand.Web.Controllers; @@ -317,6 +319,7 @@ public virtual async Task VendorAll(VendorPagingModel command) #region Vendor reviews + [EnableRateLimiting(GrandCommonStartup.StorefrontFormRateLimitPolicy)] [HttpPost] [DenySystemAccount] public virtual async Task VendorReviews(VendorReviewsModel model) diff --git a/src/Web/Grand.Web/Controllers/ContactController.cs b/src/Web/Grand.Web/Controllers/ContactController.cs index d93301894..3d1897f4e 100644 --- a/src/Web/Grand.Web/Controllers/ContactController.cs +++ b/src/Web/Grand.Web/Controllers/ContactController.cs @@ -11,11 +11,13 @@ using Grand.Web.Common.Controllers; using Grand.Web.Common.Extensions; using Grand.Web.Common.Filters; +using Grand.Web.Common.Startup; using Grand.Web.Events; using Grand.Web.Models.Contact; using Grand.Mediator; using Microsoft.AspNetCore.Mvc; using Grand.Web.Common.Localization; +using Microsoft.AspNetCore.RateLimiting; namespace Grand.Web.Controllers; @@ -58,6 +60,7 @@ public virtual async Task> Index( return View(model); } + [EnableRateLimiting(GrandCommonStartup.StorefrontFormRateLimitPolicy)] [HttpPost] [ClosedStore(true)] [DenySystemAccount] @@ -115,6 +118,7 @@ public virtual async Task ContactAttributeChange(ContactAttribute }); } + [EnableRateLimiting(GrandCommonStartup.StorefrontFormRateLimitPolicy)] [HttpPost] [DenySystemAccount] public virtual async Task UploadFileContactAttribute(string attributeId, IFormFile file, diff --git a/src/Web/Grand.Web/Controllers/NewsController.cs b/src/Web/Grand.Web/Controllers/NewsController.cs index ccad4482b..468a25112 100644 --- a/src/Web/Grand.Web/Controllers/NewsController.cs +++ b/src/Web/Grand.Web/Controllers/NewsController.cs @@ -9,6 +9,7 @@ using Grand.Web.Common.Controllers; using Grand.Web.Common.Filters; using Grand.Web.Common.Security.Authorization; +using Grand.Web.Common.Startup; using Grand.Web.Events; using Grand.Web.Features.Models.News; using Grand.Web.Models.News; @@ -16,6 +17,7 @@ using Microsoft.AspNetCore.Mvc; using Grand.SharedKernel.Attributes; using Grand.Web.Common.Localization; +using Microsoft.AspNetCore.RateLimiting; namespace Grand.Web.Controllers; @@ -103,6 +105,7 @@ await _permissionService.Authorize(StandardPermission.ManageNews)) return View(model); } + [EnableRateLimiting(GrandCommonStartup.StorefrontFormRateLimitPolicy)] [HttpPost] [DenySystemAccount] public virtual async Task NewsCommentAdd(AddNewsCommentModel model) diff --git a/src/Web/Grand.Web/Controllers/NewsletterController.cs b/src/Web/Grand.Web/Controllers/NewsletterController.cs index 53c3c16d3..3084962cf 100644 --- a/src/Web/Grand.Web/Controllers/NewsletterController.cs +++ b/src/Web/Grand.Web/Controllers/NewsletterController.cs @@ -2,9 +2,11 @@ using Grand.Web.Commands.Models.Newsletter; using Grand.Web.Common.Controllers; using Grand.Web.Common.Filters; +using Grand.Web.Common.Startup; using Grand.Web.Models.Newsletter; using Grand.Mediator; using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.RateLimiting; namespace Grand.Web.Controllers; @@ -19,6 +21,7 @@ public NewsletterController(IMediator mediator) _mediator = mediator; } + [EnableRateLimiting(GrandCommonStartup.StorefrontFormRateLimitPolicy)] [HttpPost] public virtual async Task SubscribeNewsletter(string email, bool subscribe) { diff --git a/src/Web/Grand.Web/Controllers/ProductController.cs b/src/Web/Grand.Web/Controllers/ProductController.cs index d194342b7..3e2b88cfa 100644 --- a/src/Web/Grand.Web/Controllers/ProductController.cs +++ b/src/Web/Grand.Web/Controllers/ProductController.cs @@ -17,6 +17,7 @@ using Grand.Web.Common.Filters; using Grand.Web.Common.RequestCustomerResolvers; using Grand.Web.Common.Security.Captcha; +using Grand.Web.Common.Startup; using Grand.Web.Events; using Grand.Web.Extensions; using Grand.Web.Features.Models.Catalog; @@ -24,6 +25,7 @@ using Grand.Web.Models.Catalog; using Grand.Mediator; using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.RateLimiting; using Microsoft.Extensions.Logging; using Grand.SharedKernel.Attributes; using Grand.SharedKernel.Extensions; @@ -143,6 +145,7 @@ public virtual async Task NewProducts() #region Email a friend + [EnableRateLimiting(GrandCommonStartup.StorefrontFormRateLimitPolicy)] [HttpPost] [DenySystemAccount] public virtual async Task ProductEmailAFriend(ProductEmailAFriendModel model) @@ -187,6 +190,7 @@ await _mediator.Send(new SendProductEmailAFriendMessageCommand { #region Ask question + [EnableRateLimiting(GrandCommonStartup.StorefrontFormRateLimitPolicy)] [HttpPost] [DenySystemAccount] public virtual async Task AskQuestionOnProduct(ProductAskQuestionSimpleModel model) @@ -413,6 +417,7 @@ public virtual async Task ProductDetails_WarehouseChange(ProductM }); } + [EnableRateLimiting(GrandCommonStartup.StorefrontFormRateLimitPolicy)] [HttpPost] public virtual async Task UploadFileProductAttribute(string attributeId, string productId, IFormFile file, [FromServices] IDownloadService downloadService) @@ -584,6 +589,7 @@ public virtual async Task QuickView(string productId) #region Product reviews + [EnableRateLimiting(GrandCommonStartup.StorefrontFormRateLimitPolicy)] [HttpPost] [DenySystemAccount] public virtual async Task ProductReviews( diff --git a/src/Web/Grand.Web/Controllers/ShoppingCartController.cs b/src/Web/Grand.Web/Controllers/ShoppingCartController.cs index 0b339c77e..6ecc68e5e 100644 --- a/src/Web/Grand.Web/Controllers/ShoppingCartController.cs +++ b/src/Web/Grand.Web/Controllers/ShoppingCartController.cs @@ -20,6 +20,7 @@ using Grand.Web.Common.Extensions; using Grand.Web.Common.Filters; using Grand.Web.Common.Security.Authorization; +using Grand.Web.Common.Startup; using Grand.Web.Features.Models.ShoppingCart; using Grand.Web.Models.ShoppingCart; using Grand.Mediator; @@ -27,6 +28,7 @@ using Microsoft.AspNetCore.Mvc; using Grand.SharedKernel.Extensions; using Grand.Web.Common.Localization; +using Microsoft.AspNetCore.RateLimiting; namespace Grand.Web.Controllers; @@ -193,6 +195,7 @@ await checkoutAttributeFormatter.FormatAttributes(checkoutAttributes, _contextAc }); } + [EnableRateLimiting(GrandCommonStartup.StorefrontFormRateLimitPolicy)] [DenySystemAccount] [HttpPost] public virtual async Task UploadFileCheckoutAttribute(string attributeId, IFormFile file, diff --git a/src/Web/Grand.Web/Controllers/VendorController.cs b/src/Web/Grand.Web/Controllers/VendorController.cs index 9f11b9f4f..39a022b61 100644 --- a/src/Web/Grand.Web/Controllers/VendorController.cs +++ b/src/Web/Grand.Web/Controllers/VendorController.cs @@ -15,12 +15,14 @@ using Grand.Web.Common.Filters; using Grand.Web.Common.Security.Authorization; using Grand.Web.Common.Security.Captcha; +using Grand.Web.Common.Startup; using Grand.Web.Extensions; using Grand.Web.Features.Models.Common; using Grand.Web.Models.Vendors; using Grand.Mediator; using Microsoft.AspNetCore.Mvc; using Grand.Web.Common.Localization; +using Microsoft.AspNetCore.RateLimiting; namespace Grand.Web.Controllers; @@ -194,6 +196,7 @@ await _vendorMessageProviderService.SendNewVendorAccountApplyStoreOwnerMessage(_ return View(model); } + [EnableRateLimiting(GrandCommonStartup.StorefrontFormRateLimitPolicy)] [HttpPost] [DenySystemAccount] public virtual async Task ContactVendor(ContactVendorModel model)