gpt4 book ai didi

nashorn - 如何阻止 Nashorn 允许使用 quit() 函数?

转载 作者:行者123 更新时间:2023-12-03 22:15:28 28 4
gpt4 key购买 nike

我正在尝试向我们的系统添加一个脚本功能,不受信任的用户可以在其中编写简单的脚本并让它们在服务器端执行。我正在尝试使用 Nashorn 作为脚本引擎。

不幸的是,他们为 Nashorn 添加了一些非标准功能:

https://docs.oracle.com/javase/8/docs/technotes/guides/scripting/nashorn/shell.html#sthref29

向下滚动到“Additional Nashorn Built-in Functions”并查看“quit()”函数。是的,如果一个不受信任的用户运行此代码,整个 JVM 就会关闭。

这很奇怪,因为 Nashorn 专门预期运行不受信任的脚本。见:https://docs.oracle.com/javase/8/docs/technotes/guides/scripting/nashorn/api.html#classfilter_introduction

Applications that embed Nashorn, in particular, server-side JavaScript frameworks, often have to run scripts from untrusted sources and therefore must limit access to Java APIs. These applications can implement the ClassFilter interface to restrict Java class access to a subset of Java classes.



有什么办法可以防止这种行为?如何防止用户运行任何附加功能?

最佳答案

不幸的是,目前没有办法控制非标准全局函数的创建。一种解决方法是在 ScriptEngine 初始化后简单地从全局对象中删除这些函数:

final NashornScriptEngineFactory engineManager = new NashornScriptEngineFactory();
final ScriptEngine engine = engineManager.getScriptEngine();
final Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
bindings.remove("print");
bindings.remove("load");
bindings.remove("loadWithNewGlobal");
bindings.remove("exit");
bindings.remove("quit");
System.err.println(engine.eval("'quit is ' + typeof quit"));

如果您使用的是 Nashorn shell,一个简单的 delete quit;会做。

如果您使用 ScriptEngine 接口(interface)并创建多个绑定(bind),则必须对创建的每个全局对象/绑定(bind)执行此操作。

关于nashorn - 如何阻止 Nashorn 允许使用 quit() 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31127641/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com