package com.steerinfo.filter;

import java.io.IOException;
import java.util.Enumeration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSONArray;
import com.steerinfo.framework.constant.RESTCodes;
import com.steerinfo.framework.controller.RESTfulResult;

/**
 * SQL注入过滤器
 *
 * @author CL
 *
 */
/*@Component
@ConfigurationProperties(prefix = "security.sql")
@WebFilter(filterName = "SqlInjectFilter", urlPatterns = "/*")*/
public class SqlInjectFilter implements Filter {
    private static final Logger log = LoggerFactory.getLogger(SqlInjectFilter.class);
    /**
     * 过滤器配置对象
     */
    FilterConfig filterConfig = null;

    /**
     * 初始化
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }

    /**
     * 拦截
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse res = (HttpServletResponse) servletResponse;
        // 获得所有请求参数名
        Enumeration params = req.getParameterNames();
//        String requestUriMb= req.getRequestURI();
        String sql = "";
        String strparams = "";
        while (params.hasMoreElements()) {
            // 得到参数名
            String name = params.nextElement().toString();
            // 得到参数对应值
            String[] value = req.getParameterValues(name);
            for (int i = 0; i < value.length; i++) {
                sql = sql + value[i];
                strparams = strparams + " " + value[i];
            }
        }
        if (sqlValidate(sql) ) { //&& !requestUriMb.contains("executeSqlDataWf")
            // res.sendRedirect("error.jsp");
            log.info("发现sql注入:" + strparams);
            String msg = "非法请求参数,请检查后再进行操作";
            RESTfulResult result = new RESTfulResult(RESTCodes.ERROR, msg);
            res.setCharacterEncoding("UTF-8");
            res.setHeader("Content-Type", "application/json");
            res.setContentType("application/json;charset=UTF-8");
            res.setStatus(HttpServletResponse.SC_OK);
            res.getWriter().write(JSONArray.toJSON(result).toString());
        } else {
            filterChain.doFilter(req, res);
        }
    }

    /**
     * 销毁
     */
    @Override
    public void destroy() {
        this.filterConfig = null;
    }

    // 校验
    protected static boolean sqlValidate(String str) {
        str = str.toLowerCase();// 统一转为小写
        // String badStr = "and|exec";
        String badStr =
                "'| and | exec | execute | insert | select | delete | update | count | drop | chr | mid | master | truncate | char | declare | sitename | net user | xp_cmdshell | or | like | - | -- | + | , | like | // | / | % | #|insert |select |delete |update";
        /*
         * String badStr =
         * "'|and|exec|execute|insert|create|drop|table|from|grant|use|group_concat|column_name|" +
         * "information_schema.columns|table_schema|union|where|select|delete|update|order|by|count|*|" +
         * "chr|mid|master|truncate|char|declare|or|;|-|--|+|,|like|//|/|%|#";
         */ // 过滤掉的sql关键字，可以手动添加
        String[] badStrs = badStr.split("\\|");
        for (int i = 0; i < badStrs.length; i++) {
            if (str.indexOf(badStrs[i]) != -1) {
                log.info("匹配到：" + badStrs[i]);
                return true;
            }
        }
        return false;
    }
}