Skip to content

Commit 62c0aaa

Browse files
cliffhallclaude
andcommitted
fix(fetch): connect only to the address the private-IP guard checked
The guard resolved a URL's host and checked the addresses, and httpx then resolved the name again to connect, so a name whose DNS answer changed between the two lookups (DNS rebinding) passed the check with a public address and was fetched from a private one. The client's direct transport now opens connections through a network backend that resolves the host itself, checks every address, and connects to those addresses by IP literal. The Host header, TLS SNI and certificate verification still use the URL's hostname. Proxied requests and --allow-private-ips are unchanged. Closes #5557 Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Signed-off-by: cliffhall <cliff@futurescale.com>
1 parent e1d154e commit 62c0aaa

5 files changed

Lines changed: 1184 additions & 6 deletions

File tree

‎src/fetch/README.md‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ Requires MCP Python SDK 2.x (`mcp>=2.3,<3`).
1111
> [!CAUTION]
1212
> This server can access local/internal IP addresses and may represent a security risk. Exercise caution when using this MCP server to ensure this does not expose any sensitive data.
1313
>
14-
> By default the server refuses to fetch private, loopback, link-local and other non-public addresses, including cloud metadata endpoints such as `169.254.169.254`, and checks every redirect hop the same way. The `--allow-private-ips` argument turns this guard off; see [Customization - Private addresses](#customization---private-addresses). The guard checks the addresses a hostname resolves to before each request, so it does not protect against DNS rebinding between that check and the connection, and a hostname the server cannot resolve itself (one only a proxy can resolve) is not checked.
14+
> By default the server refuses to fetch private, loopback, link-local and other non-public addresses, including cloud metadata endpoints such as `169.254.169.254`, and checks every redirect hop the same way. The `--allow-private-ips` argument turns this guard off; see [Customization - Private addresses](#customization---private-addresses). The server connects only to an address the guard checked, so a hostname cannot pass the check with one address and be fetched from another (DNS rebinding). A request sent through a proxy is the exception: the proxy resolves the hostname and makes the connection, so the address it reaches is not the server's to check, and a hostname the server cannot resolve itself (one only a proxy can resolve) is not checked at all.
1515
1616
The fetch tool will truncate the response, but by using the `start_index` argument, you can specify where to start the content extraction. This lets models read a webpage in chunks, until they find the information they need.
1717

@@ -202,6 +202,18 @@ judged by the IPv4 address it carries; a deprecated IPv4-compatible address (`::
202202
refused whatever IPv4 it carries. A hostname is refused if any one of its addresses is in those ranges.
203203
The client receives an error naming the refused address.
204204

205+
The address that is checked is the address the server connects to. When it opens a connection the server resolves the
206+
hostname itself, checks every address in that answer, and connects to one of those addresses directly, so the name is
207+
not looked up again in between: a hostname whose DNS answer changes from a public address to a private one between the
208+
check and the connection (DNS rebinding) is refused. This holds for every connection the server opens, redirect hops
209+
and robots.txt fetches included. The request still carries the hostname in its `Host` header, and an HTTPS connection
210+
still sends it as the TLS server name and verifies the certificate against it, not against the address.
211+
212+
A request that goes through a proxy (`--proxy-url`, or the proxy environment variables) is different, because the
213+
server connects to the proxy and the proxy resolves the hostname and connects to it. The hostname is still checked
214+
against what it resolves to for the server, but the proxy's own lookup is not pinned to that answer, and a hostname
215+
only the proxy can resolve is not checked.
216+
205217
To fetch from local or internal hosts (a development server, an intranet page), add the argument
206218
`--allow-private-ips` to the `args` list in the configuration.
207219

Lines changed: 202 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,202 @@
1+
# Pins the fetch server's direct connections to addresses the private-address
2+
# guard approved (#5557). The guard in server.py is a request hook: it resolves
3+
# the URL's host and refuses a non-public address. httpx then opened the
4+
# connection by resolving the same name a second time, so a name whose DNS
5+
# answer changed between the two lookups (DNS rebinding) passed the check with
6+
# a public address and connected to a private one.
7+
#
8+
# The fix is to make the lookup that picks the address the one that is
9+
# checked. httpcore opens every TCP connection through a network backend's
10+
# `connect_tcp(host, port)`. `PinnedBackend` stands in front of the real
11+
# backend there: it resolves the host itself, hands every address to the
12+
# guard, and then connects to those addresses by IP literal, so nothing below
13+
# it resolves a name again. Nothing above it changes: httpcore still derives
14+
# the `Host` header, the TLS SNI name and the certificate's expected name from
15+
# the URL's host, not from what `connect_tcp` was given.
16+
#
17+
# Only the client's direct transport is pinned. A request that goes through a
18+
# proxy connects to the proxy, which may well be on loopback and which resolves
19+
# the destination on its side, so the proxy transports are left as httpx built
20+
# them and the request hook stays the (best-effort) check for that case.
21+
#
22+
# httpx has no public way to give its default transport a network backend
23+
# while it still reads the proxy environment variables (passing `transport=`
24+
# turns those off), so `pin_direct_connections` replaces the client's default
25+
# transport after construction, and fails loudly if httpx's internals are not
26+
# the shape it expects, rather than leave connections unpinned.
27+
28+
import asyncio
29+
import socket
30+
from collections.abc import Awaitable, Callable, Iterable, Sequence
31+
from typing import Any, cast
32+
33+
import httpcore
34+
import httpx
35+
36+
# How long a connection attempt gets before the next address is tried
37+
# alongside it (RFC 8305's "Connection Attempt Delay"), so one unresponsive
38+
# address does not hold up a host that has a working one. The name-based
39+
# connect this replaces raced a host's addresses the same way.
40+
CONNECTION_ATTEMPT_DELAY = 0.25
41+
42+
# httpx's own defaults for its connection pool (`httpx.Limits()`), which the
43+
# pinned transport keeps.
44+
_MAX_CONNECTIONS = 100
45+
_MAX_KEEPALIVE_CONNECTIONS = 20
46+
_KEEPALIVE_EXPIRY = 5.0
47+
48+
Resolver = Callable[[str], Awaitable[Sequence[str]]]
49+
# Raises to refuse a host given every address it resolved to.
50+
Vetter = Callable[[str, Sequence[str]], None]
51+
52+
53+
class PinnedBackend(httpcore.AsyncNetworkBackend):
54+
"""A network backend that connects only to addresses it resolved and vetted.
55+
56+
``resolve`` turns a host into its addresses and ``vet`` raises when any of
57+
them is refused; ``inner`` (the anyio backend by default) then opens the
58+
socket to an address, never to the name.
59+
"""
60+
61+
def __init__(
62+
self,
63+
resolve: Resolver,
64+
vet: Vetter,
65+
inner: httpcore.AsyncNetworkBackend | None = None,
66+
) -> None:
67+
self._resolve = resolve
68+
self._vet = vet
69+
# The cast: httpcore also declares a placeholder `AnyIOBackend` for an
70+
# install without anyio, which is the declaration a type checker sees.
71+
# httpx requires anyio, so the real backend is what this builds.
72+
self._inner = (
73+
cast(httpcore.AsyncNetworkBackend, httpcore.AnyIOBackend())
74+
if inner is None
75+
else inner
76+
)
77+
78+
async def connect_tcp(
79+
self,
80+
host: str,
81+
port: int,
82+
timeout: float | None = None,
83+
local_address: str | None = None,
84+
socket_options: Iterable[Any] | None = None,
85+
) -> httpcore.AsyncNetworkStream:
86+
try:
87+
resolved = await self._resolve(host)
88+
except socket.gaierror as e:
89+
# What the inner backend reports for a name it cannot resolve.
90+
raise httpcore.ConnectError(str(e)) from e
91+
# getaddrinfo lists an address once per socket type.
92+
addresses = list(dict.fromkeys(resolved))
93+
self._vet(host, addresses)
94+
95+
loop = asyncio.get_running_loop()
96+
started = loop.time()
97+
waiting = list(addresses)
98+
attempts: set[asyncio.Task[httpcore.AsyncNetworkStream]] = set()
99+
failures: list[Exception] = []
100+
try:
101+
while waiting or attempts:
102+
if waiting:
103+
# Each attempt gets what is left of the one connect
104+
# timeout, so trying several addresses does not extend it.
105+
left = (
106+
None if timeout is None else timeout - (loop.time() - started)
107+
)
108+
attempts.add(
109+
loop.create_task(
110+
self._inner.connect_tcp(
111+
waiting.pop(0),
112+
port,
113+
timeout=left,
114+
local_address=local_address,
115+
socket_options=socket_options,
116+
)
117+
)
118+
)
119+
# Wake on the first attempt to finish, or to start the next
120+
# address once this one has had its head start.
121+
done, attempts = await asyncio.wait(
122+
attempts,
123+
timeout=CONNECTION_ATTEMPT_DELAY if waiting else None,
124+
return_when=asyncio.FIRST_COMPLETED,
125+
)
126+
winner: httpcore.AsyncNetworkStream | None = None
127+
for attempt in done:
128+
error = attempt.exception()
129+
if isinstance(error, Exception):
130+
failures.append(error)
131+
elif winner is None:
132+
winner = attempt.result()
133+
else:
134+
await attempt.result().aclose()
135+
if winner is not None:
136+
return winner
137+
# Every address failed: report the first, as a single connect would.
138+
if failures:
139+
raise failures[0]
140+
raise httpcore.ConnectError(f"{host} has no addresses")
141+
finally:
142+
# Attempts still running lost the race, or the caller gave up.
143+
for attempt in attempts:
144+
attempt.cancel()
145+
for outcome in await asyncio.gather(*attempts, return_exceptions=True):
146+
if isinstance(outcome, httpcore.AsyncNetworkStream):
147+
await outcome.aclose()
148+
149+
async def connect_unix_socket(
150+
self,
151+
path: str,
152+
timeout: float | None = None,
153+
socket_options: Iterable[Any] | None = None,
154+
) -> httpcore.AsyncNetworkStream:
155+
# A Unix socket has no name to resolve. The server never asks for one.
156+
return await self._inner.connect_unix_socket(
157+
path, timeout=timeout, socket_options=socket_options
158+
)
159+
160+
async def sleep(self, seconds: float) -> None:
161+
await self._inner.sleep(seconds)
162+
163+
164+
class PinnedTransport(httpx.AsyncHTTPTransport):
165+
"""httpx's HTTP transport with its connections opened by ``backend``.
166+
167+
Everything else is httpx's default transport: certificate verification
168+
against the URL's host with the default trust store (``SSL_CERT_FILE`` and
169+
``SSL_CERT_DIR`` honored), HTTP/1.1, and the default pool limits.
170+
"""
171+
172+
def __init__(self, backend: httpcore.AsyncNetworkBackend) -> None:
173+
ssl_context = httpx.create_ssl_context()
174+
super().__init__(verify=ssl_context)
175+
# `AsyncHTTPTransport` takes no network backend, so its pool is
176+
# rebuilt with one; httpcore's pool takes it as a public argument.
177+
self._pool = httpcore.AsyncConnectionPool(
178+
ssl_context=ssl_context,
179+
max_connections=_MAX_CONNECTIONS,
180+
max_keepalive_connections=_MAX_KEEPALIVE_CONNECTIONS,
181+
keepalive_expiry=_KEEPALIVE_EXPIRY,
182+
network_backend=backend,
183+
)
184+
185+
186+
def pin_direct_connections(
187+
client: httpx.AsyncClient, resolve: Resolver, vet: Vetter
188+
) -> None:
189+
"""Make ``client``'s direct connections go only to vetted addresses.
190+
191+
Replaces the client's default transport, the one used for every request
192+
no proxy applies to, with a `PinnedTransport`. Proxy transports are left
193+
alone (see the top of this file). Raises ``TypeError`` when the client
194+
is not built the way this relies on, so a future httpx cannot silently
195+
drop the pinning.
196+
"""
197+
if not isinstance(getattr(client, "_transport", None), httpx.AsyncHTTPTransport):
198+
raise TypeError(
199+
"Cannot pin connections to the checked addresses: this version of "
200+
"httpx does not expose its default transport as expected"
201+
)
202+
client._transport = PinnedTransport(PinnedBackend(resolve, vet))

‎src/fetch/src/mcp_server_fetch/server.py‎

Lines changed: 37 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,9 @@
33
# beside the handlers because every request path (tool, prompt and robots.txt
44
# check) must go through it: the private-address guard on each request and
55
# redirect hop, robots.txt for autonomous fetches, the cap on how much of a
6-
# response body is read (#5370), and proxy normalization.
6+
# response body is read (#5370), and proxy normalization. The guard's check at
7+
# connect time, which closes the gap between checking a name and connecting to
8+
# it, is in `pinning.py` (#5557).
79
#
810
# Built on the MCP Python SDK's high-level `MCPServer` (#5174), as the example
911
# to follow: the tool and the prompt are plain decorated functions, whose type
@@ -47,6 +49,7 @@
4749
from pydantic import AnyUrl, Field, TypeAdapter, ValidationError
4850

4951
from .allowlist import normalize_allowed_hosts, refuse_unlisted_destination
52+
from .pinning import pin_direct_connections
5053
from .readability_js import extract_article
5154
from .timeout import (
5255
DEFAULT_TIMEOUT_MS,
@@ -207,6 +210,24 @@ async def _refuse_private_destination(request: httpx.Request) -> None:
207210
)
208211

209212

213+
def _refuse_private_addresses(host: str, addresses: Sequence[str]) -> None:
214+
"""The same refusal at connect time, for the addresses about to be used.
215+
216+
`pin_direct_connections` calls this with what ``host`` resolved to when
217+
the connection is opened, and connects only to those addresses, so the
218+
address that was checked is the address that is reached (#5557). The hook
219+
above still runs first: it names the URL, and it is the only check a
220+
proxied request gets.
221+
"""
222+
for address in addresses:
223+
if not _is_public_address(address):
224+
raise ToolError(
225+
f"Refused to connect to {host}: it resolves to {address}, "
226+
"which is not a public address. Start the server with "
227+
"--allow-private-ips to allow private, loopback and link-local addresses."
228+
)
229+
230+
210231
def _readability_content(html: str) -> str:
211232
"""readabilipy's pure-Python simplified HTML for ``html``, or "" when it has none.
212233
@@ -406,21 +427,32 @@ def normalize_proxy_env() -> None:
406427
os.environ[name] = normalize_proxy_url(value)
407428

408429

409-
def make_client(proxy_url: str | None) -> httpx.AsyncClient:
430+
def make_client(
431+
proxy_url: str | None, allow_private_ips: bool = False
432+
) -> httpx.AsyncClient:
410433
"""Build the httpx client, turning a bad proxy setting into a ``ToolError``.
411434
412435
httpx validates the proxy (``--proxy-url`` or the proxy environment
413436
variables) when the client is constructed, before any request, so this
414437
failure is not an ``HTTPError``.
438+
439+
Unless ``allow_private_ips``, the client's direct connections are pinned
440+
to addresses the private-address guard checked (see `pinning.py`).
415441
"""
416442
try:
417-
return httpx.AsyncClient(proxy=proxy_url)
443+
client = httpx.AsyncClient(proxy=proxy_url)
418444
except (ValueError, ImportError) as e:
419445
raise ToolError(
420446
f"Failed to set up the HTTP client, check the proxy "
421447
f"configuration (--proxy-url or the HTTP_PROXY, HTTPS_PROXY and "
422448
f"ALL_PROXY environment variables): {e}"
423449
)
450+
if not allow_private_ips:
451+
# The lambda looks `_resolve_host` up on each call, as the hook does.
452+
pin_direct_connections(
453+
client, lambda host: _resolve_host(host), _refuse_private_addresses
454+
)
455+
return client
424456

425457

426458
# The most body bytes the server reads from one response (#5370). A body is
@@ -741,7 +773,7 @@ async def check_may_autonomously_fetch_url(
741773

742774
robot_txt_url = get_robots_txt_url(url)
743775

744-
async with make_client(proxy_url) as client:
776+
async with make_client(proxy_url, allow_private_ips) as client:
745777
hooks: list[Callable[[httpx.Request], Awaitable[None]]] = []
746778
if allowed_hosts:
747779
hooks.append(refuse_unlisted_destination(allowed_hosts))
@@ -843,7 +875,7 @@ async def _check_redirect_robots_txt(request: httpx.Request) -> None:
843875
str(request.url), user_agent, proxy_url, allow_private_ips, allowed_hosts
844876
)
845877

846-
async with make_client(proxy_url) as client:
878+
async with make_client(proxy_url, allow_private_ips) as client:
847879
hooks: list[Callable[[httpx.Request], Awaitable[None]]] = []
848880
if allowed_hosts:
849881
hooks.append(refuse_unlisted_destination(allowed_hosts))

‎src/fetch/tests/harness.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,9 @@ def factory(**kwargs: Any) -> httpx.AsyncClient:
115115
# patching the attribute on the httpx module is what it picks up.
116116
monkeypatch.setattr(httpx, "AsyncClient", factory)
117117
monkeypatch.setattr(server_module, "_resolve_host", fake.resolve)
118+
# The mock transport opens no connection, so there is nothing to pin, and
119+
# pinning would replace it with a real transport (test_pinning.py covers it).
120+
monkeypatch.setattr(server_module, "pin_direct_connections", lambda *_: None)
118121
return fake
119122

120123

0 commit comments

Comments
 (0)