fix: harden SSRF checks and use explicit local LNURL route opt-ins (#4313)
What changed, and why it matters
This commit is a security hardening patch for LNbits, a Bitcoin Lightning wallet platform. It fixes weaknesses in the server's outgoing web-request protections (SSRF, or Server-Side Request Forgery) that could let an attacker trick the LNbits server into making requests to internal or cloud metadata addresses, potentially stealing funds or secrets. The patch also replaces a fixed internal list of allowed local LNURL paths with an explicit opt-in marker on each route, so only intentionally exposed endpoints can be reached internally. The vendor says every version before 1.7.0 is affected, funds are at risk, and operators must rotate keys/secrets after upgrading.
Upgrade to LNbits v1.7.0 or later immediately. Because the vendor states exposed credentials may remain usable after patching, also rotate all LNbits admin keys, wallet keys, API secrets, and any linked external service credentials. Review server logs for unexpected outbound requests to internal/cloud metadata addresses before the upgrade.
Security signals we found
SSRF hardening: multicast, IPv6 transition/embedded addresses, and EC2 IPv6 metadata endpoint blocked
Local LNURL routing moved from hard-coded regex allow-list to explicit per-route openapi_extra opt-in
Backslash path traversal blocked in private HTTP endpoint checks
In-process local LNURL requests stripped of Authorization/Cookie headers and avoid DNS resolution
Vendor security release (v1.7.0) states pre-1.7.0 versions affected, funds at risk, requires key/secret rotation
Evidence from the diff
The commit hardens SSRF defenses across lnbits/utils/network.py, safe_http.py, and core/services/lnurl.py. network.py now rejects multicast addresses and recursively validates embedded IPv4 inside IPv6 (mapped, 6to4, Teredo, NAT64). safe_http.py blocks backslash path traversal and the EC2 IPv6 metadata endpoint fd00:ec2::254. lnurl.py replaces a hard-coded regex allow-list for in-process local LNURL callbacks with a runtime FastAPI route lookup that requires the matched APIRoute to carry openapi_extra={‘x-lnbits-local-lnurl’: True}. Core LNURL routes in lnurl_api.py are annotated with that marker. Tests cover multicast rejection, route opt-in, shadowed/mounted route isolation, and extension LNURL flows staying in-process without network or auth headers.
Changed components
lnbits/core/services/lnurl.pylnbits/core/views/lnurl_api.pylnbits/utils/network.pylnbits/utils/safe_http.pyInspect captured patch +168 / −40
### lnbits/core/services/lnurl.py
@@ -12,6 +12,8 @@
import httpx
from bolt11 import Bolt11Exception, MilliSatoshi
from bolt11 import decode as bolt11_decode
+from fastapi import FastAPI
+from fastapi.routing import APIRoute
from lnurl import (
InvalidLnurl,
LnAddress,
@@ -32,6 +34,7 @@
from lnurl.types import CallbackUrl
from loguru import logger
from pydantic import TypeAdapter, ValidationError
+from starlette.routing import Match
from lnbits.core.crud import update_wallet
from lnbits.core.db import core_app_extra
@@ -558,19 +561,20 @@ def _is_local_lnurl_url(url: httpx.URL) -> bool:
or b"%" in url.raw_path.split(b"?", 1)[0]
):
return False
- # Only these public LNURL endpoints may run in-process. No arbitrary path,
- # credentials, alternative port or network connection is permitted.
- return any(
- re.fullmatch(pattern, url.path)
- for pattern in (
- r"/\.well-known/lnurlp/[A-Za-z0-9_.-]+",
- r"/api/v1/lnurl/wallet/[A-Za-z0-9_.-]+/cb",
- r"/lnurlp/[A-Za-z0-9_-]+",
- r"/lnurlp/api/v1/lnurl/(?:cb/)?[A-Za-z0-9_-]+",
- r"/lnurlp/api/v1/well-known/[A-Za-z0-9_.-]+",
- r"/withdraw/api/v1/lnurl/[A-Za-z0-9_-]+(?:/[A-Za-z0-9_-]+)?",
- )
- )
+ app = core_app_extra.local_lnurl_app
+ if not isinstance(app, FastAPI):
+ return False
+ scope = {"type": "http", "method": "GET", "path": url.path, "root_path": ""}
+ # The actual first matching route must opt in. Extension-owned metadata
+ # survives include_router(), upgrades and route removal without a core list.
+ for route in app.routes:
+ match, _ = route.matches(scope)
+ if match == Match.FULL:
+ return (
+ isinstance(route, APIRoute)
+ and (route.openapi_extra or {}).get("x-lnbits-local-lnurl") is True
+ )
+ return False
async def _send_local_lnurl_request(
### lnbits/core/views/lnurl_api.py
@@ -45,6 +45,7 @@
@lnurl_router.get(
"/.well-known/lnurlp/{username}",
name="lnurl.api_wallet_lightning_address_response",
+ openapi_extra={"x-lnbits-local-lnurl": True},
)
async def api_wallet_lightning_address_response(
username: str, request: Request
@@ -68,6 +69,7 @@ async def api_wallet_lightning_address_response(
@lnurl_router.get(
"/api/v1/lnurl/wallet/{username}/cb",
name="lnurl.api_wallet_lightning_address_callback",
+ openapi_extra={"x-lnbits-local-lnurl": True},
)
async def api_wallet_lightning_address_callback(
username: str, request: Request, amount: int = Query(...)
### lnbits/utils/network.py
@@ -7,7 +7,7 @@
def is_global_address(address: ipaddress.IPv4Address | ipaddress.IPv6Address) -> bool:
"""Require both the address and any embedded IPv4 addresses to be global."""
- if not address.is_global:
+ if not address.is_global or address.is_multicast:
return False
if isinstance(address, ipaddress.IPv4Address):
return True
@@ -16,11 +16,11 @@ def is_global_address(address: ipaddress.IPv4Address | ipaddress.IPv6Address) ->
if address in _NAT64_LOCAL_NETWORK:
return False
if address.ipv4_mapped is not None:
- return address.ipv4_mapped.is_global
+ return is_global_address(address.ipv4_mapped)
if address.sixtofour is not None:
- return address.sixtofour.is_global
+ return is_global_address(address.sixtofour)
if address.teredo is not None:
- return all(ip.is_global for ip in address.teredo)
+ return all(is_global_address(ip) for ip in address.teredo)
if address in _NAT64_NETWORK or address in _IPV4_COMPATIBLE_NETWORK:
- return ipaddress.IPv4Address(address.packed[-4:]).is_global
+ return is_global_address(ipaddress.IPv4Address(address.packed[-4:]))
return True
### lnbits/utils/safe_http.py
@@ -240,6 +240,8 @@ def _check_endpoint_scope(url, endpoint):
or url.path.startswith(endpoint.path.rstrip("/") + "/")
)
or b"%" in url.raw_path.split(b"?", 1)[0]
+ or "\\" in url.path
+ or "\\" in endpoint.path
):
raise ValueError("Request is outside the configured private endpoint.")
@@ -266,6 +268,9 @@ async def _check_addresses(
def _is_private_service_address(address):
# Explicit private services may use LAN/ULA or loopback addresses, never
# cloud metadata/link-local, multicast, unspecified or transition addresses.
+ # EC2's IPv6 metadata endpoint is ULA rather than link-local.
+ if address == ipaddress.ip_address("fd00:ec2::254"):
+ return False
networks = (
("10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "127.0.0.0/8")
if address.version == 4
### tests/unit/test_network.py
@@ -11,6 +11,13 @@
"127.0.0.1",
"10.0.0.1",
"169.254.169.254",
+ "224.0.0.1",
+ "239.255.255.250",
+ "ff02::1",
+ "ff0e::1",
+ "::ffff:224.0.0.1",
+ "64:ff9b::224.0.0.1",
+ "2002:e000:1::",
"::1",
"fc00::1",
"64:ff9b::127.0.0.1",
### tests/unit/test_outbound.py
@@ -11,7 +11,7 @@
import httpx
import pytest
-from fastapi import FastAPI, Request
+from fastapi import APIRouter, FastAPI, Request
from fastapi.responses import StreamingResponse
from lnurl import LnurlResponseException
from pydantic import ValidationError
@@ -25,6 +25,7 @@
@pytest.fixture(autouse=True)
def policy(monkeypatch):
+ monkeypatch.setattr(core_app_extra, "local_lnurl_app", None)
monkeypatch.setattr(settings, "lnbits_baseurl", "https://instance.example/")
monkeypatch.setattr(settings, "lnbits_outbound_host_ips", [])
monkeypatch.setattr(settings, "lnbits_callback_url_rules", [])
@@ -121,12 +122,14 @@ async def test_local_payment_metadata_and_callback_use_no_network(monkeypatch):
app = FastAPI()
calls = []
- @app.get("/.well-known/lnurlp/alice")
+ @app.get("/.well-known/lnurlp/alice", openapi_extra={"x-lnbits-local-lnurl": True})
async def metadata(request: Request):
calls.append(request)
return {"callback": "https://instance.example/api/v1/lnurl/wallet/alice/cb"}
- @app.get("/api/v1/lnurl/wallet/alice/cb")
+ @app.get(
+ "/api/v1/lnurl/wallet/alice/cb", openapi_extra={"x-lnbits-local-lnurl": True}
+ )
async def callback(request: Request, amount: int):
calls.append(request)
return {"pr": "test-invoice", "amount": amount}
@@ -161,7 +164,7 @@ async def stall():
finally:
cancelled.set()
- @app.get("/.well-known/lnurlp/alice")
+ @app.get("/.well-known/lnurlp/alice", openapi_extra={"x-lnbits-local-lnurl": True})
async def metadata():
if phase == "response":
await stall()
@@ -185,27 +188,74 @@ async def body():
assert isinstance(exc.value.__cause__, asyncio.TimeoutError)
-@pytest.mark.parametrize(
- "path",
- [
- "/lnurlp/abc",
- "/lnurlp/api/v1/lnurl/abc",
- "/lnurlp/api/v1/lnurl/cb/abc",
- "/lnurlp/api/v1/well-known/alice",
- "/withdraw/api/v1/lnurl/abc",
- "/withdraw/api/v1/lnurl/cb/abc",
- "/withdraw/api/v1/lnurl/abc/unique",
- ],
-)
-def test_known_extension_lnurls_have_an_internal_path(path):
- assert lnurl._is_local_lnurl_url(httpx.URL("https://instance.example" + path))
+def test_local_lnurl_requires_registered_opted_in_get_route(monkeypatch):
+ app = FastAPI()
+ router = APIRouter(prefix="/example_ext")
+
+ @router.get("/pay/{link_id}", openapi_extra={"x-lnbits-local-lnurl": True})
+ async def metadata(link_id: str):
+ return {"id": link_id}
+
+ @router.get("/admin")
+ async def admin():
+ return {}
+
+ @router.post("/post", openapi_extra={"x-lnbits-local-lnurl": True})
+ async def post_only():
+ return {}
+
+ app.include_router(router)
+ monkeypatch.setattr(core_app_extra, "local_lnurl_app", app)
+ url = httpx.URL("https://instance.example/example_ext/pay/abc")
+ assert lnurl._is_local_lnurl_url(url)
+ for path in ("/example_ext/admin", "/example_ext/post", "/other_ext/pay/abc"):
+ assert not lnurl._is_local_lnurl_url(url.copy_with(path=path))
+ # Removed or upgraded routes must not retain stale permission.
+ app.router.routes = []
+ assert not lnurl._is_local_lnurl_url(url)
+
+
+def test_shadowed_or_mounted_route_cannot_borrow_lnurl_permission(monkeypatch):
+ app = FastAPI()
+
+ @app.get("/example_ext/pay/{link_id}")
+ async def unmarked(link_id: str):
+ return {}
+
+ @app.get("/example_ext/pay/{link_id}", openapi_extra={"x-lnbits-local-lnurl": True})
+ async def marked(link_id: str):
+ return {}
+
+ monkeypatch.setattr(core_app_extra, "local_lnurl_app", app)
+ url = httpx.URL("https://instance.example/example_ext/pay/abc")
+ assert not lnurl._is_local_lnurl_url(url)
+ mounted = FastAPI()
+ mounted.mount("/", app)
+ monkeypatch.setattr(core_app_extra, "local_lnurl_app", mounted)
+ assert not lnurl._is_local_lnurl_url(url)
+
+
+def test_core_public_lnurl_routes_explicitly_opt_in(monkeypatch):
+ from lnbits.core.views.lnurl_api import lnurl_router
+
+ app = FastAPI()
+ app.include_router(lnurl_router)
+ monkeypatch.setattr(core_app_extra, "local_lnurl_app", app)
+ for path in ("/.well-known/lnurlp/alice", "/api/v1/lnurl/wallet/alice/cb"):
+ assert lnurl._is_local_lnurl_url(httpx.URL("https://instance.example" + path))
+ assert not lnurl._is_local_lnurl_url(
+ httpx.URL("https://instance.example/api/v1/lnurlscan/test")
+ )
@pytest.mark.anyio
@pytest.mark.parametrize(
"url",
[
"https://instance.example/admin/api/v1/settings",
+ "https://instance.example/example_ext/admin",
+ "https://instance.example/example_ext/auth?wipe=true",
+ "https://instance.example/unknown/api/v1/lnurl/cb/charge",
"https://instance.example:8443/.well-known/lnurlp/alice",
"http://instance.example/.well-known/lnurlp/alice",
"https://user:secret@instance.example/.well-known/lnurlp/alice",
@@ -227,11 +277,11 @@ async def test_internal_dispatch_does_not_allow_arbitrary_self_requests(
@pytest.mark.anyio
async def test_internal_redirect_is_checked_and_missing_app_fails_closed(monkeypatch):
monkeypatch.setattr(core_app_extra, "local_lnurl_app", None)
- with pytest.raises(LnurlResponseException, match="unavailable"):
- await lnurl.request_lnurl_json("https://instance.example/lnurlp/abc")
+ with pytest.raises(LnurlResponseException, match="this server"):
+ await lnurl.request_lnurl_json("https://instance.example/example_ext/pay/abc")
app = FastAPI()
- @app.get("/lnurlp/abc")
+ @app.get("/example_ext/pay/abc", openapi_extra={"x-lnbits-local-lnurl": True})
async def redirect():
from fastapi.responses import RedirectResponse
@@ -240,7 +290,7 @@ async def redirect():
monkeypatch.setattr(core_app_extra, "local_lnurl_app", app)
monkeypatch.setattr(settings, "lnbits_lnurl_redirect_url_rules", [".*"])
with pytest.raises(LnurlResponseException, match="this server"):
- await lnurl.request_lnurl_json("https://instance.example/lnurlp/abc")
+ await lnurl.request_lnurl_json("https://instance.example/example_ext/pay/abc")
def test_environment_addresses_are_validated_and_readonly():
@@ -363,3 +413,43 @@ def test_hostname_guard_normalizes_international_names(monkeypatch, target):
monkeypatch.setattr(settings, "lnbits_baseurl", "https://bücher.example/")
with pytest.raises(ValueError, match="this server"):
outbound.check_outbound_hostname(target)
+
+
+@pytest.mark.anyio
+@pytest.mark.parametrize(
+ "metadata_path,callback_path",
+ [
+ ("/example_ext/pay/item", "/example_ext/pay/cb/item"),
+ ("/example_ext/v2/withdraw/device", "/example_ext/v2/withdraw/cb/cGF5bG9hZA=="),
+ ("/example_ext/custom/route/21", "/example_ext/callback"),
+ ],
+)
+async def test_same_instance_extension_lnurl_flow_stays_inside_app(
+ monkeypatch, metadata_path, callback_path
+):
+ app = FastAPI()
+ seen = []
+
+ @app.get(metadata_path, openapi_extra={"x-lnbits-local-lnurl": True})
+ async def metadata():
+ return {"callback": "https://instance.example" + callback_path}
+
+ @app.get(callback_path, openapi_extra={"x-lnbits-local-lnurl": True})
+ async def callback(request: Request, k1: str, pr: str):
+ seen.append(request)
+ return {"status": "OK", "k1": k1, "pr": pr}
+
+ monkeypatch.setattr(core_app_extra, "local_lnurl_app", app)
+ send = AsyncMock(side_effect=AssertionError("Must not connect to the host"))
+ monkeypatch.setattr(lnurl, "_send_lnurl_request", send)
+ resolver = dns(monkeypatch, [])
+ data = await lnurl.request_lnurl_json("https://instance.example" + metadata_path)
+ response = await lnurl.request_lnurl_json(
+ data["callback"], params={"k1": "charge", "pr": "test-invoice"}
+ )
+ assert response == {"status": "OK", "k1": "charge", "pr": "test-invoice"}
+ assert len(seen) == 1
+ assert "authorization" not in seen[0].headers
+ assert "cookie" not in seen[0].headers
+ resolver.assert_not_awaited()
+ send.assert_not_awaited()
### tests/unit/test_safe_http.py
@@ -321,6 +321,7 @@ def handler(request):
"http://mempool.example:3007/testnet/api",
"http://mempool.example:3006/admin",
"http://mempool.example:3006/testnet/%2e%2e/admin",
+ r"http://mempool.example:3006/testnet/..\admin",
]:
with pytest.raises(ValueError):
await client.get(url)
@@ -335,6 +336,7 @@ def handler(request):
[
"169.254.169.254",
"169.254.170.2",
+ "fd00:ec2::254",
"0.0.0.0", # noqa: S104 - rejected destination, not a listening address
"224.0.0.1",
"::",
### tests/unit/test_services_lnurl.py
@@ -451,3 +451,21 @@ async def __aexit__(self, *_args):
async def aiter_bytes(self):
for chunk in self._chunks:
yield chunk
+
+
+@pytest.mark.anyio
+@pytest.mark.parametrize("target_ip", ["224.0.0.1", "ff02::1", "64:ff9b::224.0.0.1"])
+async def test_lnurl_requests_reject_multicast_targets(settings, mocker, target_ip):
+ settings.lnbits_lnurl_allow_private_ips = False
+ mocker.patch(
+ "lnbits.core.services.lnurl._resolve_lnurl_host",
+ mocker.AsyncMock(return_value=[ipaddress.ip_address(target_ip)]),
+ )
+ send = mocker.patch("lnbits.core.services.lnurl._send_lnurl_request")
+ for url in (
+ httpx.URL("https://multicast.example/"),
+ httpx.URL("https://multicast.example/").copy_with(host=target_ip),
+ ):
+ with pytest.raises(LnurlResponseException, match="non-global IP address"):
+ await lnurl_service.request_lnurl_json(str(url))
+ send.assert_not_called()Why this scored 89/100
Evidence and disclosure record
Verified links used to place this patch in context. External claims remain attributed to their publishers.
Harden SSRF checks and require explicit local LNURL opt-ins
Follow-up incident hardening that strengthens SSRF checks and changes local LNURL routing from an implicit exception to explicit route-level opt-ins. It was merged into v1.7.0 before the urgent security release.
LNbits 1.7.0 security update and recovery guidance
The vendor says every version before 1.7.0 is affected, funds are at risk of theft, and exposed credentials may remain usable after an upgrade. It requires key and secret rotation in addition to updating.
LNbits v1.7.0 urgent security update
The first stable release containing the November incident fixes and recovery controls. LNbits instructs all operators to update immediately.
LNbits v1.7.0 security release announcement
Official announcement that v1.7.0 is released and operators should follow the linked upgrade guidance.
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.