Java最新SQL注入原因以及预防方案(易理解)

开发 后端 数据库
在现有的框架中sql防注入已经做得很好了,我们需要做的就是尽量不要使用sql拼接调用

[[374950]]

 前沿

在现有的框架中sql防注入已经做得很好了,我们需要做的就是尽量不要使用sql拼接调用

java sql注入原因以及预防方案(易理解)

1. SQL注入

1.1 原理

SQL注入是通过客户端的输入把SQL命令注入到一个应用的数据库中,从而执行恶意的SQL语句。

1.2 演示

1.2.1 案例1

有一个登录框,需要 输入用户名和密码 ,然后我们的密码输入 'or '123' = '123 这样的。我们在查询用户名和密码是否正确的时候,本来执行的sql语句是:select * from user where username = '' and password = ''. 这样的sql语句,现在我们输入密码是如上这样的,然后我们会通过参数进行拼接,拼接后的sql语句就是:

select * from user where username = '' and password = ' ' or '123' = '123 ';这样的了,那么会有一个or语句,只要这两个有一个是正确的话,就条件成立,因此 123 = 123 是成立的。因此验证就会被跳过。这只是一个简单的例子,

1.2.2 案例2

密码比如是这样的:'; drop table user;, 这样的话,那么sql命令就变成了:

select * from user where username = '' and password = ''; drop table user;', 那么这个时候我们会把user表直接删除了。

1.3 防范

1.3.1 前端

前端表单进行参数格式控制;

