Ruby on Rails Security Guide

Ruby on Rails Security Guide


Why is Ruby on Rails the best choice for web development? Rails is a pretty popular development environment, which is considered among the most practical. RoR is suitable for teams of varying size – from small startups to large corporations. This is because of the fact that Ruby on Rails has a rather simple syntax, is easy to learn and supports teamwork. This technology was used to create such known internet platforms as Twitter, Airbnb, Github, Groupon, Basecamp, Scribd, Kickstarter, CrunchBase and many others.


Ruby on Rails Security Issues

RoR first appeared in 2005 and quickly gained a lot of attention. Six years later, this framework was widely used as a web development technology. It is worth noting that the Apple Corporation played an important role in such a rapid take-off. The first significant difficulties arose in 2012-2013. It was at this time when the issue of the security of platforms based on Ruby became acute. A lot of problems and Ruby security vulnerabilities were found, which caused a wave of dissatisfied comments and criticism. This gave ill-wishers an excuse for malevolence: the technology slogan was unofficially paraphrased – “Web development that hurts a lot” instead of “Web development that does not hurt”.

In spite of all the difficulties, the Rails developers did not give up, which allowed them to identify and make a number of useful Rails security updates really quickly. Moreover, a Ruby security audit is conducted every year, which allows improve the platform security and avoid a number of difficulties. Today, RoR contains an in-built by-default protection against many different types of attacks such as CSRF, Clickjacking, Mass assignment, XSS and a number of others. Thanks to this, Ruby on Rail is justly considered as one of the safest development environments.


Ruby on Rails Security Vulnerabilities

The main advantage of RoR is that it is perfectly balanced and harmoniously combines appliance and safety. With built-in Rails secure password and solutions, this framework provides a high level of protection from a variety of different attacks. Considering the improvements, it would seem that one could say that the technology is invulnerable, but an irresponsible approach to the coding will entail many problems, including security Rails for Windows issues.

The basis of Ruby on Rails is the system of modules, so-called gems. Each of them contains the code and metafile in the appropriate format – YAML. If one of the known RCE-exploit for YAML is put into the metafile and such gem is loaded to the RubyGems server, you can execute any code in the context of the main Ruby code repository, thus compromising the entire “ecosystem”. So how do you protect against various attacks?


Ruby on Rails Security Guide: The Types of Attacks Most Often Used On the Websites

XSS or so-called cross-site scripting attacks are the biggest problems. This type of attack is the most harmful and can easily destroy your web service. There are a great number of entry points that allow injecting the malicious code. XSS attack can be launched from search result pages, comments, messages, reviews, the names of documents, projects, and so on. In fact, even URL parameters can open the way for an attack. In this case, the modified item stays integrated into the application and will subsequently be accessed by users. The main problem is that a malicious element may stay passive for a long time or activate in several parts of a site at the same time, which will be even more destructive. Because of the attack’s complex structure, you should not rely on standard XSS filters. Difficulties arise as soon as a programmer adds data in an unsafe format, such as JSON. It is better to give preference to converting the data to another format or to avoid embedding scripts into the transmitted data.

The protection from XSS by the automatic screening of potentially dangerous components is well implemented in RoR. Each line is marked with a special flag html_safe. If this flag is not set, then before the output of the variable part, Rails will filter it.

For the output of secure data, it is customary to use the next construction:

<% = raw data%>

but for everything else:

<% = data%>

The ‘raw’ method marks the line with the html_safe flag:

def raw (stringish)



Therefore, many developers are accustomed to the availability of XSS filters, used automatically. Nevertheless, a good Rails security specialist understands that XSS is a complex attack, which can take various forms and may be carried out in several stages.

The problem occurs when developers need to insert data in JSON format to the page sent to a user. Usually, the next code is implemented for the purpose:

<% = data.to_json%>

or in the HTML-based version:

: javascript

  var data = # {data.to_json}

In the first case, the ‘<%’ construct is used. It means that the standard filtering will be applied. In the second case, JSON, which can contain HTML code, will not be cleared. The vulnerability was fixed in the 4th version of Rails, where the symbols ‘<’, ‘>’ and ‘&’ were replaced by their Unicode analogs.

Attacks with cross-site request forgery or CSRFs are based on the vulnerability of the HTTP transfer protocol. This type of attack negatively affects the performance and work of your app or web resource and operate on the assumption of already active user privileges. Rails has a ready-made mechanism of protection against such attacks – token authentication. Nevertheless, the presence of built-in protection is not a reason to avoid implementing the additional safety recommendations. First of all, it is necessary to pay special attention to POST and DELETE queries.

