当前位置:网站首页>[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 .
边栏推荐
- About Estimation Statistics
- 【达梦数据库】备份恢复后要执行两个sql语句
- Sorting operation partition, argpartition, sort, argsort in numpy
- Graphical tools package yolov5 and generate executable files exe
- 注意力机制原理
- SSL certificate deployment
- 树莓派设置静态ip
- The latest 2022 review of "small sample deep learning image recognition"
- Optimization of application startup speed
- 大白话高并发(二)
猜你喜欢
Decoration design enterprise website management system source code (including mobile source code)
小程序能运行在自有App中,且实现直播和连麦?
About Tolerance Intervals
leetcode
Code quality management
24. (ArcGIS API for JS) ArcGIS API for JS point modification point editing (sketchviewmodel)
代码质量管理
源代码保密的意义和措施
[safe office and productivity application] Shanghai daoning provides you with onlyoffice download, trial and tutorial
Tencent cloud native database tdsql-c was selected into the cloud native product catalog of the Academy of communications and communications
随机推荐
leetcode
HDU 4337 King Arthur&#39; S Knights it outputs a Hamiltonian circuit
unrecognized selector sent to instance 0x10b34e810
Domcontentloaded and window onload
Flink task exit process and failover mechanism
Under the tide of "going from virtual to real", Baidu AI Cloud is born from real
1200.Minimum Absolute Difference
Calculation of time and space complexity (notes of runners)
Set static IP for raspberry pie
图形化工具打包YOLOv5,生成可执行文件EXE
input_ delay
Stored procedures and functions (MySQL)
HMS Core 机器学习服务打造同传翻译新“声”态,AI让国际交流更顺畅
My brave way to line -- elaborate on what happens when the browser enters the URL
CMB's written test - quantitative relationship
如何替换模型的骨干网络(backbone)
函数重入、函数重载、函数重写自己理解
qt-线程等01概念
21.(arcgis api for js篇)arcgis api for js矩形采集(SketchViewModel)
[colmap] 3D reconstruction with known camera pose