Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

fix(guardrails): ssrf-guarded remote hook dial (replaces remote skip)

Andy Paviab057c5423a1b
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index 20030b14a..b27e10992 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.250",
+ "version": "0.1.251",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.250",
+ "version": "0.1.251",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@anthropic-ai/sdk": "^0.32.0",
diff --git a/mcp-host/package.json b/mcp-host/package.json
index 61cb5a33f..85149ea3b 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.250",
+ "version": "0.1.251",
"description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude",
"main": "dist/main.js",
"engines": {
diff --git a/mcp-host/src/__tests__/guardrailHookResolver.test.ts b/mcp-host/src/__tests__/guardrailHookResolver.test.ts
index c258dce34..0d067914a 100644
--- a/mcp-host/src/__tests__/guardrailHookResolver.test.ts
+++ b/mcp-host/src/__tests__/guardrailHookResolver.test.ts
@@ -78,11 +78,11 @@ describe('resolveGuardrailHookDescriptors', () => {
expect(out[0].lifecyclePoints).toEqual(['pre_call'])
})
- it('does NOT resolve a remote-target hook (disabled pending SSRF-guarded transport, §8.3)', async () => {
+ it('resolves a remote-target hook to its baseUrl and marks it external (SSRF-guarded)', async () => {
const cr: LlmHookCR = {
metadata: { name: 'r' },
spec: {
- target: { remote: { baseUrl: 'https://hooks.example.com' } },
+ target: { remote: { baseUrl: 'https://guardrails.aporia.com' } },
lifecyclePoints: ['preCall'],
capabilities: ['may_deny'],
},
@@ -91,8 +91,22 @@ describe('resolveGuardrailHookDescriptors', () => {
guardrails({ preCall: [{ id: 'r' }] }),
deps({ r: cr })
)
- // Fail-closed: the external dial is not enabled until the SSRF guard lands.
- expect(out).toEqual([])
+ expect(out[0].endpoint).toBe('https://guardrails.aporia.com')
+ expect(out[0].external).toBe(true)
+ })
+
+ it('marks in-cluster (image/service) targets as NOT external', async () => {
+ const svc: LlmHookCR = {
+ spec: {
+ target: { service: { name: 's', namespace: NS, port: 80 } },
+ lifecyclePoints: ['moderate'],
+ },
+ }
+ const out = await resolveGuardrailHookDescriptors(
+ guardrails({ moderate: [{ id: 's' }] }),
+ deps({ s: svc })
+ )
+ expect(out[0].external).toBeFalsy()
})
it('skips a dangling reference (CR not found)', async () => {
diff --git a/mcp-host/src/core/guardrails/hooks/__tests__/hookFetcher.test.ts b/mcp-host/src/core/guardrails/hooks/__tests__/hookFetcher.test.ts
index 277b76aed..71d5c7406 100644
--- a/mcp-host/src/core/guardrails/hooks/__tests__/hookFetcher.test.ts
+++ b/mcp-host/src/core/guardrails/hooks/__tests__/hookFetcher.test.ts
@@ -1,103 +1,66 @@
/**
- * HookFetcher transport tests (spec §8.1 wire contract): URL building, auth
- * header, and outcome classification (5xx / timeout / malformed / oversized →
- * unavailable; 2xx/4xx returned for the mapping).
+ * Hook fetcher transport routing (spec §8.1/§8.3): in-cluster targets use the
+ * plain transport; `external` (remote) targets use the SSRF-guarded transport.
*/
import { describe, expect, it, vi } from 'vitest'
-import { type FetchLike, buildHookUrl, createHookFetcher } from '../hookFetcher'
+import { type FetchLike, createHookFetcher } from '../hookFetcher'
import type { HookDescriptor } from '../types'
-const desc: HookDescriptor = {
+const base: HookDescriptor = {
id: 'h',
- endpoint: 'http://hook-server.llm-hooks.svc/',
- path: '/pii-redact',
- lifecyclePoints: ['moderate'],
+ endpoint: 'http://svc.llm-hooks.svc.cluster.local:8080',
+ path: '/',
+ lifecyclePoints: ['pre_call'],
capabilities: [],
failMode: 'closed',
order: 100,
}
-const okResponse = (
- status: number,
- text: string
-): { status: number; text: () => Promise<string> } => ({
- status,
- text: async () => text,
-})
-
-describe('buildHookUrl', () => {
- it('normalizes slashes → {endpoint}{path}/v1/{point}', () => {
- expect(buildHookUrl('http://svc/', '/pii-redact', 'moderate')).toBe(
- 'http://svc/pii-redact/v1/moderate'
- )
- expect(buildHookUrl('http://svc', '/', 'pre_call')).toBe('http://svc/v1/pre_call')
- expect(buildHookUrl('http://svc', '', 'on_error')).toBe('http://svc/v1/on_error')
- })
-})
-
-describe('createHookFetcher', () => {
- it('POSTs with bearer auth to the built URL and parses JSON', async () => {
- const fetchImpl = vi.fn<FetchLike>(async () => okResponse(200, '{"action":"continue"}'))
- const fetcher = createHookFetcher({ getAuthToken: () => 'tok', fetchImpl })
- const r = await fetcher({ point: 'moderate', descriptor: desc, body: { a: 1 } })
- expect(r).toEqual({ status: 200, body: { action: 'continue' }, unavailable: false })
- const [url, init] = fetchImpl.mock.calls[0]
- expect(url).toBe('http://hook-server.llm-hooks.svc/pii-redact/v1/moderate')
- expect(init.headers.Authorization).toBe('Bearer tok')
- expect(init.method).toBe('POST')
- })
-
- it('5xx → unavailable', async () => {
- const fetcher = createHookFetcher({
- getAuthToken: () => 't',
- fetchImpl: async () => okResponse(503, ''),
- })
- expect((await fetcher({ point: 'moderate', descriptor: desc, body: {} })).unavailable).toBe(
- true
- )
- })
-
- it('4xx is NOT unavailable (mapping classifies it)', async () => {
- const fetcher = createHookFetcher({
- getAuthToken: () => 't',
- fetchImpl: async () => okResponse(422, '{"code":"blocked"}'),
- })
- const r = await fetcher({ point: 'moderate', descriptor: desc, body: {} })
- expect(r).toEqual({ status: 422, body: { code: 'blocked' }, unavailable: false })
- })
+function okFetch(): FetchLike {
+ return vi.fn(async () => ({ status: 200, text: async () => '{"ok":true}' }))
+}
- it('malformed JSON → unavailable', async () => {
- const fetcher = createHookFetcher({
+describe('createHookFetcher transport routing', () => {
+ it('dials an in-cluster (non-external) target with the plain transport', async () => {
+ const inCluster = okFetch()
+ const external = okFetch()
+ const fetch = createHookFetcher({
getAuthToken: () => 't',
- fetchImpl: async () => okResponse(200, 'not json'),
+ fetchImpl: inCluster,
+ externalFetchImpl: external,
})
- expect((await fetcher({ point: 'moderate', descriptor: desc, body: {} })).unavailable).toBe(
- true
- )
+ const res = await fetch({ point: 'pre_call', descriptor: base, body: {} })
+ expect(res.status).toBe(200)
+ expect(inCluster).toHaveBeenCalledTimes(1)
+ expect(external).not.toHaveBeenCalled()
})
- it('oversized body → unavailable', async () => {
- const fetcher = createHookFetcher({
+ it('dials a remote (external) target with the SSRF-guarded transport', async () => {
+ const inCluster = okFetch()
+ const external = okFetch()
+ const fetch = createHookFetcher({
getAuthToken: () => 't',
- maxOutputBytes: 4,
- fetchImpl: async () => okResponse(200, '{"action":"continue"}'),
+ fetchImpl: inCluster,
+ externalFetchImpl: external,
})
- expect((await fetcher({ point: 'moderate', descriptor: desc, body: {} })).unavailable).toBe(
- true
- )
+ const descriptor: HookDescriptor = {
+ ...base,
+ endpoint: 'https://guardrails.aporia.com',
+ external: true,
+ }
+ await fetch({ point: 'pre_call', descriptor, body: {} })
+ expect(external).toHaveBeenCalledTimes(1)
+ expect(inCluster).not.toHaveBeenCalled()
})
- it('connection error / timeout → unavailable', async () => {
- const fetcher = createHookFetcher({
- getAuthToken: () => 't',
- fetchImpl: async () => {
- throw new Error('ECONNREFUSED')
- },
- })
- expect(await fetcher({ point: 'moderate', descriptor: desc, body: {} })).toEqual({
- status: 0,
- body: undefined,
- unavailable: true,
+ it('maps an SSRF refusal (transport throws) to unavailable → fail-mode', async () => {
+ const external: FetchLike = vi.fn(async () => {
+ throw new Error('Domain resolves to private IP (10.0.0.5)')
})
+ const fetch = createHookFetcher({ getAuthToken: () => 't', externalFetchImpl: external })
+ const descriptor: HookDescriptor = { ...base, endpoint: 'https://evil.example', external: true }
+ const res = await fetch({ point: 'pre_call', descriptor, body: {} })
+ expect(res.unavailable).toBe(true)
+ expect(res.status).toBe(0)
})
})
diff --git a/mcp-host/src/core/guardrails/hooks/hookFetcher.ts b/mcp-host/src/core/guardrails/hooks/hookFetcher.ts
index 24bf5a3e1..3f86b9e7d 100644
--- a/mcp-host/src/core/guardrails/hooks/hookFetcher.ts
+++ b/mcp-host/src/core/guardrails/hooks/hookFetcher.ts
@@ -8,13 +8,18 @@
* connection error / malformed or oversized body → `unavailable` (→ the hook's
* fail-mode, §8.6). `4xx`/`2xx` are returned for the per-point mapping to judge.
*
- * In-cluster (`image`/`service`) targets are trusted and dialed directly. The
- * SSRF-guarded `remote`-mode transport (DNS-pin + `isPrivateIp`, spec §8.3) is a
- * later increment — pass a guarded `fetchImpl` to reuse this shell for it.
+ * In-cluster (`image`/`service`) targets resolve to cluster-private IPs and are
+ * dialed directly. A `remote` (external) target — `descriptor.external` — is
+ * dialed through the SSRF-guarded transport (`../../net/ssrf`: reject
+ * private/loopback/link-local/metadata ranges, DNS-pin the connection), so a
+ * hosted provider (e.g. guardrails.aporia.com) works while an internal/metadata
+ * URL is refused (spec §8.3). An SSRF refusal maps to `unavailable` → the hook's
+ * fail-mode.
*/
+import { SsrfBlockedError, requestPinned, resolvePinnedPublicIp } from '../../net/ssrf'
import type { HookFetcher, LifecyclePoint } from './types'
-/** Minimal fetch surface (injectable for tests + a future SSRF-guarded impl). */
+/** Minimal fetch surface (injectable for tests + the in-cluster path). */
export type FetchLike = (
url: string,
init: { method: string; headers: Record<string, string>; body: string; signal: AbortSignal }
@@ -24,8 +29,10 @@ export interface HookFetcherDeps {
getAuthToken: () => string
timeoutMs?: number
maxOutputBytes?: number
- /** Defaults to the global `fetch`. Inject an SSRF-guarded impl for `remote` hooks. */
+ /** In-cluster transport. Defaults to the global `fetch`. */
fetchImpl?: FetchLike
+ /** External (remote) transport. Defaults to the SSRF-guarded impl. Injectable for tests. */
+ externalFetchImpl?: FetchLike
}
const POINT_PATH: Record<LifecyclePoint, string> = {
@@ -44,13 +51,40 @@ export function buildHookUrl(endpoint: string, path: string, point: LifecyclePoi
return `${base}${mid}/v1/${POINT_PATH[point]}`
}
+/**
+ * SSRF-guarded transport for `remote` hook targets: requires https, validates
+ * the host resolves only to public IPs, and connects to a pinned IP. Adapts to
+ * the `FetchLike` shape so the outcome classification is shared with the
+ * in-cluster path. Throws `SsrfBlockedError` on a blocked/unverifiable host.
+ */
+function makeSsrfGuardedFetch(timeoutMs: number): FetchLike {
+ return async (urlStr, init) => {
+ const url = new URL(urlStr)
+ if (url.protocol !== 'https:') {
+ throw new SsrfBlockedError(`remote hook URL must be https (got ${url.protocol})`)
+ }
+ const pinnedIp = await resolvePinnedPublicIp(url) // throws SsrfBlockedError on private/unresolvable
+ const { statusCode, body } = await requestPinned({
+ url,
+ method: init.method,
+ headers: init.headers,
+ body: init.body,
+ pinnedIp,
+ timeoutMs,
+ })
+ return { status: statusCode, text: async () => body }
+ }
+}
+
export function createHookFetcher(deps: HookFetcherDeps): HookFetcher {
const timeoutMs = deps.timeoutMs ?? 5000
const maxOutputBytes = deps.maxOutputBytes ?? 65536
- const doFetch: FetchLike = deps.fetchImpl ?? (globalThis.fetch as unknown as FetchLike)
+ const inClusterFetch: FetchLike = deps.fetchImpl ?? (globalThis.fetch as unknown as FetchLike)
+ const externalFetch: FetchLike = deps.externalFetchImpl ?? makeSsrfGuardedFetch(timeoutMs)
return async ({ point, descriptor, body }) => {
const url = buildHookUrl(descriptor.endpoint, descriptor.path, point)
+ const doFetch = descriptor.external ? externalFetch : inClusterFetch
try {
const res = await doFetch(url, {
method: 'POST',
@@ -75,8 +109,13 @@ export function createHookFetcher(deps: HookFetcherDeps): HookFetcher {
}
// 5xx → unavailable; 2xx/4xx are returned for the mapping to classify.
return { status: res.status, body: parsed, unavailable: res.status >= 500 }
- } catch {
- // timeout / connection error → unavailable
+ } catch (err) {
+ // timeout / connection error / SSRF refusal → unavailable (→ fail-mode, §8.6).
+ if (err instanceof SsrfBlockedError) {
+ console.warn(
+ `[Guardrails] remote hook ${descriptor.id} blocked by SSRF guard: ${err.message}`
+ )
+ }
return { status: 0, body: undefined, unavailable: true }
}
}
diff --git a/mcp-host/src/core/guardrails/hooks/types.ts b/mcp-host/src/core/guardrails/hooks/types.ts
index 080dc7c72..ed981aa4c 100644
--- a/mcp-host/src/core/guardrails/hooks/types.ts
+++ b/mcp-host/src/core/guardrails/hooks/types.ts
@@ -32,6 +32,13 @@ export interface HookDescriptor {
/** Fail-posture when the hook is unavailable (spec §8.6). */
failMode: 'open' | 'closed'
order: number
+ /**
+ * True for a `remote` (external) target dialed over the public internet. Such
+ * calls MUST go through the SSRF-guarded transport (reject private/metadata
+ * ranges, DNS-pin). In-cluster `image`/`service` targets resolve to
+ * cluster-private IPs and are NOT external, so they bypass that guard.
+ */
+ external?: boolean
}
/** Result of one `/v1` HTTP call. `unavailable` = 5xx / timeout / connection error / malformed body (spec §8.1). */
diff --git a/mcp-host/src/core/net/__tests__/ssrf.test.ts b/mcp-host/src/core/net/__tests__/ssrf.test.ts
new file mode 100644
index 000000000..032913618
--- /dev/null
+++ b/mcp-host/src/core/net/__tests__/ssrf.test.ts
@@ -0,0 +1,62 @@
+/**
+ * SSRF guard tests: `resolvePinnedPublicIp` must reject private/metadata targets
+ * (literal and DNS-resolved), fail closed on unresolvable hosts, and pin a
+ * validated public IP. `isPrivateIp` range classification is covered in
+ * core/tools/__tests__/shellAndHttp.test.ts (same implementation, re-exported).
+ */
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import * as dns from 'dns/promises'
+import { SsrfBlockedError, resolvePinnedPublicIp } from '../ssrf'
+
+vi.mock('dns/promises', () => ({
+ resolve4: vi.fn(),
+ resolve6: vi.fn(),
+}))
+
+const resolve4 = vi.mocked(dns.resolve4)
+const resolve6 = vi.mocked(dns.resolve6)
+
+afterEach(() => vi.clearAllMocks())
+
+describe('resolvePinnedPublicIp', () => {
+ it('returns a public IP literal unchanged (no DNS)', async () => {
+ await expect(resolvePinnedPublicIp(new URL('https://8.8.8.8/x'))).resolves.toBe('8.8.8.8')
+ expect(resolve4).not.toHaveBeenCalled()
+ })
+
+ it('rejects a private IP literal', async () => {
+ await expect(resolvePinnedPublicIp(new URL('http://10.0.0.5/'))).rejects.toBeInstanceOf(
+ SsrfBlockedError
+ )
+ })
+
+ it('rejects the cloud-metadata IP literal', async () => {
+ await expect(
+ resolvePinnedPublicIp(new URL('http://169.254.169.254/latest/meta-data/'))
+ ).rejects.toThrow(/private IP/)
+ })
+
+ it('resolves a hostname to a public IP and pins it', async () => {
+ resolve4.mockResolvedValue(['93.184.216.34'])
+ resolve6.mockRejectedValue(new Error('no AAAA'))
+ await expect(resolvePinnedPublicIp(new URL('https://guardrails.aporia.com/v1'))).resolves.toBe(
+ '93.184.216.34'
+ )
+ })
+
+ it('rejects a hostname that resolves to a private IP (even via AAAA)', async () => {
+ resolve4.mockResolvedValue(['93.184.216.34'])
+ resolve6.mockResolvedValue(['::1']) // loopback hidden behind AAAA
+ await expect(resolvePinnedPublicIp(new URL('https://sneaky.example.com/'))).rejects.toThrow(
+ /private IP/
+ )
+ })
+
+ it('fails closed when DNS resolution fails', async () => {
+ resolve4.mockRejectedValue(new Error('nxdomain'))
+ resolve6.mockRejectedValue(new Error('nxdomain'))
+ await expect(resolvePinnedPublicIp(new URL('https://nope.invalid/'))).rejects.toThrow(
+ /DNS resolution failed/
+ )
+ })
+})
diff --git a/mcp-host/src/core/net/ssrf.ts b/mcp-host/src/core/net/ssrf.ts
new file mode 100644
index 000000000..4c6cac4e2
--- /dev/null
+++ b/mcp-host/src/core/net/ssrf.ts
@@ -0,0 +1,296 @@
+/**
+ * SSRF-safe outbound HTTP primitives, shared by the `http_request` native tool
+ * and the guardrail hook fetcher (remote/external hook targets).
+ *
+ * The guarantees:
+ * - `isPrivateIp` classifies an IP (v4/v6, incl. IPv4-mapped/compatible forms)
+ * as private/loopback/link-local/metadata/reserved — fail-closed on
+ * unparseable-but-v6-looking literals.
+ * - `resolvePinnedPublicIp` validates a URL's host resolves ONLY to public
+ * addresses and returns a single pinned IP, so the caller connects to the
+ * exact address that was validated (closing the DNS-rebinding window).
+ * - `requestPinned` connects to that pinned IP while keeping the original
+ * hostname in the Host header and TLS SNI.
+ *
+ * This module MUST remain the single source of truth for these checks — do not
+ * reimplement them at call sites.
+ */
+import * as dns from 'dns/promises'
+import * as http from 'http'
+import * as https from 'https'
+import * as net from 'net'
+
+/** Thrown when a target host is (or resolves to) a non-public address, or can't be verified. */
+export class SsrfBlockedError extends Error {
+ constructor(message: string) {
+ super(message)
+ this.name = 'SsrfBlockedError'
+ }
+}
+
+function stripIpv6Decorations(ip: string): string {
+ let s = ip.trim()
+ if (s.startsWith('[') && s.endsWith(']')) {
+ s = s.slice(1, -1)
+ }
+ const zoneIdx = s.indexOf('%')
+ if (zoneIdx !== -1) {
+ s = s.slice(0, zoneIdx)
+ }
+ return s
+}
+
+function parseIpv6ToBytes(ip: string): Uint8Array | null {
+ const normalized = stripIpv6Decorations(ip).toLowerCase()
+ if (normalized.length === 0) return null
+
+ // Reject more than one "::" compression marker.
+ const doubleColonCount = (normalized.match(/::/g) ?? []).length
+ if (doubleColonCount > 1) return null
+
+ // Detect IPv4-embedded tail (e.g. "::ffff:192.168.1.1"). The tail is the
+ // segment after the final ':' and contains dots.
+ let headPart = normalized
+ let ipv4Tail: number[] | null = null
+ const finalColon = normalized.lastIndexOf(':')
+ if (finalColon !== -1 && normalized.slice(finalColon + 1).includes('.')) {
+ const tail = normalized.slice(finalColon + 1)
+ const ipv4Parts = tail.split('.').map(p => Number(p))
+ if (ipv4Parts.length !== 4 || ipv4Parts.some(n => !Number.isInteger(n) || n < 0 || n > 255)) {
+ return null
+ }
+ ipv4Tail = ipv4Parts
+ // Replace the IPv4 segment with two placeholder hextets so the rest of
+ // the parser treats it as a normal 8-hextet IPv6 literal.
+ headPart = normalized.slice(0, finalColon + 1) + '0:0'
+ }
+
+ const targetGroupCount = 8
+ let left: string[] = []
+ let right: string[] = []
+ let sawDoubleColon = false
+
+ if (headPart.includes('::')) {
+ sawDoubleColon = true
+ const [leftRaw, rightRaw] = headPart.split('::')
+ left = leftRaw && leftRaw.length > 0 ? leftRaw.split(':') : []
+ right = rightRaw && rightRaw.length > 0 ? rightRaw.split(':') : []
+ } else {
+ left = headPart.split(':')
+ }
+
+ // Any empty hextet outside of the "::" marker is invalid.
+ if (left.some(h => h === '') || right.some(h => h === '')) return null
+
+ const fillCount = targetGroupCount - (left.length + right.length)
+ if (sawDoubleColon) {
+ if (fillCount < 0) return null
+ } else {
+ if (left.length !== targetGroupCount) return null
+ }
+
+ const groups = sawDoubleColon
+ ? [...left, ...Array.from({ length: fillCount }, () => '0'), ...right]
+ : left
+
+ if (groups.length !== targetGroupCount) return null
+
+ const bytes = new Uint8Array(16)
+ for (let i = 0; i < groups.length; i++) {
+ const part = groups[i]!
+ if (!/^[0-9a-f]{1,4}$/.test(part)) return null
+ const value = parseInt(part, 16)
+ bytes[i * 2] = (value >> 8) & 0xff
+ bytes[i * 2 + 1] = value & 0xff
+ }
+
+ if (ipv4Tail) {
+ bytes[12] = ipv4Tail[0]!
+ bytes[13] = ipv4Tail[1]!
+ bytes[14] = ipv4Tail[2]!
+ bytes[15] = ipv4Tail[3]!
+ }
+ return bytes
+}
+
+function isIpv4MappedBytes(bytes: Uint8Array): boolean {
+ for (let i = 0; i < 10; i++) {
+ if (bytes[i] !== 0) return false
+ }
+ return bytes[10] === 0xff && bytes[11] === 0xff
+}
+
+function isPrivateIpv4Octets(octets: readonly number[]): boolean {
+ if (octets.length !== 4) return false
+ const [a = 0, b = 0] = octets
+ return (
+ a === 10 ||
+ a === 127 ||
+ (a === 172 && b >= 16 && b <= 31) ||
+ (a === 192 && b === 168) ||
+ (a === 169 && b === 254) ||
+ a === 0
+ )
+}
+
+/**
+ * Block private and metadata IP ranges (SSRF defense).
+ *
+ * IPv4 ranges: 10/8, 127/8, 172.16/12, 192.168/16, 169.254/16 (metadata), 0/8.
+ * IPv6 ranges: ::/128, ::1/128, fc00::/7, fe80::/10, fec0::/10, plus
+ * IPv4-mapped/compatible forms delegated to the IPv4 rules.
+ */
+export function isPrivateIp(ip: string): boolean {
+ if (typeof ip !== 'string' || ip.length === 0) return false
+
+ // IPv6 path — normalize and test against known private prefixes bit-for-bit.
+ if (ip.includes(':')) {
+ const bytes = parseIpv6ToBytes(ip)
+ if (!bytes) {
+ // Fail-closed on unparseable literal that still "looks like" IPv6.
+ return true
+ }
+
+ // ::/128 unspecified and ::1/128 loopback
+ let allZero = true
+ for (let i = 0; i < 15; i++) {
+ if (bytes[i] !== 0) {
+ allZero = false
+ break
+ }
+ }
+ if (allZero && (bytes[15] === 0 || bytes[15] === 1)) return true
+
+ // fc00::/7 (unique local)
+ if ((bytes[0]! & 0xfe) === 0xfc) return true
+
+ // fe80::/10 (link-local) and fec0::/10 (deprecated site-local)
+ if (bytes[0] === 0xfe && (bytes[1]! & 0xc0) === 0x80) return true
+ if (bytes[0] === 0xfe && (bytes[1]! & 0xc0) === 0xc0) return true
+
+ // ::ffff:0:0/96 IPv4-mapped — delegate to IPv4 rules.
+ if (isIpv4MappedBytes(bytes)) {
+ return isPrivateIpv4Octets([bytes[12]!, bytes[13]!, bytes[14]!, bytes[15]!])
+ }
+
+ // IPv4-compatible ::x.x.x.x (bytes[0..11]==0, bytes[10..11] NOT 0xffff).
+ // Form is deprecated but still parseable; attackers use it to wrap a
+ // private v4 target inside a literal that survives naive v6 checks.
+ // `::` (all-zero) and `::1` were already matched by the unspecified
+ // + loopback block above, so any surviving first-12-zero address here
+ // is a genuine embedded IPv4.
+ let first12AllZero = true
+ for (let i = 0; i < 12; i++) {
+ if (bytes[i] !== 0) {
+ first12AllZero = false
+ break
+ }
+ }
+ if (first12AllZero) {
+ return isPrivateIpv4Octets([bytes[12]!, bytes[13]!, bytes[14]!, bytes[15]!])
+ }
+
+ return false
+ }
+
+ // IPv4 path
+ const parts = ip.split('.').map(p => Number(p))
+ if (parts.length !== 4 || parts.some(n => !Number.isInteger(n) || n < 0 || n > 255)) {
+ return false
+ }
+ return isPrivateIpv4Octets(parts)
+}
+
+/**
+ * Validate that `url`'s host is public and return a single DNS-pinned IP to
+ * connect to. An IP-literal host is checked directly; a hostname is resolved
+ * over BOTH A and AAAA (so a private target can't hide behind the record type we
+ * skip) and every returned address must be public. Throws `SsrfBlockedError` on
+ * a private/reserved address or when resolution fails (fail-closed: an
+ * unverifiable host is treated as unsafe).
+ */
+export async function resolvePinnedPublicIp(url: URL): Promise<string> {
+ const bareHost = stripIpv6Decorations(url.hostname)
+
+ // IP-literal targets never resolve via DNS — check the literal directly.
+ if (net.isIP(bareHost) !== 0) {
+ if (isPrivateIp(url.hostname)) {
+ throw new SsrfBlockedError(`Target is a private IP (${bareHost})`)
+ }
+ return bareHost
+ }
+
+ let addresses: string[]
+ try {
+ const [v4, v6] = await Promise.allSettled([
+ dns.resolve4(url.hostname),
+ dns.resolve6(url.hostname),
+ ])
+ addresses = []
+ if (v4.status === 'fulfilled') addresses.push(...v4.value)
+ if (v6.status === 'fulfilled') addresses.push(...v6.value)
+ if (addresses.length === 0) throw new Error('no addresses resolved')
+ } catch {
+ // Cannot verify the target is not internal → fail closed.
+ throw new SsrfBlockedError(
+ `DNS resolution failed for "${url.hostname}". Cannot verify IP safety.`
+ )
+ }
+
+ for (const addr of addresses) {
+ if (isPrivateIp(addr)) {
+ throw new SsrfBlockedError(`Domain resolves to private IP (${addr})`)
+ }
+ }
+ return addresses[0]!
+}
+
+/**
+ * Make an HTTP(S) request to a caller-validated, DNS-pinned IP while keeping the
+ * original hostname in the Host header and TLS SNI. Reads the full body (callers
+ * apply their own size/parse policy) and rejects on error/timeout.
+ */
+export function requestPinned(opts: {
+ url: URL
+ method: string
+ headers: Record<string, string>
+ body?: string
+ pinnedIp: string
+ timeoutMs: number
+}): Promise<{ statusCode: number; body: string }> {
+ const { url, method, headers, body, pinnedIp, timeoutMs } = opts
+ return new Promise((resolve, reject) => {
+ const isHttps = url.protocol === 'https:'
+ const client = isHttps ? https : http
+ const defaultPort = isHttps ? 443 : 80
+ // IPv6 literals must be bracketed in a Host header but NOT in the
+ // hostname/servername fields themselves.
+ const hostHeaderValue = url.port ? `${url.hostname}:${url.port}` : url.hostname
+ const mergedHeaders: Record<string, string> = { ...headers, host: hostHeaderValue }
+ const requestOptions: https.RequestOptions = {
+ method,
+ headers: mergedHeaders,
+ timeout: timeoutMs,
+ hostname: pinnedIp,
+ port: url.port ? Number(url.port) : defaultPort,
+ path: `${url.pathname}${url.search}`,
+ // SNI — the TLS handshake must still use the real hostname even though we
+ // connect to a pinned IP literal.
+ servername: url.hostname,
+ }
+ const req = client.request(requestOptions, res => {
+ const chunks: Buffer[] = []
+ res.on('data', chunk => chunks.push(chunk))
+ res.on('end', () => {
+ resolve({ statusCode: res.statusCode!, body: Buffer.concat(chunks).toString('utf-8') })
+ })
+ })
+ req.on('error', reject)
+ req.on('timeout', () => {
+ req.destroy()
+ reject(new Error('Request timeout'))
+ })
+ if (body) req.write(body)
+ req.end()
+ })
+}
diff --git a/mcp-host/src/core/tools/httpRequest.ts b/mcp-host/src/core/tools/httpRequest.ts
index 34d3dbc28..af81b97ce 100644
--- a/mcp-host/src/core/tools/httpRequest.ts
+++ b/mcp-host/src/core/tools/httpRequest.ts
@@ -1,11 +1,13 @@
-import * as dns from 'dns/promises'
-import * as http from 'http'
-import * as https from 'https'
-import * as net from 'net'
import { URL } from 'url'
import { Tool } from '../interfaces'
+import { requestPinned, resolvePinnedPublicIp } from '../net/ssrf'
import { ToolOutput } from '../types'
+// Re-exported for existing importers (safety.ts, tests). The implementation now
+// lives in ../net/ssrf as the single source of truth shared with the guardrail
+// hook fetcher.
+export { isPrivateIp } from '../net/ssrf'
+
export class HttpRequestTool implements Tool {
constructor(private readonly allowlist: string[]) {}
@@ -80,72 +82,37 @@ export class HttpRequestTool implements Tool {
}
}
- // The address we ultimately connect to. For an IP literal it is the literal
- // itself; for a hostname it is the first DNS-validated address (pinned into
- // makeRequest to close the DNS-rebinding window between validation and
- // connect). The Host header (and SNI) always keep the original hostname.
- let resolvedIp: string | undefined
-
- // IP-literal targets never resolve via DNS — dns.resolve4/resolve6 reject a
- // literal, so the DNS-based guard below would never inspect them. Check the
- // literal directly (stripping [] brackets and %zone) and skip DNS entirely.
- // Without this, `http://169.254.169.254/…`, `http://127.0.0.1/…`, etc. slip
- // straight through to the connect step (SSRF).
- const bareHost = stripIpv6Decorations(url.hostname)
- if (net.isIP(bareHost) !== 0) {
- if (isPrivateIp(url.hostname)) {
- return {
- content: `Error: Target is a private IP (${bareHost})`,
- duration_ms: Date.now() - startTime,
- is_error: true,
- }
- }
- resolvedIp = bareHost
- } else {
- // Hostname target. Resolve BOTH A and AAAA in parallel so attackers cannot
- // hide a private target behind the record type we skip.
- try {
- const [v4, v6] = await Promise.allSettled([
- dns.resolve4(url.hostname),
- dns.resolve6(url.hostname),
- ])
- const addresses: string[] = []
- if (v4.status === 'fulfilled') addresses.push(...v4.value)
- if (v6.status === 'fulfilled') addresses.push(...v6.value)
-
- if (addresses.length === 0) {
- throw new Error('no addresses resolved')
- }
-
- for (const addr of addresses) {
- if (isPrivateIp(addr)) {
- return {
- content: `Error: Domain resolves to private IP (${addr})`,
- duration_ms: Date.now() - startTime,
- is_error: true,
- }
- }
- }
- resolvedIp = addresses[0]
- } catch {
- // DNS resolution failed — we cannot verify the target is not a
- // private/internal address, so fail closed. This holds whether or not
- // an allowlist is configured: an unresolvable name could not have been
- // reached anyway, and proceeding would be the SSRF hole this guards.
- return {
- content: `Error: DNS resolution failed for "${url.hostname}". Cannot verify IP safety.`,
- duration_ms: Date.now() - startTime,
- is_error: true,
- }
+ // SSRF guard: validate the host is public and pin the connect IP (closes the
+ // DNS-rebinding window). Preserves the prior error phrasing ("private IP",
+ // "DNS resolution failed") via the thrown message.
+ let pinnedIp: string
+ try {
+ pinnedIp = await resolvePinnedPublicIp(url)
+ } catch (err) {
+ return {
+ content: `Error: ${(err as Error).message}`,
+ duration_ms: Date.now() - startTime,
+ is_error: true,
}
}
try {
- const response = await this.makeRequest(url, method, headers, body, resolvedIp)
+ const { statusCode, body: responseBody } = await requestPinned({
+ url,
+ method,
+ headers,
+ body,
+ pinnedIp,
+ timeoutMs: 30000,
+ })
+ const truncated =
+ responseBody.length > 50000
+ ? responseBody.substring(0, 50000) + '\n...[truncated]'
+ : responseBody
return {
- content: `HTTP ${response.statusCode}\n\n${response.body}`,
+ content: `HTTP ${statusCode}\n\n${truncated}`,
duration_ms: Date.now() - startTime,
- is_error: response.statusCode >= 400,
+ is_error: statusCode >= 400,
}
} catch (err) {
return {
@@ -155,256 +122,4 @@ export class HttpRequestTool implements Tool {
}
}
}
-
- private makeRequest(
- url: URL,
- method: string,
- headers: Record<string, string>,
- body?: string,
- pinnedIp?: string
- ): Promise<{ statusCode: number; body: string }> {
- return new Promise((resolve, reject) => {
- const isHttps = url.protocol === 'https:'
- const client = isHttps ? https : http
- const defaultPort = isHttps ? 443 : 80
- const connectHost = pinnedIp ?? url.hostname
- // IPv6 literals must be bracketed in a Host header but NOT in the
- // hostname/servername fields themselves.
- const hostHeaderValue = url.port ? `${url.hostname}:${url.port}` : url.hostname
- const mergedHeaders: Record<string, string> = {
- ...headers,
- host: hostHeaderValue,
- }
- const requestOptions: https.RequestOptions = {
- method,
- headers: mergedHeaders,
- timeout: 30000,
- hostname: connectHost,
- port: url.port ? Number(url.port) : defaultPort,
- path: `${url.pathname}${url.search}`,
- // SNI — required so TLS handshake still uses the real hostname
- // even when we connect to a pinned IP literal.
- servername: url.hostname,
- }
- const req = client.request(requestOptions, res => {
- const chunks: Buffer[] = []
- res.on('data', chunk => chunks.push(chunk))
- res.on('end', () => {
- const responseBody = Buffer.concat(chunks).toString('utf-8')
- // Truncate large responses
- const truncated =
- responseBody.length > 50000
- ? responseBody.substring(0, 50000) + '\n...[truncated]'
- : responseBody
- resolve({ statusCode: res.statusCode!, body: truncated })
- })
- })
-
- req.on('error', reject)
- req.on('timeout', () => {
- req.destroy()
- reject(new Error('Request timeout'))
- })
- if (body) req.write(body)
- req.end()
- })
- }
-}
-
-/**
- * Block private and metadata IP ranges (SSRF defense).
- *
- * IPv4 ranges:
- * 10.0.0.0/8 RFC 1918 private
- * 127.0.0.0/8 Loopback
- * 172.16.0.0/12 RFC 1918 private
- * 192.168.0.0/16 RFC 1918 private
- * 169.254.0.0/16 Link-local (cloud metadata, e.g. 169.254.169.254)
- * 0.0.0.0/8 "This network"
- *
- * IPv6 ranges:
- * ::/128 Unspecified
- * ::1/128 Loopback
- * fc00::/7 Unique local (fc00::/8 + fd00::/8)
- * fe80::/10 Link-local
- * ::ffff:0:0/96 IPv4-mapped (delegate to IPv4 check)
- * fec0::/10 Site-local (deprecated, still blocked)
- * 2001:db8::/32 Documentation
- *
- * The previous implementation had several bypasses:
- * - `0:0:0:0:0:0:0:1` (long-form ::1) skipped the `::1` equality check
- * - `::ffff:7f00:1` (IPv4-mapped in hex) skipped the dotted-quad prefix match
- * - `[::1]` brackets from URL hostnames were never stripped
- * - `fe80::1%eth0` zone identifiers broke startsWith matching
- * - 172.16/12 IPv4-mapped was only matched by prefix `172.` (too broad)
- *
- * Current implementation normalizes IPv6 to 16 raw bytes and tests CIDR
- * membership bit-for-bit, matching the same ranges that BlockList would
- * resolve.
- */
-
-function stripIpv6Decorations(ip: string): string {
- let s = ip.trim()
- if (s.startsWith('[') && s.endsWith(']')) {
- s = s.slice(1, -1)
- }
- const zoneIdx = s.indexOf('%')
- if (zoneIdx !== -1) {
- s = s.slice(0, zoneIdx)
- }
- return s
-}
-
-function parseIpv6ToBytes(ip: string): Uint8Array | null {
- const normalized = stripIpv6Decorations(ip).toLowerCase()
- if (normalized.length === 0) return null
-
- // Reject more than one "::" compression marker.
- const doubleColonCount = (normalized.match(/::/g) ?? []).length
- if (doubleColonCount > 1) return null
-
- // Detect IPv4-embedded tail (e.g. "::ffff:192.168.1.1"). The tail is the
- // segment after the final ':' and contains dots.
- let headPart = normalized
- let ipv4Tail: number[] | null = null
- const finalColon = normalized.lastIndexOf(':')
- if (finalColon !== -1 && normalized.slice(finalColon + 1).includes('.')) {
- const tail = normalized.slice(finalColon + 1)
- const ipv4Parts = tail.split('.').map(p => Number(p))
- if (ipv4Parts.length !== 4 || ipv4Parts.some(n => !Number.isInteger(n) || n < 0 || n > 255)) {
- return null
- }
- ipv4Tail = ipv4Parts
- // Replace the IPv4 segment with two placeholder hextets so the rest of
- // the parser treats it as a normal 8-hextet IPv6 literal.
- headPart = normalized.slice(0, finalColon + 1) + '0:0'
- }
-
- const targetGroupCount = 8
- let left: string[] = []
- let right: string[] = []
- let sawDoubleColon = false
-
- if (headPart.includes('::')) {
- sawDoubleColon = true
- const [leftRaw, rightRaw] = headPart.split('::')
- left = leftRaw && leftRaw.length > 0 ? leftRaw.split(':') : []
- right = rightRaw && rightRaw.length > 0 ? rightRaw.split(':') : []
- } else {
- left = headPart.split(':')
- }
-
- // Any empty hextet outside of the "::" marker is invalid.
- if (left.some(h => h === '') || right.some(h => h === '')) return null
-
- const fillCount = targetGroupCount - (left.length + right.length)
- if (sawDoubleColon) {
- if (fillCount < 0) return null
- } else {
- if (left.length !== targetGroupCount) return null
- }
-
- const groups = sawDoubleColon
- ? [...left, ...Array.from({ length: fillCount }, () => '0'), ...right]
- : left
-
- if (groups.length !== targetGroupCount) return null
-
- const bytes = new Uint8Array(16)
- for (let i = 0; i < groups.length; i++) {
- const part = groups[i]!
- if (!/^[0-9a-f]{1,4}$/.test(part)) return null
- const value = parseInt(part, 16)
- bytes[i * 2] = (value >> 8) & 0xff
- bytes[i * 2 + 1] = value & 0xff
- }
-
- if (ipv4Tail) {
- bytes[12] = ipv4Tail[0]!
- bytes[13] = ipv4Tail[1]!
- bytes[14] = ipv4Tail[2]!
- bytes[15] = ipv4Tail[3]!
- }
- return bytes
-}
-
-function isIpv4MappedBytes(bytes: Uint8Array): boolean {
- for (let i = 0; i < 10; i++) {
- if (bytes[i] !== 0) return false
- }
- return bytes[10] === 0xff && bytes[11] === 0xff
-}
-
-function isPrivateIpv4Octets(octets: readonly number[]): boolean {
- if (octets.length !== 4) return false
- const [a = 0, b = 0] = octets
- return (
- a === 10 ||
- a === 127 ||
- (a === 172 && b >= 16 && b <= 31) ||
- (a === 192 && b === 168) ||
- (a === 169 && b === 254) ||
- a === 0
- )
-}
-
-export function isPrivateIp(ip: string): boolean {
- if (typeof ip !== 'string' || ip.length === 0) return false
-
- // IPv6 path — normalize and test against known private prefixes bit-for-bit.
- if (ip.includes(':')) {
- const bytes = parseIpv6ToBytes(ip)
- if (!bytes) {
- // Fail-closed on unparseable literal that still "looks like" IPv6.
- return true
- }
-
- // ::/128 unspecified and ::1/128 loopback
- let allZero = true
- for (let i = 0; i < 15; i++) {
- if (bytes[i] !== 0) {
- allZero = false
- break
- }
- }
- if (allZero && (bytes[15] === 0 || bytes[15] === 1)) return true
-
- // fc00::/7 (unique local)
- if ((bytes[0]! & 0xfe) === 0xfc) return true
-
- // fe80::/10 (link-local) and fec0::/10 (deprecated site-local)
- if (bytes[0] === 0xfe && (bytes[1]! & 0xc0) === 0x80) return true
- if (bytes[0] === 0xfe && (bytes[1]! & 0xc0) === 0xc0) return true
-
- // ::ffff:0:0/96 IPv4-mapped — delegate to IPv4 rules.
- if (isIpv4MappedBytes(bytes)) {
- return isPrivateIpv4Octets([bytes[12]!, bytes[13]!, bytes[14]!, bytes[15]!])
- }
-
- // IPv4-compatible ::x.x.x.x (bytes[0..11]==0, bytes[10..11] NOT 0xffff).
- // Form is deprecated but still parseable; attackers use it to wrap a
- // private v4 target inside a literal that survives naive v6 checks.
- // `:: ` (all-zero) and `::1` were already matched by the unspecified
- // + loopback block above, so any surviving first-12-zero address here
- // is a genuine embedded IPv4.
- let first12AllZero = true
- for (let i = 0; i < 12; i++) {
- if (bytes[i] !== 0) {
- first12AllZero = false
- break
- }
- }
- if (first12AllZero) {
- return isPrivateIpv4Octets([bytes[12]!, bytes[13]!, bytes[14]!, bytes[15]!])
- }
-
- return false
- }
-
- // IPv4 path
- const parts = ip.split('.').map(p => Number(p))
- if (parts.length !== 4 || parts.some(n => !Number.isInteger(n) || n < 0 || n > 255)) {
- return false
- }
- return isPrivateIpv4Octets(parts)
}
diff --git a/mcp-host/src/guardrailHookResolver.ts b/mcp-host/src/guardrailHookResolver.ts
index 2f0227419..cc76710a8 100644
--- a/mcp-host/src/guardrailHookResolver.ts
+++ b/mcp-host/src/guardrailHookResolver.ts
@@ -141,19 +141,6 @@ export async function resolveGuardrailHookDescriptors(
continue
}
- // SSRF posture (§8.3): the hook fetcher has no private-range/metadata-IP
- // guard yet and the base mcp-host egress permits 0.0.0.0/0:443, so dialing an
- // admin-authored external URL would ship the full conversation to an arbitrary
- // host (incl. 169.254.169.254). Remote targets are therefore NOT resolved
- // until the SSRF-guarded transport lands — fail-closed (the hook does not run)
- // rather than enabling an unvalidated external dial.
- if (ep.kind === 'remote') {
- console.warn(
- `[Guardrails] LlmHook ${id} is a remote target — disabled pending SSRF-guarded transport (§8.3); skipping`
- )
- continue
- }
-
const points = (cr.spec?.lifecyclePoints ?? [])
.map(p => PHASE_TO_POINT[p])
.filter((p): p is LifecyclePoint => !!p)
@@ -186,6 +173,11 @@ export async function resolveGuardrailHookDescriptors(
const failMode: 'open' | 'closed' = cr.spec?.failMode === 'open' ? 'open' : 'closed'
const order = typeof cr.spec?.order === 'number' ? cr.spec.order : 100
+ // `remote` targets are dialed over the public internet → SSRF-guarded
+ // transport (private/metadata-range reject + DNS-pin). image/service targets
+ // resolve to cluster-private IPs and must bypass that guard.
+ const external = ep.kind === 'remote'
+
out.push({
id,
endpoint: ep.endpoint,
@@ -194,9 +186,10 @@ export async function resolveGuardrailHookDescriptors(
capabilities,
failMode,
order,
+ external,
})
console.log(
- `[Guardrails] resolved hook ${id} -> ${ep.endpoint}${path} points=[${points.join(',')}] caps=[${capabilities.join(',')}] failMode=${failMode}`
+ `[Guardrails] resolved hook ${id} -> ${ep.endpoint}${path} points=[${points.join(',')}] caps=[${capabilities.join(',')}] failMode=${failMode}${external ? ' external=true(SSRF-guarded)' : ''}`
)
}