1. 程式人生 > >特殊字符的過濾,防止xss攻擊

特殊字符的過濾,防止xss攻擊

factor change 源碼 ive ride ray react list css

概念

XSS攻擊全稱跨站腳本攻擊,是為不和層疊樣式表(Cascading Style Sheets, CSS)的縮寫混淆,故將跨站腳本攻擊縮寫為XSS,XSS是一種在web應用中的計算機安全漏洞,它允許惡意web用戶將代碼植入到提供給其它用戶使用的頁面中。

項目環境

spring + struts2 +.....(僅列舉相關的)

需求

防止xss攻擊

分析

1.防止xss攻擊,可以從請求處攔截特殊字符,核心是過濾特殊字符串

2.由於項目是采用struts2來處理請求的,所以應從struts處著手找方案

3.struts2中的StrutsPrepareAndExecuteFilter,核心是一個Filter,Action可以脫離web容器,讓http請求和action關聯在一起的

4.可以繼承StrutsPrepareAndExecuteFilter類來實現特殊字符過濾

StrutsPrepareAndExecuteFilter分析

StrutsPrepareAndExecuteFilter與普通的Filter並無區別,方法除繼承自Filter外,僅有一個回調方法,Filter方法調用順序是init—>doFilter—>destroy

註意:只關心怎麽實現可以跳過這個內容,直接看下面實現部分

1.init方法

   init是Filter第一個運行的方法,主要的工作是初始化一些配置

public void init(FilterConfig filterConfig) throws
ServletException { InitOperations init = new InitOperations(); Dispatcher dispatcher = null; try { //封裝filterConfig,其中有個主要方法getInitParameterNames將參數名字以String格式存儲在List中 FilterHostConfig config = new FilterHostConfig(filterConfig); // 初始化struts內部日誌 init.initLogging(config);
//創建dispatcher ,加載資源 dispatcher = init.initDispatcher(config); init.initStaticContentLoader(config, dispatcher); //初始化類屬性:prepare 、execute this.prepare = new PrepareOperations(dispatcher); this.execute = new ExecuteOperations(dispatcher); this.excludedPatterns = init.buildExcludedPatternsList(dispatcher); //回調空的postInit方法 this.postInit(dispatcher, filterConfig); } finally { if (dispatcher != null) { dispatcher.cleanUpAfterInit(); } init.cleanup(); } }

1-1.FilterHostConfig類

  可以看出,FilterHostConfig主要是對配置文件的一個封裝,如果有需求要操作配置文件的參數,可以繼承此類實現我們的業務

public class FilterHostConfig implements HostConfig {
    private FilterConfig config;
     /** 
     *構造函數   
     */  
    public FilterHostConfig(FilterConfig config) {
        this.config = config;
    }
    /** 
     *  根據init-param配置的param-name獲取param-value的值 
     */
    public String getInitParameter(String key) {
        return this.config.getInitParameter(key);
    }
    /** 
     *  返回初始化參數名的List 
     */ 
    public Iterator<String> getInitParameterNames() {
        return MakeIterator.convert(this.config.getInitParameterNames());
    }
    /** 
     *  返回上下文
     */ 
    public ServletContext getServletContext() {
        return this.config.getServletContext();
    }
}

1-2.初始化Dispatcher

   創建Dispatcher,會讀取 filterConfig 中的配置信息

public Dispatcher initDispatcher(HostConfig filterConfig) {
        Dispatcher dispatcher = this.createDispatcher(filterConfig);
        dispatcher.init();
        return dispatcher;
}

Dispatcher類init的源碼

技術分享
public void init() {
    if (this.configurationManager == null) {
        this.configurationManager = this
                .createConfigurationManager("struts");
    }

    try {
        
        this.init_FileManager();
        //加載org/apache/struts2/default.properties  
        this.init_DefaultProperties();
        //加載struts-default.xml,struts-plugin.xml,struts.xml 
        this.init_TraditionalXmlConfigurations();
        this.init_LegacyStrutsProperties();
        //用戶自己實現的ConfigurationProviders類     
        this.init_CustomConfigurationProviders();
        //Filter的初始化參數  
        this.init_FilterInitParameters();
        this.init_AliasStandardObjects();
        Container ex = this.init_PreloadConfiguration();
        ex.inject(this);
        this.init_CheckWebLogicWorkaround(ex);
        if (!dispatcherListeners.isEmpty()) {
            Iterator i$ = dispatcherListeners.iterator();

            while (i$.hasNext()) {
                DispatcherListener l = (DispatcherListener) i$.next();
                l.dispatcherInitialized(this);
            }
        }

        this.errorHandler.init(this.servletContext);
    } catch (Exception arg3) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Dispatcher initialization failed", arg3,
                    new String[0]);
        }

        throw new StrutsException(arg3);
    }
}
View Code

