Skip to content

Commit b4e4a6a

Browse files
authored
Merge pull request #5562 from modelcontextprotocol/v2/fix/5521-fetch-allowed-hosts-wildcard-ip
fix(fetch): refuse --allowed-hosts wildcards on IP addresses
2 parents 6b7aab9 + 10aa034 commit b4e4a6a

3 files changed

Lines changed: 124 additions & 2 deletions

File tree

‎src/fetch/README.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -216,6 +216,10 @@ repeated). Each entry is one of:
216216
(`api.github.com`, `a.b.github.com`) but not `github.com` itself: list both to allow both;
217217
- an IP address, such as `203.0.113.7` or `2001:db8::7`, which matches a URL that uses that address literally.
218218

219+
A wildcard applies to domain names only. An entry that puts `*.` in front of an IP address or of a numeric suffix of
220+
one, such as `*.10.0.0.1` or `*.0.0.1`, is refused at startup, and a URL that uses an IP address is only ever matched
221+
by an entry naming that exact address.
222+
219223
Matching ignores case and a trailing dot, and an internationalized name may be given in either its Unicode or its
220224
`xn--` form. An entry names a host only, so it carries no scheme, port or path. The list is checked before every request
221225
the server sends, by the host name in the URL rather than by the addresses it resolves to: the requested page, its

‎src/fetch/src/mcp_server_fetch/allowlist.py‎

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,12 @@
1313
# keep the semantics obvious: an exact host (a name or an IP literal), and
1414
# `*.example.com`, which matches any subdomain at any depth of example.com but
1515
# not example.com itself. Ports and schemes are not part of an entry.
16+
#
17+
# A wildcard is for domain names only (#5521). `*.` in front of an address, or
18+
# of anything whose last label is a number, is refused when the list is read:
19+
# `*.0.0.1` is not a domain, and matched as a suffix it would cover 10.0.0.1
20+
# and 127.0.0.1 alike. Matching holds the same line from the other side: an
21+
# IP-literal host is only ever compared with exact entries.
1622

