Repository navigation
feat(nip05): verify through an egress proxy with a pinned address #1341
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Priyanshubhartistm
wants to merge
3
commits into
cameri:main
Choose a base branch
from
Priyanshubhartistm:feat/nip05-verify-through-proxy-pinned
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+804
−23
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
21ddb8e
feat(nip05): verify through an egress proxy with a pinned address
Priyanshubhartistm 8d75cd6
fix(nip05): bound the proxy tunnel setup and test it over real TLS
Priyanshubhartistm 07c78b4
fix(nip05): size the proxy reply head the same however it is split
Priyanshubhartistm File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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( | ||
| (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`) | ||
| }) | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.