The root of the problem lays in the usage of the ‘match’ method in the routes.rb file, which describes the path processing system on the site. This method is designed to map a specific action to all the possible HTTP request methods: GET, POST, PATCH, DELETE, etc. The ‘match’ method is used everywhere, so any Rails security scanner would suggest passing the parameters through alternative HTTP methods and monitoring the server responses. The following expression is a classic illustration of the described case:

match “/ follow”, to: “followings # create”


Mass assignment is a capability that greatly simplifies the creation of the code. Using it, the developer can simultaneously set an array of attributes. Without this function, the programmer would have to create an operator for each attribute separately. In the applications with Model-View-Controller (MVC) architecture, sets of parameters are passed in the form of a hash. When the controller receives such hash, it is conveyed into the model unchecked and unchanged. In this case, if you add to the hash the values of other fields that were not designed to be altered from the beginning, it becomes possible to change them.

This Ruby on Rails security vulnerability is common to many MVC frameworks. It allows hackers making changes in the code covertly. In the case of Ruby, the usage of the “strong_parameters” module makes it possible to exclude the possibility of unauthorized changes in the code, allowing to declare explicitly the parameters, which cannot be changed through mass assignment:

class User <ActiveRecord :: Base

  attr_protected: can_fire_missiles


SQL injection is the most popular method of hacker attacks. Of course, a significant amount of ORMs allow blocking the unsafe input but with effort, the perpetrator can always find a way to pass the unverified data. For example, if we use such statement:

Order.where (: user_id => 1) .joins (params [: table]),

the table parameters and data will not be checked. It should be noted that SQL injection opens access to the database, which makes it possible not only to read confidential data but also to change it.

Often, this attack method is used to seek the certain information, for instance:

def index

  @writers = Writer.all

  unless params [: query] .blank?

     @writers = @ writers.where (“biography like ‘% # {params [: query]}%'”)



On the one hand, it allows looking for the required records quickly. On the other hand, it is a good way to inject the malicious code into the returned result. You may solve the problem using a safer array declaration:

def index

  @writers = Writer.all

  unless params [: query] .blank?

     @writers = @ writers.where (“biography like”, params [: query])



You can read more about the SQL-injection attacks and ways to protect your application in more detail at the OWASP Cheat Sheet.


Clickjacking is a type of network attack that automatically redirects a user to another page. It is worth noting that, as a rule, this type of attack does not harm your site and is used to increase the attendance of a third-party resource. In spite of this, the latest versions of Ruby have a mechanism that can prevent the redirects. To do it, the developer simply needs to add the HTTP header “X-Frame-Options: SAMEORIGIN” to the created pages.

RoR sessions are stored by default in a signed cookie, which is a regular line signed with a secret HMAC key. Many developers believe that the session contents is something secure and inaccessible to the user. Of course, the user cannot modify the values of the session parameters, since it is signed by the session key – ‘session_secret’, but it is possible to find out everything that is written in the session protocol. For example, this is how ‘_gh_sess’ cookie looks like on



It consists of two parts: the first part is a line encoded by the Base64 algorithm, the second part is its MD5-signature. Let us try to decode the first part of the line using the ‘atob (decodeURIComponent ())’ functions:

“{: _csrf_token” 19yv3VZY8veGCQXyS3dl47XGB9r4rzWVUNZqUFqSmWNI =: session_id “% 76f701b09a1b5a1831a51a309ff8f79d: userieª: contextI” /: EF: fingerprint “% 5ffecf01f27d79b4ff0dbeaa39568eb7: return_toI” (; TI “

flash; FIC: ‘ActionController :: Flash :: FlashHash {:

@used {“

Frankly speaking, this vulnerability carries nothing but disclosure of data. In Rails 4 version, encrypted session storage is already used to store sessions, which significantly limits the ability to retrieve useful data from the session, since it is stored in an encrypted form. Anyway, experienced developers strongly recommend against storing such data client-side. To ensure the session safety it is also advisable using the methods of ‘activerecord-session_store’ gem to process and store sessions.


Ruby on Rails Security: Final Word

Ruby on Rails has many built-in mechanisms that allow protecting a web page or application. Despite this, many developers do not use these mechanisms or do it wrong. This is why many problems can subsequently arise. To avoid the possible issue, we advise you to remember our Ruby on Rails security guide when you code in RoR. Also, it is important to frequently check your apps with Ruby security scanner, Brakeman or Codesake::Dawn, for instance.

Victor Rak

Victor Rak

Backend Developer

Join our Newsletter