← Blog

Claude skill SSRF via URL parsing inconsistencies — SA-SKL-SSRF7

URL parsing is not a solved problem. The WHATWG URL Standard, Node.js's new URL(), the urllib module, cURL, and browser fetch() all interpret edge-case URLs differently — and SSRF defenses built on the wrong parser lose. SA-SKL-SSRF7 covers four URL-parsing-inconsistency patterns that bypass naive SSRF blocklists in Claude MCP skills: IPv6 loopback addresses invisible to an IPv4-only blocklist, @ URL authority confusion that hides the true destination host, Unicode characters that normalize to blocklisted internal domains, and CRLF injection in URL path components that splits an HTTP request at a forwarding proxy.

By SkillAudit  |  7 Nov 2026

Why URL parsing inconsistencies break SSRF defenses

An SSRF defense is only as correct as the URL parser it uses to extract the hostname and IP address before validation. When an MCP skill's validation logic and its HTTP client parse the same URL string differently, the client connects to a host that the validation step never evaluated. This class of vulnerability is distinct from bypasses based on blocked IP ranges: even a perfectly accurate IP blocklist fails if the wrong hostname is extracted from the URL and resolved.

Three common mistakes underlie SA-SKL-SSRF7 findings. First, performing hostname extraction with string operations (url.split('/')[2], regex.exec(url), url.includes()) rather than a standards-compliant URL parser. Second, checking the raw input string rather than the normalized output of new URL(). Third, checking IPv4 ranges while ignoring IPv6 representations of the same addresses. Each of these creates a gap that maps directly to one of the four SSRF7 patterns below.

