360[警告]跨站腳本攻擊漏洞/java web利用Filter防止XSS/Spring MVC防止XSS攻擊

就以這張圖片做爲開篇和問題引入吧javascript

     <options>問題解決辦法請參考上一篇php

  如何獲取360站長邀請碼,360網站安全站長邀請碼html

     首先360可以提供一個這樣平臺去檢測仍是不錯的。可是當體檢出來 看到漏洞報告,覺得360會像windows上360安全衛士同樣幫咱們打好補丁。可是實際發現漏洞是要本身修復,而且php和asp aspx有360提供的補丁或者解決方案(想要看這些方案以前要申請爲站長可是須要邀請碼 這個能夠在頁面 頁面左下角 360主機衛士感恩卡里面領取)。java

   進入修復方案後發現java幾乎沒有提供一些建議,只能本身處理。開始使用搜索引擎搜索 java防止xss攻擊代碼。linux

http://www.yihaomen.com/article/java/409.htmweb

查到了這個方案spring

. 能夠採用spring 裏面提供的工具類來實現.

   一, 第一種方法。shell

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 的包裝類windows

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='...' 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;
    }
}

還須要到web.xml裏面配置安全

<filter>
    <filter-name>XSSFilter</filter-name>
    <filter-class>com.shanheyongmu.XSSFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>XSSFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

放上去以後 出現了 Java.lang.UnsupportedClassVersionError仍是classnotfound 項目跑起來就是首頁404。 而後考慮了下linux環境是jdk 1.6而編譯的都是maven3.3.0之後版本以及使用的jdk 1.7 版本問題(版本切換步驟能夠參考【maven學習總結】裏面的execption ,版本以前工做中遇到過因此有印象) 從新換jdk和eclipse設置jdk都是1.6以後編譯。不報錯了shell上,可是用360快速檢測我已修復,仍是存在漏洞。因而繼續百度

http://www.what21.com/programming/java/javaweb-summary/xss3.html 發現了不一樣的XssFilter寫法,嘗試以後仍是失敗。

https://my.oschina.net/wanglu/blog/267069   Springmvc安全  ,嘗試以後失敗,固然有些人視圖解析器不一樣 無加spring 的form標籤 沒法嘗試。

http://www.cnblogs.com/Mainz/archive/2012/11/01/2749874.html  來到了本篇 本篇有3種解決方法

第二種方法

web.xml加上:

       <context-param>
 <param-name>defaultHtmlEscape</param-name>
 <param-value>true</param-value>
 </context-param>

Forms加上:不少人對forms究竟是哪裏不理解你能夠 加在<form>標籤以前 或者body以前

<spring:htmlEscape defaultHtmlEscape="true" />
由於是線上項目因此沒法採用如下標籤 https://my.oschina.net/wanglu/blog/267069
也就是spring的標籤
<form:input path="someFormField" htmlEscape="true" />

可是<spring:htmlEscape defaultHtmlEscape="true" />在jsp視圖解析中仍是能夠的,而且這個添加方法 能夠不改變原有項目。

所有部署完成後,遺憾的是仍是體檢有原有漏洞。

 

從這篇獲得了答案 而且修復了 http://huangpengpeng.iteye.com/blog/2091798

 <!--@分隔 -->  
    <filter>  
        <filter-name>xssFilter</filter-name>  
        <filter-class>com.yoro.core.web.XssFilter</filter-class>  
        <init-param>  
            <param-name>SplitChar</param-name>  
            <param-value>@</param-value>  
        </init-param>  
        <init-param>  
            <param-name>FilterChar</param-name>  
            <param-value>>@&lt;@\'@\"@\\@#@(@)</param-value>  
        </init-param>  
        <init-param>  
            <param-name>ReplaceChar</param-name>  
            <param-value>>'@<@‘@「@\@#@(@)</param-value>  
        </init-param>  
    </filter>  
      
 <filter-mapping>  
    
        <filter-name>xssFilter</filter-name>  
          
  <url-pattern>/*</url-pattern>  
   
    </filter-mapping>  
package com.yoro.core.web;  
  
/** 
 * @author zoro 
 */  
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;  
  
public class XssFilter implements Filter {  
      
