DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Why "Polyglot Programming" or "Do It Yourself Programming Languages" or "Language Oriented Programming" sucks?
  • Designing Mathematical Software for Humans
  • Advancing DSLs in the Age of GenAI
  • The Unreasonable Effectiveness of the Actor Model for Creating Agentic LLM Applications

Trending

  • Why Your Test Automation Is Always Behind the Code And the Architecture That Fixes It
  • Persistent Memory for AI Agents Using LangChain's Deep Agents
  • The Documentation Crisis Nobody Sees: Why AI Agents Are Breaking Faster Than Humans Can Document Them
  • Zero-Downtime Deployments for Java Apps on Kubernetes
  1. DZone
  2. Coding
  3. Languages
  4. Groovy Goodness: Restricting Script Syntax With SecureASTCustomizer

Groovy Goodness: Restricting Script Syntax With SecureASTCustomizer

By 
Hubert Klein Ikkink user avatar
Hubert Klein Ikkink
·
Apr. 27, 14 · Interview
Likes (0)
Comment
Save
Tweet
Share
9.2K Views

Join the DZone community and get the full member experience.

Join For Free

Running Groovy scripts with GroovyShell is easy. We can for example incorporate a Domain Specific Language (DSL) in our application where the DSL is expressed in Groovy code and executed by GroovyShell. To limit the constructs that can be used in the DSL (which is Groovy code) we can apply a SecureASTCustomizer to the GroovyShell configuration. With the SecureASTCustomizer the Abstract Syntax Tree (AST) is inspected, we cannot define runtime checks here. We can for example disallow the definition of closures and methods in the DSL script. Or we can limit the tokens to be used to just a plus or minus token. To have even more control we can implement the StatementChecker andExpressionChecker interface to determine if a specific statement or expression is allowed or not.

In the following sample we first use the properties of the SecureASTCustomizer class to define what is possible and not within the script:

package com.mrhaki.blog

import org.codehaus.groovy.control.customizers.SecureASTCustomizer
import org.codehaus.groovy.control.CompilerConfiguration
import org.codehaus.groovy.ast.stmt.*
import org.codehaus.groovy.ast.expr.*
import org.codehaus.groovy.control.MultipleCompilationErrorsException

import static org.codehaus.groovy.syntax.Types.PLUS
import static org.codehaus.groovy.syntax.Types.MINUS
import static org.codehaus.groovy.syntax.Types.EQUAL

// Define SecureASTCustomizer to limit allowed
// language syntax in scripts.
final SecureASTCustomizer astCustomizer = new SecureASTCustomizer(
    // Do not allow method creation.
    methodDefinitionAllowed: false,

    // Do not allow closure creation.
    closuresAllowed: false,

    // No package allowed.
    packageAllowed: false,

    // White or blacklists for imports.
    importsBlacklist: ['java.util.Date'],
    // or importsWhitelist
    staticImportsWhitelist: [],
    // or staticImportBlacklist
    staticStarImportsWhitelist: [],
    // or staticStarImportsBlacklist

    // Make sure indirect imports are restricted.
    indirectImportCheckEnabled: true,

    // Only allow plus and minus tokens.
    tokensWhitelist: [PLUS, MINUS, EQUAL],
    // or tokensBlacklist

    // Disallow constant types.
    constantTypesClassesWhiteList: [Integer, Object, String],
    // or constantTypesWhiteList
    // or constantTypesBlackList
    // or constantTypesClassesBlackList
    
    // Restrict method calls to whitelisted classes.
    // receiversClassesWhiteList: [],
    // or receiversWhiteList
    // or receiversClassesBlackList
    // or receiversBlackList

    // Ignore certain language statement by
    // whitelisting or blacklisting them.
    statementsBlacklist: [IfStatement],
    // or statementsWhitelist

    // Ignore certain language expressions by
    // whitelisting or blacklisting them.
    expressionsBlacklist: [MethodCallExpression]
    // or expresionsWhitelist
)

