As seen in comment_controller.rb:
def create
@comment = Comment.new(params[:comment])
@comment.save
end
Im assuming that this is SQL injection-unsafe. But what is the correct way of doing it?.. All the examples on the net deal with finds.
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.
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.
SQL injections typically fall under three categories: In-band SQLi (Classic), Inferential SQLi (Blind) and Out-of-band SQLi. You can classify SQL injections types based on the methods they use to access backend data and their damage potential.
Remediation. Prepared statements will protect against (almost) all SQL injection vulnerabilities. They take the form of a template in which certain constant values are substituted during execution for variables containing user input.
That code is safe from SQL injection attacks. The escaping is done by ActiveRecord, so any time you call a model's find
, create
, new
/save
, or any other method that does database interaction, you're OK. The only exception is if you use raw SQL for one of the options, for example:
Comment.find(:all, :conditions => "user_id = #{params[:user_id]}")
the preferred form is:
Comment.find(:all, :conditions => {:user_id => params[:user_id]})
which will be automatically protected against SQL injection.
Note that your code example is safe from SQL injection as explained by Alex, but it's not safe from mass assignment exploits.
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