Claude skill SSRF via cloud metadata endpoints — SA-SKL-SSRF6
Cloud metadata services are the highest-value SSRF targets in a modern deployment: a single unauthenticated HTTP GET to http://169.254.169.254/latest/meta-data/iam/security-credentials/ on an AWS EC2 instance returns temporary IAM credentials with the same permissions as the instance profile — often including S3 bucket access, Secrets Manager reads, and SSM parameter access. SA-SKL-SSRF6 covers four cloud-specific SSRF patterns: AWS IMDSv1 credential theft, GCP and Azure metadata endpoint access, DNS rebinding to bypass IP allowlists, and Redis or MongoDB command execution via SSRF or the gopher:// protocol scheme.
Why cloud IMDS is the worst-case SSRF target
The AWS Instance Metadata Service (IMDS) listens on the link-local IP 169.254.169.254 on every EC2 instance. IMDSv1 (the original version) requires no authentication beyond network reachability — any process on the instance, including an MCP skill's Node.js process, can retrieve credentials by making a simple GET request. The credential response includes an AWS access key ID, secret access key, and session token with the permissions of the instance's IAM role. These credentials are rotated every few hours, but during their validity period they provide full programmatic access to every AWS API the instance role is authorized to call.
IMDSv2 (the recommended version as of 2019) requires a preliminary PUT request to obtain a session token, adding a minimal SSRF barrier: an SSRF via a URL-fetch vulnerability cannot make the PUT request if the HTTP client follows a redirect that changes the method to GET. However, IMDSv1 remains the default on many existing EC2 instances, and disabling IMDSv1 requires an explicit aws ec2 modify-instance-metadata-options command. The safe fix for MCP skills is to block the entire 169.254.0.0/16 range at the outgoing fetch layer, making the IMDS unreachable regardless of whether IMDSv1 or IMDSv2 is configured.
SA-SKL-SSRF6 in scope: SSRF6-001 (AWS EC2 IMDS at 169.254.169.254 — IAM credential theft via unrestricted fetch()), SSRF6-002 (GCP metadata.google.internal and Azure 169.254.169.254 — same link-local range), SSRF6-003 (DNS rebinding with TTL-0 bypasses IP allowlist — fix via IP pinning in custom http.Agent), SSRF6-004 (Redis/MongoDB on localhost via http://localhost:6379 or gopher:// — unauthenticated command injection). Each finding includes SkillAudit detection rules and correct Node.js fixes.
SSRF6-001 — AWS EC2 IMDS credential theft via unrestricted fetch()
An MCP skill exposes a tool that fetches a URL supplied by the Claude model — for example, a "fetch web page content" tool used for research assistance. The skill's fetch() call is not restricted by IP range. When deployed on an EC2 instance, the skill's Node.js process can reach http://169.254.169.254/latest/meta-data/iam/security-credentials/ without any special permissions. The response from IMDS is the name of the attached IAM role. A second request to http://169.254.169.254/latest/meta-data/iam/security-credentials/<role-name> returns the role's temporary credentials in JSON: AccessKeyId, SecretAccessKey, Token, and Expiration. With these credentials, an attacker can call any AWS API the role is authorized for — typically including at minimum S3 object listing, Secrets Manager, and SSM Parameter Store on a production deployment.
The fix requires blocking the 169.254.0.0/16 (link-local) range and the 100.64.0.0/10 range (AWS-specific carrier-grade NAT, used by some EC2 internal services) at the fetch layer. This check must happen after DNS resolution — if the URL contains a hostname rather than a literal IP, the hostname must be resolved and the resulting IP checked against the blocked ranges. Blocking only literal IP addresses in the URL is insufficient; a hostname like imds.internal that resolves to 169.254.169.254 would bypass a literal-IP check.
// VULNERABLE — fetch() with no IP restriction, deployed on EC2
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { z } from 'zod';
const server = new McpServer({ name: 'research-skill', version: '1.0.0' });
server.tool(
'fetch_url',
'Fetch the content of a web page for research',
{ url: z.string().url() },
async ({ url }) => {
// VULNERABLE: no IP range check before fetching
// If url = "http://169.254.169.254/latest/meta-data/iam/security-credentials/"
// This returns the IAM role name on EC2 — no auth required
// Step 1: attacker requests /iam/security-credentials/ → returns "skill-ec2-role"
// Step 2: attacker requests /iam/security-credentials/skill-ec2-role → returns:
// {
// "AccessKeyId": "ASIA...",
// "SecretAccessKey": "...",
// "Token": "...",
// "Expiration": "2026-11-07T23:00:00Z"
// }
// Attacker now has temporary AWS credentials valid for ~1 hour
const response = await fetch(url, {
headers: { 'User-Agent': 'SkillAudit-Research/1.0' },
redirect: 'follow',
signal: AbortSignal.timeout(10_000),
});
const text = await response.text();
return { content: [{ type: 'text', text }] };
}
);
// FIXED — block 169.254.0.0/16, 100.64.0.0/10, private ranges, and loopback at fetch layer
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { z } from 'zod';
import dns from 'dns/promises';
import { Agent as HttpAgent } from 'node:http';
import { Agent as HttpsAgent } from 'node:https';
import ipRangeCheck from 'ip-range-check';
// All ranges that must be blocked for SSRF safety on a cloud deployment
const BLOCKED_IP_RANGES = [
'169.254.0.0/16', // Link-local — AWS IMDS, GCP IMDS, Azure IMDS, APIPA
'100.64.0.0/10', // Carrier-grade NAT — AWS internal services
'10.0.0.0/8', // RFC 1918 private
'172.16.0.0/12', // RFC 1918 private
'192.168.0.0/16', // RFC 1918 private
'127.0.0.0/8', // Loopback
'::1/128', // IPv6 loopback
'fc00::/7', // IPv6 unique local
'fe80::/10', // IPv6 link-local
];
const ALLOWED_SCHEMES = new Set(['http:', 'https:']);
async function fetchWithSsrfProtection(urlString: string): Promise<Response> {
// 1. Parse and validate URL scheme
let parsed: URL;
try {
parsed = new URL(urlString);
} catch {
throw new Error('Invalid URL');
}
if (!ALLOWED_SCHEMES.has(parsed.protocol)) {
throw new Error(`Scheme not allowed: ${parsed.protocol} — only http and https are permitted`);
}
// 2. Resolve DNS once and check the resulting IP
const { address: resolvedIp, family } = await dns.lookup(parsed.hostname);
if (ipRangeCheck(resolvedIp, BLOCKED_IP_RANGES)) {
throw new Error(
`SSRF blocked: ${parsed.hostname} resolves to ${resolvedIp} ` +
`which is in a blocked IP range (link-local/private/loopback)`
);
}
// 3. Pin the HTTP agent to the validated resolved IP — prevents DNS rebinding
// (see SSRF6-003 for the DNS rebinding attack this defeats)
const lookupFn = (_: string, __: unknown, cb: Function) => cb(null, resolvedIp, family);
const AgentClass = parsed.protocol === 'https:' ? HttpsAgent : HttpAgent;
const pinnedAgent = new AgentClass({ lookup: lookupFn });
// 4. Fetch with pinned agent, no redirects (re-validate redirect targets separately)
return fetch(urlString, {
// @ts-ignore — undici/node-fetch agent option
agent: pinnedAgent,
redirect: 'manual', // Never follow redirects without re-validating the new URL
signal: AbortSignal.timeout(10_000),
headers: {
'User-Agent': 'SkillAudit-Research/1.0',
// Do NOT forward the request's Authorization header to external URLs
},
});
}
const server = new McpServer({ name: 'research-skill', version: '1.0.0' });
server.tool(
'fetch_url',
'Fetch the content of a web page for research',
{ url: z.string().url().max(2000) },
async ({ url }) => {
let response: Response;
try {
response = await fetchWithSsrfProtection(url);
} catch (err) {
return {
content: [{ type: 'text', text: `Error: ${(err as Error).message}` }],
isError: true,
};
}
if (response.status >= 300 && response.status < 400) {
// Redirect detected — do NOT follow; return error so Claude can handle it
return {
content: [{ type: 'text', text: `Redirect to: ${response.headers.get('location')} — not followed` }],
};
}
const text = await response.text();
// Limit response size to prevent memory exhaustion
return { content: [{ type: 'text', text: text.slice(0, 100_000) }] };
}
);
fetch() on an EC2 instance can reach http://169.254.169.254/latest/meta-data/iam/security-credentials/<role> and retrieve temporary IAM credentials (AccessKeyId, SecretAccessKey, Token) with the instance profile's full permissions; block the 169.254.0.0/16 and 100.64.0.0/10 ranges at the fetch layer after DNS resolution, pin the HTTP agent to the validated resolved IP to prevent DNS rebinding, and disallow all schemes other than http: and https:. Detection: SkillAudit flags tool handler implementations that call fetch(), axios(), got(), or node-fetch() with a user-supplied URL parameter without first resolving the hostname and checking the resolved IP against the 169.254.0.0/16 and 100.64.0.0/10 blocked ranges.SSRF6-002 — GCP and Azure IMDS endpoints reachable via same link-local range
The same 169.254.0.0/16 link-local range that hosts AWS IMDS also hosts the metadata services for Google Cloud Platform and Microsoft Azure. On GCP, the metadata server is accessible at both http://169.254.169.254/computeMetadata/v1/ and via the DNS name http://metadata.google.internal/computeMetadata/v1/. The GCP metadata API returns the service account access token at /computeMetadata/v1/instance/service-accounts/default/token and project-level secrets at /computeMetadata/v1/project/attributes/. On Azure, the IMDS is at http://169.254.169.254/metadata/instance with a required Metadata: true header; however, an SSRF that can supply custom headers can include this header. Azure IMDS returns managed identity tokens at /metadata/identity/oauth2/token.
Because all three major cloud providers use the same 169.254.0.0/16 range, a single IP range block at the fetch layer protects against all of them. The GCP DNS name metadata.google.internal resolves to 169.254.169.254, so the fix from SSRF6-001 (blocking the range after DNS resolution) also covers GCP hostname-based SSRF. The metadata.google.internal DNS name must be resolved and the resulting IP checked — blocking the string "metadata.google.internal" in a hostname check is insufficient because the attacker could use a different DNS name that also resolves to the same IP.
// VULNERABLE — skill running on GCP without IMDS protection
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { z } from 'zod';
const server = new McpServer({ name: 'data-fetch-skill', version: '1.0.0' });
server.tool(
'fetch_external_data',
'Fetch data from an external API endpoint',
{ endpoint: z.string().url() },
async ({ endpoint }) => {
// VULNERABLE on GCP: attacker supplies:
// endpoint = "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token"
// With header: "Metadata-Flavor: Google"
// This returns the GCP service account access token for the instance
//
// On Azure: endpoint = "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://management.azure.com/"
// With header: "Metadata: true"
// Returns the managed identity OAuth token for the VM
const response = await fetch(endpoint, {
headers: {
'Content-Type': 'application/json',
// If skill forwards user-supplied headers, attacker can add:
// 'Metadata-Flavor': 'Google' (required by GCP IMDS)
// 'Metadata': 'true' (required by Azure IMDS)
},
});
return { content: [{ type: 'text', text: await response.text() }] };
}
);
// Also vulnerable: skills that accept user-supplied HTTP headers to forward
server.tool(
'fetch_with_headers',
'Fetch a URL with custom headers',
{
url: z.string().url(),
headers: z.record(z.string()).optional(), // Attacker controls these headers
},
async ({ url, headers }) => {
// Even if url is validated against the IP blocklist, headers can include
// Metadata-Flavor: Google or Metadata: true which enable IMDS access
// if the url validation is incomplete
const response = await fetch(url, { headers });
return { content: [{ type: 'text', text: await response.text() }] };
}
);
// FIXED — block 169.254.0.0/16 after DNS resolution; strip dangerous IMDS headers
import dns from 'dns/promises';
import ipRangeCheck from 'ip-range-check';
import { Agent as HttpAgent } from 'node:http';
import { Agent as HttpsAgent } from 'node:https';
// Headers that enable cloud IMDS access — must never be forwarded to external URLs
const BLOCKED_REQUEST_HEADERS = new Set([
'metadata-flavor', // GCP IMDS authentication header
'metadata', // Azure IMDS authentication header
'x-aws-ec2-metadata-token', // AWS IMDSv2 session token
'x-aws-ec2-metadata-token-ttl-seconds', // AWS IMDSv2 TTL
]);
function sanitizeForwardedHeaders(headers: Record<string, string>): Record<string, string> {
const safe: Record<string, string> = {};
for (const [key, value] of Object.entries(headers)) {
// Strip headers that enable IMDS access
if (BLOCKED_REQUEST_HEADERS.has(key.toLowerCase())) {
console.warn(`Blocked IMDS header in forwarded request: ${key}`);
continue;
}
// Strip authorization headers — never forward credentials to external URLs
if (/^(authorization|cookie|x-auth|x-api-key)$/i.test(key)) {
continue;
}
// Limit header value length
safe[key] = String(value).slice(0, 1000);
}
return safe;
}
const BLOCKED_RANGES = [
'169.254.0.0/16', // All cloud IMDS (AWS, GCP, Azure) + link-local
'100.64.0.0/10', // AWS carrier-grade NAT internal services
'10.0.0.0/8',
'172.16.0.0/12',
'192.168.0.0/16',
'127.0.0.0/8',
'::1/128',
'fe80::/10',
];
async function safeFetch(
urlString: string,
extraHeaders: Record<string, string> = {}
): Promise<Response> {
const parsed = new URL(urlString);
if (!['http:', 'https:'].includes(parsed.protocol)) {
throw new Error(`Protocol not allowed: ${parsed.protocol}`);
}
// Resolve hostname and validate IP — covers both literal IPs and DNS names
// like metadata.google.internal which resolves to 169.254.169.254
const { address: ip, family } = await dns.lookup(parsed.hostname);
if (ipRangeCheck(ip, BLOCKED_RANGES)) {
throw new Error(`Request blocked: ${parsed.hostname} → ${ip} is in a restricted range`);
}
// Strip IMDS-enabling headers from any user-supplied headers
const safeHeaders = sanitizeForwardedHeaders(extraHeaders);
// Pin agent to the validated IP — prevents DNS rebinding between check and connect
const lookupFn = (_: string, __: unknown, cb: Function) => cb(null, ip, family);
const AgentClass = parsed.protocol === 'https:' ? HttpsAgent : HttpAgent;
const pinnedAgent = new AgentClass({ lookup: lookupFn });
return fetch(urlString, {
headers: safeHeaders,
// @ts-ignore
agent: pinnedAgent,
redirect: 'manual',
signal: AbortSignal.timeout(10_000),
});
}
http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token and Azure IMDS at http://169.254.169.254/metadata/identity/oauth2/token are both reachable via SSRF on the same 169.254.0.0/16 range; GCP additionally requires the Metadata-Flavor: Google header which an attacker can inject via a skill that forwards user-supplied headers; fix by blocking 169.254.0.0/16 after DNS resolution and stripping Metadata-Flavor, Metadata, and AWS IMDSv2 headers from any user-supplied header map before forwarding. Detection: SkillAudit flags tool handler implementations that accept a headers or requestHeaders parameter alongside a URL parameter without stripping known IMDS-enabling headers from the forwarded header map.SSRF6-003 — DNS rebinding to bypass IP allowlist — fix via resolved-IP pinning
An MCP skill implements an SSRF allowlist: it resolves the target hostname with dns.lookup(), checks the IP against a blocklist, and proceeds to fetch() if the IP is not in a blocked range. The flaw is that dns.lookup() and fetch() perform two independent DNS lookups. An attacker who controls a DNS server for their hostname sets the TTL to 0, ensuring no caching. The first lookup (at validation time) returns a legitimate public IP like 93.184.216.34 (example.com). The IP check passes. Before the TCP connection is initiated by fetch(), the DNS TTL expires, and the second lookup returns 169.254.169.254. The fetch() connects to the IMDS rather than the validated public IP.
The fix is to prevent the second DNS lookup entirely by injecting the already-resolved IP into the HTTP agent's lookup function. Node.js's http.Agent and https.Agent accept a custom lookup function that is called instead of the system's DNS resolver when establishing a TCP connection. By providing a function that immediately calls the callback with the already-validated IP, the HTTP client never makes a second DNS query. The host header sent to the server still contains the original hostname (which is correct for virtual-hosted services), but the TCP connection goes to the validated IP.
// VULNERABLE — two separate DNS lookups: validation and fetch are independent
import dns from 'dns/promises';
import ipRangeCheck from 'ip-range-check';
const BLOCKED = ['169.254.0.0/16', '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', '127.0.0.0/8'];
async function checkUrl(url: string): Promise<void> {
const { hostname } = new URL(url);
const { address } = await dns.lookup(hostname); // DNS lookup #1 — returns public IP
if (ipRangeCheck(address, BLOCKED)) {
throw new Error(`Blocked: ${address}`);
}
// Returns — validation passed with the public IP
}
export async function fetchContent(url: string): Promise<string> {
await checkUrl(url); // DNS lookup #1: 93.184.216.34 → passes
const response = await fetch(url); // DNS lookup #2: now returns 169.254.169.254
// TCP connection goes to 169.254.169.254 — IMDS is reached
return response.text();
}
// FIXED — single DNS resolution, validate IP, pin agent to prevent second lookup
import dns from 'dns/promises';
import ipRangeCheck from 'ip-range-check';
import { Agent as HttpAgent } from 'node:http';
import { Agent as HttpsAgent } from 'node:https';
const BLOCKED = [
'169.254.0.0/16', '100.64.0.0/10',
'10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16',
'127.0.0.0/8', '::1/128', 'fe80::/10',
];
export async function fetchContentSafe(urlString: string): Promise<string> {
const parsed = new URL(urlString);
if (!['http:', 'https:'].includes(parsed.protocol)) {
throw new Error('Only http and https are permitted');
}
// Single DNS resolution — validate and immediately pin the result
const { address: resolvedIp, family } = await dns.lookup(parsed.hostname);
if (ipRangeCheck(resolvedIp, BLOCKED)) {
throw new Error(
`SSRF blocked: ${parsed.hostname} resolves to ${resolvedIp} ` +
`in a blocked IP range`
);
}
// Custom lookup function that ALWAYS returns the already-validated IP
// No matter how many times the HTTP client calls this function,
// it gets the same validated IP — no second DNS query is made
const pinnedLookup = (
_hostname: string,
_options: unknown,
callback: (err: Error | null, addr: string, family: number) => void
) => {
callback(null, resolvedIp, family);
};
const AgentClass = parsed.protocol === 'https:' ? HttpsAgent : HttpAgent;
const pinnedAgent = new AgentClass({
lookup: pinnedLookup,
// Also set keepAlive: false so the agent is not reused across requests
// (the pinned IP is only valid for the current request's validated hostname)
keepAlive: false,
});
const response = await fetch(urlString, {
// @ts-ignore — node-fetch / undici agent option
agent: pinnedAgent,
redirect: 'manual', // Re-validate redirect targets separately
signal: AbortSignal.timeout(10_000),
});
if (response.status >= 300 && response.status < 400) {
// Redirect — do NOT follow automatically; re-run validation on redirect target
const location = response.headers.get('location');
throw new Error(`Redirect to ${location} — re-validate before following`);
}
// Limit response body size to prevent memory exhaustion
const reader = response.body?.getReader();
if (!reader) return '';
const chunks: Uint8Array[] = [];
let totalBytes = 0;
const MAX_BYTES = 5 * 1024 * 1024; // 5 MB limit
while (true) {
const { done, value } = await reader.read();
if (done) break;
totalBytes += value.byteLength;
if (totalBytes > MAX_BYTES) {
reader.cancel();
throw new Error('Response body exceeds 5 MB limit');
}
chunks.push(value);
}
return new TextDecoder().decode(Buffer.concat(chunks));
}
dns.lookup()) and the HTTP client's internal DNS resolution (fetch()): the attacker's DNS returns a valid public IP for the validation lookup and 169.254.169.254 for the HTTP client's lookup milliseconds later; fix by performing DNS resolution once, validating the IP, and injecting a custom lookup function into the http.Agent that always returns the pre-validated IP, eliminating any second DNS query. Detection: SkillAudit flags implementations where dns.lookup() or dns.resolve() is called before fetch() but no custom agent with a pinned lookup function is passed to the fetch() call.SSRF6-004 — Redis and MongoDB on localhost reached via SSRF or gopher:// protocol
MCP skills are commonly co-deployed with Redis (for caching and session storage) and MongoDB or PostgreSQL (for primary data) on the same host or within the same VPC subnet. If Redis is bound to 127.0.0.1:6379 without authentication (the default configuration for development Redis installations), an SSRF that can reach http://localhost:6379 will receive Redis's inline error response (-ERR wrong number of arguments), confirming the port is open and running Redis. More critically, if the HTTP client can be induced to use the gopher:// protocol scheme — which allows the client to send arbitrary TCP bytes to any host:port — an attacker can craft a gopher://localhost:6379/FLUSHALL URI that sends Redis commands directly to the server, bypassing HTTP framing entirely. The gopher:// scheme is not a valid HTTP URL scheme and must be blocked by the URL scheme allowlist.
The fix has two components. First, block loopback addresses (127.0.0.0/8 and ::1/128) at the IP validation layer, which prevents http://localhost:6379 from reaching Redis. Second, enforce a URL scheme allowlist that permits only http: and https:, rejecting gopher:, ftp:, file:, dict:, ldap:, and all other schemes. Even if the IP validation is bypassed (e.g., via DNS rebinding to 127.0.0.1), the scheme allowlist provides a second layer. Additionally, configure Redis in production with a strong password via requirepass and bind it to a non-loopback interface only accessible within the VPC.
// VULNERABLE — SSRF can reach Redis via localhost, and gopher:// is not blocked
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { z } from 'zod';
const server = new McpServer({ name: 'link-preview-skill', version: '1.0.0' });
server.tool(
'preview_url',
'Generate a link preview for a URL',
{ url: z.string().url() },
async ({ url }) => {
// VULNERABLE scenario 1: url = "http://127.0.0.1:6379/"
// HTTP GET to Redis port — Redis responds with:
// "-ERR wrong number of arguments for 'get' command"
// This confirms Redis is running on port 6379, unauthenticated
// VULNERABLE scenario 2: url = "gopher://127.0.0.1:6379/_FLUSHALL%0D%0A"
// gopher:// sends "FLUSHALL\r\n" directly to the Redis TCP socket
// Redis executes: FLUSHALL — wipes the entire cache/session store
// More dangerous payloads:
// gopher://127.0.0.1:6379/_SET%20session%3Aadmin%20%7B%22role%22%3A%22admin%22%7D%0D%0A
// This writes a fake admin session to Redis
// VULNERABLE scenario 3: url = "http://localhost:27017/"
// MongoDB on default port — HTTP GET sends an HTTP request to Mongo's TCP port
// Mongo responds with its server version info (unauthenticated)
const response = await fetch(url); // No scheme or IP validation
const html = await response.text();
// Parse OG tags for preview... (irrelevant to the vulnerability)
return { content: [{ type: 'text', text: html.slice(0, 1000) }] };
}
);
// FIXED — scheme allowlist blocks gopher://; IP blocklist blocks localhost; Redis auth
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { z } from 'zod';
import dns from 'dns/promises';
import ipRangeCheck from 'ip-range-check';
import { Agent as HttpAgent } from 'node:http';
import { Agent as HttpsAgent } from 'node:https';
const ALLOWED_SCHEMES = new Set(['http:', 'https:']);
// Explicitly listing blocked schemes for documentation — the allowlist handles all others
// 'gopher:' — arbitrary TCP byte injection to any host:port
// 'ftp:' — file server access and directory listing
// 'file:' — local filesystem read
// 'dict:' — DICT protocol, can probe services
// 'ldap:' — LDAP injection
// 'sftp:', 'ssh:' — SSH service probing
const BLOCKED_IP_RANGES = [
'127.0.0.0/8', // Loopback — blocks http://localhost:6379, http://127.0.0.1:27017
'::1/128', // IPv6 loopback
'169.254.0.0/16', // Link-local — AWS/GCP/Azure IMDS
'100.64.0.0/10', // AWS carrier-grade NAT
'10.0.0.0/8', // RFC 1918 private (adjust if skill needs to reach internal services)
'172.16.0.0/12', // RFC 1918 private
'192.168.0.0/16', // RFC 1918 private
'fc00::/7', // IPv6 unique local
'fe80::/10', // IPv6 link-local
];
async function fetchSafe(urlString: string): Promise<Response> {
let parsed: URL;
try {
parsed = new URL(urlString);
} catch {
throw new Error('Invalid URL');
}
// 1. Scheme allowlist — blocks gopher://, file://, ftp://, dict://, ldap://, etc.
if (!ALLOWED_SCHEMES.has(parsed.protocol)) {
throw new Error(
`URL scheme '${parsed.protocol}' is not permitted. ` +
`Only http: and https: are allowed.`
);
}
// 2. Reject URLs with explicit port numbers matching common internal services
// This is defense-in-depth — the IP blocklist is the primary control
const port = parseInt(parsed.port, 10);
if (!isNaN(port)) {
const BLOCKED_PORTS = new Set([6379, 6380, 27017, 27018, 5432, 3306, 1521, 2181, 9200]);
if (BLOCKED_PORTS.has(port)) {
throw new Error(`Port ${port} is a known internal service port and is blocked`);
}
}
// 3. DNS resolution + IP range validation
const { address: resolvedIp, family } = await dns.lookup(parsed.hostname);
if (ipRangeCheck(resolvedIp, BLOCKED_IP_RANGES)) {
throw new Error(
`Request to ${parsed.hostname} (${resolvedIp}) is blocked — ` +
`resolves to a loopback, link-local, or private IP range`
);
}
// 4. Pin agent to validated IP — prevents DNS rebinding (see SSRF6-003)
const lookupFn = (_: string, __: unknown, cb: Function) => cb(null, resolvedIp, family);
const AgentClass = parsed.protocol === 'https:' ? HttpsAgent : HttpAgent;
const pinnedAgent = new AgentClass({ lookup: lookupFn, keepAlive: false });
return fetch(urlString, {
// @ts-ignore
agent: pinnedAgent,
redirect: 'manual',
signal: AbortSignal.timeout(10_000),
});
}
// Also: configure Redis with authentication in production
// redis.conf: requirepass "$(openssl rand -base64 32)"
// And bind Redis to a specific non-loopback IP, not 0.0.0.0:
// redis.conf: bind 10.0.0.5 (VPC internal IP, not reachable from Internet)
const server = new McpServer({ name: 'link-preview-skill', version: '1.0.0' });
server.tool(
'preview_url',
'Generate a link preview for a URL',
{ url: z.string().url().max(2000) },
async ({ url }) => {
let response: Response;
try {
response = await fetchSafe(url);
} catch (err) {
return {
content: [{ type: 'text', text: `Error: ${(err as Error).message}` }],
isError: true,
};
}
if (response.status >= 300 && response.status < 400) {
return { content: [{ type: 'text', text: 'Redirect — not followed' }] };
}
const html = await response.text();
return { content: [{ type: 'text', text: html.slice(0, 50_000) }] };
}
);
localhost can be reached via SSRF to http://127.0.0.1:6379 (confirming the service is running) or via gopher://127.0.0.1:6379/_FLUSHALL (injecting arbitrary Redis commands by sending raw TCP bytes through the gopher protocol); fix by enforcing a URL scheme allowlist that permits only http: and https: (blocking gopher:, file:, ftp:, dict:, and all others), blocking 127.0.0.0/8 and ::1/128 at the IP validation layer, and configuring Redis with requirepass and binding to a non-loopback interface. Detection: SkillAudit flags tool handler implementations where the URL scheme is not validated against an allowlist before the outbound request is made, and separately flags Redis or MongoDB client configurations that use loopback addresses without authentication.Detection summary
| ID | Severity | Pattern | Fix |
|---|---|---|---|
| SSRF6-001 | CRITICAL | AWS IMDSv1 at 169.254.169.254 — unrestricted fetch() returns IAM credentials with instance profile permissions |
Block 169.254.0.0/16 and 100.64.0.0/10 after DNS resolution; pin agent to validated IP |
| SSRF6-002 | CRITICAL | GCP metadata.google.internal and Azure 169.254.169.254/metadata — same link-local range; skills that forward headers enable IMDS auth headers |
Block 169.254.0.0/16 after DNS resolution; strip Metadata-Flavor, Metadata, and AWS IMDSv2 headers |
| SSRF6-003 | HIGH | DNS rebinding: TTL-0 returns public IP at validation, loopback/link-local at TCP connection — two-lookup gap | Single dns.lookup(); custom agent.lookup function pins connection to validated IP |
| SSRF6-004 | CRITICAL | Redis/MongoDB on localhost via http://localhost:6379 or gopher://localhost:6379/_FLUSHALL — unauthenticated command injection |
Scheme allowlist (http/https only); block 127.0.0.0/8; Redis requirepass + non-loopback bind |
Related patterns: SA-SKL-SSRF4 covers SSRF via cloud metadata endpoints with AWS IMDSv2 session token requirements and VPC DNS probing. SA-SKL-SSRF5 covers blind SSRF via DNS callbacks and timing channels where the response body is never returned to the attacker. SA-SKL-SSRF3 covers SSRF via URL parsing inconsistencies including IPv6 bypass and authority confusion.