flawopen.com/path-traversal/Ruby
How File.join in Ruby leaves relative paths unresolved, and how to verify boundaries using File.expand_path.
设想一家酒店的房卡扫描锁原本只允许开启二楼的客房。如果客人在门禁键盘上输入 '../../master-safe',有缺陷的门锁就会跳出当前楼道,直接打开酒店经理办公室的主保险箱。
Web Application SecurityCWE-918.CWE-918CWE-918):Standard Common Weakness Enumeration classification for path-traversal-ruby.Defense-in-Depth应用程序接口通过 HTTP 参数接收用户指定的文件名、报告路径或静态资源标识。
攻击者在文件名参数中注入相对路径遍历符号(如 '../', '..%2f')或绝对路径覆盖。
后端直接将不可信输入与基础目录拼接,未进行规范化绝对路径解析(Canonicalization)与边界校验。
系统运行时打开并回传敏感配置文件(如 /etc/passwd、源码凭证、环境变量密钥),造成数据外泄。
# 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