How to block (or isolate) the JDK built-in Javascript interpreter to run untrusted scripts

we have a Java application and we want to run untrusted code using the built-in Javascript interpreter (javax.script. *)

However, by default, the interpreter allows access to any java class. For example, " java.lang.System.exit(0) " in the script will disable the JVM. I find this to be called “Live Connect,” see Sun's “Java Script Programmer's Guide” for more details.

I would like to somehow disable the script access feature for Java classes, i.e. I want the script to be able to access objects that I specifically insert using the eval() or put() methods on ScriptEngine .

I found some documentation on how to achieve this using an older standalone version of the interpreter (Rhino), e.g. see http://codeutopia.net/blog/2009/01/02/sandboxing-rhino-in-java/

However, this approach is not possible in JDK 1.6 without using the inner classes of the sun, since ClassShutter, etc. are internally configured and cannot be overridden by public methods.

I hope there is an easy way around this that does not require going through complex hoops with the help of a special SecurityManager, ClassLoader, etc., but could not find anything.

You would expect with the frequency of the security bulletins surrounding Javascript in different applications, there would be a simple flag to disable Live Connect!

+7
javascript security sandbox
source share
2 answers

Take a look at the java sandbox library and a post on how to do exactly what you want for groovy ( http://blog.datenwerke.net/2013/06/sandboxing-groovy-with-java-sandbox.html ). Rhino can be solved in a similar way.

+1
source share

I searched a lot, tried to use the sandboxing method for codeutopia.net and other SecurityManager solutions, I felt unsatisfied. And then a solution came out for my class loader based on the built-in JDK rion library without importing any third-party libraries. Two Java classes with approximately 200 lines of code, this is currently my simplest solution that fits my requirement for JavaScript only.

  • Find JavaScript script engine factory class name using ScriptEngineManager # getEngineFactories
  • Load the script engine factory class into a new classloader in which JavaMembers or other related classes are ignored.
  • Call #getScriptEngine in a loaded script engine factory and eval scripts on the returned script engine.

If this script contains a Java script, the class loader will try to load JavaMembers or other classes and throw a class class exception. In this way, malicious scripts will be ignored without execution.

Read the ConfigJSParser.java and ConfigJSClassLoader.java files for more details:

https://github.com/webuzz/simpleconfig/tree/master/js/im/webuzz/config

+1
source share

All Articles