SQL Injection in Rails

Contrary to widespread belief, SQL injection is a problem in Rails applications, too. But it’s less frequent by far than in other frameworks. Still, SQL injection (together with other types of injection) is the #1 vulnerability in web applications according to the OWASP Top 10. Here’s a common example of SQL injection in Rails:

params[:name] = "') OR 1--"
User.where("name = '#{params[:name]}'").first
This will run: SELECT "users".* FROM "users" WHERE (name = '') OR 1--') LIMIT 1

Note that this will return a random user because the condition will be true for every record. The “--” is a comment and depends on the database configuration to work.

Database configuration against SQL injection

The OWASP recommends the least privileges for a DB user

Rails SQL injection cheat sheet

Many examples of what NOT to do

Rails SQL Injection with LIKE

Injection with % in SQL LIKE is common and may lead to long queries.

Countermeasures against SQL Injection in Rails

Testing every statement for SQL Injection seems tedious. Good countermeasures are a static code scanner like brakeman, some unit tests if user input goes directly into SQL and periodic manual security code audits. The cheat sheet above gives you plenty of examples of what not to do. Search your entire code for the ActiveRecord methods and option names from the cheat sheet to do an audit yourself.