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.

[portfolio display_types=false display_tags=false display_content=true columns=3 showposts=3 orderby=title include_tag=sqli-intro]

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.