Harden payment accounting and app inputs, and correct POS top-up records (#7772)
What changed, and why it matters
This commit is a defensive hardening patch for BTCPay Server. It adds length limits to many user-supplied inputs (email addresses, URLs, order IDs) to prevent oversized or malformed data from causing problems, fixes a currency-conversion calculation so payment accounting uses correct math, and corrects how point-of-sale 'top-up' transactions are recorded so receipts don't show wrong amounts. The changes reduce the risk of denial-of-service, accounting errors, and possibly minor injection issues, but the commit itself does not describe a specific active vulnerability.
Treat this as a security-hardening fix and include it in the next maintenance release. Review whether any of the previously unbounded inputs were reachable by unauthenticated or low-privilege users, and consider adding automated tests for the new length limits and the corrected currency conversion/top-up behavior. No immediate emergency response is indicated by the diff alone.
Security signals we found
Input length limits added to emails, URLs, and order IDs across API and UI surfaces
Currency conversion clamped to MaxCoinValue to prevent overflow/underflow in payment accounting
POS top-up logic corrected to avoid incorrect receipt totals
RegexOptions.NonBacktracking used to mitigate potential ReDoS
Reporting providers now consume pre-computed InvoicePaidAmount.Gross instead of raw rate*value multiplication
Evidence from the diff
The patch introduces a central LengthLimits constants class (MaxOrderIdLength=512, MaxUrlLength=2048, MaxEmailLength=254) and applies MaxLength/length checks across GreenField and UI controllers, view models, and validation attributes. It also refactors currency conversion in PaymentPrompt/InvoiceEntity/PaymentEntity to use a new ToInvoiceCurrency helper that clamps values to MaxCoinValue, preventing overflow/underflow when converting paid amounts. Reporting providers now use payment.InvoicePaidAmount.Gross instead of re-computing rate*payment.Value. POS top-up handling is corrected: isTopup is now determined before calculating the order summary, and top-up receipts are initialized with an empty OrderSummary and zeroed amounts rather than carrying values from a previous calculation. A regex in UISubscriberPortalController is switched to RegexOptions.NonBacktracking to reduce ReDoS risk.
Changed components
GreenfieldStoresControllerGreenfieldUsersControllerUILNURLControllerExtensions (email validation)RegisterViewModelCreateInvoiceModelIndexViewModelGeneralSettingsViewModelStoreUsersViewModelUICrowdfundControllerPayButtonViewModelUIPointOfSaleControllerGreenfieldOfferingControllerUIOfferingControllerUISubscriberPortalControllerInvoiceEntity / PaymentPrompt / PaymentEntityPosReceiptDataPaymentRequestsReportProviderPaymentsReportProviderUriAttributeInspect captured patch +75 / −17
### BTCPayServer/Controllers/GreenField/GreenfieldStoresController.cs
@@ -345,7 +345,7 @@ private IActionResult Validate(StoreBaseData request, StoreBaseData existing)
ModelState.AddModelError(nameof(request.Website), "Website is not a valid url");
}
if (!string.IsNullOrEmpty(request.LogoUrl) &&
- ((request.LogoUrl != existing.LogoUrl && request.LogoUrl.Length > 2048) ||
+ ((request.LogoUrl != existing.LogoUrl && request.LogoUrl.Length > LengthLimits.MaxUrlLength) ||
!Uri.TryCreate(request.LogoUrl, UriKind.Absolute, out _)))
{
ModelState.AddModelError(nameof(request.LogoUrl), "Logo is not a valid url");
### BTCPayServer/Controllers/GreenField/GreenfieldUsersController.cs
@@ -166,7 +166,7 @@ public async Task<IActionResult> UpdateCurrentUser(UpdateApplicationUserRequest
}
if (request.Name?.Length > 50)
ModelState.AddModelError(nameof(request.Name), "Name is too long");
- if (request.ImageUrl?.Length > 2048)
+ if (request.ImageUrl?.Length > LengthLimits.MaxUrlLength)
ModelState.AddModelError(nameof(request.ImageUrl), "ImageUrl is too long");
bool needUpdate = false;
@@ -328,11 +328,11 @@ public async Task<IActionResult> CreateUser(CreateApplicationUserRequest request
{
if (request.Email is null)
ModelState.AddModelError(nameof(request.Email), "Email is missing");
- if (!MailboxAddressValidator.IsMailboxAddress(request.Email))
+ if (request.Email?.Length > LengthLimits.MaxEmailLength || !MailboxAddressValidator.IsMailboxAddress(request.Email))
ModelState.AddModelError(nameof(request.Email), "Invalid email");
if (request.Name?.Length > 50)
ModelState.AddModelError(nameof(request.Name), "Name is too long");
- if (request.ImageUrl?.Length > 2048)
+ if (request.ImageUrl?.Length > LengthLimits.MaxUrlLength)
ModelState.AddModelError(nameof(request.ImageUrl), "ImageUrl is too long");
if (!ModelState.IsValid)
### BTCPayServer/Controllers/UILNURLController.cs
@@ -328,8 +328,8 @@ public async Task<IActionResult> GetLNURLForApp(string cryptoCode, string appId,
order.AddLine(new(item.Id ?? "", 1, item.Price ?? 0m, item.TaxRate ?? posS?.DefaultTaxRate ?? 0m));
}
- var summary = order.Calculate();
var isTopup = item is null or { PriceType: AppItemPriceType.Topup } or { Price: null };
+ var summary = isTopup ? new PoSOrder.OrderSummary() : order.Calculate();
var receiptData = PosReceiptData.Create(isTopup, item is {} ? new[]{ item } : [], posAppData, order, summary, currencyCode, _displayFormatter);
var createInvoice = new CreateInvoiceRequest
{
### BTCPayServer/Extensions.cs
@@ -244,7 +244,7 @@ public static Task<BufferizedFormFile> Bufferize(this IFormFile formFile)
}
public static bool IsValidEmail(this string email)
{
- if (string.IsNullOrEmpty(email))
+ if (string.IsNullOrEmpty(email) || email.Length > LengthLimits.MaxEmailLength)
{
return false;
}
### BTCPayServer/Models/AccountViewModels/RegisterViewModel.cs
@@ -6,6 +6,7 @@ public class RegisterViewModel
{
[Required]
[EmailAddress]
+ [MaxLength(LengthLimits.MaxEmailLength)]
[Display(Name = "Email")]
public string Email { get; set; }
### BTCPayServer/Models/InvoicingModels/CreateInvoiceModel.cs
@@ -25,6 +25,7 @@ public string StoreId
}
[DisplayName("Order Id")]
+ [MaxLength(LengthLimits.MaxOrderIdLength)]
public string OrderId
{
get; set;
@@ -48,6 +49,7 @@ public string Metadata
}
[MailboxAddress]
+ [MaxLength(LengthLimits.MaxEmailLength)]
[DisplayName("Buyer Email")]
public string BuyerEmail
{
### BTCPayServer/Models/ManageViewModels/IndexViewModel.cs
@@ -20,6 +20,7 @@ public class IndexViewModel
[Display(Name = "Profile Picture")]
public IFormFile ImageFile { get; set; }
+ [MaxLength(LengthLimits.MaxUrlLength)]
public string ImageUrl { get; set; }
[Display(Name = "Allow Basic authentication for Greenfield API")]
### BTCPayServer/Models/StoreViewModels/GeneralSettingsViewModel.cs
@@ -31,10 +31,12 @@ public class GeneralSettingsViewModel
[Display(Name = "Logo")]
public IFormFile LogoFile { get; set; }
+ [MaxLength(LengthLimits.MaxUrlLength)]
public string LogoUrl { get; set; }
[Display(Name = "Custom CSS")]
public IFormFile CssFile { get; set; }
+ [MaxLength(LengthLimits.MaxUrlLength)]
public string CssUrl { get; set; }
public bool Archived { get; set; }
### BTCPayServer/Models/StoreViewModels/StoreUsersViewModel.cs
@@ -33,6 +33,7 @@ public class StoreUserViewModel
[Required]
[EmailAddress]
+ [MaxLength(LengthLimits.MaxEmailLength)]
[Display(Name = "Email address")]
public string Email { get; set; }
public string StoreId { get; set; }
### BTCPayServer/Plugins/Crowdfund/Controllers/UICrowdfundController.cs
@@ -114,6 +114,11 @@ public async Task<IActionResult> ContributeToCrowdfund(string appId, ContributeT
return NotFound("Crowdfund is not currently active");
}
+ if (request.Email?.Length > LengthLimits.MaxEmailLength)
+ return NotFound("Email is too long");
+ if (request.RedirectUrl?.Length > LengthLimits.MaxUrlLength)
+ return NotFound("Redirect URL is too long");
+
var info = await GetAppInfo(appId);
if (!isAdmin &&
((settings.StartDate.HasValue && DateTime.UtcNow < settings.StartDate) ||
### BTCPayServer/Plugins/PayButton/Models/PayButtonViewModel.cs
@@ -17,6 +17,7 @@ public class PayButtonViewModel
public string DefaultPaymentMethod { get; set; }
public PaymentMethodOptionViewModel.Format[] PaymentMethods { get; set; }
public string CheckoutDesc { get; set; }
+ [MaxLength(LengthLimits.MaxOrderIdLength)]
public string OrderId { get; set; }
public int ButtonSize { get; set; }
public int ButtonType { get; set; }
@@ -31,8 +32,10 @@ public class PayButtonViewModel
public bool FitButtonInline { get; set; }
[Url]
+ [MaxLength(LengthLimits.MaxUrlLength)]
public string ServerIpn { get; set; }
[Url]
+ [MaxLength(LengthLimits.MaxUrlLength)]
public string BrowserRedirect { get; set; }
public string StoreId { get; set; }
public string CheckoutQueryString { get; set; }
### BTCPayServer/Plugins/PointOfSale/Controllers/UIPointOfSaleController.cs
@@ -251,6 +251,11 @@ IActionResult Error(string message)
if (customAmount < 0)
customAmount = 0;
+ if (email?.Length > LengthLimits.MaxEmailLength ||
+ orderId?.Length > LengthLimits.MaxOrderIdLength ||
+ redirectUrl?.Length > LengthLimits.MaxUrlLength)
+ return Error(StringLocalizer["The order details are too long"]);
+
var settings = app.GetSettings<PointOfSaleSettings>();
settings.DefaultView = settings.EnableShoppingCart ? PosViewType.Cart : settings.DefaultView;
@@ -397,9 +402,10 @@ jposData.Amounts is null &&
break;
}
- var summary = order.Calculate();
var isTopup = currentView == PosViewType.Static &&
- selectedChoices is [{ PriceType: AppItemPriceType.Topup }];
+ selectedChoices is [{ PriceType: AppItemPriceType.Topup }] &&
+ order.ItemLines is [{ Count: 1 }];
+ var summary = isTopup ? new PoSOrder.OrderSummary() : order.Calculate();
var receiptData = PosReceiptData.Create(isTopup, selectedChoices, jposData, order, summary, settings.Currency, _displayFormatter);
if (!isTopup && summary.PriceTaxIncludedWithTips <= 0m && settings.DisableZeroAmountInvoice is true)
### BTCPayServer/Plugins/Subscriptions/Controllers/GreenfieldOfferingController.cs
@@ -37,7 +37,7 @@ public class GreenfieldOfferingController(
{
private const int MaxMetadataLength = 64 * 1024;
private const int MaxFeatures = 100;
- private const int MaxCreditDescriptionLength = 500;
+ internal const int MaxCreditDescriptionLength = 500;
[HttpGet("~/api/v1/stores/{storeId}/offerings/{offeringId?}")]
public async Task<IActionResult> GetOffering(string storeId, string? offeringId = null)
@@ -527,8 +527,7 @@ public async Task<IActionResult> CreatePlanCheckout([FromBody]CreatePlanCheckout
ModelState.AddModelError(nameof(model.PlanId), "PlanId is required");
if (model.NewSubscriberEmail is not null && model.CustomerSelector is not null)
ModelState.AddModelError(nameof(model.NewSubscriberEmail), "If customerSelector is specified, newSubscriberEmail cannot be specified");
- if (model.NewSubscriberEmail is not null &&
- (model.NewSubscriberEmail.Length > 254 || !model.NewSubscriberEmail.IsValidEmail()))
+ if (model.NewSubscriberEmail is not null && !model.NewSubscriberEmail.IsValidEmail())
ModelState.AddModelError(nameof(model.NewSubscriberEmail), "Invalid email");
ValidateMetadata(nameof(model.NewSubscriberMetadata), model.NewSubscriberMetadata);
ValidateMetadata(nameof(model.InvoiceMetadata), model.InvoiceMetadata);
### BTCPayServer/Plugins/Subscriptions/Controllers/UIOfferingController.cs
@@ -157,6 +157,14 @@ public async Task<IActionResult> SubscriberSuspend(string storeId, string offeri
Html = StringLocalizer["The amount must be at most {0}", GreenfieldConstants.MaxAmount]
});
}
+ else if (command is "credit" or "charge" && description?.Length > GreenfieldOfferingController.MaxCreditDescriptionLength)
+ {
+ TempData.SetStatusMessageModel(new()
+ {
+ Severity = StatusMessageModel.StatusSeverity.Error,
+ Html = StringLocalizer["The description must be at most {0} characters", GreenfieldOfferingController.MaxCreditDescriptionLength]
+ });
+ }
else if (command is "credit" or "charge" && amount is > 0)
{
var message = command is "credit"
### BTCPayServer/Plugins/Subscriptions/Controllers/UISubscriberPortalController.cs
@@ -153,7 +153,7 @@ public async Task<IActionResult> SubscriberPortal(string portalSessionId, string
return View(vm);
}
- private static readonly Regex _invoiceIdRegex = new(@"\(Inv: ([^\)]*)\)", RegexOptions.Compiled);
+ private static readonly Regex _invoiceIdRegex = new(@"\(Inv: ([^\)]*)\)", RegexOptions.NonBacktracking);
private string AddInvoiceLink(string desc)
{
### BTCPayServer/Plugins/Translations/Translations.Default.cs
@@ -1901,6 +1901,7 @@ static Translations()
"The currency to generate the invoice in when generated through this lightning address": "",
"The current password is not correct.": "",
"The custom color, logo and CSS are applied on the public/customer-facing pages (Invoice, Payment Request, Pull Payment, etc.). The brand color is used as the accent color for buttons, links, etc. It might get adapted to fit the light/dark color scheme.": "",
+ "The description must be at most {0} characters": "",
"The device has not been initialized.": "",
"The DNS record has been refreshed:": "",
"The domain {0} is not pointing to this BTCPay Server.": "",
@@ -1939,6 +1940,7 @@ static Translations()
"The node is offline": "",
"The node is starting...": "",
"The node is synchronized (Height: {0})": "",
+ "The order details are too long": "",
"The overpaid amount has not settled yet": "",
"The passkey was removed successfully.": "",
"The password is the <code>http-password</code> generated in your <code>~/.phoenix/phoenix.conf</code> file.": "",
### BTCPayServer/Services/Invoices/InvoiceEntity.cs
@@ -976,7 +976,7 @@ public PaymentMethodAccounting Calculate()
if (i.MinimumNetDue > 0.0m)
{
accounting.TxRequired++;
- grossDue += rate * PaymentMethodFee;
+ grossDue += ToInvoiceCurrency(PaymentMethodFee, rate);
}
accounting.TotalDue = Coins(grossDue, rate, divisibility);
accounting.TotalDueSettled = Coins(i.Price + i.GrossSettled - i.NetSettled, rate, divisibility);
@@ -1038,6 +1038,14 @@ internal static decimal Coins(decimal v, int precision)
v = MaxCoinValue;
return v;
}
+
+ internal static decimal ToInvoiceCurrency(decimal value, decimal rate)
+ {
+ var absoluteRate = Math.Abs(rate);
+ if (absoluteRate > 1m && Math.Abs(value) > MaxCoinValue / absoluteRate)
+ return (value < 0m) != (rate < 0m) ? -MaxCoinValue : MaxCoinValue;
+ return Math.Clamp(value * rate, -MaxCoinValue, MaxCoinValue);
+ }
}
public class PaymentEntity : PaymentBlob
@@ -1093,8 +1101,8 @@ public void UpdateAmounts()
InvoicePaidAmount = new Amounts()
{
Currency = InvoiceCurrency,
- Gross = PaidAmount.Gross * Rate,
- Net = PaidAmount.Net * Rate
+ Gross = PaymentPrompt.ToInvoiceCurrency(PaidAmount.Gross, Rate),
+ Net = PaymentPrompt.ToInvoiceCurrency(PaidAmount.Net, Rate)
};
}
}
### BTCPayServer/Services/Invoices/PosReceiptData.cs
@@ -107,6 +107,17 @@ public static PosReceiptData Create(bool isTopup, IEnumerable<AppItem> choices,
jposData.UpdateFrom(summary);
receiptData.UpdateTotals(jposData, order, summary, currency, displayFormatter);
}
+ else
+ {
+ jposData.UpdateFrom(new PoSOrder.OrderSummary());
+ jposData.Amounts = null;
+ jposData.CustomAmount = jposData.DiscountPercentage = jposData.TipPercentage = 0m;
+ foreach (var cartItem in jposData.Cart ?? [])
+ {
+ cartItem.Price = 0m;
+ cartItem.Count = 1;
+ }
+ }
receiptData.UpdateFromCart(choices, jposData, currency, displayFormatter);
return receiptData;
}
### BTCPayServer/Services/Reporting/PaymentRequestsReportProvider.cs
@@ -184,7 +184,7 @@ public override async Task Query(QueryContext queryContext, CancellationToken ca
if (invoice.TryGetRate(payment.Currency, out var rate))
{
- row.Add(displayFormatter.ToFormattedAmount(rate * payment.Value, invoice.Currency));
+ row.Add(displayFormatter.ToFormattedAmount(payment.InvoicePaidAmount.Gross, invoice.Currency));
row.Add(displayFormatter.ToFormattedAmount(rate, invoice.Currency));
}
else
### BTCPayServer/Services/Reporting/PaymentsReportProvider.cs
@@ -134,7 +134,7 @@ public override async Task Query(QueryContext queryContext, CancellationToken ca
values.Add(invoice.Currency);
if (invoice.TryGetRate(payment.Currency, out var rate))
{
- values.Add(DisplayFormatter.ToFormattedAmount(rate * payment.Value, invoice.Currency)); // Currency amount
+ values.Add(DisplayFormatter.ToFormattedAmount(payment.InvoicePaidAmount.Gross, invoice.Currency)); // Currency amount
values.Add(DisplayFormatter.ToFormattedAmount(rate, invoice.Currency));
}
else
### BTCPayServer/Validation/LengthLimits.cs
@@ -0,0 +1,8 @@
+namespace BTCPayServer;
+
+public static class LengthLimits
+{
+ public const int MaxOrderIdLength = 512;
+ public const int MaxUrlLength = 2048;
+ public const int MaxEmailLength = 254;
+}
### BTCPayServer/Validation/UriAttribute.cs
@@ -20,6 +20,7 @@ protected override ValidationResult IsValid(object value, ValidationContext vali
{
var str = value == null ? null : Convert.ToString(value, CultureInfo.InvariantCulture);
bool valid = string.IsNullOrEmpty(str) ||
+ str.Length <= LengthLimits.MaxUrlLength &&
Uri.TryCreate(str, UriKind.Absolute, out var uri) &&
Array.Exists(_allowedSchemes,
scheme => scheme.Equals(uri.Scheme, StringComparison.OrdinalIgnoreCase));Why this scored 61/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.