SQL injection
Active Record won’t save you from string interpolation
Hash conditions and placeholders are safe. The moment a request value lands inside a SQL string, they aren’t.
In 2022, HackerOne disclosed a report against its own Rails app. Its engineers had an internal tool for running EXPLAIN ANALYZE on queries, wrapped in a transaction so whatever the query did would get rolled back. A researcher found a SQL injection in it, used it to break out of that transaction so the changes stuck, and from there got to running arbitrary Ruby on an application server (report #1663299). The company whose whole business is bug reports wrote one, which tells you how easy this is to write.
Active Record parameterizes queries when you let it. where(email: params[:email]) and where("email = ?", params[:email]) are both fine. The bug is always the same shape: a request value interpolated into a string that Rails hands to the database as-is.
The basic bug
@user = User.where("email = '#{params[:email]}'").first
Send ' OR '1'='1 as the email and you get the first user in the table, which is usually an admin. With a UNION SELECT, you can read any table the app’s database user can read, which is all of them.
The basic fix
@user = User.find_by( params[])
Hash conditions, or ? placeholders when you need an operator the hash syntax doesn’t cover. Either way the value travels separately from the SQL.
The hardcore version
def index
@products = Product.where("name ILIKE '%#{params[:q]}%'")
.order("#{params[:sort]} #{params[:direction]}")
end
Search and sort are where interpolation sneaks back in, because column names and ASC can’t be bound as parameters. Since Rails 6.1, order and pluck raise ActiveRecord::UnknownAttributeReference for arguments that don’t look like column names, which blocks the obvious payloads in sort. The ILIKE clause has no such protection, and "Rails blocks most of it" isn’t a security model anyway.
The filter version
def index
@orders = Current.account.orders
params.fetch(, {}).each do |column, value|
@orders = @orders.where("#{column} = ?", value)
end
end
The values are bound, which is what code review looks for, so it passes. The keys aren’t. A data table with column filters sends filter[status]=paid, and nothing stops a request from sending a key that’s a chunk of SQL instead of a column name. The key lands in the WHERE clause as written, and the account scoping on the first line stops meaning much.
FILTERABLE = .freeze
def index
@orders = Current.account.orders
params.fetch(, {}).permit(*FILTERABLE).each do |column, value|
@orders = @orders.where(column => value)
end
end
Permit the keys you support and use hash conditions, which quote the column name for you. Unknown filters get dropped instead of interpolated.
Gems that build filters for you can leak data without any injection at all. Before 4.0, Ransack let a search filter on any attribute by default, associations included. Positive Security showed how that let an attacker recover password reset tokens one character at a time with _start predicates: no SQL injection, just asking the search "does any user’s token start with a?" over and over. Ransack 4.0 now requires an explicit allowlist on every model:
class User < ApplicationRecord
def self.ransackable_attributes(auth_object = nil)
end
def self.ransackable_associations(auth_object = nil)
[]
end
end
Don’t satisfy the requirement with column_names to make the upgrade error go away. That puts you right back where 3.x was.
The Arel.sql version
def index
@products = Product.order(Arel.sql("#{params[:sort]} #{params[:direction]}"))
end
This is what the hardcore version turns into after an upgrade to 6.1. order starts raising UnknownAttributeReference, the error says known-safe values can be wrapped in Arel.sql, and somebody wraps the request params. Arel.sql means "I promise I wrote this SQL." It doesn’t escape anything; it switches the check off. The error message also says not to pass request parameters, but nobody reads past the first sentence of an error message (I’m including myself).
Use the allowlist from Fix #1 below. Then grep for Arel.sql( with #{ inside it, and for select, group, having, find_by_sql, and execute with interpolation, since those never got the 6.1 check in the first place.
Fix #1: Placeholders and an allowlist
SORTABLE = .freeze
def index
@products = Product.all
@products = @products.where("name ILIKE ?", "%#{Product.sanitize_sql_like(params[:q])}%") if params[].present?
@products = @products.order(sort_column => sort_direction)
end
private
def sort_column
SORTABLE.include?(params[]) ? params[] : "created_at"
end
def sort_direction
params[] == "asc" ? :
end
The #{} in the search line is fine: it builds the value that gets bound to ?, not SQL. sanitize_sql_like escapes % and _ so a search for 100% doesn’t match everything. The sort only ever reaches the database as one of three known column names.
Fix #2: Move it into a query object
class ProductSearch
SORTS = {
"name" => Product.arel_table[],
"price" => Product.arel_table[],
"newest" => Product.arel_table[]
}.freeze
def initialize(params)
@params = params
end
def results
scope = Product.all
scope = scope.where("name ILIKE ?", "%#{Product.sanitize_sql_like(@params[:q])}%") if @params[].present?
scope.order(direction(SORTS.fetch(@params[], SORTS["newest"])))
end
private
def direction(column)
@params[] == "asc" ? column.asc : column.desc
end
end
Same rules, one place. The public sort names are decoupled from the column names, and every search screen that needs filtering gets the safe version by default instead of a fresh copy-paste of the unsafe one. Controllers shrink to ProductSearch.new(params).results.
Fix #3: Limit what a successful injection can do
CREATE ROLE app_web LOGIN;
GRANT CONNECT ON DATABASE app_production TO app_web;
GRANT USAGE ON SCHEMA public TO app_web;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO app_web;
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO app_web;
ALTER DEFAULT PRIVILEGES FOR ROLE app_owner IN SCHEMA public
GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO app_web;
REVOKE ALL ON TABLE admin_audit_logs FROM app_web;
ALTER ROLE app_web SET statement_timeout = '5s';
Most Rails apps connect as the role that owns the schema, so an injection can drop and alter tables too, not just read them. Run migrations as app_owner and serve requests as app_web, which can read and write rows and nothing else. The statement timeout kills the pg_sleep and giant-join tricks attackers use to probe blind injection. You’ll still have the bug, but the bug can do a lot less.
HackerOne’s report teaches the same lesson from the other side. A transaction you plan to roll back isn’t a sandbox, because the SQL inside it can end the transaction. If a tool has to run SQL that someone typed, point it at something that can’t write at all:
def create
@plan = ActiveRecord::Base.connected_to( ) do
ActiveRecord::Base.connection.select_all("EXPLAIN #{params[:sql]}")
end
end
With connects_to pointing the reading role at a hot standby replica, Postgres rejects every write no matter what got appended to the query. The tool still runs whatever an admin types (that’s its job), but the worst case is a slow read. We don’t know exactly what HackerOne changed; this is how we’d build it.
Brakeman flags most interpolated SQL statically. Run it in CI and read what it tells you.