All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.hecloud.runtime.database.validator.InjectionAssert Maven / Gradle / Ivy

There is a newer version: 1.0.8
Show newest version
package com.hecloud.runtime.database.validator;

import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.regex.Pattern;

/**
 * SQL注入校验器
 *
 * @author LoveinBJ
 */
public class InjectionAssert {

    private static String paramInjectRegex = "(?:')|(?:--)|(/\\*(?:.|[\\n\\r])*?\\*/)|(\\b(select|update|union|and|or|delete|insert|trancate|char|substr|ascii|declare|exec|count|master|into|drop|execute)\\b)";
    private static String queryInjectRegex = "(?:--)|(/\\*(?:.|[\\n\\r])*?\\*/)|(\\b(create|alter|update|delete|insert|trancate|drop|execute)\\b)";
    private static Pattern paramInjectPattern = Pattern.compile(paramInjectRegex, Pattern.CASE_INSENSITIVE);
    private static Pattern queryInjectPattern = Pattern.compile(queryInjectRegex, Pattern.CASE_INSENSITIVE);

    /**
     * 验证参数属性和属性值是否包括注入字段
     *
     * @param params  参数
     * @param message 返回消息
     */
    public static void assertValidate(Map params, String message) {
        Optional.ofNullable(params).ifPresent(parameters -> parameters.forEach((key, value) -> {
            if (StringUtils.hasText(key) && paramInjectPattern.matcher(key).find()) {
                throw new IllegalArgumentException(message);
            }
            if (Objects.nonNull(value) && paramInjectPattern.matcher(value.toString()).find()) {
                throw new IllegalArgumentException(message);
            }
        }));
    }

    /**
     * 判断当前sql是否存在sql注入
     *
     * @param sql     SQL语句
     * @param message 返回消息
     */
    public static void assertValidate(String sql, String message) {
        Assert.hasLength(sql, "SQL语句为空!");
        if (queryInjectPattern.matcher(sql).find()) {
            throw new IllegalArgumentException(message);
        }
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy