Code injection occurs when an application executes untrusted code from an attacker. User input gets concatenated with code. The input is executed without validation or sanitization.
1// Noncompliant: User input gets executed as a code.
2fun noncompliant() {
3 val shell = GroovyShell()
4 val script: String = request.getParameter("script")
5 shell.evaluate(script)
6}
1// Compliant: Pre-defined string gets executed as a code.
2fun compliant() {
3 val shell = GroovyShell()
4 val script: String = request.getParameter("script")
5 shell.evaluate("script")
6}
1// Noncompliant: User input gets executed as a expression.
2fun noncompliant() {
3 val input = request.getParameter("expr")
4 val jexl: JexlEngine = JexlBuilder().create()
5 val expression: JexlExpression = jexl.createExpression(input)
6 val context: JexlContext = MapContext()
7 expression.evaluate(context)
8}
1// Compliant: Pre-defined string gets executed as a expression.
2fun compliant() {
3 val input = "hardcoded-value"
4 val jexl: JexlEngine = JexlBuilder().create()
5 val expression: JexlExpression = jexl.createExpression(input)
6 val context: JexlContext = MapContext()
7 expression.evaluate(context)
8}