mirror of
https://github.com/Such-Software/xmrcheckout.git
synced 2026-12-01 12:14:11 +01:00
fix(webhooks): refuse internal webhook targets and stop following redirects
Merchant-supplied webhook URLs were posted to without any host check, redirects were followed, and the raw request error was stored and returned to the caller. With open registration, anyone could make the service send requests to the wallet RPC, the database, the daemon or a cloud metadata address, and read back what the error revealed. Every delivery path now goes through webhook_targets.post_webhook. It accepts only http and https URLs without embedded credentials, requires every resolved address to be public, and never follows redirects (a 3xx is a failed delivery). WEBHOOK_ALLOWED_PRIVATE_HOSTS names exact hosts that may resolve privately, for receivers reached over a LAN. Stored delivery errors carry only the refusal reason or the exception class.
This commit is contained in:
+11
-38
@@ -6,20 +6,16 @@ import json
|
||||
import logging
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from urllib.parse import urljoin
|
||||
|
||||
import requests
|
||||
from requests import RequestException
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from .models import BtcpayWebhook, Invoice, InvoiceTransfer
|
||||
from .security import decrypt_secret
|
||||
from .webhook_targets import WebhookTargetRefused, post_webhook
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_REDIRECT_STATUSES = {301, 302, 303, 307, 308}
|
||||
|
||||
|
||||
def dispatch_btcpay_webhooks(
|
||||
db: Session,
|
||||
user_id: str,
|
||||
@@ -61,13 +57,13 @@ def dispatch_btcpay_webhooks(
|
||||
last_response = None
|
||||
for attempt in range(3):
|
||||
try:
|
||||
last_response = _post_with_redirects(
|
||||
last_response = post_webhook(
|
||||
hook.url,
|
||||
data=body,
|
||||
headers=headers,
|
||||
timeout=10,
|
||||
)
|
||||
if last_response is not None and last_response.status_code < 500:
|
||||
if last_response.status_code < 500:
|
||||
break
|
||||
except RequestException:
|
||||
if attempt == 2:
|
||||
@@ -75,12 +71,9 @@ def dispatch_btcpay_webhooks(
|
||||
if attempt < 2:
|
||||
time.sleep(1.0 * (attempt + 1))
|
||||
if last_response is None:
|
||||
logger.warning(
|
||||
"BTCPay webhook delivery failed after retries (redirect loop)",
|
||||
extra={"webhook_id": str(hook.id), "event": event_type, "url": hook.url},
|
||||
)
|
||||
continue
|
||||
if last_response.status_code >= 400:
|
||||
# Redirects are not followed, so a 3xx is a failed delivery.
|
||||
if last_response.status_code >= 300:
|
||||
logger.warning(
|
||||
"BTCPay webhook delivered non-success status",
|
||||
extra={
|
||||
@@ -89,6 +82,12 @@ def dispatch_btcpay_webhooks(
|
||||
"http_status": last_response.status_code,
|
||||
},
|
||||
)
|
||||
except WebhookTargetRefused as exc:
|
||||
logger.warning(
|
||||
"BTCPay webhook target refused: %s",
|
||||
exc,
|
||||
extra={"webhook_id": str(hook.id), "event": event_type},
|
||||
)
|
||||
except RequestException as exc:
|
||||
logger.error(
|
||||
"BTCPay webhook delivery failed after 3 attempts: %s",
|
||||
@@ -179,29 +178,3 @@ def _after_expiration(invoice: Invoice) -> bool:
|
||||
|
||||
def _sign_payload(body: bytes, secret: str) -> str:
|
||||
return hmac.new(secret.encode("utf-8"), body, hashlib.sha256).hexdigest()
|
||||
|
||||
|
||||
def _post_with_redirects(
|
||||
url: str,
|
||||
*,
|
||||
data: bytes,
|
||||
headers: dict[str, str],
|
||||
timeout: int,
|
||||
max_redirects: int = 3,
|
||||
) -> requests.Response | None:
|
||||
current_url = url
|
||||
for _ in range(max_redirects + 1):
|
||||
response = requests.post(
|
||||
current_url,
|
||||
data=data,
|
||||
headers=headers,
|
||||
timeout=timeout,
|
||||
allow_redirects=False,
|
||||
)
|
||||
if response.status_code not in _REDIRECT_STATUSES:
|
||||
return response
|
||||
location = response.headers.get("Location")
|
||||
if not location:
|
||||
return response
|
||||
current_url = urljoin(current_url, location)
|
||||
return None
|
||||
|
||||
@@ -47,3 +47,12 @@ FOUNDER_PAYMENT_ADDRESS = os.getenv("FOUNDER_PAYMENT_ADDRESS", "")
|
||||
FOUNDER_VIEW_KEY = os.getenv("FOUNDER_VIEW_KEY", "")
|
||||
QR_STORAGE_DIR = os.getenv("QR_STORAGE_DIR", "/qr")
|
||||
ADMIN_API_KEY = os.getenv("ADMIN_API_KEY", "").strip()
|
||||
|
||||
# Webhook targets must resolve to public addresses. Hostnames listed here may
|
||||
# resolve to private addresses, for a merchant receiver reached over a LAN.
|
||||
# Exact hostnames, comma separated; empty refuses every private target.
|
||||
WEBHOOK_ALLOWED_PRIVATE_HOSTS = frozenset(
|
||||
host.strip().lower().rstrip(".")
|
||||
for host in os.getenv("WEBHOOK_ALLOWED_PRIVATE_HOSTS", "").split(",")
|
||||
if host.strip()
|
||||
)
|
||||
|
||||
+4
-4
@@ -8,7 +8,6 @@ import json
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response, status
|
||||
from fastapi.responses import RedirectResponse, StreamingResponse
|
||||
import requests
|
||||
from requests import RequestException
|
||||
from sqlalchemy import func, or_
|
||||
from sqlalchemy.sql import cast
|
||||
@@ -60,6 +59,7 @@ from .security import (
|
||||
require_api_key,
|
||||
)
|
||||
from .webhooks import build_webhook_payload, dispatch_webhooks
|
||||
from .webhook_targets import WebhookTargetRefused, delivery_error_message, post_webhook
|
||||
from .qr_codes import ensure_invoice_qr_png, invoice_qr_url, resolve_qr_settings
|
||||
router = APIRouter()
|
||||
|
||||
@@ -740,15 +740,15 @@ def redeliver_webhook_delivery(
|
||||
status_code = None
|
||||
error_message = None
|
||||
try:
|
||||
response = requests.post(
|
||||
response = post_webhook(
|
||||
delivery.url,
|
||||
json=payload,
|
||||
headers={"X-Webhook-Secret": webhook_secret},
|
||||
timeout=5,
|
||||
)
|
||||
status_code = response.status_code
|
||||
except RequestException as exc:
|
||||
error_message = str(exc)
|
||||
except (RequestException, WebhookTargetRefused) as exc:
|
||||
error_message = delivery_error_message(exc)
|
||||
|
||||
redelivery = WebhookDelivery(
|
||||
user_id=user.id,
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import ipaddress
|
||||
import socket
|
||||
from typing import Any
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
import requests
|
||||
|
||||
from .config import WEBHOOK_ALLOWED_PRIVATE_HOSTS
|
||||
|
||||
|
||||
class WebhookTargetRefused(Exception):
|
||||
"""The webhook URL points somewhere this service must not send requests."""
|
||||
|
||||
|
||||
def _is_public(address: ipaddress.IPv4Address | ipaddress.IPv6Address) -> bool:
|
||||
if isinstance(address, ipaddress.IPv6Address) and address.ipv4_mapped is not None:
|
||||
address = address.ipv4_mapped
|
||||
return address.is_global and not (
|
||||
address.is_private
|
||||
or address.is_loopback
|
||||
or address.is_link_local
|
||||
or address.is_multicast
|
||||
or address.is_reserved
|
||||
or address.is_unspecified
|
||||
)
|
||||
|
||||
|
||||
def _resolve(host: str, port: int) -> list[ipaddress.IPv4Address | ipaddress.IPv6Address]:
|
||||
try:
|
||||
infos = socket.getaddrinfo(host, port, type=socket.SOCK_STREAM)
|
||||
except socket.gaierror as exc:
|
||||
raise WebhookTargetRefused("webhook host does not resolve") from exc
|
||||
return [ipaddress.ip_address(info[4][0].split("%", 1)[0]) for info in infos]
|
||||
|
||||
|
||||
def check_webhook_target(url: str, *, allowed_private_hosts: frozenset[str] | None = None) -> None:
|
||||
"""Refuse a URL that is not http(s) or that resolves to a non-public address.
|
||||
|
||||
Every resolved address must be public, so a name with one private record is
|
||||
refused. Hosts in allowed_private_hosts (default: WEBHOOK_ALLOWED_PRIVATE_HOSTS)
|
||||
skip the address check.
|
||||
"""
|
||||
allowed = WEBHOOK_ALLOWED_PRIVATE_HOSTS if allowed_private_hosts is None else allowed_private_hosts
|
||||
parts = urlsplit(url)
|
||||
if parts.scheme not in ("http", "https"):
|
||||
raise WebhookTargetRefused("webhook URL must use http or https")
|
||||
host = (parts.hostname or "").lower().rstrip(".")
|
||||
if not host:
|
||||
raise WebhookTargetRefused("webhook URL has no host")
|
||||
if parts.username or parts.password:
|
||||
raise WebhookTargetRefused("webhook URL must not carry credentials")
|
||||
if host in allowed:
|
||||
return
|
||||
try:
|
||||
port = parts.port or (443 if parts.scheme == "https" else 80)
|
||||
except ValueError as exc:
|
||||
raise WebhookTargetRefused("webhook URL has an invalid port") from exc
|
||||
addresses = _resolve(host, port)
|
||||
if not addresses or not all(_is_public(address) for address in addresses):
|
||||
raise WebhookTargetRefused("webhook host resolves to a non-public address")
|
||||
|
||||
|
||||
def post_webhook(url: str, **kwargs: Any) -> requests.Response:
|
||||
"""Check the target, then POST once without following redirects."""
|
||||
check_webhook_target(url)
|
||||
kwargs["allow_redirects"] = False
|
||||
return requests.post(url, **kwargs)
|
||||
|
||||
|
||||
def delivery_error_message(exc: Exception) -> str:
|
||||
"""A delivery error safe to store and show: never the raw exception text."""
|
||||
if isinstance(exc, WebhookTargetRefused):
|
||||
return f"refused: {exc}"
|
||||
return f"delivery failed ({type(exc).__name__})"
|
||||
+4
-4
@@ -4,13 +4,13 @@ import logging
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
import requests
|
||||
from requests import RequestException
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from .formatting import format_xmr_amount
|
||||
from .models import Invoice, User, Webhook, WebhookDelivery
|
||||
from .security import decrypt_secret, encrypt_secret, generate_webhook_secret
|
||||
from .webhook_targets import WebhookTargetRefused, delivery_error_message, post_webhook
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -73,10 +73,10 @@ def dispatch_webhooks(
|
||||
error_message = None
|
||||
try:
|
||||
headers = {"X-Webhook-Secret": webhook_secret} if webhook_secret else None
|
||||
response = requests.post(target_url, json=payload, headers=headers, timeout=5)
|
||||
response = post_webhook(target_url, json=payload, headers=headers, timeout=5)
|
||||
status_code = response.status_code
|
||||
except RequestException as exc:
|
||||
error_message = str(exc)
|
||||
except (RequestException, WebhookTargetRefused) as exc:
|
||||
error_message = delivery_error_message(exc)
|
||||
logger.warning(
|
||||
"Webhook delivery failed",
|
||||
extra={"webhook_id": str(hook.id), "event": event},
|
||||
|
||||
Reference in New Issue
Block a user