1-3.創建Dispatcher

  將配置信息解析出來,封裝成為一個Map,然後根據servlet上下文和參數Map構造Dispatcher

private Dispatcher createDispatcher(HostConfig filterConfig) {
        HashMap params = new HashMap();
        Iterator e = filterConfig.getInitParameterNames();
        while (e.hasNext()) {
            String name = (String) e.next();
            String value = filterConfig.getInitParameter(name);
            params.put(name, value);
        }
        return new Dispatcher(filterConfig.getServletContext(), params);
    }

2.doFilter方法

public void doFilter(ServletRequest req, ServletResponse res,
        FilterChain chain) throws IOException, ServletException {
    //父類向子類轉:強轉為http請求、響應
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    try {
        if (this.excludedPatterns != null
                && this.prepare.isUrlExcluded(request,
                        this.excludedPatterns)) {
            chain.doFilter(request, response);
        } else {
            //設置編碼和國際化  
            this.prepare.setEncodingAndLocale(request, response);
            //創建Action上下文
            this.prepare.createActionContext(request, response);
            this.prepare.assignDispatcherToThread();
            request = this.prepare.wrapRequest(request);
            ActionMapping mapping = this.prepare.findActionMapping(request,
                    response, true);
            if (mapping == null) {
                boolean handled = this.execute
                        .executeStaticResourceRequest(request, response);
                if (!handled) {
                    chain.doFilter(request, response);
                }
            } else {
                this.execute.executeAction(request, response, mapping);
            }
        }
    } finally {
        this.prepare.cleanupRequest(request);
    }

}

2-1.setEncodingAndLocale

  設置編碼這是調用了Dispatcherde.prepare方法加載配置

public void setEncodingAndLocale(HttpServletRequest request,
            HttpServletResponse response) {
        this.dispatcher.prepare(request, response);
    }

prepare方法只是做一些初始化和國際化的缺省設置

技術分享
public void prepare(HttpServletRequest request, HttpServletResponse response) {
    String encoding = null;
    if (this.defaultEncoding != null) {
        encoding = this.defaultEncoding;
    }

    if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
        encoding = "UTF-8";
    }

    Locale locale = null;
    if (this.defaultLocale != null) {
        locale = LocalizedTextUtil.localeFromString(this.defaultLocale,
                request.getLocale());
    }

    if (encoding != null) {
        this.applyEncoding(request, encoding);
    }

    if (locale != null) {
        response.setLocale(locale);
    }

    if (this.paramsWorkaroundEnabled) {
        request.getParameter("foo");
    }

}
View Code

2-2.createActionContext

   ActionContext是一個容器,這個容易主要存儲request、session、application、parameters等

ActionContext是一個線程的本地變量,不同的action之間不會共享ActionContext,所以也不用考慮線程安全問題。

實質是一個Map,key是標示request、session、……的字符串,值是其對應的對象

private static ThreadLocal<Dispatcher> instance = new ThreadLocal();
protected Map<String, String> initParams;

創建Action上下文,初始化thread local

public ActionContext createActionContext(HttpServletRequest request,
        HttpServletResponse response) {
    Integer counter = Integer.valueOf(1);
    Integer oldCounter = (Integer) request
            .getAttribute("__cleanup_recursion_counter");
    if (oldCounter != null) {
        counter = Integer.valueOf(oldCounter.intValue() + 1);
    }
    //從ThreadLocal中獲取此ActionContext變量  
    ActionContext oldContext = ActionContext.getContext();
    ActionContext ctx;
    if (oldContext != null) {
        ctx = new ActionContext(new HashMap(oldContext.getContextMap()));
    } else {
        ValueStack stack = ((ValueStackFactory) this.dispatcher
                .getContainer().getInstance(ValueStackFactory.class))
                .createValueStack();
        stack.getContext().putAll(
                this.dispatcher.createContextMap(request, response,
                        (ActionMapping) null));
        //stack.getContext()返回的是一個Map<String,Object>,根據此Map構造一個ActionContext
        ctx = new ActionContext(stack.getContext());
    }

    request.setAttribute("__cleanup_recursion_counter", counter);
    //將ActionContext存到ThreadLocal<ActionContext> actionContext  
    ActionContext.setContext(ctx);
    return ctx;
}

