XSS漏洞修补及预防--使用过滤器

什么是XSS攻击 :
XSS是一种经常出现在web应用中的计算机安全漏洞,它允许恶意web用户将代码植入到提供给其它用户使用的页面中。比如这些代码包括HTML代码和客户端脚本。攻击者利用XSS漏洞旁路掉访问控制——例如同源策略(same origin policy)。这种类型的漏洞由于被黑客用来编写危害性更大的网络钓鱼(Phishing)攻击而变得广为人知。对于跨站脚本攻击,黑客界共识是:跨站脚本攻击是新型的“缓冲区溢出攻击“,而JavaScript是新型的“ShellCode”。

如下代码不涉及对原有开发人员的代码,进行修改。在最外层增加过滤器,进行对所有参数进行过滤,涉及框架SpringMVC
1.创建过滤器类,使其实现Filter。

package com.data.interceptor;

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;

/** * * @Title: XSSFilter.java * @Package: com.data.interceptor * @author you.xu * @date 2016年3月4日上午11:21:47 * @version 1.0 */
public class XSSFilter implements Filter {

    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest req, ServletResponse res,
            FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        request = new XSSServletRequest(request);
        filterChain.doFilter(request, res);
    }

    public void destroy() {

    }

}

2.创建XSSServletRequest.java类,将request请求进行过滤。

package com.data.interceptor;

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

import com.data.utils.XssFilterUtil;

/** * * @Title: XSSServletRequest.java * @Package: com.data.interceptor * @author you.xu * @date 2016年3月4日上午11:25:02 * @version 1.0 */
public class XSSServletRequest extends HttpServletRequestWrapper {

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

    @Override
    public String getParameter(String name) {
        String string = super.getParameter(name);
        // 返回值之前 先进行过滤
        return XssFilterUtil.stripXss(string);
    }

    @Override
    public String[] getParameterValues(String name) {
        // 返回值之前 先进行过滤
        String[] values = super
                .getParameterValues(name);
        if (values != null) {
            for (int i = 0; i < values.length; i++) {
                values[i] = XssFilterUtil.stripXss(values[i]);
            }
        }
        return values;
    }
}

3.创建过滤器工具类XssFilterUtil.java,

package com.data.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;

/** * * @Title: XssFilterUtil.java * @author you.xu * @date 2016年3月4日上午9:52:02 * @version 1.0 */

public class XssFilterUtil {

    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 (null == value) {
            return value;
        }
        if (StringUtils.isNotBlank(value)) {

            Matcher matcher = null;

            for (Pattern pattern : getPatterns()) {
                matcher = pattern.matcher(value);
                // 匹配
                if (matcher.find()) {
                    // 删除相关字符串
                    value = matcher.replaceAll("");
                }
            }
            value = StringFilter.StringFilter(value);
        }
        // 预防SQL盲注
        String[] pattern = { "%", "select", "insert", "delete", "from",
                "count\\(", "drop table", "update", "truncate", "asc\\(",
                "mid\\(", "char\\(", "xp_cmdshell", "exec", "master",
                "netlocalgroup administrators", "net user", "or", "and" };
        for (int i = 0; i < pattern.length; i++) {
            value = value.replace(pattern[i].toString(), "");
        }
        return value;
    }

    public static void main(String[] args) {

        String value = null;
        value = XssFilterUtil
                .stripXss("<br>select ***//||&;/*-+ <>$###@%$#@$%^#$^%$&^(&*)*\\''count or %% ..... ,,,, ");
        System.out.println("type-1: '" + value + "'");

        value = XssFilterUtil
                .stripXss("<script src='' onerror='alert(document.cookie)'></script>");
        System.out.println("type-2: '" + value + "'");

        value = XssFilterUtil.stripXss("</script>");
        System.out.println("type-3: '" + value + "'");

        value = XssFilterUtil.stripXss(" eval(abc);");
        System.out.println("type-4: '" + value + "'");

        value = XssFilterUtil.stripXss(" expression(abc);");
        System.out.println("type-5: '" + value + "'");

        value = XssFilterUtil
                .stripXss("<img src='' onerror='alert(document.cookie);'></img>");
        System.out.println("type-6: '" + value + "'");

        value = XssFilterUtil
                .stripXss("<img src='' onerror='alert(document.cookie);'/>");
        System.out.println("type-7: '" + value + "'");

        value = XssFilterUtil
                .stripXss("<img src='' onerror='alert(document.cookie);'>");
        System.out.println("type-8: '" + value + "'");

        value = XssFilterUtil
                .stripXss("<script language=text/javascript>alert(document.cookie);");
        System.out.println("type-9: '" + value + "'");

        value = XssFilterUtil.stripXss("<script>window.location='url'");
        System.out.println("type-10: '" + value + "'");

        value = XssFilterUtil.stripXss(" onload='alert(\"abc\");");
        System.out.println("type-11: '" + value + "'");

        value = XssFilterUtil.stripXss("<img src=x<!--'<\"-->>");
        System.out.println("type-12: '" + value + "'");

        value = XssFilterUtil.stripXss("<=img onstop=");
        System.out.println("type-13: '" + value + "'");
    }
}

4.配置web.xml

<filter>
    <filter-name>XSSFilter</filter-name>
    <filter-class>com.data.interceptor.XSSFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>XSSFilter</filter-name>
    <url-pattern>*.do</url-pattern>
</filter-mapping>

本文对其增加了预防SQL盲注漏洞,将字符串中涉及到的与sql相关的关键字进行了过滤。

我是一个小菜鸟,大家如有更简单高效的代码,欢迎在评论中指出,一起分享。谢谢

参考文档:http://blog.csdn.net/catoop/article/details/50338259

你可能感兴趣的:(漏洞,安全漏洞,网络钓鱼)