java防御xss攻击
.
关于xss的概念和解决方案网上很多,可以参考这个:
http://www.cnblogs.com/TankXiao/archive/2012/03/21/2337194.html#xsshappen
这里说下最近项目中我们的解决方案,主要用到commons-lang3-3.1.jar这个包的org.apache.commons.lang3.StringEscapeUtils.escapeHtml4()这个方法。
解决过程主要在用户输入和显示输出两步:在输入时对特殊字符如<>"'&转义,在输出时用jstl的fn:excapeXml("fff")方法。
其中,输入时的过滤是用一个filter来实现,
实现过程:
在web.xml加一个filter
<filter>
<filter-name>XssEscape</filter-name>
<filter-class>cn.pconline.morden.filter.XssFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>XssEscape</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
packagecn.pconline.morden.filter;
importjava.io.IOException;
importjavax.servlet.Filter;
importjavax.servlet.FilterChain;
importjavax.servlet.FilterConfig;
importjavax.servlet.ServletException;
importjavax.servlet.ServletRequest;
importjavax.servlet.ServletResponse;
importjavax.servlet.http.HttpServletRequest;
publicclassXssFilterimplementsFilter{
@Override
publicvoidinit(FilterConfigfilterConfig)throwsServletException{
}
@Override
publicvoiddoFilter(ServletRequestrequest,ServletResponseresponse,
FilterChainchain)throwsIOException,ServletException{
chain.doFilter(newXssHttpServletRequestWrapper((HttpServletRequest)request),response);
}
@Override
publicvoiddestroy(){
}
}
packagecn.pconline.morden.filter;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletRequestWrapper;
importorg.apache.commons.lang3.StringEscapeUtils;
publicclassXssHttpServletRequestWrapperextendsHttpServletRequestWrapper{
publicXssHttpServletRequestWrapper(HttpServletRequestrequest){
super(request);
}
@Override
publicStringgetHeader(Stringname){
returnStringEscapeUtils.escapeHtml4(super.getHeader(name));
}
@Override
publicStringgetQueryString(){
returnStringEscapeUtils.escapeHtml4(super.getQueryString());
}
@Override
publicStringgetParameter(Stringname){
returnStringEscapeUtils.escapeHtml4(super.getParameter(name));
}
@Override
publicString[]getParameterValues(Stringname){
String[]values=super.getParameterValues(name);
if(values!=null){
intlength=values.length;
String[]escapseValues=newString[length];
for(inti=0;i<length;i++){
escapseValues[i]=StringEscapeUtils.escapeHtml4(values[i]);
}
returnescapseValues;
}
returnsuper.getParameterValues(name);
}
}