How to use Brakeman to find Rails security vulnerabilities

How to use Brakeman to find Rails security vulnerabilities

Security is a huge concern for web applications. To protect your Rails app from potential vulnerabilities and threats, it’s essential to perform regular security assessments opens a new window . Brakeman opens a new window , a widely used static analysis tool for Ruby on Rails, can help you identify security vulnerabilities proactively.

In this article, we’ll explore how to use Brakeman to check your Rails app for security vulnerabilities.

What is Brakeman?

Brakeman is an open-source static analysis tool specifically designed for Ruby on Rails applications. It scans your application’s source code to identify potential security vulnerabilities. Here are some common security vulnerabilities that Brakeman can detect:

  • SQL Injection opens a new window : Brakeman can identify code patterns that may lead to SQL injection vulnerabilities, such as improper use of user input in SQL queries.
  • Cross-Site Scripting (XSS) opens a new window : Brakeman scans for potential XSS vulnerabilities by analyzing how user input such as parameters, cookies, and model attributes are used in views, and whether the code uses “dangerous” methods such as link_to.
  • Mass Assignment opens a new window : Brakeman can detect instances where user input is directly assigned to model attributes, potentially leading to unauthorized changes in database records.
  • Command Injection opens a new window : Brakeman can detect instances where user-controlled data is used in system commands, which can lead to remote code execution vulnerabilities.
  • Remote Code Execution opens a new window : Brakeman can detect instances where user-controlled data is used to control code in ways that are not intended by the application’s authors.

The full list of vulnerabilities that Brakeman can detect can be found in Brakeman Warning Types opens a new window .

Getting Started with Brakeman

The easiest way to get started with Brakeman is by installing it as a gem. You can install Brakeman as a gem by running the following command: gem install brakeman.

To run Brakeman, navigate to your Rails application’s root directory and use the following command: brakeman. Brakeman will then analyze your code and generate a report of any potential security issues and their severity.

You can also run Brakeman as a step in your CI/CD pipeline. To do that, you can follow the instructions on the Readme opens a new window .

How to Read Your Security Results

Brakeman will generate a report that looks like this:

== Brakeman Report ==

Application Path: /Users/gelsey/code/test_project
Rails Version: 6.0.3.4
Brakeman Version: 5.4.1
Scan Date: 2023-10-30 14:23:25 -0400
Duration: 0.391331 seconds
Checks Run: BasicAuth, BasicAuthTimingAttack, CSRFTokenForgeryCVE, ContentTag, CookieSerialization, CreateWith, CrossSiteScripting, Def
aultRoutes, Deserialize, DetailedExceptions, DigestDoS, DynamicFinders, EOLRails, EOLRuby, EscapeFunction, Evaluation, Execute, FileAcc
ess, FileDisclosure, FilterSkipping, ForgerySetting, HeaderDoS, I18nXSS, JRubyXML, JSONEncoding, JSONEntityEscape, JSONParsing, LinkTo,
 LinkToHref, MailTo, MassAssignment, MimeTypeDoS, ModelAttrAccessible, ModelAttributes, ModelSerialize, NestedAttributes, NestedAttribu
tesBypass, NumberToCurrency, PageCachingCVE, Pathname, PermitAttributes, QuoteTableName, Redirect, RegexDoS, Render, RenderDoS, RenderI
nline, ResponseSplitting, RouteDoS, SQL, SQLCVEs, SSLVerify, SafeBufferManipulation, SanitizeConfigCve, SanitizeMethods, SelectTag, Sel
ectVulnerability, Send, SendFile, SessionManipulation, SessionSettings, SimpleFormat, SingleQuotes, SkipBeforeFilter, SprocketsPathTrav
ersal, StripTags, SymbolDoSCVE, TemplateInjection, TranslateBug, UnsafeReflection, UnsafeReflectionMethods, ValidationRegex, VerbConfus
ion, WeakRSAKey, WithoutProtection, XMLDoS, YAMLParsing

== Overview ==

Controllers: 6
Models: 7
Templates: 17
Errors: 0
Security Warnings: 5

== Warning Types ==

Cross-Site Scripting: 1
HTTP Verb Confusion: 1
SQL Injection: 1
Unmaintained Dependency: 2

== Warnings ==

Confidence: High
Category: Unmaintained Dependency
Check: EOLRuby
Message: Support for Ruby 2.7.1 ended on 2023-03-31
File: .ruby-version
Line: 1

Confidence: High
Category: Unmaintained Dependency
Check: EOLRails
Message: Support for Rails 6.0.3.4 ended on 2023-06-01
File: Gemfile.lock
Line: 143

Confidence: Medium
Category: SQL Injection
Check: SQL
Message: Possible SQL injection
Code: Restaurant.joins(:categories).where("#{"restaurants.#{"address"} LIKE ?"} AND #{"categories.#{"name"} = ?"} AND #{"restaurants.#{key} = ?"}", *search_params.select do  (value != "")  end.values)
File: app/controllers/pages_controller.rb
Line: 25

Confidence: Weak
Category: Cross-Site Scripting
Check: SanitizeConfigCve
Message: rails-html-sanitizer 1.3.0 is vulnerable to cross-site scripting when `select` and `style` tags are allowed (CVE-2022-32209). Upgrade to 1.4.3 or newer
File: Gemfile.lock
Line: 161

Some of the information in this report might be self-explanatory, other things might not be so clear. Here is an explanation of what the above elements mean:

Check: The checks that are run for Brakeman. You can run a subset of checks, or just stick with the default checks. For a list of checks, run brakeman —checks. You can add and remove checks as needed. To find out more about how to do that, check out Brakeman’s Options documentation opens a new window .

Warning types: These are the warning types found in Brakeman Warning Types opens a new window .

Confidence: According to the documentation opens a new window , the confidence level indicates how certain Brakeman is that the warning is a real problem. There are three confidence levels: high, medium, and weak.

Category: This is the category that the particular vulnerability belongs to. It is also analogous to Brakeman Warning Types opens a new window .

It’s important to note that Brakeman can only do so much - it can not 100% guarantee that a potential warning is a true vulnerability. It’s important to review all potential warnings to determine whether they are actual security risks or false positives opens a new window .

Mitigating Security Vulnerabilities

Identifying vulnerabilities is only the first step. To enhance your Rails app’s security, you must address and mitigate the issues Brakeman highlights:

  • Follow Best Practices: Adhere to Rails security best practices, such as using strong parameters, escaping user input, and validating user input thoroughly.
  • Patch Vulnerabilities: Update your code to fix the vulnerabilities detected by Brakeman. This may involve changing the code logic, sanitizing user input, or implementing proper access controls.
  • Regular Scanning: Integrate Brakeman into your continuous integration/continuous deployment (CI/CD) pipeline to ensure that new code changes are scanned for security issues automatically.
  • Stay Informed: Keep up to date with the latest security threats and best practices in Rails application security to proactively address emerging risks.

Conclusion

Brakeman is a powerful tool for enhancing the security of your Ruby on Rails applications. By regularly scanning your codebase with Brakeman and addressing the vulnerabilities it identifies, you can significantly reduce the risk of security breaches and protect your users’ data.

Remember that security is an ongoing process, so make security assessments and mitigation a part of your development workflow to maintain a robust and secure Rails application.

Need help keeping your Rails applications secure? Contact us for a security audit! opens a new window

Get the book