Ruby On Rails Cheat Sheet



Filed under: Ruby On Rails — Tags: Cheat Sheet, gems, rails, Rails Commands, Rails tips, ROR tips, ruby, Ruby on Rails — Veerasundaravel @ 3:08 pm These are the commands, we ROR folks use often in. Railsroot app apis controllers application.rb helpers applicationhelper.rb models views layouts components config environments development.rb production.rb test.rb database.yml environment.rb. Ruby on Rails Cheat Sheet Author. Ruby on Rails is an open source framework you can use to build Web sites and Web-based databases. Of course, as with any programming language, you need to know Ruby’s keywords and Rail’s naming conventions. Making sure that your data meets validation standards is key, and the proper iterators make traveling amongst your data a.

Last revision (mm/dd/yy): 01/18/2018

  • 2Items
    • 2.5Authentication

This Cheatsheet intends to provide quick basic Ruby on Rails security tips for developers. It complements, augments or emphasizes points brought up in the rails security guide from rails core. The Rails framework abstracts developers from quite a bit of tedious work and provides the means to accomplish complex tasks quickly and with ease. New developers, those unfamiliar with the inner-workings of Rails, likely need a basic set of guidelines to secure fundamental aspects of their application. The intended purpose of this doc is to be that guide.

Command Injection

Ruby offers a function called “eval” which will dynamically build new Ruby code based on Strings. It also has a number of ways to call system commands.

While the power of these commands is quite useful, extreme care should be taken when using them in a Rails based application. Usually, its just a bad idea. If need be, a whitelist of possible values should be used and any input should be validated as thoroughly as possible. The Ruby Security Reviewer's Guide has a section on injection and there are a number of OWASP references for it, starting at the top: Command Injection.

SQL Injection

Ruby on Rails is often used with an ORM called ActiveRecord, though it is flexible and can be used with other data sources. Typically very simple Rails applications use methods on the Rails models to query data. Many use cases protect for SQL Injection out of the box. However, it is possible to write code that allows for SQL Injection.

Here is an example (Rails 2.X style):

A Rails 3.X example:

In both of these cases, the statement is injectable because the name parameter is not escaped.

Here is the idiom for building this kind of statement:

Sheet

An AREL based solution:

Use caution not to build SQL statements based on user controlled input. A list of more realistic and detailed examples is here: rails-sqli.org. OWASP has extensive information about SQL Injection.

Cross-site Scripting (XSS)

By default, in Rails 3.0 and up protection against XSS comes as the default behavior. When string data is shown in views, it is escaped prior to being sent back to the browser. This goes a long way, but there are common cases where developers bypass this protection - for example to enable rich text editing. In the event that you want to pass variables to the front end with tags intact, it is tempting to do the following in your .erb file (ruby markup).

Unfortunately, any field that uses raw, html_safe, content_tag or similar like this will be a potential XSS target. Note that there are also widespread misunderstandings about html_safe. This writeup describes the underlying SafeBuffer mechanism in detail. Other tags that change the way strings are prepared for output can introduce similar issues, including content_tag.

The method html_safe() of String is somewhat confusingly named. It means that we know for sure the content of the string is safe to include in HTML without escaping. This method itself is un-safe!

If you must accept HTML content from users, consider a markup language for rich text in an application (Examples include: markdown and textile) and disallow HTML tags. This helps ensures that the input accepted doesn’t include HTML content that could be malicious. If you cannot restrict your users from entering HTML, consider implementing content security policy to disallow the execution of any javascript. And finally, consider using the #sanitize method that let's you whitelist allowed tags. Be careful, this method has been shown to be flawed numerous times and will never be a complete solution.

An often overlooked XSS attack vector for older versions of rails is the href value of a link:

If @user.website contains a link that starts with “javascript:”, the content will execute when a user clicks the generated link:

Newer Rails versions escape such links in a better way.

Using Content Security Policy is one more security measure to forbid execution for links starting with javascript: .

Brakeman scanner helps in finding XSS problems in Rails apps.

OWASP provides more general information about XSS in a top level page: Cross-site Scripting (XSS).

Sessions

By default, Ruby on Rails uses a Cookie based session store. What that means is that unless you change something, the session will not expire on the server. That means that some default applications may be vulnerable to replay attacks. It also means that sensitive information should never be put in the session.

The best practice is to use a database based session, which thankfully is very easy with Rails:

There is an OWASP Session Management Cheat Sheet.

Authentication

As with all sensitive data, start securing your authentication with enabling TLS in your configuration:

