Repository navigation
Fix/aiohttp ssrf cwe918 #28252
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Fix/aiohttp ssrf cwe918 #28252
Changes from 5 commits
537db99
80cea73
eb9914e
a9cdbca
fc7718c
6c22ca0
90ec5dc
1bc6fc8
3aff456
7dad714
fedf0c7
2bde496
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,8 +1,13 @@ | ||
| import asyncio | ||
| 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 | ||
| from aiohttp import ClientSession, FormData | ||
| from aiohttp.abc import AbstractResolver | ||
|
|
||
| import litellm | ||
| import litellm.litellm_core_utils | ||
|
|
@@ -31,6 +36,107 @@ | |
|
|
||
| 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("::/128"), # IPv6 unspecified / wildcard | ||
| ipaddress.ip_network("::1/128"), | ||
| ipaddress.ip_network("fc00::/7"), | ||
| ipaddress.ip_network("fe80::/10"), # IPv6 link-local | ||
| ] | ||
|
|
||
|
|
||
| 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) | ||
|
veria-ai[bot] marked this conversation as resolved.
Resolved
|
||
|
|
||
|
|
||
| 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. | ||
| Used as a fast-fail guard on the sync path (httpx) and as defence-in-depth on async. | ||
|
|
||
| Set ``litellm.allow_requests_to_internal_ips = True`` to disable this check | ||
| for self-hosted / on-prem deployments where api_base is an internal address. | ||
| """ | ||
| if litellm.allow_requests_to_internal_ips: | ||
| return | ||
| parsed = urlparse(url) | ||
| hostname = parsed.hostname | ||
| if not hostname: | ||
| return | ||
| try: | ||
| answers = socket.getaddrinfo(hostname, None) | ||
| 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)" | ||
| ) | ||
|
|
||
|
|
||
| class _SSRFGuardResolver(AbstractResolver): | ||
| """Custom aiohttp resolver that validates IPs at TCP-connection time. | ||
|
|
||
| By hooking into aiohttp's resolver — used for every connection including | ||
| redirect targets — this eliminates the DNS-rebinding TOCTOU window that | ||
| a separate preflight check cannot close. All DNS answers are validated, | ||
| not just the first, to defend against A-record rotation. | ||
| """ | ||
|
|
||
| async def resolve( | ||
| self, host: str, port: int = 0, family: int = socket.AF_INET | ||
| ) -> list: | ||
| loop = asyncio.get_running_loop() | ||
| try: | ||
| infos = await loop.getaddrinfo( | ||
| host, port, family=family, type=socket.SOCK_STREAM | ||
| ) | ||
| except socket.gaierror: | ||
| raise # Propagate so aiohttp wraps it in a ClientConnectorError | ||
| if not litellm.allow_requests_to_internal_ips: | ||
| for info in infos: | ||
| raw_ip = info[4][0] | ||
| try: | ||
| addr = ipaddress.ip_address(raw_ip) | ||
| except ValueError: | ||
| continue | ||
| if _is_blocked_address(addr): | ||
| raise ValueError( | ||
| f"Host '{host}' resolves to a private/reserved IP address " | ||
| f"({raw_ip}) which is not allowed (SSRF protection)" | ||
| ) | ||
| return [ | ||
| { | ||
| "hostname": host, | ||
| "host": info[4][0], | ||
| "port": info[4][1] if len(info[4]) > 1 else port, | ||
| "family": info[0], | ||
| "proto": info[2], | ||
| "flags": 0, | ||
| } | ||
| for info in infos | ||
| ] | ||
|
|
||
| async def close(self) -> None: | ||
| pass | ||
|
|
||
|
|
||
| class BaseLLMAIOHTTPHandler: | ||
| def __init__( | ||
|
|
@@ -95,8 +201,12 @@ def _create_client_session_with_transport(self) -> ClientSession: | |
| session = aiohttp.ClientSession(connector=connector) | ||
| return session | ||
| else: | ||
| # Default session creation | ||
| session = aiohttp.ClientSession() | ||
| # Default session creation — attach SSRF guard resolver so every | ||
| # TCP connection (including redirect targets) is validated at the | ||
| # network layer, eliminating the DNS-rebinding TOCTOU window. | ||
| session = aiohttp.ClientSession( | ||
| connector=aiohttp.TCPConnector(resolver=_SSRFGuardResolver()) | ||
| ) | ||
| return session | ||
|
greptile-apps[bot] marked this conversation as resolved.
Resolved
|
||
|
|
||
| def _get_async_client_session( | ||
|
|
@@ -147,26 +257,17 @@ def __del__(self): | |
| and self._owns_session | ||
| ): | ||
| try: | ||
| import asyncio | ||
|
|
||
| try: | ||
| loop = asyncio.get_event_loop() | ||
| if loop.is_running(): | ||
| # Event loop is running - schedule cleanup task | ||
| asyncio.create_task(self.close()) | ||
| else: | ||
| # Event loop exists but not running - run cleanup | ||
| loop.run_until_complete(self.close()) | ||
| loop = asyncio.get_running_loop() | ||
| loop.create_task(self.close()) | ||
| except RuntimeError: | ||
| # No event loop available - create one for cleanup | ||
| # No running loop — run cleanup in a temporary one. | ||
| loop = asyncio.new_event_loop() | ||
| asyncio.set_event_loop(loop) | ||
| try: | ||
| loop.run_until_complete(self.close()) | ||
| finally: | ||
| loop.close() | ||
| except Exception: | ||
| # Silently ignore errors during __del__ to avoid issues | ||
| pass | ||
|
|
||
| async def _make_common_async_call( | ||
|
|
@@ -191,6 +292,8 @@ async def _make_common_async_call( | |
| dynamic_client_session=async_client_session | ||
| ) | ||
|
|
||
| _assert_not_private_url(api_base) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. High: Redirect target is not validated This validates only the original
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Addressed in commit Fix: Added
Tests in |
||
|
|
||
| for i in range(max(max_retry_on_unprocessable_entity_error, 1)): | ||
| try: | ||
| response = await async_client_session.post( | ||
|
|
@@ -235,6 +338,8 @@ def _make_common_sync_call( | |
| provider_config.max_retry_on_unprocessable_entity_error | ||
| ) | ||
|
|
||
| _assert_not_private_url(api_base) | ||
|
veria-ai[bot] marked this conversation as resolved.
Resolved
Sameerlite marked this conversation as resolved.
Resolved
|
||
|
|
||
| response: Optional[httpx.Response] = None | ||
|
|
||
| for i in range(max(max_retry_on_unprocessable_entity_error, 1)): | ||
|
|
||
Uh oh!
There was an error while loading. Please reload this page.