flawopen.com/path-traversal/Ruby
How File.join in Ruby leaves relative paths unresolved, and how to verify boundaries using File.expand_path.
Stellen Sie sich ein Hotelschloss vor, das eigentlich nur Zimmer im zweiten Stock öffnen soll. Wenn ein Gast am Tastenfeld '../../master-safe' eingibt, verlässt das Schloss den Flur und öffnet den Haupttresor des Hotelmanagers.
Web Application SecurityCWE-918 betroffen ist.CWE-918Defense-in-DepthEin Endpunkt akzeptiert Dateinamen oder Ressourcenbezeichner direkt über einen HTTP-Anfrageparameter.
Der Angreifer schleust relative Pfadsequenzen wie '../', '..%2f' oder absolute Pfadüberschreibungen ein.
Das Backend verbindet die Eingabe mit dem Basispfad, ohne kanonische Pfade aufzulösen oder Grenzen zu prüfen.
Das System öffnet und übermittelt vertrauliche Systemdateien (z. B. /etc/passwd oder Konfigurationsgeheimnisse).
# 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
# 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