从 Rhino 脚本中访问 Java 特权操作

Accessing Java Privileged Actions from within Rhino script

本文关键字:Java 特权 操作 访问 Rhino 脚本      更新时间:2023-09-26

如何在 Java 中从 Rhino 中运行的 JavaScript 执行本地文件?我会考虑任何在 Rhino 环境中工作的方法。我目前对这个问题的探讨如下。

我正在通过java.lang.Runtime.exec尝试这样做,在Mozilla"脚本Java"教程的帮助下,我可以访问它。但是,这是一个受限的操作,因此直接调用它会给出访问控制异常。

为了解决这个问题,我需要使用 AccesController.doPrivileged 方法。下面是在 Java 中使用它的示例;

AccessController.doPrivileged(new PrivilegedAction() {
          public Object run() {
             // Code goes here. Any permission checks within this
             // run method will require that the intersection of the
             // callers protection domain and the snapshot's
             // context have the desired permission.
          }

障碍是在javascript中复制PrivilegedAction的构造。

var ourRuntime = Packages.java.lang.Runtime.getRuntime();
//ourRuntime.exec("notepad.exe") //will raise Access Control Exception
var controller = Packages.java.security.AccessController.doPrivileged
var action = new Packages.java.security.PrivilegedAction(ourRuntime.exec("notepad.exe"))         // somehow make this wwrk
controller.doPrivileged(action)

Mozilla Scripting Java

java.securit.AccessController

Java 6 脚本 API 支持 Rhino,因此您可以使用 doPrivileged 包装脚本的评估,并使用必要的权限执行整个脚本。Java 脚本 API 与 doPrivileged 相结合的示例在这里

我以

这种方式成功地启动了 KWrite(例如)。我基本上将运行时对象公开给嵌入式JavaScript解释器。

public class RunBasicScript {
public static void main(String[] args) {
    // Get a handle to the JavaScript context
    Context cx = Context.enter();
    try 
    {
        // Set up the standard JavaScript objects
        // like Object, Function etc.
        Scriptable scope = cx.initStandardObjects();
        // Make Runtime.getRuntime available to our JavaScript code
        Object exec = Context.javaToJS(Runtime.getRuntime(), scope);
        ScriptableObject.putProperty(scope, "exec", exec);
        // Build our awesome script
        String script = "exec.exec('kwrite');";
        // Now we execute the script
        Object obj = cx.evaluateString(scope, script, "Testing", 1, null);
    } 
    catch (Exception e) 
    {
        System.err.println("Error : " + e);
    }
    finally 
    {
        // We need to exit the Context.
        Context.exit();
    }
}

}