""" Network guards for remote MCP servers (SSRF protection). Two postures, because the two kinds of server carry different trust: **Deployment servers** (an administrator's ``mcp.json``) keep the original, permissive rules. A self-hosted deployment legitimately runs MCP servers on localhost or its own LAN, and the administrator already has host access, so the guard only has to stop *accidental* dangerous targets: link-local / cloud-metadata ranges (169.254.0.0/16 — 169.254.169.254 is the classic credential-theft target — and fe80::/10) plus the 0.0.0.0/8 "this network" range. **Self-service servers** (a user's own, ``strict=True``) additionally lose loopback and private ranges. The request is made by the *app process*, which holds every provider API key and shares a network with PocketBase and the sandbox runner; a URL a user supplies must not be able to aim it inward. An explicit ``allow_private_network`` selection can use RFC1918 addresses only for an origin approved in the administrator-owned registry; metadata and loopback remain blocked for self-service callers. This 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 ipaddress.ip_network("fe80::/10"), ipaddress.ip_network("fd00:ec2::254/128"), ipaddress.ip_network("100.100.100.200/32"), ipaddress.ip_network("::/128"), # link-local v6 ] # Additionally blocked for user-supplied URLs: everything that points back at # the deployment itself or its private network. _STRICT_EXTRA_NETWORKS = [ ipaddress.ip_network("127.0.0.0/8"), ipaddress.ip_network("10.0.0.0/8"), ipaddress.ip_network("172.16.0.0/12"), ipaddress.ip_network("192.168.0.0/16"), ipaddress.ip_network("100.64.0.0/10"), # carrier-grade NAT / tailscale ipaddress.ip_network("::1/128"), ipaddress.ip_network("fc00::/7"), # unique-local v6 ] def _normalize_addr( addr: ipaddress.IPv4Address | ipaddress.IPv6Address, ) -> ipaddress.IPv4Address | ipaddress.IPv6Address: """Normalize IPv6-mapped IPv4 addresses (``::ffff:169.254.x.x``) to IPv4.""" if isinstance(addr, ipaddress.IPv6Address) and addr.ipv4_mapped is not None: return addr.ipv4_mapped return addr def _is_blocked( addr: ipaddress.IPv4Address | ipaddress.IPv6Address, *, strict: bool, ) -> bool: normalized = _normalize_addr(addr) networks = _BLOCKED_NETWORKS + (_STRICT_EXTRA_NETWORKS if strict else []) 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]: """Validate a remote MCP server URL: scheme, hostname, resolved IPs. ``strict`` applies the self-service posture (see the module docstring): a user-supplied URL may not resolve to loopback or a private range. Returns ``(ok, error_message)``; ``error_message`` is empty when ok. """ try: parsed = urlparse(url) except Exception as exc: return False, str(exc) if parsed.scheme not in ("http", "https"): return False, f"Only http/https allowed, got {parsed.scheme or 'none'!r}" try: _ = parsed.port except ValueError as exc: return False, str(exc) hostname = parsed.hostname if not hostname: return False, "Missing hostname" if parsed.username or parsed.password or parsed.fragment: return False, "MCP URLs must not contain embedded credentials or fragments" private_allowed = trusted_origin is not None and mcp_origin(url) == trusted_origin try: infos = socket.getaddrinfo(hostname, None, socket.AF_UNSPEC, socket.SOCK_STREAM) 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: addr = ipaddress.ip_address(info[4][0]) except ValueError: continue 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 or fake_ip) ): return False, ( f"Blocked: {hostname} resolves to a disallowed address ({addr}). " "A server you configure yourself must be reachable on the public internet." if strict else f"Blocked: {hostname} resolves to link-local/metadata address {addr}" ) return (True, "") if resolved else (False, "No usable address resolved for this MCP host") async def validate_mcp_url_async( url: str, *, strict: bool = False, trusted_origin: str | None = None ) -> tuple[bool, str]: """:func:`validate_mcp_url` off the event loop. The check resolves DNS with a blocking call, which on a slow or dead resolver stalls for seconds. On the event loop that is not one slow request — it is every request in the process, so any caller already inside async code uses this. """ import asyncio return await asyncio.to_thread( validate_mcp_url, url, strict=strict, trusted_origin=trusted_origin ) __all__ = ["validate_mcp_url", "validate_mcp_url_async", "warn_fake_ip_config_if_set"] _RFC1918 = tuple( ipaddress.ip_network(value) for value in ("10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16") ) def mcp_origin(url: str) -> str: parsed = urlparse(url) if ( parsed.scheme not in {"http", "https"} or not parsed.hostname or parsed.username or parsed.password ): raise ValueError( "A trusted MCP origin must be an http(s) server without embedded credentials" ) host = parsed.hostname.casefold().rstrip(".") if ":" in host: host = f"[{host}]" port = parsed.port or (443 if parsed.scheme == "https" else 80) return f"{parsed.scheme}://{host}:{port}" def approved_private_origin(url: str) -> str | None: """An admin-owned server approval grants only its exact scheme/host/port.""" from deeptutor.services.mcp.config import load_mcp_config origin = mcp_origin(url) for cfg in load_mcp_config().servers.values(): if not cfg.allow_private_network or cfg.resolved_type() not in {"sse", "streamableHttp"}: continue try: if mcp_origin(cfg.url) == origin: return origin except ValueError: continue return None