Search code examples
securityjsfelcode-injectioncrlf-vulnerability

How to prevent code injection with EL expression


While I am using the JSF and I am trying to find the ValueExpression with below code:

public static final ValueExpression createValueExpression(
            final FacesContext context, final ELContext elContext,
            final String ev, final Class classType) {
        return context.getApplication().getExpressionFactory()
            .createValueExpression(elContext, ev, classType);
    }

But When I am running these code on HP fortify says that Interpreting user-controlled instructions at run-time can allow attackers to execute malicious code. It seems there is a risk of code injection with EL expression evaluation. But I know there is the code vulnerability so I want to know How Can I prevent the EL injection?

Could anyone help on the same?


Solution

  • Here expression string 'env' can be vulnerable to Expression Language Injection which occurs when attackers control data that is evaluated by an Expression Language interpreter.

    For the solution, A more effective approach may be to perform data validation best practice against untrusted input and to ensure that output encoding is applied when data arrives on the EL layer, so that no metacharacter is found by the interpreter within the user content before evaluation. The most obvious patterns to detect include “${“ and “#{“, but it may be possible to encode or fragment this data.

    So you can create a 'whitelist' pattern to match for the expression 'evn' before creating a value expression(whitelist can be something like: `[a-zA-Z0-9_.*#{}]*').

        Pattern pattern = Pattern.compile("[a-zA-Z0-9_\.\*#\{\}]*");
        Matcher matcher = pattern.matcher(ev);
        if (!matcher.matches()) {
            String message = "Detected a potential EL injection attack - 
                  value["
                + ev+ "]"; 
             throw new Exception(message);
        }