// Add SecureASTCustomizer to configuration for shell.
final conf = new CompilerConfiguration()
conf.addCompilationCustomizers(astCustomizer)

// Create shell with given configuration.
final shell = new GroovyShell(conf)

// All valid script.
final result = shell.evaluate '''
def s1 = 'Groovy'
def s2 = 'rocks'
"$s1 $s2!"
'''

assert result == 'Groovy rocks!'

// Some invalid scripts.
try {
    // Importing [java.util.Date] is not allowed
    shell.evaluate '''
    new Date() 
    '''
} catch (MultipleCompilationErrorsException e) {
    assert e.message.contains('Indirect import checks prevents usage of expression')
}


try {
    // MethodCallExpression not allowed
    shell.evaluate '''
    println "Groovy rocks!" 
    '''
} catch (MultipleCompilationErrorsException e) {
    assert e.message.contains('MethodCallExpressions are not allowed: this.println(Groovy rocks!)')
}

To have more fine-grained control on which statements and expression are allowed we can implement the StatementChecker andExpressionChecker interfaces. These interfaces have one method isAuthorized with a boolean return type. We return true if a statement or expression is allowed and false if not.

package com.mrhaki.blog

import org.codehaus.groovy.control.customizers.SecureASTCustomizer
import org.codehaus.groovy.control.CompilerConfiguration
import org.codehaus.groovy.ast.stmt.*
import org.codehaus.groovy.ast.expr.*
import org.codehaus.groovy.control.MultipleCompilationErrorsException

import static org.codehaus.groovy.control.customizers.SecureASTCustomizer.ExpressionChecker
import static org.codehaus.groovy.control.customizers.SecureASTCustomizer.StatementChecker


// Define SecureASTCustomizer.
final SecureASTCustomizer astCustomizer = new SecureASTCustomizer()

// Define expression checker to deny 
// usage of variable names with length of 1.
def smallVariableNames = { expr ->
    if (expr instanceof VariableExpression) {
        expr.variable.size() > 1
    } else {
        true
    }
} as ExpressionChecker

astCustomizer.addExpressionCheckers smallVariableNames


// In for loops the collection name
// can only be 'names'.
def forCollectionNames = { statement ->
    if (statement instanceof ForStatement) {
        statement.collectionExpression.variable == 'names'
    } else {    
        true
    }
} as StatementChecker

astCustomizer.addStatementCheckers forCollectionNames


// Add SecureASTCustomizer to configuration for shell.
final CompilerConfiguration conf = new CompilerConfiguration()
conf.addCompilationCustomizers(astCustomizer)

// Create shell with given configuration.
final GroovyShell shell = new GroovyShell(conf)

// All valid script.
final result = shell.evaluate '''
def names = ['Groovy', 'Grails']
for (name in names) {
    print "$name rocks! " 
}

def s1 = 'Groovy'
def s2 = 'rocks'
"$s1 $s2!"
'''

assert result == 'Groovy rocks!'

// Some invalid scripts.
try {
    // Variable s has length 1, which is not allowed.
    shell.evaluate '''
    def s = 'Groovy rocks'
    s
    '''
} catch (MultipleCompilationErrorsException e) {
    assert e.message.contains('Expression [VariableExpression] is not allowed: s')
}


try {
    // Only names as collection expression is allowed.
    shell.evaluate '''
    def languages = ['Groovy', 'Grails']
    for (name in languages) {
        println "$name rocks!" 
    }
    '''
} catch (MultipleCompilationErrorsException e) {
    assert e.message.contains('Statement [ForStatement] is not allowed')
}

Code written with Groovy 2.2.2.

Groovy (programming language) Domain-Specific Language Syntax (programming languages)

Published at DZone with permission of Hubert Klein Ikkink. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Why "Polyglot Programming" or "Do It Yourself Programming Languages" or "Language Oriented Programming" sucks?
  • Designing Mathematical Software for Humans
  • Advancing DSLs in the Age of GenAI
  • The Unreasonable Effectiveness of the Actor Model for Creating Agentic LLM Applications

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook