Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
132 changes: 132 additions & 0 deletions litellm/proxy/common_utils/static_asset_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
"""
Helpers for the unauthenticated logo / favicon endpoints (``/get_image`` and
``/get_favicon``). Both read an admin-set environment variable that may be a
local filesystem path or an HTTP URL, fetch the resource, and return the
bytes verbatim to any unauthenticated caller.

Without these helpers:

* a misconfigured / hostile env var like ``UI_LOGO_PATH=/etc/passwd`` lets
any unauthenticated caller exfiltrate the file (LFI β€” GHSA-3pcp-536p-ghjc).
* a legitimate-looking ``UI_LOGO_PATH=http://internal-service/branding.png``
pointing at a private host lets any unauthenticated caller exfiltrate
whatever that host returns (SSRF β€” GHSA-pjc9-2hw6-78rr), regardless of
whether the body is actually an image.
"""

import os
from typing import List, Optional

from litellm._logging import verbose_proxy_logger
from litellm.litellm_core_utils.url_utils import SSRFError, validate_url
from litellm.llms.custom_httpx.http_handler import get_async_httpx_client
from litellm.types.llms.custom_http import httpxSpecialProvider

# Conservative allowlist of image MIME types. Anything else is refused β€”
# without this, an admin-configured URL whose upstream returns
# ``application/json`` (e.g. cloud metadata, internal API) would still be
# served back to the caller verbatim.
ALLOWED_IMAGE_CONTENT_TYPES = frozenset(
{
"image/jpeg",
"image/jpg",
"image/png",
"image/gif",
"image/svg+xml",
Comment thread
stuxf marked this conversation as resolved.
Resolved
"image/webp",
"image/x-icon",
"image/vnd.microsoft.icon",
}
)


def resolve_local_asset_path(candidate: str, allowed_roots: List[str]) -> Optional[str]:
"""
Resolve ``candidate`` and return its absolute path only if it lives
within one of ``allowed_roots``. Returns None on any miss (caller
falls back to the bundled default asset).

Resolution uses ``realpath`` to follow symlinks, so a symlink inside
``allowed_roots`` pointing at ``/etc/passwd`` is rejected the same as
a direct ``/etc/passwd`` config.
"""
if not candidate:
return None
try:
resolved = os.path.realpath(os.path.expanduser(candidate))
except (OSError, ValueError):
return None
if not os.path.isfile(resolved):
return None
for root in allowed_roots:
if not root:
continue
try:
root_resolved = os.path.realpath(root)
except (OSError, ValueError):
continue
if resolved == root_resolved:
return resolved
if resolved.startswith(root_resolved + os.sep):
return resolved
return None


async def fetch_validated_image_bytes(
url: str, *, timeout_s: float = 5.0
) -> Optional[bytes]:
"""
Fetch ``url`` with SSRF protection (always-on) and Content-Type
validation. Returns the raw bytes on success, ``None`` on any
failure (blocked target, non-200, or non-image response).

The SSRF guard is enforced unconditionally β€” these endpoints are
unauthenticated, so the admin-facing ``litellm.user_url_validation``
toggle does not apply. An admin who opted out of URL validation for
LLM provider paths should not also expose ``/get_image`` to SSRF.
"""
if not url:
return None
try:
rewritten_url, host_header = validate_url(url)
except SSRFError as exc:
verbose_proxy_logger.warning(
"Blocked unauthenticated asset fetch β€” SSRF guard rejected %r: %s",
url,
exc,
)
return None

# ``validate_url`` rewrites HTTP URLs to point at a validated IP and
# returns the original hostname for the Host header. For HTTPS with
# ssl_verify enabled, it returns the URL unchanged (TLS hostname
# validation handles DNS rebinding).
request_kwargs = {}
if rewritten_url != url:
request_kwargs["headers"] = {"host": host_header}

async_client = get_async_httpx_client(
llm_provider=httpxSpecialProvider.UI,
params={"timeout": timeout_s},
)
try:
response = await async_client.get(rewritten_url, **request_kwargs)
Comment thread
stuxf marked this conversation as resolved.
Resolved
except Exception as exc:
verbose_proxy_logger.debug("Asset fetch failed for %r: %s", url, exc)
return None

