Rules / Java
SHIELD-JAVA-017
SpEL or OGNL Expression Injection
What it detects
Parsing an expression built from concatenated input allows SpEL or OGNL injection.
How to fix
Never evaluate expressions built from user input; use a fixed expression with bound variables.
Vulnerable — Shield flags thisDiscountEngine.java
import org.springframework.expression.Expression;
import org.springframework.expression.spel.standard.SpelExpressionParser;
public class DiscountEngine {
private final SpelExpressionParser parser = new SpelExpressionParser();
// "rule" is typed by the shop admin in the coupon form
public boolean applies(String rule, int cartTotal) {
Expression exp = parser.parseExpression("cartTotal " + rule);
return Boolean.TRUE.equals(exp.getValue(Boolean.class));
}
}
Fixed — scans cleanDiscountEngine.java
import org.springframework.expression.Expression;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
public class DiscountEngine {
private final SpelExpressionParser parser = new SpelExpressionParser();
public boolean applies(int threshold, int cartTotal) {
Expression exp = parser.parseExpression("#cartTotal >= #threshold");
StandardEvaluationContext ctx = new StandardEvaluationContext();
ctx.setVariable("cartTotal", cartTotal);
ctx.setVariable("threshold", threshold);
return Boolean.TRUE.equals(exp.getValue(ctx, Boolean.class));
}
}
Both snippets are verified against the shipped scanner: the vulnerable one triggers SHIELD-JAVA-017, the fixed one does not.