
# toctou_server.py - File server that checks permission then opens
import os, time, tempfile
from flask import Flask, request
app = Flask(__name__)
SAFE_DIR = '/tmp/safe'
@app.route('/read')
def read_file():
filename = request.args.get('file')
filepath = os.path.join(SAFE_DIR, filename)
# Check: ensure it's a regular file and owned by user
if not os.path.isfile(filepath):
return "Not a file", 403
# Race window: attacker replaces file with symlink to /etc/shadow
time.sleep(0.2) # simulate processing delay
with open(filepath, 'r') as f:
return f.read()
if __name__ == '__main__':
app.run(port=5000)
A file server checks whether a path is a regular file and then opens it after a delay. An attacker can replace the file with a symbolic link to a sensitive system file (e.g., /etc/shadow) during the race window, bypassing the check and reading protected data.
isfile) and the use (open) are not atomic, allowing an attacker to change the filesystem object in between.pip install flask
python toctou_server.py
python exploit_toctou.py
If the race succeeds, the response contains the shadow file.