Detect Path Traversal Vulnerability in Rails
Description
Path Traversal (Directory Traversal) occurs when user input is used to construct file paths without proper validation. This allows attackers to access files outside the intended directory by using special characters like ../ to navigate the filesystem.
This rule detects common path traversal patterns in Rails applications where user-controlled variables are used in:
Rails.root.join()- Building file paths relative to the Rails application rootFile.join()- Constructing file pathssend_file- Sending files to users
To prevent path traversal vulnerabilities, always validate and sanitize file paths, use File.basename() to extract only the filename, or use allowlists for permitted files.
YAML
yaml
id: path-traversal
message: Potential Path Traversal vulnerability detected. User input is being used to construct file paths without validation.
severity: hint
language: Ruby
note: |
Path Traversal (Directory Traversal) occurs when user input is used to construct file paths
without proper validation. This allows attackers to access files outside the intended directory.
Validate and sanitize file paths, and use File.basename() or similar functions.
rule:
any:
- pattern: Rails.root.join($$$, $VAR, $$$)
- pattern: File.join($$$, $VAR, $$$)
- pattern: send_file $VARExample
rb
# Pattern 1: Rails.root.join with variable
Rails.root.join('uploads', params[:filename])
Rails.root.join('data', user_input, 'file.txt')
# Pattern 2: File.join with variable
File.join('/var/www', params[:path])
File.join(base_path, user_id, filename)
# Pattern 3: send_file with variable
send_file params[:file]
send_file user.document_pathContributed by
sora fs0414 from this blog post