Application security
suggest changeMost security bugs in Ruby applications come from the same few mistakes: untrusted input pasted into SQL, shell commands, HTML or file paths; deserializing data that creates arbitrary objects; and secrets generated or compared the wrong way. Ruby, its standard library and the common gems give you a safe tool for each of these. This article goes through the main vulnerability classes with the vulnerable code, the fix, and the output of running both.
The examples were run with Ruby 4.0, Sequel 5, Sinatra 4 and Rack 3. Related articles cover Password hashing, Authentication (tokens, JWT, HTTP auth), CORS and File uploads in more depth.
The general rule: treat everything that comes from outside the process as untrusted. That includes query parameters, form fields, JSON bodies, headers, cookies, uploaded file names, and data read back from your own database that a user once typed in.
SQL injection
Building SQL with string interpolation lets the input change the structure of the query. Sequel's mock database prints the SQL it would send, which makes the difference easy to see:
require 'sequel'
DB = Sequel.mock(host: 'sqlite')
users = DB[:users]
name = "x' OR '1'='1"
# string interpolation: injectable
puts users.where(Sequel.lit("name = '#{name}'")).sql
# hash conditions: escaped
puts users.where(name: name).sql
# placeholders
puts users.where(Sequel.lit("name = ? AND age > ?", name, 18)).sql
puts users.where(Sequel.lit("name = :n", n: name)).sql
SELECT * FROM `users` WHERE (name = 'x' OR '1'='1')
SELECT * FROM `users` WHERE (`name` = 'x'' OR ''1''=''1')
SELECT * FROM `users` WHERE (name = 'x'' OR ''1''=''1' AND age > 18)
SELECT * FROM `users` WHERE (name = 'x'' OR ''1''=''1')
The first query returns every row. In the others the quote characters are escaped and the whole input is compared as one string. The same rules apply to ActiveRecord:
# vulnerable
User.where("name = '#{params[:name]}'")
User.order(params[:sort]) # ORDER BY is also SQL
# safe
User.where(name: params[:name])
User.where("name = ? AND age > ?", params[:name], 18)
User.where("name = :name", name: params[:name])
User.order(params[:sort] == "email" ? :email : :created_at)
Placeholders only work for values. Column names, table names, ORDER BY direction and LIMIT must never come straight from input: map them through an allowlist as in the last line. With the raw database drivers (pg, mysql2, sqlite3) use their prepared statement APIs (exec_params, prepare/execute) rather than string building.
Command injection
A single string passed to system, backticks, exec, spawn, IO.popen or Open3 goes through /bin/sh, so shell metacharacters in the input run extra commands:
filename = "notes.txt; echo HACKED"
system("echo listing #{filename}")
system("echo", "listing", filename)
listing notes.txt
HACKED
listing notes.txt; echo HACKED
With several arguments Ruby calls execve directly, no shell is involved, and filename is just one argument. Use the same form with Open3 when you need the output:
require 'open3'
out, status = Open3.capture2("wc", "-c", "--", "/etc/hostname")
p out, status.success?
"16 /etc/hostname\n"
true
The -- stops the program from treating a value such as -rf or --output=/etc/passwd as an option. That is argument injection, and the array form doesn't protect against it.
If you really need a shell string (for example to build a pipeline), escape each value with Shellwords:
require 'shellwords'
puts Shellwords.escape("notes.txt; echo HACKED")
puts ["grep", "-r", "--", "a b", "dir"].shelljoin
notes.txt\;\ echo\ HACKED
grep -r -- a\ b dir
Older Ruby code has one more trap: Kernel#open("| cmd") and IO.read("| cmd") used to start a process when the name began with a pipe, so open(params[:file]) was remote code execution. This was deprecated in Ruby 3.3 and removed in Ruby 4.0:
begin
File.read("| echo pwned")
rescue => e
puts "#{e.class}: #{e.message}"
end
Errno::ENOENT: No such file or directory @ rb_sysopen - | echo pwned
Still, prefer File.open/File.read for files and URI.open (from open-uri) only for URLs you have validated. See Recommended ways to execute shell code in Ruby for more on running processes.
Cross-site scripting (XSS)
When user input ends up in HTML without escaping, an attacker can inject <script> that runs in other users' browsers with their cookies and session. Three standard ways to escape HTML give the same result:
require 'erb'
require 'cgi'
require 'rack'
comment = %q{<script>alert("xss")</script> & 'friends'}
puts ERB::Util.html_escape(comment)
puts CGI.escapeHTML(comment)
puts Rack::Utils.escape_html(comment)
<script>alert("xss")</script> & 'friends'
<script>alert("xss")</script> & 'friends'
<script>alert("xss")</script> & 'friends'
Plain ERB does not escape <%= %> by default. Include ERB::Util and use h for HTML and u for values in URLs:
require 'erb'
include ERB::Util
comment = %q{<script>alert("xss")</script> & 'friends'}
query = "a&b=c d"
template = ERB.new(<<~HTML)
<p><%= h(comment) %></p>
<a href="/search?q=<%= u(query) %>">search</a>
HTML
puts template.result(binding)
<p><script>alert("xss")</script> & 'friends'</p>
<a href="/search?q=a%26b%3Dc%20d">search</a>
Rails views, Hanami views, and Sinatra with set :erb, escape_html: true escape automatically. There, the danger is anything that marks a string as safe: raw, html_safe, <%== %>, and helpers that build HTML from strings. Only call them on content you produced, or on user HTML that went through a sanitizer such as Rails::HTML5::SafeListSanitizer or the sanitize gem.
Escaping isn't enough inside a URL attribute. javascript:alert(1) contains no characters that need escaping, so check the scheme of user-supplied links:
require 'uri'
def safe_url?(s)
uri = URI.parse(s)
%w[http https].include?(uri.scheme&.downcase)
rescue URI::InvalidURIError
false
end
p safe_url?("javascript:alert(1)")
p safe_url?("JAVASCRIPT:alert(1)")
p safe_url?("https://example.com/x")
false
false
true
Similarly, never interpolate user data into inline <script> blocks or event attributes; put it in a data- attribute (escaped) or serve it as JSON. A Content Security Policy header (shown later) limits the damage when something slips through.
Unsafe deserialization
Formats that can describe arbitrary Ruby objects let an attacker create objects whose methods run code during loading or later use. Never call Marshal.load on untrusted data; there is no safe mode. For YAML, Psych 4 (Ruby 3.1+) made YAML.load safe by default:
require 'yaml'
require 'date'
evil = "--- !ruby/object:OpenStruct\ntable:\n name: x\n"
begin
YAML.load(evil)
rescue Psych::DisallowedClass => e
puts "#{e.class}: #{e.message}"
end
p YAML.load("name: alice\nroles: [admin]\n")
p YAML.safe_load("born: 1990-05-01\n", permitted_classes: [Date])
begin
YAML.load("a: &x [1]\nb: *x\n")
rescue Psych::AliasesNotEnabled => e
puts e.class
end
Psych::DisallowedClass: Tried to load unspecified class: OpenStruct
{"name" => "alice", "roles" => ["admin"]}
{"born" => #<Date: 1990-05-01 ((2448013j,0s,0n),+0s,-Infj)>}
Psych::AliasesNotEnabled
Only plain types (strings, numbers, booleans, nil, arrays, hashes) load unless you list extra classes in permitted_classes:. Aliases are off too, because nested aliases can expand into a huge structure ("billion laughs"). YAML.unsafe_load restores the old behaviour; keep it for files you wrote yourself.
For JSON, use JSON.parse, which only returns plain types. Avoid JSON.load and create_additions: true on input, because they can instantiate classes named by a json_class key. See JSON with Ruby.
Dynamic code with user input
eval, instance_eval, class_eval, send, constantize and Object.const_get all turn a string into code or a method call. With send, a user who controls the method name controls much more than you think:
class Report
def summary = "summary"
def details = "details"
end
params = { "format" => "instance_eval" }
Report.new.send(params["format"], "puts 'arbitrary code ran'")
arbitrary code ran
public_send would block private methods, but instance_eval is public. The fix is an allowlist, or a lookup table that maps input to code:
ALLOWED_FORMATS = %w[summary details].freeze
def render(report, format)
raise ArgumentError, "unknown format: #{format}" unless ALLOWED_FORMATS.include?(format)
report.public_send(format)
end
puts render(Report.new, "details")
begin
render(Report.new, "instance_eval")
rescue ArgumentError => e
puts e.message
end
EXPORTERS = { "csv" => -> { "csv data" }, "json" => -> { "json data" } }.freeze
puts EXPORTERS.fetch("json").call
p EXPORTERS.fetch("Kernel", nil)
details
unknown format: instance_eval
json data
nil
The same goes for params[:type].constantize in Rails: pick from a fixed hash of classes instead. More on these methods in Dynamic evaluation.
Mass assignment
Passing the whole params hash to a constructor lets the user set fields you didn't put in the form, such as admin or account_id. Keep only the keys you expect:
User = Struct.new(:name, :email, :admin, keyword_init: true)
params = { "name" => "eve", "email" => "eve@example.com", "admin" => true }
safe = params.slice("name", "email").transform_keys(&:to_sym)
p User.new(**safe)
#<struct User name="eve", email="eve@example.com", admin=nil>
In Rails this is what strong parameters do: params.expect(user: [:name, :email]) (Rails 8) or params.require(:user).permit(:name, :email).
A closely related bug is insecure direct object reference: Invoice.find(params[:id]) returns any user's invoice. Scope lookups to the current user, current_user.invoices.find(params[:id]), so a wrong id is simply "not found".
Path traversal
A file name from a request can contain ../ or be absolute. Resolve the path and check it's still inside the directory you meant:
require 'tmpdir'
UPLOAD_DIR = File.realpath(Dir.mktmpdir)
File.write(File.join(UPLOAD_DIR, "report.txt"), "quarterly numbers")
def safe_path(name)
path = File.expand_path(name, UPLOAD_DIR)
unless path.start_with?(UPLOAD_DIR + File::SEPARATOR)
raise ArgumentError, "path escapes upload dir: #{name.inspect}"
end
path
end
puts File.read(safe_path("report.txt"))
["../../etc/passwd", "/etc/passwd", "report.txt\0.png"].each do |name|
safe_path(name)
rescue ArgumentError => e
puts e.message
end
quarterly numbers
path escapes upload dir: "../../etc/passwd"
path escapes upload dir: "/etc/passwd"
path name contains null byte
Append the separator before start_with?, otherwise /srv/uploads-old/x passes a check for /srv/uploads. Ruby rejects null bytes in paths, which closes the old "evil.rb\0.png" trick. If the directory may contain symlinks, compare File.realpath(path) instead. Better still, don't use client file names at all: store files under a generated name (SecureRandom.uuid) and keep the original name in the database, as the File uploads article does.
Regular expressions: anchors and ReDoS
In Ruby ^ and $ match at the start and end of every line, not of the string. A validation written with them accepts input with a newline in it:
input = "alice\n<script>alert(1)</script>"
p input.match?(/^[a-z]+$/)
p input.match?(/\A[a-z]+\z/)
true
false
Always use \A and \z for validation. (Rails' validates format: raises an error if you use ^/$ without multiline: true.)
The other regex risk is ReDoS: a pattern with nested repetition can backtrack exponentially on crafted input, tying up a worker. Since Ruby 3.2 the regex engine memoizes most patterns so they run in linear time, and Regexp.linear_time? tells you whether a pattern qualifies. Backreferences and some lookarounds disable the optimization:
p Regexp.linear_time?(/\A(a|a)*\z/)
p Regexp.linear_time?(/\A(a+)+\1\z/)
slow = /\A(a+)+\1\z/
[16, 20, 24].each do |n|
t = Time.now
slow.match?("a" * n + "!")
puts "#{n} chars: #{(Time.now - t).round(3)}s"
end
true
false
16 chars: 0.001s
20 chars: 0.014s
24 chars: 0.224s
Every 4 more characters cost 16 times as long. Set a global timeout at boot, and a tighter one on individual patterns that run on user input:
Regexp.timeout = 1.0
begin
slow.match?("a" * 40 + "!")
rescue Regexp::TimeoutError => e
puts "#{e.class} after 1s"
end
strict = Regexp.new('\A(a+)+\1\z', timeout: 0.1)
begin
strict.match?("a" * 40 + "!")
rescue Regexp::TimeoutError => e
puts "#{e.class}: #{e.message}"
end
Regexp::TimeoutError after 1s
Regexp::TimeoutError: regexp match timeout
Also limit the length of input before matching it; it's the cheapest defence.
Randomness, secrets and comparisons
rand and Random are fine for games and sampling, but they are predictable: the same seed gives the same sequence, and the internal state can be recovered from outputs. Anything an attacker must not guess (session ids, API keys, reset tokens, one-time codes, salts) comes from SecureRandom:
require 'securerandom'
srand(42); a = Array.new(3) { rand(1_000_000) }
srand(42); b = Array.new(3) { rand(1_000_000) }
p a == b
p SecureRandom.hex(16) # 128-bit token
p SecureRandom.urlsafe_base64(32) # 256-bit, URL-safe
p SecureRandom.alphanumeric(10)
p SecureRandom.random_number(1_000_000).to_s.rjust(6, "0") # 6-digit code
true
"07b513111bb624f1a2820c6160144cf4"
"OTEHEtIZ20BNxm9s7pFnxlazgot_VLZjDXiBHxOuKc8"
"9yFViaiVSK"
"150761"
When checking a secret the client sent (an API key, a signature, a webhook token), use a constant-time comparison so the response time doesn't reveal how many leading characters were right:
require 'openssl'
require 'rack/utils'
stored = "4f1c2a9e7b"
p Rack::Utils.secure_compare(stored, "4f1c2a9e7b")
p Rack::Utils.secure_compare(stored, "4f1c")
p OpenSSL.secure_compare(stored, "4f1c2a9e7b")
true
false
true
To hand data to a client and get it back unchanged (a download link, an unsubscribe token), sign it with an HMAC and a server-side key:
require 'openssl'
require 'securerandom'
KEY = SecureRandom.bytes(32) # in production: from ENV or a secrets manager
def sign(data) = "#{data}--#{OpenSSL::HMAC.hexdigest("SHA256", KEY, data)}"
def verify(token)
data, _, mac = token.rpartition("--")
expected = OpenSSL::HMAC.hexdigest("SHA256", KEY, data)
OpenSSL.secure_compare(mac, expected) ? data : nil
end
t = sign("user_id=42")
p verify(t)
p verify(t.sub("42", "1"))
"user_id=42"
nil
Signing proves the data wasn't modified but doesn't hide it. In Rails, ActiveSupport::MessageVerifier and MessageEncryptor (or Rails.application.message_verifier) do this with expiry and purpose built in.
Keep secrets out of source code: read them with ENV.fetch("NAME") so a missing value fails at boot, or use Rails' encrypted credentials. See Environment variables.
Open redirects
Redirecting to params[:return_to] after login lets a phishing link send users to an attacker's site that looks like yours. Only accept local paths:
require 'uri'
def safe_redirect(target, default: "/")
uri = URI.parse(target.to_s)
return default if uri.scheme || uri.host # absolute or //host URL
return default unless uri.path&.start_with?("/")
target
rescue URI::InvalidURIError
default
end
['/dashboard?tab=1', 'https://evil.example', '//evil.example',
'/\evil.example', 'javascript:alert(1)', 'dashboard'].each do |t|
puts "#{t.ljust(22)} -> #{safe_redirect(t)}"
end
/dashboard?tab=1 -> /dashboard?tab=1
https://evil.example -> /
//evil.example -> /
/\evil.example -> /
javascript:alert(1) -> /
dashboard -> /
//evil.example is the subtle one: browsers treat it as a protocol-relative URL to another host. Browsers also turn /\ into //, which is why the backslash case matters; URI.parse rejects it. Rails 7+ raises UnsafeRedirectError on redirect_to to another host unless you pass allow_other_host: true.
A related problem is server-side request forgery (SSRF): if your server fetches a URL the user supplies (webhooks, link previews, image import), an attacker can point it at http://169.254.169.254/ or internal services. Allow only http/https, resolve the host, and reject private, loopback and link-local addresses (the ssrf_filter gem does this, including on redirects).
CSRF, cookies and security headers
A cross-site request forgery makes a logged-in user's browser submit a form to your site from another site. The defences are SameSite cookies plus a secret token in every state-changing form. Sinatra uses rack-protection for this, and the same app can set secure cookie flags and response headers:
# app.rb
require 'sinatra/base'
require 'securerandom'
class App < Sinatra::Base
set :sessions,
key: "__Host-session",
secret: ENV.fetch("SESSION_SECRET") { SecureRandom.hex(64) },
httponly: true,
secure: true,
same_site: :lax,
path: "/"
set :protection, use: [:authenticity_token], reaction: :deny
set :host_authorization, permitted_hosts: ["example.com"]
before do
headers "Content-Security-Policy" => "default-src 'self'; frame-ancestors 'none'",
"Strict-Transport-Security" => "max-age=63072000; includeSubDomains",
"Referrer-Policy" => "strict-origin-when-cross-origin"
end
get "/form" do
token = Rack::Protection::AuthenticityToken.token(session)
%(<form method="post" action="/transfer">
<input type="hidden" name="authenticity_token" value="#{token}">
<button>Send</button>
</form>)
end
post "/transfer" do
"transferred"
end
end
Exercising it with rack-test:
require 'rack/test'
require_relative 'app'
include Rack::Test::Methods
def app = App
get "https://example.com/form"
last_response.headers.each { |k, v| puts "#{k}: #{v[0, 60]}" unless k == "content-length" }
token = last_response.body[/value="([^"]+)"/, 1]
post "https://example.com/transfer"
puts "without token: #{last_response.status}"
post "https://example.com/transfer", authenticity_token: token
puts "with token: #{last_response.status} #{last_response.body}"
get "https://evil.example/form"
puts "other host: #{last_response.status} #{last_response.body}"
content-security-policy: default-src 'self'; frame-ancestors 'none'
strict-transport-security: max-age=63072000; includeSubDomains
referrer-policy: strict-origin-when-cross-origin
content-type: text/html;charset=utf-8
x-xss-protection: 1; mode=block
x-content-type-options: nosniff
x-frame-options: SAMEORIGIN
set-cookie: __Host-session=At5SdFbVZCxELDosb%2BSQRsedCP8nsYt4H%2F9wYbqBD
without token: 403
with token: 200 transferred
other host: 403 Host not permitted
What each setting does:
httponlykeeps JavaScript (and so XSS payloads) from reading the session cookie.securesends it over HTTPS only.same_site: :laxstops the browser from sending it on cross-site POSTs. The__Host-name prefix makes browsers refuse the cookie unless it issecure, haspath=/and nodomain, so a subdomain can't overwrite it.authenticity_tokenrejects POST, PUT, PATCH and DELETE requests without a valid token. Notereaction: :deny: Sinatra's default reaction is:drop_session, which lets the request through with an empty session. That's safe for session-authenticated actions, but surprising if you expected a 403.host_authorization(Sinatra 4.1+) rejects unexpectedHostheaders, which blocks DNS rebinding and host-header poisoning of generated links.- The headers: CSP restricts where scripts, styles and frames may come from; HSTS tells browsers to use HTTPS only;
X-Frame-Options/frame-ancestorsprevent clickjacking;nosniffstops browsers guessing content types.rack-protectionadds the last three by default.
Rails enables CSRF protection, secure cookies in production (with config.force_ssl = true) and most of these headers out of the box; configure CSP in config/initializers/content_security_policy.rb. JSON APIs authenticated with an Authorization header instead of cookies are not vulnerable to CSRF, but then CORS settings matter.
Keeping secrets out of logs
Request logging, exception trackers and inspect output easily leak passwords, tokens and card numbers. ActiveSupport::ParameterFilter (what Rails' filter_parameters uses) works outside Rails too:
require 'active_support'
require 'active_support/parameter_filter'
filter = ActiveSupport::ParameterFilter.new([:passw, :token, :secret, /\Acard/, :ssn])
params = { "email" => "a@example.com", "password" => "hunter2",
"card_number" => "4111111111111111",
"user" => { "api_token" => "abc123", "name" => "Alice" } }
p filter.filter(params)
{"email" => "a@example.com", "password" => "[FILTERED]", "card_number" => "[FILTERED]", "user" => {"api_token" => "[FILTERED]", "name" => "Alice"}}
Symbols match as substrings (:passw covers password and password_confirmation), regexes as written, and nested hashes are filtered too. Also make sure query strings with tokens don't end up in access logs, and see Logging for structured logging.
Dependencies and static analysis
Much of your code is gems, so keep them patched and scan them automatically, for example in CI:
$ gem install bundler-audit brakeman
$ bundle-audit check --update # known CVEs in Gemfile.lock
$ brakeman --no-pager # static analysis for Rails apps
$ bundle outdated --strict
bundler-audit compares Gemfile.lock with the Ruby Advisory Database. Brakeman finds SQL injection, XSS, unsafe send/constantize, mass assignment and open redirects in Rails code without running it. Commit Gemfile.lock, add only gems from sources you trust, and enable Dependabot or a similar service so security updates arrive as pull requests. Rails 7.2+ generates a CI workflow that runs both tools.
Checklist
| Risk | Don't | Do |
|---|---|---|
| SQL injection | "WHERE name = '#{x}'" |
hash conditions, ? placeholders, allowlist columns |
| Command injection | system("cmd #{x}"), backticks |
system("cmd", "--", x), Open3 with arrays |
| XSS | raw, html_safe, unescaped ERB |
auto-escaping templates, ERB::Util.h, check URL schemes |
| Deserialization | Marshal.load, YAML.unsafe_load, JSON.load |
JSON.parse, YAML.safe_load |
| Dynamic code | send(params[:m]), constantize |
allowlists, lookup hashes |
| Mass assignment | User.new(params) |
slice / strong parameters, scoped lookups |
| Path traversal | File.join(dir, params[:name]) |
expand_path + prefix check, generated names |
| Regex | ^...$, unbounded input |
\A...\z, Regexp.timeout, length limits |
| Secrets | rand, == on tokens, hard-coded keys |
SecureRandom, secure_compare, ENV.fetch |
| Redirects / SSRF | redirect params[:to], fetching any URL |
local paths only, block private addresses |
| CSRF / cookies | cookies without flags | tokens, SameSite, Secure, HttpOnly, __Host- |
| Dependencies | stale Gemfile.lock |
bundle-audit, brakeman, automatic updates |