- Loading...
When you call "eval" method on ScriptEngine passing a String or a Reader, the script is treated as untrusted and so it gets only permissions given to "sandbox" code. This is true for eval ECMAScript builtin function as well. The nashorn script evaluated does not inherit permissions of the calling Java code. This is because nashorn engine receives script whose origin URL is unknown to it!
So, how can we then grant permissions for specific scripts? We may have trusted local scripts for which we may want grant more permissions compared to what is given to sandbox scripts.
Instead of passing a String or any other Reader to "eval" method, you can pass an instance of jdk.nashorn.api.scripting.URLReader. URLReader constructor accepts a URL. With that, you can grant permissions to a specific script by using URL of the script in your security policy file. The following sample code demonstrates the use of URLReader.
import java.io.*; import java.nio.file.*; import javax.script.*; import jdk.nashorn.api.scripting.*; public class Main { public static void main(String[] args) throws Exception { ScriptEngineManager m = new ScriptEngineManager(); ScriptEngine e = m.getEngineByName("nashorn"); if (args.length == 0) { System.err.println("Usage: java Main <script_file>"); return; } // args[0] is script file to which permissions are granted // in security policy File file = new File(args[0]); // read the file content and pass a String to 'eval' // The script is untrusted as nashorn does not know the origin! try { e.eval(new String(Files.readAllBytes(file.toPath()))); } catch (SecurityException se) { System.out.println(se); } // create a Reader over the file and pass to 'eval' // The script is untrusted as nashorn does not know the origin! try { e.eval(new FileReader(file)); } catch (SecurityException se) { System.out.println(se); } // pass a URLReader on file - script will get permissions // configured in security policy! e.eval(new URLReader(file.toURL())); } }
var File = java.io.File; // list contents of the current directory! for each (var f in new File(".").list()) print(f)