Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to run user-submitted scripts securely in a node.js sandbox?

How to run user-submitted scripts securely in a node.js sandbox?

Problem

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, {}) is a tempting starting point... but it seems like there are known issues there.

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

Problem courtesy of: broofa

Solution

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.

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.

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:

  • The code is getting old and hasn't been updated for 7 months.
  • The Child Process module in node already provides most of the features you need, especially child_process.fork().
  • The IPC channel provided by child_process.fork probably has better performances.

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.

Solution courtesy of: Laurent Perrin

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

How to run user-submitted scripts securely in a node.js sandbox?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×