Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

prevent sql injection in rails

I am using the following query to find nearest locations google maps. Is it immune to the Sql injection. If not can anyone help me to get rid of it.

AlphaCourses.find_by_sql("SELECT *,(  6371 * acos( cos( radians( #{@latitude} ) ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians( #{@longitude} ) ) + sin( radians( #{@latitude} ) ) * sin( radians( latitude ) ) ) ) AS distance FROM alpha_courses HAVING distance <= #{@radius} ORDER BY distance LIMIT 200")

Thanks in advance.

like image 914
P J S Avatar asked May 20 '13 07:05

P J S


People also ask

Does rails prevent SQL injection?

Summary. As you can see, Ruby on Rails, by default, won't save you from all SQL injection attack attempts. Some of the methods of its built-in library, Active Records, prevent these types of attacks automatically, but others don't. However, it's not that difficult to make your application secure.

How can SQL injection be prevented?

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.

Does sanitizing input prevent SQL injection?

To avoid SQL injection, all input that are to be concatenated in dynamic SQL must be correctly filtered and sanitized.


1 Answers

From: http://guides.rubyonrails.org/active_record_querying.html#pure-string-conditions

This code

....("orders_count = ?", params[:orders])

is highly preferable to this code:

....("orders_count = #{params[:orders]}")

because of argument safety. Putting the variable directly into the conditions string will pass the variable to the database as-is. This means that it will be an unescaped variable directly from a user who may have malicious intent. If you do this, you put your entire database at risk because once a user finds out he or she can exploit your database they can do just about anything to it. Never ever put your arguments directly inside the conditions string.

Apply this to your example!

like image 68
bjelli Avatar answered Oct 16 '22 06:10

bjelli