Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql injection prevention for create method in rails controller

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.

like image 525
udit Avatar asked Jan 27 '10 05:01

udit


People also ask

How does rails prevent SQL injection?

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.

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 are 3 methods SQL injection can be done by?

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.

Is a way to prevent SQL injection they takes the form of a template into which certain constant values are substituted during each execution it does not mix code and data?

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.


2 Answers

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.

like image 103
Alex Reisner Avatar answered Oct 06 '22 01:10

Alex Reisner


Note that your code example is safe from SQL injection as explained by Alex, but it's not safe from mass assignment exploits.

like image 30
John Topley Avatar answered Oct 06 '22 03:10

John Topley