Ruby on Rails Security Guide 2024

Quick Summary:

Ruby on Rails is a popular web application framework that is widely used for building web applications. This ruby on rails security guide will shed light on ruby hacks such as using secure authentication and authorization mechanisms which will help you secure your ruby application.

To aid developers in creating online apps, web application frameworks were created. Although no framework is entirely secure, if you utilize it properly, you may create secure apps. The security of your website should be one of your top priorities when developing it. To ensure business continuity, it is essential to safeguard client data and avoid minor vulnerabilities like content spoofing. You should keep in mind, that hacking methods are also developing as quickly as technologies.

So, does that means that you can just plug in some security essentials and you are good to go? Not so fast!

Plug-and-play security does not really exist. Security is sometimes influenced by the development methodology and other times by the users of the framework, the web application itself, the web server, and the back-end storage are all factors that affect it.

However, according to the Gartner Group, 97% of the 300 assessed sites are vulnerable to attack as 75% of attacks are believed to occur at the web application layer. This is because web applications, even by non-technical users, are quite simple to attack and influence.

This post will shed some light on how to secure Rails apps. However, it’s crucial to remember that these attacks are getting more sophisticated so it’s best to have a second line of defense against cyberattacks. It would also recommend the ruby gems such as Brakeman to check for vulnerabilities in the application and secure them. Still if you’re not sure which gems you can use in your project you can take help from the proficient ruby on rails development company.  Let’s take a look at the security issues in ruby on rails.

Ruby on Rails Security Issues

This web framework had an instantaneous rise in popularity, yet it has faced harsh criticism for its data breaches. Due to the numerous vulnerabilities and difficulties encountered, ROR developers tirelessly endeavor to deliver multiple security patches. To assure perfect security in ROR products, they went one step further.

A Ruby-on-Rails security audit is now carried out once a year. The audit not only strengthens the platform’s security but also lessens a few other issues. A built-in default defense against numerous security issues such as SQL injection, Clickjacking, CSRF, Man-in-the-middle and more of them is available in Ruby on Rails. The development environment has improved to become the safest one currently accessible.

Ruby On Rails Security Vulnerability

The application and safety are expertly combined in Ruby, which is well-balanced. A secure degree of defense is offered by built-in Rails strong passwords & countermeasures against numerous threats that endanger its existence. A set of modules referred to as gems serve as the foundation for the Ruby on Rails framework. Every gem includes code and a metafile in the proper format.

The “entire ecosystem” will be brought down if a known RCE for YAML is introduced into the metafile and the gem is deployed to the Ruby Gems server. Although the vibrant community and the core ruby team are working extremely hard to ensure the confidentiality offered by the framework.

However, it is advised to bear in mind that you can’t account for every conceivable circumstance, and there is always a program on top that is typically a cause of the risks. The ruby security guidelines are important to read. You can find it here.

Ruby on Rails Security Attacks & Mitigation

The development & security against multiple cyberattacks are perfectly balanced in the Ruby on Rails framework. It is well protected from the most common kinds of cyber assaults thanks to a multitude of built-in security solutions.

Even with all the built-in security features, though, irresponsible ruby programming can still leave an app open to attack. Let’s go over the different kinds of cyberattacks that Ruby on Rails may encounter.

Ruby on Rails Security Attacks

Cross-site scripting

Cross-site Malicious scripts are inserted into websites that are otherwise trustworthy and legitimate during scripting assaults. It happens when an attacker sends malicious code, which typically takes the form of a  browser-side script, to another end user via a web application.

A malicious script can be sent to an unwary user by an attacker using XSS. The end user’s browser will run the script even though it shouldn’t be trusted. The malicious script is capable of accessing any passwords, authentication information or other sensitive data stored by the client and associated with that site since it believes the script is from a reliable source. These scripts can completely change HTML page content. There are three types of XSS:

  • Reflected XSS
  • Stored XSS
  • DOM Based XSS

Types of XSS

Also Read : Popular Ruby Design Patterns

Reflected XSS (Also known as: Non-Persistent or Type I)

A malicious script is reflected from a web application and onto a user’s browser in a technique known as “reflected XSS” When a user clicks on a link that has a script embedded in it, the script only then comes into action.

Stored XSS (Also known as Persistent or Type II)

