如何在 SecurityManager 下运行 Java 8 的 nashorn

Sco*_*t B 4 security sandbox java-8 nashorn

我正在寻找沙盒 Java 8 的 Nashorn javascript 引擎。我已经发现了 --no-java 标志,它有帮助,但我还发现以下链接说需要“在启用 SecurityManager 的情况下运行”:http : //mail.openjdk.java.net/ pipermail/nashorn-dev/2013-September/002010.html

我还没有找到说明如何使用 Nashorn 完成此操作的文档,那么如何安全地完成此操作?

小智 5

我知道您可能不再需要它了,但是对于那些在这里寻找在沙箱中运行 nashorn 的简单方法的人来说:如果您只想防止脚本使用反射,请设置一个 ClassFilter。这样你就可以只允许使用一些可用的类......或者根本不使用。

NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
ScriptEngine scriptEngine = factory.getScriptEngine(
    new String[] { "--no-java" }, //a quick way to disable direct access to java API
    null, //a ClassLoader, let's just ignore it
    new ClassFilter() { //this one simply forbids use of any java classes, including reflection
        @Override
        public boolean exposeToScripts(String string) {
            return false;
        }
    }
);
Run Code Online (Sandbox Code Playgroud)