For AI agents: A markdown version of this page is available at https://docs.datadoghq.com/security/code_security/static_analysis/static_analysis_rules/ruby-security/rails-path-traversal.md. A documentation index is available at /llms.txt.

Avoid path traversal for Ruby on Rails applications

This product is not supported for your selected Datadog site. ().

Metadata

ID: ruby-security/rails-path-traversal

Language: Ruby

Severity: Warning

Category: Security

CWE: 35

Description

This rule aims to prevent path traversal vulnerabilities in Ruby on Rails applications. Path traversal occurs when user input is used to construct file paths without proper validation, allowing attackers to access sensitive files outside the intended directories. This can lead to unauthorized disclosure of system files, application source code, or configuration data.

It is crucial to avoid directly incorporating user-controlled parameters into file paths, especially when using methods like render file:, send_file, or render template:. Attackers can manipulate these inputs to traverse directories using sequences like ../, potentially exposing critical files. Such vulnerabilities can compromise the security and integrity of your application and underlying system.

To mitigate this risk, use hardcoded paths and template names, or validate input against a list of allowed values before passing it into render file:, render template:, or send_file. If dynamic file access is necessary, use strict validation and sanitization of input parameters, or constrain access to a predefined allowlist of acceptable files. Following these practices helps maintain the application’s security posture against path traversal attacks.

Non-Compliant Code Examples

def myfunction
    base = Rails.root.join("public/docs")
    requested = base.join(params[:path].to_s).cleanpath
    send_file requested, disposition: "inline"
end
def myfunction
    # e.g. params[:page] = "../../etc/passwd"
    render file: Rails.root.join("app/views/pages", "#{params[:page]}.html.erb")
end
# e.g. params[:page] = "../../etc/passwd"
render file: Rails.root.join("app/views/pages", "#{params[:page]}.html.erb")
def show
  render template: params[:page]
end

def update
  template = params[:template]
  render template: template
end

Compliant Code Examples

def show
  render file: Rails.root.join("app/views/pages/fixed.html.erb")
end

def show_again
  template = Page.find_by(id: params[:id]).template_path
  render file: Rails.root.join("app/views", template)
end

def about
  render template: "pages/about"
end
render template: "pages/otherpage"
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Security