Uncomment the line 3 as above in your configuration.

Generally speaking, Rails does not provide authentication by itself. However, most developers using Rails leverage libraries such as Devise or AuthLogic to provide authentication.

To enable authentication it is possible to use Devise gem.

Install it using:

Then install it to the user model:

Next, specify which resources (routes) require authenticated access in routes:

To enforce password complexity, it is possible to use zxcvbn gem.Configure your user model with it:

And configure the required password complexity:


You can try out this PoC, to learn more about it.


Next, omniauth gem allows for multiple strategies for authentication. Using it one can configure secure authentication with Facebook, LDAPand many other providers. Read on here.

Token Authentication

Devise usually uses Cookies for authentication.

In the case token authentication is wished instead, it could be implemented with a gem devise_token_auth.

It supports multiple front end technologies, for example angular2-token.

This gem is configured similar to the devise gem itself. It also requiresomniauth as a dependency.

Then a route is defined:

And the User model is modified accordingly.

These actions can be done with one command:

You may need to edit the generated migration to avoid unnecessary fieldsand/or field duplication depending on your use case.

Note: when you use only token authentication, there is no more need in CSRF protection in controllers. If you use both ways: cookies and tokens, the paths where cookies are used for authentication still must be protected from forgery!


There is an OWASP Authentication Cheat Sheet.

Insecure Direct Object Reference or Forceful Browsing

By default, Ruby on Rails apps use a RESTful uri structure. That means that paths are often intuitive and guessable. To protect against a user trying to access or modify data that belongs to another user, it is important to specifically control actions. Out of the gate on a vanilla Rails application, there is no such built in protection. It is possible to do this by hand at the controller level.

It is also possible, and probably recommended, to consider resource-based access control libraries such as cancancan (cancan replacement) or punditto do this. This ensures that all operations on a database object are authorized by the business logic of the application.

More general information about this class of vulnerability is in the OWASP Top 10 Page.

CSRF (Cross Site Request Forgery)

Ruby on Rails has specific, built in support for CSRF tokens. To enable it, or ensure that it is enabled, find the base ApplicationController and look for a directive such as the following:

Note that the syntax for this type of control includes a way to add exceptions. Exceptions may be useful for API’s or other reasons - but should be reviewed and consciously included. In the example below, the Rails ProjectController will not provide CSRF protection for the show method.

Also note that by default Rails does not provide CSRF protection for any HTTP GET request.

Note: if you use token authentication only, there is no need to protect from CSRF in controllers like this. If cookie-based authentication is used on some paths, then the protections is still required on them.

There is a top level OWASP page for Cross-Site Request Forgery (CSRF).

Mass Assignment and Strong Parameters

Although the major issue with Mass Assignment has been fixed by default in base Rails specifically when generating new projects, it still applies to older and upgraded projects so it is important to understand the issue and to ensure that only attributes that are intended to be modifiable are exposed.

When working with a model, the attributes on the model will not be accessible to forms being posted unless a programmer explicitly indicates that:

With the admin attribute accessible based on the example above, the following could work:

Review accessible attributes to ensure that they should be accessible. If you are working in Rails < 3.2.3 you should ensure that your attributes are whitelisted with the following:

In Rails 4.0 strong parameters will be the recommended approach for handling attribute visibility. It is also possible to use the strong_parameters gem with Rails 3.x, and the strong_parameters_rails2 gem for Rails 2.3.x applications.

Redirects and Forwards

Web applications often require the ability to dynamically redirect users based on client-supplied data. To clarify, dynamic redirection usually entails the client including a URL in a parameter within a request to the application. Once received by the application, the user is redirected to the URL specified in the request. For example:

The above request would redirect the user to http://www.example.com/checkout. The security concern associated with this functionality is leveraging an organization’s trusted brand to phish users and trick them into visiting a malicious site, in our example, “badhacker.com”. Example:

The most basic, but restrictive protection is to use the :only_path option. Setting this to true will essentially strip out any host information. However, the :only_path option must be part of the first argument. If the first argument is not a hash table, then there is no way to pass in this option. In the absence of a custom helper or whitelist, this is one approach that can work:

If matching user input against a list of approved sites or TLDs against regular expression is a must, it makes sense to leverage a library such as URI.parse() to obtain the host and then take the host value and match it against regular expression patterns. Those regular expressions must, at a minimum, have anchors or there is a greater chance of an attacker bypassing the validation routine.

Example:



Also blind redirecting to user input parameter can lead to XSS. Example:

