Skip to content
Open
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-verify-through-pinned-proxy.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'nostream': minor
---

feat(nip05): verify through an egress proxy by pinning the address that was checked (`nip05.proxy`)

NIP-05 verification connects directly and ignores `HTTPS_PROXY`, because a proxy resolves the host name itself and so skips the check that refuses private addresses. A relay that reaches the internet only through an egress proxy could therefore not verify NIP-05 identifiers at all. The new setting `nip05.proxy` (`disabled`, the default, or `pin`) gives that relay a way back. With `pin`, the relay sends the requests through the proxy in `HTTPS_PROXY`, but resolves the host itself, refuses a private, loopback or link-local address before the proxy is contacted, and asks the proxy for `CONNECT <address>:443` with the address it checked. TLS runs through the tunnel with the host name as `servername`, so the certificate is still checked against the host. A redirect target goes through the same steps. A proxy that refuses the `CONNECT` makes the verification fail with a reason naming the proxy and the host. With the setting absent or `disabled`, nothing changes.
6 changes: 4 additions & 2 deletions CONFIGURATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,8 @@ 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`. 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.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` unless `nip05.proxy` is `pin`, so the relay needs direct outbound HTTPS or `nip05.proxy`; a domain or redirect target that resolves to a loopback, private or link-local address is not contacted. |
| nip05.proxy | How NIP-05 verification requests reach the internet: `disabled` (default) connects directly and ignores `HTTPS_PROXY`; `pin` goes through the HTTP or HTTPS proxy in `HTTPS_PROXY` (`NO_PROXY` is not read). The relay resolves the host itself, refuses a private address, and asks the proxy for `CONNECT <address>:443` with the address it checked, then checks the certificate against the host name, a redirect target included. A proxy that refuses the `CONNECT` makes the verification fail with a reason naming the proxy and the host. With `pin` and no `HTTPS_PROXY` the connection is direct. |
| 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 +279,8 @@ 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`. 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.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` unless `nip05.proxy` is `pin`, so the relay needs direct outbound HTTPS or `nip05.proxy`; a domain or redirect target that resolves to a loopback, private or link-local address is not contacted. |
| nip05.proxy | How NIP-05 verification requests reach the internet: `disabled` (default) connects directly and ignores `HTTPS_PROXY`; `pin` goes through the HTTP or HTTPS proxy in `HTTPS_PROXY` (`NO_PROXY` is not read). The relay resolves the host itself, refuses a private address, and asks the proxy for `CONNECT <address>:443` with the address it checked, then checks the certificate against the host name, a redirect target included. A proxy that refuses the `CONNECT` makes the verification fail with a reason naming the proxy and the host. With `pin` and no `HTTPS_PROXY` the connection is direct. |
| 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
4 changes: 4 additions & 0 deletions resources/default-settings.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,10 @@ nip05:
domainWhitelist: []
# Block authors with NIP-05 at these domains
domainBlacklist: []
# How verification requests reach the internet. 'disabled' connects directly and ignores HTTPS_PROXY.
# 'pin' goes through the proxy in HTTPS_PROXY, but the relay resolves the host itself and asks the proxy
# to connect to the address it checked, so a proxy cannot send the request to a private address.
proxy: disabled
nip42:
# When true, clients must AUTH (NIP-42) as the event author before publishing.
# Advertised in NIP-11 as limitation.restricted_writes (not auth_required).
Expand Down
8 changes: 8 additions & 0 deletions src/@types/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -352,6 +352,8 @@ export interface Dvm {

export type Nip05Mode = 'enabled' | 'passive' | 'disabled'

export type Nip05Proxy = 'disabled' | 'pin'

export interface Nip45Settings {
enabled?: boolean
}
Expand Down Expand Up @@ -439,6 +441,12 @@ export interface Nip05Settings {
maxConsecutiveFailures?: number
domainWhitelist?: string[]
domainBlacklist?: string[]
/**
* How verification requests reach the internet. `disabled` (the default) connects directly and ignores HTTPS_PROXY.
* `pin` goes through the proxy in HTTPS_PROXY, but resolves the host here and asks the proxy for the address that
* was checked.
*/
proxy?: Nip05Proxy
}

export interface AdminNip98Settings {
Expand Down
32 changes: 30 additions & 2 deletions src/utils/nip05.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ import { createLogger } from '../factories/logger-factory'
import { Event } from '../@types/event'
import { EventKinds } from '../constants/base'
import { pubkeySchema } from '../schemas/base-schema'
import { PinnedProxyAgent } from './pinned-proxy-agent'
import { createSafeLookup, isBlockedAddress } from './safe-lookup'
import { SettingsStatic } from './settings'

const logger = createLogger('nip05')

Expand All @@ -26,6 +28,32 @@ const nip05Lookup = createSafeLookup('NIP-05')
// redo DNS, TCP and TLS; the guarded lookup still runs for every new socket.
const nip05HttpsAgent = new Agent({ keepAlive: true, keepAliveMsecs: 30_000 })

// `nip05.proxy: pin` sends the verification requests through the proxy in HTTPS_PROXY, but resolves the host here and
// asks the proxy for the address that was checked, so the proxy never decides where the request goes. One agent per
// proxy URL, so connections to the same origin are still reused.
const pinnedProxyAgents = new Map<string, Agent>()

const getPinnedProxyAgent = (proxyUrl: string): Agent => {
let agent = pinnedProxyAgents.get(proxyUrl)
if (!agent) {
agent = new PinnedProxyAgent(proxyUrl, 'NIP-05', { keepAlive: true, keepAliveMsecs: 30_000 })
pinnedProxyAgents.set(proxyUrl, agent)
}
return agent
}

const getVerificationAgent = (): Agent => {
let proxyMode: string | undefined
try {
proxyMode = SettingsStatic.createSettings().nip05?.proxy
} catch (error) {
logger('could not read nip05.proxy, using a direct connection: %o', error)
}

const proxyUrl = process.env.HTTPS_PROXY || process.env.https_proxy
return proxyMode === 'pin' && proxyUrl ? getPinnedProxyAgent(proxyUrl) : nip05HttpsAgent
}

// 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.
export const DEFAULT_NIP05_VERIFY_EXPIRATION_MS = 604800000
Expand Down Expand Up @@ -169,9 +197,9 @@ 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.
// axios must not pick up a proxy itself: nip05Lookup (or the pinned agent) checks every host, redirects included.
proxy: false,
httpsAgent: nip05HttpsAgent,
httpsAgent: getVerificationAgent(),
lookup: nip05Lookup,
// `beforeRedirect` is forwarded to follow-redirects by axios. Any throw
// here aborts the request with that error, which we catch below.
Expand Down
232 changes: 232 additions & 0 deletions src/utils/pinned-proxy-agent.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,232 @@
import { Agent, AgentOptions } from 'node:https'
import { connect as netConnect, isIP, Socket } from 'node:net'
import { connect as tlsConnect, ConnectionOptions } from 'node:tls'

import { createSafeLookup, isBlockedAddress } from './safe-lookup'

const CONNECT_TIMEOUT_MS = 10_000
// The whole setup of one tunnel: resolving the host, reaching the proxy and the CONNECT, retries included. The request's
// own timeout starts only once a socket is assigned, so it does not cover this wait.
const DEFAULT_SETUP_TIMEOUT_MS = 10_000
const MAX_RESPONSE_HEAD_BYTES = 8 * 1024
const HTTPS_PORT = 443

type Lookup = ReturnType<typeof createSafeLookup>

export interface PinnedProxyAgentOptions extends AgentOptions {
/** Time allowed to set up one tunnel, in milliseconds. */
setupTimeoutMs?: number
}

interface TunnelSetup {
expired: boolean
pending?: Socket
}

const HEAD_TERMINATOR = '\r\n\r\n'

// How many bytes at the end of an unfinished head could be the start of the terminator, split by a chunk boundary.
const partialTerminatorLength = (head: Buffer): number => {
for (let length = HEAD_TERMINATOR.length - 1; length > 0; length--) {
if (
head.length >= length &&
head.subarray(head.length - length).toString('latin1') === HEAD_TERMINATOR.slice(0, length)
) {
return length
}
}
return 0
}

const hostForAuthority = (address: string): string => (isIP(address) === 6 ? `[${address}]` : address)

/**
* An https agent that reaches the origin through an HTTP proxy without letting the proxy resolve the name.
*
* The host is resolved here, every address is checked, and the proxy is asked for `CONNECT <address>:443` with the
* address that was checked, so the proxy can only connect to an address this relay validated. TLS then runs through
* the tunnel with the hostname as `servername`, so the certificate is still checked against the host and not against
* the pinned address. Every new connection, a redirect target's included, goes through the same steps.
*/
export class PinnedProxyAgent extends Agent {
private readonly proxy: URL

private readonly lookup: Lookup

private readonly tlsOptions: AgentOptions

private readonly setupTimeoutMs: number

public constructor(proxyUrl: string, target: string, { setupTimeoutMs, ...options }: PinnedProxyAgentOptions = {}) {
super(options)
this.tlsOptions = options
this.setupTimeoutMs = setupTimeoutMs ?? DEFAULT_SETUP_TIMEOUT_MS
this.proxy = new URL(proxyUrl)
if (this.proxy.protocol !== 'http:' && this.proxy.protocol !== 'https:') {
throw new Error(`unsupported proxy protocol ${this.proxy.protocol} for ${target}`)
}
this.lookup = createSafeLookup(target)
}

// Node calls this for every new socket and accepts the socket through the callback.
public createConnection(options: any, callback: (error: Error | null, socket?: Socket) => void): undefined {
this.tunnel(options).then(
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
(socket) => callback(null, socket),
(error) => callback(error instanceof Error ? error : new Error(String(error))),
)
return undefined
}

// Every address returned here has been checked; the tunnel is only ever asked for one of them.
private async resolve(hostname: string): Promise<string[]> {
if (isIP(hostname)) {
if (isBlockedAddress(hostname)) {
throw new Error(`refused target ${hostname} resolving to a private address`)
}
return [hostname]
}

// Throws when any address of the host is private; nothing has been dialed at that point.
const [addresses] = await this.lookup(hostname, {})
return addresses.map((entry) => entry.address)
}

private async tunnel(options: { host?: string; hostname?: string; port?: number | string }): Promise<Socket> {
const hostname = String(options.host ?? options.hostname ?? '')
const setup: TunnelSetup = { expired: false }
let timer: NodeJS.Timeout | undefined
const deadline = new Promise<never>((_, reject) => {
timer = setTimeout(() => {
setup.expired = true
setup.pending?.destroy()
reject(new Error(`timed out setting up a tunnel to ${hostname} through proxy ${this.proxy.host}`))
}, this.setupTimeoutMs)
})

try {
return await Promise.race([this.openTunnel(options, hostname, setup), deadline])
} finally {
clearTimeout(timer)
}
}

private async openTunnel(
options: { host?: string; hostname?: string; port?: number | string },
hostname: string,
setup: TunnelSetup,
): Promise<Socket> {
const port = Number(options.port) || HTTPS_PORT
const addresses = await this.resolve(hostname)

// A host with an address the proxy cannot reach (an AAAA record on an IPv4-only network) is tried on its next
// checked address, the way a direct connection moves on to the next one.
let lastError: Error | undefined
for (const address of addresses) {
if (setup.expired) {
break
}

const proxySocket = await this.connectToProxy(hostname, setup)

try {
await this.requestTunnel(proxySocket, hostname, `${hostForAuthority(address)}:${port}`)
} catch (error) {
proxySocket.destroy()
lastError = error instanceof Error ? error : new Error(String(error))
continue
}

if (setup.expired) {
proxySocket.destroy()
break
}

// The agent's TLS options (a CA, rejectUnauthorized) and the request's apply to the origin, as they would to a
// direct connection. The socket is the tunnel, and the certificate is checked against the host name.
const origin = { ...options, ...this.tlsOptions, socket: proxySocket, servername: hostname }
return tlsConnect(origin as ConnectionOptions) as unknown as Socket
}

throw lastError ?? new Error(`no address to connect to for ${hostname}`)
}

private connectToProxy(hostname: string, setup: TunnelSetup): Promise<Socket> {
const port = Number(this.proxy.port) || (this.proxy.protocol === 'https:' ? 443 : 80)
const host = this.proxy.hostname.replace(/^\[|\]$/g, '')

return new Promise((resolve, reject) => {
const secure = this.proxy.protocol === 'https:'
const socket: Socket = secure
? (tlsConnect({ ...this.tlsOptions, host, port, servername: host }) as unknown as Socket)
: netConnect({ host, port })
setup.pending = socket
const onError = (error: Error) =>
reject(new Error(`could not reach proxy ${this.proxy.host} for ${hostname}: ${error.message}`))
socket.setTimeout(CONNECT_TIMEOUT_MS, () => {
socket.destroy()
reject(new Error(`timed out reaching proxy ${this.proxy.host} for ${hostname}`))
})
socket.once('error', onError)
socket.once(secure ? 'secureConnect' : 'connect', () => {
socket.off('error', onError)
socket.setTimeout(0)
resolve(socket)
})
})
}

private requestTunnel(socket: Socket, hostname: string, authority: string): Promise<void> {
const headers = [`CONNECT ${authority} HTTP/1.1`, `Host: ${authority}`]
if (this.proxy.username) {
const credentials = `${decodeURIComponent(this.proxy.username)}:${decodeURIComponent(this.proxy.password)}`
headers.push(`Proxy-Authorization: Basic ${Buffer.from(credentials).toString('base64')}`)
}

return new Promise((resolve, reject) => {
let head = Buffer.alloc(0)
const fail = (reason: string) => {
cleanup()
reject(new Error(`proxy ${this.proxy.host} refused CONNECT to ${hostname}: ${reason}`))
}
const onData = (chunk: Buffer) => {
head = Buffer.concat([head, chunk])
const end = head.indexOf(HEAD_TERMINATOR)
// The size of the head without its terminator, so the same reply is refused or accepted however it is split
// into chunks, a split inside the terminator included.
const size = end === -1 ? head.length - partialTerminatorLength(head) : end
if (size > MAX_RESPONSE_HEAD_BYTES) {
fail('response too large')
return
}
if (end === -1) {
return
}

const statusLine = head.subarray(0, head.indexOf('\r\n')).toString('latin1')
const status = /^HTTP\/1\.[01] (\d{3})/.exec(statusLine)?.[1]
if (!status || status[0] !== '2') {
fail(statusLine.slice(0, 100) || 'no status line')
return
}

// Bytes after the head would belong to the tunneled TLS stream, which the origin has not started yet.
cleanup()
resolve()
}
const onClose = () => fail('connection closed')
const onError = (error: Error) => fail(error.message)
const timer = setTimeout(() => fail('timed out'), CONNECT_TIMEOUT_MS)
const cleanup = () => {
clearTimeout(timer)
socket.off('data', onData)
socket.off('close', onClose)
socket.off('error', onError)
}

socket.on('data', onData)
socket.once('close', onClose)
socket.once('error', onError)
socket.write(`${headers.join('\r\n')}\r\n\r\n`)
})
}
}
Loading
Loading