Sitemap
Tim M.

Tim M.

Security Analysis: Rails

6 min readOct 25, 2022

--

Press enter or click to view image in full size

What is Rails?

Rails is a web application framework that is used to build web applications. It is written in Ruby and runs on the Ruby interpreter. Rails has been around for over 10 years and has been used by many companies, including Twitter, Groupon, and Shopify.

Rails security vulnerabilities are a big problem because they can lead to data breaches or other security issues. In this blog, we will discuss some of the most common vulnerabilities found in Rails applications and how to fix them.

Common Vulnerability: SQL injection

The most common vulnerability in Rails is SQL injection. This vulnerability occurs when the user enters a string of text into a form field and the string gets converted into SQL code without being sanitized first. To fix this vulnerability, developers should always sanitize any input strings before converting them to SQL code.

Press enter or click to view image in full size

Preventing SQL injections in Rails

Rails uses an Object Relational Mapping (ORM) framework called ActiveRecord to abstract interactions with a database. ActiveRecord, in most cases, protects against SQL Injections by default. However, there are ways how it can be used insecurely, which can lead to security issues.

Using ActiveRecord, we can select the user with the supplied id and retrieve that user’s username:

User.find(params[:id]).username

The above will return the username of the user whose user id matches the one supplied via the params hash. Let’s take a look at the SQL query generated by the code above on the backend:

SELECT  "users".* FROM "users"  WHERE "users"."id" = ? LIMIT 1  [["id", 1]]

As we can see from the SQL query above, when using the find method on the User object ActiveRecord is binding id to the SQL statement, protecting us from SQL Injection.

What if we wanted to select a user which matches a username and password, commonly seen in authentication forms? You might see something like this:

User.where("username = '#{username}' AND encrypted_password = '#{password}'").first

If we supply a username with the value ‘) OR 1– the corresponding SQL query on the backend becomes:

SELECT  "users".* FROM "users"  WHERE (username = '') OR 1--' AND encrypted_password = 'a')  ORDER BY "users"."id" ASC LIMIT 1

By injecting our specially crafted SQL, what we have done is told the database to return all rows from the users table where the username is null or true. This makes the SQL statement return true along with all of the data in the users table.

Common Vulnerability: Cross-site scripting

Another common vulnerability in Rails is cross-site scripting (XSS). This occurs when an attacker injects malicious scripts into an application’s pages or posts using a variety of methods such as email, chat messages, or social media posts. To fix this vulnerability, developers should always validate user input before displaying it on the page and never trust data coming from outside sources such as cookies or URL parameters.

Press enter or click to view image in full size

Preventing Cross-Site Scripting (XSS)

To help prevent cross-site scripting (XSS) vulnerabilities, we sanitize input and encode output using correct encoding for the output context.

Press enter or click to view image in full size

Sanitizing Input

Rails makes sanitizing user input easy with its MVC (Model View Controller) design. All data stored or retrieved from the database should pass through the model, so this is a great place to sanitize our stored data. Using active record validations within our models, we can ensure that data is present and/or in a specific format.

You can also sanitize the input/output in your view using the sanitize method. The sanitize method HTML encodes all tags and removes any attributes that are not explicitly allowed. Let’s pass it regular JavaScript XSS and see how it reacts:

<%= sanitize '<img src=x onerror=prompt(1)>' %>

The above will output:

<img src="x">

As we can see, the sanitize method has allowed our img tag with the src attribute, but it has removed the onerror event attribute. By default, if we don’t whitelist which tags/attributes we want, Rails will make that decision for us on what it believes is safe.

Get Tim M.’s stories in your inbox

Join Medium for free to get updates from this writer.

If we whitelist the src and onerror attributes, our XSS payload is executed:

<%= sanitize '<img src=x onerror=prompt(1)>', attributes: %w(src onerror) %>

The above will output:

<img src="x" onerror="prompt(1)">
Press enter or click to view image in full size

Ruby on Rails Security Gems

As we’ve seen, Rails offers many built-in security features that help protect our applications, sensitive data, and users from web-based attacks. But we have also seen that these have their limitations. For security features that Rails doesn’t offer out of the box, there are always open source options: gems, lots and lots of gems. Here are some of the top Rails security gems that you can put in your Gemfile.

Devise

Devise is a popular access control, authentication, and authorization gem for Rails. It offers secure password storage using bcrypt to hash salted passwords, user lockouts, user registration, forgotten password functionality, and more.

Although Devise’s own README states “If you are building your first Rails application, we recommend you to not use Devise”, I would ignore this statement. If you’re security-aware and have built applications in other frameworks before, I don’t see any issue with using Devise for your first Rails application.

URL: https://github.com/plataformatec/devise

Brakeman

Brakeman is a Static Code Analysis tool for Rails applications. It searches your application’s source code for potential vulnerabilities. Although it does report the occasional false positive, personally, I think this is a great gem and one that I would definitely recommend running against your application before going into production. Even better, run it after every commit.

URL: https://github.com/presidentbeef/brakeman

Secure Headers

Developed by Twitter, SecureHeaders is a Gem that implements security-related HTTP headers into your application’s HTTP responses. Headers such as Content Security Policy to help protect against Cross-Site Scripting (XSS) attacks, HTTP Strict Transport Security (HSTS) to ensure your site is only accessible over secure SSL connections, X-Frame-Options, and others.

URL: https://github.com/twitter/secureheaders

Rack Attack

Developed by Kickstarter, Rack::Attack is a Gem for blocking & throttling abusive requests. Personally, I use Rack::Attack to prevent form abuse. For example, instead of implementing a CAPTCHA on a submission form, I use Rack::Attack to ensure it is not submitted too many times in a short space of time. This should prevent automated tools from abusing the form submission. It also supports whitelisting and blacklisting of requests.

URL: https://github.com/kickstarter/rack-attack

Codesake Dawn

Codesake::Dawn is similar to Brakeman in that it scans your source code for potential vulnerabilities. However, Codesake::Dawn also has a database of known vulnerabilities, which it uses to scan your Ruby, Rails, and gems for known issues.

URL: https://github.com/codesake/codesake-dawn

Ruby on Rails Code Quality Gems

Sloppy and messy code leads to bugs and some bugs may have security implications. Better quality code means more secure code. Let’s take a look at what gems we can use to ensure our code is nice and clean.

Rails Best Practices

The Rails best practices gem is a great gem for ensuring that your code adheres to best practices. It will help you make your code more readable and eloquent by scanning through it and giving you suggestions on how to improve the syntax.

URL: https://github.com/railsbp/rails_best_practices

Rubocop

Rubocop is not specific to Rails and can be used for any Ruby application. It uses the Ruby Style Guide as a reference to scan your code and ensure that you adhere to it. This includes tings like variable naming, method size, using outdated syntax, etc.

URL: https://github.com/bbatsov/rubocop

Conclusion

Rails does a lot of things right when it comes to security. When you develop a Rails application, it feels like Rails has your back. However, don’t let this sense of security lull you into a state of not caring about security. As we have seen, there are pitfalls, and it only takes one mistake for your sensitive information such as credit card data to end up on pastebin.

--

--