Skip to content
Tutorials Center
My learning

Topics

Lesson 120 of 134 ยท Web and Ecosystem

Secure Ruby Code

Write safer Ruby. Prevent SQL, shell and path injection, avoid mass assignment, load YAML and JSON safely, compare secrets in constant time, escape HTML and keep credentials out of code.

Security bugs rarely come from clever attackers breaking cryptography. They come from ordinary code that trusts something it should not: a form field pasted into a query, a file name joined onto a path, a YAML document loaded into live objects, an API key committed to Git. Ruby gives you short, expressive tools, which is wonderful for productivity and also makes it easy to write the dangerous version of a line without noticing.

This lesson is a tour of the mistakes that cause most real incidents in Ruby programs, each with the safe replacement. The rule behind almost all of them is the same: treat every value that comes from outside your program as data, never as code, and keep it separate from anything that gets interpreted. "Outside" includes request parameters, headers, uploaded file names, JSON bodies, environment you do not control and even rows read back from your own database.

flowchart LR
  A["Untrusted input<br/>params, files, headers"] --> B{"Validate and<br/>allow-list"}
  B -- rejected --> X["Reject with an error"]
  B -- accepted --> C{"Where does it go?"}
  C --> D["SQL: placeholders"]
  C --> E["Shell: argument array"]
  C --> F["HTML: escape"]
  C --> G["Files: expand and check root"]

Validate on the way in, then use the matching safe API for each place the value ends up.

Injection: keep data out of the command

Injection happens when input is glued into a string that another system then interprets: SQL, a shell command, HTML, a regular expression. The cure is always to hand the data over through a channel that cannot be confused with the command.

SQL

Never interpolate into SQL. Compare the two queries below. Our stand-in bind quotes each value as a literal, which is what a driver's placeholder support does (real drivers actually send the SQL and the values separately, which is even stronger). The attacker's input is the classic ' OR '1'='1.

Shell commands

system("convert #{file}") runs through a shell, so a file name such as a.png; rm -rf ~ becomes two commands. Pass the program and its arguments as separate strings and no shell is involved. Never use backticks, %x(), system with one string, or open("| ...") with anything an outsider can influence.

Paths

A name like ../../etc/passwd climbs out of the directory you meant. Resolve the path with File.expand_path, then check that the result is still inside your root before touching the file.

Ruby SQL, shell and path injection, and the safe versions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

In the shell example the whole string, semicolon and all, arrives at echo as one argument, so INJECTED is just printed as text and never runs as a command. In the path example File.expand_path removes the .. parts first, so the check sees where the path really ends up. The folder is checked with a trailing separator so that /srv/app/uploads-evil does not pass a prefix test. If symbolic links are involved, compare File.realpath results instead.

HTML (cross-site scripting)

If you build HTML by hand, escape every dynamic value with ERB::Util.html_escape (alias h). Rails and ERB templates in frameworks escape by default, and you only get into trouble by calling raw, html_safe or <%== on user input. See ERB for the template syntax. Escaping turns <script> into harmless text:

Ruby
require "erb"
puts ERB::Util.html_escape("<script>alert(1)</script>")
# &lt;script&gt;alert(1)&lt;/script&gt;

Regular expressions

Two traps. First, in Ruby ^ and $ match at line boundaries, so name =~ /^[a-z]+$/ accepts "abc\n<script>". Use \A and \z to anchor the whole string. Second, a badly written pattern can take exponential time on crafted input (ReDoS). Since Ruby 3.2 many cases are optimized, and you can set a global cap with Regexp.timeout = 1.0 (seconds) as a safety net. The details of anchors are in Regular Expressions.

Mass assignment

A model that accepts a whole hash of attributes can be told to change fields the visitor was never meant to touch (admin, price, owner_id). The defence is an allow-list: name the fields that may be set and ignore the rest. Rails does this with strong parameters (see Rails MVC, Routing and Controllers); outside Rails you can use Hash#slice. Never use a deny-list ("everything except admin"), because the day you add a new sensitive column it is exposed automatically.

Ruby
ALLOWED = %i[name email].freeze

def build_user(input)
  input.slice(*ALLOWED)
end

p build_user({ name: "Ana", email: "[email protected]", admin: true })
# {name: "Ana", email: "[email protected]"}

Safe deserialization

