Rules / Python
SHIELD-PY-009
Path traversal via open()
What it detects
Opening files with user-controlled paths allows directory traversal.
How to fix
Validate file paths using os.path.realpath() and check against an allowed base directory.
Vulnerable — Shield flags thisapp.py
from flask import Flask, request
app = Flask(__name__)
@app.route("/download")
def download():
with open("uploads/" + request.args.get("file", "")) as f:
return f.read()
Fixed — scans cleanapp.py
import os
from flask import Flask, request, abort
app = Flask(__name__)
BASE_DIR = os.path.realpath("uploads")
@app.route("/download")
def download():
filename = request.args.get("file", "")
path = os.path.realpath(os.path.join(BASE_DIR, filename))
if not path.startswith(BASE_DIR + os.sep):
abort(400)
with open(path) as f:
return f.read()
Both snippets are verified against the shipped scanner: the vulnerable one triggers SHIELD-PY-009, the fixed one does not.