【问题标题】:How to identify SQL injection issue while passing table name from params?从参数传递表名时如何识别 SQL 注入问题?
【发布时间】:2014-12-30 05:03:09
【问题描述】:

我正在使用brakeman gem 来识别我的rails 项目中的sql 注入问题。发现一个中等级别的注入问题,我从参数传递表名的 sql 查询。我如何避免这个问题。我尝试用 `(ticks) 包围表名。

以下是导致此问题的代码:

Student.find_by_sql("select * from students,#{params[:name]} where conditions")

以下是我尝试过的:

Student.find_by_sql("select * from students,`#{params[:name]}` where conditions")

我正在使用 ruby​​ 1.8.7 和 rails 2.3.2。

【问题讨论】:

  • 你错过了一堆"...
  • rails 不使用准备好的语句,?
  • 使用find_by_sql 可能是代码异味。您能否添加一个更好的示例,您想要归档哪些内容以及哪些部分需要动态化?目前我认为Student.joins(params[:name]).where... 可能是更好的方法。
  • 我刚刚写了一个任意代码@meager。
  • @spickerman,where 不适用于我正在使用的版本。

标签: ruby-on-rails ruby


【解决方案1】:

不要将params 插入到您的 SQL 语句中。

您应该将值提取到变量中,并将其与白名单进行比较:

class SomeController < ApplicationController

  KNOWN_GOOD_TABLES = %w(posts records songs items)

  def index
    @table_name = params[:name]

    raise "Invalid table" unless KNOWN_GOOD_TABLES.include?(table_name)

    Student.find_by_sql("select * from students,#{@table_name} where conditions")

  end
end

【讨论】:

  • 不能这样做,表名是动态的。这是一个临时表。
【解决方案2】:

您会想要使用quotequote_table_name,请参阅http://api.rubyonrails.org/v2.3.8/classes/ActiveRecord/ConnectionAdapters/Quoting.html

您如何访问这些方法将取决于使用它的代码所在的位置。

【讨论】:

  • quote_table_name 使用 quote_column_name 最终在表格名称周围打勾。因此与我尝试的没有什么不同。 Brakeman 仍在将其检测为 sql 注入问题。
  • 您必须将“代码中存在漏洞”与“Brakeman 对此发出警告”分开。 Brakeman 并不完美(没有 SAST),并且通常无法检测到何时使用了有效的保护措施。在这种情况下,quoted_table_name 将不再发出警告。它等同于您手动在值周围加上反引号的代码,即使在简单的情况下结果是相同的。
【解决方案3】:

你可以ActiveRecord::Base.connection.quote_table_name(params[:name])

【讨论】:

    猜你喜欢
    • 2021-03-27
    • 1970-01-01
    • 2014-07-14
    • 1970-01-01
    • 2020-03-26
    • 2014-04-25
    • 2019-08-02
    • 1970-01-01
    相关资源
    最近更新 更多