[NISACTF 2022]babyupload

php 复制代码
from flask import Flask, request, redirect, g, send_from_directory
import sqlite3
import os
import uuid

app = Flask(__name__)

SCHEMA = """CREATE TABLE files (
id text primary key,
path text
);
"""


def db():
    g_db = getattr(g, '_database', None)
    if g_db is None:
        g_db = g._database = sqlite3.connect("database.db")
    return g_db


@app.before_first_request
def setup():
    os.remove("database.db")
    cur = db().cursor()
    cur.executescript(SCHEMA)


@app.route('/')
def hello_world():
    return """<!DOCTYPE html>
<html>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
    Select image to upload:
    <input type="file" name="file">
    <input type="submit" value="Upload File" name="submit">
</form>
<!-- /source -->
</body>
</html>"""


@app.route('/source')
def source():
    return send_from_directory(directory="/var/www/html/", path="www.zip", as_attachment=True)


@app.route('/upload', methods=['POST'])
def upload():
    if 'file' not in request.files:
        return redirect('/')
    file = request.files['file']
    if "." in file.filename:
        return "Bad filename!", 403
    conn = db()
    cur = conn.cursor()
    uid = uuid.uuid4().hex    #生成uid
    try:
        cur.execute("insert into files (id, path) values (?, ?)", (uid, file.filename,))
    except sqlite3.IntegrityError:
        return "Duplicate file"
    conn.commit()

    file.save('uploads/' + file.filename)
    return redirect('/file/' + uid)


@app.route('/file/<id>')
def file(id):
    conn = db()
    cur = conn.cursor()
    cur.execute("select path from files where id=?", (id,))
    res = cur.fetchone()
    if res is None:
        return "File not found", 404

    # print(res[0])

    with open(os.path.join("uploads/", res[0]), "r") as f:
        return f.read()


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=80)

def upload() 要求上传的文件不能有后缀,且文件名前会拼接一个前缀upload/,使得输出的文件只能是在目录upload/下的,这里就涉及到os.path.join()的绝对路径拼接漏洞:

绝对路径拼接漏洞

os.path.join(path,*paths)函数用于将多个文件路径连接成一个组合的路径。第一个函数通常包含了基础路径,而之后的每个参数被当作组件拼接到基础路径之后。

然而,这个函数有一个少有人知的特性,如果拼接的某个路径以 / 开头,那么包括基础路径在内的所有前缀路径都将被删除,该路径将视为绝对路径。

php 复制代码
with open(os.path.join("uploads/", res[0]), "r") as f:
    return f.read() 

就是说传/flag,那么之前的upload/就会删除,就直接读取了根目录下的flag文件。抓包将文件名改为/flag。

直接访问得到的路径,获得flag:

相关推荐
程序员-Benothing8 分钟前
MySQL 的存储引擎有哪些?它们之间有什么区别?
后端·mysql·面试·职场和发展
DBA_G12 分钟前
解析GBase 8s数据库锁机制
数据库·oracle
captain37622 分钟前
多线程进阶
java·开发语言·数据库
initialize130622 分钟前
Oracle数据库 binary XML data类型同步
xml·数据库
treesforest23 分钟前
随意装软件也会被恶意IP入侵电脑?
网络·网络协议·tcp/ip·网络安全·ip属地·查ip归属地
倔强的石头10624 分钟前
连接池参数治理-HikariCP怎么配才稳
数据库·oracle
zcmodeltech41 分钟前
智慧城市沙盘模型多系统协同控制系统设计:基于STM32与Modbus RTU的园区-城市-数字孪生联动方案
服务器·数据库·人工智能·stm32·嵌入式硬件·信息可视化·智慧城市
ashiho1 小时前
【Redis】原理篇 3w字详解
数据库·redis·缓存·bootstrap
灯澜忆梦1 小时前
【MySQL9】进阶篇 | 存储引擎
mysql