当前位置:网站首页>[security attack and Defense] how much do you know about serialization and deserialization?
[security attack and Defense] how much do you know about serialization and deserialization?
2022-07-07 03:36:00 【Great safety home】
1. Serialization and deserialization
First, we need to understand the definition of serialization and deserialization , And the basic functions used in serialization and deserialization .
serialize : The process of converting an object into a sequence of bytes is called object serialization , Equivalent to archiving in the game .
PHP Serialization function in serialize()
**serialize()** Function for serialization object or Array , And return a string .serialize() Function serializes the object , It can be easily passed to other places that need it , And its The type and structure will not change .
| grammar | string serialize ( mixed $value ) |
|---|---|
| Parameter description | $value: Object or array to serialize . |
| Return value | Returns a string . |
Example :
<?php
highlight_file(__FILE__);
$sites=array('I', 'Like', 'PHP');
echo'<br/>';
var_dump(serialize($sites)); // Serialize this object
echo'<br/>';
classman{
public$name="xiaocui";
public$sex="man";
private$age=26;
}
$M=newman();// Create an object
var_dump(serialize($M)); // Serialize this object
?>
The output is :
string(47) "a:3:{i:0;s:1:"I";i:1;s:4:"Like";i:2;s:3:"PHP";}"
string(79) "O:3:"man":3:{s:4:"name";s:7:"xiaocui";s:3:"sex";s:3:"man";s:8:"manage";i:26;}"
Parameter description :
Serialization of arrays :
a Represents an array
3 There are... In the representative array 3 Elements
i Subscripts representing arrays
0 representative I Subscript value of element
s Representative elements I The data type of is character type
1 Representative elements I The length of is 1
object serialization :
O Representation is an object
3 Represents the class name man The length of
3 Represents the number of fields in the class
s Representative attribute name The type of is character type
4 Representative attribute name The length of
// And so on , Serialize the field contents in the string with { Start ,;} end
Deserialization : The process of restoring a byte sequence to an object is called deserialization of the object , Equivalent to reading files in the game .
【 Help safe learning , All resources are obtained from one by one 】
① Network Security Learning Route
②20 Penetration test ebook
③ Safe attack and defense 357 Page notes
④50 A security attack and defense interview guide
⑤ Safety red team penetration Kit
⑥ information gathering 80 Search syntax
⑦100 Three actual cases of vulnerability
⑧ Internal video resources of the safety factory
⑨ Calendar year CTF Analysis of the flag race
PHP Deserialization function in unserialize()
**unserialize()** Function is used to restore the serialized string to The original array or object The process of .**unserialize()** Function can quickly restore the serialized string , Used to complete its original function .
| grammar | mixed unserialize ( string $str ) |
|---|---|
| Parameter description | $str: Serialized string . |
| Return value | What is returned is the converted value , for integer、float、string、array or object. Returns... When not deserializable FALSE, And throw a reminder . |
Sample code :
<?php
highlight_file(__FILE__);
$sites=array('I', 'Like', 'PHP');
echo'<br/>';
echo$ser=serialize($sites).'<br/>'; // Serialize this object
var_dump(unserialize($ser)); // Deserialize the serialized string
echo'<br/>';
classman{
public$name="xiaocui";
public$sex="man";
private$age=26;
}
$M=newman();// Create an object
echo$ser=serialize($M).'<br/>'; // Serialize this object
var_dump(unserialize($ser)); // Deserialize the serialized string
?>
The output is :
a:3:{i:0;s:1:"I";i:1;s:4:"Like";i:2;s:3:"PHP";}
array(3) { [0]=>string(1) "I"[1]=>string(4) "Like"[2]=>string(3) "PHP"}
O:3:"man":3:{s:4:"name";s:7:"xiaocui";s:3:"sex";s:3:"man";s:8:"manage";i:26;}
object(man)#2 (3) { ["name"]=> string(7) "xiaocui" ["sex"]=> string(3) "man" ["age":"man":private]=> int(26) }
You can see the array or object deserialized above , There is no change with the original data .
The role of serialization and deserialization in the system
① Put the byte sequence of the object permanently on disk , It can be called at any time when necessary , Greatly save disk space .
② Byte sequence can be directly transmitted during transmission , Not the object , This can greatly improve the transmission rate .
In the business system , Some objects need to be serialized and stored , Get them out of memory space , In a file , For persistent storage . for example : When the user registers and logs into the system , User information such as user name , password ,cookie Wait for information to be stored through serialization , When the user logs in again, the serialized byte sequence is deserialized into the original object and used in memory , It can greatly save memory overhead .
2. Magic methods
PHP Put all in __( Two underscores ) Class methods at the beginning remain magic methods . So when defining a class method , In addition to the above magic methods , It is not recommended that __ The prefix .
PHP Common magic methods in
__construct()
have __construct The class of the function will call this method first every time a new object is created , It's suitable to do some initialization work before using objects .
Code example :
<?php
highlight_file(__FILE__);
classdemo{
public$name="xiaocui";
public$sex="man";
private$age=26;
publicfunction__construct()
{
echo"<br/>"." Call me when the class is instantiated !";
}
}
$D=newdemo(); // Instantiate objects
?>
Output results :
Call me when the class is instantiated !
__destruct()
This function will be executed when all references to an object are deleted or when the object is destroyed
Code example :
<?php
highlight_file(__FILE__);
class demo{
public $name="xiaocui";
public $sex="man";
private $age=26;
public function __construct()
{
echo "<br/>"." Call me when the class is instantiated !"."<br/>";
}
public function num($a,$b){
echo $c = $a + $b.'<br/>';
return $c;
}
public function __destruct(){
echo " Call me when all the methods in the class are destroyed !";
}
public function person($per){
echo "We are $per !!!".'<br/>';
}
}
$D=new demo(); // Instantiate objects
$D->num(5,6); // call num() Method
$D->person(man); // call person() Method
?>
Output results :
Call me when the class is instantiated !
11
Weareman!!!
Call me when all the methods in the class are destroyed !
The above output results can directly see the execution order of the code :__construct()=>num(5,6)=>person(nanren)=>__destruct()
When instantiating an object, first execute the construction method __construct(), Then, execute the instance in the class num()、person(), When all methods are executed and destroyed , Finally, call the destructor method __destruct().
__wakeup()
In the use of unserialize() when , Will check if there is one __wakeup() Magic methods . If there is , Then the method will be called first , Prepare resources needed for objects in advance .
Code example :
<?php
highlight_file(__FILE__);
classdemo{
public$name="xiaocui";
protected$sex="man";
private$age=26;
publicfunction__construct()
{
echo"<br/>"." Call me when the class is instantiated !"."<br/>";
}
publicfunction__destruct(){
echo"<br/>"." Call me when all the methods in the class are destroyed !"."<br/>";
}
publicfunction__wakeup()
{
echo"<br/>"." When the sequence is reversed, first call me !".'<br/>';
}
}
$D=newdemo(); // Instantiate objects
echo$ser=serialize($D); // Serializing objects $D
var_dump(unserialize($ser)); // Deserialize string $ser
?>
Output results :
because $age For private property , White space characters will be added before and after serialization %00, The original character length is 7, If you add white space characters on both sides, the character length will become 9
Call me when the class is instantiated !
O:4:"demo":3:{s:4:"name";s:7:"xiaocui";s:6:"*sex";s:3:"man";s:9:"demoage";i:26;}
Call me when the sequence is reversed !
object(demo)#2
(3) { ["name"]=> string(7) "xiaocui" ["sex":protected]=>
string(3) "man" ["age":"demo":private]=> int(26) }
Call me when all the methods in the class are destroyed !
Call me when all the methods in the class are destroyed !
The above output results can directly see the execution order of the code :__construct()=>serialize($D)=>__wakeup()=>unserialize($ser)=>__destruct()=>__destruct()
When instantiating an object, first execute the construction method __construct(), Then the serialization is performed serialize($D), Then, before deserialization, execute __wakeup() Method , Then perform deserialization unserialize($ser), When all methods are executed and destroyed, execute finally __destruct() destructor , After deserialization, the original serialized string is restored and executed again __destruct().
__toString()
__toString() Method is used to define how a class is treated as a string .
Sample code :
<?php
highlight_file(__FILE__);
class demo{
public $name="xiaocui";
protected $sex="man";
private $age=26;
public function __construct()
{
echo "<br/>"." Call me when the class is instantiated !"."<br/>";
}
public function __destruct(){
echo "<br/>"." Call me when all the methods in the class are destroyed !"."<br/>";
}
public function __wakeup()
{
echo "<br/>"." Call me when the sequence is reversed !".'<br/>';
}
public function __toString(){
return "<br/>"." Class is called when it is treated as a string !"."<br/>";
}
}
$D=new demo(); // Instantiate objects
echo $D; // Class is output as a string
?>
Output results :
Call me when the class is instantiated !
Class is called when it is treated as a string !
Call me when all the methods in the class are destroyed !
The above output results can be seen , When a class is treated as a string echo when ,__toString() Method is called and executed .
If there is no... In this class __toString() Method , Conduct echo When the output ,PHP Will throw fatal errors , Error is as follows :
Catchablefatalerror: ObjectofclassdemocouldnotbeconvertedtostringinD:\XXXX\phpstudy_pro\WWW\two\demo.phponline30
__sleep()
In the use of serialize() Function time , The program will check whether there is a __sleep() Magic methods . If there is , Then the method will be called first , And then perform the serialization operation .
__sleep() Methods are often used to submit uncommitted data , Or similar cleaning operations . meanwhile , If there are some big objects , But it doesn't need to be all saved , This function has a good cleaning effect .
Sample code :
<?php
highlight_file(__FILE__);
class demo{
public $name="xiaocui";
protected $sex="man";
private $age=26;
public function __construct()
{
echo "<br/>"." Call me when the class is instantiated !"."<br/>";
}
public function __destruct(){
echo "<br/>"." Call me when all the methods in the class are destroyed !"."<br/>";
}
public function __wakeup()
{
echo "<br/>"." Call me when the sequence is reversed !".'<br/>';
}
public function __sleep(){
echo "<br/>"." Call me when the sequence !".'<br/>';
return array("name","sex","age"); // Here you have to return a number , The element inside represents the name of the returned attribute
}
}
$D=new demo(); // Instantiate objects
echo $ser = serialize($D); // Serializing objects
?>
Output results :
Call me when the class is instantiated !
Call me when the sequence !
O:4:"demo":3:{s:4:"name";s:7:"xiaocui";s:6:"*sex";s:3:"man";s:9:"demoage";i:26;}
Call me when all the methods in the class are destroyed !
The above output results can be seen , When the class is serialized, it first calls __sleep() Method , This function must return a value . If the function does not return properties , When serializing, the attribute will be cleared .
__invoke()
When trying to call an object as a function ,__invoke Method will be called automatically .( This feature only exists in PHP 5.3.0 And above are valid .)
Code example :
<?php
highlight_file(__FILE__);
class demo{
public $name="xiaocui";
protected $sex="man";
private $age=26;
public function __construct()
{
echo "<br/>"." Call me when the class is instantiated !"."<br/>";
}
public function __destruct(){
echo "<br/>"." Call me when all the methods in the class are destroyed !"."<br/>";
}
public function __wakeup()
{
echo "<br/>"." Call me when deserializing !".'<br/>';
}
public function __sleep(){
echo "<br/>"." Call me when serializing !".'<br/>';
return array("name","sex","age");
}
public function __invoke()
{
echo "<br/>"." When you call an object in a functional way, you will call me !".'<br/>';
}
}
$D=new demo(); // Instantiate objects
$D(); // Call the object as a function
?>
Results output :
Call me when the class is instantiated !
When you call an object in a functional way, you will call me !
Call me when all the methods in the class are destroyed !
The above results can be seen when using the method of a function to call an object , Will call __invoke() Method .
If there is no such method in the class , that PHP Fatal errors will be reported , as follows :
Fatalerror:
UncaughtError:
FunctionnamemustbeastringinD:\xxxxx\phpstudy_pro\WWW\two\demo.php:42Stacktrace:
#0 {main} thrown in D:\xxxxx\phpstudy_pro\WWW\two\demo.php on line 42
__call()
When calling a nonexistent or inaccessible method in an object ,__call Will be called .
Code example :
<?php
highlight_file(__FILE__);
class demo{
public $name="xiaocui";
protected $sex="man";
private $age=26;
public function __construct()
{
echo "<br/>"." Call me when the class is instantiated !"."<br/>";
}
public function num($a,$b){
echo "<br/>".$c = $a + $b.'<br/>';
return $c;
}
public function __destruct(){
echo "<br/>"." Call me when all the methods in the class are destroyed !"."<br/>";
}
public function person($per){
echo "<br/>"."We are $per !!!".'<br/>';
}
public function __wakeup()
{
echo "<br/>"." Call me when deserializing !".'<br/>';
}
public function __sleep(){
echo "<br/>"." Call me when the sequence !".'<br/>';
return array("name","sex","age");
}
public function __call($arg1,$arg2){
echo "<br/>"." Call me when an object calls a method that does not exist or is inaccessible !".'<br/>';
}
}
$D=new demo(); // Instantiate objects
$D->num1(1,2); // Call a method that doesn't exist
?>
Results output :
Call me when the class is instantiated !
Call me when an object calls a method that does not exist or is inaccessible !
Call me when all the methods in the class are destroyed !
__set()
When assigning a value to an inaccessible property ,__set Will be called .
Code example :
<?php
highlight_file(__FILE__);
class demo extends demo1{
public $name="xiaocui";
protected $sex="man";
private $age=26;
public function __construct()
{
echo "<br/>"." Call me when the class is instantiated !"."<br/>";
}
public function __destruct(){
echo "<br/>"." Call me when all the methods in the class are destroyed !"."<br/>";
}
public function person($per){
echo "<br/>"."We are $per !!!".'<br/>';
}
public function __set($arg1,$arg2){
echo "<br/>"." Call me when assigning a value to a nonexistent or inaccessible property !"."<br/>";
}
}
class demo1{
private $weight;
public $height;
public function people(){
echo $this->weight;
echo $this->height;
}
}
$D=new demo(); // Instantiate objects
$D->weight=74; // Assign values to inaccessible properties
?>
Output results :
Call me when the class is instantiated !
Call me when assigning a value to a nonexistent or inaccessible property !
Call me when all the methods in the class are destroyed !
__isset()
Call on inaccessible properties isset() or empty() when ,__iset() Will be called .
__unset()
Call on inaccessible properties unset() when ,__unset() Will be called .
__get()
When reading the value of an inaccessible property ,__get Will be called .
Code example :
<?php
highlight_file(__FILE__);
class demo extends demo1{
public $name="xiaocui";
protected $sex="man";
private $age=26;
public function __construct()
{
echo "<br/>"." Call me when the class is instantiated !"."<br/>";
}
public function __destruct(){
echo "<br/>"." Call me when all the methods in the class are destroyed !"."<br/>";
}
public function __get($arg1){
echo "<br/>"." Call me when reading non-existent or inaccessible properties !";
}
}
class demo1{
private $weight = 0;
public $height;
public function people(){
echo $this->weight;
echo $this->height;
}
}
$D=new demo(); // Instantiate objects
$D->weight; // Read inaccessible properties in the parent class
?>
Output results :
Call me when the class is instantiated !
Call me when reading non-existent or inaccessible properties !
Call me when all the methods in the class are destroyed !
3. Deserialization vulnerability
3.1 Deserialization exploit condition
① unserialize() The parameters in the function are controllable
② There are classes available , And there are magic methods in the class
Code example 1:
<?php
highlight_file(__FILE__);
class demo
{
public $arg1 = "0";
public function __destruct()
{
echo $this->arg1; // Output user passed arg1 value
}
}
$a=$_GET['arg']; // Receive the... Transmitted by the front end arg1 Variable
$unser = unserialize($a); // Deserialize passed arg1
?>
The above code meets two conditions of deserialization vulnerability ,arg Parameter controllable , That is to say unserialize() The parameters of the function are controllable ; There are classes available demo, And demo There are magic methods available in class __destruct(), However __destruct() Magic method used echo Output variables arg.
adopt arg Parameters , Construct serialization string , adopt unserialize() Function , Finally through __destruct() Magic method output variable , cause XSS.


