Skip to content

Instantly share code, notes, and snippets.

@valotas
Created September 11, 2011 11:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save valotas/1209461 to your computer and use it in GitHub Desktop.
Save valotas/1209461 to your computer and use it in GitHub Desktop.
Decorator pattern with HttpServerRequest
public class HttpServletRequestDecoratorFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
//do nothing
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
request = decorate(request);
chain.doFilter(request, response);
}
private ServletRequest decorate(ServletRequest request) {
try {
HttpServletRequest req = (HttpServletRequest) request;
return new XFFAwareReq(req);
}
catch (ClassCastException e) {
// As we are not able to cast the request to an Http one, we just return the same object
return request;
}
}
@Override
public void destroy() {
// Do nothing
}
}
public class XFFAwareReq extends HttpServletRequestWrapper {
public XFFAwareReq(HttpServletRequest request) {
super(request);
}
@Override
public String getRemoteAddr() {
String xff = getXForwardedFor();
return xff != null ? xff : super.getRemoteAddr();
}
public String getXForwardedFor() {
String xff = getHeader("X-Forwarded-For");
if (xff == null || "".equals(xff)) return null;
return getIpFromXFF(xff);
}
protected static final String getIpFromXFF(String xff) {
//extract and return the ip from the X-Forwarded-For header
}
}
public class XSSAwareReq extends HttpServletRequestWrapper {
protected XSSAwareReq(HttpServletRequest req) {
super(req);
}
@Override
public String getParameter(String name) {
return super.getParameter(name)
.replaceAll("<", "&lt;")
.replaceAll(">", "&gt;")
.replaceAll("\\(", "&#40;")
.replaceAll("\\)", "&#41;")
.replaceAll("'", "&#39;")
.replaceAll("eval\\((.*)\\)", "")
.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\"")
.replaceAll("script", "");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment