【问题标题】:Fix sql injection on Rails model scope修复 Rails 模型范围上的 sql 注入
【发布时间】:2019-12-06 01:41:25
【问题描述】:

我一直在尝试重构一个模型范围,Brakeman 一直在抱怨它,所以我认为修复它是个好主意,因为我们被正在寻找我们网站漏洞的机器人扫描。

scope :cash_deal_aggregated, -> (filter = '') {
  select("deals.*")
  .from([Arel.sql(
    "(SELECT DISTINCT ON (COALESCE(cash_deal_details.cash_deal_id, 0.1*deals.id)) deals.*
      FROM deals
      INNER JOIN portfolios ON portfolios.id = deals.portfolio_id
      LEFT JOIN cash_deal_details ON deals.cash_deal_detail_id = cash_deal_details.id
      #{filter}) deals"
    )]
  )
}

上面的作用域是这样使用的:

filter = "WHERE portfolios.client_id = #{client_id}"
deal_records = deal_records = Deal.cash_deal_aggregated(filter)

而且也是这样使用的:

deal_records = Deal.cash_deal_aggregated

最初我尝试通过直接在查询中添加filter 来修复它,但随后出现多个错误。

感谢您对此重构的建议。

【问题讨论】:

  • 尝试用 Rails 关联重构内连接和左连接。
  • @SantoshAryal 这会有什么帮助?
  • 如果制动员向您发送有关可能的 SQL 注入的警告,请尝试测试注入 SQL 的 SQL 注入。 Brakeman 也可能会针对格式不正确的 SQL 命令发送 SQL 注入警告,例如 select * from books;SELECT * FROM 'BOOKS';。希望这会对你有所帮助。
  • IMO,如果您可以将 SQL 中的字符串插值(#{filter}#{client_id} 在您的情况下)重构为 Arel 或 ActiveRecord,那么刹车员应该不再抱怨。

标签: sql ruby-on-rails postgresql arel


【解决方案1】:

用这种方法包装 ActiveRecord 的 connection.quote(),包装 client_id,例如,在你的情况下,试试这个

"WHERE portfolios.client_id = #{connection.quote(client_id)}"

我之前也从刹车手那里得到了这些错误,这解决了它。

【讨论】:

【解决方案2】:

这是重构。感谢Rajdeep Singh

scope :cash_deal_aggregated, -> (client_id = nil) {
  filter = "WHERE portfolios.client_id = #{connection.quote(client_id)}" if client_id
  select("deals.*")
  .from([Arel.sql(
      "(SELECT DISTINCT ON (COALESCE(cash_deal_details.cash_deal_id, 0.1*deals.id)) deals.*
      FROM deals
      INNER JOIN portfolios ON portfolios.id = deals.portfolio_id
      LEFT JOIN cash_deal_details ON deals.cash_deal_detail_id = cash_deal_details.id
        #{filter}) deals"
      )]
    )
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 2021-07-26
    相关资源
    最近更新 更多