Sample code 2
<?php
highlight_file(__FILE__);
class demo
{
public $arg1 = "0";
public function __destruct()
{
eval($this->arg1); //eval() To execute the user passed arg1 value
}
}
$a=$_GET['arg']; // Receive the... Transmitted by the front end arg1 Variable
$unser = unserialize($a); // Deserialize passed arg1
var_dump($unser);
?>
If magic methods exist eval(), And the parameters are controllable , Then by constructing a serialized string , Through deserialization vulnerability RCE.

3.2 __wakeup() Function bypasses
When the attributes of the passed object are larger than those of the actual object during serialization ,__wakeup() Magic methods will not be performed , This leads to bypassing .
PHP edition <=5.6.25 perhaps PHP edition <=7.0.11
Sample code :
<?php
highlight_file(__FILE__);
class demo
{
public $arg1 = "0";
public function __destruct()
{
eval($this->arg1); //eval() To execute the user passed arg1 value
}
public function __wakeup(){
foreach(get_object_vars($this) as $k => $v) {
$this->$k = ''; // Traverse the passed parameters , All assignments are empty
}
}
}
$a=$_GET['arg']; // Receive the... Transmitted by the front end arg1 Variable
$unser = unserialize($a); // Deserialize passed arg1
var_dump($unser);
?>
If the attribute value is the same as the actual attribute value of the object , Will be executed during deserialization __wakeup() Function replaces the passed in variable value with null .
If the property value is set to be greater than the actual object property value, it will bypass __wakeup() function .
边栏推荐
- Jerry's broadcast has built-in flash prompt tone to control playback pause [chapter]
- About Estimation Statistics
- sshd[12282]: fatal: matching cipher is not supported: aes256- [email protected] [preauth]
- 21.(arcgis api for js篇)arcgis api for js矩形采集(SketchViewModel)
- VHDL implementation of arbitrary size matrix addition operation
- Huawei and Xiaomi "copy each other"
- VHDL implementation of arbitrary size matrix multiplication
- [untitled]
- pip只下载不安装
- 【达梦数据库】添加自动收集统计信息的任务
猜你喜欢

