我们的应用程序中有一个管理调试控制台,可让您输入脚本
并提交以返回结果。我们不用担心
恶意用户,但希望阻止某些基本内容
进入System.exit(1)只是为了查看它的作用。不幸,
添加安全策略文件不是一种选择。还有其他办法吗
沙盒脚本?

最佳答案

我查看了Groovy的“ NoExitSecurityManager”,发现它正是在这样做:禁止System.exit()...这还不够。

我的解决方案是创建自己的类“ DisallowAllSecurityManager”,该类扩展了SecurityManager并通过在每个check ..方法中抛出SecurityException来禁止脚本不需要的所有内容,例如对文件系统的写访问或连接到其他主机。

但是:您不能在所有check ..方法中引发异常。这是您需要允许的check ..方法的列表:


checkCreateClassLoader()
checkMemberAccess()
checkPackageAccess()
checkPermission()
checkPropertyAccess()
checkRead()


当您要评估Groovy脚本时,可以通过以下方式进行操作,仅限制groovy脚本:

SecurityManager securityManager = System.getSecurityManager();
try {
 System.setSecurityManager(new DisallowAllSecurityManager());
 Object result = groovyShell.evaluate(expression);
        ...
} catch (...) {
        ...
} finally {
        System.setSecurityManager(securityManager);
}

10-06 16:11
查看更多