安全漏洞解决方案

过滤器解决方案:

1.将BadInputFilter.java放到自己的源码中;

package com.accredit.common.badInput;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 安全漏洞过滤器
 */
public class BadInputFilter implements Filter {

    protected static String info = BadInputFilter.class.getName() + "/1.0";

    private static final String[] STRING_ARRAY = new String[0];

    protected boolean escapeQuotes = false;

    protected boolean escapeAngleBrackets = false;


    protected boolean escapeJavaScript = false;

    protected HashMap<String, String> quotesHashMap = new HashMap();

    protected HashMap<String, String> angleBracketsHashMap = new HashMap();

    protected HashMap<String, String> javaScriptHashMap = new HashMap();

    protected String allow = null;

    protected Pattern[] allows = new Pattern[0];

    protected Pattern[] denies = new Pattern[0];

    protected String deny = null;

    protected HashMap<String, String> parameterEscapes = new HashMap();

    protected ServletContext servletContext;

    protected Method setLockedMethod;

    public BadInputFilter() {
        this.quotesHashMap.put("\"", "&quot;");
        this.quotesHashMap.put("'", "&#39;");
        this.quotesHashMap.put("`", "&#96;");
        this.angleBracketsHashMap.put("<", "&lt;");
        this.angleBracketsHashMap.put(">", "&gt;");
        this.javaScriptHashMap.put("document(.*)\\.(.*)cookie", "document&#46;&#99;ookie");
        this.javaScriptHashMap.put("eval(\\s*)\\(", "eval&#40;");
        this.javaScriptHashMap.put("setTimeout(\\s*)\\(", "setTimeout$1&#40;");
        this.javaScriptHashMap.put("setInterval(\\s*)\\(", "setInterval$1&#40;");
        this.javaScriptHashMap.put("execScript(\\s*)\\(", "exexScript$1&#40;");
        this.javaScriptHashMap.put("(?i)javascript(?-i):", "javascript&#58;");
    }

    public boolean getEscapeQuotes() {
        return this.escapeQuotes;
    }

    public void setEscapeQuotes(boolean escapeQuotes) {
        this.escapeQuotes = escapeQuotes;
        if (!escapeQuotes) return;
        this.parameterEscapes.putAll(this.quotesHashMap);
    }


    public boolean getEscapeAngleBrackets() {
        return this.escapeAngleBrackets;
    }


    public void setEscapeAngleBrackets(boolean escapeAngleBrackets) {
        this.escapeAngleBrackets = escapeAngleBrackets;
        if (!escapeAngleBrackets) return;
        this.parameterEscapes.putAll(this.angleBracketsHashMap);
    }

    public boolean getEscapeJavaScript() {
        return this.escapeJavaScript;
    }

    public void setEscapeJavaScript(boolean escapeJavaScript) {
        this.escapeJavaScript = escapeJavaScript;
        if (!escapeJavaScript) return;
        this.parameterEscapes.putAll(this.javaScriptHashMap);
    }

    public String getAllow() {
        return this.allow;
    }


    public void setAllow(String allow) {
        this.allow = allow;
        this.allows = precalculate(allow);
        this.servletContext.log("BadInputFilter: allow = " + this.deny);
    }


    public String getDeny() {
        return this.deny;
    }

    public void setDeny(String deny) {
        this.deny = deny;
        this.denies = precalculate(deny);
        this.servletContext.log("BadInputFilter: deny = " + deny);
    }


    public void init(FilterConfig filterConfig) throws ServletException {
        this.servletContext = filterConfig.getServletContext();
        setAllow(filterConfig.getInitParameter("allow"));
        setDeny(filterConfig.getInitParameter("deny"));
        String initParam = filterConfig.getInitParameter("escapeQuotes");
        if (initParam != null) {
            boolean flag = Boolean.parseBoolean(initParam);
            setEscapeQuotes(flag);
        }
        initParam = filterConfig.getInitParameter("escapeAngleBrackets");
        if (initParam != null) {
            boolean flag = Boolean.parseBoolean(initParam);
            setEscapeAngleBrackets(flag);
        }
        initParam = filterConfig.getInitParameter("escapeJavaScript");
        if (initParam != null) {
            boolean flag = Boolean.parseBoolean(initParam);
            setEscapeJavaScript(flag);
        }
        this.servletContext.log(toString() + " initialized.");
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        if ((!(request instanceof HttpServletRequest)) || (!(response instanceof HttpServletResponse))) {
            filterChain.doFilter(request, response);
            return;
        }
        if (!processAllowsAndDenies(request, response)) {
            return;
        }
        filterParameters(request);
        filterChain.doFilter(request, response);
    }


    public boolean processAllowsAndDenies(ServletRequest request, ServletResponse response) throws IOException, ServletException {
        Map paramMap = request.getParameterMap();
        Iterator y = paramMap.keySet().iterator();
        while (y.hasNext()) {
            String name = (String) y.next();
            String[] values = request.getParameterValues(name);
            if (!checkAllowsAndDenies(name, response)) {
                return false;
            }
            if (values != null) {
                for (int i = 0; i < values.length; ++i) {
                    String value = values[i];
                    if (!checkAllowsAndDenies(value, response)) {
                        return false;
                    }
                }
            }
        }
        return true;
    }

    public boolean checkAllowsAndDenies(String property, ServletResponse response) throws IOException, ServletException {
        if ((this.denies.length == 0) && (this.allows.length == 0)) {
            return true;
        }
        for (int i = 0; i < this.denies.length; ++i) {
            Matcher m = this.denies[i].matcher(property);
            if ((!m.find()) || (!(response instanceof HttpServletResponse))) continue;
            HttpServletResponse hres = (HttpServletResponse) response;
            hres.sendError(403);
            return false;
        }
        for (int i = 0; i < this.allows.length; ++i) {
            Matcher m = this.allows[i].matcher(property);
            if (m.find()) {
                return true;
            }
        }
        if ((this.denies.length > 0) && (this.allows.length == 0)) {
            return true;
        }
        if (response instanceof HttpServletResponse) {
            HttpServletResponse hres = (HttpServletResponse) response;
            hres.sendError(403);
        }
        return false;
    }


    public void filterParameters(ServletRequest request) {
        Map paramMap = ((HttpServletRequest) request).getParameterMap();
        try {
            if (this.setLockedMethod == null) {
                this.setLockedMethod = paramMap.getClass().getMethod("setLocked", new Class[] { Boolean.TYPE });
            }
            this.setLockedMethod.invoke(paramMap, new Object[] { Boolean.FALSE });
        } catch (Exception e) {
            this.servletContext.log("BadInputFilter: Cannot filter parameters!");
        }
        Iterator escapesIterator = this.parameterEscapes.keySet().iterator();
        while (escapesIterator.hasNext()) {
            String patternString = (String) escapesIterator.next();
            Pattern pattern = Pattern.compile(patternString);
            String[] paramNames = (String[]) paramMap.keySet().toArray(STRING_ARRAY);
            for (int i = 0; i < paramNames.length; ++i) {
                String name = paramNames[i];
                // 部分特殊系统参数不进行过滤(xml内容,sql语句)
                if (("sql".equals(name)) || ("paramsql".equals(name)) || "content".equals(name) || "hightcontent".equals(name)) {
                    continue;
                }
                String[] values = ((HttpServletRequest) request).getParameterValues(name);
                Matcher matcher = pattern.matcher(name);
                boolean nameMatch = matcher.matches();
                if (nameMatch) {
                    String newName = matcher.replaceAll((String) this.parameterEscapes.get(patternString));
                    paramMap.remove(name);
                    paramMap.put(newName, values);
                    this.servletContext.log("Parameter name " + name + " matched pattern \"" + patternString + "\".  Remote addr: "
                            + ((HttpServletRequest) request).getRemoteAddr());
                }
                if (values != null) {
                    for (int j = 0; j < values.length; ++j) {
                        String value = values[j];
                        matcher = pattern.matcher(value);
                        boolean valueMatch = matcher.find();
                        if (!valueMatch) {
                            continue;
                        }
                        String newValue = matcher.replaceAll((String) this.parameterEscapes.get(patternString));
                        values[j] = newValue;
                        this.servletContext.log("Parameter \"" + name + "\"'s value \"" + value + "\" matched pattern \"" + patternString
                                + "\".  Remote addr: " + ((HttpServletRequest) request).getRemoteAddr());
                    }
                }
            }
        }
        try {
            if (this.setLockedMethod == null) {
                this.setLockedMethod = paramMap.getClass().getMethod("setLocked", new Class[] { Boolean.TYPE });
            }
            this.setLockedMethod.invoke(paramMap, new Object[] { Boolean.TRUE });
        } catch (Exception localException1) {
        }
    }


    public String toString() {
        return "BadInputFilter";
    }


    public void destroy() {
    }


    protected Pattern[] precalculate(String list) {
        if (list == null) return new Pattern[0];
        list = list.trim();
        if (list.length() < 1) return new Pattern[0];
        list = list + ",";
        ArrayList reList = new ArrayList();
        while (list.length() > 0) {
            int comma = list.indexOf(',');
            if (comma < 0) break;
            String pattern = list.substring(0, comma).trim();
            try {
                reList.add(Pattern.compile(pattern));
            } catch (PatternSyntaxException e) {
                IllegalArgumentException iae = new IllegalArgumentException("Syntax error in request filter pattern" + pattern);
                iae.initCause(e);
                throw iae;
            }
            list = list.substring(comma + 1);
        }
        Pattern[] reArray = new Pattern[reList.size()];
        return (Pattern[]) reList.toArray(reArray);
    }
}

2.在web.xml中加入:
<filter>
<filter-name>BadInputFilter</filter-name>
<filter-class>com.accredit.common.badInput.BadInputFilter</filter-class>
<init-param>
<param-name>deny</param-name>
<param-value>(?i)script</param-value>
</init-param>
<init-param>
<param-name>escapeQuotes</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>escapeJavaScript</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>escapeAngleBrackets</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>BadInputFilter</filter-name>
<url-pattern>/*</url-pattern>

</filter-mapping>

完成!微笑

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值