How to run a JavaScript function in a sandbox environment?

I have an application server written in JavaScript (node.js). I accept the JS function code as input from a web browser. Now I want to be able to run this function on the server without affecting anything else.

I want to make sure that all the variables that this function changes are local to this function and do not affect any other vars on the server.

Also, I would like to somehow avoid endless loops or recursions and any other unforeseen problems.

Basically, I would like the user to be able to run some code as a function that needs to be run before taking any action.

Any ideas?

0
source share
2 answers

Sandbox is a node module, which according to README;

  • Can be used to execute untrusted code.
  • Timeout support (e.g. preventing infinite loops)
  • Limited code (cannot access node.js methods)

The stopping problem , as @maerics wrote about , can be solved by setting a timeout for the code, although you cannot do this in the same process, because, for example, while(1) block it. The sandbox solves this problem using a child process.

Therefore, the variable problem must also be resolved because Sandbox is in the child process, and not in the main process.

As mentioned earlier, if possible, you should avoid users from running arbitrary code on your server, as it carries a huge security risk. Even through the module, these restrictions you must run at least child processes with the most unacceptable user.

+1
source

You cannot programmatically determine whether arbitrary code will run indefinitely or terminate.

This is called the closure problem .

Perhaps you can prevent arbitrary JS code from changing variables other than those it creates with a sandbox in a separate process.

In any case, the adoption of arbitrary code for execution on the server poses a huge risk to your system. Think about how you can avoid this.

+2
source

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


All Articles