createContextMap方法

public Map<String, Object> createContextMap(HttpServletRequest request,
        HttpServletResponse response, ActionMapping mapping) {
    RequestMap requestMap = new RequestMap(request);
    HashMap params = new HashMap(request.getParameterMap());
    SessionMap session = new SessionMap(request);
    ApplicationMap application = new ApplicationMap(this.servletContext);
    //requestMap、params、session等Map封裝成為一個上下文Map,逐個調用了map.put(Map p). 
    HashMap extraContext = this.createContextMap(requestMap, params,
            session, application, request, response);
    if (mapping != null) {
        extraContext.put("struts.actionMapping", mapping);
    }
    return extraContext;
}

executeAction方法

  封裝執行的上下文環境,主要將相關信息存儲入map,根據執行上下文參數,命名空間,名稱等創建用戶自定義Action的代理對象,執行execute方法,並轉向結果

public void executeAction(HttpServletRequest request,
            HttpServletResponse response, ActionMapping mapping)
            throws ServletException {
       this.dispatcher.serviceAction(request, response, mapping);
}

實現

繼承StrutsPrepareAndExecuteFilter類,重寫init方法,在web.xml引用這個filter

 @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        InitOperations init = new InitOperations();
        Dispatcher dispatcher = null;
        try {
            FilterHostConfig config = new FilterHostConfig(filterConfig);
            init.initLogging(config);
            dispatcher = initDispatcher(config);
            init.initStaticContentLoader(config, dispatcher);

            prepare = new PrepareOperations(filterConfig.getServletContext(), dispatcher);
            execute = new ExecuteOperations(filterConfig.getServletContext(), dispatcher);
            this.excludedPatterns = init.buildExcludedPatternsList(dispatcher);

            postInit(dispatcher, filterConfig);
        } finally {
            if (dispatcher != null) {
                dispatcher.cleanUpAfterInit();
            }
            init.cleanup();
        }
    }

   
    public Dispatcher initDispatcher(HostConfig filterConfig) {
        Dispatcher dispatcher = createDispatcher(filterConfig);
        dispatcher.init();
        return dispatcher;
    }

   
    private Dispatcher createDispatcher(HostConfig filterConfig) {
        Map<String, String> params = new HashMap<String, String>();
        for (Iterator e = filterConfig.getInitParameterNames(); e.hasNext();) {
            String name = (String) e.next();
            String value = filterConfig.getInitParameter(name);
            params.put(name, value);
        }
        return new MDispatcher(filterConfig.getServletContext(), params);
    }

繼承Dispatcher實現自己的MDispatcher重寫createContextMap方法

@Override
    public Map<String,Object> createContextMap(HttpServletRequest request, HttpServletResponse response,
            ActionMapping mapping) {

        // request map wrapping the http request objects
        Map requestMap = new RequestMap(request);
        
        //對參數進行xss過濾
        Map<String, String[]> paramMap = xssFilterParam(request); 

        // parameters map wrapping the http parameters.  ActionMapping parameters are now handled and applied separately
        Map params = new HashMap(paramMap);

        // session map wrapping the http session
        Map session = new SessionMap(request);

        // application map wrapping the ServletContext
        Map application = new ApplicationMap(servletContext);

        Map<String,Object> extraContext = createContextMap(requestMap, params, session, application, request, response);

        if (mapping != null) {
            extraContext.put(ServletActionContext.ACTION_MAPPING, mapping);
        }
        return extraContext;
    }

xssFilterParam

private Map<String, String[]> xssFilterParam(HttpServletRequest request) {
        Map<String, String[]> paramMap = new HashMap<String, String[]>();
        Map<String, String[]> reqParamMap = request.getParameterMap();
        for (Map.Entry<String, String[]> entry : reqParamMap.entrySet()) {   
            String key = entry.getKey();
            LOG.debug("Key = " + entry.getKey() + ", Value = " + entry.getValue());  
            if(!key.endsWith("$HTML")){
                //過濾
                String[] values = getParameterValues(request,key);
                paramMap.put(key, values);
            }else{
                //如果以   “$HTML” 結尾的參數,不進行過濾,並且構造新參數值
                String keyNew = key.substring(0,key.length()-5);
                paramMap.put(keyNew, entry.getValue());
                paramMap.put(key, entry.getValue());
            }
            
        }
        return paramMap;
    }