SA-SKL-SSRF7 in scope: SSRF7-001 (IPv6 loopback [::1] and IPv4-mapped ::ffff:127.0.0.1 bypass an IPv4-only 127.0.0.0/8 blocklist), SSRF7-002 (URL authority confusion — http://skillaudit.dev@169.254.169.254/ passes a string includes() check but connects to IMDS), SSRF7-003 (Unicode circled letters normalize via IDNA/Punycode to blocklisted internal hostnames; raw-string blocklist does not match the Unicode form), SSRF7-004 (CRLF %0D%0A in URL path injects a second HTTP request at the proxy layer). Each finding includes SkillAudit detection rules and correct Node.js fixes.

SSRF7-001 — IPv6 loopback [::1] bypasses IPv4-only blocklist

An MCP skill wraps outbound HTTP requests with an SSRF guard that calls ipRangeCheck(ip, ['127.0.0.0/8']) to block loopback traffic. The check is correct for IPv4 — 127.0.0.1, 127.0.0.2, and all addresses in 127.0.0.0/8 are blocked. However, it does not cover the IPv6 loopback address ::1, which is the IPv6 equivalent of 127.0.0.1. When an attacker supplies http://[::1]/admin, the URL is syntactically valid (IPv6 literals in URLs are written inside square brackets per RFC 2732). Node.js's new URL('http://[::1]/admin').hostname returns [::1], and dns.lookup('[::1]') resolves to ::1 with family 6. The ipRangeCheck('::1', ['127.0.0.0/8']) call returns false because ::1 is not in the IPv4 range 127.0.0.0/8 — it is in the IPv6 range ::1/128. The check passes, and the request hits the local server on its IPv6 stack.

The same bypass applies to IPv4-mapped IPv6 addresses. The address ::ffff:127.0.0.1 is a valid way to express IPv4 127.0.0.1 in IPv6 notation, commonly used when a dual-stack socket receives an IPv4 connection. Some DNS resolvers and OS stacks return IPv4-mapped IPv6 addresses from dns.lookup() when the system is configured for dual-stack. A blocklist that checks only 127.0.0.0/8 misses ::ffff:127.0.0.0/104. The fix requires blocking all three ranges: 127.0.0.0/8 (IPv4 loopback), ::1/128 (IPv6 loopback), and ::ffff:127.0.0.0/104 (IPv4-mapped IPv6 loopback). Additionally, dns.lookup() must be called with the raw hostname extracted by new URL().hostname after stripping the square brackets from IPv6 literals, and the returned address must be checked against all three ranges.

// VULNERABLE — IPv4-only loopback block; [::1] and ::ffff:127.0.0.1 pass unchecked
import dns from 'dns/promises';
import ipRangeCheck from 'ip-range-check';

// Only IPv4 loopback is blocked — IPv6 loopback is not covered
const BLOCKED_RANGES_INCOMPLETE = [
  '127.0.0.0/8',    // IPv4 loopback only
  '169.254.0.0/16', // Link-local
  '10.0.0.0/8',
  '172.16.0.0/12',
  '192.168.0.0/16',
];

async function validateUrl_VULNERABLE(urlString: string): Promise<void> {
  const parsed = new URL(urlString);

  // dns.lookup strips brackets from IPv6 literals like [::1] automatically
  const { address: resolvedIp } = await dns.lookup(parsed.hostname);

  // VULNERABLE: ipRangeCheck('::1', ['127.0.0.0/8']) === false
  // ::1 is NOT in 127.0.0.0/8 — it is an IPv6 address in ::1/128
  // So this check passes, and the request proceeds to the local server
  if (ipRangeCheck(resolvedIp, BLOCKED_RANGES_INCOMPLETE)) {
    throw new Error(`Blocked IP: ${resolvedIp}`);
  }

  // ALSO VULNERABLE: ::ffff:127.0.0.1 (IPv4-mapped IPv6)
  // ipRangeCheck('::ffff:127.0.0.1', ['127.0.0.0/8']) === false
  // The IPv4-mapped form is not in the IPv4 CIDR — it needs ::ffff:127.0.0.0/104
}

// Attack: attacker supplies http://[::1]/internal-api/admin
// parsed.hostname === '[::1]'
// dns.lookup resolves to ::1, family 6
// ipRangeCheck('::1', ['127.0.0.0/8']) === false → check passes
// fetch connects to [::1]:80 — the local server's IPv6 loopback interface

// Attack variant: http://[::ffff:127.0.0.1]/admin
// dns.lookup resolves to ::ffff:127.0.0.1
// ipRangeCheck('::ffff:127.0.0.1', ['127.0.0.0/8']) === false → check passes
// FIXED — block IPv4 loopback, IPv6 loopback, AND IPv4-mapped IPv6 loopback
import dns from 'dns/promises';
import ipRangeCheck from 'ip-range-check';
// npm install ip-address is-ip
import { Address4, Address6 } from 'ip-address';

// Complete loopback + private + link-local blocklist covering IPv4 and IPv6
const BLOCKED_RANGES = [
  // Loopback — all three representations
  '127.0.0.0/8',           // IPv4 loopback: 127.0.0.1 ... 127.255.255.255
  '::1/128',               // IPv6 loopback: [::1]
  '::ffff:127.0.0.0/104',  // IPv4-mapped IPv6 loopback: ::ffff:127.0.0.1 etc.

  // Link-local — cloud IMDS (AWS, GCP, Azure)
  '169.254.0.0/16',
  'fe80::/10',             // IPv6 link-local

  // Private ranges
  '10.0.0.0/8',
  '172.16.0.0/12',
  '192.168.0.0/16',
  'fc00::/7',              // IPv6 unique local (fc00:: and fd00::)

  // AWS carrier-grade NAT
  '100.64.0.0/10',
];

// Normalize an IP address to its canonical form for consistent comparison.
// Handles IPv4-mapped IPv6 addresses (::ffff:a.b.c.d) by extracting the
// embedded IPv4 address so it matches the IPv4 CIDR rules as well.
function normalizeIp(ip: string): string[] {
  // Return both the original address and, if IPv4-mapped, the embedded IPv4
  const candidates = [ip];
  try {
    const addr6 = new Address6(ip);
    if (addr6.isValid() && addr6.v4) {
      // Address6.v4 is true for ::ffff:0:0/96 — extract the embedded IPv4
      const embedded = addr6.to4().address;
      if (embedded) candidates.push(embedded);
    }
  } catch {
    // Not a valid IPv6 address — that's fine, we keep only the original
  }
  return candidates;
}

async function validateAndFetch(urlString: string): Promise<Response> {
  let parsed: URL;
  try {
    parsed = new URL(urlString);
  } catch {
    throw new Error('Invalid URL');
  }

  if (!['http:', 'https:'].includes(parsed.protocol)) {
    throw new Error(`URL scheme '${parsed.protocol}' is not permitted`);
  }

  // new URL().hostname includes square brackets for IPv6 literals: "[::1]"
  // dns.lookup() accepts "[::1]" and strips brackets internally
  const { address: resolvedIp, family } = await dns.lookup(parsed.hostname);

  // Check both the raw resolved address and any embedded IPv4 address
  const candidates = normalizeIp(resolvedIp);
  for (const candidate of candidates) {
    if (ipRangeCheck(candidate, BLOCKED_RANGES)) {
      throw new Error(
        `SSRF blocked: ${parsed.hostname} resolves to ${resolvedIp}` +
        (candidates.length > 1 ? ` (embedded IPv4: ${candidates[1]})` : '') +
        ` — blocked IP range`
      );
    }
  }

  // Pin the HTTP agent to the validated resolved IP — prevents DNS rebinding
  const { Agent: HttpAgent } = await import('node:http');
  const { Agent: HttpsAgent } = await import('node:https');
  const pinnedLookup = (_: string, __: unknown, cb: Function) => cb(null, resolvedIp, family);
  const AgentClass = parsed.protocol === 'https:' ? HttpsAgent : HttpAgent;
  const pinnedAgent = new AgentClass({ lookup: pinnedLookup, keepAlive: false });

  return fetch(urlString, {
    // @ts-ignore
    agent: pinnedAgent,
    redirect: 'manual',
    signal: AbortSignal.timeout(10_000),
  });
}

// Test cases that must all be BLOCKED:
// validateAndFetch('http://[::1]/admin')           → resolves ::1   → blocked by ::1/128
// validateAndFetch('http://[::ffff:127.0.0.1]/')  → resolves ::ffff:127.0.0.1
//                                                   embedded IPv4 127.0.0.1 → blocked by 127.0.0.0/8
// validateAndFetch('http://127.0.0.1/')           → resolves 127.0.0.1 → blocked by 127.0.0.0/8
// validateAndFetch('http://localhost/')           → resolves 127.0.0.1 → blocked
HIGH
SA-SKL-SSRF7-001 — An SSRF defense that blocks only 127.0.0.0/8 allows IPv6 loopback [::1] and IPv4-mapped IPv6 loopback [::ffff:127.0.0.1] to bypass the check and reach the local server; fix by adding ::1/128 and ::ffff:127.0.0.0/104 to the blocked ranges, normalizing IPv4-mapped IPv6 addresses to their embedded IPv4 form before the CIDR comparison, and using the ip-address npm library for accurate IPv6 address classification. Detection: SkillAudit flags SSRF guard implementations where the blocked IP range list includes 127.0.0.0/8 but does not include ::1/128, or where IPv6 loopback is mentioned in comments but not included in the runtime blocklist array.

SSRF7-002 — URL authority confusion — http://skillaudit.dev@169.254.169.254/

URL authority syntax allows a userinfo component before the host: scheme://userinfo@host/path. This is used by authenticated protocols — ftp://user:pass@ftp.example.com/ is a typical example. The @ character is the delimiter between userinfo and host. In the URL http://skillaudit.dev@169.254.169.254/, skillaudit.dev is the userinfo (username) and 169.254.169.254 is the actual host. The browser and fetch() both connect to 169.254.169.254 — the userinfo is sent as the HTTP Authorization header or discarded for HTTP URLs.

An MCP skill's SSRF defense that uses string operations to check the URL falls directly into this trap. A check like if (!url.includes('skillaudit.dev')) throw new Error('Blocked') passes for the attack URL because the string does include skillaudit.dev — it just appears in the userinfo, not the host. Similarly, a regex like /^https?:\/\/skillaudit\.dev\// as an allowlist check passes on a URL like http://skillaudit.dev@169.254.169.254/latest/meta-data/iam/ if the regex is not anchored to the end of the host component. The fix is unambiguous: always use new URL(input).hostname to extract the host — the WHATWG URL parser places the host in .hostname regardless of any userinfo prefix. new URL('http://skillaudit.dev@169.254.169.254/').hostname returns '169.254.169.254', which the IP blocklist correctly blocks.

// VULNERABLE — string.includes() / regex on raw URL for hostname extraction
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { z } from 'zod';

const ALLOWED_HOSTS = new Set(['skillaudit.dev', 'api.skillaudit.dev', 'cdn.skillaudit.dev']);

function isAllowedUrl_VULNERABLE_v1(urlString: string): boolean {
  // VULNERABLE: string.includes() cannot reliably extract the hostname.
  // Attack URL: "http://skillaudit.dev@169.254.169.254/latest/meta-data/iam/"
  // This string DOES include "skillaudit.dev" — check passes.
  // But fetch() connects to 169.254.169.254 — the AWS IMDS.
  for (const host of ALLOWED_HOSTS) {
    if (urlString.includes(host)) return true;
  }
  return false;
}

function isAllowedUrl_VULNERABLE_v2(urlString: string): boolean {
  // VULNERABLE: regex anchored at start but not end of hostname.
  // Attack URL: "http://skillaudit.dev@169.254.169.254/"
  // The regex matches "http://skillaudit.dev" and then .* matches the rest.
  return /^https?:\/\/skillaudit\.dev.*/.test(urlString);
}

function isAllowedUrl_VULNERABLE_v3(urlString: string): boolean {
  // VULNERABLE: naive split-based extraction.
  // "http://skillaudit.dev@169.254.169.254/path".split('/')[2]
  //  → "skillaudit.dev@169.254.169.254"
  // The result includes @ and is NOT in ALLOWED_HOSTS (which checks for exact match),
  // so this particular variant would correctly reject the URL — BUT:
  // If the check is: extractedPart.endsWith('@169...') → truthy → pass
  // or: extractedPart.startsWith('skillaudit.dev') → truthy → pass
  // Both string checks are bypassable.
  const afterScheme = urlString.split('/')[2]; // "skillaudit.dev@169.254.169.254"
  const beforeAt = afterScheme.split('@')[0];  // "skillaudit.dev" — WRONG host!
  return ALLOWED_HOSTS.has(beforeAt);          // true — passes, but wrong host extracted
}

const server = new McpServer({ name: 'data-proxy-skill', version: '1.0.0' });

server.tool(
  'proxy_request',
  'Proxy a request to an allowed SkillAudit API endpoint',
  { url: z.string().url() },
  async ({ url }) => {
    // Any of the three vulnerable checks above would pass for:
    // url = "http://skillaudit.dev@169.254.169.254/latest/meta-data/iam/security-credentials/"
    //
    // After passing the check, fetch(url) connects to 169.254.169.254:80
    // HTTP GET /latest/meta-data/iam/security-credentials/ HTTP/1.1
    // Host: 169.254.169.254
    // Authorization: Basic c2tpbGxhdWRpdC5kZXY=  (base64 of "skillaudit.dev")
    //
    // Response: "skill-ec2-role"
    // Follow-up fetch to /iam/security-credentials/skill-ec2-role → IAM credentials
    if (!isAllowedUrl_VULNERABLE_v3(url)) {
      return { content: [{ type: 'text', text: 'URL not allowed' }], isError: true };
    }

    const response = await fetch(url);
    return { content: [{ type: 'text', text: await response.text() }] };
  }
);
// FIXED — always use new URL().hostname for host extraction; never string operations
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_HOSTS = new Set(['skillaudit.dev', 'api.skillaudit.dev', 'cdn.skillaudit.dev']);

const BLOCKED_IP_RANGES = [
  '169.254.0.0/16', '100.64.0.0/10',
  '127.0.0.0/8', '::1/128', '::ffff:127.0.0.0/104',
  '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16',
  'fc00::/7', 'fe80::/10',
];

// Demonstrates the correct output of new URL() for the attack URL:
//
// const attack = new URL('http://skillaudit.dev@169.254.169.254/path');
// attack.hostname  === '169.254.169.254'  ← CORRECT host, exposed by the parser
// attack.username  === 'skillaudit.dev'   ← userinfo is in .username, not .hostname
// attack.host      === '169.254.169.254'  ← also correct (includes port if present)
// attack.href      === 'http://skillaudit.dev@169.254.169.254/path'

async function validateAllowedHostFetch(urlString: string): Promise<Response> {
  let parsed: URL;
  try {
    parsed = new URL(urlString);
  } catch {
    throw new Error('Invalid URL');
  }

  if (!['http:', 'https:'].includes(parsed.protocol)) {
    throw new Error(`Scheme '${parsed.protocol}' not permitted — only http and https`);
  }

  // CORRECT: use parsed.hostname, NOT urlString.includes() or string.split()
  // For "http://skillaudit.dev@169.254.169.254/", parsed.hostname === "169.254.169.254"
  if (!ALLOWED_HOSTS.has(parsed.hostname)) {
    throw new Error(
      `Host '${parsed.hostname}' is not in the allowed host list. ` +
      `Note: the URL you supplied had userinfo '${parsed.username}' — ` +
      `only the host matters for routing.`
    );
  }

  // Defense-in-depth: also validate the resolved IP even for allowlisted hosts.
  // An allowed hostname could be compromised and start pointing at an internal IP.
  const { address: resolvedIp, family } = await dns.lookup(parsed.hostname);

  if (ipRangeCheck(resolvedIp, BLOCKED_IP_RANGES)) {
    throw new Error(
      `SSRF blocked: allowed host '${parsed.hostname}' resolves to '${resolvedIp}' ` +
      `which is in a blocked IP range — DNS may be compromised`
    );
  }

  // Pin agent to validated IP to prevent DNS rebinding between check and connect
  const pinnedLookup = (_: string, __: unknown, cb: Function) => cb(null, resolvedIp, family);
  const AgentClass = parsed.protocol === 'https:' ? HttpsAgent : HttpAgent;
  const pinnedAgent = new AgentClass({ lookup: pinnedLookup, keepAlive: false });

  return fetch(urlString, {
    // @ts-ignore
    agent: pinnedAgent,
    redirect: 'manual',
    signal: AbortSignal.timeout(10_000),
  });
}

// Quick unit-test assertions (run with: node --input-type=module << 'EOF' ... 'EOF')
// new URL('http://skillaudit.dev@169.254.169.254/').hostname
//   → '169.254.169.254'  — blocked by ALLOWED_HOSTS check
// new URL('http://skillaudit.dev/').hostname
//   → 'skillaudit.dev'   — allowed, then IP check runs
// new URL('http://skillaudit.dev@169.254.169.254@api.skillaudit.dev/').hostname
//   → 'api.skillaudit.dev'  — WHATWG: last @ wins for host; first segment is userinfo
//   This would pass the host check! Mitigated by the IP validation step.
CRITICAL
SA-SKL-SSRF7-002 — URL authority confusion via @ — in http://skillaudit.dev@169.254.169.254/ the actual host is 169.254.169.254 (the AWS IMDS) while skillaudit.dev is the userinfo; a string.includes() allowlist check, a prefix regex, or a split('@')[0] extraction all pass on this URL while fetch() connects to the IMDS and returns IAM credentials; fix by extracting the host exclusively via new URL(input).hostname which the WHATWG URL parser always places correctly, and also validate the resolved IP against the full blocklist as defense-in-depth. Detection: SkillAudit flags SSRF guards that apply hostname checks using String.prototype.includes, String.prototype.startsWith, RegExp.prototype.test, or String.prototype.split on the raw URL string rather than on new URL(input).hostname.

SSRF7-003 — Unicode normalization bypass — circled letters normalize to internal hostnames

Domain names are restricted to ASCII by the DNS protocol. Internationalized domain names (IDNs) containing non-ASCII characters are encoded into ASCII-compatible encoding (ACE) form by the IDNA (Internationalizing Domain Names in Applications) algorithm — a process commonly called Punycode encoding. For example, the domain münchen.de is encoded as xn--mnchen-3ya.de. The WHATWG URL Standard, which Node.js's new URL() implements, applies IDNA normalization to hostnames automatically: new URL('http://münchen.de/').hostname returns 'xn--mnchen-3ya.de'.

The attack abuses Unicode characters that IDNA normalization maps to ordinary ASCII. The Unicode standard defines "compatibility equivalences" — for example, the circled Latin letter Ⓐ (U+24B6, CIRCLED LATIN CAPITAL LETTER A) normalizes to a, and ⓒ (U+24CA, CIRCLED LATIN CAPITAL LETTER S) normalizes to s. A hostname built from these characters — ⓒⓐⓒⓌⓒ.corp — might normalize to sssis.corp or admin.internal depending on which characters are chosen. If the SSRF blocklist checks the raw input string for 'internal.corp' and the attacker supplies the Unicode lookalike that normalizes to 'internal.corp', the raw string check sees different bytes and passes. The new URL() parser normalizes the hostname, so dns.lookup() resolves the normalized form and the request reaches the internal server.

The fix is to always apply the blocklist to the hostname extracted from new URL(input).hostname (the IDNA-normalized form), never to the raw input string. Because new URL() normalizes via the same IDNA algorithm that DNS uses, the hostname in .hostname is what the DNS resolver will actually query. Any blocklist applied to this normalized hostname correctly blocks Unicode lookalikes.

// VULNERABLE — blocklist applied to raw input string, not normalized hostname
import dns from 'dns/promises';
import ipRangeCheck from 'ip-range-check';

// Internal hostnames that must be blocked
const BLOCKED_HOSTNAMES = new Set([
  'internal.corp',
  'admin.internal',
  'metadata.google.internal',
  'localhost',
]);

async function validateUrl_VULNERABLE(urlString: string): Promise<void> {
  // VULNERABLE: check applied to raw urlString, not to new URL().hostname
  //
  // Attack: attacker supplies a URL containing Unicode characters that
  // new URL() normalizes to a blocked hostname.
  //
  // Example: 'http://ⓤⓠⓤⓜⓤⓠ.corp/'
  // Raw string check: 'internal.corp' in urlString? No → passes.
  // But: new URL('http://ⓤⓠⓤⓜⓤⓠ.corp/').hostname
  //   may normalize (via IDNA) to 'internal.corp' depending on the Unicode mapping.
  //
  // Another real example with fullwidth ASCII:
  // 'http://Internal。corp/'
  //   = 'http://internal.corp/' (fullwidth Unicode)
  // new URL(...).hostname → 'internal.corp'  ← normalized!

  for (const blocked of BLOCKED_HOSTNAMES) {
    if (urlString.includes(blocked)) {
      throw new Error(`Blocked hostname: ${blocked}`);
    }
  }
  // Check passes for Unicode forms — raw string does not contain ASCII hostname.
  // Falls through to dns.lookup() which resolves the normalized hostname.

  const { hostname } = new URL(urlString);
  const { address } = await dns.lookup(hostname); // hostname is normalized here
  // address resolves to an internal IP — SSRF succeeds
}

// Also vulnerable: blocklist compared against the raw URL input before parsing
function isBlockedDomain_VULNERABLE(rawUrl: string): boolean {
  // Attack: 'http://localhost/' — fullwidth 'localhost'
  // rawUrl.includes('localhost') → false (different bytes)
  // But new URL(rawUrl).hostname → 'localhost'
  return rawUrl.includes('localhost') ||
         rawUrl.includes('internal') ||
         rawUrl.includes('169.254');
  // All three checks are bypassable via Unicode normalization or
  // IPv6 representations for 169.254.169.254
}
// FIXED — blocklist applied to new URL().hostname (IDNA-normalized); raw input never checked
import dns from 'dns/promises';
import ipRangeCheck from 'ip-range-check';

// Blocklisted hostnames — applied to the NORMALIZED hostname from new URL().hostname
const BLOCKED_HOSTNAMES = new Set([
  'localhost',
  'internal.corp',
  'admin.internal',
  'metadata.google.internal',
  'metadata.internal',
]);

const BLOCKED_HOSTNAME_SUFFIXES = [
  '.internal',
  '.local',
  '.corp',
  '.lan',
  '.intranet',
];

const BLOCKED_IP_RANGES = [
  '169.254.0.0/16', '100.64.0.0/10',
  '127.0.0.0/8', '::1/128', '::ffff:127.0.0.0/104',
  '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16',
  'fc00::/7', 'fe80::/10',
];

async function validateUrl_FIXED(urlString: string): Promise<void> {
  let parsed: URL;
  try {
    // new URL() applies IDNA normalization to the hostname.
    // 'http://localhost/' → parsed.hostname === 'localhost'
    // 'http://ⓒⓐⓒⓌⓒ.corp/' → parsed.hostname === 'sssis.corp' (normalized)
    // The normalization happens here — before any checks.
    parsed = new URL(urlString);
  } catch {
    throw new Error('Invalid URL');
  }

  if (!['http:', 'https:'].includes(parsed.protocol)) {
    throw new Error(`Scheme '${parsed.protocol}' not permitted`);
  }

  // CORRECT: check against parsed.hostname — the IDNA-normalized hostname.
  // Unicode lookalikes are already normalized at this point.
  const normalizedHostname = parsed.hostname;

  // 1. Exact hostname blocklist
  if (BLOCKED_HOSTNAMES.has(normalizedHostname)) {
    throw new Error(`Hostname '${normalizedHostname}' is blocked`);
  }

  // 2. Suffix blocklist — blocks *.internal, *.local, *.corp, *.lan
  for (const suffix of BLOCKED_HOSTNAME_SUFFIXES) {
    if (normalizedHostname.endsWith(suffix)) {
      throw new Error(
        `Hostname '${normalizedHostname}' ends with blocked suffix '${suffix}'`
      );
    }
  }

  // 3. IP range check on the DNS-resolved address (defense-in-depth)
  const { address: resolvedIp } = await dns.lookup(normalizedHostname);
  if (ipRangeCheck(resolvedIp, BLOCKED_IP_RANGES)) {
    throw new Error(`IP '${resolvedIp}' for '${normalizedHostname}' is in a blocked range`);
  }

  // Note: the IDNA normalization in new URL() uses the same algorithm as
  // the DNS resolver, so the blocked hostname check and the dns.lookup()
  // are operating on the same domain name representation.
  // A Unicode lookalike that normalizes to 'internal.corp' will:
  //   - be caught by the hostname blocklist (step 1 above)
  //   - AND resolve to the internal IP (caught by step 3 as well)
}

// Demonstration of normalization:
// new URL('http://localhost/').hostname
//   → 'localhost'  (fullwidth ASCII → normalized ASCII)
// new URL('http://ⅉnternal.corp/').hostname
//   → 'internal.corp'  (double-struck j → i after normalization in some IDNA implementations)
// Always validate the .hostname property, not the raw string.
HIGH
SA-SKL-SSRF7-003 — Unicode characters that IDNA normalizes to ASCII (fullwidth ASCII, circled Latin letters, compatibility equivalences) allow an attacker to supply a URL whose raw string does not match a blocklisted hostname but whose new URL().hostname normalizes to it; applying the hostname blocklist to the raw input string rather than to parsed.hostname means the Unicode form passes the check while dns.lookup() resolves the normalized internal hostname; fix by applying all hostname checks to new URL(input).hostname which performs IDNA normalization by the same algorithm the DNS resolver uses. Detection: SkillAudit flags SSRF guards that call String.prototype.includes, String.prototype.startsWith, String.prototype.endsWith, or String.prototype.match on the raw urlString argument for hostname-based blocking rather than on new URL(urlString).hostname.

SSRF7-004 — CRLF injection in URL path component splits HTTP request at proxy

An MCP skill constructs an outbound URL by concatenating user-supplied path segments into a base URL. For example, a tool that fetches a resource by ID might build https://api.example.com/v1/resources/${userPath}. If userPath contains the URL-encoded CRLF sequence %0D%0A, and the skill passes this URL to an HTTP library that does not normalize percent-encoding in the path, the resulting request line is split at the CRLF. The proxy or intermediate server receives what appears to be two HTTP requests in the same TCP stream — the first from the skill and a second injected request whose headers and body the attacker controls. This technique is called HTTP request splitting or CRLF injection.

The SSRF escalation path works as follows: the first request reaches the intended server and returns a normal response. The injected second request targets an internal service — for example, GET /latest/meta-data/iam/security-credentials/ HTTP/1.1\r\nHost: 169.254.169.254\r\n\r\n — and its response is returned to the proxy as the response to the second connection. If the proxy is a shared reverse proxy like nginx, the injected response may be delivered to a different client, causing response queue poisoning. Combined with an open redirect on the target server, CRLF injection can be escalated to full SSRF against arbitrary internal hosts. The fix requires rejecting %0D and %0A in user-supplied URL components and encoding path segments with encodeURIComponent() before concatenation, which re-encodes any bare \r or \n characters.

// VULNERABLE — user-supplied path segment concatenated without CRLF sanitization
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { z } from 'zod';

const BASE_URL = 'https://api.example.com/v1/resources/';

const server = new McpServer({ name: 'resource-fetch-skill', version: '1.0.0' });

server.tool(
  'get_resource',
  'Fetch a resource by its path identifier',
  { resourcePath: z.string() },
  async ({ resourcePath }) => {
    // VULNERABLE: resourcePath is concatenated directly into the URL.
    //
    // Attack payload:
    // resourcePath = "legitimate-id%0D%0A%0D%0AGET%20/latest/meta-data/iam/security-credentials/%20HTTP/1.1%0D%0AHost:%20169.254.169.254%0D%0A%0D%0A"
    //
    // The constructed URL string becomes:
    // "https://api.example.com/v1/resources/legitimate-id\r\n\r\nGET /latest/meta-data/... HTTP/1.1\r\nHost: 169.254.169.254\r\n\r\n"
    //
    // Some HTTP clients (especially older ones or those that don't re-encode path)
    // send the raw bytes in the request line, splitting the stream:
    //
    //   GET /v1/resources/legitimate-id HTTP/1.1\r\n   ← first request (intended)
    //   Host: api.example.com\r\n
    //   \r\n
    //   GET /latest/meta-data/iam/security-credentials/ HTTP/1.1\r\n  ← injected!
    //   Host: 169.254.169.254\r\n
    //   \r\n
    //
    // If the proxy forwards both, the IMDS response is returned.
    //
    // Even without a proxy, %0D%0A in URLs can cause issues with:
    // - Log injection (fake log entries after the CRLF)
    // - Cache poisoning via injected response headers
    // - Open redirects when combined with 301/302 from the target server

    const url = `${BASE_URL}${resourcePath}`; // No encoding — VULNERABLE
    const response = await fetch(url);
    return { content: [{ type: 'text', text: await response.text() }] };
  }
);
// FIXED — reject %0D/%0A in path/query; encode path segments with encodeURIComponent
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 HttpsAgent } from 'node:https';

