JSP写过滤器避免xss攻击的方法:
利用Servlet的过滤器机制,编写定制的XssFilter,将request要求代理,覆盖getParameter和getHeader方法将参数名和参数值里的指定半角字符,强迫替换玉成角字符,代码以下:
XssFilter.java
packagefilter;
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{
publicvoidinit(FilterConfigconfig)throwsServletException{
}
publicvoiddoFilter(ServletRequestrequest,ServletResponseresponse,
FilterChainchain)throwsIOException,ServletException
{
XssHttpServletRequestWrapperxssRequest=newXssHttpServletRequestWrapper(
(HttpServletRequest)request);
chain.doFilter(xssRequest,response);
}
publicvoiddestroy(){
}
}
XssHttpServletRequestWrapper.java
packagefilter;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletRequestWrapper;
publicclassXssHttpServletRequestWrapperextendsHttpServletRequestWrapper{
HttpServletRequestorgRequest=null;
publicXssHttpServletRequestWrapper(HttpServletRequestrequest){
super(request);
orgRequest=request;
}
/**
*覆盖getParameter方法,将参数名和参数值都做xss过滤。<br/>
*如果需要取得原始的值,则通过super.getParameterValues(name)来获得<br/>
*getParameterNames,getParameterValues和getParameterMap也可能需要覆盖
*/
@Override
publicStringgetParameter(Stringname){
Stringvalue=super.getParameter(xssEncode(name));
if(value!=null){
value=xssEncode(value);
}
returnvalue;
}
/**
*覆盖getHeader方法,将参数名和参数值都做xss过滤。<br/>
*如果需要取得原始的值,则通过super.getHeaders(name)来获得<br/>
*getHeaderNames也可能需要覆盖
*/
@Override
publicStringgetHeader(Stringname){
Stringvalue=super.getHeader(xssEncode(name));
if(value!=null){
value=xssEncode(value);
}
returnvalue;
}
/**
*将容易引发xss漏洞的半角字符直代替换玉成角字符
*
*@params
*@return
*/
privatestaticStringxssEncode(Strings){
if(s==null||s.isEmpty()){
returns;
}
StringBuildersb=newStringBuilder(s.length()+16);
for(inti=0;i<s.length();i++){
charc=s.charAt(i);
switch(c){
case'>':
sb.append('>');//全角大于号
break;
case'<':
sb.append('<');//全角小于号
break;
case'\'':
sb.append('‘');//全角单引号
break;
case'\"':
sb.append('“');//全角双引号
break;
case'&':
sb.append('&');//全角
break;
case'\\':
sb.append('\');//全角斜线
break;
case'#':
sb.append('#');//全角井号
break;
default:
sb.append(c);
break;
}
}
returnsb.toString();
}
/**
*获得最原始的request
*
*@return
*/
publicHttpServletRequestgetOrgRequest(){
returnorgRequest;
}
/**
*获得最原始的request的静态方法
*
*@return
*/
publicstaticHttpServletRequestgetOrgRequest(HttpServletRequestreq){
if(reqinstanceofXssHttpServletRequestWrapper){
return((XssHttpServletRequestWrapper)req).getOrgRequest();
}
returnreq;
}
}
</pre>
在web.xml中添加使用:
<filter>
<filter-name>xssFilter</filter-name>
<filter-class>filter.XssFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>xssFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
本文来源:https://www.yuntue.com/post/61732.html | 云服务器网,转载请注明出处!