# upload_server.py - File upload with race condition
from flask import Flask, request
import os, tempfile, time, threading
app = Flask(__name__)
UPLOAD_DIR = '/tmp/uploads'
os.makedirs(UPLOAD_DIR, exist_ok=True)
@app.route('/upload', methods=['POST'])
def upload():
file = request.files['file']
# Save to a temporary file
fd, tmp_path = tempfile.mkstemp(dir=UPLOAD_DIR)
file.save(tmp_path)
# Simulate validation (check extension)
if not file.filename.endswith('.txt'):
os.unlink(tmp_path)
return "Invalid extension", 400
# Race window: between save and move, attacker can execute the script
# In a real server, we'd move to safe name, but we simulate time delay
time.sleep(0.5) # vulnerability
final_path = os.path.join(UPLOAD_DIR, file.filename)
os.rename(tmp_path, final_path)
return "Uploaded", 200
if __name__ == '__main__':
app.run(port=5000)
上传端点将上传的文件写入临时路径,验证扩展名,然后在一段延迟后将其移动到安全名称。攻击者可以在重命名之前竞相访问并执行临时文件,从而实现远程代码执行。
pip install flask
python upload_server.py
python exploit_race_upload.py