flawopen.com/path-traversal/Ruby

● CWE-918 · Tinggi
Riset Keamanan · FlawOpen

Path Traversal in Ruby

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

💡 Penjelasan Sederhana (ELI5)

Bayangkan pembaca kartu kunci hotel yang hanya boleh membuka kamar di lantai dua. Jika seorang tamu mengetik '../../master-safe' pada tombol pintu, kunci yang rentan keluar ke lorong dan membuka brankas utama milik manajer.

Konsep Kunci & Istilah

Web Application Security
Komponen arsitektur utama yang terpengaruh oleh CWE-918.
CWE-918
Klasifikasi standar Common Weakness Enumeration (CWE) untuk path-traversal-ruby.
Defense-in-Depth
Verifikasi rekayasa berlapis dan isolasi batas waktu proses (runtime).

Alur Serangan Langkah demi Langkah

Step 1

Input Jalur Berkas Klien

Titik akhir menerima nama file atau pengenal sumber daya dari parameter permintaan HTTP.

Step 2

Injeksi Urutan Penelusuran Direktori

Penyerang menyisipkan urutan traversal seperti '../', '..%2f' atau jalur mutlak ke parameter file.

Step 3

Penerobosan Batas Direktori Dasar

Backend menggabungkan nama file tanpa kanonisasi jalur dan tanpa memastikan target tetap dalam folder aman.

Step 4

Pengungkapan Berkas Sensitif Sistem

Sistem membaca dan mengalirkan file sensitif (misal: /etc/passwd atau rahasia konfigurasi) ke klien.

Kode Sumber: Rentan vs Aman

✕ IMPLEMENTASI RENTAN
# 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
✓ PERBAIKAN AMAN & KUAT
# 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

Daftar Periksa Penguatan Sistem Rekayasa

References