SQL注入是项目开发中很重要的一个概念,初级中级面试的概率非常高,需要重点掌握!
1 准备工作
本次演示使用的是目前最热门的Java快速开发架构:SpringBoot2.3.4 + Mybatis + Mysql8
先准备一张测试表:
drop table if exists `test`;
create table `test` (
id bigint not null comment 'id',
name varchar(50) comment '名称',
primary key (`id`)
) engine=innodb default charset=utf8mb4 comment='测试';
insert into `test` (id, name) values (1, 'test1');
insert into `test` (id, name) values (2, 'test2');
TestController:
@RequestMapping("/find")
public List<Test> test(@RequestBody Map<String, String> map) {
return testService.find(map.get("id"));
}
TestService:
public List<Test> find(String id) {
return testMapper.find(id);
}
TestMapper.java:
public List<Test> find(@Param("id") String id);
TestMapper.xml:
<select id="find" resultType="com.jiawa.demo.domain.Test">
select `id`, `name` from `test` where id = #{id}
</select>
测试:test.http(使用IDEA自带的HttpClient)
GET http://localhost:8080/test/find
Content-Type: application/json
Accept: application/json
{
"id": "1" # 改为3则查不出数据,表里没id=3
}
测试结果:查出id=1的数据,修改test.http,改为3,则查不出数据
[ { "id": "1", "name": "test1" }]
上面这些都是正常的代码,演示结果也正常
2 注入演示:获取数据
由于手滑,把xml里的#,写成了$
<select id="find" resultType="com.jiawa.demo.domain.Test">
select `id`, `name` from `test` where id = ${id}
</select>
测试正常值id=1,能查出数据,但是如果脚本参数改为这样
GET http://localhost:8080/test/find
Content-Type: application/json
Accept: application/json
{
"id": "3 or 1=1"
}
结果:表里所有的数据全部都查出来了!
[ { "id": "1", "name": "test1" }, { "id": "2", "name": "test2" }]
3 注入演示:删除数据
现在我在数据库连接里增加一个参数,xml里还是手滑,写成$:
allowMultiQueries=true (不知道怎么看开启的可以看视频)
...
select `id`, `name` from `test` where id = ${id}
脚本写成这样:
GET http://localhost:8080/test/find
Content-Type: application/json
Accept: application/json
{
"id": "1; delete from test"
}
结果:表里的数据全没了!!!
4 如何预防
总结如下三点,具体可以看视频:
- 使用#代替$,使用PreparedStatement代替SQL拼接
- 后端记得做参数校验,后端永远不要相信前端
- 打开allowMultiQueries要慎重,尽量不要打开
5 高频面试题
Q:什么是SQL注入?如何预防?
**A:**通过输入特定的参数来改变SQL意图,可以将演示的注入现象简述一遍。如何预防见上面第4点。
****Q:Mybatis里#和$的区别是什么?
**A:**这两个都可以用来传递变量。#对应会变成占位符"?",可防止注入。$是简单的值传递,是啥填啥。
****Q:Mybatis和JDBC什么关系?
**A:**或问Mybatis原理是什么?Mybatis就是封装了JDBC。
****Q:SQL日志里的“?”是什么作用?
**A:**或问:JDBC中的“?”是什么作用?"?"是Mysql中预编译功能的占位符。
关于Mysql的预编译的讲解,敬请关注公众号:甲蛙全栈!
——————_THE END _——————