问题
I am currently considering issues of running user-supplied code in node. I have two issues:
- The user script must not read or write global state. For that, I assume I can simply spawn of a new process. Are there any other considerations? Do I have to hide the parent process from the child somehow, or is there no way a child can read, write or otherwise toy with the parent process?
- The user script must not do anything funky with the system. So, I am thinking of disallowing any system calls. How do I achieve this? (Note that if I can disallow the process module, point 1 should be fixed as well, no?)
回答1:
You are looking for the runInNewContext
function from the vm
module (vm documentation).
When you use this function it creates a VERY limited context. You'll need to pass anything you want into the sandbox object which become global objects. For example: You will need to include console
in the sandbox object if you want your untrusted code to write to the console.
Another thing to consider: Creating a new context is a VERY expensive operation - takes extra time and memory to do. Seriously consider if you absolutely need this. Also seriously consider how often this is going to happen.
Example:
var vm = require('vm');
var sandbox = {
console: console,
msg: "this is a test",
};
vm.runInNewContext('console.log(msg);', sandbox, 'myfile.vm');
// this is a test
Edit: More to consider: You will want to create a new process to run this in. Even though it's in a new context it's still in the same process that it's being called from. So a malicious user could simply set a never ending for
loop so that it never exits. You'll need to figure out logic to know when something like this happens so that you can kill the process and create a new one.
Last thought: A new context does not have setTimeout or
setInterval. You may or may not want to add these. However, if you create a
setInterval` in the untrusted code and the untrusted code never stops it then it will continue on forever. You'll need to figure a way to end the script, it's probably possible I just haven't looked into it.
来源:https://stackoverflow.com/questions/22572781/prevent-system-calls-in-node-js-when-running-untrusted-user-code