参考:https://blog.csdn.net/zhangbeizhen18/article/details/125239707

/**
 * @desc: sql注入过滤器
 * @author: 毛会懂
 * @create: 2022-11-14 11:04:00
 **/
@Slf4j
@RefreshScope
@Service
public class SqlInjectionFilter implements Filter {

    // 总开关: 0:关闭 1:打开   在nacos中配置
    @Value("${sqlInjectionAllSwitch:1}")
    private Integer sqlInjectionAllSwitch;

    // 特殊字符的开关: 0:关闭 1:打开 在nacos中配置
    @Value("${sqlInjectionKeySwitch:1}")
    private Integer sqlInjectionKeySwitch;

    /**
    * 校验的关键词
    **/
    private static final String SQL_REG_EXP = ".*(\\b(and|exec|execute|insert|into|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)\\b).*";

    /**
    * 根据开关是否校验字段的开头和结尾有特殊字符
    **/
    private static final List<String> keys = Arrays.asList(";","--",",","//","%","#","'","*");

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        if(sqlInjectionAllSwitch.equals(0) || ("POST".equals(request.getMethod().toUpperCase()) && request.getHeader("content-type").startsWith("multipart/form-data"))){ 
// 总开关关闭 或 文件上传不sql过滤 filterChain.doFilter(servletRequest, servletResponse); return; } HttpServletRequest request = (HttpServletRequest) servletRequest; CustomRequestWrapper requestWrapper = new CustomRequestWrapper(request); Map<String, Object> parameterMap = new HashMap<>(); parameterMap =getParameterMap(parameterMap, request, requestWrapper); // 正则校验是否有SQL关键字 for (Object obj : parameterMap.entrySet()) { Map.Entry entry = (Map.Entry) obj; Object value = entry.getValue(); if (value != null) { boolean isValid = isSqlInject(value.toString(), servletResponse); if (!isValid) { return; } } } filterChain.doFilter(requestWrapper, servletResponse); } private Map<String, Object> getParameterMap(Map<String, Object> paramMap, HttpServletRequest request, CustomRequestWrapper requestWrapper) { // 1.POST请求获取参数 if ("POST".equals(request.getMethod().toUpperCase())) { String body = requestWrapper.getBody(); paramMap = JSONObject.parseObject(body, HashMap.class); } else { Map<String, String[]> parameterMap = requestWrapper.getParameterMap(); //普通的GET请求 if (parameterMap != null && parameterMap.size() > 0) { Set<Map.Entry<String, String[]>> entries = parameterMap.entrySet(); for (Map.Entry<String, String[]> next : entries) { paramMap.put(next.getKey(), next.getValue()[0]); } } else { //GET请求,参数在URL路径型式,比如server/{var1}/{var2} String afterDecodeUrl = null; try { //编码过URL需解码解码还原字符 afterDecodeUrl = URLDecoder.decode(request.getRequestURI(), "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } paramMap.put("pathVar", afterDecodeUrl); } } return paramMap; } private boolean isSqlInject(String value, ServletResponse servletResponse) throws IOException { if ((null != value && value.toLowerCase().matches(SQL_REG_EXP)) || isKey(value)) { // if (null != value && Pattern.compile(SQL_REG_EXP).matcher(value.toLowerCase()).find()) { log.info("入参中有非法字符: " + value); HttpServletResponse response = (HttpServletResponse) servletResponse; Map<String, String> responseMap = new HashMap<>(); // 匹配到非法字符,立即返回 responseMap.put("code", "999"); responseMap.put("message","入参中有非法字符"); response.setContentType("application/json;charset=UTF-8"); response.setStatus(HttpStatus.OK.value()); response.getWriter().write(JSON.toJSONString(responseMap)); response.getWriter().flush(); response.getWriter().close(); return false; } return true; } /** * @desc : 校验是否以关键字开头或结尾 * @author : 毛会懂 * @create: 2022/11/14 15:38:00 **/ private Boolean isKey(String value){ // 不开启关键字校验 if(sqlInjectionKeySwitch.equals(0)){ return Boolean.FALSE; } for (String key : keys) { if(value.startsWith(key) || value.endsWith(key)){ return Boolean.TRUE; } } return Boolean.FALSE; } }

  

 

包装请求:

/**
 * @desc: 装饰请求
 * @author: 毛会懂
 * @create: 2022-11-14 11:05:00
 **/
public class CustomRequestWrapper extends HttpServletRequestWrapper {
    private final String body;
    public CustomRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        StringBuilder sb = new StringBuilder();
        BufferedReader bufferedReader = null;
        try {
            InputStream inputStream = request.getInputStream();
            if (inputStream != null) {
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
                char[] charBuffer = new char[512];
                int bytesRead = -1;
                while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
                    sb.append(charBuffer, 0, bytesRead);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    throw e;
                }
            }
        }
        body = sb.toString();
    }
    @Override
    public ServletInputStream getInputStream() throws IOException {
        final ByteArrayInputStream bais = new ByteArrayInputStream(body.getBytes("UTF-8"));
        return new ServletInputStream() {
            @Override
            public boolean isFinished() {
                return false;
            }
            @Override
            public boolean isReady() {
                return false;
            }
            @Override
            public void setReadListener(ReadListener readListener) {
            }
            @Override
            public int read() {
                return bais.read();
            }
        };
    }
    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(this.getInputStream(), StandardCharsets.UTF_8));
    }
    public String getBody() {
        return this.body;
    }
    @Override
    public String getParameter(String name) {
        return super.getParameter(name);
    }
    @Override
    public Map<String, String[]> getParameterMap() {
        return super.getParameterMap();
    }
    @Override
    public Enumeration<String> getParameterNames() {
        return super.getParameterNames();
    }
    @Override
    public String[] getParameterValues(String name) {
        return super.getParameterValues(name);
    }
}

 

/**
 * @desc: sql过滤器注册
 * @author: 毛会懂
 * @create: 2022-11-14 11:35:00
 **/
@Configuration
public class FilterConfiguration {

    @Autowired
    private SqlInjectionFilter filter;

    @Bean
    public FilterRegistrationBean<SqlInjectionFilter> sqlFilterRegistrationBean() {
        FilterRegistrationBean<SqlInjectionFilter> filterReg = new FilterRegistrationBean<>();
        filterReg.setFilter(filter);
        filterReg.addUrlPatterns("/*");
        filterReg.setOrder(1);
        return filterReg;
    }
}

 

posted on 2022-11-14 17:24  毛会懂  阅读(1707)  评论(0编辑  收藏  举报