Prepare the security check environment for Rails 6

Purpose of this article

Visualize security measures in Rails We have built a mechanism to detect any security vulnerabilities. I hope it will be helpful for those who have trouble with the memorandum and Rails security measures. I wrote this article.

Construction environment

Gem

About Gem to use

Brakeman Official site: https://brakemanscanner.org/ brakeman.jpeg

A library that can detect security vulnerabilities such as SQL injection, XSS, and Dos attacks. There are more than 50 types of analysis items, which are also used on GitHub, Twitter, etc. We recommend using it as a code security measure for Rails.

・ Installation method

It's easy to install with bundler in your Rails project. Add gem under develop environment and install by bundle.

group :development do
  gem 'brakeman'
end

Easy to install globally.

gem install brakeman

·Execution method

It's easy to do.

Just run the brakeman command under the Rails environment and it will start running. The sample below is taken from the execution result of my application development environment. My app is a Docker-compose environment Running after docker-compose exec web bash. When the execution starts, the report will be output as shown below.

❯ docker-compose exec web bash
root@3dde8034237f:~# brakeman
Loading scanner...
Processing application in /app
Processing gems...
[Notice] Detected Rails 6 application
Processing configuration...
[Notice] Escaping HTML by default
Parsing files...
Processing initializers...
Processing libs...ed
Processing routes...          
Processing templates...       
Processing data flow in templates...
Processing models...          
Processing controllers...     
Processing data flow in controllers...
Indexing call sites...        
Running checks in parallel...
 - CheckBasicAuth
 - CheckBasicAuthTimingAttack
 - CheckCrossSiteScripting
 - CheckContentTag
 - CheckCookieSerialization
 - CheckCreateWith
 - CheckCSRFTokenForgeryCVE
 - CheckDefaultRoutes
 - CheckDeserialize
 - CheckDetailedExceptions
 - CheckDigestDoS
 - CheckDynamicFinders
 - CheckEscapeFunction
 - CheckEvaluation
 - CheckExecute
 - CheckFileAccess
 - CheckFileDisclosure
 - CheckFilterSkipping
 - CheckForgerySetting
 - CheckHeaderDoS
 - CheckI18nXSS
 - CheckJRubyXML
 - CheckJSONEncoding
 - CheckJSONEntityEscape
 - CheckJSONParsing
 - CheckLinkTo
 - CheckLinkToHref
 - CheckMailTo
 - CheckMassAssignment
 - CheckMimeTypeDoS
 - CheckModelAttrAccessible
 - CheckModelAttributes
 - CheckModelSerialize
 - CheckNestedAttributes
 - CheckNestedAttributesBypass
 - CheckNumberToCurrency
 - CheckPageCachingCVE
 - CheckPermitAttributes
 - CheckQuoteTableName
 - CheckRedirect
 - CheckRegexDoS
 - CheckRender
 - CheckRenderDoS
 - CheckRenderInline
 - CheckResponseSplitting
 - CheckRouteDoS
 - CheckSafeBufferManipulation
 - CheckSanitizeMethods
 - CheckSelectTag
 - CheckSelectVulnerability
 - CheckSend
 - CheckSendFile
 - CheckSessionManipulation
 - CheckSessionSettings
 - CheckSimpleFormat
 - CheckSingleQuotes
 - CheckSkipBeforeFilter
 - CheckSprocketsPathTraversal
 - CheckSQL
 - CheckSQLCVEs
 - CheckSSLVerify
 - CheckStripTags
 - CheckSymbolDoSCVE
 - CheckTemplateInjection
 - CheckTranslateBug
 - CheckUnsafeReflection
 - CheckValidationRegex
 - CheckWithoutProtection
 - CheckXMLDoS
 - CheckYAMLParsing
Checks finished, collecting results...
Generating report...

== Brakeman Report ==

Application Path: /app
Rails Version: 6.0.3.3
Brakeman Version: 4.9.1
Scan Date: 2020-09-15 02:51:42 +0000
Duration: 2.0712347 seconds
Checks Run: BasicAuth, BasicAuthTimingAttack, CSRFTokenForgeryCVE, ContentTag, CookieSerialization, CreateWith, CrossSiteScripting, DefaultRoutes, Deserialize, DetailedExceptions, DigestDoS, DynamicFinders, EscapeFunction, Evaluation, Execute, FileAccess, FileDisclosure, FilterSkipping, ForgerySetting, HeaderDoS, I18nXSS, JRubyXML, JSONEncoding, JSONEntityEscape, JSONParsing, LinkTo, LinkToHref, MailTo, MassAssignment, MimeTypeDoS, ModelAttrAccessible, ModelAttributes, ModelSerialize, NestedAttributes, NestedAttributesBypass, NumberToCurrency, PageCachingCVE, PermitAttributes, QuoteTableName, Redirect, RegexDoS, Render, RenderDoS, RenderInline, ResponseSplitting, RouteDoS, SQL, SQLCVEs, SSLVerify, SafeBufferManipulation, SanitizeMethods, SelectTag, SelectVulnerability, Send, SendFile, SessionManipulation, SessionSettings, SimpleFormat, SingleQuotes, SkipBeforeFilter, SprocketsPathTraversal, StripTags, SymbolDoSCVE, TemplateInjection, TranslateBug, UnsafeReflection, ValidationRegex, WithoutProtection, XMLDoS, YAMLParsing

