標籤:
在前面的一篇文章中,講到了java web應用程式防止 csrf 攻擊的方法,參考這裡 java網頁程式採用 spring 防止 csrf 攻擊. ,但這隻是攻擊的一種方式,還有其他方式,比如今天要記錄的 XSS 攻擊, XSS 攻擊的專業解釋,可以在網上搜尋一下,參考百度百科的解釋 http://baike.baidu.com/view/2161269.htm, 但在實際的應用中如何去防止這種攻擊呢,下面給出幾種辦法.
1. 自己寫 filter 攔截來實現,但要注意的時,在WEB.XML 中配置 filter 的時候,請將這個 filter 放在第一位.
2. 採用開源的實現 ESAPI library ,參考網址: https://www.owasp.org/index.php/Category:OWASP_Enterprise_Security_API
3. 可以採用spring 裡面提供的工具類來實現.
一, 第一種方法。
配置過濾器
public class XSSFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void destroy() { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { chain.doFilter(new XSSRequestWrapper((HttpServletRequest) request), response); }}
再實現 ServletRequest 的封裝類
import java.util.regex.Pattern;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletRequestWrapper;public class XSSRequestWrapper extends HttpServletRequestWrapper { public XSSRequestWrapper(HttpServletRequest servletRequest) { super(servletRequest); } @Override public String[] getParameterValues(String parameter) { String[] values = super.getParameterValues(parameter); if (values == null) { return null; } int count = values.length; String[] encodedValues = new String[count]; for (int i = 0; i < count; i++) { encodedValues[i] = stripXSS(values[i]); } return encodedValues; } @Override public String getParameter(String parameter) { String value = super.getParameter(parameter); return stripXSS(value); } @Override public String getHeader(String name) { String value = super.getHeader(name); return stripXSS(value); } private String stripXSS(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("<script>(.*?)</script>", 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(""); 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("</script>", Pattern.CASE_INSENSITIVE); value = scriptPattern.matcher(value).replaceAll(""); // Remove any lonesome <script ...> tag scriptPattern = Pattern.compile("<script(.*?)>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); value = scriptPattern.matcher(value).replaceAll(""); // Avoid eval(...) e-xpressions scriptPattern = Pattern.compile("eval\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); value = scriptPattern.matcher(value).replaceAll(""); // Avoid e-xpression(...) e-xpressions scriptPattern = Pattern.compile("e-xpression\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); value = scriptPattern.matcher(value).replaceAll(""); // Avoid javascript:... e-xpressions scriptPattern = Pattern.compile("javascript:", Pattern.CASE_INSENSITIVE); value = scriptPattern.matcher(value).replaceAll(""); // Avoid vbscript:... e-xpressions scriptPattern = Pattern.compile("vbscript:", Pattern.CASE_INSENSITIVE); value = scriptPattern.matcher(value).replaceAll(""); // Avoid onload= e-xpressions scriptPattern = Pattern.compile("onload(.*?)=", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); value = scriptPattern.matcher(value).replaceAll(""); } return value; }}
例子中注釋的部分,就是採用 ESAPI library 來防止XSS攻擊的,推薦使用.
當然,我還看到這樣一種辦法,將所有的編程全形字元的解決方式,但個人覺得並沒有上面這種用Regex替換的好
private static String xssEncode(String s) { if (s == null || s.equals("")) { return 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(‘\\‘); sb.append(‘\‘‘); sb.append(‘\\‘); sb.append(‘\‘‘); break; case ‘\"‘: sb.append(‘\\‘); 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(); }
當然,還有如下更簡單的方式:
private String cleanXSS(String value) { //You‘ll need to remove the spaces from the html entities below value = value.replaceAll("<", "& lt;").replaceAll(">", "& gt;"); value = value.replaceAll("\\(", "& #40;").replaceAll("\\)", "& #41;"); value = value.replaceAll("‘", "& #39;"); value = value.replaceAll("eval\\((.*)\\)", ""); value = value.replaceAll("[\\\"\\\‘][\\s]*javascript:(.*)[\\\"\\\‘]", "\"\""); value = value.replaceAll("script", ""); return value; }
在後台或者用spring 如何?呢:
首先添加一個jar包:commons-lang-2.5.jar ,然後在後台調用這些函數:
StringEscapeUtils.escapeHtml(string); StringEscapeUtils.escapeJavaScript(string); StringEscapeUtils.escapeSql(string);
當然,我記得在spring 裡面好像有一個 HtmlUtils.htmlEscape , 同樣可以做到 過濾 XSS 攻擊。從上面的介紹可以看出,防止 XSS 攻擊並不難,就是要小心。
java 防止 XSS 攻擊的常用方法總結