Rails SQL Injection with LIKE

SQL ‘LIKE’ injection is a form of denial-of-service attack where an end-user adds wildcards to a SQL query that uses the ‘LIKE’ keyword. This greatly increases the time it takes to run the query. If your Rails application allows user searching using email:

users = User.includes(:profile).where("profiles.email LIKE ?", "#{term}%“).all

A user can include percent signs in their search and vastly increase the query duration, slowing down the database.

What are the risks?

Because the attack causes database queries to skip the index and run slower, the main risk is a denial-of-service attack. Many searches could bog down the database.

Countermeasures in Rails

Sanitizing user input is the best way to prevent injection. For Rails version 4.2 or greater, ActiveRecord has a new helper function, sanitize_sql_like, which escapes out the percent signs (and the _ character).