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
7 changes: 7 additions & 0 deletions .changeset/nip05-pin-resolved-address.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'nostream': patch
---

fix(nip05): refuse a verification host that resolves to a private address

NIP-05 verification fetched the domain from an author's kind-0 profile but only checked the text of a redirect URL, so a domain whose DNS points at loopback, a private network or a cloud metadata address was still fetched, on the first request and on its redirect. Each host is now resolved and refused before connecting when any of its addresses is on the private-address blocklist the NIP-11 probe already used (now shared, with `fec0::/10` added), a redirect to an IPv4 literal is checked against the same list, and the request ignores `HTTPS_PROXY` and `NODE_USE_ENV_PROXY`, because a proxy would resolve the name itself and skip the check. A deliberate limit: a relay that reaches the internet only through a proxy can no longer verify NIP-05 identifiers.
4 changes: 2 additions & 2 deletions CONFIGURATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ The settings below are listed in alphabetical order by name. Please keep this ta
| nip05.domainBlacklist | List of domains blocked from NIP-05 verification. Authors with NIP-05 at these domains will be rejected. |
| nip05.domainWhitelist | List of domains allowed for NIP-05 verification. If set, only authors verified at these domains can publish. |
| nip05.maxConsecutiveFailures | Number of consecutive verification failures before giving up on an author. Defaults to 20. |
| nip05.mode | NIP-05 verification mode: `enabled` requires verification, `passive` verifies without blocking, `disabled` does nothing. Defaults to `disabled`. |
| nip05.mode | NIP-05 verification mode: `enabled` requires verification, `passive` verifies without blocking, `disabled` does nothing. Defaults to `disabled`. Verification requests go out directly over HTTPS and ignore `HTTPS_PROXY` and Node's `NODE_USE_ENV_PROXY`, so the relay needs direct outbound HTTPS; a domain or redirect target that resolves to a loopback, private or link-local address is not contacted. |
| nip05.verifyExpiration | Time in milliseconds before a successful NIP-05 verification expires and needs re-checking. Defaults to 604800000 (1 week). |
| nip05.verifyUpdateFrequency | Minimum interval in milliseconds between re-verification attempts for a given author. Defaults to 86400000 (24 hours). |
| nip42.authRequired | When true, clients must NIP-42 AUTH as the event author before publishing events. Advertised in NIP-11 as `limitation.restricted_writes` (not `auth_required`, which means AUTH before any connection action). Defaults to false. |
Expand Down Expand Up @@ -278,7 +278,7 @@ The settings below are listed in alphabetical order by name. Please keep this ta
| nip05.domainBlacklist | List of domains blocked from NIP-05 verification. Authors with NIP-05 at these domains will be rejected. |
| nip05.domainWhitelist | List of domains allowed for NIP-05 verification. If set, only authors verified at these domains can publish. |
| nip05.maxConsecutiveFailures | Number of consecutive verification failures before giving up on an author. Defaults to 20. |
| nip05.mode | NIP-05 verification mode: `enabled` requires verification, `passive` verifies without blocking, `disabled` does nothing. Defaults to `disabled`. |
| nip05.mode | NIP-05 verification mode: `enabled` requires verification, `passive` verifies without blocking, `disabled` does nothing. Defaults to `disabled`. Verification requests go out directly over HTTPS and ignore `HTTPS_PROXY` and Node's `NODE_USE_ENV_PROXY`, so the relay needs direct outbound HTTPS; a domain or redirect target that resolves to a loopback, private or link-local address is not contacted. |
| nip05.verifyExpiration | Time in milliseconds before a successful NIP-05 verification expires and needs re-checking. Defaults to 604800000 (1 week). |
| nip05.verifyUpdateFrequency | Minimum interval in milliseconds between re-verification attempts for a given author. Defaults to 86400000 (24 hours). |
| paymentProcessors.lnbits.baseURL | Base URL of your LNbits instance. |
Expand Down
50 changes: 31 additions & 19 deletions src/utils/nip05.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import { Agent } from 'node:https'
import { isIP } from 'node:net'
import axios, { AxiosError } from 'axios'
import { z } from 'zod'

