Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

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. The following files Main.java, test.js and test.policy are assumed to stored under "D:\test" directory on a Windows machine. You may want to adjust security policy file – if you store these under a different directory (or in a different OS).

 

Code Block
languagejava
titleMain.java
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()));
  }
}

...

Code Block
languagejava
titletest.policy
// give AllPermission for Main class (or any class in that directory!)
grant codeBase "file:///d:/test" {
    permission java.security.AllPermission;
};

// give AllPermission to test.js script
grant codeBase "file:///d:/test/test.js" {
    permission java.security.AllPermission;
};

 

$ javac Main.java

$ java -Djava.security.manager -Djava.security.policy=./test.policy Main test.js

java.security.AccessControlException: access denied ("java.io.FilePermission" "." "read")
java.security.AccessControlException: access denied ("java.io.FilePermission" "." "read")
Main.class
Main.java
test.js
test.policy