Modify Request Parameter with Servlet Filter
In an existing web application, you're facing an XSS vulnerability and are prohibited from modifying the source code. To address this issue, you intend to utilize a servlet filter to sanitize request parameters before they reach the vulnerable page.
The provided code sample demonstrates your filter class, XssFilter:
import java.io.*;
import javax.servlet.*;
public final class XssFilter implements Filter {
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException
{
String badValue = request.getParameter("dangerousParamName");
String goodValue = sanitize(badValue);
// Unable to modify parameter using request.setParameter
chain.doFilter(request, response);
}
public void destroy() {
}
public void init(FilterConfig filterConfig) {
}
}
However, you've encountered an obstacle: HttpServletRequest lacks the setParameter method. To overcome this limitation, consider the following approaches:
Using HttpServletRequestWrapper:
Utilize the HttpServletRequestWrapper class to create a wrapper around the original request. You can override the getParameter method to return the sanitized value. Then, pass the wrapped request to chain.doFilter instead of the original.
This approach requires subclassing and wraps the original request, but complies with the servlet API by delegating the filtering to the wrapped request.
Setting Request Attribute:
Alternatively, you can modify the target servlet or JSP to expect a request attribute rather than a request parameter for the dangerous parameter. Your filter can then examine the parameter, sanitize it, and set the request attribute with the sanitized value using request.setAttribute.
This method is more elegant as it avoids subclassing or spoofing, but requires modifications to the application's code to use the request attribute instead of the parameter.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3