【问题标题】:Rails ActiveRecord escape variable in join clause连接子句中的 Rails ActiveRecord 转义变量
【发布时间】:2012-08-06 15:56:15
【问题描述】:

此查询有效,但对 SQL 注入完全开放:

products = Product.find(pids,
  :select => 'products.*, P.code',
  :joins => "left join product_dist_match P on
    (P.pid = products.pid and P.cid = #{cid})",
)

如何正确转义 cid 变量? conditions 参数允许为此目的使用 ['foo = ?', bar] 格式,但 joins 不允许。

我不想使用find_by_sql,因为这样我就需要添加属于模型默认范围(不会是 DRY)的连接和条件。

编辑:我的表结构基本上是这样的:

products: pid (primary key)
product_dist_match: pid, cid, code
customers (not used in the query): cid (primary key)

请注意,这是一个只读数据库,Rails 仅参与有限。我不打算为所有表设置模型;我只想做一个如上所述的简单查询,而不会让自己受到 SQL 注入攻击。

【问题讨论】:

  • 你能描述一下你的表结构吗?这可能通过使用哈希条件来实现

标签: mysql sql ruby-on-rails ruby-on-rails-3 activerecord


【解决方案1】:

我找到的答案是在模型上使用.sanitize方法:

products = Product.find(pids,
  :select => 'products.*, P.code',
  :joins => 'left join product_dist_match P on
    (P.pid = products.pid and P.cid = ' + Product.sanitize(cid) + ')',
)

如果您找到更好的解决方案,请发布!

【讨论】:

  • 我以同样的方式实现了这一点——ActiveRecord 假设一个人不想在连接中添加条件似乎有点缺点,并且以安全的方式这样做!跨度>
  • 为什么我们不能在 where 子句中使用 P.cid = cid 功能?
  • @parallelRails 如果您知道使用where 而不是left join 重写上述查询并获得相同结果的方法,请将其作为答案发布!
  • 我不太反对 sql 注入,因为您的问题主要是关于它,我宁愿不作为答案发布:Product.select('products.*, P.code').joins('left join product_dist_match P on P.pid = products.pid').where('P.cid = ?', cid) 同样我不确定这是否会停止 sql注射,这不是答案,而只是一种改进,也许
  • 您的建议在注入问题上很好,但它不会返回与我的查询相同的结果。测试用例:create temporary table r (pid integer); create temporary table p (pid integer, cid integer, code integer); insert into r values (123); insert into p values (123, 20, 1); select r.*, p.code from r left join p on (p.pid=r.pid and p.cid=4); select r.*, p.code from r left join p on (p.pid=r.pid) where p.cid=4; 同样,如果您确实有办法重写查询并获得相同的结果,我很乐意看到它。
【解决方案2】:

这似乎更像是你想要做的。

products = Product.find(pids,
    :select => 'products.*, P.code',
    :joins => sanitize_sql_array [
      'left join product_dist_match P on P.pid = products.pid and P.cid = ?', 
       cid
    ]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-14
    相关资源
    最近更新 更多