const BASE_URL = 'https://api.example.com/v1/resources/';

// Characters that must never appear (decoded or encoded) in a user-supplied URL segment.
// %0D = carriage return (\r), %0A = line feed (\n) — CRLF injection
// %00 = null byte — may cause truncation in some URL parsers
const FORBIDDEN_ENCODED_SEQUENCES = /(%0[dD]|%0[aA]|%00)/;
const FORBIDDEN_RAW_CHARS = /[\r\n\0]/;

function sanitizePathSegment(segment: string): string {
  // 1. Reject any percent-encoded CRLF or null byte BEFORE decoding.
  //    This catches %0D, %0A, %00 as they appear in the raw input string.
  if (FORBIDDEN_ENCODED_SEQUENCES.test(segment)) {
    throw new Error(
      `Path segment contains forbidden encoded characters ` +
      `(CRLF: %0D%0A or null byte: %00): ${segment}`
    );
  }

  // 2. Reject raw CR, LF, or null byte characters (in case the input was decoded upstream).
  if (FORBIDDEN_RAW_CHARS.test(segment)) {
    throw new Error('Path segment contains forbidden raw CRLF or null byte characters');
  }

  // 3. Encode the segment with encodeURIComponent — this percent-encodes all
  //    characters that are not unreserved (alphanumeric + - _ . ~), including:
  //    spaces, slashes, question marks, hashes, and any remaining control characters.
  //    This re-encodes any CR or LF that slipped through as %0D and %0A — but we
  //    already rejected those above, so this is defense-in-depth only.
  //
  //    encodeURIComponent('hello/world') → 'hello%2Fworld'  (/ is encoded)
  //    encodeURIComponent('a b') → 'a%20b'
  //    This prevents path traversal (../) as well as CRLF injection.
  return encodeURIComponent(segment);
}

