Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid sql injection with connection.execute

If a query can't be efficiently expressed using ActiveRecord, how to safely use ActiveRecord::Base.connection.execute when interpolating passed params attributes?

connection.execute "... #{params[:search]} ..."
like image 959
ave Avatar asked Feb 06 '15 14:02

ave


People also ask

Which methods can be used to avoid SQL injection?

The only sure way to prevent SQL Injection attacks is input validation and parametrized queries including prepared statements. The application code should never use the input directly. The developer must sanitize all input, not only web form inputs such as login forms.

What is an approach to avoid SQL injection vulnerabilities?

Developers can prevent SQL Injection vulnerabilities in web applications by utilizing parameterized database queries with bound, typed parameters and careful use of parameterized stored procedures in the database. This can be accomplished in a variety of programming languages including Java, . NET, PHP, and more.


2 Answers

You can use the methods in ActiveRecord::Sanitization::ClassMethods.

You do have to be slightly careful as they are protected and therefore only readily available for ActiveRecord::Base subclasses.

Within a model class you could do something like:

class MyModel < ActiveRecord::Base

  def bespoke_query(params)
    query = sanitize_sql(['select * from somewhere where a = ?', params[:search]])
    connection.execute(query)
  end

end

You can send the method to try it out on the console too:

> MyModel.send(:sanitize_sql, ["Evening Officer ?", "'Dibble'"])
=> "Evening Officer '\\'Dibble\\''"
like image 144
Shadwell Avatar answered Sep 17 '22 05:09

Shadwell


ActiveRecord has a sanitize method that allows you to clean the query first. Perhaps it's something you can look into: http://apidock.com/rails/v4.1.8/ActiveRecord/Sanitization/ClassMethods/sanitize

I'd be very careful inserting parameters directly like that though. What problem are you experiencing, that you cannot use ActiveRecord?

like image 42
codingbunny Avatar answered Sep 18 '22 05:09

codingbunny