原创作者: hideto
阅读:1410次
评论:0条
更新时间:2011-05-26
Sql injection是老问题,对如下查询:
当用户输入的query条件加上单引号时很容易通过sql injection来攻击我们的Rails程序
而我们使用如下查询方式就可以避免sql注入问题:
为什么?
先来看看active_record文档里的一段话:
OK,第一种是不安全的,后两者都是安全的。因为后两者都会使用sanitize方法来escape查询条件。
def index @tasks = Task.find(:all, :conditions => "name LIKE '%#{params[:query]}%'") end
当用户输入的query条件加上单引号时很容易通过sql injection来攻击我们的Rails程序
而我们使用如下查询方式就可以避免sql注入问题:
def index @tasks = Task.find(:all, :conditions => ["name LIKE ?", '%' + params[:query] + '%']) end
为什么?
先来看看active_record文档里的一段话:
# == Conditions # # Conditions can either be specified as a string, array, or hash representing the WHERE-part of an SQL statement. # The array form is to be used when the condition input is tainted and requires sanitization. The string form can # be used for statements that don't involve tainted data. The hash form works much like the array form, except # only equality and range is possible. Examples: # # class User < ActiveRecord::Base # def self.authenticate_unsafely(user_name, password) # find(:first, :conditions => "user_name = '#{user_name}' AND password = '#{password}'") # end # # def self.authenticate_safely(user_name, password) # find(:first, :conditions => [ "user_name = ? AND password = ?", user_name, password ]) # end # # def self.authenticate_safely_simply(user_name, password) # find(:first, :conditions => { :user_name => user_name, :password => password }) # end # end # # The <tt>authenticate_unsafely</tt> method inserts the parameters directly into the query and is thus susceptible to SQL-injection # attacks if the <tt>user_name</tt> and +password+ parameters come directly from a HTTP request. The <tt>authenticate_safely</tt> and # <tt>authenticate_safely_simply</tt> both will sanitize the <tt>user_name</tt> and +password+ before inserting them in the query, # which will ensure that an attacker can't escape the query and fake the login (or worse).
OK,第一种是不安全的,后两者都是安全的。因为后两者都会使用sanitize方法来escape查询条件。
评论 共 0 条 请登录后发表评论