Generally speaking, Stored cross-site scripting attacks take place when a malicious script is placed right into the target web application, and they are among the most dangerous XSS assaults. It depends on unsanitized user input, for scripts to be permanently kept on the target servers. Full user account takeover is frequently made possible by these assaults because they provide malicious users control over how the browser runs a script.

With the introduction of HTML5 and other browser capabilities, it is possible to picture the attack payload being entirely kept within the victim’s browser—perhaps in the form of an HTML5 database—and never being communicated to the server.

DOM Based XSS (Also known as Type 0)

Amit Klein describes DOM Based XSS as a kind of XSS in which the whole contaminated data flow from source to sink occurs inside the browser, i.e., the sources of the information is in the DOM, the sink is likewise in the DOM, and the flow of data never leaves the browser.

For instance, the URL of the website, such as document.location.href, or an HTML element may serve as the source (where hostile data is read), and the sink could be a vulnerable method call that triggers the execution of the harmful data.

How does XSS work

Practical Example: Include CVE details

Vulnerability Details:  CVE-2015-3226

CWE No: CWE – 79

CWE ID: 79

CVSS Score: 4.3

No. of vulnerabilities: 20831

Description: The software does not sufficiently validate, filter, escape and encode user-controllable input before it is placed in output that is used as a web page which is served to other users

Confidentiality Impact: There is no impact on the confidentiality of the system

Integrity Impact: There is a partial impact on some system information

Availability Impact: There is no impact availability of the system

Access Complexity: There is a medium complexity in the app, and there are certain preconditions that must be satisfied to exploit

Authentication: There is no need for authentication to exploit vulnerabilities


Preventing cross-site scripting is trivial and can be much harder depending on the complexity of the application and the ways it handles user-controlled data. You can find the ruby cheat sheet here.

Filter the input: When the user input is received filter it as strictly as possible

Encode the output: When user-controllable data is sent in HTTP replies, the output should be encoded to avoid it from being mistaken for active content. This can call for combining several encodings, based on the output situation.

Utilizing Response Header: You may use the Content-Type and X-Content-Type-Options headers to make sure that browsers read HTTP responses the way you intend them to in order to stop XSS in HTTP responses that aren’t meant to contain any HTML or JavaScript.

CSP: If XSS vulnerabilities still exist, your final line of protection is to implement Content Security Policy (CSP).

Mass Assignment

One feature that made the creation of the code incredibly simple was the mass assignment. A variety of attributes can be selected by the developer at once. A unique operating operator would need to be created for each attribute if this function didn’t exist.

A hash is used to pass groups of parameters in applications that use the Model-View-Controller (MVC) architecture. Such a hash is delivered unchecked and unaltered to the model when the controller receives it. In this situation, changing them becomes conceivable if the values of additional fields that weren’t initially intended to be changed are added to the hash.

Numerous MVC frameworks share this security flaw with Ruby on Rails. It permits hackers to discreetly alter the code. In the case of Ruby, using the “strong parameters” module enables the declaration of the parameters that cannot be modified through mass assignment, hence excluding the possibility of unauthorized changes in the code:

Practical Example: Include CVE details

Vulnerability Details:  CVE-2012-2055

CWE No: CWE –255

CWE ID: 255

CVSS Score: 4.3

No. of vulnerabilities:

Description: It is the vulnerability that was used to hack GitHub. Before this vulnerability, GitHub doesn’t properly restrict the use of a hash to provide values for a model’s attributes, which allows remote attackers to set the public_key[user_id] value via a modified URL for the public-key update form, related to a “mass assignment” vulnerability.

Confidentiality Impact: There is no impact on the confidentiality of the system

Integrity Impact: There is a partial impact on some system information

Availability Impact: There is no impact availability of the system

Access Complexity: There is a low complexity in the app, you need to have little knowledge or skill required to exploit the vulnerability

Authentication: There is no need for authentication to exploit vulnerabilities


Mitigating the mass assignment is a crucial task, it also depends on the complexity of your applications. You can find the mass assignment ruby cheat sheet here. Following are some of the solutions that you can follow to prevent this attack.

  • Specify an allow-list for the sensitive but bindable fields
  • Sensitive fields that cannot be bound should be blocked
  • Employ Data Transfer Objects (DTOs)


An online application where a user is currently authenticated is subjected to a cross-site request forgery (CSRF) attack that compels them to carry out undesired actions. An attacker could utilize a web application to deceive people into taking actions they don’t want them to by using social engineering techniques (such as providing a link via email or chat).