const BLOCKED_IP_RANGES = [
  '169.254.0.0/16', '100.64.0.0/10',
  '127.0.0.0/8', '::1/128', '::ffff:127.0.0.0/104',
  '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16',
  'fc00::/7', 'fe80::/10',
];

async function fetchResource(resourcePath: string): Promise<Response> {
  // Sanitize and encode the user-supplied path segment
  const encodedPath = sanitizePathSegment(resourcePath);

  // Construct the full URL from the safe base + encoded segment
  const urlString = `${BASE_URL}${encodedPath}`;

  // Parse to validate the final URL structure
  const parsed = new URL(urlString);

  // Validate scheme (should always be https: given our BASE_URL, but verify)
  if (parsed.protocol !== 'https:') {
    throw new Error('Only HTTPS is permitted');
  }

  // Also validate that the constructed URL's hostname has not been manipulated.
  // This guards against BASE_URL misconfiguration or future changes.
  const { address: resolvedIp, family } = await dns.lookup(parsed.hostname);

  if (ipRangeCheck(resolvedIp, BLOCKED_IP_RANGES)) {
    throw new Error(`Constructed URL resolves to blocked IP: ${resolvedIp}`);
  }

  // Pin agent to validated IP
  const pinnedLookup = (_: string, __: unknown, cb: Function) => cb(null, resolvedIp, family);
  const pinnedAgent = new HttpsAgent({ lookup: pinnedLookup, keepAlive: false });

  return fetch(urlString, {
    // @ts-ignore
    agent: pinnedAgent,
    redirect: 'manual',
    signal: AbortSignal.timeout(10_000),
  });
}

