Security

Path Traversal in Python: Example and Fix

Path traversal allows attackers to access files outside the intended directory using ../ sequences. Python apps serving files based on user input are commonly vulnerable.


❌ Vulnerable Code

@app.route('/download')
def download():
    filename = request.args.get('file')
    return send_file(os.path.join('/var/app/uploads', filename))

✅ Secure Fix

BASE_DIR = os.path.realpath('/var/app/uploads')

@app.route('/download')
def download():
    filename = request.args.get('file')
    safe_path = os.path.realpath(os.path.join(BASE_DIR, filename))
    if not safe_path.startswith(BASE_DIR):
        abort(403)
    return send_file(safe_path)
💡

Pro tip: Use os.path.realpath() to resolve all ../ sequences. Always verify the final path starts with your base directory.

Paste this code into LearnCodeGuide

Detect Python vulnerabilities and bugs automatically with AI-powered analysis.

Analyze Python Code →

Related Guides

Python Command InjectionPython Sql InjectionGo Path Traversal