- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
如何阻止用户输入: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/
我必须开发一个自定义选项卡控件并决定使用 WPF/XAML 创建它,因为我无论如何都打算学习它。完成后应该是这样的: 到目前为止,我取得了很好的进展,但还有两个问题: 只有第一个/最后一个标签项应该有
我要定制xtable用于导出到 LaTeX。我知道有些问题是关于 xtable在这里,但我找不到我要找的具体东西。 以下是我的表的外观示例: my.table <- data.frame(Specif
用ejs在这里显示日期 它给我结果 Tue Feb 02 2016 16:02:24 GMT+0530 (IST) 但是我需要表现为 19th January, 2016 如何在ejs中执行此操作?
我想问在 JavaFX 中使用自定义对象制作 ListView 的最佳方法,我想要一个每个项目如下所示的列表: 我搜了一下,发现大部分人都是用细胞工厂的方法来做的。有没有其他办法?例如使用客户 fxm
我是一名优秀的程序员,十分优秀!