我试图限制在 Groovy 脚本中使用循环(FOR 和 WHILE 运算符)。 我试过http://groovy-sandbox.kohsuke.org/但似乎无法使用此库限制循环。
代码:
final String script = "while(true){}";
final ImportCustomizer imports = new ImportCustomizer();
imports.addStaticStars("java.lang.Math");
imports.addStarImports("groovyx.net.http");
imports.addStaticStars("groovyx.net.http.ContentType", "groovyx.net.http.Method");
final SecureASTCustomizer secure = new SecureASTCustomizer();
secure.setClosuresAllowed(true);
List<Integer> tokensBlacklist = new ArrayList<>();
tokensBlacklist.add(Types.KEYWORD_WHILE);
secure.setTokensBlacklist(tokensBlacklist);
final CompilerConfiguration config = new CompilerConfiguration();
config.addCompilationCustomizers(imports, secure);
Binding intBinding = new Binding();
GroovyShell shell = new GroovyShell(intBinding, config);
final Object eval = shell.evaluate(script);
我的代码有什么问题,或者可能有人知道我如何限制某些循环或运算符?
最佳答案
WHILE 和 FOR 是语句。您应该尝试将它们添加为 statementsBlacklist而不是 tokenBlacklist。
List<Class> statementBlacklist = new ArrayList<>();
statementBlacklist.add( org.codehaus.groovy.ast.stmt.WhileStatement );
secure.setStatementsBlacklist( statementBlacklist );
关于java - SecureAST定制器 : how to restrict loops?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23764613/