SqlUtil.java 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package com.backendsys.utils.v2;
  2. import cn.hutool.core.util.StrUtil;
  3. import com.backendsys.exception.CustException;
  4. /**
  5. * sql操作工具类
  6. */
  7. public class SqlUtil
  8. {
  9. /**
  10. * 定义常用的 sql关键字
  11. */
  12. public static String SQL_REGEX = "and |extractvalue|updatexml|sleep|exec |insert |select |delete |update |drop |count |chr |mid |master |truncate |char |declare |or |union |like |+|/*|user()";
  13. /**
  14. * 仅支持字母、数字、下划线、空格、逗号、小数点(支持多个字段排序)
  15. */
  16. public static String SQL_PATTERN = "[a-zA-Z0-9_\\ \\,\\.]+";
  17. /**
  18. * 限制orderBy最大长度
  19. */
  20. private static final int ORDER_BY_MAX_LENGTH = 500;
  21. /**
  22. * 检查字符,防止注入绕过
  23. */
  24. public static String escapeOrderBySql(String value)
  25. {
  26. if (StrUtil.isNotEmpty(value) && !isValidOrderBySql(value))
  27. {
  28. throw new CustException("参数不符合规范,不能进行查询");
  29. }
  30. if (StrUtil.length(value) > ORDER_BY_MAX_LENGTH)
  31. {
  32. throw new CustException("参数已超过最大限制,不能进行查询");
  33. }
  34. return value;
  35. }
  36. /**
  37. * 验证 order by 语法是否符合规范
  38. */
  39. public static boolean isValidOrderBySql(String value)
  40. {
  41. return value.matches(SQL_PATTERN);
  42. }
  43. /**
  44. * SQL关键字检查
  45. */
  46. public static void filterKeyword(String value)
  47. {
  48. if (StrUtil.isEmpty(value))
  49. {
  50. return;
  51. }
  52. String[] sqlKeywords = SQL_REGEX.split( "\\|");
  53. for (String sqlKeyword : sqlKeywords)
  54. {
  55. if (StrUtil.indexOfIgnoreCase(value, sqlKeyword) > -1)
  56. {
  57. throw new CustException("参数存在SQL注入风险");
  58. }
  59. }
  60. }
  61. }