1

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?

Lugaru
  • 1,430
  • 3
  • 25
  • 38

1 Answers1

2

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 );
dmahapatro
  • 49,365
  • 7
  • 88
  • 117
  • I think that is correct. You can simplify those 3 lines down to just "secure.statementsBlacklist = [org.codehaus.groovy.ast.stmt.WhileStatement]" if you like. – Jeff Scott Brown May 21 '14 at 03:10
  • Cool, i also just realised that. And what i found that in a case of using Whitelists its better and less buggy compare with Blacklists. – Lugaru May 21 '14 at 08:11