注入攻击的本质就是数据被当做代码执行,注入成功两个关键原因
1.用户可以控制输入数据
2.原来执行的代码拼接了用户的输入数据
1.我们做个实验如下,先创建一张测试表
create table t_test_injection
(
id int not null,
constraint t_test_sql_pk
primary key (id)
);
正常查询语句如下,输入参数id值为1
select * from t_test_injection where id=1
然后构造注入语句,输入参数值改为"1;drop table t_test_injection"
select * from t_test_injection where id=1;drop table t_test_injection
通过语句执行监控发现,sql语句分为两次执行,一次为查询操作,另一次为删除table操作
schema_test0> select * from t_test_injection where id=1
[2021-08-17 17:07:47] 1 row retrieved starting from 1 in 113 ms (execution: 9 ms, fetching: 104 ms)
schema_test0> drop table t_test_injection
[2021-08-17 17:07:47] completed in 17 ms
2.我们再看另外一个例子,通过构造sql语句,规避掉本身查询限制,查询出所有数据
正常查询语句如下,输入参数id值为1,原本语义为查询出id为1的数据
select * from t_test_injection where id=1
构造注入语句,输入参数值改为"1 or 1=1"
select * from t_test_injection where id=1 or 1=1
通过语句执行监控发现,查询出了所有数据(表中准备了3条测试数据)
schema_test0> select * from t_test_injection where id=1 or 1=1
[2021-08-17 17:10:48] 3 rows retrieved starting from 1 in 140 ms (execution: 10 ms, fetching: 130 ms)
随意sql注入是非常危险的漏洞,存在数据泄露,数据库被破坏的风险,所以我们不仅需要防范sql注入,同时不要将数据库相关错误信息回显给用户。
3.再看一个如何获取数据库版本,我们先查看下我们现在使用的版本
select @@version from t_test_injection where id=1 ;
![](https://img.haomeiwen.com/i10034490/116e4a93a45a4e1a.png)
构造语句
select * from t_test_injection where id=1 and substring(@@version,1,1)=8
查询出结果,可以知道mysql大的版本,当然可以多次执行,获取到最终的mysql版本。
最后介绍下常用的sql注入工具,比如sqlmap。
4.防御sql注入手段
1.利用代码和数据隔离原则,采用预编译语句,绑定变量的方式
2.使用最小权限原则,为应用使用的数据库用户设置合理的权限
网友评论