当前位置:网站首页>[deserialization vulnerability-01] Introduction to serialization and deserialization
[deserialization vulnerability-01] Introduction to serialization and deserialization
2022-07-24 11:20:00 【Like the wind 9】
Catalog
1 background
(1) stay PHP in , Each class is defined in keyword class start , Followed by the class name , Followed by a pair of curly braces , It contains Definition of class properties and methods .
(2) A class can contain its own attribute ( Constant , Variable ) And methods ( function ).
(3) Because of the instantiation object of the class More abstract , Inconvenient for transmission and storage .
tips( Classes and objects ):
- Class is class, The object is object; for instance , Cars belong to a large category , The major categories are divided into sub categories, such as bicycles 、 truck ; And a specific car is an object .
2 Definition of serialization and deserialization
The serialization and deserialization processes are in php、python And many other languages .
- serialize : Program will Object state Convert to A sequence of bytes that can be stored or transmitted The process of ( The process of converting an object's state to storable or transportable )
- Deserialization : The program put A sequence of bytes stored or transmitted Revert to object The process of .
- The core idea : Save and rebuild the object state .
PHP Serialization and deserialization in , It's all about serialize() and unserialize() The expansion of two functions .
3 Functions and advantages
The meaning of serialization : When passing and saving objects , To ensure the integrity and transitivity of objects , Program will Object into an ordered byte stream , To save in a local file , And it can cross platform between processes in a specific format 、 Communicate safely . For instance from java Platform transfer to php platform .
The meaning of deserialization : According to the object state and description information saved in the byte stream , Rebuild objects by deserializing .
Advantages of serialization :
- Turn the object into a byte stream and store it in On hard disk ( It is actually stored in the database , It's usually redis database - Key-value pair database ), When JVM In case of shutdown , The byte stream will wait silently on the hard disk , Wait for the next time JVM Start of , hold Serialized objects , By deserializing to the original object .
- The serialized binary sequence can reduce the storage space ( Keep objects permanently ).
- Objects serialized into byte streams can be transmitted over the network .
- Objects can be passed between processes through serialization .
tips:
In fact, it uses redis Database as cache , It is generally used to store serialized strings , When the string needs to be used , And then deserialize it to an object , Convenient to call .
4 Example : test php The execution process of serialization and deserialization in code
4.1 Test environment
The server : Install... In a virtual machine win2008 And phpstudy, Reference resources 《【 Language environment 】WAMP Environment deployment and optimization — With win2008R2SP1 For the operating system 》.
client : Real machine browser .
4.2 Test serialization process
(1) Create a new folder under the root directory of the server website serialize_unserialize, Create a new folder under this folder txt file , Enter the following , And rename to serialize.php.
<meta charset = "utf-8">
<?php
// Define a stu class , There are 4 Attributes , Method is not defined yet .
class stu{
public $name;
public $sex;
public $age;
public $score;
}
// Create objects 1
$stu1=new stu();
$stu1->name="gzz";
$stu1->sex=true;
$stu1->age=18;
$stu1->score=66;
// Create objects 2
$stu2=new stu();
$stu2->name="dqq";
$stu2->sex=false;
$stu2->age=18;
$stu2->score=96;
// Output gzz and dqq The achievement of
echo $stu1->name."'s score=".$stu1->score;
echo "<br/>";
echo $stu2->name."'s score=".$stu2->score;
// use var_dump Output object
echo "<hr>";
var_dump($stu1);
echo "<br/>";
var_dump($stu2);
// Serialize the object and output
echo "<hr>";
echo " After serialization echo Output <br>";
echo serialize($stu1);
?>
(2) Visit the web page with a real browser , It is shown as follows . You can see that the object is serialized into a string :, among :
object(stu)#1 (4) { ["name"]=> string(3) "gzz" ["sex"]=> bool(true) ["age"]=> int(18) ["score"]=> int(66) }
①object Representing objects ;(stu) Represents the class to which the object belongs , (4) Express 4 AttributesO:3:"stu":4:{s:4:"name";s:3:"gzz";s:3:"sex";b:1;s:3:"age";i:18;s:5:"score";i:66;}
①O Indicates that the string is for the object ;3 Indicates that the object name has 3 Characters ;stu Represents the object name ;4 Express 4 Attributes ;
② Every two semicolons in curly braces represent the key value pair of an attribute .
4.3 Test the deserialization process
(1) Copy above serialize.php file , And rename to unserialize.php The content is modified as follows :
<meta charset = "utf-8">
<?php
// Define a stu class , There are 4 Attributes , Method is not defined yet .
class stu{
public $name;
public $sex;
public $age;
public $score;
}
// Receive the string from input or generated above .
$obj=$_GET['obj'];
// Deserialization
$stu1 = unserialize($obj);
// use var_dump Output
echo " use var_dump Output <br>";
var_dump($stu1);
echo '<hr>';
// Serialize the object and output
echo " After serialization echo Output <br>";
echo serialize($stu1);
?>
(2) The real browser accesses the web page and passes in parameters obj, The access parameter is ?obj=O:3:%22stu%22:4:{s:4:%22name%22;s:3:%22gzz%22;s:3:%22sex%22;b:1;s:3:%22age%22;i:18;s:5:%22score%22;i:66;}, The results are as follows . You can see that the object is successfully generated after the inverse sequence .
5 Example :SessionID stay php Serialization and deserialization in
5.1 SessionID serialize
With PHP Language as an example , Brief introduction Session ID The process of serialization .
(1) In the 4 In line ,odbc_connect function , Return if the execution is successful connection ID function , Failure returns false. The input parameters are the database name 、 user name 、 password 、 The other parameters .
(1) In the 5 In line ,odbc_prepare function , If successful, prepare SQL command , Then return to ODBC Result identifier ; Return... On error false.
(1) In the 6 That's ok ,serialize() Function will session_data serialize ; And then ,array() Generate an array , The first element of the array is the serialized byte stream , The second element is the variable .
(1) In the 7 In the judgment condition of the line ,odbc_execute() The function passes the prepared array into the prepared SQL Execute in statement , Update the corresponding data in the database . If execution fails , execute if The body of the function .
<?php
// $session_data Yes, including the current user session Multidimensional array of information .
// We use serialize() Store the request in the database before it ends .
$conn = odbc_connect ("webdb", "php", "chicken");
$stmt = odbc_prepare ($conn, "UPDATE sessions SET data = ? WHERE id = ?");
$sqldata = array (serialize($session_data), $PHP_AUTH_USER);
if (!odbc_execute ($stmt, &$sqldata)) {
$stmt = odbc_prepare($conn,
"INSERT INTO sessions (id, data) VALUES(?, ?)");
if (!odbc_execute($stmt, &$sqldata)) {
/* error */
}
}
?>
5.2 SessionID Deserialization
With PHP Language as an example , Brief introduction Session ID Deserialization process , It is a continuation of the above example .
(1) In the 6 That's ok , Use array() The function will super global variables $_SERVER Properties of PHP_AUTH_USER The content is defined as an array .
(1) In the 7 In line , Use odbc_execute() Function to find the corresponding... From the database user Of SessionID;odbc_fetch_into() Returns the number of columns in the result , Returns... In case of error false.
(1) In the 12 In line , For the data obtained from the database SessionID deserialize .
<?php
// here , We use unserialize() Load data from the database $session_data Session data in array .
// This example describes serialize() In addition to the example of .
$conn = odbc_connect("webdb", "php", "chicken");
$stmt = odbc_prepare($conn, "SELECT data FROM sessions WHERE id = ?");
$sqldata = array($_SERVER['PHP_AUTH_USER']);
if (!odbc_execute($stmt, $sqldata) || !odbc_fetch_into($stmt, $tmp)) {
// If the execution fails or returns an error , Then initialize to an empty array
$session_data = array();
} else {
// Now what we need is $tmp[0] Serialized data in .
$session_data = unserialize($tmp[0]);
if (!is_array($session_data)) {
// error , Initialize to an empty array
$session_data = array();
}
}
?>
6 summary
(1) Understand the role of serialization and deserialization ;
(1) master PHP How to use serialization and deserialization in .
Reference article
[1]《 A detailed explanation of serialization and deserialization 》
[2]《PHP Basic concepts of class and object 》 Beginners suggest taking a look at PHP Official manual on the application of classes .
边栏推荐
- 简单理解modbus功能码和分区
- What is the difference between low code and no code?
- Talk about software testing - automated testing framework
- E2PROM read / write (xiicps) on PS side of zcu102 board
- RRPN:Arbitrary-Oriented Scene Text Detection via Rotation Proposals
- Druid encryption command
- 黑马瑞吉外卖之员工信息分页查询
- Openresty Lua resty logger socket log transfer
- Publish local image to private library
- Over the weekend, I had a dinner with the technology gurus and talked about the "golden nine and silver ten" peak of the software testing industry [the trend of involution has been formed]
猜你喜欢

Depth first search and breadth first search of Graphs

Publish local image to private library

HDU5667 Sequence

Four components and working principle of frequency converter

Why can't memset initialize array elements to 1?

Conversion between hexadecimal string and byte array

JPS has no namenode and datanode reasons

Pytorch learning -- using gradient descent method to realize univariate linear regression

黑马瑞吉外卖之员工信息分页查询

Ldr6028 charging OTG live line live sound card audio adapter is the most cost-effective solution
随机推荐
The number of digits of power and factorial
"Low power Bluetooth module" master-slave integrated Bluetooth sniffer - help smart door lock
【Golang】golang实现sha256加密函数
高频笔试题(蔚来)
Kubernetes Foundation
Detailed explanation and example demonstration of Modbus RTU communication protocol
MySQL query field matches the record of a rule
[golang] golang implements sha256 encryption function
Text message verification of web crawler
Exceptions about configuring Postgres parameters
简单使用 MySQL 索引
MySQL根据备注查询表、字段
Depth first search and breadth first search of Graphs
在线客服聊天系统源码_美观强大golang内核开发_二进制运行傻瓜式安装_附搭建教程
《Nature》论文插图复刻第3期—面积图(Part2-100)
RRPN:Arbitrary-Oriented Scene Text Detection via Rotation Proposals
How to access the code of online customer service system to your website
Reprint: getting started with cache coherence
2022, the average salary of the soft tester, after reading it, I was instantly cool
网络爬虫之短信验证