Skip to content

Instantly share code, notes, and snippets.

@shautzin
Last active August 29, 2015 13:57
Show Gist options
  • Save shautzin/9541546 to your computer and use it in GitHub Desktop.
Save shautzin/9541546 to your computer and use it in GitHub Desktop.
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.Map;
/**
* Anti XSS RequestWraper
*
* <p>
*
* Usage: write {chain.doFilter(new XssHttpServletRequestWrapper((HttpServletRequest) request), response);}
* in a named XssFilter and config it, then it works.
*
* Created by ShaoJin on 14-3-14.
*/
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
public XssHttpServletRequestWrapper(HttpServletRequest request) {
super(request);
}
@Override
public String[] getParameterValues(String name) {
String[] values = super.getParameterValues(name);
if (values != null) {
String[] newValues = new String[values.length];
for (int i = 0; i < values.length; i++) {
newValues[i] = strip(values[i]);
}
return newValues;
} else {
return null;
}
}
@Override
public Map getParameterMap() {
return super.getParameterMap();
}
@Override
public String getParameter(String name) {
String value = super.getParameter(name);
return strip(value);
}
@Override
public String getHeader(String name) {
String header = super.getHeader(name);
return strip(header);
}
/**
* do replace
*
* @param value
* @return
*/
private String strip(String value) {
if (value != null) {
value = value.replaceAll("<", "&lt;").replaceAll(">", "&gt;");
value = value.replaceAll("\\(", "&#40;").replaceAll("\\)", "&#41;");
value = value.replaceAll("'", "&#39;").replaceAll("\"", "&#34;");
value = value.replaceAll("eval\\((.*)\\)", "");
value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\"");
value = value.replaceAll("script", "");
return value;
} else {
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment