JAVA审计中的SQL注入

admin 2023年1月17日19:03:25评论51 views字数 2519阅读8分23秒阅读模式

废话不多,直接看代码。

普通的Statement查询,在第三行可以看到,直接进行了拼接这就是典型的注入

Connection coon = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8","root","root");Statement statement = coon.createStatement();ResultSet resultSet = statement.executeQuery("select * from user where user="+拼接变量);List<Integer> lists = new ArrayList<>();while(resultSet.next()){    System.out.println(resultSet.getInt("id"));    System.out.println(resultSet.getString("user"));    System.out.println(resultSet.getString("pass"));    lists.add(resultSet.getInt("id"));}---------------------------------------------------------------------------------------------------------String sql = "select * from user where user= "+user;System.out.println(sql);List<Map<String,Object>> lists = jdbcTemplate.queryForList(sql);return lists;

预处理来防范SQL注入,在第二行使用了占位符,来防范预处理


Connection coon = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8","root","root");String sql = "select * from user where user = ?";PreparedStatement statement = coon.prepareStatement(sql);statement.setString(1,user);ResultSet resultSet = statement.executeQuery();List<String> lists = new ArrayList<>();while(resultSet.next()){    System.out.println(resultSet.getInt("id"));    System.out.println(resultSet.getString("user"));    System.out.println(resultSet.getString("pass"));    lists.add(resultSet.getString("user"));}return lists.toString();

Mybatis中的常见注入

代码1:

<select id="selectByNameAndPassword" parameterType="java.util.Map" resultMap="BaseResultMap">select id, username, password, rolefrom userwhere username = #{username,jdbcType=VARCHAR}and password = #{password,jdbcType=VARCHAR}</select>

代码2:

<select id="selectByNameAndPassword" parameterType="java.util.Map" resultMap="BaseResultMap">select id, username, password, rolefrom userwhere username = ${username,jdbcType=VARCHAR}and password = ${password,jdbcType=VARCHAR}</select>

1、#将传入的数据都当成一个字符串,会对自动传入的数据加一个双引号。
如:where username=#{username},如果传入的值是111,那么解析成sql时的值为where username="111", 如果传入的值是id,则解析成的sql为where username="id" 


2、$将传入的数据直接显示生成在sql中。
如:where username=${username},如果传入的值是111,那么解析成sql时的值为where username=111;
如果传入的值是;drop table user;,则解析成的sql为:select id, username, password, role from user where username=;drop table user;

3、#能够很大程度防止sql注入,$无法防止Sql注入。

4、$一般用于传入数据库对象,例如传入表名.

5、一般能用#的就别用$,若不得不使用${xxx}这样的参数,要手工地做好过滤工作,来防止sql注入攻击。

6、在MyBatis中,${xxx}这样格式的参数会直接参与SQL编译,从而不能避免注入攻击。但涉及到动态表名和列名时,只能使用${xxx}这样的参数格式。所以,这样的参数需要我们在代码中手工进行处理来防止注入。
【结论】在编写MyBatis的映射语句时,尽量采用#{xxx}这样的格式。若不得不使用${xxx}这样的参数,要手工地做好过滤工作,来防止SQL注入攻击。

JAVA审计中的SQL注入


原文始发于微信公众号(HACK安全):JAVA审计中的SQL注入

  • 左青龙
  • 微信扫一扫
  • weinxin
  • 右白虎
  • 微信扫一扫
  • weinxin
admin
  • 本文由 发表于 2023年1月17日19:03:25
  • 转载请保留本文链接(CN-SEC中文网:感谢原作者辛苦付出):
                   JAVA审计中的SQL注入http://cn-sec.com/archives/1428132.html

发表评论

匿名网友 填写信息