    private String filterChar;  
    private String replaceChar;  
    private String splitChar;  
    FilterConfig filterConfig = null;  
    public void init(FilterConfig filterConfig) throws ServletException {  
        this.filterChar=filterConfig.getInitParameter("FilterChar");  
        this.replaceChar=filterConfig.getInitParameter("ReplaceChar");  
        this.splitChar=filterConfig.getInitParameter("SplitChar");  
        this.filterConfig = filterConfig;  
    }  
  
    public void destroy() {  
        this.filterConfig = null;  
    }  
  
    public void doFilter(ServletRequest request, ServletResponse response,  
  
    FilterChain chain) throws IOException, ServletException {  
        chain.doFilter(new XssHttpServletRequestWrapper((HttpServletRequest) request,filterChar,replaceChar,splitChar), response);  
    }  
}  
package com.yoro.core.web;  
  
  
  
import java.io.UnsupportedEncodingException;  
import java.net.URLDecoder;  
  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletRequestWrapper;  
  
  
/** 
 * @author zoro 
 */  
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {  
    private String[]filterChars;  
    private String[]replaceChars;  
    public XssHttpServletRequestWrapper(HttpServletRequest request,String filterChar,String replaceChar,String splitChar) {  
        super(request);  
        if(filterChar!=null&&filterChar.length()>0){  
            filterChars=filterChar.split(splitChar);  
        }  
        if(replaceChar!=null&&replaceChar.length()>0){  
            replaceChars=replaceChar.split(splitChar);  
        }  
    }  
    public String getQueryString() {  
        String value = super.getQueryString();  
        if (value != null) {  
            value = xssEncode(value);  
        }  
        return value;  
    }  
      
    /** 
     * 覆蓋getParameter方法,將參數名和參數值都作xss過濾。<br/> 
     * 若是須要得到原始的值,則經過super.getParameterValues(name)來獲取<br/> 
     * getParameterNames,getParameterValues和getParameterMap也可能須要覆蓋 
     */  
    public String getParameter(String name) {  
        String value = super.getParameter(xssEncode(name));  
        if (value != null) {  
            value = xssEncode(value);  
        }  
        return value;  
    }  
      
    public String[] getParameterValues(String name) {  
        String[]parameters=super.getParameterValues(name);  
        if (parameters==null||parameters.length == 0) {  
            return null;  
        }  
        for (int i = 0; i < parameters.length; i++) {  
            parameters[i] = xssEncode(parameters[i]);  
        }  
        return parameters;  
    }  
      
    /** 
     * 覆蓋getHeader方法,將參數名和參數值都作xss過濾。<br/> 
     * 若是須要得到原始的值,則經過super.getHeaders(name)來獲取<br/> getHeaderNames 也可能須要覆蓋 
     */  
    public String getHeader(String name) {  
  
        String value = super.getHeader(xssEncode(name));  
        if (value != null) {  
            value = xssEncode(value);  
        }  
        return value;  
    }  
      
    /** 
     * 將容易引發xss漏洞的半角字符直接替換成全角字符 
     *  
     * @param s 
     * @return 
     */  
    private  String xssEncode(String s) {  
        if (s == null || s.equals("")) {  
            return s;  
        }  
        try {  
            s = URLDecoder.decode(s, "UTF-8");  
        } catch (UnsupportedEncodingException e) {  
            e.printStackTrace();  
        }  
        for (int i = 0; i < filterChars.length; i++) {  
            if(s.contains(filterChars[i])){  
                s=s.replace(filterChars[i], replaceChars[i]);  
            }  
        }  
        return s;  
    }  
}

因爲嘗試較多,也比較混亂,也不肯定哪一個適用各位的狀況,只能多查多參考。

此處再補充一個 其餘防止Xss攻擊代碼寫法 http://www.what21.com/programming/java/javaweb-summary/xss3.html。

 

後來搜索到了 http://www.cnblogs.com/wangdaijun/p/5652864.html Antisamy項目實現防XSS攻擊

遺憾的是配置文件很難找 我在csdn找到了antisamy.xml,你們能夠基於搜索關鍵字 Antisamy項目實現防XSS攻擊多查查 。

小弟技術菜,而且思惟通常,求大神勿噴,給予指導和共同交流進步仍是能夠的。

相關文章
相關標籤/搜索