node:vm, vm2 and Python's exec are not sandboxes: in-process isolation and why it fails
本文为原文前 6,000 字符的节选翻译,完整内容请查看原文。
node:vm, vm2 and Python’s exec are not sandboxes: in-process isolation and why it fails
The first version of many agent tools runs model-written code the quick way: inside the same process, with a language feature that sounds like isolation. In Node that is the vm module. In Python it is exec with a stripped-down builtins. It works in the demo, it is easy, and it does not isolate anything. This post shows why, using the languages’ own documentation and two escapes short enough to fit in a tweet, then covers what to use instead.
许多代理工具的第一个版本都采用了一种快捷方式来运行模型生成的代码:在同一个进程内,利用一种听起来像是隔离的语言特性。在 Node.js 中,这就是 vm 模块;在 Python 中,则是带有精简版 __builtins__ 的 exec。这种方法在演示时有效,实现起来也很简单,但它实际上并没有实现任何隔离。本文将通过这些语言自身的文档以及两个短到足以塞进推文的逃逸示例来解释原因,并探讨应该使用什么来替代。
What the docs say
Both runtimes are explicit about this, which makes it unusual among security pitfalls: you do not need to find a researcher’s blog post, the warning is in the manual. The Node.js vm documentation opens with: “The node:vm module is not a security mechanism. Do not use it to run untrusted code.” The Python documentation for eval and exec warns that calling them “with untrusted user-supplied input will lead to security vulnerabilities”, and on the builtins trick says that overriding it “can be used to restrict or change the available names, but this is not a security mechanism: the executed code can still access all builtins.” Code written by a model from a prompt that may contain text from the internet is untrusted input. That settles it, but it helps to see why.
文档怎么说
这两个运行时环境对此都有明确说明,这在安全陷阱中并不常见:你不需要去寻找研究人员的博客文章,警告直接写在手册里。Node.js 的 vm 文档开头写道:“node:vm 模块不是一种安全机制。不要使用它来运行不受信任的代码。” Python 关于 eval 和 exec 的文档警告称,使用“不受信任的用户输入”调用它们“会导致安全漏洞”,并且关于 __builtins__ 的技巧,文档指出覆盖它“可以用来限制或更改可用的名称,但这并不是一种安全机制:执行的代码仍然可以访问所有的内置函数。”由模型根据可能包含互联网文本的提示词所编写的代码,属于不受信任的输入。结论已定,但了解其背后的原因很有帮助。
The Node escape
vm.runInNewContext runs code with a different global object. It does not run it in a different heap, process or permission set. Objects you pass into the context, including the context object itself, come from the outer world, and every object in JavaScript can reach its constructor:
const vm = require('node:vm');
const result = vm.runInNewContext(
'this.constructor.constructor("return process")().version',
{},
);
this inside the context is the object you passed in, created outside. Its constructor is the outer Object, and that function’s constructor is the outer Function. Calling it compiles a function in the host’s realm, which returns the host’s process. We ran this on Node 24, and result equals the host’s process.version. Replace .version with .env or .mainModule.require(‘child_process’) and the “sandboxed” code reads your secrets or runs commands. Freezing the context object or passing Object.create(null) closes this particular path, and then someone finds another through an error object, a callback or a promise. That is the history of the next section.
Node.js 的逃逸
vm.runInNewContext 使用不同的全局对象运行代码。它并没有在不同的堆、进程或权限集中运行代码。你传入上下文的对象(包括上下文对象本身)都来自外部世界,而 JavaScript 中的每个对象都可以访问其构造函数:
const vm = require('node:vm');
const result = vm.runInNewContext(
'this.constructor.constructor("return process")().version',
{},
);
上下文中的 this 就是你传入的、在外部创建的对象。它的构造函数是外部的 Object,而该函数的构造函数是外部的 Function。调用它会在宿主环境中编译一个函数,该函数会返回宿主的 process。我们在 Node 24 上运行了这段代码,结果等于宿主的 process.version。将 .version 替换为 .env 或 .mainModule.require('child_process'),所谓的“沙箱”代码就能读取你的机密信息或执行命令。冻结上下文对象或传递 Object.create(null) 可以堵住这一特定路径,但随后人们又会通过错误对象、回调或 Promise 找到另一条路径。这就是下一节的历史背景。
vm2: a library that tried harder
vm2 wrapped vm with proxies that intercepted every object crossing the boundary, and for years it was the popular answer to “how do I run untrusted JavaScript in Node?”. It also accumulated a series of sandbox escapes. One example is CVE-2023-37466: in vm2 up to 3.9.19, Promise handler sanitization could be bypassed with the @@species accessor property, allowing attackers to escape the sandbox and run arbitrary code. The project’s README now says it is discontinued, that it “contains critical security issues and should not be used for production”, and points users to isolated-vm. The lesson is not that vm2’s authors were careless. It is that intercepting every path between two worlds that share a heap is a game the defender has to win every time.
vm2:一个更努力的库
vm2 使用代理包装了 vm,拦截了每一个跨越边界的对象。多年来,它是“如何在 Node 中运行不受信任的 JavaScript”这一问题的流行答案。它也积累了一系列沙箱逃逸漏洞。一个例子是 CVE-2023-37466:在 3.9.19 及之前的 vm2 版本中,Promise 处理程序的清理可以通过 @@species 访问器属性绕过,从而允许攻击者逃离沙箱并执行任意代码。该项目的 README 现在声明它已停止维护,称其“包含严重的安全问题,不应用于生产环境”,并建议用户使用 isolated-vm。这给我们的教训并不是 vm2 的作者粗心大意,而是因为在共享堆的两个世界之间拦截每一条路径,是一场防御者必须次次获胜的游戏。
The Python escape
Python’s version of the trick is to pass exec or eval a globals dictionary with builtins set to an empty dict, so open, import and friends are gone. But the code can still write literals, and every literal is an object with a class, and every class leads back to object, which knows all its subclasses:
g = {"__builtins__": {}}
code = (
'[c for c in ().__class__.__base__.__subclasses__()'
' if c.__name__ == "_wrap_close"][0].__init__.__globals__["system"]'
)
system = eval(code, g)
() is a tuple; its base class is object; object.subclasses() lists every class loaded in the interpreter. One of them, os._wrap_close, is defined in the os module, so its init function’s globals are the os module’s globals, which include system. On Python 3.13, system is the real os.system. No builtins needed. Blocklisting subclasses, double underscores or particular names in the source string is the usual next step, and it fails for the same reason vm2 did: there are too many paths, and encodings, getattr with computed strings and format tricks make source filtering a losing game.
Python 的逃逸
Python 版的技巧是向 exec 或 eval 传递一个 __builtins__ 被设置为空字典的全局变量字典,这样 open、__import__ 等函数就消失了。但代码仍然可以编写字面量,每个字面量都是一个带有类的对象,而每个类最终都会追溯到 object,它知道自己所有的子类:
g = {"__builtins__": {}}
code = (
'[c for c in ().__class__.__base__.__subclasses__()'
' if c.__name__ == "_wrap_close"][0].__init__.__globals__["system"]'
)
system = eval(code, g)
() 是一个元组;它的基类是 object;object.__subclasses__() 列出了解释器中加载的每一个类。其中之一 os._wrap_close 定义在 os 模块中,因此其 __init__ 函数的全局变量就是 os 模块的全局变量,其中包含了 system。在 Python 3.13 上,system 就是真正的 os.system。根本不需要内置函数。将 __subclasses__、双下划线或源代码字符串中的特定名称列入黑名单是通常的后续步骤,但它失败的原因与 vm2 相同:路径太多了,而且编码、使用计算字符串的 getattr 以及格式化技巧使得源代码过滤成为一场注定失败的游戏。
Why in-process isolation keeps failing
The common thread: the untrusted code and your code share one process. They share a memory space, a set of loaded modules, file descriptors, credentials and the operating system’s view of who is running. Language-level tricks try to hide those things. Any object that leaks across, any bug in the interception layer, or any bug in the runtime itself puts the untrusted code on your side. Even a stronger in-process tool, such as a separate V8 isolate, still runs inside your process: it narrows what the code can reach through the language, but a bug in the engine is still a bug in the process holding your credentials.
为什么进程内隔离总是失败
共同点在于:不受信任的代码和你的代码共享同一个进程。它们共享内存空间、一组已加载的模块、文件描述符、凭据以及操作系统对运行者的识别。语言层面的技巧试图隐藏这些东西。任何泄露的对象、拦截层中的任何错误,或运行时本身的任何错误,都会让不受信任的代码进入你的阵营。即使是更强大的进程内工具(例如独立的 V8 隔离区),仍然运行在你的进程内:它通过语言限制了代码可以触及的范围,但引擎中的一个错误仍然是持有你凭据的进程中的一个错误。
What to use instead
Put a boundary the operating system or hardware enforces between the code and anything you care about:
- A separate process with reduced privileges, at minimum: a different user, no secrets in its environment, a seccomp filter, resource limits and a timeout. Better than in-process, though it shares your kernel.
- A container with a hardened profile, for code you mostly trust. It also shares your kernel, and our post on container escape CVEs shows what that has meant in practice.
- A microVM or a user-space kernel such as gVisor, for code nobody has read. See our comparison of containers, gVisor and Firecracker. Whatever you pick, keep the habits that matter at every layer: give the code no secrets it does not need, no network it does not need, and a time limit.
应该使用什么来替代
在代码和你关心的任何事物之间设置一道由操作系统或硬件强制执行的边界:
- 一个权限降低的独立进程,至少包括:不同的用户、环境中没有机密信息、seccomp 过滤器、资源限制和超时设置。这比进程内隔离要好,尽管它仍然共享你的内核。
- 一个带有强化配置文件的容器,适用于你基本信任的代码。它也共享你的内核,我们关于容器逃逸 CVE 的文章展示了这意味着什么。
- 一个微型虚拟机(microVM)或用户空间内核(如 gVisor),适用于无人审阅的代码。请参阅我们对容器、gVisor 和 Firecracker 的比较。 无论你选择什么,都要保持在每一层都至关重要的习惯:不要给代码它不需要的机密信息,不要给它不需要的网络访问权限,并设置时间限制。
Where Sandscale fits
Sandscale gives each run its own Firecracker microVM with its own kernel, which is the third option above as an API. You send the model’s code with writeFile, run it with run, and read the exit code and output back, instead of calling eval in your server. Our quickstart shows the whole loop.
Sandscale 的定位
Sandscale 为每次运行提供其专属的、带有独立内核的 Firecracker 微型虚拟机,这正是上述第三种选项的 API 化实现。你通过 writeFile 发送模型的代码,使用 run 执行它,并读取退出代码和输出,而不是在你的服务器中调用 eval。我们的快速入门指南展示了整个流程。