XSS攻击,即Cross Site Script,跨脚本攻击,往web页面注入html代码或者script代码,造成页面混乱。
HttpServletRequestWrapper 是HttpServletRequest的装饰器。
大体流程:包装request->创建过滤器->添加过滤器
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import org.apache.commons.lang.StringUtils;
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
String method = null;
public DMTRequest(HttpServletRequest servletRequest) {
super(servletRequest);
}
public String[] getParameterValues(String parameter) {
String[] values = super.getParameterValues(parameter);
if(values == null) {
return null;
} else {
int count = values.length;
String[] encodedValues = new String[count];
for(int i = 0; i < count; ++i) {
encodedValues[i] = this.cleanXSS(values[i]);
}
return encodedValues;
}
}
public String getParameter(String parameter) {
String value = super.getParameter(parameter);
return value == null?null:this.cleanXSS(value);
}
public String getHeader(String name) {
String value = super.getHeader(name);
return value == null?null:this.cleanXSS(value);
}
private String cleanXSS(String value) {
if(StringUtils.isEmpty(value)) {
return "";
} else {
value = value.replaceAll("\"", "").replaceAll("\'", "").replaceAll("<", "").replaceAll(">", "");
value = value.replaceAll("eval\\((.*)\\)", "");
value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\"");
value = value.replaceAll("script", "");
return value;
}
}
}
public class XssFilter implements Filter {
FilterConfig filterConfig = null;
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
}
public void destroy() {
this.filterConfig = null;
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
chain.doFilter(new XssHttpServletRequestWrapper (
(HttpServletRequest) request), response);
}
}
在web.xml文件中将该过滤器放在最前面或者是字符编码过滤器之后:
filter>
<filter-name>xssFilter</filter-name>
<filter-class>xxx.xxx.filter.XssFilter</filter-class>
<init-param>
<param-name>exclude</param-name>
<param-value>/;/scripts/*;/styles/*;/images/*</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>xssFilter</filter-name>
<url-pattern>*.html</url-pattern>
<!-- 直接从客户端过来的请求以及通过forward过来的请求都要经过该过滤器 -->
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>