From 570e8abf01ac024195359b13c8b2535717acba66 Mon Sep 17 00:00:00 2001 From: user <70670632+stuxf@users.noreply.github.com> Date: Thu, 16 Apr 2026 04:13:54 +0000 Subject: [PATCH 01/12] fix(proxy): add SSRF protection via resolve-and-rewrite for user-supplied URLs Add validate_url() utility that resolves DNS once, validates all IPs against private network ranges, and rewrites the URL to connect to the validated IP directly. Prevents DNS rebinding by pinning to the resolved IP. Disable follow_redirects to prevent redirect-based SSRF bypasses. Applied to all user-supplied URL entry points: - Image URL fetching in chat completions - Token counter image dimension fetching - RAG file ingestion - MCP OpenAPI spec loading --- .../prompt_templates/image_handling.py | 19 ++- litellm/litellm_core_utils/token_counter.py | 10 +- .../mcp_server/openapi_to_mcp_generator.py | 10 +- litellm/proxy/common_utils/url_utils.py | 123 ++++++++++++++++++ litellm/rag/ingestion/base_ingestion.py | 8 +- 5 files changed, 162 insertions(+), 8 deletions(-) create mode 100644 litellm/proxy/common_utils/url_utils.py diff --git a/litellm/litellm_core_utils/prompt_templates/image_handling.py b/litellm/litellm_core_utils/prompt_templates/image_handling.py index eaf78b7bcf5a..c07276991678 100644 --- a/litellm/litellm_core_utils/prompt_templates/image_handling.py +++ b/litellm/litellm_core_utils/prompt_templates/image_handling.py @@ -10,6 +10,7 @@ from litellm import verbose_logger from litellm.caching.caching import InMemoryCache from litellm.constants import MAX_IMAGE_URL_DOWNLOAD_SIZE_MB +from litellm.proxy.common_utils.url_utils import SSRFError, validate_url MAX_IMGS_IN_MEMORY = 10 @@ -81,10 +82,17 @@ async def async_convert_url_to_base64(url: str) -> str: if cached_result: return cached_result + # Resolve DNS once, validate IPs, rewrite URL to validated IP + validated_url, original_host = validate_url(url) + client = litellm.module_level_aclient for _ in range(3): try: - response = await client.get(url, follow_redirects=True) + response = await client.get( + validated_url, + headers={"Host": original_host}, + follow_redirects=False, + ) return _process_image_response(response, url) except litellm.ImageFetchError: raise @@ -106,10 +114,17 @@ def convert_url_to_base64(url: str) -> str: if cached_result: return cached_result + # Resolve DNS once, validate IPs, rewrite URL to validated IP + validated_url, original_host = validate_url(url) + client = litellm.module_level_client for _ in range(3): try: - response = client.get(url, follow_redirects=True) + response = client.get( + validated_url, + headers={"Host": original_host}, + follow_redirects=False, + ) return _process_image_response(response, url) except litellm.ImageFetchError: raise diff --git a/litellm/litellm_core_utils/token_counter.py b/litellm/litellm_core_utils/token_counter.py index 09c62f2eb556..e2d2a56c6981 100644 --- a/litellm/litellm_core_utils/token_counter.py +++ b/litellm/litellm_core_utils/token_counter.py @@ -30,6 +30,7 @@ ) from litellm.litellm_core_utils.default_encoding import encoding as default_encoding from litellm.llms.custom_httpx.http_handler import _get_httpx_client +from litellm.proxy.common_utils.url_utils import validate_url from litellm.types.llms.anthropic import ( AnthropicMessagesToolResultParam, AnthropicMessagesToolUseParam, @@ -211,9 +212,14 @@ def get_image_dimensions( """ img_data = None try: - # Try to open as URL + # Try to open as URL — validate and pin to resolved IP + validated_url, original_host = validate_url(data) client = _get_httpx_client() - response = client.get(data) + response = client.get( + validated_url, + headers={"Host": original_host}, + follow_redirects=False, + ) img_data = response.read() except Exception: # If not URL, assume it's base64 diff --git a/litellm/proxy/_experimental/mcp_server/openapi_to_mcp_generator.py b/litellm/proxy/_experimental/mcp_server/openapi_to_mcp_generator.py index 4b4818892bb4..68f52f343955 100644 --- a/litellm/proxy/_experimental/mcp_server/openapi_to_mcp_generator.py +++ b/litellm/proxy/_experimental/mcp_server/openapi_to_mcp_generator.py @@ -15,6 +15,7 @@ get_async_httpx_client, httpxSpecialProvider, ) +from litellm.proxy.common_utils.url_utils import validate_url from litellm.proxy._experimental.mcp_server.tool_registry import ( global_mcp_tool_registry, ) @@ -74,10 +75,13 @@ def load_openapi_spec(filepath: str) -> Dict[str, Any]: async def load_openapi_spec_async(filepath: str) -> Dict[str, Any]: if filepath.startswith("http://") or filepath.startswith("https://"): + validated_url, original_host = validate_url(filepath) client = get_async_httpx_client(llm_provider=httpxSpecialProvider.MCP) - # NOTE: do not close shared client if get_async_httpx_client returns a shared singleton. - # If it returns a new client each time, consider wrapping it in an async context manager. - r = await client.get(filepath) + r = await client.get( + validated_url, + headers={"Host": original_host}, + follow_redirects=False, + ) r.raise_for_status() return r.json() diff --git a/litellm/proxy/common_utils/url_utils.py b/litellm/proxy/common_utils/url_utils.py new file mode 100644 index 000000000000..97fee0c09653 --- /dev/null +++ b/litellm/proxy/common_utils/url_utils.py @@ -0,0 +1,123 @@ +""" +URL validation for user-controlled URLs. + +Use validate_url() before fetching any URL that originates from user +input (image_url, file_url, spec_path, etc.) to prevent SSRF attacks. + +The function resolves DNS once, validates all IPs, and rewrites the URL +to connect to the validated IP directly — no TOCTOU gap, no DNS rebinding. +Callers should also set follow_redirects=False to prevent redirect-based +SSRF bypasses. +""" + +import ipaddress +import socket +from ipaddress import ip_address, ip_network +from typing import Optional, Tuple +from urllib.parse import urlparse, urlunparse + +_BLOCKED_NETWORKS = [ + ip_network("0.0.0.0/8"), + ip_network("10.0.0.0/8"), + ip_network("100.64.0.0/10"), + ip_network("127.0.0.0/8"), + ip_network("169.254.0.0/16"), + ip_network("172.16.0.0/12"), + ip_network("192.0.0.0/24"), + ip_network("192.168.0.0/16"), + ip_network("198.18.0.0/15"), + ip_network("::1/128"), + ip_network("fc00::/7"), + ip_network("fe80::/10"), +] + +_ALLOWED_SCHEMES = ("http", "https") + + +class SSRFError(ValueError): + """Raised when a URL targets a blocked network.""" + + pass + + +def _is_blocked_ip(addr: str) -> bool: + try: + ip = ip_address(addr) + except ValueError: + return False + if ip.version == 6 and hasattr(ip, "ipv4_mapped") and ip.ipv4_mapped: + ip = ip.ipv4_mapped + return any(ip in net for net in _BLOCKED_NETWORKS) + + +def validate_url(url: str) -> Tuple[str, str]: + """ + Validate a user-supplied URL and rewrite it to connect to a validated IP. + + Resolves the hostname, checks all resolved IPs against blocked networks, + then returns a rewritten URL that points to the validated IP along with + the original hostname (for use in the Host header). + + This eliminates DNS rebinding because the caller connects to the IP we + validated, not the hostname that could rebind. Callers should also disable + follow_redirects to prevent redirect-based SSRF bypasses. + + Args: + url: The user-supplied URL to validate. + + Returns: + Tuple of (rewritten_url, original_hostname). + The rewritten URL has the hostname replaced with the validated IP. + The original hostname should be set as the Host header. + + Raises: + SSRFError: If the URL scheme is invalid or the hostname resolves + to a private/internal IP address. + """ + parsed = urlparse(url) + + if parsed.scheme not in _ALLOWED_SCHEMES: + raise SSRFError(f"URL scheme '{parsed.scheme}' is not allowed") + + hostname = parsed.hostname + if not hostname: + raise SSRFError("URL has no hostname") + + port = parsed.port + default_port = 443 if parsed.scheme == "https" else 80 + + # Resolve hostname and validate ALL addresses + try: + addrinfo = socket.getaddrinfo( + hostname, port or default_port, proto=socket.IPPROTO_TCP + ) + except socket.gaierror as e: + raise SSRFError(f"DNS resolution failed for '{hostname}': {e}") + + if not addrinfo: + raise SSRFError(f"No addresses found for '{hostname}'") + + for family, type_, proto, canonname, sockaddr in addrinfo: + if _is_blocked_ip(sockaddr[0]): + raise SSRFError( + f"URL targets a blocked address ({sockaddr[0]}). " + "If this is a legitimate internal service, use a direct " + "provider configuration instead of a user-supplied URL." + ) + + # Rewrite URL to connect to the first validated IP + validated_ip = addrinfo[0][4][0] + is_ipv6 = addrinfo[0][0] == socket.AF_INET6 + ip_host = f"[{validated_ip}]" if is_ipv6 else validated_ip + + # Reconstruct netloc with IP instead of hostname + if port: + new_netloc = f"{ip_host}:{port}" + else: + new_netloc = ip_host + + rewritten = urlunparse( + (parsed.scheme, new_netloc, parsed.path, parsed.params, parsed.query, "") + ) + + return rewritten, hostname diff --git a/litellm/rag/ingestion/base_ingestion.py b/litellm/rag/ingestion/base_ingestion.py index 0d12bdfffc1f..1d868d35c7a8 100644 --- a/litellm/rag/ingestion/base_ingestion.py +++ b/litellm/rag/ingestion/base_ingestion.py @@ -24,6 +24,7 @@ get_async_httpx_client, httpxSpecialProvider, ) +from litellm.proxy.common_utils.url_utils import validate_url from litellm.rag.ingestion.file_parsers import extract_text_from_pdf from litellm.rag.text_splitters import RecursiveCharacterTextSplitter from litellm.types.rag import RAGIngestOptions, RAGIngestResponse @@ -111,8 +112,13 @@ async def upload( return filename, file_content, content_type, None if file_url: + validated_url, original_host = validate_url(file_url) http_client = get_async_httpx_client(llm_provider=httpxSpecialProvider.RAG) - response = await http_client.get(file_url) + response = await http_client.get( + validated_url, + headers={"Host": original_host}, + follow_redirects=False, + ) response.raise_for_status() file_content = response.content filename = file_url.split("/")[-1] or "document" From ba5e7c4fb88ef03c9623a25570917047db2734ed Mon Sep 17 00:00:00 2001 From: user <70670632+stuxf@users.noreply.github.com> Date: Thu, 16 Apr 2026 04:30:14 +0000 Subject: [PATCH 02/12] fix(proxy): add safe_get/async_safe_get with redirect validation Add safe_get() and async_safe_get() helpers that validate each redirect hop before following. For HTTPS, rely on TLS certificate binding instead of URL rewriting. Simplify call sites to use the new helpers. --- .../prompt_templates/image_handling.py | 20 +----- litellm/litellm_core_utils/token_counter.py | 11 +-- .../mcp_server/openapi_to_mcp_generator.py | 9 +-- litellm/proxy/common_utils/url_utils.py | 70 +++++++++++++++++-- litellm/rag/ingestion/base_ingestion.py | 9 +-- 5 files changed, 73 insertions(+), 46 deletions(-) diff --git a/litellm/litellm_core_utils/prompt_templates/image_handling.py b/litellm/litellm_core_utils/prompt_templates/image_handling.py index c07276991678..c036ec23ddb6 100644 --- a/litellm/litellm_core_utils/prompt_templates/image_handling.py +++ b/litellm/litellm_core_utils/prompt_templates/image_handling.py @@ -10,7 +10,7 @@ from litellm import verbose_logger from litellm.caching.caching import InMemoryCache from litellm.constants import MAX_IMAGE_URL_DOWNLOAD_SIZE_MB -from litellm.proxy.common_utils.url_utils import SSRFError, validate_url +from litellm.proxy.common_utils.url_utils import async_safe_get, safe_get MAX_IMGS_IN_MEMORY = 10 @@ -82,17 +82,10 @@ async def async_convert_url_to_base64(url: str) -> str: if cached_result: return cached_result - # Resolve DNS once, validate IPs, rewrite URL to validated IP - validated_url, original_host = validate_url(url) - client = litellm.module_level_aclient for _ in range(3): try: - response = await client.get( - validated_url, - headers={"Host": original_host}, - follow_redirects=False, - ) + response = await async_safe_get(client, url) return _process_image_response(response, url) except litellm.ImageFetchError: raise @@ -114,17 +107,10 @@ def convert_url_to_base64(url: str) -> str: if cached_result: return cached_result - # Resolve DNS once, validate IPs, rewrite URL to validated IP - validated_url, original_host = validate_url(url) - client = litellm.module_level_client for _ in range(3): try: - response = client.get( - validated_url, - headers={"Host": original_host}, - follow_redirects=False, - ) + response = safe_get(client, url) return _process_image_response(response, url) except litellm.ImageFetchError: raise diff --git a/litellm/litellm_core_utils/token_counter.py b/litellm/litellm_core_utils/token_counter.py index e2d2a56c6981..ad2691156a50 100644 --- a/litellm/litellm_core_utils/token_counter.py +++ b/litellm/litellm_core_utils/token_counter.py @@ -30,7 +30,7 @@ ) from litellm.litellm_core_utils.default_encoding import encoding as default_encoding from litellm.llms.custom_httpx.http_handler import _get_httpx_client -from litellm.proxy.common_utils.url_utils import validate_url +from litellm.proxy.common_utils.url_utils import safe_get from litellm.types.llms.anthropic import ( AnthropicMessagesToolResultParam, AnthropicMessagesToolUseParam, @@ -212,14 +212,9 @@ def get_image_dimensions( """ img_data = None try: - # Try to open as URL — validate and pin to resolved IP - validated_url, original_host = validate_url(data) + # Try to open as URL with SSRF protection client = _get_httpx_client() - response = client.get( - validated_url, - headers={"Host": original_host}, - follow_redirects=False, - ) + response = safe_get(client, data) img_data = response.read() except Exception: # If not URL, assume it's base64 diff --git a/litellm/proxy/_experimental/mcp_server/openapi_to_mcp_generator.py b/litellm/proxy/_experimental/mcp_server/openapi_to_mcp_generator.py index 68f52f343955..d6b2cb86b265 100644 --- a/litellm/proxy/_experimental/mcp_server/openapi_to_mcp_generator.py +++ b/litellm/proxy/_experimental/mcp_server/openapi_to_mcp_generator.py @@ -15,7 +15,7 @@ get_async_httpx_client, httpxSpecialProvider, ) -from litellm.proxy.common_utils.url_utils import validate_url +from litellm.proxy.common_utils.url_utils import async_safe_get from litellm.proxy._experimental.mcp_server.tool_registry import ( global_mcp_tool_registry, ) @@ -75,13 +75,8 @@ def load_openapi_spec(filepath: str) -> Dict[str, Any]: async def load_openapi_spec_async(filepath: str) -> Dict[str, Any]: if filepath.startswith("http://") or filepath.startswith("https://"): - validated_url, original_host = validate_url(filepath) client = get_async_httpx_client(llm_provider=httpxSpecialProvider.MCP) - r = await client.get( - validated_url, - headers={"Host": original_host}, - follow_redirects=False, - ) + r = await async_safe_get(client, filepath) r.raise_for_status() return r.json() diff --git a/litellm/proxy/common_utils/url_utils.py b/litellm/proxy/common_utils/url_utils.py index 97fee0c09653..0583cc3a42b4 100644 --- a/litellm/proxy/common_utils/url_utils.py +++ b/litellm/proxy/common_utils/url_utils.py @@ -4,16 +4,15 @@ Use validate_url() before fetching any URL that originates from user input (image_url, file_url, spec_path, etc.) to prevent SSRF attacks. -The function resolves DNS once, validates all IPs, and rewrites the URL -to connect to the validated IP directly — no TOCTOU gap, no DNS rebinding. -Callers should also set follow_redirects=False to prevent redirect-based -SSRF bypasses. +validate_url() resolves DNS once, validates all IPs, and rewrites the +URL to connect to the validated IP directly — no TOCTOU gap, no DNS +rebinding. Redirects are followed manually with validation at each hop. """ import ipaddress import socket from ipaddress import ip_address, ip_network -from typing import Optional, Tuple +from typing import Any, Optional, Tuple, Union from urllib.parse import urlparse, urlunparse _BLOCKED_NETWORKS = [ @@ -105,12 +104,18 @@ def validate_url(url: str) -> Tuple[str, str]: "provider configuration instead of a user-supplied URL." ) - # Rewrite URL to connect to the first validated IP + # For HTTPS, TLS certificate validation binds the connection to the + # hostname — DNS rebinding can't redirect to a different server because + # the cert wouldn't match. Return the original URL. + if parsed.scheme == "https": + return url, hostname + + # For HTTP, rewrite URL to connect to the validated IP directly + # to prevent DNS rebinding (no TLS to bind the connection). validated_ip = addrinfo[0][4][0] is_ipv6 = addrinfo[0][0] == socket.AF_INET6 ip_host = f"[{validated_ip}]" if is_ipv6 else validated_ip - # Reconstruct netloc with IP instead of hostname if port: new_netloc = f"{ip_host}:{port}" else: @@ -121,3 +126,54 @@ def validate_url(url: str) -> Tuple[str, str]: ) return rewritten, hostname + + +_MAX_REDIRECTS = 10 + + +def safe_get(client: Any, url: str, **kwargs: Any) -> Any: + """ + Fetch a user-supplied URL with SSRF protection on every redirect hop. + + Validates the initial URL and each redirect target before making the + request. No DNS rebinding (resolve-and-rewrite). No redirect bypass + (each hop validated). No breaking change for legitimate CDN redirects. + + Args: + client: An httpx.Client or httpx.AsyncClient (sync version). + url: The user-supplied URL. + **kwargs: Additional kwargs passed to client.get(). + + Returns: + The final httpx.Response. + """ + kwargs.pop("follow_redirects", None) + for _ in range(_MAX_REDIRECTS): + validated_url, original_host = validate_url(url) + response = client.get( + validated_url, + headers={**kwargs.pop("headers", {}), "Host": original_host}, + follow_redirects=False, + **kwargs, + ) + if not response.is_redirect or response.next_request is None: + return response + url = str(response.next_request.url) + raise SSRFError("Too many redirects") + + +async def async_safe_get(client: Any, url: str, **kwargs: Any) -> Any: + """Async version of safe_get.""" + kwargs.pop("follow_redirects", None) + for _ in range(_MAX_REDIRECTS): + validated_url, original_host = validate_url(url) + response = await client.get( + validated_url, + headers={**kwargs.pop("headers", {}), "Host": original_host}, + follow_redirects=False, + **kwargs, + ) + if not response.is_redirect or response.next_request is None: + return response + url = str(response.next_request.url) + raise SSRFError("Too many redirects") diff --git a/litellm/rag/ingestion/base_ingestion.py b/litellm/rag/ingestion/base_ingestion.py index 1d868d35c7a8..6f139764a857 100644 --- a/litellm/rag/ingestion/base_ingestion.py +++ b/litellm/rag/ingestion/base_ingestion.py @@ -24,7 +24,7 @@ get_async_httpx_client, httpxSpecialProvider, ) -from litellm.proxy.common_utils.url_utils import validate_url +from litellm.proxy.common_utils.url_utils import async_safe_get from litellm.rag.ingestion.file_parsers import extract_text_from_pdf from litellm.rag.text_splitters import RecursiveCharacterTextSplitter from litellm.types.rag import RAGIngestOptions, RAGIngestResponse @@ -112,13 +112,8 @@ async def upload( return filename, file_content, content_type, None if file_url: - validated_url, original_host = validate_url(file_url) http_client = get_async_httpx_client(llm_provider=httpxSpecialProvider.RAG) - response = await http_client.get( - validated_url, - headers={"Host": original_host}, - follow_redirects=False, - ) + response = await async_safe_get(http_client, file_url) response.raise_for_status() file_content = response.content filename = file_url.split("/")[-1] or "document" From c0b677d103e48592ef0a20298180cea45a7f94fc Mon Sep 17 00:00:00 2001 From: user <70670632+stuxf@users.noreply.github.com> Date: Thu, 16 Apr 2026 04:38:29 +0000 Subject: [PATCH 03/12] fix: preserve caller headers across redirect hops in safe_get --- litellm/proxy/common_utils/url_utils.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/litellm/proxy/common_utils/url_utils.py b/litellm/proxy/common_utils/url_utils.py index 0583cc3a42b4..2a160d3cec73 100644 --- a/litellm/proxy/common_utils/url_utils.py +++ b/litellm/proxy/common_utils/url_utils.py @@ -148,11 +148,12 @@ def safe_get(client: Any, url: str, **kwargs: Any) -> Any: The final httpx.Response. """ kwargs.pop("follow_redirects", None) + caller_headers = kwargs.pop("headers", {}) for _ in range(_MAX_REDIRECTS): validated_url, original_host = validate_url(url) response = client.get( validated_url, - headers={**kwargs.pop("headers", {}), "Host": original_host}, + headers={**caller_headers, "Host": original_host}, follow_redirects=False, **kwargs, ) @@ -165,11 +166,12 @@ def safe_get(client: Any, url: str, **kwargs: Any) -> Any: async def async_safe_get(client: Any, url: str, **kwargs: Any) -> Any: """Async version of safe_get.""" kwargs.pop("follow_redirects", None) + caller_headers = kwargs.pop("headers", {}) for _ in range(_MAX_REDIRECTS): validated_url, original_host = validate_url(url) response = await client.get( validated_url, - headers={**kwargs.pop("headers", {}), "Host": original_host}, + headers={**caller_headers, "Host": original_host}, follow_redirects=False, **kwargs, ) From 70438642c16bea64dd687b8ec65c235ea5014b81 Mon Sep 17 00:00:00 2001 From: user <70670632+stuxf@users.noreply.github.com> Date: Thu, 16 Apr 2026 04:40:54 +0000 Subject: [PATCH 04/12] fix: skip DNS resolution for base64 data in token counter, add unit tests Check URL scheme before calling safe_get in token counter to avoid unnecessary DNS resolution on base64-encoded image data. Add 14 unit tests for validate_url covering blocked networks, scheme validation, URL rewriting, and DNS failure handling. --- litellm/litellm_core_utils/token_counter.py | 16 +++-- .../proxy/common_utils/test_url_utils.py | 64 +++++++++++++++++++ 2 files changed, 73 insertions(+), 7 deletions(-) create mode 100644 tests/test_litellm/proxy/common_utils/test_url_utils.py diff --git a/litellm/litellm_core_utils/token_counter.py b/litellm/litellm_core_utils/token_counter.py index ad2691156a50..6245828a381f 100644 --- a/litellm/litellm_core_utils/token_counter.py +++ b/litellm/litellm_core_utils/token_counter.py @@ -211,13 +211,15 @@ def get_image_dimensions( Tuple[int, int]: The width and height of the image. """ img_data = None - try: - # Try to open as URL with SSRF protection - client = _get_httpx_client() - response = safe_get(client, data) - img_data = response.read() - except Exception: - # If not URL, assume it's base64 + if data.startswith(("http://", "https://")): + try: + client = _get_httpx_client() + response = safe_get(client, data) + img_data = response.read() + except Exception: + pass + if img_data is None: + # Not a URL or fetch failed — assume base64 _header, encoded = data.split(",", 1) img_data = base64.b64decode(encoded) diff --git a/tests/test_litellm/proxy/common_utils/test_url_utils.py b/tests/test_litellm/proxy/common_utils/test_url_utils.py new file mode 100644 index 000000000000..73f465cfbc4c --- /dev/null +++ b/tests/test_litellm/proxy/common_utils/test_url_utils.py @@ -0,0 +1,64 @@ +import pytest + +from litellm.proxy.common_utils.url_utils import SSRFError, validate_url + + +class TestValidateUrl: + def test_blocks_loopback(self): + with pytest.raises(SSRFError): + validate_url("http://127.0.0.1/test") + + def test_blocks_imds(self): + with pytest.raises(SSRFError): + validate_url("http://169.254.169.254/latest/meta-data/") + + def test_blocks_rfc1918_class_a(self): + with pytest.raises(SSRFError): + validate_url("http://10.0.1.5:8080/v1/completions") + + def test_blocks_rfc1918_class_b(self): + with pytest.raises(SSRFError): + validate_url("http://172.16.0.1/") + + def test_blocks_rfc1918_class_c(self): + with pytest.raises(SSRFError): + validate_url("http://192.168.1.1/") + + def test_blocks_file_scheme(self): + with pytest.raises(SSRFError): + validate_url("file:///etc/passwd") + + def test_blocks_ftp_scheme(self): + with pytest.raises(SSRFError): + validate_url("ftp://internal.host/data") + + def test_blocks_no_hostname(self): + with pytest.raises(SSRFError): + validate_url("http:///path") + + def test_allows_public_https(self): + rewritten, host = validate_url("https://example.com/image.png") + assert host == "example.com" + assert rewritten == "https://example.com/image.png" + + def test_rewrites_public_http_to_ip(self): + rewritten, host = validate_url("http://example.com/image.png") + assert host == "example.com" + assert "example.com" not in rewritten + + def test_preserves_path_and_query(self): + rewritten, host = validate_url("http://example.com/path?key=value") + assert "/path" in rewritten + assert "key=value" in rewritten + + def test_dns_failure_raises(self): + with pytest.raises(SSRFError, match="DNS resolution failed"): + validate_url("http://this-domain-does-not-exist-xyz123.invalid/test") + + def test_blocks_localhost_hostname(self): + with pytest.raises(SSRFError): + validate_url("http://localhost/") + + def test_blocks_ipv6_loopback(self): + with pytest.raises(SSRFError): + validate_url("http://[::1]/") From 45e53605faf77427bea7623bc5f6d33a3e272218 Mon Sep 17 00:00:00 2001 From: user <70670632+stuxf@users.noreply.github.com> Date: Thu, 16 Apr 2026 04:44:10 +0000 Subject: [PATCH 05/12] test: mock SSRF validation in openapi spec URL test --- tests/mcp_tests/test_openapi_spec_path_url.py | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/tests/mcp_tests/test_openapi_spec_path_url.py b/tests/mcp_tests/test_openapi_spec_path_url.py index 03e9db949679..17a0022046e7 100644 --- a/tests/mcp_tests/test_openapi_spec_path_url.py +++ b/tests/mcp_tests/test_openapi_spec_path_url.py @@ -55,6 +55,11 @@ def fake_get_async_httpx_client(*args, **kwargs): # Ensure shared/custom client path is used monkeypatch.setattr(gen, "get_async_httpx_client", fake_get_async_httpx_client) + # Bypass SSRF validation in test (example.local doesn't resolve) + monkeypatch.setattr( + gen, "async_safe_get", lambda client, url, **kw: client.get(url) + ) + # Fail loudly if someone reintroduces direct httpx.get() def boom(*args, **kwargs): raise AssertionError("Direct httpx.get() must not be used for URL spec loading") @@ -68,7 +73,9 @@ def boom(*args, **kwargs): assert handler_holder["handler"].calls == 1 -def test_load_openapi_spec_supports_local_file_path(tmp_path, monkeypatch: pytest.MonkeyPatch) -> None: +def test_load_openapi_spec_supports_local_file_path( + tmp_path, monkeypatch: pytest.MonkeyPatch +) -> None: expected: Dict[str, Any] = { "openapi": "3.0.0", "info": {"title": "Local API", "version": "1.0.0"}, @@ -83,10 +90,11 @@ def test_load_openapi_spec_supports_local_file_path(tmp_path, monkeypatch: pytes # For local files, shared client must NOT be used. def boom_client(*args, **kwargs): - raise AssertionError("get_async_httpx_client() must not be called for local file paths") + raise AssertionError( + "get_async_httpx_client() must not be called for local file paths" + ) monkeypatch.setattr(gen, "get_async_httpx_client", boom_client) spec = gen.load_openapi_spec(str(p)) assert spec == expected - From 2253300cb963a2e36249eefc0dee8416646ae1aa Mon Sep 17 00:00:00 2001 From: user <70670632+stuxf@users.noreply.github.com> Date: Thu, 16 Apr 2026 04:48:12 +0000 Subject: [PATCH 06/12] fix: fail-closed on unparseable IPs, rewrite HTTPS when SSL verify disabled _is_blocked_ip now returns True (blocked) for unparseable addresses instead of False (allowed). HTTPS URLs are rewritten to validated IPs when ssl_verify is disabled, closing the DNS rebinding window that exists without TLS certificate binding. --- litellm/proxy/common_utils/url_utils.py | 15 +++++++---- .../proxy/common_utils/test_url_utils.py | 25 ++++++++++++++++++- 2 files changed, 34 insertions(+), 6 deletions(-) diff --git a/litellm/proxy/common_utils/url_utils.py b/litellm/proxy/common_utils/url_utils.py index 2a160d3cec73..72cbc7765893 100644 --- a/litellm/proxy/common_utils/url_utils.py +++ b/litellm/proxy/common_utils/url_utils.py @@ -15,6 +15,8 @@ from typing import Any, Optional, Tuple, Union from urllib.parse import urlparse, urlunparse +import litellm + _BLOCKED_NETWORKS = [ ip_network("0.0.0.0/8"), ip_network("10.0.0.0/8"), @@ -43,7 +45,7 @@ def _is_blocked_ip(addr: str) -> bool: try: ip = ip_address(addr) except ValueError: - return False + return True # fail-closed: unparseable addresses are blocked if ip.version == 6 and hasattr(ip, "ipv4_mapped") and ip.ipv4_mapped: ip = ip.ipv4_mapped return any(ip in net for net in _BLOCKED_NETWORKS) @@ -104,10 +106,13 @@ def validate_url(url: str) -> Tuple[str, str]: "provider configuration instead of a user-supplied URL." ) - # For HTTPS, TLS certificate validation binds the connection to the - # hostname — DNS rebinding can't redirect to a different server because - # the cert wouldn't match. Return the original URL. - if parsed.scheme == "https": + # For HTTPS with SSL verification enabled, TLS certificate validation + # binds the connection to the hostname — DNS rebinding can't redirect + # to a different server because the cert wouldn't match. + # When SSL verification is disabled, this defense doesn't apply, so + # we rewrite to the validated IP like HTTP. + ssl_verify = getattr(litellm, "ssl_verify", True) + if parsed.scheme == "https" and ssl_verify is not False: return url, hostname # For HTTP, rewrite URL to connect to the validated IP directly diff --git a/tests/test_litellm/proxy/common_utils/test_url_utils.py b/tests/test_litellm/proxy/common_utils/test_url_utils.py index 73f465cfbc4c..4dbda6a815ef 100644 --- a/tests/test_litellm/proxy/common_utils/test_url_utils.py +++ b/tests/test_litellm/proxy/common_utils/test_url_utils.py @@ -1,6 +1,18 @@ import pytest -from litellm.proxy.common_utils.url_utils import SSRFError, validate_url +import litellm +from litellm.proxy.common_utils.url_utils import SSRFError, _is_blocked_ip, validate_url + + +class TestIsBlockedIp: + def test_blocks_private(self): + assert _is_blocked_ip("10.0.0.1") is True + + def test_allows_public(self): + assert _is_blocked_ip("8.8.8.8") is False + + def test_unparseable_is_blocked(self): + assert _is_blocked_ip("not-an-ip") is True class TestValidateUrl: @@ -62,3 +74,14 @@ def test_blocks_localhost_hostname(self): def test_blocks_ipv6_loopback(self): with pytest.raises(SSRFError): validate_url("http://[::1]/") + + def test_https_rewrites_when_ssl_verify_disabled(self, monkeypatch): + monkeypatch.setattr(litellm, "ssl_verify", False) + rewritten, host = validate_url("https://example.com/image.png") + assert host == "example.com" + assert "example.com" not in rewritten # rewritten to IP + + def test_https_not_rewritten_when_ssl_verify_enabled(self, monkeypatch): + monkeypatch.setattr(litellm, "ssl_verify", True) + rewritten, host = validate_url("https://example.com/image.png") + assert rewritten == "https://example.com/image.png" From 63cb4fd296d6d8c11d4a25d17c8a410852fd34c7 Mon Sep 17 00:00:00 2001 From: user <70670632+stuxf@users.noreply.github.com> Date: Thu, 16 Apr 2026 04:53:09 +0000 Subject: [PATCH 07/12] fix: redirect loop was dead code, clean up imports Read Location header directly instead of response.next_request (which is None when follow_redirects=False). Resolve relative redirect URLs with httpx.URL.join(). Remove unused imports. --- litellm/proxy/common_utils/url_utils.py | 25 ++++++++++++++++++------- 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/litellm/proxy/common_utils/url_utils.py b/litellm/proxy/common_utils/url_utils.py index 72cbc7765893..f18378f90076 100644 --- a/litellm/proxy/common_utils/url_utils.py +++ b/litellm/proxy/common_utils/url_utils.py @@ -9,10 +9,10 @@ rebinding. Redirects are followed manually with validation at each hop. """ -import ipaddress +import asyncio import socket from ipaddress import ip_address, ip_network -from typing import Any, Optional, Tuple, Union +from typing import Any, Tuple from urllib.parse import urlparse, urlunparse import litellm @@ -136,6 +136,17 @@ def validate_url(url: str) -> Tuple[str, str]: _MAX_REDIRECTS = 10 +def _extract_redirect_url(response: Any, request_url: str) -> str: + """Extract and resolve the redirect target from a response's Location header.""" + import httpx + + location = response.headers.get("location") + if not location: + raise SSRFError("Redirect response has no Location header") + # Resolve relative URLs against the request URL + return str(httpx.URL(request_url).join(location)) + + def safe_get(client: Any, url: str, **kwargs: Any) -> Any: """ Fetch a user-supplied URL with SSRF protection on every redirect hop. @@ -145,7 +156,7 @@ def safe_get(client: Any, url: str, **kwargs: Any) -> Any: (each hop validated). No breaking change for legitimate CDN redirects. Args: - client: An httpx.Client or httpx.AsyncClient (sync version). + client: An httpx.Client (sync). url: The user-supplied URL. **kwargs: Additional kwargs passed to client.get(). @@ -162,9 +173,9 @@ def safe_get(client: Any, url: str, **kwargs: Any) -> Any: follow_redirects=False, **kwargs, ) - if not response.is_redirect or response.next_request is None: + if not response.is_redirect: return response - url = str(response.next_request.url) + url = _extract_redirect_url(response, validated_url) raise SSRFError("Too many redirects") @@ -180,7 +191,7 @@ async def async_safe_get(client: Any, url: str, **kwargs: Any) -> Any: follow_redirects=False, **kwargs, ) - if not response.is_redirect or response.next_request is None: + if not response.is_redirect: return response - url = str(response.next_request.url) + url = _extract_redirect_url(response, validated_url) raise SSRFError("Too many redirects") From 9d379af0d131c4ec6edc82ea418332fb579b9b43 Mon Sep 17 00:00:00 2001 From: user <70670632+stuxf@users.noreply.github.com> Date: Thu, 16 Apr 2026 04:55:56 +0000 Subject: [PATCH 08/12] fix: sync redirect bypass, Host header port, redirect loop dead code MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Pass follow_redirects through in HTTPHandler.get() — previously the parameter was accepted but never forwarded to the underlying httpx client, making sync redirect protection ineffective. Include port in Host header when non-default (e.g. example.com:8080). Fix redirect loop to read Location header directly instead of response.next_request (which is None when follow_redirects=False). --- litellm/llms/custom_httpx/http_handler.py | 7 ++++--- litellm/proxy/common_utils/url_utils.py | 9 +++++++-- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/litellm/llms/custom_httpx/http_handler.py b/litellm/llms/custom_httpx/http_handler.py index 859afcfe7e5f..ae1aac423d02 100644 --- a/litellm/llms/custom_httpx/http_handler.py +++ b/litellm/llms/custom_httpx/http_handler.py @@ -912,9 +912,9 @@ def _create_aiohttp_transport( if AIOHTTP_CONNECTOR_LIMIT > 0: transport_connector_kwargs["limit"] = AIOHTTP_CONNECTOR_LIMIT if AIOHTTP_CONNECTOR_LIMIT_PER_HOST > 0: - transport_connector_kwargs[ - "limit_per_host" - ] = AIOHTTP_CONNECTOR_LIMIT_PER_HOST + transport_connector_kwargs["limit_per_host"] = ( + AIOHTTP_CONNECTOR_LIMIT_PER_HOST + ) return LiteLLMAiohttpTransport( client=lambda: ClientSession( @@ -999,6 +999,7 @@ def get( url, params=params, headers=headers, + follow_redirects=_follow_redirects, ) return response diff --git a/litellm/proxy/common_utils/url_utils.py b/litellm/proxy/common_utils/url_utils.py index f18378f90076..a47d7ae2ca42 100644 --- a/litellm/proxy/common_utils/url_utils.py +++ b/litellm/proxy/common_utils/url_utils.py @@ -87,6 +87,11 @@ def validate_url(url: str) -> Tuple[str, str]: port = parsed.port default_port = 443 if parsed.scheme == "https" else 80 + # Build the Host header value — include port when non-default + host_header = ( + hostname if (port is None or port == default_port) else f"{hostname}:{port}" + ) + # Resolve hostname and validate ALL addresses try: addrinfo = socket.getaddrinfo( @@ -113,7 +118,7 @@ def validate_url(url: str) -> Tuple[str, str]: # we rewrite to the validated IP like HTTP. ssl_verify = getattr(litellm, "ssl_verify", True) if parsed.scheme == "https" and ssl_verify is not False: - return url, hostname + return url, host_header # For HTTP, rewrite URL to connect to the validated IP directly # to prevent DNS rebinding (no TLS to bind the connection). @@ -130,7 +135,7 @@ def validate_url(url: str) -> Tuple[str, str]: (parsed.scheme, new_netloc, parsed.path, parsed.params, parsed.query, "") ) - return rewritten, hostname + return rewritten, host_header _MAX_REDIRECTS = 10 From 840255f66689dff5f7726830c4a49dd694da6ba5 Mon Sep 17 00:00:00 2001 From: user <70670632+stuxf@users.noreply.github.com> Date: Thu, 16 Apr 2026 04:59:25 +0000 Subject: [PATCH 09/12] refactor: move url_utils to litellm_core_utils to avoid proxy dependency SDK core modules (image_handling, token_counter) should not import from litellm.proxy. Move url_utils.py to litellm_core_utils/ so bare SDK installs without proxy dependencies still work. --- litellm/litellm_core_utils/prompt_templates/image_handling.py | 2 +- litellm/litellm_core_utils/token_counter.py | 2 +- litellm/{proxy/common_utils => litellm_core_utils}/url_utils.py | 0 .../proxy/_experimental/mcp_server/openapi_to_mcp_generator.py | 2 +- litellm/proxy/_experimental/out/404/index.html | 1 + litellm/proxy/_experimental/out/_not-found/index.html | 1 + litellm/proxy/_experimental/out/api-reference/index.html | 1 + litellm/proxy/_experimental/out/chat/index.html | 1 + .../_experimental/out/experimental/api-playground/index.html | 1 + litellm/proxy/_experimental/out/experimental/budgets/index.html | 1 + litellm/proxy/_experimental/out/experimental/caching/index.html | 1 + .../out/experimental/claude-code-plugins/index.html | 1 + .../proxy/_experimental/out/experimental/old-usage/index.html | 1 + litellm/proxy/_experimental/out/experimental/prompts/index.html | 1 + .../_experimental/out/experimental/tag-management/index.html | 1 + litellm/proxy/_experimental/out/guardrails/index.html | 1 + litellm/proxy/_experimental/out/login/index.html | 1 + litellm/proxy/_experimental/out/logs/index.html | 1 + litellm/proxy/_experimental/out/mcp/oauth/callback/index.html | 1 + litellm/proxy/_experimental/out/model-hub/index.html | 1 + litellm/proxy/_experimental/out/model_hub/index.html | 1 + litellm/proxy/_experimental/out/model_hub_table/index.html | 1 + litellm/proxy/_experimental/out/models-and-endpoints/index.html | 1 + litellm/proxy/_experimental/out/onboarding/index.html | 1 + litellm/proxy/_experimental/out/organizations/index.html | 1 + litellm/proxy/_experimental/out/playground/index.html | 1 + litellm/proxy/_experimental/out/policies/index.html | 1 + .../proxy/_experimental/out/settings/admin-settings/index.html | 1 + .../_experimental/out/settings/logging-and-alerts/index.html | 1 + .../proxy/_experimental/out/settings/router-settings/index.html | 1 + litellm/proxy/_experimental/out/settings/ui-theme/index.html | 1 + litellm/proxy/_experimental/out/teams/index.html | 1 + litellm/proxy/_experimental/out/test-key/index.html | 1 + litellm/proxy/_experimental/out/tools/mcp-servers/index.html | 1 + litellm/proxy/_experimental/out/tools/vector-stores/index.html | 1 + litellm/proxy/_experimental/out/usage/index.html | 1 + litellm/proxy/_experimental/out/users/index.html | 1 + litellm/proxy/_experimental/out/virtual-keys/index.html | 1 + litellm/rag/ingestion/base_ingestion.py | 2 +- .../common_utils => litellm_core_utils}/test_url_utils.py | 2 +- 40 files changed, 39 insertions(+), 5 deletions(-) rename litellm/{proxy/common_utils => litellm_core_utils}/url_utils.py (100%) create mode 100644 litellm/proxy/_experimental/out/404/index.html create mode 100644 litellm/proxy/_experimental/out/_not-found/index.html create mode 100644 litellm/proxy/_experimental/out/api-reference/index.html create mode 100644 litellm/proxy/_experimental/out/chat/index.html create mode 100644 litellm/proxy/_experimental/out/experimental/api-playground/index.html create mode 100644 litellm/proxy/_experimental/out/experimental/budgets/index.html create mode 100644 litellm/proxy/_experimental/out/experimental/caching/index.html create mode 100644 litellm/proxy/_experimental/out/experimental/claude-code-plugins/index.html create mode 100644 litellm/proxy/_experimental/out/experimental/old-usage/index.html create mode 100644 litellm/proxy/_experimental/out/experimental/prompts/index.html create mode 100644 litellm/proxy/_experimental/out/experimental/tag-management/index.html create mode 100644 litellm/proxy/_experimental/out/guardrails/index.html create mode 100644 litellm/proxy/_experimental/out/login/index.html create mode 100644 litellm/proxy/_experimental/out/logs/index.html create mode 100644 litellm/proxy/_experimental/out/mcp/oauth/callback/index.html create mode 100644 litellm/proxy/_experimental/out/model-hub/index.html create mode 100644 litellm/proxy/_experimental/out/model_hub/index.html create mode 100644 litellm/proxy/_experimental/out/model_hub_table/index.html create mode 100644 litellm/proxy/_experimental/out/models-and-endpoints/index.html create mode 100644 litellm/proxy/_experimental/out/onboarding/index.html create mode 100644 litellm/proxy/_experimental/out/organizations/index.html create mode 100644 litellm/proxy/_experimental/out/playground/index.html create mode 100644 litellm/proxy/_experimental/out/policies/index.html create mode 100644 litellm/proxy/_experimental/out/settings/admin-settings/index.html create mode 100644 litellm/proxy/_experimental/out/settings/logging-and-alerts/index.html create mode 100644 litellm/proxy/_experimental/out/settings/router-settings/index.html create mode 100644 litellm/proxy/_experimental/out/settings/ui-theme/index.html create mode 100644 litellm/proxy/_experimental/out/teams/index.html create mode 100644 litellm/proxy/_experimental/out/test-key/index.html create mode 100644 litellm/proxy/_experimental/out/tools/mcp-servers/index.html create mode 100644 litellm/proxy/_experimental/out/tools/vector-stores/index.html create mode 100644 litellm/proxy/_experimental/out/usage/index.html create mode 100644 litellm/proxy/_experimental/out/users/index.html create mode 100644 litellm/proxy/_experimental/out/virtual-keys/index.html rename tests/test_litellm/{proxy/common_utils => litellm_core_utils}/test_url_utils.py (97%) diff --git a/litellm/litellm_core_utils/prompt_templates/image_handling.py b/litellm/litellm_core_utils/prompt_templates/image_handling.py index c036ec23ddb6..fd38bc9388d3 100644 --- a/litellm/litellm_core_utils/prompt_templates/image_handling.py +++ b/litellm/litellm_core_utils/prompt_templates/image_handling.py @@ -10,7 +10,7 @@ from litellm import verbose_logger from litellm.caching.caching import InMemoryCache from litellm.constants import MAX_IMAGE_URL_DOWNLOAD_SIZE_MB -from litellm.proxy.common_utils.url_utils import async_safe_get, safe_get +from litellm.litellm_core_utils.url_utils import async_safe_get, safe_get MAX_IMGS_IN_MEMORY = 10 diff --git a/litellm/litellm_core_utils/token_counter.py b/litellm/litellm_core_utils/token_counter.py index 6245828a381f..01e5dc39a34a 100644 --- a/litellm/litellm_core_utils/token_counter.py +++ b/litellm/litellm_core_utils/token_counter.py @@ -30,7 +30,7 @@ ) from litellm.litellm_core_utils.default_encoding import encoding as default_encoding from litellm.llms.custom_httpx.http_handler import _get_httpx_client -from litellm.proxy.common_utils.url_utils import safe_get +from litellm.litellm_core_utils.url_utils import safe_get from litellm.types.llms.anthropic import ( AnthropicMessagesToolResultParam, AnthropicMessagesToolUseParam, diff --git a/litellm/proxy/common_utils/url_utils.py b/litellm/litellm_core_utils/url_utils.py similarity index 100% rename from litellm/proxy/common_utils/url_utils.py rename to litellm/litellm_core_utils/url_utils.py diff --git a/litellm/proxy/_experimental/mcp_server/openapi_to_mcp_generator.py b/litellm/proxy/_experimental/mcp_server/openapi_to_mcp_generator.py index d6b2cb86b265..3b2fa097b70c 100644 --- a/litellm/proxy/_experimental/mcp_server/openapi_to_mcp_generator.py +++ b/litellm/proxy/_experimental/mcp_server/openapi_to_mcp_generator.py @@ -15,7 +15,7 @@ get_async_httpx_client, httpxSpecialProvider, ) -from litellm.proxy.common_utils.url_utils import async_safe_get +from litellm.litellm_core_utils.url_utils import async_safe_get from litellm.proxy._experimental.mcp_server.tool_registry import ( global_mcp_tool_registry, ) diff --git a/litellm/proxy/_experimental/out/404/index.html b/litellm/proxy/_experimental/out/404/index.html new file mode 100644 index 000000000000..344481d3aed2 --- /dev/null +++ b/litellm/proxy/_experimental/out/404/index.html @@ -0,0 +1 @@ +