Search code examples
javasecurityscriptengine

Java - How do I sandbox ScriptEngineManager?


I can easily execute JavaScript using the built-in ScriptEngineManager. However, it gives full permission to JavaScript, which is a big problem for me.

It allows dangerous commands such as:

  • javax.swing.JOptionPane.showMessageDialog(null, "Hello, Server!");
  • java.lang.System.exit(0);

How do I limit the availability of Java functions in the Javascript Engine?


Solution

  • The sandbox by default blocks access to all Java classes.

    NashornSandbox sandbox = NashornSandboxes.create();
    sandbox.allow(File.class);  
    sandbox.eval("var File = Java.type('java.io.File'); File;")
    

    delight-nashorn-sandbox