The obvious fix for this type of vulnerability is to restrict to specific Top-Level Domains (TLDs), statically define specific sites, or map a key to it’s value. Example:

There is a more general OWASP resource about unvalidated redirects and forwards.

Dynamic Render Paths

In Rails, controller actions and views can dynamically determine which view or partial to render by calling the “render” method. If user input is used in or for the template name, an attacker could cause the application to render an arbitrary view, such as an administrative page.

Care should be taken when using user input to determine which view to render. If possible, avoid any user input in the name or path to the view.

Cross Origin Resource Sharing

Occasionally, a need arises to share resources with another domain. For example, a file-upload function that sends data via an AJAX request to another domain. In these cases, the same-origin rules followed by web browsers must be bent. Modern browsers, in compliance with HTML5 standards, will allow this to occur but in order to do this; a couple precautions must be taken.

When using a nonstandard HTTP construct, such as an atypical Content-Type header, for example, the following applies:

The receiving site should whitelist only those domains allowed to make such requests as well as set the Access-Control-Allow-Origin header in both the response to the OPTIONS request and POST request. This is because the OPTIONS request is sent first, in order to determine if the remote or receiving site allows the requesting domain. Next, a second request, a POST request, is sent. Once again, the header must be set in order for the transaction to be shown as successful.

When standard HTTP constructs are used:

The request is sent and the browser, upon receiving a response, inspects the response headers in order to determine if the response can and should be processed.

Whitelist in Rails:

Gemfile

config/application.rb

Security-related headers

To set a header value, simply access the response.headers object as a hash inside your controller (often in a before/after_filter).

Rails 4 provides the 'default_headers' functionality that will automatically apply the values supplied. This works for most headers in almost all cases.

Strict transport security is a special case, it is set in an environment file (e.g. production.rb)

For those not on the edge, there is a library (secure_headers) for the same behavior with content security policy abstraction provided. It will automatically apply logic based on the user agent to produce a concise set of headers.

Business Logic Bugs

Any application in any technology can contain business logic errors that result in security bugs. Business logic bugs are difficult to impossible to detect using automated tools. The best ways to prevent business logic security bugs are to do code review, pair program and write unit tests.

Attack Surface

Generally speaking, Rails avoids open redirect and path traversal types of vulnerabilities because of its /config/routes.rb file which dictates what URL’s should be accessible and handled by which controllers. The routes file is a great place to look when thinking about the scope of the attack surface. An example might be as follows:

In this case, this route allows any public method on any controller to be called as an action. As a developer, you want to make sure that users can only reach the controller methods intended and in the way intended.

Sensitive Files

Many Ruby on Rails apps are open source and hosted on publicly available source code repositories. Whether that is the case or the code is committed to a corporate source control system, there are certain files that should be either excluded or carefully managed.


Encryption

Rails uses OS encryption. Generally speaking, it is always a bad idea to write your own encryption.

Devise by default uses bcrypt for password hashing, which is an appropriate solution. Typically, the following config causes the 10 stretches for production: /config/initializers/devise.rb

In early 2013, a number of critical vulnerabilities were identified in the Rails Framework. Organizations that had fallen behind current versions had more trouble updating and harder decisions along the way, including patching the source code for the framework itself.

An additional concern with Ruby applications in general is that most libraries (gems) are not signed by their authors. It is literally impossible to build a Rails based project with libraries that come from trusted sources. One good practice might be to audit the gems you are using.

In general, it is important to have a process for updating dependencies. An example process might define three mechanisms for triggering an update of response:

  • Every month/quarter dependencies in general are updated.
  • Every week important security vulnerabilities are taken into account and potentially trigger an update.
  • In EXCEPTIONAL conditions, emergency updates may need to be applied.

Use brakeman, an open source code analysis tool for Rails applications, to identify many potential issues. It will not necessarily produce comprehensive security findings, but it can find easily exposed issues. A great way to see potential issues in Rails is to review the brakeman documentation of warning types.

There are emerging tools that can be used to track security issues in dependency sets, like https://appcanary.com/ and https://gemnasium.com/.

Another area of tooling is the security testing tool Gauntlt which is built on cucumber and uses gherkin syntax to define attack files.

Launched in May 2013 and very similiar to brakeman scanner, the dawnscanner rubygem is a static analyzer for security issues that work with Rails, Sinatra and Padrino web applications. Version 0.60 has more than 30 ruby specific CVE security checks and future releases custom checks against Cross Site Scripting and SQL Injections will be added.

Matt Konda - mkonda [at] jemurai.com
Neil Matatall neil [at] matatall.com
Ken Johnson cktricky [at] gmail.com
Justin Collins justin [at] presidentbeef.com
Jon Rose - jrose400 [at] gmail.com
Lance Vaughn - lance [at] cabforward.com
Jon Claudius - jonathan.claudius [at] gmail.com
Jim Manico jim [at] owasp.org
Aaron Bedra aaron [at] aaronbedra.com
Egor Homakov homakov [at] gmail.com
Zaur Molotnikov qutorial [at] gmail.com 🡕 profile

Semgrep ruleset for this cheatsheet: https://semgrep.dev/p/minusworld.ruby-on-rails-xss

This is a cross-site scripting (XSS) prevention cheat sheet by r2c. Itcontains code patterns of potential XSS in an application. Instead of scrutinizing codefor exploitable vulnerabilities, the recommendations in this cheat sheetpave a safe road for developers that mitigates the possibility of XSS in your code. By following these recommendations, you can be reasonably sure your code is free of XSS.

Exploitation Conditions:

User input +

Check your project for these conditions:

$ semgrep --config p/minusworld.ruby-on-rails-xss

1. Server code: Unescaped variable enters template engine in Python code

1.A. Using html_safe()

html_safe() marks the supplied string as 'safe for HTML rendering.' This bypassesHTML escaping and potentially creates XSS vulnerabilities.

Recommendation: If needed, review each usage and exempt with # nosem.

Code example:

References:

1.B. Using content_tag()

content_tag()'s escaping behavior has changed between Rails 2 and 3. In Rails 2,no supplied content is escaped. In Rails 2 and 3, attribute names are not escaped.Further, the returned value is marked as 'safe,' the same as if html_safe() had been used.This confusing behavior makes it difficult to use content_tag() properly; improper usecan create XSS vulnerabilities in your application.

Recommendation: If necessary, prefer html_safe() due to its straightforward behavior.

Code example:

References:

1.C. Using raw()

raw() disables HTML escaping for the returned content. This permitsraw HTML to be rendered in a template, which could create a XSS vulnerability.

Recommendation: Prefer html_safe() if necessary.

Code example:

References:

1.D. Disabling of ActiveSupport#escape_html_entities_in_json

ActiveSupport#escape_html_entities_in_json is a setting which determines whether Hash#to_json() willescape HTML characters. Disabling this could create XSS vulnerabilities.

Recommendation: If HTML is needed in JSON, use JSON.generate() and review each usage carefully. Exempt each case with # nosem.

Code example:

References:

2. Server code: Bypassing the template engine

2.A. Manually creating an ERB template

Manually creating an ERB template could create a server-side template injection (SSTI) vulnerability ifit is created with user input. (This could also result in XSS.) Due to the severity of this type ofvulnerability, it is better to use a template file instead of creating templates in code.

Recommendation: Use ERB template files

Code example:

References:

2.B. Rendering an inline template with render inline:

render inline: is the same as creating a template manually and is therefore susceptibleto the same vulnerabilities as manually creating an ERB template. This can result in aSSTI or XSS vulnerability.

Recommendation: Use ERB template files

Code example:

References:

2.C. Using render text:

render text: unintuitively sets the Content-Type to text/html. This means anything renderedthrough render text: will be interpreted as HTML. Templates rendered in this manner could createa XSS vulnerability.

Recommendation: Use ERB template files

Code example:

References:

3. Templates: Variable explicitly unescaped

3.A. Using html_safe()

html_safe() marks the supplied string as 'safe for HTML rendering.' This bypassesHTML escaping and potentially creates XSS vulnerabilities.

Recommendation: Prefer using html_safe() in Ruby code instead of templates.

Code example:

References:

Ruby On Rails Cheat Sheet

3.B. Using content_tag()

content_tag()'s escaping behavior has changed between Rails 2 and 3. In Rails 2,no supplied content is escaped. In Rails 2 and 3, attribute names are not escaped.Further, the returned value is marked as 'safe,' the same as if html_safe() had been used.This confusing behavior makes it difficult to use content_tag() properly; improper usecan create XSS vulnerabilities in your application.

Recommendation: If necessary, prefer html_safe() in Ruby code due to its straightforward behavior.

Cheat

Code example:

References:

3.C. Using raw()

raw() disables HTML escaping for the returned content. This permitsraw HTML to be rendered in a template, which could create a XSS vulnerability.

Recommendation: Prefer html_safe() in Ruby code if necessary.

Code example:

References:

3.D. Using <% ... %>, which is an alias for html_safe()

