Harden untrusted HTML and URL handling (#7666)
What changed, and why it matters
This commit tightens how BTCPay Server handles web links and HTML that come from user or invoice data. It blocks dangerous URL schemes like javascript: and data:, and it HTML-encodes values before putting them into emails and web pages. These changes reduce the risk that an attacker could trick an administrator or customer into running malicious code through invoice metadata, subscription redirect URLs, email notifications, or wallet labels.
Treat this as a security hardening patch addressing cross-site scripting and unsafe-redirect risks. Review whether any other user-supplied URLs or HTML are still rendered unencoded, and consider applying the same GetSafeHttpUrl/IsSafeRedirectUrl pattern to any remaining redirect or link fields. No immediate emergency response is indicated, but deployment should follow normal security-update prioritization.
Security signals we found
URL scheme allowlisting for invoice orderUrl and redirectUrl
Validation of subscription SuccessRedirectUrl to http/https absolute URLs
HTML encoding added to email notification body fields
Raw HTML rendering removed from PointOfSale error status message
HTML encoding added to webhook tooltip error message
Scheme allowlisting for wallet label custom attachment links
UriAttribute default restricted to http/https and whitespace rejected
Evidence from the diff
The patch hardens untrusted HTML/URL handling across multiple components. Key changes: (1) invoice order URLs and receipt redirect URLs are now filtered to absolute http/https only via GetSafeHttpUrl; (2) subscription plan SuccessRedirectUrl is validated to be absolute http/https; (3) the UriAttribute validator now defaults to http/https and rejects whitespace-only values; (4) BitpayIPNSender HTML-encodes JSON and dynamic fields in notification emails; (5) PointOfSale error messages are no longer rendered as raw HTML; (6) webhook tooltip error messages and wallet label links are encoded or scheme-restricted. Tests are added for each restriction.
Changed components
UIInvoiceController (invoice details and receipt)GreenfieldOfferingController (subscription offerings)BitpayIPNSender (email notifications)UIPointOfSaleController (error status messages)Webhooks viewLabelService (wallet transaction labels)UriAttribute validatorInspect captured patch +146 / −21
### BTCPayServer.Data/Data/Subscriptions/PlanCheckoutData.cs
@@ -111,13 +111,19 @@ public enum OnPayBehavior
public string? GetRedirectUrl()
{
- if (SuccessRedirectUrl is null)
+ if (!IsSafeRedirectUrl(SuccessRedirectUrl))
return null;
// Add ?checkoutPlanId=... to the redirect URL
- try { return QueryHelpers.AddQueryString(SuccessRedirectUrl, "checkoutPlanId", Id); }
+ try { return QueryHelpers.AddQueryString(SuccessRedirectUrl!, "checkoutPlanId", Id); }
catch (UriFormatException) { return null; }
}
+ public static bool IsSafeRedirectUrl(string? url)
+ {
+ return Uri.TryCreate(url, UriKind.Absolute, out var uri) &&
+ uri.Scheme is "http" or "https";
+ }
+
public static void OnModelCreating(ModelBuilder builder, DatabaseFacade databaseFacade)
{
var b = builder.Entity<PlanCheckoutData>();
### BTCPayServer.Tests/FastTests.cs
@@ -18,6 +18,7 @@
using BTCPayServer.Client.Models;
using BTCPayServer.Configuration;
using BTCPayServer.Data;
+using BTCPayServer.Data.Subscriptions;
using BTCPayServer.HostedServices;
using BTCPayServer.Hosting;
using BTCPayServer.JsonConverters;
@@ -104,6 +105,29 @@ public void CreateTransactionTagModelsIgnoresInvalidCpfpOutpoints()
Assert.DoesNotContain("invalid", model.Tooltip);
}
+ [Theory]
+ [InlineData("https://example.com/details", "https://example.com/details")]
+ [InlineData("/wallet/transactions", null)]
+ [InlineData("#", "#")]
+ [InlineData("javascript:alert(1)", null)]
+ [InlineData("data:text/html,<script>alert(1)</script>", null)]
+ [InlineData("//example.com/details", null)]
+ public void CreateTransactionTagModelsOnlyAllowsSafeCustomAttachmentLinks(string link, string expected)
+ {
+ const string type = "custom";
+ var transactionInfo = new WalletTransactionInfo(new WalletId("store", "BTC"));
+ transactionInfo.LabelColors.Add(type, "#000000");
+ transactionInfo.Attachments.Add(new Attachment(type, data: new JObject
+ {
+ ["link"] = link
+ }));
+
+ var model = Assert.Single(new LabelService(null!).CreateTransactionTagModels(
+ transactionInfo, new DefaultHttpContext().Request));
+
+ Assert.Equal(expected, model.Link);
+ }
+
private class RequestInspectingClient : BTCPayServerClient
{
public RequestInspectingClient(Uri btcpayHost) : base(btcpayHost)
@@ -446,10 +470,29 @@ public void CanHandleUriValidation()
Assert.False(attribute.IsValid(2));
Assert.False(attribute.IsValid("http://"));
Assert.False(attribute.IsValid("httpdsadsa.com"));
+ Assert.False(attribute.IsValid(" "));
+ Assert.False(attribute.IsValid("javascript:document.body.dataset.pwned=1"));
+ Assert.False(attribute.IsValid("data:text/html,<script>alert(1)</script>"));
var webUriAttribute = new UriAttribute("http", "https");
Assert.True(webUriAttribute.IsValid("https://example.com"));
Assert.False(webUriAttribute.IsValid("javascript:document.body.dataset.pwned=1"));
+ Assert.True(new UriAttribute("ftp").IsValid("ftp://example.com/file"));
+ }
+
+ [Fact]
+ public void PlanCheckoutRedirectOnlyAllowsHttpUrls()
+ {
+ var checkout = new PlanCheckoutData { Id = "checkout-id" };
+
+ checkout.SuccessRedirectUrl = "javascript:alert(1)";
+ Assert.Null(checkout.GetRedirectUrl());
+ checkout.SuccessRedirectUrl = "data:text/html,<script>alert(1)</script>";
+ Assert.Null(checkout.GetRedirectUrl());
+ checkout.SuccessRedirectUrl = "/subscriptions/success";
+ Assert.Null(checkout.GetRedirectUrl());
+ checkout.SuccessRedirectUrl = "https://example.com/success?source=test";
+ Assert.Equal("https://example.com/success?source=test&checkoutPlanId=checkout-id", checkout.GetRedirectUrl());
}
[Fact]
### BTCPayServer.Tests/PlaywrightTests.cs
@@ -2383,6 +2383,39 @@ await TestUtils.EventuallyAsync(async () =>
Assert.Contains("100.00 USD", content);
Assert.Contains(i, content);
+ var api = await s.AsTestAccount().CreateClient();
+ var unsafeOrderUrlInvoice = await api.CreateInvoice(s.StoreId, new CreateInvoiceRequest
+ {
+ Amount = 1,
+ Currency = "USD",
+ Metadata = new JObject
+ {
+ ["orderId"] = "unsafe-order",
+ ["orderUrl"] = "javascript:alert(1)"
+ },
+ Receipt = new InvoiceDataBase.ReceiptOptions { Enabled = true }
+ });
+ await s.GoToUrl($"/i/{unsafeOrderUrlInvoice.Id}/receipt");
+ Assert.Equal(0, await s.Page.Locator("#StoreLink").CountAsync());
+ await s.GoToInvoice(unsafeOrderUrlInvoice.Id);
+ Assert.Equal(0, await s.Page.Locator(".invoice-order-link").CountAsync());
+
+ var safeOrderUrlInvoice = await api.CreateInvoice(s.StoreId, new CreateInvoiceRequest
+ {
+ Amount = 1,
+ Currency = "USD",
+ Metadata = new JObject
+ {
+ ["orderId"] = "safe-order",
+ ["orderUrl"] = "https://example.com/order"
+ },
+ Receipt = new InvoiceDataBase.ReceiptOptions { Enabled = true }
+ });
+ await s.GoToUrl($"/i/{safeOrderUrlInvoice.Id}/receipt");
+ await Expect(s.Page.Locator("#StoreLink")).ToHaveAttributeAsync("href", "https://example.com/order");
+ await s.GoToInvoice(safeOrderUrlInvoice.Id);
+ await Expect(s.Page.Locator(".invoice-order-link")).ToHaveAttributeAsync("href", "https://example.com/order");
+
await s.GoToInvoices(s.StoreId);
i = await s.CreateInvoice();
await s.GoToInvoiceCheckout(i);
### BTCPayServer.Tests/SubscriptionTests.cs
@@ -532,6 +532,18 @@ public async Task CanUseSubscriptionAPI()
await user.CreateStoreAsync();
var client = await user.CreateClient();
+ await AssertEx.AssertValidationError(["SuccessRedirectUrl"], () =>
+ client.CreateOffering(user.StoreId, new OfferingModel
+ {
+ AppName = "Unsafe",
+ SuccessRedirectUrl = "javascript:alert(1)"
+ }));
+ await AssertEx.AssertValidationError(["SuccessRedirectUrl"], () =>
+ client.CreateOffering(user.StoreId, new OfferingModel
+ {
+ AppName = "Unsafe",
+ SuccessRedirectUrl = " "
+ }));
var offering = await client.CreateOffering(user.StoreId, new OfferingModel()
{
AppName = "Test",
@@ -607,6 +619,12 @@ public async Task CanUseSubscriptionAPI()
Assert.Equal("updated", offering.Metadata["subscription"]?.ToString());
Assert.Equal(2, offering.Features.Count);
Assert.Contains(offering.Features, f => f.Id == "can-access3");
+ await AssertEx.AssertValidationError(["SuccessRedirectUrl"], () =>
+ client.UpdateOffering(user.StoreId, offering.Id, new OfferingModel
+ {
+ AppName = "Test Updated",
+ SuccessRedirectUrl = "data:text/html,<script>alert(1)</script>"
+ }));
Assert.Equal(("NewPlanV2", 10m, "USD"), (plan.Name, plan.Price, plan.Currency));
plan = await client.GetOfferingPlan(user.StoreId, offering.Id, plan.Id);
### BTCPayServer/Controllers/UIInvoiceController.UI.cs
@@ -146,6 +146,7 @@ public async Task<IActionResult> Invoice(string invoiceId)
: _displayFormatter.Currency(invoice.Metadata.TaxIncluded ?? 0.0m, invoice.Currency),
NotificationUrl = invoice.NotificationURL?.AbsoluteUri,
RedirectUrl = invoice.RedirectURL?.AbsoluteUri,
+ OrderUrl = GetSafeHttpUrl(invoice.Metadata.OrderUrl),
TypedMetadata = invoice.Metadata,
StatusException = invoice.ExceptionStatus,
Events = await _InvoiceRepository.GetInvoiceLogs(invoice.Id),
@@ -219,7 +220,7 @@ public async Task<IActionResult> InvoiceReceipt(string invoiceId, [FromQuery] bo
{
InvoiceId = i.Id,
OrderId = i.Metadata?.OrderId,
- RedirectUrl = i.RedirectURL?.AbsoluteUri ?? i.Metadata?.OrderUrl,
+ RedirectUrl = i.RedirectURL?.AbsoluteUri ?? GetSafeHttpUrl(i.Metadata?.OrderUrl),
Status = i.Status,
Currency = i.Currency,
InvoiceAmount = i.Price,
@@ -1190,6 +1191,13 @@ public async Task<IActionResult> CreateInvoice(string? storeId = null)
return View(vm);
}
+ private static string? GetSafeHttpUrl(string? value)
+ {
+ return Uri.TryCreate(value, UriKind.Absolute, out var uri) && uri.Scheme is "http" or "https"
+ ? uri.AbsoluteUri
+ : null;
+ }
+
[HttpPost("/stores/{storeId}/invoices/create")]
[HttpPost("invoices/create")]
[Authorize(Policy = Policies.CanCreateInvoice, AuthenticationSchemes = AuthenticationSchemes.Cookie)]
### BTCPayServer/Models/InvoicingModels/InvoiceDetailsModel.cs
@@ -115,6 +115,7 @@ public string NotificationUrl
}
public string RedirectUrl { get; set; }
+ public string OrderUrl { get; set; }
public string Fiat
{
get;
### BTCPayServer/Plugins/Bitpay/BitpayIPNSender.cs
@@ -3,6 +3,7 @@
using System.Linq;
using System.Net.Http;
using System.Text;
+using System.Text.Encodings.Web;
using System.Threading;
using System.Threading.Tasks;
using BTCPayServer.Events;
@@ -132,13 +133,15 @@ async Task Notify(InvoiceEntity invoice, InvoiceEvent invoiceEvent, bool extende
invoice.NotificationEmail is String e &&
MailboxAddressValidator.TryParse(e, out MailboxAddress notificationEmail))
{
- var json = NBitcoin.JsonConverters.Serializer.ToString(notification);
+ string Encode(object value) => HtmlEncoder.Default.Encode(value?.ToString() ?? string.Empty);
+
+ var json = Encode(NBitcoin.JsonConverters.Serializer.ToString(notification));
var store = await _StoreRepository.FindStore(invoice.StoreId);
- var storeName = store.StoreName ?? "BTCPay Server";
+ var storeName = Encode(store.StoreName ?? "BTCPay Server");
var emailBody = $"Store: {storeName}<br>" +
- $"Invoice ID: {notification.Data.Id}<br>" +
- $"Status: {notification.Data.Status}<br>" +
- $"Amount: {notification.Data.Price} {notification.Data.Currency}<br>" +
+ $"Invoice ID: {Encode(notification.Data.Id)}<br>" +
+ $"Status: {Encode(notification.Data.Status)}<br>" +
+ $"Amount: {Encode(notification.Data.Price)} {Encode(notification.Data.Currency)}<br>" +
$"<br><details><summary>Details</summary><pre>{json}</pre></details>";
(await _EmailSenderFactory.GetEmailSender(invoice.StoreId)).SendEmail(
### BTCPayServer/Plugins/PointOfSale/Controllers/UIPointOfSaleController.cs
@@ -443,7 +443,7 @@ jposData.Amounts is null &&
if (wantsJson) return Json(new { error = e.Message });
TempData.SetStatusMessageModel(new StatusMessageModel
{
- Html = e.Message.Replace("\n", "<br />", StringComparison.OrdinalIgnoreCase),
+ Message = e.Message,
Severity = StatusMessageModel.StatusSeverity.Error,
AllowDismiss = true
});
### BTCPayServer/Plugins/Subscriptions/Controllers/GreenfieldOfferingController.cs
@@ -58,7 +58,7 @@ public async Task<IActionResult> CreateOffering(string storeId, [FromBody] Offer
{
if (request?.AppName is null)
ModelState.AddModelError(nameof(request.AppName), "AppName is required");
- ValidateOfferingFeatures(request);
+ ValidateOffering(request);
if (!ModelState.IsValid || request?.AppName is null)
return this.CreateValidationError(ModelState);
var o = await appService.CreateOffering(storeId, request.AppName);
@@ -87,7 +87,7 @@ public async Task<IActionResult> UpdateOffering(string storeId, string offeringI
{
if (request?.AppName is null)
ModelState.AddModelError(nameof(request.AppName), "AppName is required");
- ValidateOfferingFeatures(request);
+ ValidateOffering(request);
if (!ModelState.IsValid || request?.AppName is null)
return this.CreateValidationError(ModelState);
@@ -116,8 +116,14 @@ public async Task<IActionResult> UpdateOffering(string storeId, string offeringI
return await GetOffering(storeId, offeringId);
}
- private void ValidateOfferingFeatures(OfferingModel? request)
+ private void ValidateOffering(OfferingModel? request)
{
+ if (!string.IsNullOrEmpty(request?.SuccessRedirectUrl) &&
+ !PlanCheckoutData.IsSafeRedirectUrl(request.SuccessRedirectUrl))
+ {
+ ModelState.AddModelError(nameof(request.SuccessRedirectUrl), "SuccessRedirectUrl must be an HTTP or HTTPS URL");
+ }
+
if (request?.Features is null)
return;
for (var i = 0; i < request.Features.Count; i++)
### BTCPayServer/Plugins/Wallets/Views/UIWallets/_PSBTInfo.cshtml
@@ -192,4 +192,3 @@
});
</script>
-
### BTCPayServer/Plugins/Webhooks/Views/Webhooks.cshtml
@@ -47,7 +47,7 @@
<span id="delivery-status-icon"
data-bs-toggle="tooltip"
data-bs-html="true"
- title="Error: @wh.LastDeliveryErrorMessage. <br/> Delivery last attempted <span id='last-delivery-time'>@wh.LastDeliveryTimeStamp?.ToTimeAgo()</span>">
+ title="Error: @Html.Encode(wh.LastDeliveryErrorMessage). <br/> Delivery last attempted <span id='last-delivery-time'>@wh.LastDeliveryTimeStamp?.ToTimeAgo()</span>">
<vc:icon symbol="cross" css-class="text-danger" />
</span>
}
### BTCPayServer/Services/Labels/LabelService.cs
@@ -150,7 +150,13 @@ string PayoutTooltip(IGrouping<string, string>? payoutsByPullPaymentId = null)
model.Tooltip = tag.Data?.TryGetValue("tooltip", StringComparison.InvariantCultureIgnoreCase, out var tooltip) is true ? tooltip.ToString() : tag.Id;
if (tag.Data?.TryGetValue("link", StringComparison.InvariantCultureIgnoreCase, out var link) is true)
{
- model.Link = link.ToString();
+ var value = link.ToString();
+ if (value == "#" ||
+ (Uri.TryCreate(value, UriKind.Absolute, out var uri) &&
+ uri.Scheme is "http" or "https"))
+ {
+ model.Link = value;
+ }
}
}
}
### BTCPayServer/Validation/UriAttribute.cs
@@ -11,16 +11,18 @@ public class UriAttribute : ValidationAttribute
public UriAttribute(params string[] allowedSchemes)
{
- _allowedSchemes = allowedSchemes;
+ _allowedSchemes = allowedSchemes.Length is 0
+ ? [Uri.UriSchemeHttp, Uri.UriSchemeHttps]
+ : allowedSchemes;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var str = value == null ? null : Convert.ToString(value, CultureInfo.InvariantCulture);
- bool valid = string.IsNullOrWhiteSpace(str) ||
+ bool valid = string.IsNullOrEmpty(str) ||
Uri.TryCreate(str, UriKind.Absolute, out var uri) &&
- (_allowedSchemes.Length == 0 || Array.Exists(_allowedSchemes,
- scheme => scheme.Equals(uri.Scheme, StringComparison.OrdinalIgnoreCase)));
+ Array.Exists(_allowedSchemes,
+ scheme => scheme.Equals(uri.Scheme, StringComparison.OrdinalIgnoreCase));
if (!valid)
{
### BTCPayServer/Views/UIInvoice/Invoice.cshtml
@@ -239,9 +239,9 @@
<tr>
<th text-translate="true">Order Id</th>
<td>
- @if (!string.IsNullOrEmpty(Model.TypedMetadata.OrderUrl))
+ @if (!string.IsNullOrEmpty(Model.OrderUrl))
{
- <a href="@Model.TypedMetadata.OrderUrl" rel="noreferrer noopener" target="_blank">
+ <a class="invoice-order-link" href="@Model.OrderUrl" rel="noreferrer noopener" target="_blank">
@if (string.IsNullOrEmpty(Model.TypedMetadata.OrderId))
{
<span text-translate="true">View Order</span>Why this scored 68/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.