diff --git a/.changeset/nip05-verify-through-pinned-proxy.md b/.changeset/nip05-verify-through-pinned-proxy.md new file mode 100644 index 000000000..89a176f45 --- /dev/null +++ b/.changeset/nip05-verify-through-pinned-proxy.md @@ -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
: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. diff --git a/CONFIGURATION.md b/CONFIGURATION.md index c7966d2a5..6a45605ad 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -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
: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. | @@ -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
: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. | diff --git a/resources/default-settings.yaml b/resources/default-settings.yaml index 5eb07fa15..b0d9bd182 100755 --- a/resources/default-settings.yaml +++ b/resources/default-settings.yaml @@ -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). diff --git a/src/@types/settings.ts b/src/@types/settings.ts index 54b770b6d..3597874f3 100644 --- a/src/@types/settings.ts +++ b/src/@types/settings.ts @@ -352,6 +352,8 @@ export interface Dvm { export type Nip05Mode = 'enabled' | 'passive' | 'disabled' +export type Nip05Proxy = 'disabled' | 'pin' + export interface Nip45Settings { enabled?: boolean } @@ -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 { diff --git a/src/utils/nip05.ts b/src/utils/nip05.ts index d8603186f..6b9638dcc 100644 --- a/src/utils/nip05.ts +++ b/src/utils/nip05.ts @@ -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') @@ -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() + +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 @@ -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. diff --git a/src/utils/pinned-proxy-agent.ts b/src/utils/pinned-proxy-agent.ts new file mode 100644 index 000000000..a6560ee60 --- /dev/null +++ b/src/utils/pinned-proxy-agent.ts @@ -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 + +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
: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( + (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 { + 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 { + const hostname = String(options.host ?? options.hostname ?? '') + const setup: TunnelSetup = { expired: false } + let timer: NodeJS.Timeout | undefined + const deadline = new Promise((_, 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 { + 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 { + 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 { + 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`) + }) + } +} diff --git a/src/utils/settings-config.ts b/src/utils/settings-config.ts index 263ee38f0..e7b93d137 100644 --- a/src/utils/settings-config.ts +++ b/src/utils/settings-config.ts @@ -841,7 +841,8 @@ export const setByPath = ( current = current[token.index] // Same rule one level down: an entry the settings hold is the operator's, and its missing fields are not // filled from the default entry at that index. - currentDefaults = existing === undefined && Array.isArray(currentDefaults) ? currentDefaults[token.index] : undefined + currentDefaults = + existing === undefined && Array.isArray(currentDefaults) ? currentDefaults[token.index] : undefined } const last = tokens[tokens.length - 1] @@ -1426,6 +1427,11 @@ export const validateSettings = (settings: Settings): ValidationIssue[] => { }) } + const nip05Proxy = settings.nip05?.proxy + if (!isNil(nip05Proxy) && nip05Proxy !== 'disabled' && nip05Proxy !== 'pin') { + issues.push({ path: 'nip05.proxy', message: 'proxy must be disabled or pin' }) + } + const nip66 = settings.nip66 if (nip66?.historyRetentionRuns !== undefined) { const runs = nip66.historyRetentionRuns diff --git a/test/unit/utils/nip05.spec.ts b/test/unit/utils/nip05.spec.ts index 4487072ad..b2b505c09 100644 --- a/test/unit/utils/nip05.spec.ts +++ b/test/unit/utils/nip05.spec.ts @@ -19,6 +19,8 @@ import { verifyNip05Identifier, } from '../../../src/utils/nip05' import { Event } from '../../../src/@types/event' +import { PinnedProxyAgent } from '../../../src/utils/pinned-proxy-agent' +import { SettingsStatic } from '../../../src/utils/settings' import { EventKinds } from '../../../src/constants/base' const { expect } = chai @@ -97,39 +99,33 @@ describe('NIP-05 utils', () => { describe('extractNip05FromEvent', () => { it('extracts nip05 from kind 0 event', () => { - expect(extractNip05FromEvent( - makeEvent(EventKinds.SET_METADATA, JSON.stringify({ name: 'alice', nip05: 'alice@example.com' })), - )).to.equal('alice@example.com') + expect( + extractNip05FromEvent( + makeEvent(EventKinds.SET_METADATA, JSON.stringify({ name: 'alice', nip05: 'alice@example.com' })), + ), + ).to.equal('alice@example.com') }) it('returns undefined for non-kind-0 event', () => { - expect(extractNip05FromEvent( - makeEvent(EventKinds.TEXT_NOTE, JSON.stringify({ nip05: 'alice@example.com' })), - )).to.be.undefined + expect(extractNip05FromEvent(makeEvent(EventKinds.TEXT_NOTE, JSON.stringify({ nip05: 'alice@example.com' })))).to + .be.undefined }) it('returns undefined when nip05 is not in content', () => { - expect(extractNip05FromEvent( - makeEvent(EventKinds.SET_METADATA, JSON.stringify({ name: 'alice' })), - )).to.be.undefined + expect(extractNip05FromEvent(makeEvent(EventKinds.SET_METADATA, JSON.stringify({ name: 'alice' })))).to.be + .undefined }) it('returns undefined for invalid JSON content', () => { - expect(extractNip05FromEvent( - makeEvent(EventKinds.SET_METADATA, 'not json'), - )).to.be.undefined + expect(extractNip05FromEvent(makeEvent(EventKinds.SET_METADATA, 'not json'))).to.be.undefined }) it('returns undefined when nip05 is empty string', () => { - expect(extractNip05FromEvent( - makeEvent(EventKinds.SET_METADATA, JSON.stringify({ nip05: '' })), - )).to.be.undefined + expect(extractNip05FromEvent(makeEvent(EventKinds.SET_METADATA, JSON.stringify({ nip05: '' })))).to.be.undefined }) it('returns undefined when nip05 is not a string', () => { - expect(extractNip05FromEvent( - makeEvent(EventKinds.SET_METADATA, JSON.stringify({ nip05: 42 })), - )).to.be.undefined + expect(extractNip05FromEvent(makeEvent(EventKinds.SET_METADATA, JSON.stringify({ nip05: 42 })))).to.be.undefined }) }) @@ -208,6 +204,57 @@ describe('NIP-05 utils', () => { expect(typeof config.beforeRedirect).to.equal('function') }) + describe('nip05.proxy', () => { + const sandbox = Sinon.createSandbox() + const savedEnv = { HTTPS_PROXY: process.env.HTTPS_PROXY, https_proxy: process.env.https_proxy } + + const agentFor = async (proxy: string | undefined, proxyUrl: string | undefined) => { + sandbox.stub(SettingsStatic, 'createSettings').returns({ nip05: { mode: 'enabled', proxy } } as any) + if (proxyUrl) { + process.env.HTTPS_PROXY = proxyUrl + } else { + delete process.env.HTTPS_PROXY + } + delete process.env.https_proxy + axiosGetStub.resolves({ data: { names: { alice: pubkey } } }) + + await verifyNip05Identifier('alice@example.com', pubkey) + + return axiosGetStub.lastCall.args[1].httpsAgent + } + + afterEach(() => { + sandbox.restore() + for (const [name, value] of Object.entries(savedEnv)) { + if (value === undefined) { + delete process.env[name] + } else { + process.env[name] = value + } + } + }) + + it('goes through the proxy only with nip05.proxy set to pin and a proxy in HTTPS_PROXY', async () => { + expect(await agentFor('pin', 'http://127.0.0.1:3128')).to.be.instanceOf(PinnedProxyAgent) + }) + + it('connects directly, with the proxy in the environment ignored, when nip05.proxy is disabled or unset', async () => { + expect(await agentFor('disabled', 'http://127.0.0.1:3128')).not.to.be.instanceOf(PinnedProxyAgent) + sandbox.restore() + expect(await agentFor(undefined, 'http://127.0.0.1:3128')).not.to.be.instanceOf(PinnedProxyAgent) + }) + + it('connects directly with nip05.proxy set to pin and no proxy in the environment', async () => { + expect(await agentFor('pin', undefined)).not.to.be.instanceOf(PinnedProxyAgent) + }) + + it('keeps the proxy lookup out of axios, which would resolve the host itself', async () => { + await agentFor('pin', 'http://127.0.0.1:3128') + + expect(axiosGetStub.lastCall.args[1].proxy).to.equal(false) + }) + }) + it('returns verified when response pubkey matches', async () => { axiosGetStub.resolves({ data: { names: { alice: pubkey } } }) diff --git a/test/unit/utils/pinned-proxy-agent.spec.ts b/test/unit/utils/pinned-proxy-agent.spec.ts new file mode 100644 index 000000000..0986b70a3 --- /dev/null +++ b/test/unit/utils/pinned-proxy-agent.spec.ts @@ -0,0 +1,426 @@ +import { execFileSync } from 'node:child_process' +import dns from 'node:dns' +import fs from 'node:fs' +import { AddressInfo, connect as netConnect, createServer, Server, Socket } from 'node:net' +import os from 'node:os' +import path from 'node:path' +import tls from 'node:tls' +import chai from 'chai' +import chaiAsPromised from 'chai-as-promised' +import Sinon from 'sinon' +import sinonChai from 'sinon-chai' + +chai.use(chaiAsPromised) +chai.use(sinonChai) + +import { PinnedProxyAgent } from '../../../src/utils/pinned-proxy-agent' + +const { expect } = chai + +describe('PinnedProxyAgent', () => { + const sandbox = Sinon.createSandbox() + const servers: Server[] = [] + let dnsLookup: Sinon.SinonStub + let tlsConnect: Sinon.SinonStub + + // A proxy on 127.0.0.1 that records what it is asked. It answers the CONNECTs in turn with `replies`, the last one + // for every later request. + const startProxy = async (...replies: string[]) => { + const proxy = { connections: 0, requests: [] as string[], url: '' } + const server = createServer((socket) => { + proxy.connections += 1 + let received = '' + socket.on('data', (chunk) => { + received += chunk.toString('latin1') + if (received.includes('\r\n\r\n')) { + proxy.requests.push(received) + socket.write(replies[Math.min(proxy.requests.length, replies.length) - 1]) + } + }) + socket.on('error', () => undefined) + }) + servers.push(server) + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) + proxy.url = `http://127.0.0.1:${(server.address() as AddressInfo).port}` + return proxy + } + + const connect = (agent: PinnedProxyAgent, host: string) => + new Promise((resolve, reject) => { + agent.createConnection({ host, port: 443 }, (error, socket) => + error ? reject(error) : resolve(socket as Socket), + ) + }) + + beforeEach(() => { + dnsLookup = sandbox.stub(dns.promises, 'lookup') + // The tunnel is answered by a plain TCP server, so there is no TLS server to handshake with. + tlsConnect = sandbox.stub(tls, 'connect').callsFake((options: any) => options.socket) + }) + + afterEach(async () => { + sandbox.restore() + await Promise.all(servers.splice(0).map((server) => new Promise((resolve) => server.close(resolve)))) + }) + + it('asks the proxy for the address it resolved, not for the host name', async () => { + const proxy = await startProxy('HTTP/1.1 200 Connection established\r\n\r\n') + dnsLookup.resolves([{ address: '93.184.216.34', family: 4 }]) + + const socket = await connect(new PinnedProxyAgent(proxy.url, 'NIP-05'), 'example.com') + socket.destroy() + + expect(proxy.requests).to.have.length(1) + expect(proxy.requests[0]).to.match(/^CONNECT 93\.184\.216\.34:443 HTTP\/1\.1\r\n/) + expect(proxy.requests[0]).to.include('Host: 93.184.216.34:443') + expect(proxy.requests[0]).not.to.include('example.com') + }) + + it('runs TLS through the tunnel with the host name as servername', async () => { + const proxy = await startProxy('HTTP/1.1 200 OK\r\n\r\n') + dnsLookup.resolves([{ address: '93.184.216.34', family: 4 }]) + + const socket = await connect(new PinnedProxyAgent(proxy.url, 'NIP-05'), 'example.com') + socket.destroy() + + expect(tlsConnect).to.have.been.calledOnce + expect(tlsConnect.firstCall.args[0].servername).to.equal('example.com') + }) + + it('sends proxy credentials from the proxy URL', async () => { + const proxy = await startProxy('HTTP/1.1 200 OK\r\n\r\n') + dnsLookup.resolves([{ address: '93.184.216.34', family: 4 }]) + const url = proxy.url.replace('http://', 'http://relay:p%40ss@') + + const socket = await connect(new PinnedProxyAgent(url, 'NIP-05'), 'example.com') + socket.destroy() + + expect(proxy.requests[0]).to.include(`Proxy-Authorization: Basic ${Buffer.from('relay:p@ss').toString('base64')}`) + }) + + it('writes an IPv6 address in brackets', async () => { + const proxy = await startProxy('HTTP/1.1 200 OK\r\n\r\n') + dnsLookup.resolves([{ address: '2606:4700::1', family: 6 }]) + + const socket = await connect(new PinnedProxyAgent(proxy.url, 'NIP-05'), 'example.com') + socket.destroy() + + expect(proxy.requests[0]).to.match(/^CONNECT \[2606:4700::1\]:443 HTTP\/1\.1\r\n/) + }) + + it('does not contact the proxy for a host that resolves to a private address', async () => { + const proxy = await startProxy('HTTP/1.1 200 OK\r\n\r\n') + const agent = new PinnedProxyAgent(proxy.url, 'NIP-05') + + for (const address of ['127.0.0.1', '10.0.0.5', '192.168.1.1', '169.254.169.254', '::1']) { + dnsLookup.resolves([{ address, family: address.includes(':') ? 6 : 4 }]) + await expect(connect(agent, 'internal.example')).to.be.rejectedWith( + 'refused NIP-05 target internal.example resolving to a private address', + ) + } + + expect(proxy.connections).to.equal(0) + expect(tlsConnect).not.to.have.been.called + }) + + it('refuses a host when any one of its addresses is private', async () => { + const proxy = await startProxy('HTTP/1.1 200 OK\r\n\r\n') + dnsLookup.resolves([ + { address: '93.184.216.34', family: 4 }, + { address: '127.0.0.1', family: 4 }, + ]) + + await expect(connect(new PinnedProxyAgent(proxy.url, 'NIP-05'), 'rebind.example')).to.be.rejectedWith( + 'resolving to a private address', + ) + expect(proxy.connections).to.equal(0) + }) + + it('resolves and checks every new connection, as a redirect target needs', async () => { + const proxy = await startProxy('HTTP/1.1 200 OK\r\n\r\n') + const agent = new PinnedProxyAgent(proxy.url, 'NIP-05') + dnsLookup.withArgs('first.example').resolves([{ address: '93.184.216.34', family: 4 }]) + dnsLookup.withArgs('second.example').resolves([{ address: '100.100.100.200', family: 4 }]) + + const socket = await connect(agent, 'first.example') + socket.destroy() + await expect(connect(agent, 'second.example')).to.be.rejectedWith('resolving to a private address') + + expect(proxy.requests).to.have.length(1) + expect(proxy.requests[0]).to.include('CONNECT 93.184.216.34:443') + }) + + it('moves on to the next checked address when the proxy cannot reach one', async () => { + const proxy = await startProxy('HTTP/1.1 502 Bad Gateway\r\n\r\n', 'HTTP/1.1 200 OK\r\n\r\n') + dnsLookup.resolves([ + { address: '2606:4700::1', family: 6 }, + { address: '93.184.216.34', family: 4 }, + ]) + + const socket = await connect(new PinnedProxyAgent(proxy.url, 'NIP-05'), 'example.com') + socket.destroy() + + expect(proxy.requests.map((request) => request.split(' ')[1])).to.deep.equal([ + '[2606:4700::1]:443', + '93.184.216.34:443', + ]) + }) + + it('names the proxy and the host when the proxy refuses the CONNECT', async () => { + const proxy = await startProxy('HTTP/1.1 403 Forbidden\r\n\r\n') + dnsLookup.resolves([{ address: '93.184.216.34', family: 4 }]) + const host = new URL(proxy.url).host + + await expect(connect(new PinnedProxyAgent(proxy.url, 'NIP-05'), 'example.com')).to.be.rejectedWith( + `proxy ${host} refused CONNECT to example.com: HTTP/1.1 403 Forbidden`, + ) + expect(tlsConnect).not.to.have.been.called + }) + + it('names the proxy when it cannot be reached', async () => { + dnsLookup.resolves([{ address: '93.184.216.34', family: 4 }]) + const server = createServer() + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) + const url = `http://127.0.0.1:${(server.address() as AddressInfo).port}` + await new Promise((resolve) => server.close(resolve)) // nothing listens on it any more + + await expect(connect(new PinnedProxyAgent(url, 'NIP-05'), 'example.com')).to.be.rejectedWith( + `could not reach proxy ${new URL(url).host} for example.com`, + ) + }) + + it('refuses a reply whose head is over the limit, however it is split into chunks', async () => { + const oversized = `HTTP/1.1 200 OK\r\nX-Padding: ${'a'.repeat(9 * 1024)}\r\n\r\n` + const proxy = await startProxy(oversized) + dnsLookup.resolves([{ address: '93.184.216.34', family: 4 }]) + + await expect(connect(new PinnedProxyAgent(proxy.url, 'NIP-05'), 'example.com')).to.be.rejectedWith( + 'refused CONNECT to example.com: response too large', + ) + expect(tlsConnect).not.to.have.been.called + }) + + describe('the size limit of the proxy reply head', () => { + const limit = 8 * 1024 + const terminator = '\r\n\r\n' + // A reply whose head is `size` bytes long, without the terminator. + const replyOfHeadSize = (size: number) => { + const start = 'HTTP/1.1 200 OK\r\nX-Padding: ' + return `${start}${'a'.repeat(size - start.length)}${terminator}` + } + + // A proxy that sends its reply in two writes, split `at` bytes in. + const startSplittingProxy = async (reply: string, at: number) => { + const server = createServer((socket) => { + socket.on('error', () => undefined) + socket.once('data', () => { + socket.write(reply.slice(0, at)) + setTimeout(() => socket.write(reply.slice(at)), 20) + }) + }) + servers.push(server) + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) + return `http://127.0.0.1:${(server.address() as AddressInfo).port}` + } + + const attempt = async (size: number, at: number) => { + dnsLookup.resolves([{ address: '93.184.216.34', family: 4 }]) + const url = await startSplittingProxy(replyOfHeadSize(size), at) + return connect(new PinnedProxyAgent(url, 'NIP-05'), 'example.com') + } + + for (const offset of [0, 1, 2, 3, 4]) { + it(`accepts a head at the limit when the chunk ends ${offset} byte(s) into the terminator`, async () => { + const socket = await attempt(limit, limit + offset) + socket.destroy() + }) + + it(`refuses a head over the limit when the chunk ends ${offset} byte(s) into the terminator`, async () => { + await expect(attempt(limit + 1, limit + 1 + offset)).to.be.rejectedWith('response too large') + }) + } + }) + + it('gives up when resolving the host takes longer than the setup time, without contacting the proxy', async () => { + const proxy = await startProxy('HTTP/1.1 200 OK\r\n\r\n') + dnsLookup.returns(new Promise(() => undefined)) // never answers + + await expect( + connect(new PinnedProxyAgent(proxy.url, 'NIP-05', { setupTimeoutMs: 50 }), 'example.com'), + ).to.be.rejectedWith(`timed out setting up a tunnel to example.com through proxy ${new URL(proxy.url).host}`) + expect(proxy.connections).to.equal(0) + }) + + it('gives up and closes the proxy connection when the proxy never answers the CONNECT', async () => { + let closed = false + const server = createServer((socket) => { + socket.on('close', () => { + closed = true + }) + socket.on('error', () => undefined) + socket.resume() // read, so the close of the other end is seen + }) + servers.push(server) + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) + const url = `http://127.0.0.1:${(server.address() as AddressInfo).port}` + dnsLookup.resolves([{ address: '93.184.216.34', family: 4 }]) + + await expect( + connect(new PinnedProxyAgent(url, 'NIP-05', { setupTimeoutMs: 100 }), 'example.com'), + ).to.be.rejectedWith('timed out setting up a tunnel to example.com') + await new Promise((resolve) => setTimeout(resolve, 50)) + + expect(closed).to.equal(true) + }) + + it('rejects a proxy URL that is not http or https', () => { + expect(() => new PinnedProxyAgent('socks5://127.0.0.1:1080', 'NIP-05')).to.throw('unsupported proxy protocol') + }) +}) + +describe('PinnedProxyAgent over real TLS', () => { + const sandbox = Sinon.createSandbox() + const servers: Server[] = [] + let dir: string + let originCert: string + let originKey: string + let proxyCert: string + let proxyKey: string + let dnsLookup: Sinon.SinonStub + + const makeCertificate = (name: string, altName: string) => { + const key = path.join(dir, `${name}.key`) + const cert = path.join(dir, `${name}.pem`) + execFileSync( + 'openssl', + ['req', '-x509', '-newkey', 'rsa:2048', '-nodes', '-keyout', key, '-out', cert, '-days', '2'].concat([ + '-subj', + `/CN=${name}`, + '-addext', + `subjectAltName=${altName}`, + ]), + { stdio: 'ignore' }, + ) + return { key: fs.readFileSync(key, 'utf8'), cert: fs.readFileSync(cert, 'utf8') } + } + + const listen = async (server: Server) => { + servers.push(server) + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) + return (server.address() as AddressInfo).port + } + + // The origin is a TLS server whose certificate is for good.example. + const startOrigin = () => + listen( + tls.createServer({ key: originKey, cert: originCert }, (socket) => { + socket.on('error', () => undefined) + socket.end('hello') + }), + ) + + // A tunnel that answers any CONNECT and then relays to the origin, whatever address was asked for. + const relay = (socket: Socket, originPort: number, authorities: string[]) => { + socket.on('error', () => undefined) + socket.once('data', (data) => { + authorities.push(/^CONNECT (\S+) /.exec(data.toString())?.[1] ?? '') + const upstream = netConnect({ host: '127.0.0.1', port: originPort }, () => { + socket.write('HTTP/1.1 200 Connection established\r\n\r\n') + socket.pipe(upstream) + upstream.pipe(socket) + }) + upstream.on('error', () => socket.destroy()) + }) + } + + const handshake = (socket: Socket) => + new Promise((resolve, reject) => { + const secure = socket as tls.TLSSocket + secure.once('secureConnect', () => resolve(secure)) + secure.once('error', reject) + }) + + const open = (agent: PinnedProxyAgent, host: string) => + new Promise((resolve, reject) => { + agent.createConnection({ host, port: 443 }, (error, socket) => + error ? reject(error) : resolve(socket as Socket), + ) + }) + + before(function () { + try { + execFileSync('openssl', ['version'], { stdio: 'ignore' }) + } catch { + this.skip() // needs the openssl binary to make test certificates + } + dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nostream-pinned-proxy-')) + const origin = makeCertificate('good.example', 'DNS:good.example') + const proxy = makeCertificate('proxy', 'IP:127.0.0.1') + originCert = origin.cert + originKey = origin.key + proxyCert = proxy.cert + proxyKey = proxy.key + }) + + after(() => { + if (dir) { + fs.rmSync(dir, { recursive: true, force: true }) + } + }) + + beforeEach(() => { + dnsLookup = sandbox.stub(dns.promises, 'lookup').resolves([{ address: '93.184.216.34', family: 4 }] as any) + }) + + afterEach(async () => { + sandbox.restore() + await Promise.all(servers.splice(0).map((server) => new Promise((resolve) => server.close(resolve)))) + }) + + it('accepts the certificate of the host, through a tunnel to a pinned address', async () => { + const originPort = await startOrigin() + const authorities: string[] = [] + const proxyPort = await listen(createServer((socket) => relay(socket, originPort, authorities))) + const agent = new PinnedProxyAgent(`http://127.0.0.1:${proxyPort}`, 'NIP-05', { ca: originCert }) + + const socket = await handshake(await open(agent, 'good.example')) + + expect(socket.authorized).to.equal(true) + expect(authorities).to.deep.equal(['93.184.216.34:443']) + socket.destroy() + }) + + it('rejects a certificate that is not for the host, so servername is the host and not the pinned address', async () => { + const originPort = await startOrigin() + const proxyPort = await listen(createServer((socket) => relay(socket, originPort, []))) + const agent = new PinnedProxyAgent(`http://127.0.0.1:${proxyPort}`, 'NIP-05', { ca: originCert }) + + await expect(handshake(await open(agent, 'other.example'))).to.be.rejectedWith(/altnames|not in the cert/i) + }) + + it('rejects a certificate the agent does not trust', async () => { + const originPort = await startOrigin() + const proxyPort = await listen(createServer((socket) => relay(socket, originPort, []))) + const agent = new PinnedProxyAgent(`http://127.0.0.1:${proxyPort}`, 'NIP-05') + + await expect(handshake(await open(agent, 'good.example'))).to.be.rejectedWith(/self.signed|unable to verify/i) + }) + + it('reaches the proxy over TLS when the proxy URL is https', async () => { + const originPort = await startOrigin() + const authorities: string[] = [] + const proxyPort = await listen( + tls.createServer({ key: proxyKey, cert: proxyCert }, (socket) => + relay(socket as Socket, originPort, authorities), + ), + ) + const agent = new PinnedProxyAgent(`https://127.0.0.1:${proxyPort}`, 'NIP-05', { ca: [originCert, proxyCert] }) + + const socket = await handshake(await open(agent, 'good.example')) + + expect(socket.authorized).to.equal(true) + expect(authorities).to.deep.equal(['93.184.216.34:443']) + expect(dnsLookup).to.have.been.calledWith('good.example') + socket.destroy() + }) +}) diff --git a/test/unit/utils/settings-config.spec.ts b/test/unit/utils/settings-config.spec.ts index 39634a2b0..4ed98ee73 100644 --- a/test/unit/utils/settings-config.spec.ts +++ b/test/unit/utils/settings-config.spec.ts @@ -670,6 +670,27 @@ describe('settings-config', () => { } }) + describe('nip05.proxy', () => { + const withNip05 = (nip05: Record) => + validateSettings({ + info: { relay_url: 'wss://relay.example.com', name: 'Test Relay' }, + network: { maxPayloadSize: 1024 }, + nip05, + } as any).filter((issue) => issue.path.startsWith('nip05')) + + it('accepts disabled, pin and no value', () => { + expect(withNip05({ mode: 'disabled', proxy: 'disabled' })).to.deep.equal([]) + expect(withNip05({ mode: 'disabled', proxy: 'pin' })).to.deep.equal([]) + expect(withNip05({ mode: 'disabled' })).to.deep.equal([]) + }) + + it('rejects any other value', () => { + const issues = withNip05({ mode: 'disabled', proxy: 'env' }) + + expect(issues).to.deep.equal([{ path: 'nip05.proxy', message: 'proxy must be disabled or pin' }]) + }) + }) + describe('pubkey lists', () => { const hex = 'ab'.repeat(32) const withLimits = (event: Record) =>