1.3.2 后端

  • 我们可以使用预编译语句(PreparedStatement,这 样的话即使我们使用sql语句伪造成参数,到了服务端的时候,这个伪造sql语句的参数也只是简单的字符,并不能起到攻击的作用。
  • 使用正则表达式过滤传入的参数

注意: 永远也不要把未经检查的用户输入的值直接传给数据库

  • java中的验证字符串是否包含sql的判断
  1. package cn.javanode.thread; 
  2.  
  3. import java.util.regex.Pattern; 
  4.  
  5. /** 
  6.  * @author xgt(小光头) 
  7.  * @version 1.0 
  8.  * @date 2021-1-8 11:48 
  9.  */ 
  10. public class CheckSqlDemo { 
  11.  
  12.     /**正则表达式**/ 
  13.     private static String reg = "(?:')|(?:--)|(/\\*(?:.|[\\n\\r])*?\\*/)|" 
  14.             + "(\\b(select|update|union|and|or|delete|insert|trancate|char|into|substr|ascii|declare|exec|count|master|into|drop|execute)\\b)"
  15.  
  16.  
  17.     private static Pattern sqlPattern = Pattern.compile(reg, Pattern.CASE_INSENSITIVE); 
  18.  
  19.     private static boolean isValid(String str) { 
  20.         if (sqlPattern.matcher(str).find()) 
  21.         { 
  22.             System.out.println("未能通过过滤器:str=" + str); 
  23.             return false
  24.         } 
  25.         return true
  26.     } 
  27.  
  28.     public static void main(String[] args) { 
  29.         System.out.println(isValid("tongji_user_add")); 
  30.     } 
  31.  

 补充

PreparedStatement是如何防止SQL注入的?

1. 拼接参数(sql注入)

  1. Connection connection = DriverManager.getConnection(DB_URL, USER, PASS); 
  2.         PreparedStatement preparedStatement = connection.prepareStatement(sql);         
  3.         String param = "'test' or 1=1"
  4.         String sql = "select file from file where name = " + param; // 拼接SQL参数 
  5.         ResultSet resultSet = preparedStatement.executeQuery(); 
  6.         System.out.println(resultSet.next()); 

 输出结果为 true ,DB中执行的SQL为

  1. -- 永真条件1=1成为了查询条件的一部分,可以返回所有数据,造成了SQL注入问题 
  2. select file from file where name = 'test' or 1=1 

 2. setString (防注入) 

  1. Connection connection = DriverManager.getConnection(DB_URL, USER, PASS); 
  2.         PreparedStatement preparedStatement = connection.prepareStatement(sql);     
  3.         preparedStatement.setString(1,account);//设置参数 
  4.         preparedStatement.setString(2,password); 
  5.         ResultSet resultSet = preparedStatement.executeQuery();//执行查询sql,获取结果集 

 输出结果为 false ,DB中执行的SQL为 

  1. select file from file where name = '\'test\' or 1=1' 

我们可以看到输出的 SQL是把整个参数用引号包起来,并把参数中的引号作为转义字符,从而避免了参数也作为条件的一部分

3. 源码分析

结论 

  • preparedStatement.setString 会判断当前参数的符号是否需要转义,是的话加的转义符
  • 如果不需要,则直接加上引号

  1. //完整代码 
  2. public void setString(int parameterIndex, String x) throws SQLException { 
  3.        synchronized (checkClosed().getConnectionMutex()) { 
  4.            // if the passed string is nullthen set this column to null 
  5.            if (x == null) { 
  6.                setNull(parameterIndex, Types.CHAR); 
  7.            } else { 
  8.                checkClosed(); 
  9.  
  10.                int stringLength = x.length(); 
  11.  
  12.                if (this.connection.isNoBackslashEscapesSet()) { 
  13.                    // Scan for any nasty chars 
  14.                    // 判断是否需要转义 
  15.                    boolean needsHexEscape = isEscapeNeededForString(x, stringLength); 
  16.  
  17.                    if (!needsHexEscape) { 
  18.                        byte[] parameterAsBytes = null
  19.  
  20.                        StringBuilder quotedString = new StringBuilder(x.length() + 2); 
  21.                        quotedString.append('\''); 
  22.                        quotedString.append(x); 
  23.                        quotedString.append('\''); 
  24.  
  25.                        if (!this.isLoadDataQuery) { 
  26.                            parameterAsBytes = StringUtils.getBytes(quotedString.toString(), this.charConverter, this.charEncoding, 
  27.                                    this.connection.getServerCharset(), this.connection.parserKnowsUnicode(), getExceptionInterceptor()); 
  28.                        } else { 
  29.                            // Send with platform character encoding 
  30.                            parameterAsBytes = StringUtils.getBytes(quotedString.toString()); 
  31.                        } 
  32.  
  33.                        setInternal(parameterIndex, parameterAsBytes); 
  34.                    } else { 
  35.                        byte[] parameterAsBytes = null
  36.  
  37.                        if (!this.isLoadDataQuery) { 
  38.                            parameterAsBytes = StringUtils.getBytes(x, this.charConverter, this.charEncoding, this.connection.getServerCharset(), 
  39.                                    this.connection.parserKnowsUnicode(), getExceptionInterceptor()); 
  40.                        } else { 
  41.                            // Send with platform character encoding 
  42.                            parameterAsBytes = StringUtils.getBytes(x); 
  43.                        } 
  44.  
  45.                        setBytes(parameterIndex, parameterAsBytes); 
  46.                    } 
  47.  
  48.                    return
  49.                } 

 【编辑推荐】

 

责任编辑:姜华 来源: 今日头条
相关推荐

2011-10-19 10:47:56

2010-04-26 16:31:09

Oracle SQL

2009-09-23 10:43:22

2012-11-08 17:02:58

2016-09-06 13:40:20

2009-09-17 12:49:31

2010-09-14 16:28:52

2019-01-15 09:24:07

2010-06-30 17:56:06

2012-11-14 17:18:58

2019-09-17 10:06:46

数据库程序员网络安全

2010-12-20 16:04:30

2014-10-08 10:01:06

2020-08-30 14:34:42

Java语言安全编码web安全

2013-01-10 18:00:09

2011-07-12 10:38:10

2016-09-28 16:38:47

2013-10-02 17:56:55

苏宁易购SA权限SQL注入

2017-08-10 10:23:59

2011-12-30 11:04:14

点赞
收藏

51CTO技术栈公众号