如何在node.js沙箱中安全地运行用户提交的脚本? [英] How to run user-submitted scripts securely in a node.js sandbox?

查看:170
本文介绍了如何在node.js沙箱中安全地运行用户提交的脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

安全地在node.js中运行(可能是恶意的)用户提交的脚本有哪些选项?即在阻止代码访问敏感数据和API的环境中?

What are the options for running (possibly malicious) user-submitted scripts in node.js, securely? I.e. in an environment that prevents code from accessing sensitive data and APIs?

vm.runInNewContext(userScript,{})是一个诱人的起点...但似乎有已知问题

vm.runInNewContext(userScript, {}) is a tempting starting point... but it seems like there are known issues there.

沙盒模块看起来很有趣,但使用 runInNewContext()以及我对它有点怀疑。

The sandbox module looks interesting, but uses runInNewContext() as well so I'm a bit leery of it.

推荐答案

您应该始终在单独的进程中运行不受信任的代码,这正是沙盒模块所做的。一个简单的原因是 vm.runInNewContext('while(true){}',{})将冻结节点。

You should always run untrusted code in a separate process, which is exactly what the sandbox module does. A simple reason is that vm.runInNewContext('while(true){}', {}) will freeze node.

它首先生成一个单独的进程,稍后将在stdout上将结果序列化为JSON。无论子进程执行什么操作,父进程都会继续执行,并且可以触发超时。

It starts by spawning a separate process, which will later send the result serialized to JSON on its stdout. The parent process continues executing regardless of what the child does and can trigger a timeout.

然后将不受信任的代码封装在带有严格模式(在常规JavaScript中,您可以使用 arguments.callee.caller 访问范围之外的数据)。最后,传递了一个非常有限的全局对象,以防止访问节点的API。不受信任的代码只能进行基本计算,并且无法访问文件或套接字。

The untrusted code is then wrapped in a closure with strict mode (in regular JavaScript, you can use arguments.callee.caller to access data outside of your scope). Finally, a very limited global object is passed to prevent access to node's API. The untrusted code can only do basic computation and has no access to files or sockets.

虽然您应该阅读沙盒的代码作为灵感,但我不建议将其用作是:

While you should read sandbox's code as an inspiration, I wouldn't recommend using it as is:


  • 代码已经过时且已有7个月没有更新。

  • 节点中的子进程模块已经提供了您需要的大部分功能,尤其是 child_process.fork()

  • child_process.fork提供的IPC频道可能有更好的表现。

为了提高安全性,您还可以考虑使用 setuid-sandbox 。这是Google Chrome用于阻止标签流程访问文件系统的代码。你必须制作一个原生模块,但这个示例看起来很简单。

For increased security, you could also consider using setuid-sandbox. It's the code used by Google Chrome to prevent tab processes from accessing the file system. You would have to make a native module, but this example seems straightforward.

这篇关于如何在node.js沙箱中安全地运行用户提交的脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