• 防止SQL注入的四种方案


    一、什么是SQL注入?

    SQL注入即是指web应用程序对用户输入数据的合法性没有判断或过滤不严,攻击者可以在web应用程序中事先定义好的查询语句的结尾上添加额外的SQL语句,在管理员不知情的情况下实现非法操作,以此来实现欺骗数据库服务器执行非授权的任意查询,从而进一步得到相应的数据信息。

    SQL案列

    String sql = "delete from table1 where id = " + "id";

    这个id从请求参数中获取,若参数被拼接为:1001 or  1 = 1

    String sql = "delete from table1 where id = 1001 or 1 = 1";

    此时,数据库的数据都会被清空掉,后果非常严重.

    二、防止SQL注入方式

    这里总结4种:

    • PreparedStatement防止SQL注入

    • mybatis中#{}防止SQL注入

    • 对请求参数的敏感词汇进行过滤

    • nginx反向代理防止SQL注入

    1、PreparedStatement防止SQL注入

    PreparedStatement具有预编译功能,以上述SQL为例,使用PreparedStatement预编译后的SQL为:

    delete from table1 where id= ?

    此时SQL语句结构已固定,无论"?"被替换为任何参数,SQL语句只认为where后面只有一个条件,当再传入 1001 or  1 = 1时,语句会报错,从而达到防止SQL注入效果。

    2、mybatis中#{}防止SQL注入

    mybatis中#{}表达式防止SQL注入与PreparedStatement类似,都是对SQL语句进行预编译处理

    注意:

    #{} :参数占位符

    ${} :拼接替换符,不能防止SQL注入,一般用于

    • 传入数据库对象(如:数据库名称、表名)

    • order by  后的条件

    3、对请求参数的敏感词汇进行过滤

    这里是springboot的写法,如下:

    1. import org.springframework.context.annotation.Configuration;
    2. import javax.servlet.*;
    3. import javax.servlet.annotation.WebFilter;
    4. import java.io.IOException;
    5. import java.util.Enumeration;
    6. @WebFilter(urlPatterns = "/*",filterName = "sqlFilter")
    7. @Configuration
    8. public class SqlFilter implements Filter {
    9. @Override
    10. public void init(FilterConfig filterConfig) throws ServletException {}
    11. /**
    12. * @description sql注入过滤
    13. */
    14. @Override
    15. public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    16. ServletRequest request = servletRequest;
    17. ServletResponse response = servletResponse;
    18. // 获得所有请求参数名
    19. Enumeration<String> names = request.getParameterNames();
    20. String sql = "";
    21. while (names.hasMoreElements()){
    22. // 得到参数名
    23. String name = names.nextElement().toString();
    24. // 得到参数对应值
    25. String[] values = request.getParameterValues(name);
    26. for (int i = 0; i < values.length; i++) {
    27. sql += values[i];
    28. }
    29. }
    30. if (sqlValidate(sql)) {
    31. //TODO 这里直接抛异常处理,前后端交互项目中,请把错误信息按前后端"数据返回的VO"对象进行封装
    32. throw new IOException("您发送请求中的参数中含有非法字符");
    33. } else {
    34. filterChain.doFilter(request,response);
    35. }
    36. }
    37. /**
    38. * @description 匹配效验
    39. */
    40. protected static boolean sqlValidate(String str){
    41. // 统一转为小写
    42. String s = str.toLowerCase();
    43. // 过滤掉的sql关键字,特殊字符前面需要加\\进行转义
    44. String badStr =
    45. "select|update|and|or|delete|insert|truncate|char|into|substr|ascii|declare|exec|count|master|into|drop|execute|table|"+
    46. "char|declare|sitename|xp_cmdshell|like|from|grant|use|group_concat|column_name|" +
    47. "information_schema.columns|table_schema|union|where|order|by|" +
    48. "'\\*|\\;|\\-|\\--|\\+|\\,|\\//|\\/|\\%|\\#";
    49. //使用正则表达式进行匹配
    50. boolean matches = s.matches(badStr);
    51. return matches;
    52. }
    53. @Override
    54. public void destroy() {}
    55. }

    4、nginx反向代理防止SQL注入

    越来越多网站使用nginx进行反向代理,该层我们也可以进行防止SQL注入配置。

    将下面的Nginx配置文件代码放入到server块中,然后重启Nginx即可

    1. if ($request_method !~* GET|POST) { return 444; }
    2. #使用444错误代码可以更加减轻服务器负载压力。
    3. #防止SQL注入
    4. if ($query_string ~* (\$|'|--|[+|(%20)]union[+|(%20)]|[+|(%20)]insert[+|(%20)]|[+|(%20)]drop[+|(%20)]|[+|(%20)]truncate[+|(%20)]|[+|(%20)]update[+|(%20)]|[+|(%20)]from[+|(%20)]|[+|(%20)]grant[+|(%20)]|[+|(%20)]exec[+|(%20)]|[+|(%20)]where[+|(%20)]|[+|(%20)]select[+|(%20)]|[+|(%20)]and[+|(%20)]|[+|(%20)]or[+|(%20)]|[+|(%20)]count[+|(%20)]|[+|(%20)]exec[+|(%20)]|[+|(%20)]chr[+|(%20)]|[+|(%20)]mid[+|(%20)]|[+|(%20)]like[+|(%20)]|[+|(%20)]iframe[+|(%20)]|[\<|%3c]script[\>|%3e]|javascript|alert|webscan|dbappsecurity|style|confirm\(|innerhtml|innertext)(.*)$) { return 555; }
    5. if ($uri ~* (/~).*) { return 501; }
    6. if ($uri ~* (\\x.)) { return 501; }
    7. #防止SQL注入
    8. if ($query_string ~* "[;'<>].*") { return 509; }
    9. if ($request_uri ~ " ") { return 509; }
    10. if ($request_uri ~ (\/\.+)) { return 509; }
    11. if ($request_uri ~ (\.+\/)) { return 509; }
    12. #if ($uri ~* (insert|select|delete|update|count|master|truncate|declare|exec|\*|\')(.*)$ ) { return 503; }
    13. #防止SQL注入
    14. if ($request_uri ~* "(cost\()|(concat\()") { return 504; }
    15. if ($request_uri ~* "[+|(%20)]union[+|(%20)]") { return 504; }
    16. if ($request_uri ~* "[+|(%20)]and[+|(%20)]") { return 504; }
    17. if ($request_uri ~* "[+|(%20)]select[+|(%20)]") { return 504; }
    18. if ($request_uri ~* "[+|(%20)]or[+|(%20)]") { return 504; }
    19. if ($request_uri ~* "[+|(%20)]delete[+|(%20)]") { return 504; }
    20. if ($request_uri ~* "[+|(%20)]update[+|(%20)]") { return 504; }
    21. if ($request_uri ~* "[+|(%20)]insert[+|(%20)]") { return 504; }
    22. if ($query_string ~ "(<|%3C).*script.*(>|%3E)") { return 505; }
    23. if ($query_string ~ "GLOBALS(=|\[|\%[0-9A-Z]{0,2})") { return 505; }
    24. if ($query_string ~ "_REQUEST(=|\[|\%[0-9A-Z]{0,2})") { return 505; }
    25. if ($query_string ~ "proc/self/environ") { return 505; }
    26. if ($query_string ~ "mosConfig_[a-zA-Z_]{1,21}(=|\%3D)") { return 505; }
    27. if ($query_string ~ "base64_(en|de)code\(.*\)") { return 505; }
    28. if ($query_string ~ "[a-zA-Z0-9_]=http://") { return 506; }
    29. if ($query_string ~ "[a-zA-Z0-9_]=(\.\.//?)+") { return 506; }
    30. if ($query_string ~ "[a-zA-Z0-9_]=/([a-z0-9_.]//?)+") { return 506; }
    31. if ($query_string ~ "b(ultram|unicauca|valium|viagra|vicodin|xanax|ypxaieo)b") { return 507; }
    32. if ($query_string ~ "b(erections|hoodia|huronriveracres|impotence|levitra|libido)b") {return 507; }
    33. if ($query_string ~ "b(ambien|bluespill|cialis|cocaine|ejaculation|erectile)b") { return 507; }
    34. if ($query_string ~ "b(lipitor|phentermin|pro[sz]ac|sandyauer|tramadol|troyhamby)b") { return 507; }
    35. #这里大家根据自己情况添加删减上述判断参数,cURL、wget这类的屏蔽有点儿极端了,但要“宁可错杀一千,不可放过一个”。
    36. if ($http_user_agent ~* YisouSpider|ApacheBench|WebBench|Jmeter|JoeDog|Havij|GetRight|TurnitinBot|GrabNet|masscan|mail2000|github|wget|curl|Java|python) { return 508; }
    37. #同上,大家根据自己站点实际情况来添加删减下面的屏蔽拦截参数。
    38. if ($http_user_agent ~* "Go-Ahead-Got-It") { return 508; }
    39. if ($http_user_agent ~* "GetWeb!") { return 508; }
    40. if ($http_user_agent ~* "Go!Zilla") { return 508; }
    41. if ($http_user_agent ~* "Download Demon") { return 508; }
    42. if ($http_user_agent ~* "Indy Library") { return 508; }
    43. if ($http_user_agent ~* "libwww-perl") { return 508; }
    44. if ($http_user_agent ~* "Nmap Scripting Engine") { return 508; }
    45. if ($http_user_agent ~* "~17ce.com") { return 508; }
    46. if ($http_user_agent ~* "WebBench*") { return 508; }
    47. if ($http_user_agent ~* "spider") { return 508; } #这个会影响国内某些搜索引擎爬虫,比如:搜狗
    48. #拦截各恶意请求的UA,可以通过分析站点日志文件或者waf日志作为参考配置。
    49. if ($http_referer ~* 17ce.com) { return 509; }
    50. #拦截17ce.com站点测速节点的请求,所以明月一直都说这些测速网站的数据仅供参考不能当真的。
    51. if ($http_referer ~* WebBench*") { return 509; }
    52. #拦截WebBench或者类似压力测试工具,其他工具只需要更换名称即可。

    关注公众号”小猿数字化“,免费下载数字化建设方案。

  • 相关阅读:
    订单号传递规则
    First SP800-140Br1 Compliant FIPS 140-3 Certificates
    改进型RRT*算法的水下机器人三维全局路径规划
    技术盛宴!华云数据携六大议题亮相OpenInfra Days China
    关于亚马逊云科技云技能学习
    算法通关村第16关【青铜】| 滑动窗口思想
    web前端网页制作课作业:甜甜圈蛋糕店(HTML+CSS+JavaScript)
    IDEA安装JAVA_HOME报错、启动界面卡死的解决方案
    Java设计模式之单例模式
    引入指定字体
  • 原文地址:https://blog.csdn.net/sundehui01/article/details/132686620