Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 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
55 changes: 55 additions & 0 deletions litellm/llms/custom_httpx/aiohttp_handler.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import ipaddress
import socket
from typing import TYPE_CHECKING, Any, Callable, Optional, Tuple, Union, cast
from urllib.parse import urlparse

import aiohttp
import httpx # type: ignore
Expand Down Expand Up @@ -31,6 +34,53 @@

DEFAULT_TIMEOUT = 600

_BLOCKED_NETWORKS = [
ipaddress.ip_network("0.0.0.0/8"),
ipaddress.ip_network("10.0.0.0/8"),
ipaddress.ip_network("100.64.0.0/10"), # CGNAT
ipaddress.ip_network("127.0.0.0/8"),
ipaddress.ip_network("169.254.0.0/16"), # Link-local / AWS IMDS
ipaddress.ip_network("172.16.0.0/12"),
ipaddress.ip_network("192.168.0.0/16"),
ipaddress.ip_network("::1/128"),
ipaddress.ip_network("fc00::/7"),
ipaddress.ip_network("fe80::/10"), # IPv6 link-local
]
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved


def _is_blocked_address(addr: ipaddress.IPv4Address | ipaddress.IPv6Address) -> bool:
"""Return True if addr falls in any blocked network."""
# Unwrap IPv4-mapped IPv6 (::ffff:10.0.0.1 → 10.0.0.1)
if isinstance(addr, ipaddress.IPv6Address) and addr.ipv4_mapped is not None:
addr = addr.ipv4_mapped
return any(addr in net for net in _BLOCKED_NETWORKS)


def _assert_not_private_url(url: str) -> None:
"""Raise ValueError if url resolves to any private/reserved IP (SSRF protection).

Validates all DNS answers, not just the first, to prevent A-record rotation attacks.
"""
parsed = urlparse(url)
hostname = parsed.hostname
if not hostname:
return
try:
answers = socket.getaddrinfo(hostname, None)

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.

High: DNS rebinding can bypass the private-IP check

This preflight resolves the hostname once, but the actual aiohttp/httpx request resolves it again later. A caller who controls api_base can use a domain that returns a public address for this check and then a private or metadata address for the client connection; enforce the block in the client resolver/transport at connect time, or pin the request to the vetted resolved address.

except socket.gaierror:
return # DNS failure — request will fail naturally
for answer in answers:
raw_ip = answer[4][0]
try:
addr = ipaddress.ip_address(raw_ip)
except ValueError:
continue
if _is_blocked_address(addr):
raise ValueError(
f"api_base '{url}' resolves to a private/reserved IP address "
f"({raw_ip}) which is not allowed (SSRF protection)"
)
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved


class BaseLLMAIOHTTPHandler:
def __init__(
Expand Down Expand Up @@ -191,13 +241,16 @@ async def _make_common_async_call(
dynamic_client_session=async_client_session
)

_assert_not_private_url(api_base)
Comment thread
veria-ai[bot] marked this conversation as resolved.
Resolved
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved

for i in range(max(max_retry_on_unprocessable_entity_error, 1)):
try:
response = await async_client_session.post(
Comment thread
veria-ai[bot] marked this conversation as resolved.
Resolved

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.

High: Redirects can bypass the SSRF guard

ClientSession.post() follows redirects by default, but _assert_not_private_url(api_base) only checks the original URL. An attacker who controls api_base can point it at a public host that returns a redirect to http://169.254.169.254/... or another private IP; validate each redirect target before following it, or disable redirects here and in the sync HTTPHandler path that uses follow_redirects=True.

url=api_base,
headers=headers,
json=data,
data=form_data,
allow_redirects=False,
)
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
if not response.ok:
response.raise_for_status()
Expand Down Expand Up @@ -235,6 +288,8 @@ def _make_common_sync_call(
provider_config.max_retry_on_unprocessable_entity_error
)

_assert_not_private_url(api_base)

response: Optional[httpx.Response] = None

for i in range(max(max_retry_on_unprocessable_entity_error, 1)):
Expand Down
85 changes: 85 additions & 0 deletions tests/test_litellm/llms/test_aiohttp_ssrf_protection.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import ipaddress
import pytest
from unittest.mock import patch

from litellm.llms.custom_httpx.aiohttp_handler import (
_assert_not_private_url,
_is_blocked_address,
)


class TestBlockedAddress:
def test_ipv4_mapped_ipv6_private_blocked(self):
# ::ffff:10.0.0.1 is IPv4-mapped IPv6 for 10.0.0.1 — must be blocked
addr = ipaddress.ip_address("::ffff:10.0.0.1")
assert _is_blocked_address(addr)

def test_ipv4_mapped_ipv6_public_allowed(self):
addr = ipaddress.ip_address("::ffff:104.18.7.8")
assert not _is_blocked_address(addr)

def test_ipv6_link_local_blocked(self):
addr = ipaddress.ip_address("fe80::1")
assert _is_blocked_address(addr)

def test_ipv6_ula_blocked(self):
addr = ipaddress.ip_address("fc00::1")
assert _is_blocked_address(addr)

def test_0_0_0_0_blocked(self):
addr = ipaddress.ip_address("0.0.0.0")
assert _is_blocked_address(addr)


class TestAiohttpSSRFProtection:
def test_aws_metadata_endpoint_blocked(self):
with pytest.raises(ValueError, match="private/reserved"):
_assert_not_private_url("http://169.254.169.254/latest/meta-data/")

def test_localhost_blocked(self):
with pytest.raises(ValueError, match="private/reserved"):
_assert_not_private_url("http://127.0.0.1/admin")

def test_private_10_network_blocked(self):
with pytest.raises(ValueError, match="private/reserved"):
_assert_not_private_url("http://10.0.0.1/internal")

def test_private_172_16_network_blocked(self):
with pytest.raises(ValueError, match="private/reserved"):
_assert_not_private_url("http://172.16.0.1/internal")

def test_private_192_168_network_blocked(self):
with pytest.raises(ValueError, match="private/reserved"):
_assert_not_private_url("http://192.168.1.1/internal")

def test_cgnat_blocked(self):
with pytest.raises(ValueError, match="private/reserved"):
_assert_not_private_url("http://100.64.0.1/internal")

def test_all_dns_answers_checked(self):
# Domain returns public IP first, private IP second — must still block
with patch(
"socket.getaddrinfo",
return_value=[
(None, None, None, None, ("104.18.7.8", None)),
(None, None, None, None, ("10.0.0.1", None)),
],
):
with pytest.raises(ValueError, match="private/reserved"):
_assert_not_private_url("https://evil-rebinding.example.com/")

def test_public_ip_allowed(self):
with patch(
"socket.getaddrinfo",
return_value=[(None, None, None, None, ("104.18.7.8", None))],
):
_assert_not_private_url("https://api.openai.com/v1/chat/completions")

def test_empty_hostname_allowed(self):
_assert_not_private_url("not-a-url")

def test_dns_failure_does_not_block(self):
import socket as _socket

with patch("socket.getaddrinfo", side_effect=_socket.gaierror("DNS fail")):
_assert_not_private_url("https://nonexistent.invalid/path")
Loading