فهرست منبع

修复过滤sql关键字不全可能导致sql注入的问题

Signed-off-by: 冻冰 <86124@qq.com>
冻冰 2 سال پیش
والد
کامیت
4eefce85b6

+ 14 - 2
mybatis-plus-core/src/main/java/com/baomidou/mybatisplus/core/toolkit/StringUtils.java

@@ -63,6 +63,12 @@ public final class StringUtils {
      */
     private static final Pattern REPLACE_BLANK = Pattern.compile("\\s*|\t|\r|\n");
 
+    /**
+     * sql注入黑名单关键词
+     * '"<>&*+=#-;
+     */
+    private static final Pattern SQL_INJECTION_BLACK = Pattern.compile("'|\"|\\<|\\>|&|\\*|\\+|=|#|-|;") ;
+
     /**
      * 判断字符串中是否全是空白字符
      *
@@ -594,10 +600,16 @@ public final class StringUtils {
     public static String sqlInjectionReplaceBlank(String str) {
         if (SqlInjectionUtils.check(str)) {
             /**
-             * 存在 SQL 注入,去除空白内容
+             * 1,一次过滤过滤空白字符,存在 SQL 注入,去除空白内容
              */
             Matcher matcher = REPLACE_BLANK.matcher(str);
-            return matcher.replaceAll("");
+            str = matcher.replaceAll("");
+
+            /**
+             * 2,二次过滤,过滤sql黑名单字符,存在 SQL 注入,去除空白内容
+             */
+            matcher = SQL_INJECTION_BLACK.matcher(str);
+            str = matcher.replaceAll("");
         }
         return str;
     }

+ 7 - 0
mybatis-plus/src/test/java/com/baomidou/mybatisplus/test/toolkit/StringUtilsTest.java

@@ -21,4 +21,11 @@ class StringUtilsTest {
         Assert.isTrue(StringUtils.isBlank("   "), "error not empty");
     }
 
+    @Test
+    void sqlInjectionBlack(){
+        String originalStr = "(select*from(select sleep(if(length(database())=13,3,0))union/**/select+1)a)" ;
+        Assert.isTrue("(selectfrom(selectsleep(if(length(database())13,3,0))union//select1)a)"
+            .equals(StringUtils.sqlInjectionReplaceBlank(originalStr)),"error");
+    }
+
 }