From 5ea8fa1ebcf34a990def22fcc7ff3aad4e001c5e Mon Sep 17 00:00:00 2001 From: Rahul selvaraj Date: Tue, 1 Dec 2026 10:32:50 +0800 Subject: [PATCH] fix(mcp): let operators declare Fake-IP ranges for self-service servers (#2857) * fix(mcp): let operators declare Fake-IP ranges for self-service servers A local proxy in Fake-IP mode (Loon, Clash, Surge) answers DNS for public hostnames with synthetic private addresses, e.g. fd27:712::/32 from Loon, and routes the connection by hostname. Strict validation then rejects public MCP Store entries such as GitMCP as private-network targets. Add DEEPTUTOR_MCP_FAKE_IP_RANGES (comma separated CIDRs, opt-in, read from the process environment). In strict mode an address a hostname resolves to inside a declared range is no longer rejected as private. IP-literal URLs, loopback and the link-local/metadata ranges stay blocked regardless, and any other private answer for the same host still fails validation. Closes #2789 Assisted-by: Claude * fix(mcp): warn on Fake-IP opt-in and document single-user SSRF trade-offs Address review feedback from JinhangHE126 on #2857: Document clearly that DEEPTUTOR_MCP_FAKE_IP_RANGES relaxes hostname-based SSRF protection for hostnames resolving into declared ranges (as the proxy resolves targets and connects). Emit a startup security warning when DEEPTUTOR_MCP_FAKE_IP_RANGES is set, noting that the setting is intended strictly for single-user/desktop installations. Assisted-by: Gemini (Google Vertex AI) --- deeptutor/api/main.py | 4 + deeptutor/services/mcp/network.py | 80 +++++++++++++++++++- tests/services/mcp/test_mcp_config.py | 101 +++++++++++++++++++++++++- 3 files changed, 182 insertions(+), 3 deletions(-) diff --git a/deeptutor/api/main.py b/deeptutor/api/main.py index f48dde2e9..cad633e34 100644 --- a/deeptutor/api/main.py +++ b/deeptutor/api/main.py @@ -118,6 +118,10 @@ async def lifespan(app: FastAPI): # Validate configuration consistency validate_tool_consistency() + from deeptutor.services.mcp.network import warn_fake_ip_config_if_set + + warn_fake_ip_config_if_set() + # Build one process-level dependency graph. Every adapter resolves turns # through this container, so a WebSocket cannot accidentally construct a # second store/runtime for the same authenticated scope. diff --git a/deeptutor/services/mcp/network.py b/deeptutor/services/mcp/network.py index 267590bbd..0953ad047 100644 --- a/deeptutor/services/mcp/network.py +++ b/deeptutor/services/mcp/network.py @@ -23,14 +23,33 @@ is what makes per-user MCP configuration safe to offer at all. Validation is deliberately re-run at connect time, not only when a server is saved: a check that happens once at save time is defeated by a DNS record that changes afterwards. + +**Fake-IP proxies.** A local proxy in Fake-IP mode (Loon, Clash, Surge, ...) +answers DNS for public hostnames with synthetic addresses from a private range +(for example ``fd27:712::/32``) and routes the connection by hostname. The +operator can list those ranges in ``DEEPTUTOR_MCP_FAKE_IP_RANGES`` (comma +separated CIDRs). Within them, an address a *hostname* resolves to is not +rejected as private in strict mode. IP-literal URLs, loopback and the +link-local / metadata ranges above stay blocked whatever the setting says. + +**Security Trade-off & Single-User Notice:** Declaring Fake-IP ranges disables +hostname-based SSRF protection for hostnames that resolve to addresses within +those ranges, because the proxy resolves the real target hostname and connects. +This setting is intended strictly for single-user / desktop installations. """ from __future__ import annotations import ipaddress +import logging +import os import socket from urllib.parse import urlparse +logger = logging.getLogger(__name__) + +FAKE_IP_RANGES_ENV = "DEEPTUTOR_MCP_FAKE_IP_RANGES" + _BLOCKED_NETWORKS = [ ipaddress.ip_network("0.0.0.0/8"), ipaddress.ip_network("169.254.0.0/16"), # link-local / cloud metadata @@ -72,6 +91,59 @@ def _is_blocked( return any(normalized in net for net in networks) +_LOOPBACK = (ipaddress.ip_network("127.0.0.0/8"), ipaddress.ip_network("::1/128")) + +_fake_ip_warned = False + + +def warn_fake_ip_config_if_set() -> bool: + """Log a startup security warning if DEEPTUTOR_MCP_FAKE_IP_RANGES is set. + + Declaring Fake-IP ranges disables hostname-based SSRF protection for hostnames + that resolve to synthetic addresses within those ranges, as the proxy resolves the + target hostname and connects. This opt-in is intended strictly for single-user / + desktop installations. + """ + global _fake_ip_warned + if _fake_ip_warned: + return False + raw = os.environ.get(FAKE_IP_RANGES_ENV, "").strip() + if not raw: + return False + logger.warning( + "%s is set (%r). Declaring Fake-IP ranges disables hostname-based SSRF protection " + "for target hostnames resolving into these ranges. This opt-in is intended for " + "single-user/desktop installs only.", + FAKE_IP_RANGES_ENV, + raw, + ) + _fake_ip_warned = True + return True + + +def _fake_ip_networks() -> tuple[ipaddress.IPv4Network | ipaddress.IPv6Network, ...]: + """Ranges the operator declared as Fake-IP proxy answers (read per call).""" + warn_fake_ip_config_if_set() + networks = [] + for item in os.environ.get(FAKE_IP_RANGES_ENV, "").split(","): + item = item.strip() + if not item: + continue + try: + networks.append(ipaddress.ip_network(item, strict=False)) + except ValueError: + logger.warning("Ignoring invalid %s entry %r", FAKE_IP_RANGES_ENV, item) + return tuple(networks) + + +def _is_hostname(host: str) -> bool: + try: + ipaddress.ip_address(host) + except ValueError: + return True + return False + + def validate_mcp_url( url: str, *, strict: bool = False, trusted_origin: str | None = None ) -> tuple[bool, str]: @@ -105,6 +177,7 @@ def validate_mcp_url( except socket.gaierror: return False, f"Cannot resolve hostname: {hostname}" + fake_ip_networks = _fake_ip_networks() if strict and _is_hostname(hostname) else () resolved = False for info in infos: try: @@ -114,8 +187,11 @@ def validate_mcp_url( resolved = True normalized = _normalize_addr(addr) approved_rfc1918 = private_allowed and any(normalized in network for network in _RFC1918) + fake_ip = any(normalized in network for network in fake_ip_networks) and not any( + normalized in network for network in _LOOPBACK + ) if _is_blocked(addr, strict=False) or ( - _is_blocked(addr, strict=strict) and not approved_rfc1918 + _is_blocked(addr, strict=strict) and not (approved_rfc1918 or fake_ip) ): return False, ( f"Blocked: {hostname} resolves to a disallowed address ({addr}). " @@ -143,7 +219,7 @@ async def validate_mcp_url_async( ) -__all__ = ["validate_mcp_url", "validate_mcp_url_async"] +__all__ = ["validate_mcp_url", "validate_mcp_url_async", "warn_fake_ip_config_if_set"] _RFC1918 = tuple( diff --git a/tests/services/mcp/test_mcp_config.py b/tests/services/mcp/test_mcp_config.py index 04f56ef2c..6d03287e9 100644 --- a/tests/services/mcp/test_mcp_config.py +++ b/tests/services/mcp/test_mcp_config.py @@ -6,7 +6,7 @@ import pytest from deeptutor.services.mcp.config import MCPConfig, MCPServerConfig from deeptutor.services.mcp.manager import wrapped_tool_name -from deeptutor.services.mcp.network import validate_mcp_url +from deeptutor.services.mcp.network import validate_mcp_url, warn_fake_ip_config_if_set def test_resolved_type_stdio() -> None: @@ -91,3 +91,102 @@ def test_ssrf_allows_public_host() -> None: ok, error = validate_mcp_url("https://localhost/mcp") # localhost resolves to loopback which is allowed (not in blocklist) assert ok or "resolve" in error.lower() + + +def _resolve_to(monkeypatch: pytest.MonkeyPatch, *addresses: str) -> None: + import socket + + def fake_getaddrinfo(host, *args, **kwargs): + return [ + ( + socket.AF_INET6 if ":" in address else socket.AF_INET, + socket.SOCK_STREAM, + 6, + "", + (address, 0), + ) + for address in addresses + ] + + monkeypatch.setattr("deeptutor.services.mcp.network.socket.getaddrinfo", fake_getaddrinfo) + + +def test_strict_blocks_fake_ip_answer_without_opt_in(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.delenv("DEEPTUTOR_MCP_FAKE_IP_RANGES", raising=False) + _resolve_to(monkeypatch, "fd27:712::c600:116b") + ok, error = validate_mcp_url("https://gitmcp.io/docs", strict=True) + assert not ok + assert "fd27:712::c600:116b" in error + + +def test_strict_allows_hostname_in_declared_fake_ip_range( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv("DEEPTUTOR_MCP_FAKE_IP_RANGES", "198.18.0.0/15, fd27:712::/32") + _resolve_to(monkeypatch, "198.18.0.42", "fd27:712::c600:116b") + assert validate_mcp_url("https://gitmcp.io/docs", strict=True) == (True, "") + + +def test_fake_ip_range_does_not_exempt_other_private_answers( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv("DEEPTUTOR_MCP_FAKE_IP_RANGES", "fd27:712::/32") + _resolve_to(monkeypatch, "fd27:712::c600:116b", "10.0.0.5") + ok, error = validate_mcp_url("https://gitmcp.io/docs", strict=True) + assert not ok + assert "10.0.0.5" in error + + +def test_fake_ip_range_does_not_exempt_ip_literals(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("DEEPTUTOR_MCP_FAKE_IP_RANGES", "fd27:712::/32") + _resolve_to(monkeypatch, "fd27:712::c600:116b") + ok, _ = validate_mcp_url("https://[fd27:712::c600:116b]/mcp", strict=True) + assert not ok + + +@pytest.mark.parametrize( + ("declared", "address"), + [ + ("127.0.0.0/8", "127.0.0.1"), + ("::/0", "::1"), + ("::/0", "::ffff:127.0.0.1"), + ("169.254.0.0/16", "169.254.169.254"), + ("fc00::/7", "fd00:ec2::254"), + ], +) +def test_fake_ip_range_never_exempts_loopback_or_metadata( + monkeypatch: pytest.MonkeyPatch, declared: str, address: str +) -> None: + monkeypatch.setenv("DEEPTUTOR_MCP_FAKE_IP_RANGES", declared) + _resolve_to(monkeypatch, address) + ok, _ = validate_mcp_url("https://gitmcp.io/docs", strict=True) + assert not ok + + +def test_invalid_fake_ip_entries_are_ignored(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("DEEPTUTOR_MCP_FAKE_IP_RANGES", "not-a-range, fd27:712::/32") + _resolve_to(monkeypatch, "fd27:712::c600:116b") + assert validate_mcp_url("https://gitmcp.io/docs", strict=True) == (True, "") + + +def test_warn_fake_ip_config_if_set_logs_warning( + monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + monkeypatch.setattr("deeptutor.services.mcp.network._fake_ip_warned", False) + monkeypatch.setenv("DEEPTUTOR_MCP_FAKE_IP_RANGES", "198.18.0.0/15") + with caplog.at_level("WARNING"): + logged = warn_fake_ip_config_if_set() + assert logged is True + assert "DEEPTUTOR_MCP_FAKE_IP_RANGES is set" in caplog.text + assert "single-user/desktop installs only" in caplog.text + + +def test_warn_fake_ip_config_if_set_noop_when_empty( + monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + monkeypatch.setattr("deeptutor.services.mcp.network._fake_ip_warned", False) + monkeypatch.delenv("DEEPTUTOR_MCP_FAKE_IP_RANGES", raising=False) + with caplog.at_level("WARNING"): + logged = warn_fake_ip_config_if_set() + assert logged is False + assert "DEEPTUTOR_MCP_FAKE_IP_RANGES" not in caplog.text