Friday, August 22, 2008

SQL Injection in Ruby On Rails

SQL Injection
One of the most common security holes in web applications is that they pass user input
directly to the database without quoting. Thus, a malicious user can fairly easily run all the SQL
he wants to on the server. An example of this would be a search form submission that is handled
by the following code:

@courses = Course.find(:conditions => "name = '#{params[:q]'")

Now let’s say JHON puts the following string into the search form:

"science'; delete from courses; --"

The resulting SQL query will be as follows:

SELECT * from courses where name = 'science'; delete from courses; --'

This is a perfectly valid SQL query and will effectively wipe out the whole courses table. Thus,
you should never, ever, pass anything unquoted to the :conditions parameter of ActiveRecord
finders. Instead, use the bind variable syntax:

@courses = Course.find(:conditions => ["name = ?", params[:q]])

You can pass in as many question mark/variable pairs you need. They will be parsed and
quoted in the order they are specified.

Another option in simple cases is to use the magic finders, where the parameter value is
automatically quoted, too:
@courses = Course.find_by_name(params[:q])

No comments: