Implementing DSL whitelisting in Groovy
Groovy in Action provides the following code to secure DSL via SecureASTCustomizer
.
// @author: Groovy in Action
import org.codehaus.groovy.control.*
import org.codehaus.groovy.control.customizers.*
def secure = new SecureASTCustomizer()
secure.with {
closuresAllowed = false
methodDefinitionAllowed = false
importsWhitelist = []
staticImportsWhitelist = []
staticStarImportsWhitelist = ['java.lang.Math']
tokensWhitelist = [
PLUS, MINUS, MULTIPLY, DIVIDE, MOD, POWER,
PLUS_PLUS, MINUS_MINUS,
COMPARE_EQUAL, COMPARE_NOT_EQUAL,
COMPARE_LESS_THAN, COMPARE_LESS_THAN_EQUAL,
COMPARE_GREATER_THAN, COMPARE_GREATER_THAN_EQUAL,
]
constantTypesClassesWhiteList = [
Integer, Float, Long, Double, BigDecimal,
Integer.TYPE, Long.TYPE, Float.TYPE, Double.TYPE
]
receiversClassesWhiteList = [
Math, Integer, Float, Double, Long, BigDecimal
]
statementsWhitelist = [
BlockStatement, ExpressionStatement
]
expressionsWhitelist = [
BinaryExpression, ConstantExpression,
MethodCallExpression, StaticMethodCallExpression,
ArgumentListExpression, PropertyExpression,
UnaryMinusExpression, UnaryPlusExpression,
PrefixExpression, PostfixExpression,
TernaryExpression, ElvisOperatorExpression,
BooleanExpression, ClassExpression
]
}
def config = new CompilerConfiguration()
config.addCompilationCustomizers(secure)
def shell = new GroovyShell(config)
x = shell.evaluate '''
5 + 10
println("exiting...")
System.exit(0)
'''
println x
However, when I run this code, I get a runtime error.
How can I fix the error to get an example working, namely a DSL that does math without allowing any other types of commands like System.exit(0)
.
>groovy WhiteListSimple.groovy
Caught: groovy.lang.MissingPropertyException: No such property: PLUS for class: org.codehaus.groovy.control.customizers.SecureASTCustomizer
groovy.lang.MissingPropertyException: No such property: PLUS for class: org.codehaus.groovy.control.customizers.SecureASTCustomizer
at WhiteListSimple$_run_closure1.doCall(WhiteListSimple.groovy:14)
at WhiteListSimple.run(WhiteListSimple.groovy:6)
source to share
PLUS
and friends are now in
import static org.codehaus.groovy.syntax.Types.*
And you also need
import org.codehaus.groovy.ast.stmt.* // for the classes in `statementsWhitelist`
import org.codehaus.groovy.ast.expr.* // for the classes in `expressionsWhitelist`
Considering the book is from 2009 and you are using groovy right now in the 2.3 range, the package / class locations just changed over time or the source code never worked in the first place.
You might want to consider an IDE to help you find the classes / instantiations import
for you.
source to share