One of the most dangerous inputs in a payments backend is also one of the most boring-looking: a URL field.
Ganji is a Lightning escrow app where clients fund a deal through a public share link. The funding form asks for two things:
- the client's LNbits wallet URL
- that wallet's API key
The backend then calls that wallet and asks it to pay the escrow hold invoice. A related form asks the freelancer for a wallet URL so Ganji can generate a payee invoice.
That sounds harmless. The user owns the wallet, so the user supplies the wallet address. What could go wrong?
The problem is that the backend is the one making the HTTP request, and the caller controls the destination. That is the classic shape of a server-side request forgery (SSRF) bug.
This post covers how we hardened that path, what the scary-looking address ranges actually mean, and why "just parse the URL properly" is not enough.
The Request the Backend Used to Make
The public funding flow accepts a JSON body like this:
{ "wallet_url": "https://my-wallet.example.com", "wallet_key": "caller-supplied-key", "milestone_id": "optional-milestone-id" } The service validates that wallet_url looks like a URL, then builds a Lightning wallet client. The client sends a request to:
https://my-wallet.example.com/api/v1/payments Notice what happened. The caller chose the host. The backend supplied its network position, its ability to make outbound requests, and its error handling.
Before hardening, the validator checked useful things:
- the URL parses
- it has an
httporhttpsscheme - it has no embedded
user:pass@host - it has no query string or fragment
That is good hygiene, but it misses the most important question:
Is this an address that a public caller should ever be allowed to make our backend contact?
The original validator would happily accept all of these:
http://127.0.0.1:8080 http://localhost:3000 http://192.168.1.1 http://10.0.0.5 http://169.254.169.254 Those are not normal wallet hosts. They are places inside the backend's own network neighborhood.
SSRF in Plain English
Imagine your backend works in a secure office. A stranger outside the building cannot walk in, but they can phone the receptionist and say:
"Please go to room 127.0.0.1 and tell me what you see."
If the receptionist blindly goes, the stranger has effectively used the receptionist as a proxy into the building.
SSRF is the same idea. The attacker cannot connect directly to a private service, so they trick the backend into connecting for them.
The backend might share a machine or network with a database admin panel, an internal API, another container, a router interface, or a cloud metadata service. The attacker supplies a URL pointing there and watches how the backend responds.
Even when the response body isn't returned, small differences can leak information:
- Connection refused: probably no service on that port
- Timeout: maybe a firewall dropped it
-
401 Unauthorized: something exists and wants credentials -
404: a web server is alive - JSON error text: possibly a clue about the internal service
That makes SSRF a way to scan and probe your internal network from the inside, using your own server as the vantage point.
Why Those Specific Addresses Matter
The blocked ranges are not random. Each one describes a place that should not be reachable from a public, caller-supplied URL.
127.* and ::1: the backend itself
127.0.0.1 is localhost in IPv4, and ::1 is localhost in IPv6. When a server connects to one of them, it is connecting to itself. An attacker who can make the backend call localhost can probe services bound only to the backend's own host or container.
0.0.0.0: "this host"
0.0.0.0 is the unspecified address. As a destination it isn't meaningful, but on Linux and many other systems, connecting to it reaches the local machine. It is easy to forget because it isn't loopback by name, and a blocklist that only knows 127.* lets it through.
10.*, 172.16–31.*, 192.168.*: private networks
These are the RFC 1918 private ranges, used in homes, offices, Docker networks, Kubernetes clusters, and cloud VPCs. Your laptop probably uses 192.168.1.x on Wi-Fi, a Docker network might use 172.18.x.x, and a corporate network might use 10.x.x.x.
The public internet should not route to these addresses, but your backend often can. That is exactly the gap SSRF exploits.
169.254.*: link-local and cloud metadata
169.254.0.0/16 is the IPv4 link-local range. The most famous address in it is:
169.254.169.254 That is the instance metadata endpoint on AWS, Azure, and GCP (which also reaches it by name). Workloads query it to learn about themselves. Depending on the cloud and its configuration, it can expose instance identity documents, credentials, or tokens. Newer metadata services, such as AWS's IMDSv2, require extra request headers that a simple SSRF can't add, but you shouldn't rely on that as your only defense.
So if an attacker can make your backend request http://169.254.169.254/..., the consequences can be far worse than "we found an open port."
100.64/10: carrier-grade NAT space
100.64.0.0/10 is shared address space reserved for carrier-grade NAT. It isn't meant to be a normal public website address. It appears in ISP and internal networking contexts, so blocking it is a sensible conservative choice.
fc00::/7 and fe80::/10: IPv6 equivalents
IPv6 has its own versions of private and local-only space:
-
fc00::/7: unique local addresses, roughly the IPv6 version of private LAN addresses -
fe80::/10: link-local addresses, valid only on the local network segment
A rule that only understands IPv4 is incomplete. Attackers will happily use IPv6 if you forget it.
CIDR Without the Intimidation
CIDR notation is simpler than it looks. A CIDR block is a compact way to write a group of IP addresses.
127.0.0.0/8 The /8 means "the first 8 bits are fixed, the rest can vary." For everyday purposes, you can read it like a wildcard:
0.0.0.0/8 -> 0.*.*.* 127.0.0.0/8 -> 127.*.*.* 10.0.0.0/8 -> 10.*.*.* 172.16.0.0/12 -> 172.16.*.* through 172.31.*.* 192.168.0.0/16 -> 192.168.*.* 169.254.0.0/16 -> 169.254.*.* 100.64.0.0/10 -> 100.64.*.* through 100.127.*.* ::1/128 -> exactly ::1 fc00::/7 -> IPv6 private space fe80::/10 -> IPv6 link-local space That is all "explicit blocklist" means here. We wrote the groups down directly in code instead of hoping Go's defaults catch everything.
The Blocklist in Go
We added a package-level list of parsed CIDR networks in service_payment_status.go:
var privateOrLoopbackCIDRs = func() []*net.IPNet { blocks := []string{ "0.0.0.0/8", "127.0.0.0/8", "10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "169.254.0.0/16", "100.64.0.0/10", "::1/128", "fc00::/7", "fe80::/10", } out := make([]*net.IPNet, 0, len(blocks)) for _, b := range blocks { _, cidr, err := net.ParseCIDR(b) if err != nil { panic(err) // these are constants, so a failure is a programming error } out = append(out, cidr) } return out }() Then we wrote a small helper:
func isPrivateOrLoopback(ip net.IP) bool { if ip.IsLoopback() || ip.IsUnspecified() || ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() || ip.IsPrivate() { return true } for _, cidr := range privateOrLoopbackCIDRs { if cidr.Contains(ip) { return true } } return false } There are two layers here.
First, Go's standard library has built-in predicates such as IsLoopback, IsPrivate, IsUnspecified, and IsLinkLocalUnicast. Those already cover most of the list, including the IPv6 ranges.
Second, our explicit CIDR list makes the policy visible and reviewable in a diff instead of hidden inside library behavior. It also adds the ranges the standard predicates don't cover, such as carrier-grade NAT space (100.64.0.0/10) and the rest of 0.0.0.0/8. The redundancy is deliberate: if a predicate's behavior changes, the written policy still holds.
Checking IPs and Hostnames
The validator now does more than reject bad URL syntax:
func validateWalletEndpointStrict(raw string) (string, error) { parsed, err := url.ParseRequestURI(strings.TrimSpace(raw)) if err != nil || parsed.Host == "" || parsed.User != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.RawQuery != "" || parsed.Fragment != "" { return "", fmt.Errorf("%w: invalid wallet URL", ErrInvalidInput) } hostname := parsed.Hostname() if ip := net.ParseIP(hostname); ip != nil { if isPrivateOrLoopback(ip) { return "", fmt.Errorf("%w: wallet URL must not point to a private or loopback address", ErrInvalidInput) } } else { addrs, err := net.LookupHost(hostname) if err != nil { return "", fmt.Errorf("%w: cannot resolve wallet URL host: %v", ErrInvalidInput, err) } for _, addr := range addrs { ip := net.ParseIP(addr) if ip == nil { continue } if isPrivateOrLoopback(ip) { return "", fmt.Errorf("%w: wallet URL resolves to a private or loopback address", ErrInvalidInput) } } } return strings.TrimRight(parsed.String(), "/"), nil } If the caller submits a literal IP, we check it directly. If they submit a hostname, we resolve it and check every returned address.
That second part matters. An attacker can register or control a hostname that resolves to 127.0.0.1 or 169.254.169.254. Looking only at the hostname string would miss the attack. We care where the name actually points.
The validator is called from both funding and invoice generation, so the same rule applies anywhere a caller-supplied wallet URL becomes an outbound HTTP request.
Error Messages Without Secrets
Fixing the network check is only half the work. Error strings can become their own leak.
If validation errors include the raw URL, a caller-controlled string gets echoed into API responses and logs. Wallet URLs can contain paths, ports, and other details, and wallet keys are more sensitive still.
So the service uses generic, category-level messages:
invalid wallet URL wallet URL must not point to a private or loopback address wallet URL resolves to a private or loopback address cannot resolve wallet URL host: ... They name the class of problem without repeating the URL. Those messages are for logs and tests, though, not for the caller. At the HTTP layer, errors wrapped in ErrInvalidInput are mapped by safeDealMessage to a single generic response:
invalid request That has a second benefit. A caller can't tell "this host is private" from "this host doesn't resolve" from "this URL is malformed", so the validator can't be used as an oracle for probing which addresses are blocked. Other wallet failures get similarly fixed messages, such as could not pay escrow invoice from linked wallet instead of raw transport errors.
To be precise about one detail, there is no separate sanitizeWalletURL() helper. We avoided the need by never interpolating raw or parsed.String() into error text in the first place. The one exception is the DNS error, because the resolver's own message can contain the hostname. It stays safe only because the HTTP layer collapses it to invalid request, so remember that if you log it.
Tests That Encode the Rule
We added tests by category, not just by function call.
Valid public destinations:
https://1.1.1.1 http://1.1.1.1/wallet https://1.1.1.1:443 Blocked SSRF destinations:
http://127.0.0.1 http://127.0.0.2:5000 http://localhost http://0.0.0.0 http://10.0.0.1 http://192.168.1.1 http://172.16.0.1 http://169.254.169.254 http://[::1] Malformed inputs:
empty string no scheme ftp://... http://user:pass@host URL with query string URL with fragment The "valid" cases use IP literals, so the tests don't depend on DNS.
The local-development tests use a test-only override for the validator. That is necessary because local LNbits instances live on localhost, which production callers must never be allowed to target. The override is confined to tests, and the production default is the strict validator.
What This Does Not Solve
This blocklist is an important door closed, not a complete SSRF program. A hardened setup should also consider:
- DNS rebinding. A hostname can resolve to a public IP during validation and to a private IP when the request is actually made, because the HTTP client resolves the name again. In Go, the usual fix is a custom
net.DialerwhoseControlfunction checks the address being connected to, so validation and connection use the same IP. - HTTP redirects. Go's
http.Clientfollows redirects by default, so a public URL can bounce the request to an internal one. Disable redirects for wallet calls or revalidate each hop. - Egress firewall rules. The backend process shouldn't be able to reach internal ranges at all.
- Port and response limits. Restrict destination ports where you can, refuse unexpected content types, and cap response body sizes.
- Other special-use ranges. The list covers the common ones. Multicast and reserved blocks are further candidates if you want a stricter policy.
The validator reduces the obvious attack surface dramatically, but network-level controls are still the stronger boundary. Application validation says "we should not ask for that." An egress firewall says "this process physically cannot reach that."
The Takeaway
If your backend makes a request to a URL supplied by a user, treat that URL as an instruction that will be executed with your backend's privileges.
A parsing library answers, "Is this syntactically a URL?" A security validator must also answer, "Should this process ever contact this destination?"
For wallet URLs, the answer is no for localhost, no for private networks, no for link-local addresses, and no for cloud metadata. Write that down explicitly, test it, and keep error messages boring.
That is the difference between a form field and a trust boundary.
