一、前言
相应大家多sql注入并不陌生,如“select * from users where username='' or 1=1 ”将前端登录用户输入‘’or 1=1内容,造成用户认证成功,这里我们主要分析mybatis基于${}时候引起的安全隐患
二、代码示例
1.如下所示mybatis映射配置SQL文件如下
<?xml version="1.0" encoding="UTF-8" ?>@b@<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > @b@@b@ <sql id="query_where">@b@ <where>@b@ 1=1@b@ <if test="status != null and status != ''">@b@ and STATUS in (${status})@b@ </if>@b@ <if test="mobile != null and mobile != ''">@b@ and MOBILE = #{mobile, jdbcType=VARCHAR}@b@ </if>@b@ @b@ </where>@b@ </sql>@b@ @b@ <select id="queryDataList" resultType="com.xwood.basic.web.responseResult.UserEntity" parameterType="java.util.Map" >@b@ select * from@b@ ( select ROWNUM RN, t.* from@b@ ( select @b@ u.CNAME cname,@b@ u.MOBILE mobile,@b@ u.NAME_TYPE nametype, @b@ u.STATUS status @b@ from TB_USER u @b@ <include refid="query_where" />@b@ order by u.CNAME asc) t ) WHERE RN <= #{endNum} AND RN > #{startNum}@b@ </select> @b@ @b@</mapper>
2. 如上其中and STATUS in (${status}),存在安全漏洞问题,在H5页面对于status的如参直接status=(select status from TB_USER)将会把后台所有的状态数据返回出来
3.修改示例如下,将${}改为#{}方式
<?xml version="1.0" encoding="UTF-8" ?>@b@<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > @b@@b@ <sql id="query_where">@b@ <where>@b@ 1=1@b@ <if test="status != null and status != ''">@b@ and STATUS in @b@ <foreach collection="mystatus" open="(" close=")" separator="," item="item">@b@ #{item,jdbcType=VARCHAR}@b@ </foreach>@b@ </if>@b@ <if test="mobile != null and mobile != ''">@b@ and MOBILE = #{mobile, jdbcType=VARCHAR}@b@ </if>@b@ @b@ </where>@b@ </sql>@b@ @b@ <select id="queryDataList" resultType="com.xwood.basic.web.responseResult.UserEntity" parameterType="java.util.Map" >@b@ select * from@b@ ( select ROWNUM RN, t.* from@b@ ( select @b@ u.CNAME cname,@b@ u.MOBILE mobile,@b@ u.NAME_TYPE nametype, @b@ u.STATUS status @b@ from TB_USER u @b@ <include refid="query_where" />@b@ order by u.CNAME asc) t ) WHERE RN <= #{endNum} AND RN > #{startNum}@b@ </select> @b@ @b@</mapper>
同时在调用的时候需要增加mystatus的入参,参考相关文章“通过mybatis的foreach..”