Skip to content

Instantly share code, notes, and snippets.

@rskelley9
Created March 21, 2017 05:11
Show Gist options
  • Save rskelley9/c17caa248e3b2a3ad95828ad4ad89b59 to your computer and use it in GitHub Desktop.
Save rskelley9/c17caa248e3b2a3ad95828ad4ad89b59 to your computer and use it in GitHub Desktop.
Some Examples of SQL Injection in Rails
params = {}
## Using string interpolation in where clauses is always dangerous
## BAD (Strings unescaped)
params[:firstname] = "'cat' OR lastname='Kelley'"
User.find(:first, conditions: "firstname = #{params[:firstname]}")
#=> AR Relation matching conditions
## GOOD (Escaped/Parameterized via Hash or Array)
User.find(:first, conditions: {firstname: params[:firstname]})
#=> nil
## OR
User.find_by_firstname(params[:firstname])
#=> nil
## OR
User.where(firstname: params[:firstname]).first
#=> nil
## BAD Where Clause
params[:email] = "'' OR is_admin=1"
User.where("email = #{params[:email]}").first
#=> AR Relation with admin user
## GOOD
User.where(email: params[:email]).first
#=> nil
## OR
User.find_by_email(params[:email])
## More to Avoid
## Bad and Weird
params[:column_name] = "ip_address from customers where email like '%rkelley%'--"
Customer.pluck("DISTINCT #{params[:column_name]}")
## Never Pass an Input Directly to :destroy_all, :delete_all, :update_all
params[:account_active] = "'' OR 1=1--'"
Customer.destroy_all("uid = ? AND account_active=#{params[:id]}", params[:uid])
params[:email] = "' OR 1=1;"
Customer.where("email LIKE '%#{params[:email]}%'").update_all(inactive: true)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment