Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
21 changes: 21 additions & 0 deletions src/Core/Grand.Infrastructure/Configuration/SecurityConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
/// </summary>
public bool EnableHtmlSanitization { get; set; } = true;

/// <summary>
/// How many times one IP address may ask for the link to a guest order within the window. Default 5; 0 = no limit
/// </summary>
public int GuestOrderRateLimitPermits { get; set; } = 5;

/// <summary>
/// The window of the guest-order limit, in minutes. Default 10
/// </summary>
public int GuestOrderRateLimitWindowMinutes { get; set; } = 10;

/// <summary>
/// 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
/// </summary>
public int StorefrontFormRateLimitPermits { get; set; } = 10;

/// <summary>
/// The window of the storefront form limit, in minutes. Default 10
/// </summary>
public int StorefrontFormRateLimitWindowMinutes { get; set; } = 10;
}
Original file line number Diff line number Diff line change
@@ -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);
}
}
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// The storefront forms that mail the store or keep what a visitor sent, uploads included
/// </summary>
[TestClass]
public class StorefrontFormRateLimitTests
{
public static IEnumerable<object[]> 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<HttpPostAttribute>() != null);

Assert.AreEqual(GrandCommonStartup.StorefrontFormRateLimitPolicy,
post.GetCustomAttribute<EnableRateLimitingAttribute>()?.PolicyName);
}
}
24 changes: 21 additions & 3 deletions src/Web/Grand.Web.Common/Startup/GrandCommonStartup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<string> 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);
}

/// <summary>
/// The rate limiter policy of the page where guests ask for the link to their order
/// </summary>
public const string GuestOrderRateLimitPolicy = "GuestOrder";

/// <summary>
/// The rate limiter policy of the storefront forms that send a message or keep what the visitor sent
/// </summary>
public const string StorefrontFormRateLimitPolicy = "StorefrontForm";

/// <summary>
/// Configure the using of added middleware
/// </summary>
Expand Down
11 changes: 10 additions & 1 deletion src/Web/Grand.Web/App_Data/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
3 changes: 3 additions & 0 deletions src/Web/Grand.Web/Controllers/AccountController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;

Expand Down Expand Up @@ -427,6 +429,7 @@ public virtual IActionResult PasswordRecovery([FromServices] OidcLoginConfig oid
return View(model);
}

[EnableRateLimiting(GrandCommonStartup.StorefrontFormRateLimitPolicy)]
[HttpPost]
[PublicStore(true)]
public virtual async Task<ActionResult<PasswordRecoveryModel>> PasswordRecovery(PasswordRecoveryModel model,
Expand Down
3 changes: 3 additions & 0 deletions src/Web/Grand.Web/Controllers/BlogController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,15 @@
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;
using Grand.Mediator;
using Microsoft.AspNetCore.Mvc;
using Grand.SharedKernel.Attributes;
using Grand.Web.Common.Localization;
using Microsoft.AspNetCore.RateLimiting;

namespace Grand.Web.Controllers;

Expand Down Expand Up @@ -141,6 +143,7 @@ await permissionService.Authorize(StandardPermission.ManageBlog))
return View(model);
}

[EnableRateLimiting(GrandCommonStartup.StorefrontFormRateLimitPolicy)]
[HttpPost]
[DenySystemAccount]
public virtual async Task<ActionResult<AddBlogCommentModel>> BlogPost(AddBlogCommentModel model,
Expand Down
3 changes: 3 additions & 0 deletions src/Web/Grand.Web/Controllers/CatalogController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;

Expand Down Expand Up @@ -317,6 +319,7 @@ public virtual async Task<IActionResult> VendorAll(VendorPagingModel command)

#region Vendor reviews

[EnableRateLimiting(GrandCommonStartup.StorefrontFormRateLimitPolicy)]
[HttpPost]
[DenySystemAccount]
public virtual async Task<IActionResult> VendorReviews(VendorReviewsModel model)
Expand Down
4 changes: 4 additions & 0 deletions src/Web/Grand.Web/Controllers/ContactController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -58,6 +60,7 @@ public virtual async Task<ActionResult<ContactUsModel>> Index(
return View(model);
}

[EnableRateLimiting(GrandCommonStartup.StorefrontFormRateLimitPolicy)]
[HttpPost]
[ClosedStore(true)]
[DenySystemAccount]
Expand Down Expand Up @@ -115,6 +118,7 @@ public virtual async Task<IActionResult> ContactAttributeChange(ContactAttribute
});
}

[EnableRateLimiting(GrandCommonStartup.StorefrontFormRateLimitPolicy)]
[HttpPost]
[DenySystemAccount]
public virtual async Task<IActionResult> UploadFileContactAttribute(string attributeId, IFormFile file,
Expand Down
3 changes: 3 additions & 0 deletions src/Web/Grand.Web/Controllers/NewsController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,15 @@
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;
using Grand.Mediator;
using Microsoft.AspNetCore.Mvc;
using Grand.SharedKernel.Attributes;
using Grand.Web.Common.Localization;
using Microsoft.AspNetCore.RateLimiting;

namespace Grand.Web.Controllers;

Expand Down Expand Up @@ -103,6 +105,7 @@ await _permissionService.Authorize(StandardPermission.ManageNews))
return View(model);
}

[EnableRateLimiting(GrandCommonStartup.StorefrontFormRateLimitPolicy)]
[HttpPost]
[DenySystemAccount]
public virtual async Task<IActionResult> NewsCommentAdd(AddNewsCommentModel model)
Expand Down
3 changes: 3 additions & 0 deletions src/Web/Grand.Web/Controllers/NewsletterController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -19,6 +21,7 @@ public NewsletterController(IMediator mediator)
_mediator = mediator;
}

[EnableRateLimiting(GrandCommonStartup.StorefrontFormRateLimitPolicy)]
[HttpPost]
public virtual async Task<IActionResult> SubscribeNewsletter(string email, bool subscribe)
{
Expand Down
6 changes: 6 additions & 0 deletions src/Web/Grand.Web/Controllers/ProductController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,15 @@
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;
using Grand.Web.Features.Models.Products;
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;
Expand Down Expand Up @@ -143,6 +145,7 @@ public virtual async Task<IActionResult> NewProducts()

#region Email a friend

[EnableRateLimiting(GrandCommonStartup.StorefrontFormRateLimitPolicy)]
[HttpPost]
[DenySystemAccount]
public virtual async Task<IActionResult> ProductEmailAFriend(ProductEmailAFriendModel model)
Expand Down Expand Up @@ -187,6 +190,7 @@ await _mediator.Send(new SendProductEmailAFriendMessageCommand {

#region Ask question

[EnableRateLimiting(GrandCommonStartup.StorefrontFormRateLimitPolicy)]
[HttpPost]
[DenySystemAccount]
public virtual async Task<IActionResult> AskQuestionOnProduct(ProductAskQuestionSimpleModel model)
Expand Down Expand Up @@ -413,6 +417,7 @@ public virtual async Task<IActionResult> ProductDetails_WarehouseChange(ProductM
});
}

[EnableRateLimiting(GrandCommonStartup.StorefrontFormRateLimitPolicy)]
[HttpPost]
public virtual async Task<IActionResult> UploadFileProductAttribute(string attributeId, string productId, IFormFile file,
[FromServices] IDownloadService downloadService)
Expand Down Expand Up @@ -584,6 +589,7 @@ public virtual async Task<IActionResult> QuickView(string productId)

#region Product reviews

[EnableRateLimiting(GrandCommonStartup.StorefrontFormRateLimitPolicy)]
[HttpPost]
[DenySystemAccount]
public virtual async Task<IActionResult> ProductReviews(
Expand Down
3 changes: 3 additions & 0 deletions src/Web/Grand.Web/Controllers/ShoppingCartController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,15 @@
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;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;
using Grand.SharedKernel.Extensions;
using Grand.Web.Common.Localization;
using Microsoft.AspNetCore.RateLimiting;

namespace Grand.Web.Controllers;

Expand Down Expand Up @@ -193,6 +195,7 @@ await checkoutAttributeFormatter.FormatAttributes(checkoutAttributes, _contextAc
});
}

[EnableRateLimiting(GrandCommonStartup.StorefrontFormRateLimitPolicy)]
[DenySystemAccount]
[HttpPost]
public virtual async Task<IActionResult> UploadFileCheckoutAttribute(string attributeId, IFormFile file,
Expand Down
Loading
Loading