Baidu map JS development, open a blank, bmapgl is not defined, err_ FILE_ NOT_ FOUND

Restcloud ETL Community Edition June featured Q & A

qt-线程等01概念

Ubuntu 20 installation des enregistrements redisjson

Mathematical induction and recursion

Leetcode-02 (linked list question)

25.(arcgis api for js篇)arcgis api for js线修改线编辑(SketchViewModel)

Create applet from 0

数学归纳与递归

VHDL implementation of arbitrary size matrix multiplication
随机推荐
Under the tide of "going from virtual to real", Baidu AI Cloud is born from real
如何替换模型的骨干网络(backbone)
[dream database] add the task of automatically collecting statistical information
2022.6.28
1200.Minimum Absolute Difference
[untitled]
An error in SQL tuning advisor ora-00600: internal error code, arguments: [kesqsmakebindvalue:obj]
SSL证书部署
PHP lightweight Movie Video Search Player source code
Free PHP online decryption tool source code v1.2
VHDL implementation of single cycle CPU design
VHDL实现任意大小矩阵乘法运算
Decoration design enterprise website management system source code (including mobile source code)
R数据分析:cox模型如何做预测,高分文章复现
Variables, process control and cursors (MySQL)
“去虚向实”大潮下,百度智能云向实而生
Mathematical induction and recursion
Restcloud ETL Community Edition June featured Q & A
Mobile measurement and depth link platform - Branch
HMS core machine learning service creates a new "sound" state of simultaneous interpreting translation, and AI makes international exchanges smoother