0

I am wondering if it is possible to properly secure Nashorn (or any other script engine) to make it safe to run user code. This code would be for the purpose of letting the user perform actions at certain stages in the application, much similar to a web hook. I know there is a way to block certain classes from access from within Nashorn, but is there a way to bypass that through reflection? How would I go about securing these functions, or is this just not going to work out?

vikarjramun
  • 1,042
  • 12
  • 30
  • These come up a few times [before](https://stackoverflow.com/questions/1878052/security-problem-with-java-scriptengine) you can use the SecurityManager to control what can and can't be executed – GrahamA Feb 15 '18 at 22:50

1 Answers1

1

You should limit the objects you place in the script environment to just those that your users need to access for example from Oracle: Scripting for the Java Platform

jsEngine.put("namesListKey", namesList);
System.out.println("Executing in script environment...");
  try {
    jsEngine.eval("var x;" +
                  "var names = namesListKey.toArray();" +
                  "for(x in names) {" +
                  "  println(names[x]);" +
                  "}" +
                  "namesListKey.add(\"Dana\");");
  } catch (ScriptException ex) {
      ex.printStackTrace();
  }
  System.out.println("Executing in Java environment...");
  for (String name: namesList) {
    System.out.println(name);
  }

In this example only the namesListKey is avalaible to the script, other objects will not be. Avoid god objects.

Applications such as Thingworx implement a Javascript processing environment allowing access to a subset of the applications objects.

GrahamA
  • 5,875
  • 29
  • 39
  • Would this prevent access through reflection? For example, couldn't this code access the Java.lang package and use static methods for reflection `import(Java.lang.*)`? This was taken from your same example website – vikarjramun Feb 15 '18 at 15:58
  • I think that's why you need to be careful about what you import – GrahamA Feb 15 '18 at 19:01
  • what stops the user from adding imports to their code? – vikarjramun Feb 15 '18 at 19:03