flawopen.com/path-traversal/Ruby

● CWE-918 · Alta
Investigación · FlawOpen

Path Traversal in Ruby

How File.join in Ruby leaves relative paths unresolved, and how to verify boundaries using File.expand_path.

💡 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-ruby.
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: File.join does not resolve traversal dots
class DownloadsController < ApplicationController
  BASE_DIR = Rails.root.join('storage', 'public').to_s

  def show
    # Attacker input: "../../config/master.key"
    file_path = File.join(BASE_DIR, params[:file])
    
    # Leaks private Rails master encryption key!
    send_file file_path
  end
end
✓ PARCHE SEGURO Y ROBUSTO
# HARDENED: Canonicalize with File.realpath and enforce prefix
class DownloadsController < ApplicationController
  BASE_DIR = File.realpath(Rails.root.join('storage', 'public').to_s)

  def show
    user_file = params[:file].to_s
    return head :bad_request if user_file.blank?

    # 1. Expand path relative to BASE_DIR
    target_path = File.expand_path(user_file, BASE_DIR)

    # 2. Strict boundary check with trailing separator
    allowed_prefix = BASE_DIR.end_with?('/') ? BASE_DIR : "#{BASE_DIR}/"
    unless target_path.start_with?(allowed_prefix)
      return render plain: 'Forbidden: Path Traversal detected', status: :forbidden
    end

    return head :not_found unless File.file?(target_path)

    send_file target_path
  end
end

Lista de Verificación de Seguridad para Ingeniería

References