SQL Injection Vulnerabilities in Rails

When we first start learning Ruby on Rails, one of the things we quickly pick up is that Active Record helps protect our applications from SQL injection attacks. However, even with this powerful ORM, our apps can still become vulnerable if we’re not careful with how we write our code.

# BAD PRACTICE

class UsersController < ApplicationController
  def index
    @users = User.where("users.name = #{params[:name]}")
  end
end

What would happen if a malicious user passed in the following URL parameter:

name=John;DROP TABLE USERS;

The code would execute exactly what the attacker has input, causing the entire USERS table to be dropped from your database—leaving you with potentially devastating data loss.

# GOOD PRACTICE

class UsersController < ApplicationController
  def index
    @users = User.where(name: params[:name])
  end
end

In this example, Rails automatically escapes the input, ensuring that any user-provided data is safely handled, preventing harmful SQL code from being executed

This is a simple example, but it shows how easy it is to make a mistake when using direct SQL queries in your Rails app. If you ever need to use raw SQL, always make sure to properly sanitize any user input to avoid security risks like SQL injection.

Author

Need to improve your Rails app? Let’s talk.


SCHEDULE A CALL TODAY

Leave a Reply

Your email address will not be published. Required fields are marked *