Nodejs: Can eval js code use runInNewContext and limit its execution timeout?

I would like to execute untrusted js code using runInNewContext in node.js, but as far as I can see, there is no way to limit its runtime. It is also sync. is there any way to set a timeout for it or an asynchronous version that will allow me to control its execution from "outside"?

UPDATE: starting in an external process is not suitable:

  • takes too many resources
  • More importantly, I need code to access my data / code, although the environment is sandboxed
+6
source share
3 answers

I want to execute untrusted js code using runInNewContext in node.js, but as far as I can see, there is no way to limit its execution time. It is also sync. Is there a way to set a timeout on this or an asynchronous version that will allow me to control its execution from "outside"?

I think what you are saying is absolutely true. I think the only option is to fill out the Joyent / Ryan Dahl question. I hope he / they can come up with something clever or maybe tell you that this is not possible.

From vm.runInNewContext :

Please note that running untrusted code is a complex business requiring a lot of care. To prevent an accidental global variable leak, vm.runInNewContext is quite useful, but running untrusted code safely requires a separate process.

To do this safely, you need to run an external program. I think that the "expensive part" can be avoided pre-sales .

One management process is responsible for launching child processes that listen for communications and serve them when they arrive. Apache always tries to support several backup or idle server processes that are willing to serve incoming requests. Thus, customers do not have to wait until new child processes are developed before their requests can be submitted.

0
source

Run the script in the external process using dnode or child_process.fork , set the end timer and the end process if the timeout is reached or the timer if the script is finished.

+1
source

Now this is possible because I added support for the timeout parameter to the Node vm module. You can simply pass the timeout value in milliseconds to runInNewContext() , and it will throw an exception if the code does not complete execution within the specified period of time.

Please note: this does not imply any security model for running untrusted code. It just allows you a timeout that you trust or otherwise protect.

 var vm = require("vm"); try { vm.runInNewContext("while(true) {}", {}, "loop", 1000); } catch (e) { // Exception thrown after 1000ms } console.log("finished"); // Will now be executed 

Exactly what you expect:

 $ time ./node test.js finished real 0m1.069s user 0m1.047s sys 0m0.017s 
-2
source

Source: https://habr.com/ru/post/891692/


All Articles