Ruby on rails Rails这个查询对sql注入开放吗?

Ruby on rails Rails这个查询对sql注入开放吗?,ruby-on-rails,ruby,ruby-on-rails-3,activerecord,sql-injection,Ruby On Rails,Ruby,Ruby On Rails 3,Activerecord,Sql Injection,我还在学习如何使用ActiveRecord编写好的查询。我很好奇,由于我在查询中使用日期字段的方式,这个查询是否受到sql注入的影响 有人能指出任何明显的错误或更好的方法来写这个查询吗 @arrangements_for_month = Arrangement.joins(:timeslot). where("timeslots.timeslot BETWEEN '#{month}' AND '#{month.end_of_month}'", params[:id

我还在学习如何使用ActiveRecord编写好的查询。我很好奇,由于我在查询中使用日期字段的方式,这个查询是否受到sql注入的影响

有人能指出任何明显的错误或更好的方法来写这个查询吗

@arrangements_for_month =
  Arrangement.joins(:timeslot).
              where("timeslots.timeslot BETWEEN '#{month}' AND '#{month.end_of_month}'", params[:id]).
              order('location_id')

为了安全起见,您应该只使用包含参数的首选方式。退房:

将自己的条件构建为纯字符串会使您容易受到SQL注入攻击。例如,
Client.where(“first_name,如“%”{params[:first_name]}%')
是不安全的。有关使用数组处理条件的首选方法,请参见下一节

尝试:

如果您愿意的话,请注意,有一种替代方法可以使用ruby ranges定义范围条件,如链接指南的该部分所述:

Client.where(:created_at => (Time.now.midnight - 1.day)..Time.now.midnight)
因此,在不了解任何其他代码的情况下,您可能可以执行以下操作:

@arrangements_for_month = Arrangement.joins(:timeslot)
  .where("timeslots.timeslot" => month .. month.end_of_month)
  .order('location_id')

是的。每次将用户输入插入查询字符串时,该字符串都会受到攻击。如果
月份
为:

5' AND '8'; DROP TABLE timeslots;--
你可能有严重的麻烦。更不用说删除数据库等了

我还没有完全复制这个查询,但由于使用了acts_as_paranoid plugin],我不得不在查询中添加类似的内容:

SomeModel.pluck(:id)
 => [1, 2, 4, 3, 5, 6]

abc = 'a\');delete from some_models where id=6;--'
User.where("name = '#{abc}'")
 => []

SomeModel.pluck(:id)
 => [1, 2, 4, 3, 5] # please note that record with id 6 was deleted!
攻击之所以可能,是因为我可以提供
'
--
(开始评论)。当您使用建议的方式时,即使用.where(“name=?”,“my_name”),则不可能进行攻击。看看这个:

abc = 'a\');delete from some_models where id=5;--'

User.where("name = ?", abc)
 => []

SomeModel.pluck(:id)
 => [1, 2, 4, 3, 5] # this time record with id 5 was not deleted
这是第一个查询:

 User Load (1.5ms)  SELECT "users".* FROM "users" WHERE ("users"."deleted_at" IS NULL) AND (name = 'a');delete from some_models where id=6;--')
这是第二次

  User Load (1.0ms)  SELECT "users".* FROM "users" WHERE ("users"."deleted_at" IS NULL) AND (name = 'a'');delete from some_models where id=5;--')

注意第二个-
查询(name='a')

中附加的
'
只是一个一般性的注意事项,我发现在一些情况下,执行
参数[:id].to_I
可以避免rails中的安全漏洞。因此,即使rails声称在给定的方法中转义参数,请不要相信任何人:)您能否详细说明
params[:id]。to_i
如何防止安全漏洞?
“1”。to_i
返回整数
1
“some_string”。to_i
返回
0
为什么您在
尝试后立即给出的代码比他的更安全?
  User Load (1.0ms)  SELECT "users".* FROM "users" WHERE ("users"."deleted_at" IS NULL) AND (name = 'a'');delete from some_models where id=5;--')