Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you run Javascript using Rhino for Java in a sandbox?

Part of our java application needs to run javascript that is written by non-developers. These non-developers are using javascript for data formatting. (Simple logic and string concatenation mostly).

My question is how can I setup the execution of these scripts to make sure scripting errors don't have a major negative impact on the rest of the application.

  • Need to guard against infinite loops
  • Guard against spawning new threads.
  • Limit access to services and environment
    • File system (Example: If a disgruntled script writer decided to delete files)
    • Database (Same thing delete database records)

Basically I need to setup the javascript scope to only include exactly what they need and no more.

like image 634
delux247 Avatar asked Sep 18 '08 16:09

delux247


People also ask

What is Rhino for JavaScript used for?

Rhino converts JavaScript scripts into classes. Rhino works in both compiled and interpreted mode. It is intended to be used in desktop or server-side applications, hence there is no built-in support for the Web browser objects that are commonly associated with JavaScript.

What is the substitute of Rhino JavaScript engine?

Correct Option: CNashorn provides 2 to 10 times faster in terms of performance, as it directly compiles the code in memory and passes the bytecode to JVM. Nashorn uses invoke dynamic feature.


2 Answers

To guard against infinite loops, you can observe the instruction count as the script runs (this works only with interpreted scripts, not with compiled ones).

There is this example in the Rhino JavaDocs to prevent a script from running for more than ten seconds:

 protected void observeInstructionCount(Context cx, int instructionCount)  {      MyContext mcx = (MyContext)cx;      long currentTime = System.currentTimeMillis();      if (currentTime - mcx.startTime > 10*1000) {          // More then 10 seconds from Context creation time:          // it is time to stop the script.          // Throw Error instance to ensure that script will never          // get control back through catch or finally.          throw new Error();      }  } 
like image 194
Thilo Avatar answered Sep 29 '22 22:09

Thilo


To block Java class and method access have a look at...

http://codeutopia.net/blog/2009/01/02/sandboxing-rhino-in-java/

like image 45
Sebastian Kübeck Avatar answered Sep 30 '22 00:09

Sebastian Kübeck