天天看点

序列化和反序列化序列化和反序列化概念反序列化漏洞

序列化和反序列化概念

当我们在php中创建了一个对象后,可以通过serialize()把这个对象转变成一个字符串,用于保存对象的值方便之后的传递与使用。与 serialize() 对应的,unserialize()可以从序列化后的结果中恢复对象(object)。

形象理解: 一个柜子为了好存储在运货车中,先把柜子拆成木板放进车中运输,到达目的地后再重新组装成柜子。柜子是object,木板是string,运货车是数据库等存储。柜子拆成木板是序列化,木板组成柜子是反序列化。

php中序列化函数是serialize(Object),反序列化是unserialize(String)

<?php
class test{
	public $id = 'Baize';
	public $name = 'Sec';
}
$test1 = new test();
//序列化,将类序列化成字符串,便于存储
$test2 = serialize($test1);
print_r($test2);
//反序列化,将字符串转换为类。
$test3 = unserialize($test2);
print_r($test3)
?>
           

结果:

O:4:“test”:2:{s:2:“id”;s:5:“Baize”;s:4:“name”;s:3:“Sec”;}

test Object ( [id] => Baize [name] => Sec )

反序列化漏洞

php中特殊的魔术函数:

<?php
header("Content-type: text/html; charset=utf-8");
class people
{
    public $name = "f1r3K0";
    public $age = '18';
    function __wakeup(){
        echo "这是 __wakeup()";
        echo "<br>";
    }
    function __construct(){
        echo "这是 __consrtuct()";
        echo "<br>";
    }
    function __destruct(){
        echo "这是 __destruct()";
        echo "<br>";
    }
    function __toString(){
        echo "这是 __toString";
        echo "<br>";
    }
}
$class =  new people();
$class_ser = serialize($class);  //序列化 
print_r($class_ser);            
$class_unser = unserialize($class_ser); //反序列化
print_r($class_unser);
?>
           
这是 __consrtuct()
O:6:"people":2:{s:4:"name";s:6:"f1r3K0";s:3:"age";s:2:"18";}
这是 __wakeup()
people Object ( [name] => f1r3K0 [age] => 18 ) 
这是 __destruct()
这是 __destruct()
           

可以看出unserialize函数是优先调用"__wakeup()"再进行的反序列化字符串,所以当传给 unserialize() 的参数可控时,我们可以通过传入一个"精心”构造的序列化字符串,从而控制对象内部的变量甚至是函数,然后让一些构造函数去执行,如下是利用wakeup构造函数。

<?php   
class test{
    var $id = 'Baize';	
	function __wakeup(){
		eval($this->id);
	}
}
$test1 = $_GET['string'];
$test2 = unserialize($test1);
?>
           

payload:

序列化和反序列化序列化和反序列化概念反序列化漏洞