if response.status_code != 200:
return None

content_type = (
(response.headers.get("content-type") or "").split(";")[0].strip().lower()
)
if content_type not in ALLOWED_IMAGE_CONTENT_TYPES:
verbose_proxy_logger.warning(
"Asset fetch from %r returned non-image content-type %r β€” refusing to serve.",
url,
content_type,
)
return None

return response.content
142 changes: 77 additions & 65 deletions litellm/proxy/proxy_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -12223,9 +12223,20 @@ async def claim_onboarding_link(data: InvitationClaim):

@app.get("/get_logo_url", include_in_schema=False)
def get_logo_url():
"""Get the current logo URL from environment"""
"""Get the current logo URL from environment.

Only HTTP(S) URLs are returned β€” those are intended to be loaded
directly by the browser from a public/internal CDN. Local file
paths set via ``UI_LOGO_PATH`` are NOT returned: they are admin-
only filesystem details, the dashboard falls back to ``/get_image``
which serves the file (with path containment) instead. Without
this filter, the unauthenticated endpoint would disclose internal
hostnames or filesystem paths to any caller.
"""
logo_path = os.getenv("UI_LOGO_PATH", "")
return {"logo_url": logo_path}
if logo_path.startswith(("http://", "https://")):
return {"logo_url": logo_path}
return {"logo_url": ""}


@app.get("/get_image", include_in_schema=False)
Expand Down Expand Up @@ -12270,13 +12281,25 @@ async def get_image():
logo_path = os.getenv("UI_LOGO_PATH", default_logo)
verbose_proxy_logger.debug("Reading logo from path: %s", logo_path)

# If UI_LOGO_PATH points to a local file, serve it directly (skip cache)
# ``/get_image`` is unauthenticated. Validate any admin-configured local
# path against an allowlist of asset roots β€” without this guard, an
# env var like ``UI_LOGO_PATH=/etc/passwd`` lets any caller exfiltrate
# the file via this endpoint.
from litellm.proxy.common_utils.static_asset_utils import (
fetch_validated_image_bytes,
resolve_local_asset_path,
)

allowed_local_roots = [assets_dir, current_dir]

if logo_path != default_logo and not logo_path.startswith(("http://", "https://")):
if os.path.exists(logo_path):
return FileResponse(logo_path, media_type="image/jpeg")
# Custom path doesn't exist β€” fall back to default
safe_logo = resolve_local_asset_path(logo_path, allowed_local_roots)
if safe_logo is not None:
return FileResponse(safe_logo, media_type="image/jpeg")
verbose_proxy_logger.warning(
f"UI_LOGO_PATH '{logo_path}' does not exist, falling back to default logo"
"UI_LOGO_PATH %r is outside the allowed asset roots or does not "
"exist, falling back to default logo",
logo_path,
)
logo_path = default_logo

Expand All @@ -12286,32 +12309,21 @@ async def get_image():

# Check if the logo path is an HTTP/HTTPS URL
if logo_path.startswith(("http://", "https://")):
try:
# Download the image and cache it
from litellm.llms.custom_httpx.http_handler import get_async_httpx_client
from litellm.types.llms.custom_http import httpxSpecialProvider

async_client = get_async_httpx_client(
llm_provider=httpxSpecialProvider.UI,
params={"timeout": 5.0},
)
response = await async_client.get(logo_path)
if response.status_code == 200:
# Save the image to a local file
# SSRF + content-type validation β€” the helper rejects
# private/internal/cloud-metadata targets and non-image responses.
image_bytes = await fetch_validated_image_bytes(logo_path)
if image_bytes is not None:
try:
with open(cache_path, "wb") as f:
f.write(response.content)