1723
import argparse
1824
import ipaddress
@@ -29,7 +35,7 @@ def normalize_allowed_host(entry: str) -> str:
2935
ASCII form requests are checked in (``bücher.example`` becomes
3036
``xn--bcher-kva.example``). An IP literal is written in its compressed
3137
form, an IPv6 one with or without brackets. A wildcard is ``*.`` followed
32-
by a name.
38+
by a domain name, never by an address or a numeric suffix of one.
3339
"""
3440
value = entry.strip().rstrip(".").lower()
3541
wildcard = value.startswith("*.")
@@ -48,9 +54,27 @@ def normalize_allowed_host(entry: str) -> str:
4854
ascii_name = httpx.URL(f"http://{name}/").raw_host.decode("ascii")
4955
except httpx.InvalidURL as e:
5056
raise ValueError(f"{entry!r} is not a valid host name: {e}") from None
57+
if wildcard and _ends_in_a_number(ascii_name):
58+
raise ValueError(
59+
f"{entry!r} puts a wildcard on an IP address: *.<domain> takes a "
60+
"domain name, and an address is listed exactly"
61+
)
5162
return f"*.{ascii_name}" if wildcard else ascii_name
5263

5364

65+
def _ends_in_a_number(name: str) -> bool:
66+
"""Whether a host's last label is a number, so it reads as an IPv4 address.
67+
68+
The test URL parsers apply: a host whose last label is decimal digits or
69+
``0x`` hex is an address (``10.0.0.1``, ``0.0.1``, ``1``, ``0x7f.1``),
70+
never a domain, since no top-level domain is numeric.
71+
"""
72+
last = name.rsplit(".", 1)[-1]
73+
if last.isascii() and last.isdigit():
74+
return True
75+
return last.startswith("0x") and all(c in "0123456789abcdef" for c in last[2:])
76+
77+
5478
def parse_allowed_host(entry: str) -> str:
5579
"""``normalize_allowed_host`` as an argparse ``type``, with its message."""
5680
try:
@@ -67,13 +91,15 @@ def normalize_allowed_hosts(entries: Iterable[str] | None) -> tuple[str, ...]:
6791
def host_is_allowed(host: str, allowed_hosts: tuple[str, ...]) -> bool:
6892
"""Whether ``host`` (a request's ``raw_host``) matches a normalized entry."""
6993
host = host.rstrip(".").lower()
94+
is_address = _ends_in_a_number(host)
7095
try:
7196
host = ipaddress.ip_address(host).compressed
97+
is_address = True
7298
except ValueError:
7399
pass
74100
for entry in allowed_hosts:
75101
if entry.startswith("*."):
76-
if host.endswith(entry[1:]):
102+
if not is_address and host.endswith(entry[1:]):
77103
return True
78104
elif host == entry:
79105
return True
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
"""``--allowed-hosts`` wildcards are for domain names, never addresses (#5521).
2+
3+
``*.0.0.1`` used to be accepted and then matched, as a suffix, every IPv4
4+
literal ending ``.0.0.1``: 10.0.0.1 and 127.0.0.1 alike. These tests pin both
5+
halves of the fix: such an entry is refused when the list is read, and an
6+
IP-literal host is never matched by a wildcard entry, even one that reached
7+
``host_is_allowed`` without going through ``normalize_allowed_host``. The
8+
last test builds the real server, which refuses to start on such a list.
9+
"""
10+
11+
from __future__ import annotations
12+
13+
import argparse
14+
15+
import pytest
16+
17+
from mcp_server_fetch.allowlist import (
18+
host_is_allowed,
19+
normalize_allowed_host,
20+
normalize_allowed_hosts,
21+
parse_allowed_host,
22+
)
23+
24+
25+
@pytest.mark.parametrize(
26+
"entry",
27+
[
28+
"*.10.0.0.1",
29+
"*.0.0.1",
30+
"*.1",
31+
"*.0.0.1.",
32+
"*.[::1]",
33+
"*.::1",
34+
"*.0x7f.1",
35+
"*.0x",
36+
"*.example.123",
37+
" *.0.0.1 ",
38+
],
39+
)
40+
def test_wildcard_address_entries_are_rejected(entry: str) -> None:
41+
with pytest.raises(ValueError):
42+
normalize_allowed_host(entry)
43+
44+
45+
def test_the_rejection_says_what_a_wildcard_takes() -> None:
46+
with pytest.raises(argparse.ArgumentTypeError, match="wildcard on an IP address"):
47+
parse_allowed_host("*.0.0.1")
48+
49+
50+
@pytest.mark.parametrize(
51+
("entry", "normalized"),
52+
[
53+
("*.example.com", "*.example.com"),
54+
("*.1.example.com", "*.1.example.com"),
55+
("*.123abc", "*.123abc"),
56+
("*.0xyz", "*.0xyz"),
57+
("*.xn--p1ai", "*.xn--p1ai"),
58+
("10.0.0.1", "10.0.0.1"),
59+
("[::1]", "::1"),
60+
],
61+
)
62+
def test_domain_wildcards_and_exact_addresses_are_still_accepted(
63+
entry: str, normalized: str
64+
) -> None:
65+
assert normalize_allowed_host(entry) == normalized
66+
67+
68+
@pytest.mark.parametrize(
69+
"host", ["127.0.0.1", "10.0.0.1", "10.0.0.1.", "0x7f.0.0.1", "8.0.0.1"]
70+
)
71+
def test_a_wildcard_entry_never_matches_an_address(host: str) -> None:
72+
# Entries given already-normalized, as a caller bypassing the parser could.
73+
assert host_is_allowed(host, ("*.0.0.1",)) is False
74+
75+
76+
def test_a_wildcard_entry_never_matches_an_ipv6_address() -> None:
77+
assert host_is_allowed("2001:db8::7", ("*.db8::7", "*.7")) is False
78+
79+
80+
def test_an_address_still_matches_its_exact_entry() -> None:
81+
entries = normalize_allowed_hosts(["*.example.com", "10.0.0.1", "[2001:db8::7]"])
82+
assert host_is_allowed("10.0.0.1", entries) is True
83+
assert host_is_allowed("2001:DB8:0::7", entries) is True
84+
assert host_is_allowed("127.0.0.1", entries) is False
85+
assert host_is_allowed("a.example.com", entries) is True
86+
87+
88+
def test_create_server_rejects_a_wildcard_address_entry() -> None:
89+
from mcp_server_fetch.server import create_server
90+
91+
with pytest.raises(ValueError, match="wildcard on an IP address"):
92+
create_server(allowed_hosts=["*.0.0.1"])

0 commit comments

Comments
 (0)