Search code examples
javagroovysandbox

SecureASTCustomizer: how to restrict loops?


I'm trying to restrict using loops(FOR and WHILE operators) in Groovy script. I tried http://groovy-sandbox.kohsuke.org/ but it seems to be not possible to restrict loops with this lib.

Code:

        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);

Whats wrong with my code or probably some one knows how I can restrict some loops or operators?


Solution

  • WHILE and FOR are statements. You should rather try adding them as statementsBlacklist instead of tokenBlacklist.

    List<Class> statementBlacklist = new ArrayList<>();
    statementBlacklist.add( org.codehaus.groovy.ast.stmt.WhileStatement );
    secure.setStatementsBlacklist( statementBlacklist );