From 031507223e6b9808048db0c7878123734feb05e0 Mon Sep 17 00:00:00 2001 From: Gerardo Sabetta Date: Wed, 2 Dec 2026 17:15:43 -0300 Subject: [PATCH] fix(oauth): vet resolved addresses and redirects for issuer requests (SEC-976) assertSafeHttpUrl only matched the URL's hostname text against a regex, so hostnames that resolve to loopback (localtest.me, *.127.0.0.1.nip.io) and IPv6 forms such as [::] and [::ffff:127.0.0.1] passed, and the underlying httpRequest followed redirects without re-checking them. A bad or MITM'd issuer could steer discovery or token introspection, which carries the caller's bearer token and the introspection client secret, at an internal host. - Classify IP literals with node:net BlockList: unspecified, loopback, link-local, RFC 1918, CGNAT, 0.0.0.0/8, multicast, documentation and other reserved ranges, IPv6 outside 2000::/3, ULA, 6to4/Teredo, and IPv4-mapped/compatible forms. Refuse localhost and *.localhost. - Send discovery and introspection through safeHttpRequest, whose per-connection lookup resolves the host once, refuses it if any answer is non-public, and connects only to the answers it vetted, so DNS rebinding cannot swap the address between check and use. - Re-check every redirect hop for discovery (max 5) and refuse redirects for introspection. Credentials are dropped on cross-origin hops. --- lib/http.mts | 42 ++- lib/oauth-discovery.mts | 11 +- lib/oauth.mts | 16 +- lib/outbound-address.mts | 204 ++++++++++++ lib/outbound-http.mts | 299 +++++++++++++++++ test/repo/unit/oauth-discovery.test.mts | 14 + test/repo/unit/oauth.test.mts | 28 ++ test/repo/unit/outbound-http.test.mts | 420 ++++++++++++++++++++++++ 8 files changed, 1006 insertions(+), 28 deletions(-) create mode 100644 lib/outbound-address.mts create mode 100644 lib/outbound-http.mts create mode 100644 test/repo/unit/outbound-http.test.mts diff --git a/lib/http.mts b/lib/http.mts index 15349a55..a5da0474 100644 --- a/lib/http.mts +++ b/lib/http.mts @@ -6,6 +6,7 @@ import { errorMessage } from '@socketsecurity/lib/errors/message' import { getTrustProxy } from './env.mts' import { logger } from './logger.mts' +import { classifyAddress, isLocalhostName } from './outbound-address.mts' import { buildMcpUserAgent } from './user-agent.mts' // Trust forwarded headers only when an operator has explicitly opted in by @@ -15,21 +16,21 @@ import { buildMcpUserAgent } from './user-agent.mts' // semantics stay consistent across the application. export const TRUST_PROXY: boolean = getTrustProxy() -// Loopback / link-local / private IPv4 ranges + IPv6 loopback/ULA that an -// SSRF probe would target. Compared against the resolved URL host. -const PRIVATE_HOST_RE = - /^(?:0\.0\.0\.0$|10\.|127\.|169\.254\.|172\.(?:1[6-9]|2\d|3[01])\.|192\.168\.|\[?::1\]?$|\[?fc00:|\[?fd|\[?fe80:)/iu - /** * SSRF + transport guard for operator/issuer-supplied URLs (the OAuth issuer + * the introspection endpoint advertised in its metadata). Rejects non-HTTP(S) - * schemes, hosts that resolve to loopback/private/link-local ranges, and - * cleartext `http:` on a public host — those URLs carry the caller's bearer - * token and this server's introspection client secret, so a malicious or - * MITM'd OAuth server must not be able to pivot into internal services - * (cloud metadata, redis, etc) or read those credentials off the wire. + * schemes, IP literals outside public unicast (loopback, private, link-local, + * CGNAT, multicast, reserved, IPv4-mapped forms of those), `localhost` and + * `*.localhost`, and cleartext `http:` on a public host — those URLs carry the + * caller's bearer token and this server's introspection client secret, so a + * malicious or MITM'd OAuth server must not be able to pivot into internal + * services (cloud metadata, redis, etc) or read those credentials off the wire. * `allowLocalhost` opens the gate for `localhost`/127.0.0.1, over either * scheme, in local-stack development only. + * + * This checks the URL only. A hostname can still resolve to an internal + * address, so send the request with `safeHttpRequest` (outbound-http.mts), + * which vets and pins the resolved address and re-checks every redirect. */ export function assertSafeHttpUrl( rawUrl: string, @@ -45,14 +46,23 @@ export function assertSafeHttpUrl( if (url.protocol !== 'http:' && url.protocol !== 'https:') { throw new Error(`${label} must be http(s): ${rawUrl}`) } - const host = url.hostname.toLowerCase() - const isLocal = host === '::1' || host === '127.0.0.1' || host === 'localhost' + const host = url.hostname.toLowerCase().replace(/\.$/u, '') + const address = host.replace(/^\[|\]$/gu, '') + const isLocal = + isLocalhostName(host) || address === '127.0.0.1' || address === '::1' if (isLocal && allowLocalhost) { return url } - if (PRIVATE_HOST_RE.test(host) || isLocal) { + // An IP literal is judged here once and for all; a hostname is judged again + // on every connection, against what it resolves to (see outbound-http.mts). + const reason = isLocalhostName(host) + ? 'localhost' + : isIP(address) + ? classifyAddress(address) + : undefined + if (reason) { throw new Error( - `${label} resolves to a private/loopback host and is refused: ${rawUrl}`, + `${label} resolves to a private/loopback host and is refused (${reason}): ${rawUrl}`, ) } if (url.protocol !== 'https:') { @@ -306,10 +316,10 @@ export function writeOAuthError( } function isLoopbackHost(hostname: string): boolean { - const host = hostname.toLowerCase().replace(/\.$/u, '') - if (host === 'localhost' || host.endsWith('.localhost')) { + if (isLocalhostName(hostname)) { return true } + const host = hostname.toLowerCase().replace(/\.$/u, '') const address = host.replace(/^\[|\]$/gu, '') if (isIP(address) === 4) { return Number.parseInt(address.split('.')[0]!, 10) === 127 diff --git a/lib/oauth-discovery.mts b/lib/oauth-discovery.mts index 700e5e88..cfb19eaf 100644 --- a/lib/oauth-discovery.mts +++ b/lib/oauth-discovery.mts @@ -6,10 +6,10 @@ */ import { errorMessage } from '@socketsecurity/lib/errors/message' -import { httpRequest } from '@socketsecurity/lib/http-request/request' import { assertSafeHttpUrl, parseJsonObject } from './http.mts' import { ALLOW_LOCAL_OAUTH, defaultOAuthConfig } from './oauth-config.mts' +import { safeHttpRequest } from './outbound-http.mts' import type { OAuthAuthorizationServerMetadata, OAuthConfig, @@ -64,11 +64,16 @@ export function buildOAuthWellKnownUrls(issuerUrl: URL): string[] { // Fetch and shape-check one candidate authorization-server metadata document. // Throws with the reason on any failure so the discovery probe can record it -// against the URL that produced it. +// against the URL that produced it. The request is SSRF-guarded end to end: +// the resolved address must be public, and each redirect is re-checked. export async function fetchOAuthMetadataDocument( url: string, ): Promise { - const response = await httpRequest(url) + const response = await safeHttpRequest(url, { + label: 'SOCKET_OAUTH_ISSUER metadata URL', + allowLocalhost: ALLOW_LOCAL_OAUTH, + maxRedirects: 5, + }) const responseText = response.text() if (!response.ok) { diff --git a/lib/oauth.mts b/lib/oauth.mts index c5585c03..339869f0 100644 --- a/lib/oauth.mts +++ b/lib/oauth.mts @@ -12,12 +12,10 @@ import { } from '@modelcontextprotocol/server' import type { AuthInfo } from '@modelcontextprotocol/server' import { errorMessage } from '@socketsecurity/lib/errors/message' -import { httpRequest } from '@socketsecurity/lib/http-request/request' import type { IncomingMessage, ServerResponse } from 'node:http' import { reportServerError } from './error-reporting.mts' import { - assertSafeHttpUrl, getRequestHeaderValue, parseJsonObject, writeJson, @@ -34,6 +32,7 @@ import { } from './oauth-config.mts' import type { OAuthConfig } from './oauth-config.mts' import { loadOAuthMetadata } from './oauth-discovery.mts' +import { safeHttpRequest } from './outbound-http.mts' import { getRequiredToolScopes } from './tool-scopes.mts' export { @@ -298,13 +297,12 @@ export async function verifyAccessToken( // The introspection endpoint comes from the issuer's metadata response — a // malicious/MITM'd issuer could point it at an internal host. SSRF-guard it - // before sending the bearer token there. - const introspectionUrl = assertSafeHttpUrl( - oauthMetadata.introspection_endpoint, - 'OAuth introspection_endpoint', - ALLOW_LOCAL_OAUTH, - ).href - const response = await httpRequest(introspectionUrl, { + // before sending the bearer token there: the URL, the address it resolves + // to (pinned for the connection), and no redirects, since a redirect would + // carry the token and the client secret somewhere unvetted. + const response = await safeHttpRequest(oauthMetadata.introspection_endpoint, { + label: 'OAuth introspection_endpoint', + allowLocalhost: ALLOW_LOCAL_OAUTH, method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', diff --git a/lib/outbound-address.mts b/lib/outbound-address.mts new file mode 100644 index 00000000..159c4d8e --- /dev/null +++ b/lib/outbound-address.mts @@ -0,0 +1,204 @@ +/** + * @file Classify IP addresses and hostnames for outbound requests that carry + * credentials (OAuth discovery and token introspection). An address is + * "public" only when it is globally routable unicast; loopback, private, + * link-local, CGNAT, multicast, documentation and other reserved ranges are + * refused so an issuer-supplied URL cannot reach internal services. + */ + +import { BlockList, isIP } from 'node:net' + +// IPv4 ranges that are not globally routable unicast (IANA special-purpose +// registry plus multicast and the reserved class E block). +const BLOCKED_IPV4_SUBNETS: ReadonlyArray = [ + ['0.0.0.0', 8, 'unspecified / "this network"'], + ['10.0.0.0', 8, 'private (RFC 1918)'], + ['100.64.0.0', 10, 'carrier-grade NAT (RFC 6598)'], + ['127.0.0.0', 8, 'loopback'], + ['169.254.0.0', 16, 'link-local'], + ['172.16.0.0', 12, 'private (RFC 1918)'], + ['192.0.0.0', 24, 'IETF protocol assignments'], + ['192.0.2.0', 24, 'documentation (TEST-NET-1)'], + ['192.88.99.0', 24, '6to4 relay anycast'], + ['192.168.0.0', 16, 'private (RFC 1918)'], + ['198.18.0.0', 15, 'benchmarking'], + ['198.51.100.0', 24, 'documentation (TEST-NET-2)'], + ['203.0.113.0', 24, 'documentation (TEST-NET-3)'], + ['224.0.0.0', 4, 'multicast'], + ['240.0.0.0', 4, 'reserved (includes broadcast)'], +] + +// IPv6 ranges inside global unicast (2000::/3) that still must not be +// reached. Everything outside 2000::/3 (::, ::1, fc00::/7, fe80::/10, +// ff00::/8, 64:ff9b::/96, 100::/64, ...) is refused before this list is +// consulted. +const BLOCKED_IPV6_SUBNETS: ReadonlyArray = [ + ['2001::', 23, 'IETF protocol assignments (includes Teredo)'], + ['2001:db8::', 32, 'documentation'], + ['2002::', 16, '6to4 (embeds an IPv4 address)'], + ['3fff::', 20, 'documentation'], +] + +const GLOBAL_UNICAST_IPV6 = new BlockList() +GLOBAL_UNICAST_IPV6.addSubnet('2000::', 3, 'ipv6') + +const blockedIpv4 = buildBlockList(BLOCKED_IPV4_SUBNETS, 'ipv4') +const blockedIpv6 = buildBlockList(BLOCKED_IPV6_SUBNETS, 'ipv6') + +/** + * Why an address is refused, or `undefined` when it is public. Accepts a bare + * IPv4 or IPv6 address (IPv6 may be bracketed, as in a URL hostname). + * IPv4-mapped (`::ffff:a.b.c.d`) and IPv4-compatible (`::a.b.c.d`) IPv6 + * addresses are unwrapped and judged by the IPv4 address they carry. + */ +export function classifyAddress(rawAddress: string): string | undefined { + const address = rawAddress.replace(/^\[|\]$/gu, '').toLowerCase() + const family = isIP(address) + if (family === 4) { + return classifyIpv4(address) + } + if (family !== 6) { + return 'not an IP address' + } + const hextets = expandIpv6(address) + if (!hextets) { + return 'not an IP address' + } + const embedded = embeddedIpv4(hextets) + if (embedded) { + const reason = classifyIpv4(embedded.address) + if (reason) { + return `${embedded.kind} ${reason}` + } + // An IPv4-compatible address is deprecated (RFC 4291 §2.5.5.1) and not + // routable as IPv6, so it is never a legitimate public target. + return embedded.kind === 'IPv4-mapped' + ? undefined + : 'IPv4-compatible IPv6 (deprecated)' + } + if (hextets.every(h => h === 0)) { + return 'unspecified' + } + if (!GLOBAL_UNICAST_IPV6.check(address, 'ipv6')) { + return describeNonGlobalIpv6(hextets) + } + return blockedReason(blockedIpv6, BLOCKED_IPV6_SUBNETS, address, 'ipv6') +} + +// True for a loopback address (127.0.0.0/8, ::1, or ::ffff:127.0.0.0/104). +// Used only to open the local-development gate for `localhost` names. +export function isLoopbackAddress(rawAddress: string): boolean { + const reason = classifyAddress(rawAddress) + return reason === 'loopback' || reason === 'IPv4-mapped loopback' +} + +// True for `localhost`, `*.localhost` (RFC 6761 §6.3 reserves the whole +// zone for loopback), with or without a trailing root dot. +export function isLocalhostName(hostname: string): boolean { + const host = hostname.toLowerCase().replace(/\.$/u, '') + return host === 'localhost' || host.endsWith('.localhost') +} + +function blockedReason( + list: BlockList, + subnets: ReadonlyArray, + address: string, + type: 'ipv4' | 'ipv6', +): string | undefined { + if (!list.check(address, type)) { + return undefined + } + for (let i = 0, { length } = subnets; i < length; i += 1) { + const { 0: network, 1: prefix, 2: reason } = subnets[i]! + const single = new BlockList() + single.addSubnet(network, prefix, type) + if (single.check(address, type)) { + return reason + } + } + return 'reserved' +} + +function buildBlockList( + subnets: ReadonlyArray, + type: 'ipv4' | 'ipv6', +): BlockList { + const list = new BlockList() + for (let i = 0, { length } = subnets; i < length; i += 1) { + const { 0: network, 1: prefix } = subnets[i]! + list.addSubnet(network, prefix, type) + } + return list +} + +function classifyIpv4(address: string): string | undefined { + return blockedReason(blockedIpv4, BLOCKED_IPV4_SUBNETS, address, 'ipv4') +} + +function describeNonGlobalIpv6(hextets: number[]): string { + const first = hextets[0]! + if (hextets.slice(0, 7).every(h => h === 0) && hextets[7] === 1) { + return 'loopback' + } + if ((first & 0xfe00) === 0xfc00) { + return 'unique local (fc00::/7)' + } + if ((first & 0xffc0) === 0xfe80) { + return 'link-local' + } + if ((first & 0xff00) === 0xff00) { + return 'multicast' + } + return 'not global unicast' +} + +// The IPv4 address carried by an IPv4-mapped (::ffff:0:0/96) or +// IPv4-compatible (::/96, excluding :: and ::1) IPv6 address. +function embeddedIpv4( + hextets: number[], +): { address: string; kind: 'IPv4-mapped' | 'IPv4-compatible' } | undefined { + const high = hextets.slice(0, 5) + if (!high.every(h => h === 0)) { + return undefined + } + const marker = hextets[5]! + const hi = hextets[6]! + const lo = hextets[7]! + const address = `${hi >> 8}.${hi & 0xff}.${lo >> 8}.${lo & 0xff}` + if (marker === 0xffff) { + return { address, kind: 'IPv4-mapped' } + } + // ::/128 and ::1/128 sit inside ::/96 but are their own special addresses. + if (marker === 0 && hi !== 0) { + return { address, kind: 'IPv4-compatible' } + } + return undefined +} + +// Expand a valid IPv6 address (already checked with isIP) into its eight +// 16-bit groups, folding a trailing dotted-quad into the last two. +function expandIpv6(address: string): number[] | undefined { + let text = address.split('%', 1)[0]! + const dotted = /(\d+)\.(\d+)\.(\d+)\.(\d+)$/u.exec(text) + if (dotted) { + const octets = dotted.slice(1, 5).map(Number) + text = + text.slice(0, dotted.index) + + `${((octets[0]! << 8) | octets[1]!).toString(16)}:${((octets[2]! << 8) | octets[3]!).toString(16)}` + } + const halves = text.split('::') + const head = halves[0] ? halves[0].split(':') : [] + const tail = halves.length > 1 && halves[1] ? halves[1].split(':') : [] + const missing = 8 - head.length - tail.length + if (halves.length > 2 || missing < 0) { + return undefined + } + const groups = + halves.length === 2 + ? [...head, ...Array.from({ length: missing }, () => '0'), ...tail] + : head + if (groups.length !== 8) { + return undefined + } + return groups.map(g => Number.parseInt(g, 16)) +} diff --git a/lib/outbound-http.mts b/lib/outbound-http.mts new file mode 100644 index 00000000..16602b24 --- /dev/null +++ b/lib/outbound-http.mts @@ -0,0 +1,299 @@ +/** + * @file SSRF-safe outbound HTTP for URLs an operator or an OAuth issuer + * supplies (discovery and token introspection). `assertSafeHttpUrl` vets the + * URL text; this module vets where it actually connects. Every connection + * resolves the hostname once, refuses it if ANY answer is not a public + * address, and connects only to the answers it just vetted, so DNS + * rebinding cannot swap in an internal address between check and use. + * Redirects are re-checked hop by hop, or refused. + */ + +import dns from 'node:dns' +import http from 'node:http' +import https from 'node:https' +import type { LookupAddress, LookupOptions } from 'node:dns' +import type { IncomingHttpHeaders } from 'node:http' + +import { assertSafeHttpUrl } from './http.mts' +import { + classifyAddress, + isLocalhostName, + isLoopbackAddress, +} from './outbound-address.mts' +import { buildMcpUserAgent } from './user-agent.mts' + +const DEFAULT_TIMEOUT_MS = 30_000 +const DEFAULT_MAX_RESPONSE_BYTES = 1024 * 1024 +const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]) + +// Resolve a hostname to every address it answers with. Injectable so tests +// never touch real DNS. +export type HostResolver = (hostname: string) => Promise + +type LookupCallback = ( + error: NodeJS.ErrnoException | null, + address: string | LookupAddress[], + family?: number | undefined, +) => void + +export interface SafeHttpRequestOptions { + // Names the setting the URL came from, for error messages. + label: string + // Local-stack development only: allow `localhost` / 127.0.0.1 / ::1 over + // either scheme (see assertSafeHttpUrl). + allowLocalhost?: boolean | undefined + body?: string | undefined + headers?: Record | undefined + // Redirects to follow, each re-checked like the first URL. 0 (the default) + // refuses any redirect. + maxRedirects?: number | undefined + maxResponseBytes?: number | undefined + method?: string | undefined + resolver?: HostResolver | undefined + timeoutMs?: number | undefined +} + +export interface SafeHttpResponse { + headers: IncomingHttpHeaders + ok: boolean + status: number + // The URL that produced this response, after any redirects. + url: string + text(): string +} + +export const defaultHostResolver: HostResolver = hostname => + dns.promises.lookup(hostname, { all: true }) + +/** + * A `net` lookup function that resolves through `resolver`, refuses the host + * when any answer is not a public address, and hands the socket only the + * answers it vetted. `allowLoopback` (local development) additionally accepts + * loopback answers, and only those. + */ +export function createSafeLookup(config: { + label: string + resolver?: HostResolver | undefined + allowLoopback?: boolean | undefined +}) { + const { allowLoopback = false, label } = config + const resolver = config.resolver ?? defaultHostResolver + return function safeLookup( + hostname: string, + options: LookupOptions, + callback: LookupCallback, + ): void { + resolvePublicAddresses(hostname, label, resolver, allowLoopback).then( + addresses => { + const usable = options.family + ? addresses.filter(a => a.family === options.family) + : addresses + if (usable.length === 0) { + const error: NodeJS.ErrnoException = new Error( + `${label} host ${hostname} has no IPv${options.family} address`, + ) + error.code = 'ENOTFOUND' + callback(error, '') + } else if (options.all) { + callback(null, usable) + } else { + callback(null, usable[0]!.address, usable[0]!.family) + } + }, + (error: NodeJS.ErrnoException) => callback(error, ''), + ) + } +} + +/** + * Resolve `hostname` and return its answers only if every one of them is a + * public address. One private answer refuses the whole host: a resolver may + * hand the answers to the socket in any order. + */ +export async function resolvePublicAddresses( + hostname: string, + label: string, + resolver: HostResolver = defaultHostResolver, + allowLoopback = false, +): Promise { + const answers = await resolver(hostname) + if (answers.length === 0) { + throw new Error(`${label} host ${hostname} did not resolve to any address`) + } + for (let i = 0, { length } = answers; i < length; i += 1) { + const { address } = answers[i]! + if (allowLoopback && isLoopbackAddress(address)) { + continue + } + const reason = classifyAddress(address) + if (reason) { + throw new Error( + `${label} resolves to a private/loopback host and is refused (${reason}): ${hostname} -> ${address}`, + ) + } + } + return answers +} + +/** + * Send one request to an operator/issuer-supplied URL with the SSRF guard + * applied at every step: the URL is vetted, the connection is pinned to vetted + * addresses, and each redirect target goes through the same checks (or is + * refused when `maxRedirects` is 0). Credentials in `headers` are dropped on a + * cross-origin redirect. + */ +export async function safeHttpRequest( + rawUrl: string, + options: SafeHttpRequestOptions, +): Promise { + const { allowLocalhost = false, label, maxRedirects = 0, resolver } = options + let method = (options.method ?? 'GET').toUpperCase() + let body = options.body + let headers: Record = { ...options.headers } + let url = assertSafeHttpUrl(rawUrl, label, allowLocalhost) + + for (let hop = 0; ; hop += 1) { + const response = await requestOnce(url, { + allowLocalhost, + body, + headers, + label, + maxResponseBytes: options.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES, + method, + resolver, + timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS, + }) + const location = response.headers.location + if (!REDIRECT_STATUSES.has(response.status) || !location) { + return response + } + if (hop >= maxRedirects) { + throw new Error( + maxRedirects === 0 + ? `${label} answered HTTP ${response.status} redirecting to ${location}; redirects are not followed for this request. Fix: point it at the final URL.` + : `${label} redirected more than ${maxRedirects} times; last hop pointed at ${location}`, + ) + } + const next = assertSafeHttpUrl( + new URL(location, url).href, + `${label} redirect target`, + allowLocalhost, + ) + if (next.origin !== url.origin) { + headers = withoutCredentials(headers) + } + if ( + response.status === 303 || + ((response.status === 301 || response.status === 302) && + method === 'POST') + ) { + method = 'GET' + body = undefined + headers = withoutBodyHeaders(headers) + } + url = next + } +} + +function requestOnce( + url: URL, + config: { + allowLocalhost: boolean + body: string | undefined + headers: Record + label: string + maxResponseBytes: number + method: string + resolver: HostResolver | undefined + timeoutMs: number + }, +): Promise { + const headers: Record = { + 'user-agent': buildMcpUserAgent(), + ...config.headers, + } + if (config.body !== undefined) { + headers['content-length'] = String(Buffer.byteLength(config.body)) + } + const lookup = createSafeLookup({ + label: config.label, + resolver: config.resolver, + allowLoopback: config.allowLocalhost && isLocalhostName(url.hostname), + }) + const transport = url.protocol === 'https:' ? https : http + + return new Promise((resolve, reject) => { + const req = transport.request( + url, + { + method: config.method, + headers, + // A fresh socket per request: a pooled socket would skip the lookup. + agent: false, + lookup, + timeout: config.timeoutMs, + }, + res => { + const chunks: Buffer[] = [] + let received = 0 + res.on('data', (chunk: Buffer) => { + received += chunk.length + if (received > config.maxResponseBytes) { + req.destroy( + new Error( + `${config.label} response exceeded ${config.maxResponseBytes} bytes`, + ), + ) + return + } + chunks.push(chunk) + }) + res.on('error', reject) + res.on('end', () => { + const status = res.statusCode ?? 0 + const text = Buffer.concat(chunks).toString('utf8') + resolve({ + headers: res.headers, + ok: status >= 200 && status < 300, + status, + url: url.href, + text: () => text, + }) + }) + }, + ) + req.on('timeout', () => { + req.destroy( + new Error(`${config.label} timed out after ${config.timeoutMs}ms`), + ) + }) + req.on('error', reject) + req.end(config.body) + }) +} + +function withoutBodyHeaders( + headers: Record, +): Record { + const kept: Record = {} + for (const key of Object.keys(headers)) { + const lower = key.toLowerCase() + if (lower !== 'content-type' && lower !== 'content-length') { + kept[key] = headers[key]! + } + } + return kept +} + +function withoutCredentials( + headers: Record, +): Record { + const kept: Record = {} + for (const key of Object.keys(headers)) { + const lower = key.toLowerCase() + if (lower !== 'authorization' && lower !== 'cookie') { + kept[key] = headers[key]! + } + } + return kept +} diff --git a/test/repo/unit/oauth-discovery.test.mts b/test/repo/unit/oauth-discovery.test.mts index 25741a5a..c35f406b 100644 --- a/test/repo/unit/oauth-discovery.test.mts +++ b/test/repo/unit/oauth-discovery.test.mts @@ -169,3 +169,17 @@ test('loadOAuthMetadata probes a path-bearing issuer at the path-inserted URL', const metadata = await loadOAuthMetadata(makeConfig({ issuer: tenantIssuer })) expect(metadata?.issuer).toBe(tenantIssuer) }) + +test('loadOAuthMetadata refuses a discovery redirect to an internal address', async () => { + // SEC-976: the probe used to follow redirects unchecked. Each hop is now + // re-vetted, so a 302 to the cloud metadata service fails the probe instead. + nock(issuerBaseUrl) + .get(oauthWellKnownPath) + .reply(302, '', { location: 'http://169.254.169.254/latest/meta-data/' }) + nock(issuerBaseUrl) + .get(openidConfigurationPath) + .reply(302, '', { location: 'https://[::ffff:127.0.0.1]/' }) + await expect(loadOAuthMetadata(makeConfig())).rejects.toThrow( + /redirect target resolves to a private\/loopback host and is refused \(link-local\).*redirect target resolves to a private\/loopback host and is refused \(IPv4-mapped loopback\)/s, + ) +}) diff --git a/test/repo/unit/oauth.test.mts b/test/repo/unit/oauth.test.mts index c70bbd37..7cbffde6 100644 --- a/test/repo/unit/oauth.test.mts +++ b/test/repo/unit/oauth.test.mts @@ -617,3 +617,31 @@ test('authenticateRequest 500s when introspection discovery fails', async () => const body = JSON.parse(captured.getBody()) as { error?: string | undefined } expect(body.error).toBe('server_error') }) + +test('verifyAccessToken does not follow an introspection redirect', async () => { + // SEC-976: a redirect would carry the bearer token and the introspection + // client secret to a URL nobody vetted, so it is refused outright. + mockDiscovery() + nock(issuerBaseUrl) + .post('/introspect') + .reply(307, '', { location: 'https://issuer.example.test/elsewhere' }) + await expect( + verifyAccessToken('any-token', resourceIdentifier, makeConfig()), + ).rejects.toThrow(/redirects are not followed for this request/) +}) + +test('verifyAccessToken refuses an introspection_endpoint on an internal literal', async () => { + nock(issuerBaseUrl) + .get('/.well-known/oauth-authorization-server') + .reply(200, { + issuer: issuerBaseUrl, + authorization_endpoint: `${issuerBaseUrl}/authorize`, + token_endpoint: `${issuerBaseUrl}/token`, + introspection_endpoint: 'https://[::]/introspect', + }) + await expect( + verifyAccessToken('any-token', resourceIdentifier, makeConfig()), + ).rejects.toThrow( + /introspection_endpoint resolves to a private\/loopback host and is refused \(unspecified\)/, + ) +}) diff --git a/test/repo/unit/outbound-http.test.mts b/test/repo/unit/outbound-http.test.mts new file mode 100644 index 00000000..26acb8f3 --- /dev/null +++ b/test/repo/unit/outbound-http.test.mts @@ -0,0 +1,420 @@ +/** + * @file The SSRF guard for issuer-supplied URLs: address classification, the + * URL check, the resolve-and-pin lookup, and redirect handling. Every + * resolver is a stub, so no test touches real DNS; the only sockets opened + * are to a local server this file starts, and the refusal tests assert that + * server never sees a connection. + */ + +import { createServer } from 'node:http' +import type { Server } from 'node:http' +import type { AddressInfo } from 'node:net' + +import { afterEach, describe, expect, test } from 'vitest' + +import { assertSafeHttpUrl } from '../../../lib/http.mts' +import { + classifyAddress, + isLocalhostName, +} from '../../../lib/outbound-address.mts' +import { + createSafeLookup, + resolvePublicAddresses, + safeHttpRequest, +} from '../../../lib/outbound-http.mts' +import type { HostResolver } from '../../../lib/outbound-http.mts' + +// A resolver backed by a fixed table; counts calls per hostname. +function stubResolver(table: Record): HostResolver & { + calls: string[] +} { + const calls: string[] = [] + const resolver = async (hostname: string) => { + calls.push(hostname) + const answers = table[hostname] + if (!answers) { + throw Object.assign(new Error(`stub: no answer for ${hostname}`), { + code: 'ENOTFOUND', + }) + } + return answers.map(address => ({ + address, + family: address.includes(':') ? 6 : 4, + })) + } + return Object.assign(resolver, { calls }) +} + +type Handler = Parameters[1] + +const servers: Server[] = [] + +// Start a local HTTP server and count the TCP connections it accepts. +async function startServer( + handler: NonNullable, +): Promise<{ port: number; connections: () => number }> { + const server = createServer(handler) + let connections = 0 + server.on('connection', () => { + connections += 1 + }) + servers.push(server) + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)) + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- listen(0, host) always yields an AddressInfo, never a pipe path. + const { port } = server.address() as AddressInfo + return { port, connections: () => connections } +} + +afterEach(async () => { + await Promise.all( + servers + .splice(0) + .map(server => new Promise(resolve => server.close(resolve))), + ) +}) + +describe('classifyAddress', () => { + test.each([ + ['127.0.0.1', 'loopback'], + ['127.255.0.9', 'loopback'], + ['169.254.169.254', 'link-local'], + ['0.0.0.0', 'unspecified'], + ['0.1.2.3', 'unspecified'], + ['100.64.0.1', 'carrier-grade NAT'], + ['100.127.255.254', 'carrier-grade NAT'], + ['10.0.0.5', 'private'], + ['172.16.0.1', 'private'], + ['172.31.255.255', 'private'], + ['192.168.1.1', 'private'], + ['192.0.2.10', 'documentation'], + ['224.0.0.1', 'multicast'], + ['255.255.255.255', 'reserved'], + ['::', 'unspecified'], + ['[::]', 'unspecified'], + ['::1', 'loopback'], + ['::ffff:127.0.0.1', 'IPv4-mapped loopback'], + ['::ffff:7f00:1', 'IPv4-mapped loopback'], + ['::ffff:169.254.169.254', 'IPv4-mapped link-local'], + ['::127.0.0.1', 'IPv4-compatible loopback'], + ['::1.1.1.1', 'IPv4-compatible IPv6'], + ['fc00::1', 'unique local'], + ['fd12:3456::1', 'unique local'], + ['fe80::1', 'link-local'], + ['ff02::1', 'multicast'], + ['64:ff9b::a9fe:a9fe', 'not global unicast'], + ['2001:db8::1', 'documentation'], + ['2001::1', 'IETF protocol assignments'], + ['2002:7f00:1::', '6to4'], + ['not-an-ip', 'not an IP address'], + ])('refuses %s (%s)', (address, reason) => { + expect(classifyAddress(address)).toContain(reason) + }) + + test.each([ + '1.1.1.1', + '8.8.8.8', + '100.63.255.255', + '100.128.0.1', + '172.32.0.1', + '::ffff:1.1.1.1', + '2606:4700:4700::1111', + ])('accepts public %s', address => { + expect(classifyAddress(address)).toBeUndefined() + }) +}) + +describe('isLocalhostName', () => { + test.each(['localhost', 'LOCALHOST', 'localhost.', 'foo.localhost'])( + '%s is localhost', + host => { + expect(isLocalhostName(host)).toBe(true) + }, + ) + + test.each(['localhost.example.com', 'notlocalhost', 'example.com'])( + '%s is not localhost', + host => { + expect(isLocalhostName(host)).toBe(false) + }, + ) +}) + +describe('assertSafeHttpUrl on literal hosts', () => { + test.each([ + 'https://127.0.0.1/x', + 'https://169.254.169.254/latest/meta-data', + 'https://0.1.2.3/x', + 'https://100.64.0.1/x', + 'https://10.1.2.3/x', + 'https://172.20.0.1/x', + 'https://192.168.0.10/x', + 'https://[::]/x', + 'https://[::1]/x', + 'https://[::ffff:127.0.0.1]/x', + 'https://[::ffff:169.254.169.254]/x', + 'https://[fd00::1]/x', + 'https://[fe80::1]/x', + // WHATWG URL folds these IPv4 spellings to 127.0.0.1. + 'https://2130706433/x', + 'https://0x7f.1/x', + 'https://localhost/x', + 'https://localhost./x', + 'https://foo.localhost/x', + ])('refuses %s', raw => { + expect(() => assertSafeHttpUrl(raw, 'issuer')).toThrow( + /private\/loopback host and is refused/, + ) + }) + + test('accepts a public https URL and a public IP literal', () => { + expect(assertSafeHttpUrl('https://issuer.example.com/', 'x').hostname).toBe( + 'issuer.example.com', + ) + expect(assertSafeHttpUrl('https://1.1.1.1/', 'x').hostname).toBe('1.1.1.1') + }) + + test('allowLocalhost still refuses non-loopback private literals', () => { + expect(() => + assertSafeHttpUrl('http://169.254.169.254/', 'x', true), + ).toThrow(/link-local/) + expect(() => assertSafeHttpUrl('http://[::]/', 'x', true)).toThrow( + /unspecified/, + ) + }) +}) + +describe('resolvePublicAddresses', () => { + const resolver = stubResolver({ + 'localtest.me': ['127.0.0.1'], + 'app.127.0.0.1.nip.io': ['127.0.0.1'], + 'metadata.example.test': ['169.254.169.254'], + 'mixed.example.test': ['1.1.1.1', '10.0.0.7'], + 'mixed6.example.test': ['2606:4700:4700::1111', 'fd00::5'], + 'mapped.example.test': ['::ffff:127.0.0.1'], + 'public.example.test': ['1.1.1.1', '2606:4700:4700::1111'], + localhost: ['127.0.0.1', '::1'], + 'evil.localhost': ['10.0.0.9'], + }) + + test.each([ + ['localtest.me', /loopback.*127\.0\.0\.1/], + ['app.127.0.0.1.nip.io', /loopback/], + ['metadata.example.test', /link-local/], + ['mixed.example.test', /private.*10\.0\.0\.7/], + ['mixed6.example.test', /unique local.*fd00::5/], + ['mapped.example.test', /IPv4-mapped loopback/], + ])('refuses %s', async (hostname, message) => { + await expect( + resolvePublicAddresses(hostname, 'issuer', resolver), + ).rejects.toThrow(message) + }) + + test('accepts a host whose every answer is public', async () => { + await expect( + resolvePublicAddresses('public.example.test', 'issuer', resolver), + ).resolves.toEqual([ + { address: '1.1.1.1', family: 4 }, + { address: '2606:4700:4700::1111', family: 6 }, + ]) + }) + + test('allowLoopback admits loopback answers and nothing else', async () => { + await expect( + resolvePublicAddresses('localhost', 'issuer', resolver, true), + ).resolves.toHaveLength(2) + await expect( + resolvePublicAddresses('evil.localhost', 'issuer', resolver, true), + ).rejects.toThrow(/private/) + }) + + test('refuses a host with no answers', async () => { + await expect( + resolvePublicAddresses('empty.example.test', 'issuer', async () => []), + ).rejects.toThrow(/did not resolve to any address/) + }) +}) + +describe('createSafeLookup', () => { + const resolver = stubResolver({ + 'public.example.test': ['1.1.1.1', '2606:4700:4700::1111'], + 'localtest.me': ['127.0.0.1'], + }) + const lookup = createSafeLookup({ label: 'issuer', resolver }) + + function run( + hostname: string, + options: { all?: boolean; family?: number | undefined }, + ) { + return new Promise<{ + error: Error | null + address: unknown + family?: number | undefined + }>(resolve => { + lookup(hostname, options, (error, address, family) => + resolve({ error, address, family }), + ) + }) + } + + test('hands back the vetted answers in both callback shapes', async () => { + expect(await run('public.example.test', { all: true })).toMatchObject({ + error: null, + address: [ + { address: '1.1.1.1', family: 4 }, + { address: '2606:4700:4700::1111', family: 6 }, + ], + }) + expect(await run('public.example.test', { family: 6 })).toMatchObject({ + error: null, + address: '2606:4700:4700::1111', + family: 6, + }) + }) + + test('fails the connection for a host that resolves to loopback', async () => { + const { error } = await run('localtest.me', { all: true }) + expect(error?.message).toMatch(/private\/loopback.*localtest\.me -> 127/) + }) +}) + +describe('safeHttpRequest', () => { + test('never connects to a hostname that resolves to loopback', async () => { + const server = await startServer((_req, res) => res.end('reached')) + const resolver = stubResolver({ 'localtest.me': ['127.0.0.1'] }) + await expect( + safeHttpRequest(`https://localtest.me:${server.port}/introspect`, { + label: 'OAuth introspection_endpoint', + method: 'POST', + body: 'token=secret', + resolver, + }), + ).rejects.toThrow(/private\/loopback host and is refused \(loopback\)/) + expect(resolver.calls).toEqual(['localtest.me']) + expect(server.connections()).toBe(0) + }) + + test('never connects when one answer of several is private', async () => { + const server = await startServer((_req, res) => res.end('reached')) + const resolver = stubResolver({ + 'mixed.example.test': ['1.1.1.1', '127.0.0.1'], + }) + await expect( + safeHttpRequest(`https://mixed.example.test:${server.port}/`, { + label: 'issuer', + resolver, + }), + ).rejects.toThrow(/refused \(loopback\)/) + expect(server.connections()).toBe(0) + }) + + test('connects to the address the resolver vetted (local dev gate)', async () => { + const server = await startServer((req, res) => { + res.setHeader('content-type', 'application/json') + res.end(JSON.stringify({ method: req.method, path: req.url })) + }) + const resolver = stubResolver({ localhost: ['127.0.0.1'] }) + const response = await safeHttpRequest( + `http://localhost:${server.port}/meta`, + { label: 'issuer', allowLocalhost: true, resolver }, + ) + expect(response.ok).toBe(true) + expect(JSON.parse(response.text())).toEqual({ + method: 'GET', + path: '/meta', + }) + expect(resolver.calls).toEqual(['localhost']) + }) + + test('the local dev gate does not admit localhost resolving elsewhere', async () => { + const resolver = stubResolver({ localhost: ['10.0.0.1'] }) + await expect( + safeHttpRequest('http://localhost:9/', { + label: 'issuer', + allowLocalhost: true, + resolver, + }), + ).rejects.toThrow(/refused \(private/) + }) + + test('refuses a redirect to a link-local literal without following it', async () => { + const server = await startServer((_req, res) => { + res.writeHead(302, { + location: 'http://169.254.169.254/latest/meta-data/', + }) + res.end() + }) + await expect( + safeHttpRequest(`http://localhost:${server.port}/.well-known/x`, { + label: 'issuer', + allowLocalhost: true, + maxRedirects: 5, + resolver: stubResolver({ localhost: ['127.0.0.1'] }), + }), + ).rejects.toThrow(/redirect target resolves to a private\/loopback host/) + }) + + test('refuses a redirect to a hostname that resolves internally', async () => { + const internal = await startServer((_req, res) => res.end('internal')) + const front = await startServer((_req, res) => { + res.writeHead(307, { + location: `https://internal.example.test:${internal.port}/admin`, + }) + res.end() + }) + const resolver = stubResolver({ + localhost: ['127.0.0.1'], + 'internal.example.test': ['10.20.30.40'], + }) + await expect( + safeHttpRequest(`http://localhost:${front.port}/`, { + label: 'issuer', + allowLocalhost: true, + maxRedirects: 5, + resolver, + }), + ).rejects.toThrow(/refused \(private \(RFC 1918\)\).*10\.20\.30\.40/) + expect(resolver.calls).toEqual(['localhost', 'internal.example.test']) + expect(internal.connections()).toBe(0) + }) + + test('refuses any redirect when maxRedirects is 0', async () => { + const server = await startServer((_req, res) => { + res.writeHead(307, { location: '/elsewhere' }) + res.end() + }) + await expect( + safeHttpRequest(`http://localhost:${server.port}/introspect`, { + label: 'OAuth introspection_endpoint', + allowLocalhost: true, + method: 'POST', + body: 'token=t', + resolver: stubResolver({ localhost: ['127.0.0.1'] }), + }), + ).rejects.toThrow(/redirects are not followed for this request/) + }) + + test('follows a vetted redirect and drops credentials across origins', async () => { + const seen: Array = [] + const target = await startServer((req, res) => { + seen.push(req.headers.authorization) + res.end('{}') + }) + const front = await startServer((req, res) => { + seen.push(req.headers.authorization) + res.writeHead(302, { + location: `http://localhost:${target.port}/final`, + }) + res.end() + }) + const response = await safeHttpRequest(`http://localhost:${front.port}/`, { + label: 'issuer', + allowLocalhost: true, + maxRedirects: 1, + headers: { authorization: 'Basic c2VjcmV0' }, + resolver: stubResolver({ localhost: ['127.0.0.1'] }), + }) + expect(response.ok).toBe(true) + expect(response.url).toBe(`http://localhost:${target.port}/final`) + expect(seen).toEqual(['Basic c2VjcmV0', undefined]) + }) +})