A successful CSRF attack might compel a regular user, who is the victim, to carry out state-changing operations like transferring money, altering an email address, and other similar tasks. A web application can be completely compromised by CSRF if the target is an administrative account.

What is CSRF

When the attack is successfully carried out the victim carries out’s unintentional action. For example, this might be to change the email address on their account, to change their password, or to make a funds transfer.

Depending on the nature of the action, the attacker might be able to gain full control over the user’s account. If the compromised user has a privileged role within the application, then the attacker might be able to take full control of all the application’s data and functionality.

Practical Example: Include CVE details

Vulnerability Details:   CVE-2022-0180

CWE No: CWE – 352

CWE ID: 352

CVSS Score: 6.8

No. of vulnerabilities:

Description: Before Quiz And Survey Master 7.3.7, there was a bug called Cross-Site Request Forgery (CSRF) that allowed a remote attacker to use a specially constructed web page to hijack administrators’ login and carry out arbitrary actions.

Confidentiality Impact: There is a partial impact on the confidentiality of the system

Integrity Impact: There is a partial impact on some system information

Availability Impact: There is partial impact availability of the system

Access Complexity: There is a medium complexity in the app, you need to have little knowledge or skill required to exploit the vulnerability

Authentication: There is no need for authentication to exploit vulnerabilities


To properly identify and exploit CSRF vulnerabilities nowadays, you must go through anti-CSRF protections set up by the website, the victim’s browsers, or both. You’ll most likely run into the following types of defenses:

CSRF Tokens: A CSRF token is a one-of-a-kind, confidential, and erratic value created by the server-side program and communicated to the client. The client must provide the appropriate CSRF token in the request when trying to carry out a sensitive operation, such as submitting a form. As a result, creating a direct request on the victim’s behalf is highly challenging for an attacker.

Same Site Cookies: When cookies from one website are included in requests coming from another website, Same Site, a browser security feature, detects this. The appropriate Same Site constraints may stop an attacker from initiating these cross-site requests to undertake sensitive actions because these requests normally need an authenticated session cookie.

Lax Same Site restrictions are now in effect by default in Chrome as of 2021. We anticipate other significant browsers to follow this behavior in the future because it is the recommended standard.

Referer-based validation: To prevent CSRF attacks, several applications use the HTTP Referer header, typically by confirming that the request came from their domain. Compared to CSRF token validation, this generally performs worse.

In Search to Hire Ruby on Rails developeR?

Hire Ruby on Rails developers from Aglowid to build quality-rich RoR solutions

SQL Injection

SQL injection is a web security that allows an attacker to interfere with the queries that an application makes to its database. It generally allows an attacker to view data that they are not normally able to retrieve. This might include data belonging to other users, or any other data that the application itself can access.

In many cases, an attacker can modify or delete this data, causing persistent changes to the application’s content or behavior. In some situations, an attacker can escalate an SQL injection attack to compromise the underlying server or other back-end infrastructure or perform a denial-of-service attack.

SQL injection

Practical Example: Include CVE details

Vulnerability Details:  CVE-2021-45255

CWE No: CWE – 89

CWE ID: 89

CVSS Score: 10.0

No. of vulnerabilities: 8919

Description: The software builds all or part of a SQL command using information that has been impacted externally by an upstream component, but it fails to sanitize certain special components incorrectly that could change the planned SQL command if it is transmitted to a downstream component.

The produced SQL query may view user-controllable inputs as SQL instead of straightforward user data if enough SQL syntax is not removed or quoted from them. This can be used to modify query logic to get around security checks or to enter new statements that change the database in the background, possibly even executing system commands.

Confidentiality Impact: There is a complete impact on the confidentiality of the system

Integrity Impact: There is a complete impact on some system information

Availability Impact: There is complete impact availability of the system

Access Complexity: There is a low complexity in the app, you need to have little knowledge or skill required to exploit the vulnerability

Authentication: There is no need for authentication to exploit vulnerabilities


The primary defense of SQL injection includes:

  • Using Application with Parameterized Queries
  • Utilizing Stored Procedures That Are Properly Built
  • Validation of Allow-list Input
  • Eliminating all user input
  • Application of Least Privilege
  • Perform Allow-list Input Validation

