diff options
| author | Adam Soltys <[email protected]> | 2026-11-13 16:11:02 -0700 |
|---|---|---|
| committer | Adam Soltys <[email protected]> | 2026-11-13 16:11:02 -0700 |
| commit | b8b409910f71976959135b336b409c4923cf4c87 (patch) | |
| tree | 21115643c3bed3c967a9bdc2fe1c75fa9cdfa07d | |
| parent | 589519f2556b2d434ed23f26c705df73b6149d7c (diff) | |
| download | coinos-server-b8b409910f71976959135b336b409c4923cf4c87.tar.gz coinos-server-b8b409910f71976959135b336b409c4923cf4c87.zip | |
lnurl: fetch user-supplied URLs through the SSRF guard, relay only protocol fields
Lightning address sends (pay() and POST /send/<lnaddr>) now validate the
name and domain and fetch through safeGot instead of plain got. Zap receipt
relays from the zap request must resolve to public hosts. The LNURL decode
and proxy routes return only LNURL protocol fields instead of whatever JSON
the upstream sent, and the proxy logs failures rate-limited with a generic
error to the client. Also blocks the 172.42.0.0/16 docker range.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
| -rw-r--r-- | lib/lnurl-payload.ts | 60 | ||||
| -rw-r--r-- | lib/nostr.ts | 10 | ||||
| -rw-r--r-- | lib/payments.ts | 7 | ||||
| -rw-r--r-- | lib/safe-fetch.ts | 17 | ||||
| -rw-r--r-- | routes/lnurl.ts | 10 | ||||
| -rw-r--r-- | routes/payments.ts | 11 | ||||
| -rw-r--r-- | test/lnurl-payload.test.ts | 29 |
7 files changed, 134 insertions, 10 deletions
diff --git a/lib/lnurl-payload.ts b/lib/lnurl-payload.ts new file mode 100644 index 00000000..6248d213 --- /dev/null +++ b/lib/lnurl-payload.ts @@ -0,0 +1,60 @@ +import { bech32 } from "bech32"; + +const invalid = (): never => { throw new Error("Invalid LNURL response"); }; +const object = (v: any) => v !== null && typeof v === "object" && !Array.isArray(v); +const amount = (v: any, min: number) => Number.isSafeInteger(v) && v >= min; +const callback = (v: any) => { + if (typeof v !== "string") return invalid(); + const u = new URL(v); + if (!["http:", "https:"].includes(u.protocol) || u.username || u.password) invalid(); + return v; +}; + +// Return only protocol fields: never relay an arbitrary upstream JSON object. +export function lnurlPayload(v: any): any { + if (!object(v)) return invalid(); + if (v.status === "ERROR" && typeof v.reason === "string") + return { status: "ERROR", reason: "LNURL service returned an error" }; + if (v.status === "OK" && !v.tag && !v.pr) return { status: "OK" }; + if (v.tag === "payRequest") { + if (!amount(v.minSendable, 1) || !amount(v.maxSendable, v.minSendable) || typeof v.metadata !== "string") invalid(); + let metadata: any; + try { metadata = JSON.parse(v.metadata); } catch { return invalid(); } + if (!Array.isArray(metadata) || !metadata.every((e: any) => Array.isArray(e) && e.length >= 2 && typeof e[0] === "string") || + metadata.filter((e: any) => e[0] === "text/plain" && typeof e[1] === "string").length !== 1) invalid(); + const out: any = { tag: v.tag, callback: callback(v.callback), minSendable: v.minSendable, maxSendable: v.maxSendable, metadata: v.metadata }; + if (amount(v.commentAllowed, 0)) out.commentAllowed = v.commentAllowed; + if (v.allowsNostr === true && typeof v.nostrPubkey === "string" && /^[a-f0-9]{64}$/i.test(v.nostrPubkey)) { + out.allowsNostr = true; out.nostrPubkey = v.nostrPubkey; + } + return out; + } + if (v.tag === "withdrawRequest") { + if (typeof v.k1 !== "string" || !v.k1 || typeof v.defaultDescription !== "string" || + !amount(v.minWithdrawable, 0) || !amount(v.maxWithdrawable, v.minWithdrawable)) invalid(); + return { tag: v.tag, callback: callback(v.callback), k1: v.k1, defaultDescription: v.defaultDescription, + minWithdrawable: v.minWithdrawable, maxWithdrawable: v.maxWithdrawable }; + } + if (typeof v.pr === "string") { + let decoded: any; + try { decoded = bech32.decode(v.pr, 20000); } catch { return invalid(); } + if (!/^ln(bc|tb|bcrt|sb)[0-9]*[munp]?$/.test(decoded.prefix) || decoded.words.length < 111 || + !Array.isArray(v.routes) || v.routes.length !== 0) invalid(); + const out: any = { pr: v.pr, routes: [] }; + if (v.disposable === false || v.disposable === true) out.disposable = v.disposable; + if (typeof v.verify === "string") out.verify = callback(v.verify); + const a = v.successAction; + if (object(a)) { + if (a.tag === "message" && typeof a.message === "string" && a.message.length <= 144) + out.successAction = { tag: a.tag, message: a.message }; + else if (a.tag === "url" && typeof a.description === "string" && a.description.length <= 144) + out.successAction = { tag: a.tag, description: a.description, url: callback(a.url) }; + else if (a.tag === "aes" && typeof a.description === "string" && a.description.length <= 144 && + typeof a.ciphertext === "string" && a.ciphertext.length <= 4096 && typeof a.iv === "string" && /^[A-Za-z0-9+/]{22}==$/.test(a.iv)) + out.successAction = { tag: a.tag, description: a.description, ciphertext: a.ciphertext, iv: a.iv }; + else invalid(); + } + return out; + } + return invalid(); +} diff --git a/lib/nostr.ts b/lib/nostr.ts index ed1b2f42..63199bf8 100644 --- a/lib/nostr.ts +++ b/lib/nostr.ts @@ -1,4 +1,5 @@ import config from "$config"; +import { safeRelayUrl } from "$lib/safe-fetch"; import { db, g, s } from "$lib/db"; import { l, warn } from "$lib/logging"; import { scan } from "$lib/strfry"; @@ -125,7 +126,14 @@ export async function handleZap(invoice, sender = undefined) { l("sending receipt"); - const relays = relays_tag.slice(1).filter((r) => r?.startsWith("ws")); + // Relay URLs come from the zap request, i.e. from whoever asked for the + // invoice; don't let them point our server at internal hosts. + const requested = relays_tag + .slice(1) + .filter((r) => typeof r === "string" && r.startsWith("ws")) + .slice(0, 10); + const relays = []; + for (const r of requested) if (await safeRelayUrl(r)) relays.push(r); relays.push(config.nostr); relays.map(async (url) => { try { diff --git a/lib/payments.ts b/lib/payments.ts index 407e5eac..43070843 100644 --- a/lib/payments.ts +++ b/lib/payments.ts @@ -1,4 +1,5 @@ import config from "$config"; +import { safeGot } from "$lib/safe-fetch"; import { existsSync } from "fs"; import api from "$lib/api"; import { requireAccount } from "$lib/auth"; @@ -603,6 +604,8 @@ const pay = async ({ aid = undefined, amount, to, user }) => { let pr; if (to.includes("@") && to.includes(".")) { const [name, domain] = to.split("@"); + if (!name || /[\/\\?#%@\s]|\.\./u.test(name) || !/^[a-z0-9.-]+(:\d+)?$/i.test(domain || "")) + fail("Invalid lightning address"); if (URL.includes(domain)) to = name; lnurl = `https://${domain}/.well-known/lnurlp/${name}`; } else if (to.startsWith("lnurl")) { @@ -631,8 +634,8 @@ const pay = async ({ aid = undefined, amount, to, user }) => { const fee = Math.max(5, Math.round(amount * 0.02)); if (lnurl) { amount -= fee; - const { callback } = (await got(lnurl).json()) as any; - ({ pr } = (await got(`${callback}?amount=${amount * 1000}`).json()) as any); + const { callback } = (await safeGot(lnurl)) as any; + ({ pr } = (await safeGot(`${callback}?amount=${amount * 1000}`)) as any); } else if (to.startsWith("ln")) { amount -= fee; pr = to; diff --git a/lib/safe-fetch.ts b/lib/safe-fetch.ts index 5b1059e9..2a9c7870 100644 --- a/lib/safe-fetch.ts +++ b/lib/safe-fetch.ts @@ -26,6 +26,7 @@ const blockedV4 = (ip: string): boolean => { if (a === 127) return true; // loopback if (a === 169 && b === 254) return true; // link-local + cloud metadata (169.254.169.254) if (a === 172 && b >= 16 && b <= 31) return true; // private + if (a === 172 && b === 42) return true; // cs Docker network uses 172.42.0.0/16 if (a === 192 && b === 168) return true; // private if (a === 100 && b >= 64 && b <= 127) return true; // CGNAT 100.64/10 (incl. tailscale) if (a >= 224) return true; // multicast / reserved @@ -163,3 +164,19 @@ const fetchOnce = (url: string, redirectsLeft: number): Promise<any> => // Fetch a user-supplied URL with SSRF protection and return the parsed JSON // body. Throws on a bad scheme/URL or a host that resolves into a blocked range. export const safeGot = async (url: string): Promise<any> => fetchOnce(url, MAX_REDIRECTS); + +// For URLs we hand to a library that does its own connecting (nostr relays +// over WebSocket): allow only ws/wss to a host whose every resolved address +// is public. Not rebind-proof like safeGot, but keeps user-supplied relay +// lists from pointing us at internal services. +export const safeRelayUrl = async (raw: string): Promise<boolean> => { + let u: globalThis.URL; + try { u = new globalThis.URL(raw); } catch { return false; } + if (u.protocol !== "ws:" && u.protocol !== "wss:") return false; + const host = u.hostname.replace(/^\[|\]$/g, ""); + if (net.isIP(host)) return !isBlockedIp(host); + try { + const addrs = await dns.promises.lookup(host, { all: true }); + return addrs.length > 0 && addrs.every((a) => !isBlockedIp(a.address)); + } catch { return false; } +}; diff --git a/routes/lnurl.ts b/routes/lnurl.ts index 7f04db5d..e28bb510 100644 --- a/routes/lnurl.ts +++ b/routes/lnurl.ts @@ -5,6 +5,7 @@ import { serverPubkey2 } from "$lib/nostr"; import { SATS, bail, fail, getInvoice, getUser } from "$lib/utils"; import { bech32 } from "bech32"; import { safeGot } from "$lib/safe-fetch"; +import { lnurlPayload } from "$lib/lnurl-payload"; import { verifyEvent } from "nostr-tools"; import { v4 } from "uuid"; @@ -99,7 +100,7 @@ export default { bech32.fromWords(bech32.decode(text, 20000).words), ).toString(); - const r = await safeGot(url); + const r = lnurlPayload(await safeGot(url)); res.send(r); } catch (e) { bail(res, e.message); @@ -240,11 +241,12 @@ export default { const { url } = req.query; if (!url) return bail(res, "url required"); try { - const r = await safeGot(url); + const r = lnurlPayload(await safeGot(url)); res.send(r); } catch (e) { - warn("lnurl proxy failed", url, e.message); - bail(res, e.message); + const n = quiet("lnurl-proxy-failure", 5 * 60 * 1000); + if (n !== null) warn("lnurl proxy failed", url, e.message, suppressed(n)); + bail(res, "Unable to resolve a valid LNURL response"); } }, diff --git a/routes/payments.ts b/routes/payments.ts index cfb34af7..9cc31434 100644 --- a/routes/payments.ts +++ b/routes/payments.ts @@ -32,6 +32,7 @@ import { } from "$lib/utils"; import rpc from "@coinos/rpc"; import got from "got"; +import { safeGot } from "$lib/safe-fetch"; import { v4 } from "uuid"; // Funds are closed. The mechanism let a caller pull unbacked balance out of a @@ -789,15 +790,19 @@ export default { await requirePin({ body, user }); const [username, domain] = lnaddress.split("@"); - const { minSendable, maxSendable, callback, metadata } = (await got( + // Coinos names are any letters/digits, so don't enforce LUD-16's + // charset; just refuse what could steer the URL we fetch. + if (!username || /[\/\\?#%@\s]|\.\./u.test(username) || !/^[a-z0-9.-]+(:\d+)?$/i.test(domain || "")) + fail("Invalid lightning address"); + const { minSendable, maxSendable, callback, metadata } = (await safeGot( `https://${domain}/.well-known/lnurlp/${username}`, - ).json()) as any; + )) as any; const memo = metadata["text/plain"] || ""; if (amount * 1000 < minSendable || amount * 1000 > maxSendable) fail("amount out of range"); - const r: any = await got(`${callback}?amount=${amount * 1000}`).json(); + const r: any = await safeGot(`${callback}?amount=${amount * 1000}`); if (r.reason) fail(r.reason); const { pr } = r; diff --git a/test/lnurl-payload.test.ts b/test/lnurl-payload.test.ts new file mode 100644 index 00000000..01d1da9b --- /dev/null +++ b/test/lnurl-payload.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, test } from "bun:test"; +import { bech32 } from "bech32"; +import { lnurlPayload } from "../lib/lnurl-payload"; +import { safeGot } from "../lib/safe-fetch"; +const pay = { tag: "payRequest", callback: "https://example.com/pay", minSendable: 1000, maxSendable: 2000, metadata: '[["text/plain","coffee"]]' }; +describe("LNURL response boundary", () => { + test("keeps supported pay fields and strips unrelated data", () => { + expect(lnurlPayload({ ...pay, secret: "internal data", commentAllowed: 100 })).toEqual({ ...pay, commentAllowed: 100 }); + }); + test("rejects unrelated and malformed JSON payloads", () => { + for (const v of [null, [], "hello", { version: "docker" }, { ...pay, minSendable: -1 }, { ...pay, maxSendable: 1 }, { ...pay, metadata: "{}" }, { ...pay, callback: "file:///etc/passwd" }, { ...pay, metadata: '[["image/png;base64","abc"]]' }]) + expect(() => lnurlPayload(v)).toThrow(); + }); + test("withdrawal and status responses expose only protocol fields", () => { + const w = { tag: "withdrawRequest", callback: "https://example.com/withdraw", k1: "challenge", defaultDescription: "withdraw", minWithdrawable: 0, maxWithdrawable: 1000 }; + expect(lnurlPayload({ ...w, secret: "hidden" })).toEqual(w); + expect(lnurlPayload({ status: "OK", secret: "hidden" })).toEqual({ status: "OK" }); + expect(lnurlPayload({ status: "ERROR", reason: "sensitive upstream error", secret: "hidden" }).reason).toBe("LNURL service returned an error"); + }); + test("requires a checksummed invoice and strips extras", () => { + expect(() => lnurlPayload({ pr: "not an invoice", routes: [] })).toThrow(); + const pr = bech32.encode("lnbc10n", Array(120).fill(0), 20000); + expect(lnurlPayload({ pr, routes: [], secret: "hidden", successAction: { tag: "message", message: "thanks", secret: "hidden" } })).toEqual({ pr, routes: [], successAction: { tag: "message", message: "thanks" } }); + }); + test("blocks internal literal targets before fetching", async () => { + for (const url of ["http://172.42.0.13:3119/health", "http://127.0.0.1", "http://169.254.169.254", "http://10.1.2.3", "http://[::1]", "http://[::ffff:127.0.0.1]", "file:///etc/passwd"]) + await expect(safeGot(url)).rejects.toThrow(); + }); +}); |
