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.
Basically I need to setup the javascript scope to only include exactly what they need and no more.
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.
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.
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(); } }
To block Java class and method access have a look at...
http://codeutopia.net/blog/2009/01/02/sandboxing-rhino-in-java/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With