成人国产在线小视频_日韩寡妇人妻调教在线播放_色成人www永久在线观看_2018国产精品久久_亚洲欧美高清在线30p_亚洲少妇综合一区_黄色在线播放国产_亚洲另类技巧小说校园_国产主播xx日韩_a级毛片在线免费

資訊專欄INFORMATION COLUMN

一次詭異的關(guān)于filter的問(wèn)題

BlackHole1 / 1122人閱讀

摘要:接收前臺(tái)請(qǐng)求封裝的時(shí),莫名傳到后臺(tái)就變成了。找了半天,一直以后是前臺(tái)的問(wèn)題,一直在翻閱各種代碼。后來(lái),請(qǐng)教大佬,大佬一聽到剛好少了后,靈光乍現(xiàn),感覺(jué)是攔截器的原因,后來(lái)查閱,果不其然。全稱跨站腳本攻擊,是程序中最常見的漏洞。

接收前臺(tái)post請(qǐng)求封裝的"versionDescription":"eeeeee",時(shí),莫名傳到后臺(tái)就變成"versionDeion":"eeeeee",了。

找了半天,一直以后是前臺(tái)的問(wèn)題,一直在翻閱各種js代碼。 后來(lái),請(qǐng)教大佬,大佬一聽到剛好少了script后,靈光乍現(xiàn),感覺(jué)是攔截器的原因,后來(lái)查閱,果不其然。

XSS 全稱(Cross Site Scripting) 跨站腳本攻擊, 是Web程序中最常見的漏洞。指攻擊者在網(wǎng)頁(yè)中嵌入客戶端腳本(例如JavaScript), 當(dāng)用戶瀏覽此網(wǎng)頁(yè)時(shí),腳本就會(huì)在用戶的瀏覽器上執(zhí)行,從而達(dá)到攻擊者的目的. 比如獲取用戶的Cookie,導(dǎo)航到惡意網(wǎng)站,攜帶木馬等

參考https://www.cnblogs.com/xuxiu...

參考 http://www.cnblogs.com/jiangs...

參考 https://blog.csdn.net/qq_3292...

參考 https://blog.csdn.net/u012114...