getParameterValues

private String[] getParameterValues(HttpServletRequest request,String name) {
        name = XssShieldUtil.stripXss(name);
        // 返回值之前 先進行過濾
        String[] values = request.getParameterValues(name);
        if(values != null){
            for (int i = 0; i < values.length; i++) {
                values[i] = XssShieldUtil.stripXss(values[i]);
            }
        }
        return values;
    }

我的xss字符處理工具類

public class XssShieldUtil {

    private static List<Pattern> patterns = null;

    private static List<Object[]> getXssPatternList() {
        List<Object[]> ret = new ArrayList<Object[]>();
        ret.add(new Object[]{"<(no)?script[^>]*>.*?</(no)?script>", Pattern.CASE_INSENSITIVE});
        ret.add(new Object[]{"eval\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL});
        ret.add(new Object[]{"expression\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL});
        ret.add(new Object[]{"(javascript:|vbscript:|view-source:)*", Pattern.CASE_INSENSITIVE});
        ret.add(new Object[]{"<(\"[^\"]*\"|\‘[^\‘]*\‘|[^\‘\">])*>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL});
        ret.add(new Object[]{"(window\\.location|window\\.|\\.location|document\\.cookie|document\\.|alert\\(.*?\\)|window\\.open\\()*", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL});
        ret.add(new Object[]{"<+\\s*\\w*\\s*(oncontrolselect|oncopy|oncut|ondataavailable|ondatasetchanged|ondatasetcomplete|ondblclick|ondeactivate|ondrag|ondragend|ondragenter|ondragleave|ondragover|ondragstart|ondrop|onerror=|onerroupdate|onfilterchange|onfinish|onfocus|onfocusin|onfocusout|onhelp|onkeydown|onkeypress|onkeyup|onlayoutcomplete|onload|onlosecapture|onmousedown|onmouseenter|onmouseleave|onmousemove|onmousout|onmouseover|onmouseup|onmousewheel|onmove|onmoveend|onmovestart|onabort|onactivate|onafterprint|onafterupdate|onbefore|onbeforeactivate|onbeforecopy|onbeforecut|onbeforedeactivate|onbeforeeditocus|onbeforepaste|onbeforeprint|onbeforeunload|onbeforeupdate|onblur|onbounce|oncellchange|onchange|onclick|oncontextmenu|onpaste|onpropertychange|onreadystatechange|onreset|onresize|onresizend|onresizestart|onrowenter|onrowexit|onrowsdelete|onrowsinserted|onscroll|onselect|onselectionchange|onselectstart|onstart|onstop|onsubmit|onunload)+\\s*=+", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL});
        return ret;
    }

    private static List<Pattern> getPatterns() {

        if (patterns == null) {

            List<Pattern> list = new ArrayList<Pattern>();

            String regex = null;
            Integer flag = null;
            int arrLength = 0;

            for(Object[] arr : getXssPatternList()) {
                arrLength = arr.length;
                for(int i = 0; i < arrLength; i++) {
                    regex = (String)arr[0];
                    flag = (Integer)arr[1];
                    list.add(Pattern.compile(regex, flag));
                }
            }

            patterns = list;
        }

        return patterns;
    }

    public static String stripXss(String value) {
        if(StringUtils.isNotBlank(value)) {

            Matcher matcher = null;

            for(Pattern pattern : getPatterns()) {
                matcher = pattern.matcher(value);
                // 匹配
                if(matcher.find()) {
                    // 刪除相關字符串
                    value = matcher.replaceAll("");
                }
            }

            value = value.replaceAll("<", "&lt;").replaceAll(">", "&gt;");
        }
        return value;
    }
}

最後在web.xml引用這個StrutsPrepareAndExecuteFilter

<filter>
    <filter-name>struts2</filter-name>
    <filter-class>MStrutsPrepareAndExecuteFilter</filter-class>
</filter>

特殊字符的過濾,防止xss攻擊