What changed, and why it matters
This commit hardens how BTCPay Server handles public web forms used during checkout, such as crowdfunding and point-of-sale purchases. Before the fix, shoppers could tamper with hidden or visible form fields to change prices, add bogus fees, inject oversized data, or overwrite server-only values. The patch now forces the real price to be set after the user submits the form but before validation, rejects non-numeric amount adjustments, clears values that should be server-controlled, caps text field lengths at 10,000 characters, and adds tests showing these tampering attempts are now blocked.
Deploy the patched version. Review any custom form providers or plugins that derive from FormComponentProviderBase to ensure they also enforce value length limits and do not trust client-submitted values for server-calculated or constant fields. Monitor logs for validation failures on public forms.
Security signals we found
Client-controlled hidden amount field could override invoice price before validation
Amount validation moved after server-side price assignment to prevent price tampering
Decimal parsing of amount adjustments now uses invariant culture and rejects invalid/non-numeric input
Fieldset values are cleared on validation, blocking submission of server-only constant field data
Input and textarea fields now enforce a 10,000-character length limit
Tests added for forged amount, oversized values, forged fieldset values, and invalid adjustment values
Evidence from the diff
The change addresses form-tampering vulnerabilities in BTCPay Server’s plugin forms. Key fixes: (1) In UICrowdfundController and UIPointOfSaleController, the amount field is now made constant and overwritten with the server-calculated price using InvariantCulture before validation runs, so a client-supplied invoice_amount cannot override the price. (2) FormDataService.Validate now explicitly validates invoice_amount, invoice_amount_adjustment*, and invoice_amount_multiply_adjustment* fields as decimal numbers and adds model errors on invalid values. (3) GenerateInvoiceParametersFromForm now uses CultureInfo.InvariantCulture for decimal parsing and skips empty adjustment fields. (4) HtmlFieldsetFormProvider.Validate now clears field.Value, preventing clients from submitting values for fieldset containers that may carry server-only constant data. (5) HtmlInputFormProvider and HtmlTextareaFormProvider enforce a 10,000-character maximum value length. Tests confirm rejection of oversized values, forged fieldset values, constant-field serialization, and invalid amount adjustments.
Changed components
BTCPayServer/Plugins/Crowdfund/Controllers/UICrowdfundController.csBTCPayServer/Plugins/PointOfSale/Controllers/UIPointOfSaleController.csBTCPayServer/Plugins/Forms/FormDataService.csBTCPayServer/Plugins/Forms/HtmlFieldsetFormProvider.csBTCPayServer/Plugins/Forms/HtmlInputFormProvider.csBTCPayServer/Plugins/Forms/HtmlTextareaFormProvider.csBTCPayServer.Tests/CrowdfundTests.csBTCPayServer.Tests/FormTests.csInspect captured patch +137 / −35
### BTCPayServer.Tests/CrowdfundTests.cs
@@ -339,7 +339,8 @@ public async Task CrowdfundWithFormNoPerk()
[
Field.Create("Enter your email", "item1", "test@toto.com", true, null, "email"),
Field.Create("Name", "item2", 2.ToString(), true, null),
- Field.Create("Item3", "invoice_item3", 3.ToString(), true, null)
+ Field.Create("Item3", "invoice_item3", 3.ToString(), true, null),
+ Field.Create("Amount", "invoice_amount", "0.01", true, null)
]
};
var frmData = new FormData
@@ -363,6 +364,9 @@ public async Task CrowdfundWithFormNoPerk()
var res = await crowdfund.CrowdfundFormSubmit(app.Id, (decimal)0.01, "", vm2);
Assert.IsNotType<NotFoundObjectResult>(res);
Assert.IsNotType<BadRequest>(res);
+ var forgedAmountResult = await crowdfund.ContributeToCrowdfund(app.Id,
+ new ContributeToCrowdfund { Amount = 0.01m }, """{"invoice_amount":"not-a-number"}""");
+ Assert.IsType<OkObjectResult>(forgedAmountResult);
}
[Fact(Timeout = LongRunningTestTimeout)]
### BTCPayServer.Tests/FormTests.cs
@@ -1,9 +1,11 @@
+using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BTCPayServer.Abstractions.Form;
using BTCPayServer.Forms;
using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json.Linq;
using Xunit;
@@ -18,6 +20,75 @@ public FormTests(ITestOutputHelper helper) : base(helper)
{
}
+ [Fact]
+ [Trait("FastTest", "FastTest")]
+ public void FormProvidersRejectOversizedValuesAndForgedFieldsetValues()
+ {
+ var oversized = new string('x', 10_001);
+ var input = new Field { Name = "reference", Type = "text", Value = oversized };
+ var textarea = new Field { Name = "notes", Type = "textarea", Value = oversized };
+
+ new HtmlInputFormProvider().Validate(new Form(), input);
+ new HtmlTextareaFormProvider().Validate(new Form(), textarea);
+
+ Assert.NotEmpty(input.ValidationErrors);
+ Assert.NotEmpty(textarea.ValidationErrors);
+
+ var fieldset = new Field
+ {
+ Name = "server",
+ Type = "fieldset",
+ Value = "forged"
+ };
+ new HtmlFieldsetFormProvider().Validate(new Form(), fieldset);
+ Assert.Null(fieldset.Value);
+ }
+
+ [Fact]
+ [Trait("FastTest", "FastTest")]
+ public void ConstantFieldsAreSerializedAndInvalidAdjustmentsAreRejected()
+ {
+ var providers = new FormComponentProviders(
+ [
+ new HtmlInputFormProvider(),
+ new HtmlTextareaFormProvider(),
+ new HtmlFieldsetFormProvider()
+ ]);
+ var service = new FormDataService(null!, providers);
+ var form = new Form
+ {
+ Fields =
+ [
+ new Field
+ {
+ Name = "server",
+ Type = "fieldset",
+ Constant = true,
+ Fields = [new Field { Name = "secret", Type = "hidden", Value = "server-only" }]
+ }
+ ]
+ };
+
+ Assert.Equal("server-only", service.GetValues(form)["server"]["secret"]);
+ Assert.Equal("server-only", service.GenerateInvoiceParametersFromForm(form).Metadata["server"]["secret"]);
+
+ form = new Form
+ {
+ Fields =
+ [
+ new Field
+ {
+ Name = $"{FormDataService.InvoiceParameterPrefix}amount_adjustment",
+ Type = "hidden",
+ Value = "not-a-number"
+ }
+ ]
+ };
+ var modelState = new ModelStateDictionary();
+ Assert.False(service.Validate(form, modelState));
+ Assert.False(modelState.IsValid);
+ }
+
[Fact(Timeout = TestUtils.TestTimeout)]
[Trait("Integration", "Integration")]
@@ -170,6 +241,8 @@ public async Task CanParseForm()
var obj = service.GetValues(form);
Assert.Equal("original", obj["invoice"]["test"].Value<string>());
Assert.Equal("updated", obj["invoice_item3"].Value<string>());
+ Assert.Equal("original",
+ service.GenerateInvoiceParametersFromForm(form).Metadata["invoice"]["test"].Value<string>());
Clear(form);
service.SetValues(form, obj);
obj = service.GetValues(form);
### BTCPayServer/Plugins/Crowdfund/Controllers/UICrowdfundController.cs
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
+using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
@@ -167,27 +168,22 @@ public async Task<IActionResult> ContributeToCrowdfund(string appId, ContributeT
formResponseJObject = TryParseJObject(formResponse) ?? new JObject();
var form = Form.Parse(formData.Config);
FormDataService.SetValues(form, formResponseJObject);
- if (!FormDataService.Validate(form, ModelState))
- {
- // someone tried to bypass validation
- return RedirectToAction(nameof(ViewCrowdfund), new { appId });
- }
-
-
var amtField = form.GetFieldByFullName($"{FormDataService.InvoiceParameterPrefix}amount");
if (amtField is null)
{
- form.Fields.Add(new Field
+ amtField = new Field
{
Name = $"{FormDataService.InvoiceParameterPrefix}amount",
Type = "hidden",
- Value = price?.ToString(),
Constant = true
- });
+ };
+ form.Fields.Add(amtField);
}
- else
+ amtField.Value = price?.ToString(CultureInfo.InvariantCulture);
+ if (!FormDataService.Validate(form, ModelState))
{
- amtField.Value = price?.ToString();
+ // someone tried to bypass validation
+ return RedirectToAction(nameof(ViewCrowdfund), new { appId });
}
formResponseJObject = FormDataService.GetValues(form);
### BTCPayServer/Plugins/Forms/FormDataService.cs
@@ -127,7 +127,22 @@ public async Task AddOrUpdateForm(FormData data)
public bool Validate(Form form, ModelStateDictionary modelState)
{
- return _formProviders.Validate(form, modelState);
+ _formProviders.Validate(form, modelState);
+ var amountFields = $"{InvoiceParameterPrefix}amount";
+ var addAdjustment = $"{InvoiceParameterPrefix}amount_adjustment";
+ var multiplyAdjustment = $"{InvoiceParameterPrefix}amount_multiply_adjustment";
+ foreach (var field in form.GetAllFields())
+ {
+ if (field.FullName != amountFields &&
+ !field.FullName.StartsWith(addAdjustment) &&
+ !field.FullName.StartsWith(multiplyAdjustment))
+ continue;
+ var value = GetValue(form, field.Field);
+ if (!string.IsNullOrEmpty(value) &&
+ !decimal.TryParse(value, NumberStyles.Number, CultureInfo.InvariantCulture, out _))
+ modelState.AddModelError(field.Field.Name, "Invalid numeric value");
+ }
+ return modelState.IsValid;
}
public bool IsFormSchemaValid(string schema, [MaybeNullWhen(false)] out Form form, [MaybeNullWhen(false)] out string error)
@@ -155,22 +170,32 @@ public CreateInvoiceRequest GenerateInvoiceParametersFromForm(Form form)
var amt = string.IsNullOrEmpty(amtRaw) ? (decimal?) null : decimal.Parse(amtRaw, CultureInfo.InvariantCulture);
foreach (var f in form.GetAllFields())
{
- if (f.FullName.StartsWith($"{InvoiceParameterPrefix}amount_adjustment") && decimal.TryParse(GetValue(form, f.Field), out var adjustment))
+ if (f.FullName.StartsWith($"{InvoiceParameterPrefix}amount_adjustment"))
{
- if (amt is null)
- {
- amt = adjustment;
- }
- else
+ var adjustmentRaw = GetValue(form, f.Field);
+ if (!string.IsNullOrEmpty(adjustmentRaw))
{
- amt += adjustment;
+ var adjustment = decimal.Parse(adjustmentRaw, CultureInfo.InvariantCulture);
+ if (amt is null)
+ {
+ amt = adjustment;
+ }
+ else
+ {
+ amt += adjustment;
+ }
}
- }
- if (f.FullName.StartsWith($"{InvoiceParameterPrefix}amount_multiply_adjustment") && decimal.TryParse(GetValue(form, f.Field), out var adjustmentM))
+ }
+ if (f.FullName.StartsWith($"{InvoiceParameterPrefix}amount_multiply_adjustment"))
{
- if (amt is not null)
+ var adjustmentRaw = GetValue(form, f.Field);
+ if (!string.IsNullOrEmpty(adjustmentRaw))
{
- amt *= adjustmentM;
+ var adjustmentM = decimal.Parse(adjustmentRaw, CultureInfo.InvariantCulture);
+ if (amt is not null)
+ {
+ amt *= adjustmentM;
+ }
}
}
}
### BTCPayServer/Plugins/Forms/HtmlFieldsetFormProvider.cs
@@ -25,5 +25,6 @@ public void SetValue(Field field, JToken value)
public void Validate(Form form, Field field)
{
+ field.Value = null;
}
}
### BTCPayServer/Plugins/Forms/HtmlInputFormProvider.cs
@@ -7,6 +7,8 @@ namespace BTCPayServer.Forms;
public class HtmlInputFormProvider : FormComponentProviderBase
{
+ private const int MaxValueLength = 10_000;
+
public override void Register(Dictionary<string, IFormComponentProvider> typeToComponentProvider)
{
foreach (var t in new[] {
@@ -39,9 +41,9 @@ public override void Validate(Form form, Field field)
else if (string.IsNullOrEmpty(field.Value))
return;
+ if (field.Value.Length > MaxValueLength)
+ field.ValidationErrors.Add($"The value must be at most {MaxValueLength} characters.");
if (field.Type == "email")
- {
ValidateField<MailboxAddressAttribute>(field);
- }
}
}
### BTCPayServer/Plugins/Forms/HtmlTextareaFormProvider.cs
@@ -6,6 +6,8 @@ namespace BTCPayServer.Forms;
public class HtmlTextareaFormProvider : FormComponentProviderBase
{
+ private const int MaxValueLength = 10_000;
+
public override void Register(Dictionary<string, IFormComponentProvider> typeToComponentProvider)
{
typeToComponentProvider.Add("textarea", this);
@@ -16,8 +18,8 @@ public override void Register(Dictionary<string, IFormComponentProvider> typeToC
public override void Validate(Form form, Field field)
{
if (field.Required)
- {
ValidateField<RequiredAttribute>(field);
- }
+ if (field.Value?.Length > MaxValueLength)
+ field.ValidationErrors.Add($"The value must be at most {MaxValueLength} characters.");
}
}
### BTCPayServer/Plugins/PointOfSale/Controllers/UIPointOfSaleController.cs
@@ -351,12 +351,6 @@ jposData.Amounts is null &&
formResponseJObject = TryParseJObject(formResponse) ?? new JObject();
var form = Form.Parse(formData.Config);
FormDataService.SetValues(form, formResponseJObject);
- if (!FormDataService.Validate(form, ModelState))
- {
- //someone tried to bypass validation
- return RedirectToAction(nameof(ViewPointOfSale), new { appId, viewType });
- }
-
var amtField = form.GetFieldByFullName($"{FormDataService.InvoiceParameterPrefix}amount");
if (amtField is null)
{
@@ -370,6 +364,11 @@ jposData.Amounts is null &&
}
var originalAmount = order.Calculate().PriceTaxExcluded;
amtField.Value = originalAmount.ToString(CultureInfo.InvariantCulture);
+ if (!FormDataService.Validate(form, ModelState))
+ {
+ //someone tried to bypass validation
+ return RedirectToAction(nameof(ViewPointOfSale), new { appId, viewType });
+ }
formResponseJObject = FormDataService.GetValues(form);
var invoiceRequest = FormDataService.GenerateInvoiceParametersFromForm(form);Why this scored 77/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.