Using Brakeman prevents security incidents with Rails projects

Image for post

In this article, we discuss about Brakeman. After the introduction of Rails, Ruby started to be used for web development the world over. Rails is a full-featured and convenient framework, but perhaps because of this feeling that Rails will take care of everything for you, it is sometimes used carelessly, without regard for security. If one writes code carelessly, it’s easy to end up creating code that can become the cause of security incidents.

That’s why you want to use Brakeman . Brakeman is a tool that will conduct a static analysis your Rails project with an emphasis on security.

Installing Brakeman

Brakeman can be installed with Rubygems.

$ gem install brakeman

Of course, it’s also possible to install by entering a line in the  of your Rails project.

group :development do
  gem 'brakeman', :require => false
end

Using Brakeman

To use, just run the  command in your Rails project.

$ brakeman /path/to/rails/project

When you do, the analysis will run and output the results. For example, results such as the ones below will appear. There might be a redirect, or a warning regarding views.

+BRAKEMAN REPORT+

Application path: /path/to/rails/project
Rails version: 4.2.8
Brakeman version: 3.6.2
Started at 2017-06-11 16:22:29 +0900
Duration: 0.357863 seconds
Checks run: BasicAuth, BasicAuthTimingAttack, ContentTag, CreateWith, CrossSiteScripting, DefaultRoutes, Deserialize, DetailedExceptions, DigestDoS, DynamicFinders, EscapeFunction, Evaluation, Execute, FileAccess, FileDisclosure, FilterSkipping, ForgerySetting, HeaderDoS, I18nXSS, JRubyXML, JSONEncoding, JSONParsing, LinkTo, LinkToHref, MailTo, MassAssignment, MimeTypeDoS, ModelAttrAccessible, ModelAttributes, ModelSerialize, NestedAttributes, NestedAttributesBypass, NumberToCurrency, QuoteTableName, Redirect, RegexDoS, Render, RenderDoS, RenderInline, ResponseSplitting, RouteDoS, SQL, SQLCVEs, SSLVerify, SafeBufferManipulation, SanitizeMethods, SelectTag, SelectVulnerability, Send, SendFile, SessionManipulation, SessionSettings, SimpleFormat, SingleQuotes, SkipBeforeFilter, StripTags, SymbolDoSCVE, TranslateBug, UnsafeReflection, ValidationRegex, WithoutProtection, XMLDoS, YAMLParsing


+SUMMARY+

+-------------------+-------+
| Scanned/Reported  | Total |
+-------------------+-------+
| Controllers       | 14    |
| Models            | 7     |
| Templates         | 23    |
| Errors            | 0     |
| Security Warnings | 8 (1) |
+-------------------+-------+

+----------------------+-------+
| Warning Type         | Total |
+----------------------+-------+
| Cross Site Scripting | 5     |
| Dynamic Render Path  | 2     |
| Redirect             | 1     |
+----------------------+-------+


+SECURITY WARNINGS+

