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 Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
Securing Your Software Supply Chain with JFrog and Azure
Register Today

Trending

  • Adding Mermaid Diagrams to Markdown Documents
  • A Complete Guide to Agile Software Development
  • How AI Will Change Agile Project Management
  • An Overview of Cloud Cryptography

Trending

  • Adding Mermaid Diagrams to Markdown Documents
  • A Complete Guide to Agile Software Development
  • How AI Will Change Agile Project Management
  • An Overview of Cloud Cryptography
  1. DZone
  2. Coding
  3. Languages
  4. Groovy Goodness: Restricting Script Syntax With SecureASTCustomizer

Groovy Goodness: Restricting Script Syntax With SecureASTCustomizer

Hubert Klein Ikkink user avatar by
Hubert Klein Ikkink
·
Apr. 27, 14 · Interview
Like (0)
Save
Tweet
Share
7.94K 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, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Trending

  • Adding Mermaid Diagrams to Markdown Documents
  • A Complete Guide to Agile Software Development
  • How AI Will Change Agile Project Management
  • An Overview of Cloud Cryptography

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: