Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 26 additions & 16 deletions lib/http.mts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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,
Expand All @@ -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:') {
Expand Down Expand Up @@ -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
Expand Down
11 changes: 8 additions & 3 deletions lib/oauth-discovery.mts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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<OAuthAuthorizationServerMetadata> {
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) {
Expand Down
16 changes: 7 additions & 9 deletions lib/oauth.mts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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 {
Expand Down Expand Up @@ -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',
Expand Down
204 changes: 204 additions & 0 deletions lib/outbound-address.mts
Original file line number Diff line number Diff line change
@@ -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<readonly [string, number, string]> = [
['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<readonly [string, number, string]> = [
['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<readonly [string, number, string]>,
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<readonly [string, number, string]>,
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))
}
Loading
Loading