// Test cases that must be REJECTED:
// sanitizePathSegment('id%0D%0AHost: evil.com')  → throws (encoded CRLF)
// sanitizePathSegment('id\r\nHost: evil.com')    → throws (raw CRLF)
// sanitizePathSegment('id%00suffix')             → throws (null byte)
//
// Test cases that must be ALLOWED (and encoded):
// sanitizePathSegment('resource-id-123')   → 'resource-id-123'       (no encoding needed)
// sanitizePathSegment('path/to/item')      → 'path%2Fto%2Fitem'      (/ encoded)
// sanitizePathSegment('search query')      → 'search%20query'        (space encoded)

const server = new McpServer({ name: 'resource-fetch-skill', version: '1.0.0' });

server.tool(
  'get_resource',
  'Fetch a resource by its path identifier',
  {
    resourcePath: z.string()
      .max(500)
      .refine(
        (s) => !FORBIDDEN_ENCODED_SEQUENCES.test(s) && !FORBIDDEN_RAW_CHARS.test(s),
        { message: 'Path must not contain CRLF or null byte sequences' }
      ),
  },
  async ({ resourcePath }) => {
    let response: Response;
    try {
      response = await fetchResource(resourcePath);
    } 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 text = await response.text();
    return { content: [{ type: 'text', text: text.slice(0, 50_000) }] };
  }
);
HIGH
SA-SKL-SSRF7-004 — CRLF injection via %0D%0A in a user-supplied URL path segment splits the HTTP request at the proxy layer, injecting a second request whose headers the attacker controls; this allows SSRF escalation to internal services via injected Host: headers and, combined with a 301/302 redirect, enables request queue poisoning; fix by rejecting %0D, %0A, and %00 in user-supplied URL components (both raw and percent-encoded forms), encoding all user-supplied path segments with encodeURIComponent() before concatenation, and validating with Zod .refine() at the tool parameter layer. Detection: SkillAudit flags tool handler implementations that concatenate user-supplied strings into URL paths without prior encodeURIComponent() encoding and without a check for %0D/%0A in the input.