Deserializing means turning text or bytes back into objects. Some formats can create any class and call its methods while doing so, which lets a crafted file run code on your server.

  • Marshal.load rebuilds arbitrary objects. Never call it on data an outsider could have written (cookies, uploads, cache entries in a shared store). Use it only for data your own program produced and protected.
  • YAML can name classes with tags such as !ruby/object:SomeClass. Always load with YAML.safe_load, and list the classes you really expect.
  • JSON only produces hashes, arrays, strings, numbers, booleans and nil. JSON.parse is safe unless you switch on create_additions, which you should not.
Ruby safe_load refuses what load-anything would build

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

By default safe_load accepts only simple scalars, arrays and hashes. Dates and symbols have to be allowed explicitly, which is annoying exactly once and then protects you forever. The hostile Object tag is refused before any object is created. Notice that the json_class key in the JSON document is just a string: plain JSON.parse never turns it into a class. See YAML and CSV and JSON for the formats themselves.

If you must exchange objects between processes, convert them to a plain hash with a method you write (to_h), send JSON, and rebuild them on the other side with a constructor that validates every field.

Secrets: never in code, never in logs

API keys, database passwords and signing secrets need three rules.

  1. Not in the source. Anything committed to Git is effectively public, and it stays in the history after you delete it. Read secrets at runtime from environment variables or from an encrypted store such as Rails credentials. Use ENV.fetch("NAME") so a missing value fails loudly at start-up instead of becoming nil later.
  2. Not in the logs. Redact sensitive keys before writing parameters or exceptions anywhere. Rails does this with filter_parameters.
  3. Compared carefully. Checking a token with == stops at the first different character, so the response time leaks how much matched. Use a constant-time comparison. Hash both sides first, so the inputs have equal length, then compare with OpenSSL.fixed_length_secure_compare.

Also generate tokens with SecureRandom, never with rand, which is predictable. Store passwords only as slow salted hashes (the bcrypt gem, or has_secure_password in Rails), never as plain text or fast hashes like MD5 and SHA-256 alone. Digest and Base64 explains why those fast hashes are fine for checksums but not for passwords.

Ruby Fail-fast secrets, redaction and constant-time comparison

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The comparison first turns both strings into 32-byte digests, so different lengths are no longer a problem and no timing information about the real secret leaks. The redaction helper walks nested hashes, which matters because secrets often hide one level down.

A short security checklist

  • Allow-list input at the edge (Integer(value) raises on garbage, Hash#slice limits keys) and use the safe API at the destination.
  • Keep dependencies current. Run bundle audit (the bundler-audit gem) in continuous integration to flag gems with known vulnerabilities, and read about locking versions in RubyGems and Bundler.
  • Use HTTPS everywhere, mark session cookies secure and httponly, and protect forms against cross-site request forgery (Rails does this by default with an authenticity token).
  • Give each part of the system the least privilege it needs: a database user that can only read, a process that does not run as root.
  • Do not rescue and hide errors silently (Exceptions). A visible failure beats a quiet breach.
  • Show users a generic error message and log the details privately.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is system("convert #{name} out.png") dangerous when name comes from a user?

    A single command string is interpreted by a shell. Passing the program and each argument separately, as in system("convert", name, "out.png"), avoids the shell entirely.
  2. 2. Which loader should you use for YAML from an untrusted source?

    safe_load refuses to build arbitrary objects. Marshal.load and unsafe_load can instantiate any class from attacker-controlled input.
  3. 3. What is wrong with the pattern /^[a-z]+$/ for validating a whole string?

    In Ruby ^ and $ anchor each line. \A and \z anchor the start and end of the entire string.
  4. 4. Why should secrets be compared with a constant-time function?

    A normal comparison stops at the first mismatch, so response time can reveal progress to an attacker. Constant-time comparison takes the same time either way.
  5. 5. A model attribute list is protected by a deny-list: params.except(:admin). What is the main weakness?

    An allow-list fails safe: new fields are blocked until you permit them. A deny-list fails open.

Summary

  • Keep data and commands apart: SQL placeholders, shell argument arrays, HTML escaping and path checks against a root folder.
  • Anchor validation patterns with \A and \z, and consider Regexp.timeout as a safety net.
  • Accept input with allow-lists (slice, strong parameters), never deny-lists.
  • Load YAML with safe_load, never Marshal.load on untrusted bytes, and leave JSON create_additions off.
  • Read secrets from the environment or encrypted credentials with ENV.fetch, redact them in logs, compare with constant-time functions and create tokens with SecureRandom.
  • Update gems regularly and audit them, use HTTPS, and run with least privilege.

Next: Calculator Project