views:

38

answers:

2

Does ModelName.new protect against sql injection?

Example:

@user = User.new(params[:user])

@user.save

I've read the rails security docs and didn't see anything about inserts via Model.new.

Thanks!

A: 

yes it protect against sql injection and is safe as params[:user] is HASH

you can check it with follwing example i assumr you get some invalid values in params[:user][:name]

  @user= User.new(params[:user])

  @user.save

AND

  @user= User.new()
  @user.name=params[:user][:name]  #your application may crash here or this is not sql injection safe
  @user.save

To avoid this you can use hash

  @user= User.new({:name=>params[:user][:name]})
  @user.save

After reading this i came to conlcusion neither .new & .save are safe from sql injection

Edited 

The mass-assignment feature may become a problem, as it allows an attacker to set any model’s attributes by manipulating the hash passed to a model’s new() method:

PLEASE READ 6 Mass Assignment for it's Problems and 6.1 Countermeasures for solution

Salil
can you explain why the former is safer than the latter? thanks.
apeacox
Thanks! Are there any rails docs that explain this? I know the security docs talk about find, but not about create/save.
bandhunt
@Salil - Take a look at http://guides.rubyonrails.org/security.html#mass-assignment . What you are saying is completely the opposite of what Rails security docs say .
NM
+2  A: 

Model.new has nothing to do with SQL injection as it is not the method that writes to the database .
It is the Model.save that actually writes to the database and takes care of SQL injection .

NM
you mean if i assign value individually and then use `Model.save` it will take care of SQL injection. if Yes, `you are wrong`
Salil
Look at this http://stackoverflow.com/questions/2144778/sql-injection-prevention-for-create-method-in-rails-controller . And http://guides.rubyonrails.org/security.html#mass-assignment .
NM
@NM - so ANY .save is always safe from injection? Since you can't do raw SQL with .save? Also, mass assignment has nothing to do with this.
bandhunt
@bandhunt - Take a look at this http://guides.rubyonrails.org/security.html#mass-assignment . Mass assignment has a role to play in this as someone might corrupt the hash that is passed to the new method and hence overwrite database values . So it is always a good practice to whitelist your mass assignment variables through attr_accessible . Hope that helps .
NM
Thanks! Yeah, I have a whitelist in my model is what I was trying to say. I was just wondering about sql injection right now.
bandhunt