How does Struts 2 read parameters from request

1.3k Views Asked by At

I have implemented an XSS filter as given below,

@Override
public String getParameter(String parameter) {
    String value = super.getParameter(parameter);

    return stripXSS(value);
}

@Override
public String getHeader(String name) {
    String value = super.getHeader(name);
    return stripXSS(value);
}

private String stripXSS(String value) 
{
    System.err.println("Initial Value "+value);

    if (value != null) 
    {
        // NOTE: It's highly recommended to use the ESAPI library and uncomment the following line to
        // avoid encoded attacks.
        value = ESAPI.encoder().canonicalize(value);
        
        System.err.println("Encoded Value "+value);
        
        // Avoid null characters
        value = value.replaceAll("\0", "");

        // Remove all sections that match a pattern
        for (Pattern scriptPattern : patterns){
            value = scriptPattern.matcher(value).replaceAll("");
        }
        
        System.err.println("Pattern Value "+value);
    }
    System.err.println("Final  Value "+value);
    return value;
}

Almost all request pass through one of these methods, but when I use a Struts 2 ModelDriven approach these methods are not invoked.

How does Struts retrieve the parameters, where I can strip the parameters?

2

There are 2 best solutions below

0
On

Struts2 creates a Map of parameters from the request using request.getParameterMap() and put these parameters to the ActionContext.

So, you can create an interceptor which is getting these parameters from the context and do what you want. Add a new interceptor to all actions either using custom stack or overridden action config.

0
On

Dont mess filters and interceptors, they are completely different things.

In order to make things easier to Struts I'd recommend to use interceptors to prevent XSS attacks. Play with this parameter within the Action Context.

If you prefer to use filters, you will have to re-introduced modified variable in the request, that's imho not a good practice.