+------------+-------------------+----------+----------------------+------------------------------------------------------------------------------------------------------------------->>
| Confidence | Class             | Method   | Warning Type         | Message                                                                                                           >>
+------------+-------------------+----------+----------------------+------------------------------------------------------------------------------------------------------------------->>
| High       | OauthsController  | callback | Redirect             | Possible unprotected redirect near line 14: redirect_to(+Bot.find_by_domain(request.host.split(".")[0]).admin_edit>>
| Medium     | ScriptsController | show     | Cross Site Scripting | Unescaped model attribute rendered inline near line 9: render(text => +ChatLog.find_by_uniq_key(params[:id]).bot.c>>
+------------+-------------------+----------+----------------------+------------------------------------------------------------------------------------------------------------------->>


View Warnings:

+------------+------------------------------------------------+----------------------+------------------------------------------------------------------------------------------------->>
| Confidence | Template                                       | Warning Type         | Message                                                                                         >>
+------------+------------------------------------------------+----------------------+------------------------------------------------------------------------------------------------->>
| Medium     | shared/_bot_header (Template:admin/bots/index) | Cross Site Scripting | Unsafe model attribute in link_to href near line 12: link_to(+current_user.bots.find_by_domain(r>>
| Medium     | shared/_bot_header (Template:admin/bots/index) | Cross Site Scripting | Unsafe model attribute in link_to href near line 17: link_to(+current_user.bots.find_by_domain(r>>
| Medium     | docs/show (DocsController#show)                | Dynamic Render Path  | Render path contains parameter value near line 4: render(partial => "shared/doc_#{+params[:id].g>>
| Medium     | docs/show (DocsController#show)                | Dynamic Render Path  | Render path contains parameter value near line 9: render(partial => "shared/doc_#{+params[:id].g>>
| Weak       | bots/show (BotsController#index)               | Cross Site Scripting | Unescaped model attribute near line 17: markdown.render(strip_tags(+Bot.find_by_domain(request.h>>
| Weak       | bots/show (BotsController#index)               | Cross Site Scripting | Unescaped model attribute near line 24: markdown.render(strip_tags(+Bot.find_by_domain(request.h>>
+------------+------------------------------------------------+----------------------+------------------------------------------------------------------------------------------------->>

Afterwards, just follow these instructions and edit your project in order to fix the issues.

In addition to the standard output, result content may also be outputted in HTML/JSON/CSV/TSV/Markdown/Code Climate. Each can be selected with an extension or  option. Multiple file output is also supported, so it’s easier to indicate your preference with an extension.

$ brakeman -o output.html -o output.json

Supported Versions of Rails, etc.

Brakeman can be used with a wide selection of Rails versions, from 2.3 to 5.x. It can also be used to for a syntactic analysis of Ruby 1.8, but the version of Ruby itself must be 1.9.3 or higher.

Comparing Results with Past Data

Using the  option allows you to make comparisons with past results. This feature uses JSON files, so it will be necessary to prepare a JSON file as output. If you do so, it will be easy to confirm when new problems are occurring (or when they’ve been fixed).

$ brakeman --compare  output.json
Checks finished, collecting results...
{
  "new": [
    {
      "warning_type": "Cross Site Scripting",
      "warning_code": 84,
      "fingerprint": "947ce5634858e206076c3d1f6379c11ccb62aa3430b427150975388a5d3c4a68",
      "check_name": "RenderInline",
      "message": "Unescaped parameter value rendered inline",
      "file": "app/controllers/bots_controller.rb",
      "line": 15,
      "link": "http://brakemanscanner.org/docs/warning_types/cross_site_scripting/",
      "code": "render(text => params[\"hub.challenge\"], { :layout => false })",
      "render_path": null,
      "location": {
        "type": "method",
        "class": "BotsController",
        "method": "index"
      },
      "user_input": "params[\"hub.challenge\"]",
      "confidence": "High"
    }
  ],
  "fixed": [

  ]
}

With Heavy Rails Projects

Rails has a tendency towards being a monolithic system, so it’s easy for the scope of your project to grow quite large. Because of this, it may take a while for Brakeman to run a check. If so, you can use the  option to speed up the analysis. Although this option does run more quickly, it checks fewer items.

Creating a Settings File

Just as with other static analysis tools, the categories checked by Brakeman can be controlled with a settings file. For each of Brakeman’s featured warnings and notices, you can decided whether to disable or enable with a dialog. The settings file will be saved under . If you’d like to generate one, use the  option.

$ brakeman -I
  :
Checks finished, collecting results...
Filtering warnings...
Input file: |config/brakeman.ignore|        	
No such file. Continue with empty config? y
1. Inspect all warnings
2. Hide previously ignored warnings
3. Prune obsolete ignored warnings
4. Skip - use current ignore configuration
?  1
--------------------
Actions:
i - Add warning to ignore list
n - Add warning to ignore list and add note
s - Skip this warning (will remain ignored or shown)
u - Remove this warning from ignore list
a - Ignore this warning and all remaining warnings
k - Skip this warning and all remaining warnings
q - Quit, do not update ignored warnings
? - Display this help
--------------------
Confidence: Weak
Category: Cross Site Scripting
Message: Unescaped model attribute
Code: markdown.render(strip_tags(Bot.find_by_domain(request.host.split(".")[0]).readme.to_s))
File: app/views/bots/show.html.erb
Line: 17
Action: (i, n, k, u, a, s, q, ?) i
--------------------
Ignoring 8 warnings
Showing 0 warnings
1. Save changes
2. Start over
3. Quit, do not save changes
?  1
Output file: |config/brakeman.ignore|

If you use this setting file to disable all of the warnings, you will stop receiving them afterwards. This isn’t a good situation, so it’s best to confirm the contents and quickly correct the items which need to be fixed. Once you’ve confirmed that an item isn’t a problem, it’s alright to leave it disabled.

Rails is a framework with a very high level of features, but that doesn’t mean it’s fully secure. The same can be said for any programming language or framework. Small mistakes can lead to security incidents. By using Brakeman, you may be able to discover some of these problems and fix them.

SideCI’s automatic code review also supports Brakeman. For individual developers, just install Brakeman locally and you’re done. However, for teams-oriented development systems, checking in the cloud is the more effective way to improve the quality of all of the project’s code.

You can get a free trial from SideCI. Give it a try it with your Rails project!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.