1. 程式人生 > >配置攔截器防xss和sql注入

配置攔截器防xss和sql注入

1. web.xml配置攔截器

自定義一個實現了Filter介面的類XssAndSqlFilter。這個類用來實現具體的引數替換邏輯。

<!-- 防XSS和sql注入漏洞       開始  -->
    <filter>  
        <filter-name>xssAndSqlFilter</filter-name>  
        <filter-class>com.lancy.web.filter.XssAndSqlFilter</filter-class>  
    </filter>  
    <filter-mapping
>
<filter-name>xssAndSqlFilter</filter-name> <url-pattern>*</url-pattern> </filter-mapping> <!-- 防XSS和sql注入漏洞 結束-->

2. 編寫自定義攔截器類,實現Filter介面

package com.lancy.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import
javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import com.lancy.web.request.XssAndSqlHttpServletRequestWrapper; /** * @Title: XssAndSqlFilter.java * @Description
: 防XSS和sql注入漏洞 filter * @date 2017年9月7日 下午6:59:23 * @version V1.0 */
public class XssAndSqlFilter implements Filter { @Override public void destroy() { // TODO Auto-generated method stub } @Override public void init(FilterConfig arg0) throws ServletException { // TODO Auto-generated method stub } @Override public void doFilter(ServletRequest request, ServletResponse response, javax.servlet.FilterChain chain) throws IOException, ServletException { //此類繼承了HttpServletRequestWrapper,可以對請求引數進行過濾 XssAndSqlHttpServletRequestWrapper xssRequest = new XssAndSqlHttpServletRequestWrapper((HttpServletRequest) request); chain.doFilter(xssRequest, response); } }

3. 繼承HttpServletRequestWrapper,實現請求引數的過濾

這一步是最主要的,是業務邏輯的主要實現部分,封裝了HttpServletRequest請求,是裝飾模式。

package com.lancy.web.request;

import java.util.regex.Pattern;  

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

/**  
 * @Title: XssAndSqlHttpServletRequestWrapper.java
 * @Description: TODO
 * @version V1.0  
 */
public class XssAndSqlHttpServletRequestWrapper extends HttpServletRequestWrapper {  

  HttpServletRequest orgRequest = null;  

  public XssAndSqlHttpServletRequestWrapper(HttpServletRequest request) {  
      super(request);  
      orgRequest = request;  
  }  

  /** 
   * 覆蓋getParameter方法,將引數名和引數值都做xss & sql過濾。<br/> 
   * 如果需要獲得原始的值,則通過super.getParameterValues(name)來獲取<br/> 
   * getParameterNames,getParameterValues和getParameterMap也可能需要覆蓋 
   */  
  @Override  
  public String getParameter(String name) {  
      String value = super.getParameter(xssEncode(name));  
      if (value != null) {  
          value = xssEncode(value);  
      }  
      return value;  
  }  

  /** 
   * 覆蓋getHeader方法,將引數名和引數值都做xss & sql過濾。<br/> 
   * 如果需要獲得原始的值,則通過super.getHeaders(name)來獲取<br/> 
   * getHeaderNames 也可能需要覆蓋 
   */  
  @Override  
  public String getHeader(String name) {  

      String value = super.getHeader(xssEncode(name));  
      if (value != null) {  
          value = xssEncode(value);  
      }  
      return value;  
  }  

  /** 
   * 將容易引起xss & sql漏洞的半形字元直接替換成全形字元 
   *  
   * @param s 
   * @return 
   */  
  private static String xssEncode(String s) {  
      if (s == null || s.isEmpty()) {  
          return s;  
      }else{  
          s = stripXSSAndSql(s);  
      }  
      StringBuilder sb = new StringBuilder(s.length() + 16);  
      for (int i = 0; i < s.length(); i++) {  
          char c = 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;  
          default:  
              sb.append(c);  
              break;  
          }  
      }  
      return sb.toString();  
  }  

  /** 
   * 獲取最原始的request 
   *  
   * @return 
   */  
  public HttpServletRequest getOrgRequest() {  
      return orgRequest;  
  }  

  /** 
   * 獲取最原始的request的靜態方法 
   *  
   * @return 
   */  
  public static HttpServletRequest getOrgRequest(HttpServletRequest req) {  
      if (req instanceof XssAndSqlHttpServletRequestWrapper) {  
          return ((XssAndSqlHttpServletRequestWrapper) req).getOrgRequest();  
      }  

      return req;  
  }  

  /** 
   *  
   * 防止xss跨指令碼攻擊(替換,根據實際情況調整) 
   */  

  public static String stripXSSAndSql(String value) {  
      if (value != null) {  
          // NOTE: It's highly recommended to use the ESAPI library and  
          // uncomment the following line to  
          // avoid encoded attacks.  
          // value = ESAPI.encoder().canonicalize(value);  
          // Avoid null characters  
/**         value = value.replaceAll("", "");***/  
          // Avoid anything between script tags  
          Pattern scriptPattern = Pattern.compile("<[\r\n| | ]*script[\r\n| | ]*>(.*?)</[\r\n| | ]*script[\r\n| | ]*>", Pattern.CASE_INSENSITIVE);  
          value = scriptPattern.matcher(value).replaceAll("");  
          // Avoid anything in a src="http://www.yihaomen.com/article/java/..." type of e-xpression  
          scriptPattern = Pattern.compile("src[\r\n| | ]*=[\r\n| | ]*[\\\"|\\\'](.*?)[\\\"|\\\']", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);  
          value = scriptPattern.matcher(value).replaceAll("");  
          // Remove any lonesome </script> tag  
          scriptPattern = Pattern.compile("</[\r\n| | ]*script[\r\n| | ]*>", Pattern.CASE_INSENSITIVE);  
          value = scriptPattern.matcher(value).replaceAll("");  
          // Remove any lonesome <script ...> tag  
          scriptPattern = Pattern.compile("<[\r\n| | ]*script(.*?)>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);  
          value = scriptPattern.matcher(value).replaceAll("");  
          // Avoid eval(...) expressions  
          scriptPattern = Pattern.compile("eval\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);  
          value = scriptPattern.matcher(value).replaceAll("");  
          // Avoid e-xpression(...) expressions  
          scriptPattern = Pattern.compile("e-xpression\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);  
          value = scriptPattern.matcher(value).replaceAll("");  
          // Avoid javascript:... expressions  
          scriptPattern = Pattern.compile("javascript[\r\n| | ]*:[\r\n| | ]*", Pattern.CASE_INSENSITIVE);  
          value = scriptPattern.matcher(value).replaceAll("");  
          // Avoid vbscript:... expressions  
          scriptPattern = Pattern.compile("vbscript[\r\n| | ]*:[\r\n| | ]*", Pattern.CASE_INSENSITIVE);  
          value = scriptPattern.matcher(value).replaceAll("");  
          // Avoid onload= expressions  
          scriptPattern = Pattern.compile("onload(.*?)=", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);  
          value = scriptPattern.matcher(value).replaceAll(""); 
          value = value.trim();
      }  
      return value;  
  }  

}