== Overview ==

Controllers: 11
Models: 6
Templates: 56
Errors: 0
Security Warnings: 0

== Warning Types ==


No warnings found

(END)

A long report is output as above. The output message below the last Warning Types If it says No warnings found, it's OK.

By the way, if a warning occurs, it will be as follows. (The following is a quote from the official website Quick Start.) XSS warning.

When a warning occurs, it is necessary to read the content and take action.

・ Https://brakemanscanner.org/docs/quickstart/

brakeman_text_report.png

In addition, Brakeman can set the warning output level in 3 steps. The README on GitHub has the following explanation.

High - Either this is a simple warning (boolean value) or user input is very likely being used in unsafe ways. Medium - This generally indicates an unsafe use of a variable, but the variable may or may not be user input. Weak - Typically means user input was indirectly used in a potentially unsafe manner.

Translated in Japanese

The above level can be set with w1-w3 and output. w1 is the lowest level and w3 is the highest level. For example, w3 gives the following command. If you want to enter with CI settings, w2 etc. may be good.

brakeman -w3

Now you're ready to security check your Rails code.

Bundler-audit

https://github.com/rubysec/bundler-audit

bundler-audit-cbf59f68.png

A tool for detecting vulnerabilities in Gemfile.lock. You can detect unsafe gems. Installation in combination with Brakeman is recommended.

・ Installation method

Like Brakeman, add it to the Gemfile and bundle it.

group :development do
  gem 'bundler-audit'
end

·Execution method

Execute it with the following command.

bundle-audit

--If there is no vulnerability

root@3dde8034237f:~# bundler-audit
No vulnerabilities found

--If there is a vulnerability

The example below shows that actionpack version 3.2.10 is vulnerable. Also, as a solution, Solution: upgrade to ~> 2.3.15, ~> 3.0.19, ~> 3.1.10,> = 3.2.11 A version change is shown. If any vulnerabilities are shown, please perform the version correction work.

Name: actionpack
Version: 3.2.10
Advisory: OSVDB-89026
Criticality: High
URL: http://osvdb.org/show/osvdb/89026
Title: Ruby on Rails params_parser.rb Action Pack Type Casting Parameter Parsing Remote Code Execution
Solution: upgrade to ~> 2.3.15, ~> 3.0.19, ~> 3.1.10, >= 3.2.11

In addition, work that updates the Gemfile occurs, if it occurs, execute it as follows. The following is recommended on the official website even when using it in CI. bundler-audit makes all security recommendations related to Ruby libraries I'm using ruby-advisory-db, which is used to compile. This command updates ruby-advisory-db and then checks it.

bundle-audit check --update

Now you are ready to check for Gem vulnerabilities.

Afterword

Security measures require a wide variety of checks, from SQL and XSS measures to Dos attacks. In addition to code security measures I have to find vulnerabilities in the Gem I'm using I think it could be the target of attacks using that vulnerability.

The library introduced this time is code and Gem I think it is an effective means for implementing and visualizing security measures on both sides. I hope it will be helpful for those who develop Rails.

Recommended Posts

Prepare the security check environment for Rails 6
Prepare the format environment with "Rails" (VScode)
Prepare the environment for java11 and javaFx with Ubuntu 18.4
[Rails] Check the contents of the object
Check the migration status of rails
Check the root on the Rails browser
Change the default timezone for the rails app
Check the processing contents with [rails] binding.pry
[Rails] Reset the database in the production environment
Build a development environment for Docker + Rails6 + Postgresql
Check the options set for the running Java process
Prepare the JVM language development environment with WSL
Procedure for introducing Docker into the development environment of existing Rails applications [Rails, MySQL, Docker]
I summarized the naming conventions for each Rails
Prepare the environment of CentOS 8 with Sakura VPS
[Rails] Building an environment for developing web applications
How to check Rails commands in the terminal
For those who want to use MySQL for the database in the environment construction of Rails6 ~.
[Rails / Uniqueness constraint] How to check model validation on the console / Uniqueness constraint for multiple columns
I made a check tool for the release module
Docker the development environment of Ruby on Rails project
Stable development environment construction manual for "Rails6" with "Docker-compose"
What should I use for the testing framework [Rails]
Challenge the settings for developing with vue.js on Rails 6
Note that I stumbled upon building the Rails environment
SSL in the local environment of Docker / Rails / puma
What Java engineers need to prepare for the Java 11 release
Beginners use ubuntu in windows to prepare rails environment
Rails Docker environment construction
Master the [Rails] scope!
I tried to introduce Bootstrap 4 to the Rails 6 app [for beginners]
Building an environment for copying the book "Test Driven Development"
Change the injection target for each environment with Spring Boot 2
Beginners install docker for mac and prepare php7.0 operating environment
[Rails] I tried using the button_to method for the first time
Rails: I've summarized the model and database for a moment.
[Procedure 1 for beginners] Ruby on Rails: Construction of development environment
[Rails] Prepare dummy data to be used for testing [Faker]
[Environment construction] Get the Ruby on Rails 6 development environment within 1 hour
Change the setting value for each environment with Digdag (RubyOnRails)
[Rails] Create new files required for the application at once
Building an environment for creating apps with Rails and Vue
[For beginners] Build the environment for Ruby on Rails Tutorial 4th Edition (Rails 5.1) in less than an hour!