Also Read : Top Ruby on Rails Gems for Web Apps in 2024


Clickjacking also known UI redress attack, is when an attacker uses multiple layers which can be opaque or transparent. It will trick a user into clicking on a button or link when they intended to click on the top-level page. Therefore, the attacker is “hijacking” clicks meant for their page and routing them to another page, most likely owned by another application, domain, or both.

Using a similar technique, keystrokes can also be hijacked. With a carefully crafted combination of stylesheets, iframes, and text boxes, a user can be led to believe they are typing in the password to their email or bank account, but are instead typing into an invisible frame controlled by the attacker.

Practical Example: Include CVE details

Vulnerability Details: CVE-2019-5243

CWE No: CWE – 1021

CWE ID: 1021

CVSS Score: 10.0

No. of vulnerabilities:

Description: The Huawei HG255 product has a vulnerability related to clickjacking. Through the use of deception, an attacker can convince a client to click a link and compromise the security of a device.

Confidentiality Impact: There is no impact on the confidentiality of the system

Integrity Impact: There is a partial impact on some system information

Availability Impact: There is no impact availability of the system

Access Complexity: There is a medium complexity in the app, you need to have little knowledge or skill required to exploit the vulnerability

Authentication: There is no need for authentication to exploit vulnerabilities


There are three major ways in which you can prevent clickjacking attacks, you can find the ruby cheat sheet here. They are as follows:

  • Sending the appropriate structure directive response headers for the Content Security Policy (CSP), which tell the browser to block framing from other domains. For graceful degrading and compatibility with older browsers, the X-Frame-Options HTTP headers are employed
  • Setting authentication cookies with samesite=Strict (or Lax) as necessary, unless they specifically require None (which is rare)
  • Use defensive code in the user interface to make sure that the current frame is the top-level window

Ruby on Rails Vital Components

When you’re developing a ruby on rails application, you must keep in mind that for configuring applications you need to configure the following components securely:

Ruby on Rails Vital Components

Application Configuration

Despite the excellent default setting, you may increase security by taking a few more actions.

Business Logic

Not just by the coding, but also by design, applications should be secure. When creating an MVP rapidly, this crucial aspect is frequently disregarded.

Controller Code

Since these classes serve as the starting point for our application, additional care must always be taken when designing it.

Controller Model

The point where we expose data to the browser is also a popular target for hackers, so we must ensure that we don’t render anything that risks our users’ data or privacy.

Controller Views

We must be careful to avoid rendering anything that puts the data or privacy of our consumers in danger because there is where we disclose data to the browser, which is also a common target for hackers.

Now that you have a good idea about popular cyber attacks on ruby on rails and their mitigations, along with the ruby on rails components that play a vital role in a secure configuration. Let’s move forward to the security gems available for ruby on rails that you can use for the extra layer of protection.

Ruby on Rails Security Gems

Security is an essential part of any SDLC, following are some of the security gems that can be used in your ruby application for providing better security:

Name Description Total Download Ruby Version Requires
Brakeman A static analysis security threat scanner for Ruby applications 84,244,610 >= 2.5.0
Dawnscanner A security source code scanner, which provides 150+ security checks with its solutions. 588,092 >= 2.3.0
Rail Roader Detects vulnerability using static analysis 8,537 >= 0
OWASP ESAPI Ruby It is a port for understanding the release quality OWASP ESAPI project to ruby 128,460 >= 1.9.2

8 Ruby on Rails Security Best Practices

With the necessary disclaimer out of the way, let’s go to what matters, a list of the ruby on rails security checklist you should opt for right now:

Top 8 Ruby on Rails Security Best Practices

Utilize SSL

Your rails application can be made to use the HTTPS protocol and always establish a secure connection. Open the production.rb file and add the following line to it to accomplish this:

Config.force_ssl = true

When you do this in your ruby file, the following things happen:

  • Rails will always switch requests made to the HTTP protocol to the HTTPS protocol whenever they are made to the HTTP version of the application
  • Cookies are marked as secure as a result. As a result, browsers won’t include cookies in HTTP requests
  • It instructs the browser to remember that your application only uses TLS an HTTP protocol extension

Install CORS

CORS is a security tool that limits which websites can communicate with the API of your application. Naturally, you won’t need to worry about this protection if you create a monolithic program.

