Mybatis的SQL注入问题学习

Mybatis的SQL语句可以基于注解的方式写在类方法上面,更多的是以xml的方式写到xml文件。Mybatis中SQL语句需要我们自己手动编写或者用generator自动生成。编写xml文件时,MyBatis支持两种参数符号,一种是#,另一种是$。比如:

<select id="queryInfo"  resultType="store.pejkin.News">
  SELECT * FROM NEWS WHERE ID = #{id}
</select>

  #使用预编译,$使用拼接SQL。

Mybatis框架下易产生SQL注入漏洞的情况

1、模糊查询

Select * from news where title like ‘%#{title}%’       编译错误
Select * from news where title like ‘%${title}%’       存在sql漏洞
select * from news where tile like concat(‘%’,#{title}, ‘%’) 
或者
select * from news where tile like '%'||#{deptName}||'%'

  

2、in 之后的多个参数

Select * from news where id in (#{ids})          编译错误


Select * from news where
id in
<foreach collection="ids" item="item" open="("separatosr="," close=")">
#{ids}
</foreach>

  

3、order by

这种场景应当在Java层面做映射,设置一个字段/表名数组,仅允许用户传入索引值。这样保证传入的字段或者表名都在白名单里面。需要注意的是在mybatis-generator自动生成的SQL语句中,order by使用的也是$,而like和in没有问题

原文地址:https://www.cnblogs.com/torchstar/p/14989470.html