Search code examples
javascriptnode.jsprocesssandbox

Node JS - executing a string of code in a new process


Let's say I have a string of NodeJS code I want to execute, but it's untrusted, and thus I must sandbox it, using vm.runInNewContext(stringOfCode). Two questions arise:

  1. If I do have some objects I want to use within the executed code, how may that bee achieved?
  2. Let's say I want to limit the execution time of the code to 5 seconds, how may I do that?
  3. How may I run this code on a new process? I now I can use child_process.fork(), but how exactly will I do that?

Thank you!!


Solution

    1. The sandbox argument you provide to vm.runInNewContext() is the object which will be available to the sandboxed code. Put there anything you need to use from inside. It's described in the docs:

    http://nodejs.org/api/vm.html#vm_vm_runinnewcontext_code_sandbox_filename

    1. But as the documentation says, you should better put the untrusted code into a separate process. Otherwise the code could simply hang with while(true);. As you mentioned yourself, the chlid_process.fork() shoudl be used for that. The docs are here:

    http://nodejs.org/api/child_process.html#child_process_child_process_fork_modulepath_args_options

    But in this case you cannot transfer the objects to the new process, the messaging should be used instead.

    Finally there's a library which simplifies everything above:

    https://github.com/asvd/jailed