Skip to content
Closed
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions litellm/litellm_core_utils/prompt_templates/image_handling.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 async_safe_get, safe_get

MAX_IMGS_IN_MEMORY = 10

Expand Down Expand Up @@ -84,7 +85,7 @@ async def async_convert_url_to_base64(url: str) -> str:
client = litellm.module_level_aclient
for _ in range(3):
try:
response = await client.get(url, follow_redirects=True)
response = await async_safe_get(client, url)
return _process_image_response(response, url)
except litellm.ImageFetchError:
raise
Expand All @@ -109,7 +110,7 @@ def convert_url_to_base64(url: str) -> str:
client = litellm.module_level_client
for _ in range(3):
try:
response = client.get(url, follow_redirects=True)
response = safe_get(client, url)
return _process_image_response(response, url)
except litellm.ImageFetchError:
raise
Expand Down
17 changes: 10 additions & 7 deletions litellm/litellm_core_utils/token_counter.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 safe_get

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 SDK core importing from litellm.proxy

token_counter.py (and image_handling.py line 13) are part of the SDK core and now import from litellm.proxy.common_utils.url_utils. Users who install the bare SDK without proxy extras could hit ImportError if litellm/proxy/__init__.py or its transitive imports require unavailable deps.

Since url_utils.py only uses stdlib + import litellm, consider moving it to litellm/litellm_core_utils/url_utils.py to avoid the proxy dependency chain from SDK core code.

from litellm.types.llms.anthropic import (
AnthropicMessagesToolResultParam,
AnthropicMessagesToolUseParam,
Expand Down Expand Up @@ -210,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
client = _get_httpx_client()
response = client.get(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)

Expand Down
7 changes: 4 additions & 3 deletions litellm/llms/custom_httpx/http_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -999,6 +999,7 @@ def get(
url,
params=params,
headers=headers,
follow_redirects=_follow_redirects,
)

return response
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
get_async_httpx_client,
httpxSpecialProvider,
)
from litellm.proxy.common_utils.url_utils import async_safe_get
from litellm.proxy._experimental.mcp_server.tool_registry import (
global_mcp_tool_registry,
)
Expand Down Expand Up @@ -75,9 +76,7 @@ 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://"):
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 async_safe_get(client, filepath)
r.raise_for_status()
return r.json()

Expand Down
202 changes: 202 additions & 0 deletions litellm/proxy/common_utils/url_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,202 @@
"""
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.

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 asyncio
import socket
from ipaddress import ip_address, ip_network
from typing import Any, Tuple
from urllib.parse import urlparse, urlunparse

import litellm

_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 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)


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

# 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(
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."
)

# 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, host_header

# 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

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, host_header


_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.

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 (sync).
url: The user-supplied URL.
**kwargs: Additional kwargs passed to client.get().

Returns:
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={**caller_headers, "Host": original_host},
follow_redirects=False,
**kwargs,
)
if not response.is_redirect:
return response
url = _extract_redirect_url(response, validated_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)
caller_headers = kwargs.pop("headers", {})
for _ in range(_MAX_REDIRECTS):
validated_url, original_host = validate_url(url)
response = await client.get(
validated_url,
headers={**caller_headers, "Host": original_host},
follow_redirects=False,
**kwargs,
)
if not response.is_redirect:
return response
url = _extract_redirect_url(response, validated_url)
raise SSRFError("Too many redirects")
3 changes: 2 additions & 1 deletion litellm/rag/ingestion/base_ingestion.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
get_async_httpx_client,
httpxSpecialProvider,
)
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
Expand Down Expand Up @@ -112,7 +113,7 @@ async def upload(

if file_url:
http_client = get_async_httpx_client(llm_provider=httpxSpecialProvider.RAG)
response = await http_client.get(file_url)
response = await async_safe_get(http_client, file_url)
response.raise_for_status()
file_content = response.content
filename = file_url.split("/")[-1] or "document"
Expand Down
14 changes: 11 additions & 3 deletions tests/mcp_tests/test_openapi_spec_path_url.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand All @@ -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"},
Expand All @@ -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

Loading
Loading