How to compile and execute a SQL query SAFELY?

u = Users.new #
x = ‘3; delete from users’ # user-supplied data, which is supposed to
be an integer
u.connection.execute(“select * from users where id = #{x}”) # deletes
ALL records

How would one guard against this SQL injection?

The best way I found so far is to use the quote method as follows:

u.connection.execute(“select * from users where id = #{u.quote x}”)

Is there a preferred/safer/better way?

-pachl

Users.find(x)

On 17/10/06, clintpachl [email protected] wrote:

u.connection.execute(“select * from users where id = #{u.quote x}”)

Is there a preferred/safer/better way?

-pachl


http://www.snowblink.co.uk/

clintpachl <[email protected]…> writes:

u = Users.new #
x = ‘3; delete from users’ # user-supplied data, which is supposed to
be an integer
u.connection.execute(“select * from users where id = #{x}”) # deletes
ALL records

How would one guard against this SQL injection?

In the case of an ID:

User.find(supposed_id)

otherwise ActiveRecord has a built-in way to escape SQL:

User.find(:all, :conditions => [“my_field = ?”, supposed_field])

See http://api.rubyonrails.org/classes/ActiveRecord/Base.html for
details

Gareth

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs