package com.censoft.db;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Enumeration;

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

import com.censoft.common.base.Pub;

public class SqlFilter
        implements Filter {
    Pub pub = new Pub();
    protected boolean isDebug = false;
    protected String[] guardSqlStrings = {" select", " insert", " delete", " update", " count", "'", ";"};
    protected String errorPageUrl = "";
    protected boolean doLog = true;
    protected String needValidExt = "";
    protected String[] ignoreUrls = new String[0];

    public void destroy() {
    }

    public void doFilter(ServletRequest paramServletRequest, ServletResponse paramServletResponse, FilterChain paramFilterChain)
            throws IOException, ServletException {
        HttpServletRequest localHttpServletRequest =null;
        HttpServletResponse localHttpServletResponse = null;
        try {
            localHttpServletRequest = (HttpServletRequest) paramServletRequest;
            localHttpServletResponse = (HttpServletResponse) paramServletResponse;
            String str1 = localHttpServletRequest.getRequestURI();
            if (str1 == null)
                str1 = "";
            str1 = str1.trim();
            if (this.isDebug)
                System.out.println("requestUrl:" + str1);
            String str2 = localHttpServletRequest.getContextPath();
            if (!str2.endsWith("/"))
                str2 = str2 + "/";
            str1 = "/" + str1.substring(str1.indexOf(str2) + str2.length(), str1.length());
            for (int i = 0; i < this.ignoreUrls.length; i++) {
                if (!this.ignoreUrls[i].startsWith("/"))
                    this.ignoreUrls[i] = ("/" + this.ignoreUrls[i]);
                if (!str1.startsWith(this.ignoreUrls[i]))
                    continue;
                paramFilterChain.doFilter(paramServletRequest, paramServletResponse);
                return;
            }
            String str3 = "";
            if (str1.lastIndexOf(".") != -1)
                str3 = str1.substring(str1.lastIndexOf(".") + 1, str1.length());
            if ((this.needValidExt.equals("")) || (str3.equals("")) || (this.needValidExt.indexOf("," + str3 + ",") != -1)) {
                if (this.isDebug)
                    System.out.println("begin check:" + str1);
                if (isAttackBySql(localHttpServletRequest, this.guardSqlStrings)) {
                    localHttpServletResponse.sendRedirect(str2 + this.errorPageUrl);
                    return;
                }
                if (this.isDebug)
                    System.out.println("end check " + str1);
            }
        } catch (Exception localException) {
            System.out.println("GuardSqlFilter过滤器错误：" + localException);
        }
        paramFilterChain.doFilter(paramServletRequest, paramServletResponse);
    }

    public void init(FilterConfig paramFilterConfig)
            throws ServletException {
        String str1 = this.pub.trimNull(paramFilterConfig.getInitParameter("guardString"));
        if (str1.startsWith("|"))
            str1 = str1.substring(1, str1.length());
        if (str1.endsWith("|"))
            str1 = str1.substring(0, str1.length() - 1);
        if (!str1.equals("")) {
            str1 = str1.toLowerCase();
            str1 = this.pub.replace(str1, "&lt;", "<");
            str1 = this.pub.replace(str1, "&gt;", ">");
            str1 = this.pub.replace(str1, "&amp;", "&");
            str1 = this.pub.replace(str1, "&quot;", "\"");
            this.guardSqlStrings = this.pub.split(str1, "|");
        }
        String str2 = this.pub.trimNull(paramFilterConfig.getInitParameter("ignoreUrls"));
        if (!str2.equals(""))
            this.ignoreUrls = this.pub.split(str2, ",");
        String str3 = this.pub.trimNull(paramFilterConfig.getInitParameter("needfilterexts"));
        if (str3 == null)
            str3 = "";
        str3 = str3.trim();
        if (!str3.equals("")) {
            if (!str3.startsWith(","))
                str3 = "," + str3;
            if (!str3.endsWith(","))
                str3 = str3 + ",";
        }
        this.needValidExt = str3;
        this.errorPageUrl = this.pub.trimNull(paramFilterConfig.getInitParameter("errorPageUrl"));
        if ((!this.errorPageUrl.equals("")) && (this.errorPageUrl.startsWith("/")))
            this.errorPageUrl = this.errorPageUrl.substring(1, this.errorPageUrl.length());
        String str4 = this.pub.trimNull(paramFilterConfig.getInitParameter("doLog"));
        if (str4.equalsIgnoreCase("false"))
            this.doLog = false;
        String str5 = this.pub.trimNull(paramFilterConfig.getInitParameter("isDebug"));
        if (str5.equalsIgnoreCase("true"))
            this.isDebug = true;
    }

    public boolean isAttackBySql(HttpServletRequest paramHttpServletRequest, String[] paramArrayOfString) {
        Enumeration localEnumeration = paramHttpServletRequest.getParameterNames();
        StringBuffer localStringBuffer1 = new StringBuffer();
        StringBuffer localStringBuffer2 = new StringBuffer();
        localStringBuffer2.append(" ");
        while (localEnumeration.hasMoreElements()) {
            String str = (String) localEnumeration.nextElement();
            if ("content".equals(str) || "model_content".equals(str) || "ba_beizhu".equals(str)) continue;
            localStringBuffer1.append(str);
            localStringBuffer1.append("=[");
            String[] arrayOfString = paramHttpServletRequest.getParameterValues(str);
            if (arrayOfString == null)
                continue;
            for (int j = 0; j < arrayOfString.length; j++) {
                localStringBuffer2.append(arrayOfString[j]);
                localStringBuffer1.append(arrayOfString[j]);
                if (j != arrayOfString.length - 1)
                    localStringBuffer1.append(",");
                localStringBuffer2.append(" ");
            }
            localStringBuffer1.append("];");
        }
        String str = localStringBuffer2.toString().toLowerCase();
        for (int i = 0; i < paramArrayOfString.length; i++) {
            if (str.indexOf(paramArrayOfString[i]) == -1)
                continue;
            doLog(paramArrayOfString[i], paramHttpServletRequest, localStringBuffer1.toString());
            return true;
        }
        return false;
    }

    public boolean doLog(String paramString1, HttpServletRequest paramHttpServletRequest, String paramString2) {
        Calendar localCalendar = Calendar.getInstance();
        SimpleDateFormat localSimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss");
        String str = "SQL注入嫌疑：敏感字：[" + paramString1 + "] 时间：[" + localSimpleDateFormat.format(localCalendar.getTime()) + "] IP:[" + paramHttpServletRequest.getRemoteAddr() + "] URL:[" + paramHttpServletRequest.getRequestURI() + "] 参数：" + paramString2;
        System.out.println(str);
        return true;
    }
}