Richa Sinha
Richa Sinha

Reputation: 1456

How to identify SQL injection issue while passing table name from params?

I am using brakeman gem to identify the sql injection issues in my rails project. Found a medium level injection issue with a sql query where i am passing the table name from the params. How do i avoid this issue. I tried surrounding the table name with `(ticks).

Following is the code causing this issue:

Student.find_by_sql("select * from students,#{params[:name]} where conditions")

Following is what i tried:

Student.find_by_sql("select * from students,`#{params[:name]}` where conditions")

I am using ruby 1.8.7 and rails 2.3.2.

Upvotes: 1

Views: 565

Answers (3)

Shimaa Marzouk
Shimaa Marzouk

Reputation: 467

You can do ActiveRecord::Base.connection.quote_table_name(params[:name])

Upvotes: 0

Justin
Justin

Reputation: 1621

You will want to use quote or quote_table_name, see http://api.rubyonrails.org/v2.3.8/classes/ActiveRecord/ConnectionAdapters/Quoting.html

How you access these methods will depend on where the code using it is located.

Upvotes: 1

user229044
user229044

Reputation: 239311

Don't interpolate params into your SQL statements.

You should be pulling the value out into a variable, and the comparing it against a whitelist:

class SomeController < ApplicationController

  KNOWN_GOOD_TABLES = %w(posts records songs items)

  def index
    @table_name = params[:name]

    raise "Invalid table" unless KNOWN_GOOD_TABLES.include?(table_name)

    Student.find_by_sql("select * from students,#{@table_name} where conditions")

  end
end

Upvotes: 2

Related Questions