Rails宝典之第二十五式: Sql injection

Sql injection是老问题,对如下查询:
[code]
def index
@tasks = Task.find(:all, :conditions => "name LIKE '%#{params[:query]}%'")
end
[/code]
当用户输入的query条件加上单引号时很容易通过sql injection来攻击我们的Rails程序
而我们使用如下查询方式就可以避免sql注入问题:
[code]
def index
@tasks = Task.find(:all, :conditions => ["name LIKE ?", '%' + params[:query] + '%'])
end
[/code]
为什么?
先来看看active_record文档里的一段话:
[code]
# == 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).
[/code]

OK,第一种是不安全的,后两者都是安全的。因为后两者都会使用sanitize方法来escape查询条件。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值