Claude skill advanced SSRF security
Basic SSRF prevention checks for localhost and 127.0.0.1 in URL inputs are a starting point, not a complete defense. SA-SKL-SSRF2 covers the four bypass patterns that defeat hostname and scheme allowlist checks in real MCP skill codebases: non-HTTPS URL scheme bypass that accesses the local file system, DNS rebinding that changes what a hostname resolves to after the allowlist check passes, cloud provider metadata endpoints that expose IAM credentials to any network-reachable SSRF, and redirect chains that begin at an allowlisted URL and end at an internal network address. Each of these has caused production credential exfiltration in MCP skill deployments running on cloud VMs.
MCP skills frequently include tools that fetch URLs on behalf of users: fetch_url, read_webpage, import_config, clone_repo. Each of these is an SSRF entry point. The basic SSRF allowlist pattern — check if the hostname is in an allowed set, block localhost and 127.0.0.1 — fails against all four SA-SKL-SSRF2 patterns. URL scheme bypass works because allowlist checks typically only verify the hostname, not the scheme; file:///etc/passwd has no hostname to block. DNS rebinding works because the allowlist check and the actual HTTP request perform separate DNS lookups; an attacker controls the second lookup. Cloud metadata exploitation works because the metadata address 169.254.169.254 is a valid IP that is not localhost or 127.0.0.1, so a simple blocklist misses it. Redirect chains work because redirect following is a feature, and each hop resets the SSRF check to the new URL without re-validating it against the network-layer blocklist.
SA-SKL-SSRF2-001: URL scheme bypass — file:///, dict://, gopher:// evade https:// checks
SSRF allowlist implementations commonly check that the URL starts with https:// or parse the hostname and verify it against an allowed list. Both checks can be bypassed when Node.js’s fetch() or HTTP libraries support non-HTTPS URL schemes. The file:// scheme reads local files and has no hostname to block. The dict://, gopher://, and ftp:// schemes may be supported by underlying curl bindings in some Node.js HTTP libraries and can be used to reach internal services on non-HTTP protocols or to construct arbitrary TCP payloads to Redis and Memcached:
// VULNERABLE: allowlist check verifies hostname only — scheme is not validated
import fetch from 'node-fetch';
async function fetchUrlTool(args: { url: string }): Promise<string> {
const parsed = new URL(args.url); // parses URL but does not validate scheme
const allowedHosts = new Set(['github.com', 'raw.githubusercontent.com', 'api.github.com']);
// Check hostname but not scheme
if (!allowedHosts.has(parsed.hostname)) {
throw new Error('URL hostname not in allowlist');
}
// parsed.hostname passes for file:// URL because file:// has empty hostname
// new URL('file:///etc/passwd').hostname === '' — not in allowedHosts, so this case fails
// BUT:
const resp = await fetch(args.url); // <-- if scheme is not validated, file:// could pass
return resp.text();
}
// BYPASS 1: file:// URL — hostname is empty string, may pass !allowedHosts check
// if the check is: if (parsed.hostname && !allowedHosts.has(parsed.hostname))
// file:// has hostname = '' which is falsy — the check is skipped
// new URL('file:///etc/passwd').hostname === ''
// fetch('file:///etc/passwd') reads /etc/passwd in some environments
// BYPASS 2: Scheme-only check can be bypassed by double-encoding
// url = 'https://github.com@169.254.169.254/'
// new URL(url).hostname === '169.254.169.254' (@ separates credentials from host)
// But simpler: if scheme check is startsWith('https://'), dict:// passes if
// the developer only checks for 'http://' and 'ftp://' in a blocklist
// REAL ATTACK — URL with @ credential separator:
// 'https://github.com@169.254.169.254/latest/meta-data/iam/security-credentials/'
// new URL(that).hostname === '169.254.169.254' — hostname check catches this
// BUT if check is: url.startsWith('https://github.com') — bypass with:
// 'https://github.com.attacker.com/' — passes startsWith, different hostname
// SECURE: explicitly validate protocol AFTER parsing; never use string prefix checks
async function fetchUrlSecure(args: { url: string }): Promise<string> {
let parsed: URL;
try {
parsed = new URL(args.url);
} catch {
throw new Error('Invalid URL');
}
// 1. Enforce HTTPS-only: parsed.protocol must be exactly 'https:'
if (parsed.protocol !== 'https:') {
throw new Error(`URL scheme '${parsed.protocol}' is not permitted; only https: is allowed`);
}
// 2. Reject URLs with credentials in the authority component
if (parsed.username || parsed.password) {
throw new Error('URLs with credentials (@) in the host component are not permitted');
}
// 3. Validate hostname against explicit allowlist (after scheme and credential check)
const allowedHosts = new Set(['github.com', 'raw.githubusercontent.com', 'api.github.com']);
if (!allowedHosts.has(parsed.hostname)) {
throw new Error(`URL hostname '${parsed.hostname}' is not in the allowlist`);
}
// 4. Resolve hostname to IP and block private/loopback ranges at network layer
// (see SSRF2-002 for DNS rebind protection)
const resolvedIp = await dns.promises.lookup(parsed.hostname, { family: 4 });
assertNotPrivateIp(resolvedIp.address); // throws if RFC1918 or loopback
const resp = await fetch(args.url, {
redirect: 'manual', // do NOT follow redirects automatically — see SSRF2-004
});
if (resp.status >= 300 && resp.status < 400) {
throw new Error('Redirects are not permitted for security reasons');
}
return resp.text();
}
function assertNotPrivateIp(ip: string): void {
// Block loopback, link-local (metadata), and RFC1918 private ranges
const blocked = [
/^127\./, /^0\./, /^::1$/, /^169\.254\./,
/^10\./, /^172\.(1[6-9]|2\d|3[01])\./, /^192\.168\./,
];
if (blocked.some(r => r.test(ip))) {
throw new Error(`Resolved IP ${ip} is a private/reserved address`);
}
}
Parse the URL with new URL() then check parsed.protocol — do not use string prefix checks: url.startsWith('https://') can be bypassed by encoding, Unicode normalization, or by inserting credential components that contain the expected prefix (https://github.com@attacker.com/). After parsing, parsed.protocol returns the normalized lowercase scheme including the colon: 'https:', 'file:', 'ftp:'. Checking exact equality against 'https:' is the only bypass-resistant scheme validation. Additionally, check for credentials in parsed.username and parsed.password — a URL with an @ separator before the hostname is a common allowlist bypass technique.
file:// URL with empty hostname bypasses hostname allowlist; https://allowedhost@evil.com/ credential-in-host bypass; non-HTTPS scheme support reads local files or reaches internal TCP services. Fix: parse with new URL(); check parsed.protocol === 'https:' exactly; reject URLs with parsed.username or parsed.password; validate hostname against allowlist after both checks. Detection: new URL(args.url) followed by hostname check without protocol check → HIGH.SA-SKL-SSRF2-002: DNS rebind to localhost after allowlist check — second DNS resolution returns 127.0.0.1
DNS rebinding works by exploiting the gap between when a URL hostname is validated against an allowlist and when the actual TCP connection is established. If the allowlist check and the HTTP request each trigger a separate DNS lookup for the same hostname, an attacker who controls DNS for that hostname can return a benign IP during the allowlist check and then immediately switch the DNS record to 127.0.0.1 or any internal IP. The HTTP request uses the second lookup result — which now resolves to a localhost or private address — and the allowlist check is irrelevant because it passed before the DNS switch:
// VULNERABLE: allowlist check and fetch() use separate DNS lookups
// (The classic time-of-check/time-of-use SSRF vulnerability)
import dns from 'dns/promises';
import fetch from 'node-fetch';
async function fetchWithDnsCheck(args: { url: string }): Promise<string> {
const parsed = new URL(args.url);
// STEP 1: Resolve hostname to verify it is not private
const resolved = await dns.lookup(parsed.hostname, { family: 4 });
assertNotPrivateIp(resolved.address); // passes: attacker DNS returns 1.2.3.4 here
// TIME WINDOW: attacker changes DNS A record from 1.2.3.4 to 127.0.0.1
// with TTL=0, the OS DNS cache does not persist this record
// The gap between lookup() and fetch() is typically 1-50ms
// With enough parallel requests, attacker wins the race
// STEP 2: fetch() performs its own DNS lookup for the same hostname
const response = await fetch(args.url); // <-- DNS lookup returns 127.0.0.1 now
return response.text(); // request goes to localhost skill process
}
// ATTACK SETUP:
// 1. Attacker registers: attacker-allowed.example.com with CNAME to attacker DNS server
// 2. Attacker DNS server: for first N queries, return 1.2.3.4 (passes allowlist)
// After query N, return 127.0.0.1 or 169.254.169.254
// 3. Attacker calls the fetch_url tool with URL https://attacker-allowed.example.com/
// If attacker DNS returns 1.2.3.4: allowlist passes, fetch goes to 1.2.3.4 (benign)
// If attacker DNS returns 127.0.0.1: assertNotPrivateIp throws (rejected)
// 4. Attacker repeats with many parallel requests until timing works:
// assertNotPrivateIp lookup → 1.2.3.4 (passes) | fetch lookup → 127.0.0.1 (goes to localhost)
// 5. fetch() reaches http://127.0.0.1:[PORT]/ — the skill's own management interface,
// an internal Redis, Prometheus /metrics, or other localhost-bound service
// SECURE: resolve hostname ONCE and use the resolved IP for the connection
// Pin the connection to the resolved IP — no second DNS lookup occurs
import { Agent } from 'https';
import dns from 'dns/promises';
import { connect } from 'tls';
async function fetchWithIpPinning(args: { url: string }): Promise<string> {
const parsed = new URL(args.url);
if (parsed.protocol !== 'https:') throw new Error('Only https: permitted');
// Resolve hostname to IP — single authoritative lookup
const resolved = await dns.lookup(parsed.hostname, { family: 4 });
assertNotPrivateIp(resolved.address); // block private ranges before proceeding
// Construct URL using the resolved IP directly
// Set Host header to the original hostname for TLS SNI + virtual host routing
const ipUrl = `https://${resolved.address}${parsed.pathname}${parsed.search}`;
const response = await fetch(ipUrl, {
headers: {
Host: parsed.hostname, // SNI + Host header uses original hostname
},
agent: new Agent({
// Verify TLS cert against the original hostname (not the IP)
checkServerIdentity: (host, cert) => {
// Override: TLS check should verify parsed.hostname, not resolved.address
return require('tls').checkServerIdentity(parsed.hostname, cert);
},
}),
redirect: 'manual', // do not follow redirects (see SSRF2-004)
});
if (response.status >= 300) throw new Error('Redirects not permitted');
return response.text();
}
DNS rebind races the check window, not the DNS TTL: A common misconception is that DNS rebinding requires waiting for the DNS TTL to expire before the attack can work. With a TTL of 0 (or 1 second), there is no OS-level cache, so each call to dns.lookup() is a live DNS query. The race is between the allowlist check’s DNS lookup and the fetch’s DNS lookup — a window of milliseconds. With enough parallel requests, an attacker who controls DNS for the hostname will win the race within seconds. The only defense is to ensure the IP address used for the actual TCP connection is the same address that was checked.
dns.lookup() and then passes URL to fetch() which performs a second independent DNS lookup: attacker-controlled DNS serves benign IP during check, switches to 127.0.0.1 or 169.254.169.254 before fetch; check passes, request reaches localhost or cloud metadata. Fix: resolve hostname once; construct the fetch URL with the resolved IP; pin TLS SNI to the original hostname; set redirect: 'manual'. Detection: dns.lookup(parsed.hostname) followed by fetch(args.url) without IP-pinning → HIGH.SA-SKL-SSRF2-003: Cloud metadata endpoint via SSRF — IAM credentials from 169.254.169.254
All major cloud providers — AWS, GCP, Azure — expose an instance metadata endpoint at the link-local address 169.254.169.254. On AWS, the endpoint at http://169.254.169.254/latest/meta-data/iam/security-credentials/<role-name> returns a JSON document containing a temporary AccessKeyId, SecretAccessKey, and Token for the EC2 instance’s IAM role. These credentials have the full permissions of the IAM role attached to the instance — which in MCP skill deployments often includes S3 read/write, Secrets Manager access, and RDS access. A single SSRF request to this endpoint exfiltrates credentials that grant an attacker access to every AWS service the skill uses:
// VULNERABLE: SSRF allowlist blocks 127.0.0.1 and localhost but not 169.254.0.0/16
function isPrivateIp(ip: string): boolean {
return (
ip === '127.0.0.1' ||
ip === '::1' ||
ip.startsWith('10.') ||
ip.startsWith('192.168.') ||
/^172\.(1[6-9]|2\d|3[01])\./.test(ip)
// MISSING: 169.254.0.0/16 (link-local / metadata)
);
}
// ATTACK: tool call with URL targeting cloud metadata
// args.url = 'http://169.254.169.254/latest/meta-data/iam/security-credentials/'
// Hostname: '169.254.169.254' — not in hostname blocklist
// IP: 169.254.169.254 — not caught by isPrivateIp (missing 169.254 range)
// fetch() makes request to metadata endpoint
// Response: list of IAM role names (e.g., 'skillaudit-ec2-role')
//
// Follow-up: 'http://169.254.169.254/latest/meta-data/iam/security-credentials/skillaudit-ec2-role'
// Response:
// {
// "AccessKeyId": "ASIA...",
// "SecretAccessKey": "...",
// "Token": "...",
// "Expiration": "2026-11-04T10:00:00Z"
// }
//
// Attacker now has valid AWS credentials valid for ~6 hours.
// IAM role may include: s3:GetObject on audit storage, secretsmanager:GetSecretValue,
// rds-db:connect, ses:SendEmail (spam from your domain).
// CLOUD-SPECIFIC METADATA ENDPOINTS:
// AWS: http://169.254.169.254/latest/meta-data/ (IMDSv1 — no auth required)
// http://169.254.169.254/latest/meta-data/ (IMDSv2 — requires PUT to get token first)
// http://[fd00:ec2::254]/latest/meta-data/ (IPv6 variant in newer AWS instances)
// GCP: http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token
// http://169.254.169.254/computeMetadata/v1/ (same endpoint, numeric IP)
// Azure: http://169.254.169.254/metadata/instance?api-version=2021-02-01
// http://169.254.169.254/metadata/identity/oauth2/token?resource=...
// SECURE: block 169.254.0.0/16 (link-local) and all metadata hostnames
function assertNotPrivateOrMetadataIp(ip: string): void {
const blockedRanges = [
/^127\./, // loopback
/^0\./, // current network
/^::1$/, // IPv6 loopback
/^169\.254\./, // link-local (METADATA — most critical)
/^fd00:ec2::/, // AWS IPv6 metadata
/^10\./, // RFC1918 private
/^172\.(1[6-9]|2\d|3[01])\./, // RFC1918 private
/^192\.168\./, // RFC1918 private
/^100\.(6[4-9]|[7-9]\d|1[01]\d|12[0-7])\./, // CGNAT (RFC6598)
/^fc00:/, /^fe80:/, // IPv6 unique local + link-local
/^ff/, // IPv6 multicast
];
if (blockedRanges.some(r => r.test(ip))) {
throw new Error(`Resolved IP ${ip} is a blocked private/metadata/reserved address`);
}
}
// Block metadata hostnames before DNS resolution (defense in depth):
function assertNotMetadataHostname(hostname: string): void {
const blockedHosts = new Set([
'metadata.google.internal',
'metadata.goog',
'instance-data', // some cloud provider local aliases
]);
if (blockedHosts.has(hostname.toLowerCase())) {
throw new Error(`Hostname '${hostname}' is a cloud metadata endpoint and is blocked`);
}
}
// AWS IMDSv2 mitigation at infrastructure level:
// In AWS EC2 instance metadata settings, set:
// HttpTokens: required (IMDSv2 — requires PUT request with TTL header to get session token)
// HttpPutResponseHopLimit: 1 (prevents requests from containers inside the VM from reaching metadata)
// This does NOT prevent direct SSRF to 169.254.169.254 from the host process,
// but it blocks container-to-metadata pivots and accidental metadata access.
// Application-level IP blocking is still required.
The AWS metadata endpoint at 169.254.169.254 returns IAM credentials valid for 6 hours with the full permissions of the EC2 instance role: A single SSRF request to http://169.254.169.254/latest/meta-data/iam/security-credentials/<role> (IMDSv1) returns a JSON object with AccessKeyId, SecretAccessKey, and Token. These credentials are immediately usable with the AWS SDK or CLI. If the EC2 role has s3:GetObject, secretsmanager:GetSecretValue, or any database or messaging permissions, the attacker has those permissions for 6 hours with no additional steps. Enable IMDSv2 at the instance level AND block 169.254.0.0/16 at the application level — two independent layers of defense.
169.254.0.0/16 range: attacker requests http://169.254.169.254/latest/meta-data/iam/security-credentials/<role>; response contains AWS IAM AccessKeyId + SecretAccessKey + session Token; credentials exfiltrated via tool result returned to Claude model; attacker escalates to full IAM role permissions. Fix: add /^169\.254\./ to IP blocklist; block metadata hostnames before DNS resolution; require IMDSv2 at the AWS instance level. Detection: IP blocklist without 169.254 range in SSRF protection function → CRITICAL.SA-SKL-SSRF2-004: Redirect following expands SSRF surface — redirect chain reaches internal IP
HTTP redirect following (302, 301, 307) is enabled by default in Node.js fetch() and most HTTP client libraries. SSRF allowlist checks are applied to the initial URL before the request is made. If the initial URL passes the allowlist check but the server at that URL responds with a redirect to an internal IP or private hostname, the HTTP client follows the redirect to the new URL without repeating the SSRF validation. The initial URL can be entirely legitimate (a real GitHub URL, an allowed API endpoint) while the redirect destination is http://10.0.0.1/admin or http://169.254.169.254/latest/meta-data/:
// VULNERABLE: fetch() follows redirects by default; SSRF check only applied to initial URL
import fetch from 'node-fetch';
async function fetchUrlTool(args: { url: string }): Promise<string> {
const parsed = new URL(args.url);
if (parsed.protocol !== 'https:') throw new Error('https only');
// Check only the initial URL
const resolvedIp = await dns.lookup(parsed.hostname);
assertNotPrivateIp(resolvedIp.address); // passes for github.com
// fetch() follows all redirects without re-running SSRF validation on each hop
const resp = await fetch(args.url); // default: follow: 'follow'
return resp.text();
}
// ATTACK CHAIN:
// args.url = 'https://github.com/attacker/redirect-to-metadata'
// DNS for github.com → 140.82.112.4 (passes assertNotPrivateIp)
// fetch() makes GET to github.com
// GitHub redirects (302) to: http://169.254.169.254/latest/meta-data/iam/security-credentials/
// fetch() follows redirect — no SSRF check on the redirect target
// Response: AWS IAM credentials
// REALISTIC OPEN REDIRECT CHAIN:
// url = 'https://raw.githubusercontent.com/attacker/skill/main/redirect.php'
// GitHub serves a PHP redirect to attacker.com
// attacker.com redirects to http://10.0.0.1/internal-api (internal VPC endpoint)
// fetch() follows all hops; internal API is reached on hop 3
// REDIRECT SSRF WITH URL SHORTENERS:
// url = 'https://bit.ly/XXXXX' (bit.ly is in some allowlists)
// bit.ly redirects to any URL the account holder configured
// Attacker registers a bit.ly URL pointing to http://169.254.169.254/
// SECURE: disable redirect following; validate each redirect hop before following
// Option 1: refuse all redirects
const resp = await fetch(args.url, { redirect: 'manual' });
if (resp.status >= 300 && resp.status < 400) {
throw new Error(`Redirect responses are not permitted (received ${resp.status})`);
}
// Option 2: follow redirects with per-hop SSRF re-validation (max 3 hops)
async function fetchWithSafeRedirects(url: string, maxHops = 3): Promise<Response> {
let currentUrl = url;
for (let hop = 0; hop < maxHops; hop++) {
// Validate current URL before requesting
const parsed = new URL(currentUrl);
if (parsed.protocol !== 'https:') throw new Error(`Redirect to non-https scheme: ${parsed.protocol}`);
if (parsed.username || parsed.password) throw new Error('Redirect with credentials in URL');
const resolved = await dns.lookup(parsed.hostname, { family: 4 });
assertNotPrivateOrMetadataIp(resolved.address); // includes 169.254.0.0/16
const resp = await fetch(currentUrl, { redirect: 'manual' });
if (resp.status < 300 || resp.status >= 400) return resp; // non-redirect: done
// Extract redirect target
const location = resp.headers.get('Location');
if (!location) throw new Error('Redirect with no Location header');
// Resolve relative redirect to absolute URL using current base
currentUrl = new URL(location, currentUrl).toString();
}
throw new Error(`Too many redirects (max ${maxHops})`);
}
Redirect following is SSRF follow-on; every redirect hop must be re-validated: The standard HTTP client redirect pattern of “follow Location header transparently” was designed for browser navigation where every URL is externally visible. For server-side requests, every redirect hop is a potential SSRF pivot: the initial URL is controlled by the attacker, the second URL is controlled by the server at the first hop, and the nth URL may be an internal IP that the attacker has no direct control over but can predict. The fix is either to never follow redirects (redirect: 'manual') or to apply the full SSRF validation stack to every hop’s destination URL before following it, with a redirect depth limit of 3 to prevent infinite redirect chains.
fetch(url) with default redirect following (or explicit redirect: 'follow'): SSRF check applied only to initial URL; allowlisted URL redirects to internal IP, cloud metadata, or private hostname; fetch follows redirect without re-validation; internal service reached on redirect hop. Fix: set redirect: 'manual' and reject redirect responses; or implement per-hop SSRF re-validation with max 3 hops and full IP blocklist check on each resolved hostname. Detection: fetch( with redirect: 'follow' or no redirect option alongside SSRF URL validation code → HIGH.Remediation summary
| Finding | Severity | Vulnerable pattern | Fix | Detection signal |
|---|---|---|---|---|
| SSRF2-001: URL scheme bypass | HIGH | Allowlist checks hostname but not scheme; file:// has empty hostname; https://host@evil.com/ credential bypass |
Parse URL with new URL(); require parsed.protocol === 'https:'; reject URLs with credentials |
new URL(args.url) followed by hostname check without parsed.protocol check |
| SSRF2-002: DNS rebind post-allowlist-check | HIGH | Separate DNS lookups for allowlist check and fetch(); attacker switches DNS between lookups | Resolve hostname once; construct fetch URL with resolved IP; pin TLS SNI to original hostname | dns.lookup(parsed.hostname) followed by fetch(args.url) without IP pinning |
| SSRF2-003: Cloud metadata endpoint | CRITICAL | IP blocklist missing 169.254.0.0/16; attacker requests IAM credentials at 169.254.169.254 |
Add /^169\.254\./ to IP blocklist; block metadata hostnames; enable IMDSv2 at AWS instance level |
IP blocklist function without 169.254 range in SSRF protection code |
| SSRF2-004: Redirect chain SSRF expansion | HIGH | fetch() with default redirect following; allowlisted URL redirects to internal IP without re-validation |
Set redirect: 'manual' and reject redirects; or validate each hop with full SSRF stack + 3-hop max |
fetch(url) with default or explicit redirect: 'follow' alongside SSRF validation code |
SkillAudit detects all four SA-SKL-SSRF2-001 through SSRF2-004 patterns through static analysis and dataflow tracing: URL parsing without scheme validation, DNS lookup / fetch separation without IP pinning, IP blocklist functions missing the 169.254 link-local range, and fetch() calls with default redirect following alongside URL validation. For related security patterns see SA-SKL-NET network egress security, SA-SKL-TLS certificate validation security, and SA-SKL-DNS DNS rebinding security. See the complete SA-SKL attack surface reference for the full vulnerability taxonomy.
Scan your Claude skill for advanced SSRF vulnerabilities
SkillAudit detects URL scheme bypass, DNS rebind attacks, cloud metadata endpoint exposure, and redirect chain SSRF across the full SA-SKL-SSRF2 family in 60 seconds.
Get your free audit