Hacking Ruby on Rails — SQL injection

This week we would like to introduce the new ongoing series about hacking Ruby on Rails. Actually about preventing being hacked when writing Ruby on Rails application. Today we will focus on SQL injection a.k.a. SQLi attack.

What is SQL injection?

SQL injection is an attack that tries to manipulate SQL query being sent to the server by injecting malicious SQL statement. Injection can be done with everything that comes from user — parameters, modified form content etc.

source: xkcd.com

Oh, now I remember! That’s the part where we drop tables!

Well, more or less. So, let’s get to it!

Let’s attack one of usual Rails controllers:

class TasksController < ApplicationController def index @tasks = Task.where project_id: params[:project_id] end end

What could go wrong right? Well, at this point not much — ActiveRecord saves us from SQLi with prepared statements. However — even hero like ActiveRecord has some vulnerabilities. Let’s change one little thing in our controller:

@tasks = Task.where "project_id = #{params[:project_id]}"

Now, sending

params[:project_id] = " '0' OR 1=1"

will let us see all of tasks, whether they are in the project we belong to, or not.

Well, allright. Who would consider writing where condition as string anyways? Most of us won’t (I hope so). Let’s try another popular ActiveRecord method, order.

@agents = User.where(agent: true).order params[:sort]

Looks familiar? I hope not, because it is vulnerable to SQL injection too:

params[:sort] = "(CASE SUBSTR(email, 1, 1) WHEN 'a' THEN 0 else 1 END)"

Using params[:sort] set like that allows us to slowly, query by query, guess the emails of the agents.

But.. but I thought we’ll be dropping tables, not listing stuff…

Do you think that hackers are just going around the web and drop tables all around? Well, no. They are not. They are going for information that can get them money. Information such as emails, passwords, bank data — everything they can sell. Dropping tables is cool, but it doesn’t make a living unless you’re security tester ;).

Summary

While Ruby on Rails is an awesome framework that protects us against dropping tables, it does not protect us against data leaks. And you can earn more money selling leaked data than dropping tables ;). Remember that no framework can replace cautious, experienced programmer and no automated checker can replace careful code review.

Further reading

We’re making workshops on security in RoR!

Want to know? Check here for more. Or read here.


Originally published at blog.railwaymen.org on April 13, 2016.

Show your support

Clapping shows how much you appreciated Railwaymen’s story.