Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/lnurl-verify-url-private-addresses.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"nostream": patch
---

The LNURL payments processor no longer requests a verify URL that points at a private, loopback or link-local address. The URL comes from the provider's answer to an invoice request, so a malicious provider could use it to make the relay send GET requests to services it can reach. A verify URL on the origin of the configured `invoiceURL` is requested as before, which keeps a provider on a private network working. Any other verify URL has its host resolved by the relay and checked, and no redirect from a verify URL is followed.
1 change: 1 addition & 0 deletions docs/PAYMENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ Each processor step ends with `nostream stop` and `nostream start`, which is the
- On your `.nostr/settings.yaml` file make the following changes:
- Set `payments.processor` to `lnurl`
- Set `paymentsProcessors.lnurl.invoiceURL` to your LNURL-pay address up to but excluding `/callback` (e.g. `https://getalby.com/lnurlp/your-username`, with your own username)
- The provider's verify URL has to be on the same origin (scheme, host and port) as `invoiceURL`, or on a public address. nostream does not request a verify URL on a private, loopback or link-local address from any other origin, and it does not follow redirects from it
- Restart nostream (`nostream stop` followed by `nostream start`)
7. Nostr Wallet Connect (NIP-47 / NWC)
Expand Down
57 changes: 55 additions & 2 deletions src/payments-processors/lnurl-payments-processor.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,78 @@
import { AxiosInstance } from 'axios'
import { Agent as HttpAgent } from 'node:http'
import { Agent as HttpsAgent } from 'node:https'
import { isIP } from 'node:net'

import { AxiosInstance, AxiosRequestConfig } from 'axios'
import { Factory } from '../@types/base'

import { CreateInvoiceRequest, GetInvoiceResponse, IPaymentsProcessor } from '../@types/clients'
import { InvoiceStatus, InvoiceUnit, LnurlInvoice } from '../@types/invoice'
import { createLogger } from '../factories/logger-factory'
import { randomUUID } from 'crypto'
import { createSafeLookup, isBlockedAddress } from '../utils/safe-lookup'
import { Settings } from '../@types/settings'

const logger = createLogger('lnurl-payments-processor')

const verifyLookup = createSafeLookup('LNURL verify')
// Own agents: with NODE_USE_ENV_PROXY the global agent goes through a proxy, which resolves the host itself and skips
// verifyLookup.
const verifyHttpAgent = new HttpAgent()
const verifyHttpsAgent = new HttpsAgent()