# Return the cached image as a FileResponse
f.write(image_bytes)
return FileResponse(cache_path, media_type="image/jpeg")
else:
# Handle the case when the image cannot be downloaded
return FileResponse(default_logo, media_type="image/jpeg")
except Exception as e:
# Handle any exceptions during the download (e.g., timeout, connection error)
verbose_proxy_logger.debug(f"Error downloading logo from {logo_path}: {e}")
return FileResponse(default_logo, media_type="image/jpeg")
except OSError as e:
verbose_proxy_logger.debug(
"Could not write logo cache to %s: %s", cache_path, e
)
return FileResponse(default_logo, media_type="image/jpeg")
Comment thread
stuxf marked this conversation as resolved.
Resolved
else:
# Return the local image file if the logo path is not an HTTP/HTTPS URL
# Default logo (resolved from the bundled asset, not user-controlled).
return FileResponse(logo_path, media_type="image/jpeg")


Expand All @@ -12320,8 +12332,20 @@ async def get_favicon():
"""Get custom favicon for the admin UI."""
from fastapi.responses import Response

from litellm.proxy.common_utils.static_asset_utils import (
fetch_validated_image_bytes,
resolve_local_asset_path,
)

current_dir = os.path.dirname(os.path.abspath(__file__))
default_favicon = os.path.join(current_dir, "_experimental", "out", "favicon.ico")
favicon_default_dir = os.path.dirname(default_favicon)

# Admin-managed asset directory (parallels ``/get_image``). Custom
# favicons placed here remain readable post-fix.
is_non_root = os.getenv("LITELLM_NON_ROOT", "").lower() == "true"
default_assets_dir = "/var/lib/litellm/assets" if is_non_root else current_dir
assets_dir = os.getenv("LITELLM_ASSETS_PATH", default_assets_dir)

favicon_url = os.getenv("LITELLM_FAVICON_URL", "")

Expand All @@ -12331,42 +12355,30 @@ async def get_favicon():
raise HTTPException(status_code=404, detail="Default favicon not found")

if favicon_url.startswith(("http://", "https://")):
try:
from litellm.llms.custom_httpx.http_handler import get_async_httpx_client
from litellm.types.llms.custom_http import httpxSpecialProvider

async_client = get_async_httpx_client(
llm_provider=httpxSpecialProvider.UI,
params={"timeout": 5.0},
)
response = await async_client.get(favicon_url)
if response.status_code == 200:
content_type = response.headers.get("content-type", "image/x-icon")
return Response(
content=response.content,
media_type=content_type,
)
else:
verbose_proxy_logger.warning(
"Failed to fetch favicon from %s: status %s",
favicon_url,
response.status_code,
)
if os.path.exists(default_favicon):
return FileResponse(default_favicon, media_type="image/x-icon")
raise HTTPException(status_code=404, detail="Favicon not found")
except HTTPException:
raise
except Exception as e:
verbose_proxy_logger.debug(
"Error downloading favicon from %s: %s", favicon_url, e
)
if os.path.exists(default_favicon):
return FileResponse(default_favicon, media_type="image/x-icon")
raise HTTPException(status_code=404, detail="Favicon not found")
# SSRF + content-type validation β€” the helper rejects
# private/internal/cloud-metadata targets and non-image responses.
image_bytes = await fetch_validated_image_bytes(favicon_url)
if image_bytes is not None:
return Response(content=image_bytes, media_type="image/x-icon")
verbose_proxy_logger.warning(
"Failed to fetch favicon from %s β€” falling back to default", favicon_url
)
if os.path.exists(default_favicon):
return FileResponse(default_favicon, media_type="image/x-icon")
raise HTTPException(status_code=404, detail="Favicon not found")
else:
if os.path.exists(favicon_url):
return FileResponse(favicon_url, media_type="image/x-icon")
# ``/get_favicon`` is unauthenticated. Validate any admin-configured
# local path against an allowlist of asset roots β€” see ``/get_image``
# for the LFI threat-model rationale.
allowed_local_roots = [assets_dir, favicon_default_dir, current_dir]
safe_favicon = resolve_local_asset_path(favicon_url, allowed_local_roots)
if safe_favicon is not None:
return FileResponse(safe_favicon, media_type="image/x-icon")
verbose_proxy_logger.warning(
"LITELLM_FAVICON_URL %r is outside the allowed asset roots or "
"does not exist, falling back to default favicon",
favicon_url,
)
if os.path.exists(default_favicon):
return FileResponse(default_favicon, media_type="image/x-icon")
raise HTTPException(status_code=404, detail="Favicon not found")
Expand Down
Loading
Loading