The double-equals is an ERB alias for html_safe(). This will mark the contents as'safe for rendering' and may introduce an XSS vulnerability.

Recommendation: Prefer html_safe() in Ruby code if necessary.

Code example:

References:

Ruby On Rails Cheat Sheet Pdf

4. Templates: Variable in dangerous location

4.A. Unquoted variable in HTML attribute

Unquoted template variables rendered into HTML attributes is a potential XSS vectorbecause an attacker could inject JavaScript handlers which do not require HTML characters.An example handler might look like: onmouseover=alert(1). HTML escaping will not mitigate this.The variable must be quoted to avoid this.

Recommendation: Always use quotes around HTML attributes.

Code example:

References:

4.B. Variable in href attribute

Template variables in a href value could still accept the javascript: URI.This could be a XSS vulnerability. HTML escaping will not prevent this. Use link_tobeginning with a literal forward slash to generate links.

Recommendation: Use url_for to generate links.

Code example:

References:

4.C. Using link_to with unrestricted URL scheme

Detected a template variable used in 'link_to'. This will generate dynamic data in the 'href' attribute.This allows a malicious actor to input the 'javascript:' URI and is subject to cross-site scripting (XSS) attacks. If using a relative URL, start with a literal forward slash and concatenate the URL,like this: <%= link_to 'Here', '/'+@link %>. You may also consider setting the Content Security Policy (CSP) header.

Ruby Regex Cheat Sheet

Recommendation: If you must use this, add a literal forward-slash at the beginning to create a relative url.

Code example:

References:

4.D. Variable in <script> block

Template variables placed directly into JavaScript or similar are now directly in a code execution context.Normal HTML escaping will not prevent the possibility of code injection because code can be written withoutHTML characters. This creates the potential for XSS vulnerabilities, or worse.

Recommendation: If necessary, use the the escape_javascript function or its alias, j. Review each usage carefully and exempt with # nosem.

Code example:

References:

Mitigations

ItemNameSemgrep ruleRecommendation
1.A.Ban html_safe()ruby.rails.security.audit.xss.avoid-html-safe.avoid-html-safeIf needed, review each usage and exempt with # nosem.
1.B.Ban content_tag()ruby.rails.security.audit.xss.avoid-content-tag.avoid-content-tagIf necessary, prefer html_safe() due to its straightforward behavior.
1.C.Ban raw()ruby.rails.security.audit.xss.avoid-raw.avoid-rawPrefer html_safe() if necessary.
1.D.Ban disabling of ActiveSupport#escape_html_entities_in_jsonruby.lang.security.json-entity-escape.json-entity-escapeIf HTML is needed in JSON, use JSON.generate() and review each usage carefully. Exempt each case with # nosem.
2.A.Ban template creation in coderuby.rails.security.audit.xss.manual-template-creation.manual-template-creationUse ERB template files
2.B.Ban render inline:ruby.rails.security.audit.xss.avoid-render-inline.avoid-render-inlineUse ERB template files
2.C.Ban render text:ruby.rails.security.audit.xss.avoid-render-text.avoid-render-textUse ERB template files
3.A.Ban html_safe()ruby.rails.security.audit.xss.templates.avoid-html-safe.avoid-html-safePrefer using html_safe() in Ruby code instead of templates.
3.B.Ban content_tag()ruby.rails.security.audit.xss.templates.avoid-content-tag.avoid-content-tagIf necessary, prefer html_safe() in Ruby code due to its straightforward behavior.
3.C.Ban raw()ruby.rails.security.audit.xss.templates.avoid-raw.avoid-rawPrefer html_safe() in Ruby code if necessary.
3.D.Ban <% ... %>, which is an alias for html_safe()ruby.rails.security.audit.xss.templates.alias-for-html-safe.alias-for-html-safePrefer html_safe() in Ruby code if necessary.
4.A.Flag unquoted HTML attributes ERB expressionsruby.rails.security.audit.xss.templates.unquoted-attribute.unquoted-attributeAlways use quotes around HTML attributes.
4.B.Flag template variables in href attributesruby.rails.security.audit.xss.templates.var-in-href.var-in-hrefUse url_for to generate links.
4.C.Flag link_to in templatesruby.rails.security.audit.xss.templates.dangerous-link-to.dangerous-link-toIf you must use this, add a literal forward-slash at the beginning to create a relative url.
4.D.Ban template variables in <script> blocks.ruby.rails.security.audit.xss.templates.var-in-script-tag.var-in-script-tagIf necessary, use the the escape_javascript function or its alias, j. Review each usage carefully and exempt with # nosem.