Security in Rails Applications

Some Common Application Vulnerabilities

  • Command Injection
  • SQL Injection
  • Cross Site Scripting (XSS)
  • Cross Origin Resource Sharing (CORS)
  • Cross Site Request Forgery
  • Encryption

Command Injection

Every technology we use gives us a gun to shoot ourselves in the skull but it's your choice to stay alive.

methods like:

eval(), System(), Kernel.exec()

SQL Injection

1' OR '1' = '1

Should this still be an issue? Oh yes it is

How not to do it:

@projects = Project.find(:all, :conditions => [ “name like ?”, “#{params[:name]}”] )

What to do instead

@projects = Project.find(:all, :conditions => “name like #{params[:name]}”)

Never throw user entries directly in queries!!!

Cross Site Scripting

Rails handles this nicely for you in views:

# controller
@product.description = "This is great bro <script>alert('You got pawned!!');</script>"

Default rails behavior:

<!-- Server code -->
<p><%= @product.name %></p>

<!-- Client-side response -->
<p>This is great bro <script>alert('You got pawned!!!');</script></p>

Doing it wrong:

<!-- Server code -->
<p><%= @product.name.html_safe %></p>

Well not so bad but there are gotchas

CORS

If you need to make CORS request you may unknowingly  permit unwanted users to make CORS

requests through your website too.

 

Some solutions to this are using the

rack-cors gem,

forcing SSL: config.force_ssl = true in application

config

CSRF (Cross Site Request Forgery)

CSRF web tokens on most web app framework  these days:

<meta name="csrf-token" content="RWzhQl41AXeBuyRjESfdJlkAiXNn38AUSe0eomMkbfoohw==" />

Strong Parameters in rails as an extra step against CSRF

Keep this line always in your application controller:

protect_from_forgery with: :exception

Encryption

You are smart but not smart enough

Don't use hashing algorithms that are made for integrity checks e.g MD5, SHA1, SHA256 (Not even with your custom salt)

Bcrypt/Blowfish is known to be the most reliable encryption for web applications and is used in gems like Devise

Your Security Checklist

  • Rails version at highest patch level
  • Updated and legitimate gems
  • Password encryption methods
  • Session security and cookie encryption
  • XSS with html_safe
  • SQL injection from trusting users data
  • Avoid hard-coding credentials in code

A Recommended Testing Gem:

Brakeman (https://github.com/presidentbeef/brakeman)

Thanks!!

Joseph Rex

@joerex101

http://strich.io