1. 程式人生 > >防止常見XSS 過濾 SQL注入 JAVA過濾器filter

防止常見XSS 過濾 SQL注入 JAVA過濾器filter

XSS : 跨站指令碼攻擊(Cross Site Scripting),為不和層疊樣式表(Cascading Style Sheets, CSS)的縮寫混淆,故將跨站指令碼攻擊縮寫為XSS。惡意攻擊者往Web頁面裡插入惡意html程式碼,當用戶瀏覽該頁之時,嵌入其中Web裡面的html程式碼會被執行,從而達到惡意攻擊使用者的特殊目的。

sql注入
所謂SQL注入,就是通過把SQL命令插入到Web表單提交或輸入域名或頁面請求的查詢字串,最終達到欺騙伺服器執行惡意的SQL命令。具體來說,它是利用現有應用程式,將(惡意)的SQL命令注入到後臺資料庫引擎執行的能力,它可以通過在Web表單中輸入(惡意)SQL語句得到一個存在安全漏洞的網站上的資料庫,而不是按照設計者意圖去執行SQL語句。

1、首先配置web.xml,新增如下配置資訊:

<!-- 解決xss & sql漏洞 -->
<filter>
	<filter-name>xssAndSqlFilter</filter-name>
	<filter-class>com.cup.cms.web.framework.filter.XssAndSqlFilter</filter-class>
</filter>
<!-- 解決xss & sql漏洞 -->
<filter-mapping>
	<filter-name>xssAndSqlFilter</filter-name>
	<url-pattern>*</url-pattern>
</filter-mapping>
2、編寫過濾器
/**
 * 
 */
package com.cup.cms.web.framework.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;

/**
 * @Author hithedy
 * @Date 2016年2月2日
 * @Time 下午2:01:53
 */
public class XssAndSqlFilter implements Filter {

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		XssAndSqlHttpServletRequestWrapper xssRequest = new XssAndSqlHttpServletRequestWrapper((HttpServletRequest) request);
		chain.doFilter(xssRequest, response);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

}
3、包裝器
/**
 * 
 */
package com.cup.cms.web.framework.filter;

import java.util.regex.Pattern;

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

/**
 * @Author hithedy
 * @Date 2016年2月2日
 * @Time 下午2:03:19
 */
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("");
		}
		return value;
	}

}
能夠防止常見的XSS和SQL注入。