In Rails, when I want to find by a user given value and avoid SQL injection (escape apostrophes and the like) I can do something like this:
Post.all(:conditions => ['title = ?', params[:title]])
I know that an unsafe way of doing this (possible SQL injection) is this:
Post.all(:conditions => "title = #{params[:title]}")
My question is, does the following method prevent SQL injection or not?
Post.all(:conditions => {:title => params[:title]})
Ruby on Rails gives you a lot of tools to protect against SQL injection attacks. Input sanitization is the most important tool for preventing SQL injection in your database. And Active Record automatically does this when you use it correctly.
Rails is one of the safest frameworks to run on when you know what its security issues are and how to fix them. The most common Ruby on Rails security threats are typical to all other frameworks. The CVE Details website has been tracking vulnerabilities in the framework since 2006.
Some common SQL injection examples include: Retrieving hidden data, where you can modify an SQL query to return additional results. Subverting application logic, where you can change a query to interfere with the application's logic. UNION attacks, where you can retrieve data from different database tables.
Yes, you should always sanitize input data. Sanitation isn't just about protecting you from injection, but also to validate types, restricted value (enums), ranges, etc.. While an attacker might not be able to manipulate your sql, they can still cause undesired behavior in the rest of your application.
Yes, it does. Only the second one is dangerous.
One good reference from the RoR Guides.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With