If you’re developing an API application, you can configure CORS using the rack-cors extra gem. After completing that step, you can create a file with the name cors. rb and place it in the config/initializers initializer directory. To specify the website endpoints to access, including the request methods.

Rails.application.config.middleware.insert_before 0, Rack::Cors do
 allow do
   origins ''
   resource '/users',
     :headers => :any,
     :methods => [:post]
   resource '/articles',
     headers: :any,
     methods: [:get]

In the example above, we only permit the GET method and the POST method for calls to the /users endpoint and the /articles endpoint, respectively, on the website.

Avoid Loops And Using Methods With Blocks

With most other programming languages, loops are widespread and accepted without question, but in Ruby, we should always avoid them. This is because the use of each method and providing it as a block is more space economical than using loops.

Each element is represented by a set of variables that are kept. If you are a Rails developer, exercise extreme caution while creating policies for XSS payloads. The explanation is that, unlike SQL, JavaScript is a dynamic language. Therefore, there is constantly an opportunity to ban every XSS payload.

Dodge Insecure URL Redirects

To understand this, the best way is to understand the example

redirect_to params[:url]

This puts our users at risk of a redirect that could send them in any direction, so we shouldn’t ever use it. Avoiding redirects that require user input is the easiest way to fix this security problem. Also, you can always reroute to a path that doesn’t contain the host:

path = URL.parse(params[:url]).path.presence || "/"

redirect_to path

Avoid unsafe data serialization

Unwanted code execution in your application may result from insecure deserialization. If you want to serialize JSON:

data = { "key" => "value" }.to_json

# => "{\"key\":\"value\"}"

Instead of using methods such as load and restore method you should go for methods such as parse

# Unadvised

# advised

Environment Security Makes a Difference

One piece of advice that is frequently given to developers is to never hardcode API keys, access passwords, or sensitive login information into the source code. Inadvertently making them public or granting unauthorized access to other essential app resources are both possible outcomes. A secure means to save credentials are provided by the secure Ruby application, however, depending on the framework’s version, the implementation varies.

Rails 4: “Mysteries” is the name given to this feature. We can keep private information off-track in the git repository by storing it in a config/secrets.yml file.

Rails 5: In config/credentials.yml.enc, we can encrypt and modify sensitive data. The config/master.key file is used to change the encryption key. It is known as the “credentials” feature. The YAML configuration file can be kept in the repository because it is encrypted, but the master.key file does not need to be kept up to date.

Rails 6: Identities, also referred to as “credentials,” can be set up depending on the environment. We now have access to the encrypted YAML file and the key needed to decrypt it in every environment.

Use Pre-commit hook

You should always check to make sure no confidential material is being included before committing code to a public repository. However, mistakes do happen, thus it is advised that you employ automation to provide yourself with an extra measure of security. The use of a pre-commit hook is one technique to achieve it.

A Git repository can have hooks, which are programs. They are brought on by particular events. Pre-commit hooks are executed just before a commit is added to the repository, as the name suggests. Security leaks can be avoided using hooks, and if an issue is discovered, the commit can be securely aborted.

Duck insecure data serialization

There are several data serialization techniques that you should stay away from. These methods include YAML. load, Marshal.load, and JSON.load. These techniques could enable malicious individuals to run malware using tampered JSON or YAML when coupled with user data. Use JSON.parse or Pysch.safeload by default as opposed to the aforementioned techniques.


In conclusion, Ruby on Rails is a strong framework that can be used to create secure web applications. To secure against potential dangers, security must be appropriately established because it is not built-in. This includes adhering to best practices like input validation, encrypting sensitive data, and maintaining the program and its dependencies.

In addition, it’s critical to keep up with the latest security updates and patches and to have a plan in place for dealing with any potential problems. These recommendations can help developers build safe Ruby on Rails applications and safeguard the information of their users.

have a unique app Idea?

Hire Certified Developers To Build Robust Feature, Rich App And Websites

Need Consultation?

Put down your query here...

    Saurabh Barot

    Saurabh Barot, the CTO of Aglowid IT Solutions, leads a team of 50+ IT experts across various domains. He excels in web, mobile, IoT, AI/ML, and emerging tech. Saurabh's technical prowess is underscored by his contributions to Agile, Scrum, and Sprint-based milestones. His guidance as a CTO ensures remote teams achieve project success with precision and technical excellence.

    Related Posts