Detection summary

ID Severity Pattern Fix
SSRF7-001 HIGH IPv6 loopback [::1] and IPv4-mapped ::ffff:127.0.0.1 bypass an IPv4-only 127.0.0.0/8 blocklist Add ::1/128 and ::ffff:127.0.0.0/104 to blocked ranges; normalize IPv4-mapped addresses with ip-address before CIDR check
SSRF7-002 CRITICAL URL authority @ — http://trusted.dev@169.254.169.254/ passes string.includes() allowlist but fetch() connects to IMDS Extract host only via new URL(input).hostname; never use string operations on raw URL for hostname checks
SSRF7-003 HIGH Unicode circled/fullwidth letters normalize via IDNA to blocklisted internal hostnames; raw string check passes on Unicode form Apply hostname blocklist to new URL(input).hostname (IDNA-normalized), not to raw input string
SSRF7-004 HIGH CRLF %0D%0A in URL path splits HTTP request at proxy; injects second request with attacker-controlled Host: header Reject %0D, %0A, %00 in path/query inputs; encode path segments with encodeURIComponent(); use Zod .refine() for schema-level validation

Related patterns: SA-SKL-SSRF6 covers cloud IMDS credential theft (AWS EC2 at 169.254.169.254, GCP metadata.google.internal), DNS rebinding via TTL-0 records, and Redis/MongoDB on localhost reached via SSRF or the gopher:// protocol. SA-SKL-REDIRECT3 covers open redirect vulnerabilities that chain with SSRF — a 301/302 redirect from a trusted host to an internal address allows an attacker to bypass both the IP blocklist (checked on the initial URL) and the hostname allowlist (checked before the redirect is followed).