gpt4 book ai didi

Java运行自定义的groovy代码,如何保证groovy安全?

转载 作者:行者123 更新时间:2023-12-02 01:15:01 24 4
gpt4 key购买 nike

如何阻止用户输入:System.exit(0) 和无限循环

例如:

public class TestGroovy {
public static ScriptEngineManager factory = new ScriptEngineManager();

public static void main(String[] args) throws ScriptException, NoSuchMethodException {
TestGroovy testGroovy = new TestGroovy();
testGroovy.runGroovy(" def executeMethod(){\n" +
" System.exit(0);\n" +
" }");
}


public void runGroovy(String groovyCode) throws ScriptException, NoSuchMethodException {
ScriptEngine engine = factory.getEngineByName("groovy");
engine.eval(groovyCode);
Invocable invokeEngine = (Invocable) engine;
invokeEngine.invokeFunction("executeMethod");
}

}

如果人们输入System.exit(0)或无限循环,那就太糟糕了。

我想阻止用户输入这些内容。

谢谢~

<小时/>

我使用这个方法的一个答案:

public class MySecurityManager extends SecurityManager{

@Override
public void checkExit(int status) {
throw new SecurityException();
}

}
    public static void main(String[] args) {
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("groovy");

try {
Map<String,Object> output=new HashMap<>();
Bindings binding = engine.createBindings();
binding.put("input",1);
binding.put("output",output);

String fact = "def executeMethod(){\n" +
" \tSystem.exit(0);\n" +
" output.put('your key','your value');\n" +
" return output;\n" +
"}";
engine.eval(fact,binding);
Invocable inv = (Invocable) engine;
MySecurityManager secManager = new MySecurityManager();
System.setSecurityManager(secManager);
output = (Map<String, Object>) inv.invokeFunction("executeMethod",null);
System.out.println(output);
} catch (SecurityException | ScriptException | NoSuchMethodException e) {
System.out.println("can't input System.exit(0)");
}
}

谢谢~

最佳答案

如果您使用单独的线程来运行用户定义的代码,我可以建议以下内容:

对于 System.exit() 调用,您可以定义和设置您自己的 SecurityManager 。它有 checkExit() 方法,用于判断 System.exit 是否可行。覆盖它并提供你的逻辑。此解决方案的缺点是您必须确保您的应用程序始终在启用 SecurityManager 的情况下运行。

对于无限循环或任何其他长时间运行的代码,我只能建议一个外部监视线程,该线程在某些条件下(超时或其他)只会停止线程。但这个解决方案有很多问题:如果您停止的线程拥有未关闭的资源(打开的文件、数据库连接等)或锁,您可能会遇到资源泄漏或死锁。在这种情况下,中断调用将不起作用,因为代码可能会忽略它们。

作为替代解决方案,您可以使用单独的 JVM 来运行用户的代码。

这由你决定。

关于Java运行自定义的groovy代码,如何保证groovy安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58813363/

24 4 0
文章推荐: java - 为什么不能在 kotlin 方法 intArrayOf 中使用十六进制 Int?
文章推荐: java - 在 Spring 的多个 beans 配置文件上使用 '
  • WPF 自定义 TabControl

    我必须开发一个自定义选项卡控件并决定使用 WPF/XAML 创建它,因为我无论如何都打算学习它。完成后应该是这样的: 到目前为止,我取得了很好的进展,但还有两个问题: 只有第一个/最后一个标签项应该有

  • r - 自定义 xtable

    我要定制xtable用于导出到 LaTeX。我知道有些问题是关于 xtable在这里,但我找不到我要找的具体东西。 以下是我的表的外观示例: my.table <- data.frame(Specif

  • ejs - EJS中的日期时间格式/自定义

    用ejs在这里显示日期 它给我结果 Tue Feb 02 2016 16:02:24 GMT+0530 (IST) 但是我需要表现为 19th January, 2016 如何在ejs中执行此操作?

  • JavaFX 自定义 ListView

    我想问在 JavaFX 中使用自定义对象制作 ListView 的最佳方法,我想要一个每个项目如下所示的列表: 我搜了一下,发现大部分人都是用细胞工厂的方法来做的。有没有其他办法?例如使用客户 fxm

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