這是一個(gè)預(yù)防XSS注入的攔截器,web.xml配置如下:

    
        xssFilter
        com.cashew.utils.XssFilter
    
    
        xssFilter
        /*
    

攔截器:

package com.sgcc.utils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

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.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;

public class XssFilter implements Filter {

    Logger log = Logger.getLogger(this.getClass());
    private static Pattern SCRIPT_PATTERN = Pattern
            .compile(".*");
    private static Pattern HTML_PATTERN = Pattern.compile("<[^>]+>");

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest,
            ServletResponse servletResponse, FilterChain chain)
            throws IOException, ServletException {
        // 獲得在下面代碼中要用的request,response,session對(duì)象
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 設(shè)置cookie heetOnly
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            Cookie cookie = cookies[0];
            if (cookie != null) {
                // Servlet 2.5不支持在Cookie上直接設(shè)置HttpOnly屬性
                String value = cookie.getValue();
                StringBuilder builder = new StringBuilder();
                builder.append("JSESSIONID=" + value + "; ");
                builder.append("Secure; ");
                builder.append("HttpOnly; ");
                Calendar cal = Calendar.getInstance();
                cal.add(Calendar.MINUTE, 30);
                Date date = cal.getTime();
                Locale locale = Locale.CHINA;
                SimpleDateFormat sdf = new SimpleDateFormat(
                        "dd-MM-yyyy HH:mm:ss", locale);
                builder.append("Expires=" + sdf.format(date));
                response.setHeader("Set-Cookie", builder.toString());
            }
        }
                
        String method = request.getMethod();  
        if("POST".equalsIgnoreCase(method)){ 
            if (getParameterMap(request)) {
                log.info("-----檢測(cè)到危險(xiǎn)字符,終止請(qǐng)求");
                response.setCharacterEncoding("UTF-8");
                response.getWriter().write(JSONObject.fromObject(getFailedMap("檢測(cè)到疑似注入操作,終止請(qǐng)求")).toString());
                return;
            }
        }else{
            boolean isScri = this.filterHtmlStr(request);
            boolean isSql = this.filterSql(request);
            if (!isScri || !isSql) {
                log.info("檢測(cè)到危險(xiǎn)字符,終止請(qǐng)求");
                response.setCharacterEncoding("UTF-8");
                response.getWriter().write(JSONObject.fromObject(getFailedMap("檢測(cè)到疑似注入操作,終止請(qǐng)求")).toString());
                return;
            }
        }
        
        //chain.doFilter(servletRequest, servletResponse);  
        chain.doFilter(new XSSRequestWrapper((HttpServletRequest) servletRequest), servletResponse);
    }

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

    }
    /**  
     * 方法說(shuō)明 :通過(guò)獲取map的方法
     */   
    @SuppressWarnings("rawtypes")  
    private boolean getParameterMap(HttpServletRequest request) {  
        Map map = request.getParameterMap();  
        boolean illegalStr = false;  
        if (map != null) {  
            Set set = map.entrySet();  
            Iterator iterator = set.iterator();  
            while (iterator.hasNext()) {  
                Map.Entry entry = (Entry) iterator.next();  
                if (entry.getValue() instanceof String[]) {  
                    //System.out.println("==A==entry的key?? " + entry.getKey());  
                    String[] values = (String[]) entry.getValue();  
                   for (int i = 0; i < values.length; i++) {  
                       if(!entry.getKey().toString().equals("buildJsonSettings")){
                           if(!filterSqlFromSream(values[i]) || !filterHtmlStr(values[i])){
                               System.out.println("1====非法字符 key=" +entry.getKey().toString() + ";value=" + values[i]);  
                               illegalStr = true;
                               break;
                           } 
                       }
                    }
                } else if (entry.getValue() instanceof String) {  
                    if(!filterSqlFromSream(entry.getValue().toString()) || !filterHtmlStr(entry.getValue().toString())){
                         System.out.println("2====非法字符 key=" +entry.getKey().toString() + ";value=" + entry.getValue().toString());  
                         illegalStr = true;
                         break;
                     } 
                }  
            }  
        }  
        return illegalStr;  
} 
    public boolean filterHtmlStr(String inputStr) {

        Matcher mHtml = HTML_PATTERN.matcher(inputStr);
        if (mHtml.find()) {
            log.info("1------------------------Html str:" + inputStr);
            return false;
        }
        Matcher m = SCRIPT_PATTERN.matcher(inputStr);
        if (m.find()) {
            log.info("1------------------------js str:" + inputStr);
            return false;
        }
        return true;

    }

    public boolean filterHtmlStr(HttpServletRequest request) {

        Map paramMap = request.getParameterMap();
        String lowStr = null;
        Set> keSet = paramMap.entrySet();
        for (Iterator> itr = keSet.iterator(); itr
                .hasNext();) {
            @SuppressWarnings("rawtypes")
            Map.Entry me = (Map.Entry) itr.next();
            Object ov = me.getValue();
            String[] value = new String[1];
            if (ov instanceof String[]) {
                value = (String[]) ov;
            } else {
                value[0] = ov.toString();
            }
            for (int k = 0; k < value.length; k++) {
                lowStr = value[k];
                Matcher mHtml = HTML_PATTERN.matcher(lowStr);
                if (mHtml.find()) {
                    log.info("2------------------------Html str:" + lowStr);
                    return false;
                }
                Matcher m = SCRIPT_PATTERN.matcher(lowStr);
                if (m.find()) {
                    log.info("2------------------------js str:" + lowStr);
                    return false;
                }
            }
        }
        return true;

    }

    public boolean filterSql(HttpServletRequest request) {
        Enumeration params = request.getParameterNames();
        String sql = "";
        String name = "";
        while (params.hasMoreElements()) {
            name = params.nextElement().toString();
            log.info(String.format("name is [%s]", name));
            String[] value = request.getParameterValues(name);
            for (int i = 0; i < value.length; i++) {
                sql += value[i] + " ";
            }
        }
        sql = sql.toLowerCase();

        String badStr = ""|and|exec|execute|insert|select|delete|update|count|drop|*|chr|mid|truncate|"
                + "char|declare|sitename|net user|xp_cmdshell|or|like"|and|exec|execute|insert|create|drop|"
                + "table|from|grant|use|group_concat|column_name|"
                + "information_schema.columns|table_schema|union|where|order|by|count|*|"
                + "chr|mid|truncate|char|declare|or|like";
        String[] badStrs = badStr.split("|");
        String[] param = sql.split(" ");
        for (int j = 0; j < param.length; j++)
            for (int i = 0; i < badStrs.length; i++) {
                if (param[j].equalsIgnoreCase(badStrs[i])) {
                    log.info(String.format("1------------查詢到SQL注入,輸入?yún)?shù):[%s]", sql));
                    return false;
                }
            }
        return true;
    }

    public boolean filterSqlFromSream(String inputJson) {
        String sql = "";
        try {
            sql = URLDecoder.decode(inputJson,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String badStr = ""|and|exec|execute|insert|select|delete|update|count|drop|*|chr|mid|truncate|"
                + "char|declare|sitename|net user|xp_cmdshell|or|like"|and|exec|execute|insert|create|drop|"
                + "table|from|grant|use|group_concat|column_name|"
                + "information_schema.columns|table_schema|union|where|order|by|count|*|"
                + "chr|mid|truncate|char|declare|or|like";
        String[] badStrs = badStr.split("|");
        String[] param = sql.split(" ");
        for (int j = 0; j < param.length; j++)
            for (int i = 0; i < badStrs.length; i++) {
                if (param[j].equalsIgnoreCase(badStrs[i])) {
                    log.info(String.format("2------------查詢到SQL注入,輸入?yún)?shù):[%s]", sql));
                    return false;
                }
            }
        return true;
    }

    
    public String checkSpecialWord(String str) {
        return Pattern
                .compile(
                        "[`~!@#$%^&*()+=|{}":;",[].<>/?~!@#??%…???&*()—???+|{}【??????;:????????????,、?]")
                .matcher(str).replaceAll("").trim();
    }

    private Map getFailedMap(String message) {
        Map ret = new HashMap();
        ret.put("status", "failed");
        ret.put("message", message);
        return ret;
    }

    class XSSRequestWrapper extends HttpServletRequestWrapper {

        public XSSRequestWrapper(HttpServletRequest request) {
            super(request);
        }

        public String getParameter(String name) {
            String value = super.getParameter(name);
            if (value != null) {
                value = cleanXSS(value);
            }

            return value;
        }

        public String[] getParameterValues(String name) {
            String[] values = super.getParameterValues(name);
            if (values != null) {
                for (int i = 0; i < values.length; i++) {
                    values[i] = cleanXSS(values[i]);
                }
            }

            return values;
        }

        private String cleanXSS(String value) {
            value = value.replaceAll("<", "<").replaceAll(">", ">");
            if(value.toLowerCase().contains("") ){
                value = value.substring(0,value.toLowerCase().indexOf("script"))+value.substring(value.toLowerCase().indexOf("script")+6);
            }
            return value;
        }
    }

    
}

文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請(qǐng)注明本文地址:http://systransis.cn/yun/72455.html

相關(guān)文章

  • 處理for-in用在數(shù)組上時(shí)候出現(xiàn)詭異現(xiàn)象問(wèn)題

    摘要:在第一次循環(huán)的時(shí)候的值為,此后依次為。所以就出現(xiàn)了上面的問(wèn)題。此外,在下打印的時(shí)候可能與在中打印出現(xiàn)不同的結(jié)果。尤其是是這種牽扯到數(shù)組下標(biāo)的盡量不要使用來(lái)處理,如果非要使用可以做如下處理以避免如上的問(wèn)題。 問(wèn)題復(fù)現(xiàn) var arr = [a, b, c]; var sid = [Go]; for (var key in arr) { sid[key + 1] = arr[key...

    huangjinnan 評(píng)論0 收藏0
  • 關(guān)于 Lumen 無(wú)輸出 HTTP 狀態(tài)碼為 500 詭異錯(cuò)誤

    摘要:關(guān)于無(wú)輸出錯(cuò)誤最近接入支付寶支付時(shí)遇到一個(gè)問(wèn)題,在做支付回調(diào)函數(shù)的時(shí)候我先是寫了一個(gè)用來(lái)記錄回調(diào)時(shí)的支付寶請(qǐng)求參數(shù),但發(fā)現(xiàn)無(wú)論如何日志都沒(méi)有任何記錄,而且回調(diào)函數(shù)里面的東西也沒(méi)用執(zhí)行,于是我自己請(qǐng)求該回調(diào)地址,發(fā)現(xiàn)服務(wù)器上狀態(tài)碼為但是沒(méi)有 關(guān)于LUMEN無(wú)輸出500錯(cuò)誤 最近接入支付寶支付時(shí)遇到一個(gè)問(wèn)題,在做支付回調(diào)函數(shù)的時(shí)候我先是寫了一個(gè) Log::info(alipay_notif...

    dayday_up 評(píng)論0 收藏0
  • 慎用ThreadLocal

    摘要:另載于是個(gè)很爽的東西,線程安全,能當(dāng)全局變量來(lái)用別。第一家公司,使用框架老技術(shù),現(xiàn)代人可以理解為類似,對(duì)每個(gè)請(qǐng)求都套上,進(jìn)入時(shí)把寫入,返回或拋?zhàn)⒁鈺r(shí)清理。第二家公司,某次引入一個(gè)設(shè)計(jì),也用了來(lái)傳遞上下文信息,有的地方?jīng)]能清掉。 另載于 http://www.qingjingjie.com/blogs/12 ThreadLocal是個(gè)很爽的東西,線程安全,能當(dāng)全局變量來(lái)用(別!)。 上一...

    harriszh 評(píng)論0 收藏0
  • PHP引用,你知道多少?

    摘要:最近面試他人的過(guò)程中,問(wèn)了一些關(guān)于引用的知識(shí),發(fā)現(xiàn)很多同學(xué)對(duì)這方面知之甚少,還有很多工作中基本沒(méi)有使用過(guò)。沒(méi)錢給大家發(fā)紅包,給大家推薦一家上海的好公司。對(duì)于上海的小伙伴或者想去上海的小伙伴,強(qiáng)烈建議去看看。 真的是變懶了,一個(gè)月一篇的節(jié)湊都很難保證了。 最近面試他人的過(guò)程中,問(wèn)了一些關(guān)于PHP引用的知識(shí),發(fā)現(xiàn)很多同學(xué)對(duì)這方面知之甚少,還有很多工作中基本沒(méi)有使用過(guò)。甚至有人告訴我要少用引...

    williamwen1986 評(píng)論0 收藏0
  • 淺析WSGI

    摘要:也就是說(shuō),是連接服務(wù)器和應(yīng)用服務(wù)器的橋梁。目前實(shí)現(xiàn)的中,有兩個(gè)角色分別是和。是一個(gè)可調(diào)用對(duì)象,它包含了一個(gè)表示響應(yīng)狀態(tài)的字符串和一個(gè)響應(yīng)的列表以及一個(gè)用于出錯(cuò)返回的信息,具體參數(shù)包含及詳情請(qǐng)點(diǎn)這里??梢员贿B接在一起,由此產(chǎn)生的鏈通常被稱為。 首先,什么是WSGI? WSGI, 全稱為 Web Server Gateway Interface。 它不是什么框架,它是一個(gè)規(guī)范,但是作為一個(gè)...

    王偉廷 評(píng)論0 收藏0

發(fā)表評(píng)論

0條評(píng)論

最新活動(dòng)
閱讀需要支付1元查看
<