import { createLogger } from '../factories/logger-factory'
import { Event } from '../@types/event'
import { EventKinds } from '../constants/base'
import { pubkeySchema } from '../schemas/base-schema'
import { createSafeLookup, isBlockedAddress } from './safe-lookup'

const logger = createLogger('nip05')

Expand All @@ -15,6 +18,13 @@ const MAX_RESPONSE_BYTES = 64 * 1024
// their well-known under a redirect; unlimited would enable SSRF pivoting.
const MAX_REDIRECTS = 1
const DOMAIN_REGEX = /^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?)*\.[a-zA-Z]{2,}$/
const nip05Lookup = createSafeLookup('NIP-05')
// Own agent: with NODE_USE_ENV_PROXY the global agent goes through a proxy,
// which resolves the host itself and skips nip05Lookup. Keep-alive is on
// explicitly: a plain `new Agent()` has it off (only `https.globalAgent`
// defaults to on), so sequential verifications against one origin would
// redo DNS, TCP and TLS; the guarded lookup still runs for every new socket.
const nip05HttpsAgent = new Agent({ keepAlive: true, keepAliveMsecs: 30_000 })

// Public defaults used by callers when settings omit these fields. Exported so the
// runtime defaults stay in one place and are easy to unit test.
Expand Down Expand Up @@ -95,8 +105,9 @@ export function extractNip05FromEvent(event: Event): string | undefined {

/**
* Reject redirect targets that would turn this endpoint into an SSRF primitive:
* non-https schemes, loopback, link-local, and RFC1918 private ranges.
* Domain-based checks (e.g. `localhost`) are included for belt-and-suspenders.
* non-https schemes, non-public IPv4 literals, and IPv6 literals. Domain-based
* checks (e.g. `localhost`) are included for belt-and-suspenders; hostnames are
* checked again by nip05Lookup when they resolve.
*/
function isRedirectTargetSafe(targetUrl: string): boolean {
let parsed: URL
Expand All @@ -115,22 +126,9 @@ function isRedirectTargetSafe(targetUrl: string): boolean {
return false
}

// IPv4 literal check. Covers loopback (127/8), private ranges (10/8, 172.16/12,
// 192.168/16), link-local (169.254/16), and multicast/reserved (>=224).
const ipv4 = host.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/)
if (ipv4) {
const [a, b] = ipv4.slice(1, 3).map(Number)
if (
a === 10 ||
a === 127 ||
a === 0 ||
a >= 224 ||
(a === 169 && b === 254) ||
(a === 172 && b >= 16 && b <= 31) ||
(a === 192 && b === 168)
) {
return false
}
// Node skips `lookup` for an IP literal, so check it here.
if (isIP(host) === 4 && isBlockedAddress(host)) {
return false
}

// IPv6 literal: reject any bracketed v6 address; NIP-05 hosts are domain names.
Expand All @@ -141,6 +139,16 @@ function isRedirectTargetSafe(targetUrl: string): boolean {
return true
}

// Keep only scheme and host: the rest of the URL may carry credentials.
function describeRedirectTarget(targetUrl: string): string {
try {
const { protocol, host } = new URL(targetUrl)
return `${protocol}//${host}`
} catch {
return 'an invalid URL'
}
}

export async function verifyNip05Identifier(nip05: string, pubkey: string): Promise<Nip05VerificationOutcome> {
const parsed = parseNip05Identifier(nip05)
if (!parsed) {
Expand All @@ -161,12 +169,16 @@ export async function verifyNip05Identifier(nip05: string, pubkey: string): Prom
maxRedirects: MAX_REDIRECTS,
maxContentLength: MAX_RESPONSE_BYTES,
maxBodyLength: MAX_RESPONSE_BYTES,
// No proxy, so nip05Lookup checks every host, redirects included.
proxy: false,
httpsAgent: nip05HttpsAgent,
lookup: nip05Lookup,
// `beforeRedirect` is forwarded to follow-redirects by axios. Any throw
// here aborts the request with that error, which we catch below.
beforeRedirect: (options: { href?: string; protocol?: string; hostname?: string }) => {
const href = options.href ?? `${options.protocol ?? ''}//${options.hostname ?? ''}`
if (!isRedirectTargetSafe(href)) {
throw new Error(`refused redirect to unsafe target: ${href}`)
throw new Error(`refused redirect to unsafe target: ${describeRedirectTarget(href)}`)
}
},
})
Expand Down
66 changes: 3 additions & 63 deletions src/utils/relay-probe/nip11-probe.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import { lookup as dnsLookup } from 'node:dns/promises'
import { BlockList, isIP } from 'node:net'
import axios, { AxiosError } from 'axios'
import { z } from 'zod'

import { pubkeySchema } from '../../schemas/base-schema'
import { createSafeLookup, isBlockedAddress } from '../safe-lookup'
import { Nip11Result } from './types'

const MAX_RESPONSE_BYTES = 256 * 1024
Expand Down Expand Up @@ -43,68 +42,9 @@ export interface Nip11Fetcher {
fetch(url: string, timeoutMs: number): Promise<Nip11Result>
}

const blockedNip11Addresses = new BlockList()
blockedNip11Addresses.addSubnet('0.0.0.0', 8, 'ipv4')
blockedNip11Addresses.addSubnet('10.0.0.0', 8, 'ipv4')
blockedNip11Addresses.addSubnet('100.64.0.0', 10, 'ipv4')
blockedNip11Addresses.addSubnet('127.0.0.0', 8, 'ipv4')
blockedNip11Addresses.addSubnet('169.254.0.0', 16, 'ipv4')
blockedNip11Addresses.addSubnet('172.16.0.0', 12, 'ipv4')
blockedNip11Addresses.addSubnet('192.0.0.0', 24, 'ipv4')
blockedNip11Addresses.addSubnet('192.0.2.0', 24, 'ipv4')
blockedNip11Addresses.addSubnet('192.168.0.0', 16, 'ipv4')
blockedNip11Addresses.addSubnet('198.18.0.0', 15, 'ipv4')
blockedNip11Addresses.addSubnet('198.51.100.0', 24, 'ipv4')
blockedNip11Addresses.addSubnet('203.0.113.0', 24, 'ipv4')
blockedNip11Addresses.addSubnet('224.0.0.0', 4, 'ipv4')
blockedNip11Addresses.addSubnet('240.0.0.0', 4, 'ipv4')
blockedNip11Addresses.addSubnet('::', 128, 'ipv6')
blockedNip11Addresses.addSubnet('::1', 128, 'ipv6')
blockedNip11Addresses.addSubnet('2001:db8::', 32, 'ipv6')
blockedNip11Addresses.addSubnet('fc00::', 7, 'ipv6')
blockedNip11Addresses.addSubnet('fe80::', 10, 'ipv6')
blockedNip11Addresses.addSubnet('ff00::', 8, 'ipv6')

const normalizeResolvedAddress = (address: string): string => {
const lower = address.toLowerCase()
const mapped = lower.startsWith('::ffff:') ? lower.slice('::ffff:'.length) : lower

return isIP(mapped) === 4 ? mapped : lower
}

export const isBlockedNip11Address = (address: string): boolean => {
const normalized = normalizeResolvedAddress(address)
const family = isIP(normalized)

if (family === 4) {
return blockedNip11Addresses.check(normalized, 'ipv4')
}

if (family === 6) {
return blockedNip11Addresses.check(normalized, 'ipv6')
}

return true
}
export const isBlockedNip11Address = isBlockedAddress

/**
* Resolve a NIP-11 host and refuse private/loopback/link-local results before
* the socket connects. String-only URL checks miss hostnames whose A/AAAA
* records point inward, including DNS rebinding after the literal check.
*/
export const safeNip11Lookup = async (
hostname: string,
options: object,
): Promise<{ address: string; family: number }[]> => {
const result = await dnsLookup(hostname, { ...(options as any), all: true })
const addresses = Array.isArray(result) ? result : [result]

if (addresses.some((entry) => isBlockedNip11Address(entry.address))) {
throw new Error(`refused NIP-11 target ${hostname} resolving to a private address`)
}

return addresses
}
export const safeNip11Lookup = createSafeLookup('NIP-11')

/**
* Reject redirect targets that would turn relay probing into an SSRF primitive.
Expand Down
67 changes: 67 additions & 0 deletions src/utils/safe-lookup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { lookup as dnsLookup } from 'node:dns/promises'
import { BlockList, isIP } from 'node:net'

const blockedAddresses = new BlockList()
blockedAddresses.addSubnet('0.0.0.0', 8, 'ipv4')
blockedAddresses.addSubnet('10.0.0.0', 8, 'ipv4')
blockedAddresses.addSubnet('100.64.0.0', 10, 'ipv4')
blockedAddresses.addSubnet('127.0.0.0', 8, 'ipv4')
blockedAddresses.addSubnet('169.254.0.0', 16, 'ipv4')
blockedAddresses.addSubnet('172.16.0.0', 12, 'ipv4')
blockedAddresses.addSubnet('192.0.0.0', 24, 'ipv4')
blockedAddresses.addSubnet('192.0.2.0', 24, 'ipv4')
blockedAddresses.addSubnet('192.168.0.0', 16, 'ipv4')
blockedAddresses.addSubnet('198.18.0.0', 15, 'ipv4')
blockedAddresses.addSubnet('198.51.100.0', 24, 'ipv4')
blockedAddresses.addSubnet('203.0.113.0', 24, 'ipv4')
blockedAddresses.addSubnet('224.0.0.0', 4, 'ipv4')
blockedAddresses.addSubnet('240.0.0.0', 4, 'ipv4')
blockedAddresses.addSubnet('::', 128, 'ipv6')
blockedAddresses.addSubnet('::1', 128, 'ipv6')
blockedAddresses.addSubnet('2001:db8::', 32, 'ipv6')
blockedAddresses.addSubnet('fc00::', 7, 'ipv6')
blockedAddresses.addSubnet('fe80::', 10, 'ipv6')
blockedAddresses.addSubnet('fec0::', 10, 'ipv6')
blockedAddresses.addSubnet('ff00::', 8, 'ipv6')

const normalizeResolvedAddress = (address: string): string => {
const lower = address.toLowerCase()
const mapped = lower.startsWith('::ffff:') ? lower.slice('::ffff:'.length) : lower

return isIP(mapped) === 4 ? mapped : lower
}

export const isBlockedAddress = (address: string): boolean => {
const normalized = normalizeResolvedAddress(address)
const family = isIP(normalized)

if (family === 4) {
return blockedAddresses.check(normalized, 'ipv4')
}

if (family === 6) {
return blockedAddresses.check(normalized, 'ipv6')
}

return true
}

/**
* Build a request `lookup` that resolves the host and refuses private/loopback/link-local
* results before the socket connects. String-only URL checks miss hostnames whose A/AAAA
* records point inward, including DNS rebinding after the literal check. Node does not call
* `lookup` for an IP literal host, so callers must check literals with isBlockedAddress.
*/
export const createSafeLookup =
(target: string) =>
async (hostname: string, options: object): Promise<[{ address: string; family: number }[]]> => {
const result = await dnsLookup(hostname, { ...(options as any), all: true })
const addresses = Array.isArray(result) ? result : [result]

if (addresses.some((entry) => isBlockedAddress(entry.address))) {
throw new Error(`refused ${target} target ${hostname} resolving to a private address`)
}

// axios reads an async lookup's result as [address(es), family]; a flat array would keep only the first address.
return [addresses]
}
Loading
Loading