xss (跨站脚本攻击) 解决方案之 antisamy

问题原因:对网站用户提交的数据(请求数据)未做处理。

XXS原理分析参考:http://netsecurity.51cto.com/art/201408/448305_all.htm:点击打开链接


解决方案:引入开源antisamy框架

解决过程:

1.导入依赖

maven依赖:

<dependencies>

    <dependency>

    <groupId>org.owasp.antisamygroupId>

    <artifactId>antisamyartifactId>

    <version>1.5.3version>

    dependency>

  dependencies>


xss (跨站脚本攻击) 解决方案之 antisamy_第1张图片

或者直接下载相关jar包。

2.自定义过滤器,对指定请求进行过滤,在web.xml中添加

xss (跨站脚本攻击) 解决方案之 antisamy_第2张图片


package com.shopping.rsnet.filter;


import java.io.IOException;


import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;


import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class XssFilter implements Filter {  
@SuppressWarnings("unused")  
private FilterConfig filterConfig; 
private String excludedUris;       
private String[] excludedUriArr; 
private Logger logger;


public XssFilter(){
/**日志*/
logger = LoggerFactory.getLogger(XssFilter.class);
}
/**
* Title: doFilter
* Description:执行过滤
* author:gelin
* create_date:2017-4-27
* update_date:
* @param request
* @param response
* @param chain
* @throws IOException
* @throws ServletException
*/
public void doFilter(ServletRequest request, ServletResponse response,  FilterChain chain) 
throws IOException, ServletException { 
boolean excludedUri=false;
String uri=((HttpServletRequest)request).getRequestURI();
String contextPath=((HttpServletRequest)request).getContextPath();
String mappingURL=uri.replaceAll(contextPath, "");
for(int i=0;i if(excludedUriArr[i].equals(mappingURL)){
excludedUri=true;
break;
}
}
if(excludedUri){
chain.doFilter(request,response);
}else{
if(logger.isDebugEnabled()){
logger.debug("过滤请求:"+mappingURL);
}
chain.doFilter(new XssRequestWrapper((HttpServletRequest) request), response);  
}
}
/**
* Title: init
* Description:初始化
* author:gelin
* create_date:2017-4-27
* update_date:
* @param filterConfig
* @throws ServletException
*/
public void init(FilterConfig filterConfig) throws ServletException {  
   this.filterConfig = filterConfig;  
   excludedUris=filterConfig.getInitParameter("excludedUris");
   if(StringUtils.isNotEmpty(excludedUris)){
    excludedUriArr=excludedUris.split(",");
   }
   
}     
public void destroy() {  
   this.filterConfig = null;  


}



package com.shopping.rsnet.filter;


import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Iterator;
import java.util.Map;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;


import org.apache.commons.lang.StringEscapeUtils;
import org.owasp.validator.html.AntiSamy;
import org.owasp.validator.html.CleanResults;
import org.owasp.validator.html.Policy;
import org.owasp.validator.html.PolicyException;
import org.owasp.validator.html.ScanException;


/**
 * Description: XXS防范
 * author:gelingqin
 * version:1.0
 * CreateDateTime: 2017-4-26下午5:04:39
 * UpdateTime:
 * see:
 */
public class XssRequestWrapper extends HttpServletRequestWrapper {  
    
  private static Policy policy = null;  
    
  static{  
      //String path = URLUtility.getClassPath(XssRequestWrapper.class)+File.separator+"antisamy-anythinggoes-1.4.4.xml";  
      //antisamy-anythinggoes-1.4.4.xml
 
 /**策略文件根据安全级别选择
  * 参考:http://blog.csdn.net/softwave/article/details/53761796
  *antisamy-slashdot.xml 
  *antisamy-ebay.xml
  *antisamy-myspace.xml
  *antisamy-anythinggoes.xml
  */
 String path =XssRequestWrapper.class.getClassLoader().getResource("antisamy-anythinggoes-1.4.4.xml").getFile();   
      if(path.startsWith("file")){  
          path = path.substring(6);  
      }  
      try {  
          policy = Policy.getInstance(path);  
      } catch (PolicyException e) {  
          e.printStackTrace();  
      }  
  }  


  public XssRequestWrapper(HttpServletRequest request) {  
      super(request);  
  }  
    
  @SuppressWarnings("rawtypes") 
  @Override
  public Map getParameterMap(){  
      Map request_map = super.getParameterMap();  
      Iterator iterator = request_map.entrySet().iterator();   
      while(iterator.hasNext()){  
          Map.Entry me = (Map.Entry)iterator.next();  
          String[] values = (String[])me.getValue();  
          for(int i = 0 ; i < values.length ; i++){   
              values[i] = xssClean(values[i]);  
          }  
      }  
      return request_map;  
  }  
   @Override
   public String[] getParameterValues(String paramString)  {  
      String[] arrayOfString1 = super.getParameterValues(paramString);  
      if (arrayOfString1 == null)  
        return null;  
      int i = arrayOfString1.length;  
      String[] arrayOfString2 = new String[i];  
      for (int j = 0; j < i; j++)  
        arrayOfString2[j] = xssClean(arrayOfString1[j]);  
      return arrayOfString2;  
    }  
    @Override
    public String getParameter(String paramString)  {  
      String str = super.getParameter(paramString);  
      if (str == null)  
        return null;  
      return xssClean(str);  
    }  
    @Override
    public String getHeader(String paramString)  {  
      String str = super.getHeader(paramString);  
      if (str == null)  
        return null;  
      return xssClean(str);  
    } 
    @Override
    public String getQueryString() {
    String str =super.getQueryString();
    if (str == null)  
            return null;  
        return xssClean(str);  
}
      
      
  private String xssClean(String value) {  
      AntiSamy antiSamy = new AntiSamy();  
      try {
     //按utf-8解碼:防止有害脚本 例如1" οnmοuseοver=s5mn(9186) bad=" encode %31%22%20%6F%6E%6D%6F%75%73%65%6F%76%65%72%3D%73%35%6D%6E%28%39%31%38%36%29%20%62%61%64%3D%22 骗过通行
     try {
value=URLDecoder.decode(value, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
          final CleanResults cr = antiSamy.scan(value, policy);  
          //安全的HTML输出  
          String str=cr.getCleanHTML(); 
          //不能反转义,反转义后就没效果了,转义的作用就是使脚本不被执行。
          //str=StringEscapeUtils.unescapeHtml(str);
          //链接不转义,否则无法调转
          str=str.replaceAll("&", "&");
          return  str; 
      } catch (ScanException e) {  
          e.printStackTrace();  
      } catch (PolicyException e) {  
          e.printStackTrace();  
      }  
      return value;  
  }  
}  

策略文件需要下载:

antisamy-anythinggoes-1.4.4.xml




你可能感兴趣的:(java)