export class LnurlPaymentsProcessor implements IPaymentsProcessor {
public constructor(
private httpClient: AxiosInstance,
private settings: Factory<Settings>,
) {}

// The verify URL comes from the provider's answer to an invoice request, so it is not an address the operator chose.
// It is requested as given when it is on the origin of the configured invoiceURL, which is what a self-hosted
// provider on a private network needs. Anywhere else the host is resolved here and a private, loopback or
// link-local address is refused. No redirect is followed, since its target would be unchecked.
private verifyRequestConfig(verifyURL: string | undefined): AxiosRequestConfig {
let target: URL
try {
target = new URL(verifyURL ?? '')
} catch {
throw new Error('refused LNURL verify URL: it is not a valid URL')
}
if (target.protocol !== 'http:' && target.protocol !== 'https:') {
throw new Error(`refused LNURL verify URL: unsupported protocol ${target.protocol}`)
}

if (target.origin === this.invoiceOrigin()) {
return { maxRedirects: 0 }
}

// Node does not call `lookup` for an IP literal, so it is checked here.
const host = target.hostname.replace(/^\[|\]$/g, '')
if (isIP(host) && isBlockedAddress(host)) {
throw new Error(`refused LNURL verify URL: ${target.hostname} is a private address`)
}

return {
maxRedirects: 0,
proxy: false,
lookup: verifyLookup,
httpAgent: verifyHttpAgent,
httpsAgent: verifyHttpsAgent,
}
}

private invoiceOrigin(): string | undefined {
try {
return new URL(this.settings().paymentsProcessors?.lnurl?.invoiceURL ?? '').origin
} catch {
return undefined
}
}

public async getInvoice(invoice: LnurlInvoice): Promise<GetInvoiceResponse> {
logger('get invoice: %s', invoice.id)

try {
const response = await this.httpClient.get(invoice.verifyURL)
const response = await this.httpClient.get(invoice.verifyURL, this.verifyRequestConfig(invoice.verifyURL))

return {
id: invoice.id,
Expand Down
141 changes: 140 additions & 1 deletion test/unit/payments-processors/lnurl-payments-processor.spec.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
import { createServer, Server } from 'node:http'
import { AddressInfo } from 'node:net'

import axios from 'axios'
import chai from 'chai'
import chaiAsPromised from 'chai-as-promised'
import sinon from 'sinon'
Expand Down Expand Up @@ -85,7 +89,8 @@ describe('LnurlPaymentsProcessor', () => {

await makeProcessor(httpClient).getInvoice(lnurlInvoice)

expect(httpClient.get).to.have.been.calledOnceWithExactly('https://pay.example.com/verify/abc')
expect(httpClient.get).to.have.been.calledOnce
expect(httpClient.get.firstCall.args[0]).to.equal('https://pay.example.com/verify/abc')
})

it('reports a settled invoice as completed, confirmed now', async () => {
Expand Down Expand Up @@ -119,5 +124,139 @@ describe('LnurlPaymentsProcessor', () => {

await expect(makeProcessor(httpClient).getInvoice(lnurlInvoice)).to.be.rejectedWith('ETIMEDOUT')
})
describe('the verify url', () => {
const askedAbout = (verifyURL: string | undefined, currentSettings?: () => any) => {
const httpClient = { get: sinon.stub().resolves({ data: { settled: false } }) }
const result = makeProcessor(httpClient, currentSettings).getInvoice({
id: 'invoice-id',
verifyURL,
} as LnurlInvoice)
return { httpClient, result }
}

it('is requested as given on the origin of the configured invoice url, without following a redirect', async () => {
const { httpClient, result } = askedAbout('https://pay.example.com/verify/abc')

await result

expect(httpClient.get.firstCall.args[1]).to.deep.equal({ maxRedirects: 0 })
})

it('may be on a private network when the configured invoice url is', async () => {
const privateSettings = () => ({ paymentsProcessors: { lnurl: { invoiceURL: 'http://lnbits:5000/lnurlp/x' } } })
const { httpClient, result } = askedAbout('http://lnbits:5000/api/v1/lnurlp/verify/abc', privateSettings)

await result

expect(httpClient.get).to.have.been.calledOnce
})

it('is resolved by the relay, with no redirect and no proxy, on any other origin', async () => {
const { httpClient, result } = askedAbout('https://other.example.org/verify/abc')

await result

const config = httpClient.get.firstCall.args[1]
expect(config.maxRedirects).to.equal(0)
expect(config.proxy).to.equal(false)
expect(config.lookup).to.be.a('function')
})

it('is not on the invoice url origin when only the port differs', async () => {
const { httpClient, result } = askedAbout('https://pay.example.com:8443/verify/abc')

await result

expect(httpClient.get.firstCall.args[1].lookup).to.be.a('function')
})

it('makes the lookup refuse a host that resolves to a private address', async () => {
const { httpClient, result } = askedAbout('https://other.example.org/verify/abc')
await result

await expect(httpClient.get.firstCall.args[1].lookup('localhost', {})).to.be.rejectedWith(
'resolving to a private address',
)
})

for (const verifyURL of [
'http://127.0.0.1/verify',
'http://127.0.0.1:8080/admin',
'http://10.0.0.5/verify',
'http://192.168.1.1/verify',
'http://169.254.169.254/latest/meta-data/',
'http://[::1]/verify',
'http://[::ffff:127.0.0.1]/verify',
'http://0.0.0.0/verify',
]) {
it(`refuses ${verifyURL} without requesting it`, async () => {
const { httpClient, result } = askedAbout(verifyURL)

await expect(result).to.be.rejectedWith('refused LNURL verify URL')
expect(httpClient.get).not.to.have.been.called
})
}

for (const verifyURL of ['file:///etc/passwd', 'ftp://other.example.org/verify', 'not a url', '', undefined]) {
it(`refuses ${JSON.stringify(verifyURL)} without requesting it`, async () => {
const { httpClient, result } = askedAbout(verifyURL)

await expect(result).to.be.rejectedWith('refused LNURL verify URL')
expect(httpClient.get).not.to.have.been.called
})
}
})

describe('with a real http client', () => {
let server: Server
let hits: string[]
let port: number

beforeEach(async () => {
hits = []
server = createServer((request, response) => {
hits.push(request.url as string)
if (request.url === '/redirect') {
response.writeHead(302, { location: '/target' })
return response.end()
}
response.writeHead(200, { 'content-type': 'application/json' })
response.end(JSON.stringify({ settled: true }))
})
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
port = (server.address() as AddressInfo).port
})

afterEach(() => {
server.close()
})

const poll = (verifyURL: string, invoiceURL: string) =>
makeProcessor(axios.create(), () => ({ paymentsProcessors: { lnurl: { invoiceURL } } })).getInvoice({
id: 'invoice-id',
verifyURL,
} as LnurlInvoice)

it('reaches a verify url on the origin of the invoice url', async () => {
const result = await poll(`http://127.0.0.1:${port}/verify`, `http://127.0.0.1:${port}/lnurlp/x`)

expect(result.status).to.equal(InvoiceStatus.COMPLETED)
expect(hits).to.deep.equal(['/verify'])
})

it('does not follow a redirect, even from the origin of the invoice url', async () => {
await expect(poll(`http://127.0.0.1:${port}/redirect`, `http://127.0.0.1:${port}/lnurlp/x`)).to.be.rejected

expect(hits).to.deep.equal(['/redirect'])
})

it('never connects to a host that resolves to loopback on another origin', async () => {
await expect(
poll(`http://localhost:${port}/verify`, 'https://pay.example.com/lnurlp/relay'),
).to.be.rejectedWith('resolving to a private address')

expect(hits).to.deep.equal([])
})
})
})
})
Loading