flawopen.com/path-traversal/Python

● CWE-918 · Alta
Investigación · FlawOpen

Path Traversal in Python

How os.path.join silently discards the root directory when input starts with a slash, and how to use pathlib.Path.resolve() and is_relative_to().

💡 Explicación en Lenguaje Sencillo (ELI5)

Imagina un escáner de llaves de hotel programado para abrir únicamente habitaciones del segundo piso. Si un huésped escribe '../../master-safe' en el teclado de la puerta, la cerradura vulnerable sube por el pasillo y abre la caja fuerte principal del gerente.

Conceptos Clave y Términos

Web Application Security
Componente de arquitectura central afectado por CWE-918.
CWE-918
Clasificación estándar Common Weakness Enumeration (CWE) para path-traversal-python.
Defense-in-Depth
Verificación de ingeniería multicapa y aislamiento de límites en tiempo de ejecución.

Flujo de Ataque Paso a Paso

Step 1

Entrada de Ruta de Archivo del Cliente

Un endpoint acepta un nombre de archivo o identificador de recurso provisto por el usuario vía parámetro HTTP.

Step 2

Inyección de Secuencias de Recorrido

El atacante inyecta secuencias relativas como '../', '..%2f' o rutas absolutas en el nombre del archivo.

Step 3

Evasión del Límite de Directorio

El backend concatena el archivo al directorio base sin resolver rutas canónicas ni validar límites seguros.

Step 4

Lectura o Sobrescritura Arbitraria de Archivos

El servidor lee y transmite archivos confidenciales del sistema (/etc/passwd, claves de entorno) al atacante.

Código Fuente: Vulnerable vs. Seguro

✕ IMPLEMENTACIÓN VULNERABLE
# VULNERABLE: os.path.join discards BASE_DIR if filename starts with '/'
import os
from flask import Flask, request, abort, send_file

app = Flask(__name__)
BASE_DIR = '/var/app/public/user_uploads'

@app.route('/download')
def download_file():
    filename = request.args.get('file')
    # If filename is "/etc/passwd", os.path.join returns "/etc/passwd"!
    # If filename is "../../etc/passwd", it traverses outside BASE_DIR
    target_path = os.path.join(BASE_DIR, filename)
    
    if not os.path.exists(target_path):
        abort(404)
    return send_file(target_path)
✓ PARCHE SEGURO Y ROBUSTO
# HARDENED: Resolve canonical path and enforce strict boundary containment
from pathlib import Path
from flask import Flask, request, abort, send_file

app = Flask(__name__)
BASE_DIR = Path('/var/app/public/user_uploads').resolve()

@app.route('/download')
def download_file():
    filename = request.args.get('file', '')
    # 1. Strip leading slashes and resolve relative components
    clean_name = filename.lstrip('/\\')
    target_path = (BASE_DIR / clean_name).resolve()
    
    # 2. Strict containment check: target MUST be inside BASE_DIR
    if not target_path.is_relative_to(BASE_DIR) or not target_path.is_file():
        abort(403)
        
    return send_file(target_path)

Lista de Verificación de Seguridad para Ingeniería

References