如何在Rails中安全输出查询参数,在其中不对&符号进行转义

问题描述 投票:0回答:1

考虑以下查询参数

{
  :param1=>"<script>alert('hi')</script>", 
  :param2=>"<script>alert('hi2')</script>"
}

我想安全地将它们作为链接中的查询参数呈现。问题显示如下:

[83] pry(main)> params
=> {:param1=>"<script>alert('hi')</script>", :param2=>"<script>alert('hi2')</script>"}
[84] pry(main)> params.to_query
=> "param1=%3Cscript%3Ealert%28%27hi%27%29%3C%2Fscript%3E&param2=%3Cscript%3Ealert%28%27hi2%27%29%3C%2Fscript%3E"
[85] pry(main)> ERB::Util.html_escape params.to_query
=> "param1=%3Cscript%3Ealert%28%27hi%27%29%3C%2Fscript%3E&amp;param2=%3Cscript%3Ealert%28%27hi2%27%29%3C%2Fscript%3E"

当通过ERB渲染params.to_query时,“&”号也将被转义。您可能可以将它们作为查询参数传递给url_for和link_to,但是出于这个问题的目的,让我们假设这是不可能的。

就我而言,我只是想安全地对查询参数本身进行转义,而不对与号进行转义。

ruby-on-rails ruby xss erb
1个回答
0
投票

[我想出了一个可能的解决方案,但我对社区的反馈感到好奇:

  def escape_query_params(url)
    # in my case, we have a string that can be parsed as a URI.
    uri = URI.parse(url)

    # then we split the query part across the "&".
    # and return an array that uses the technique in the below article
    # to concat strings starting with a SafeBuffer
    # and then use ActionView's `safe_join` to bring back the & 
    safe_query_params = safe_join(uri.query.split("&").map{|s| "".html_safe + s}, "&".html_safe)
    "".html_safe + uri.path + "?" + safe_query_params
  end

上面使用了以下文章中的一种有关如何使用html_safe安全的技术:https://product.reverb.com/stay-safe-while-using-html-safe-in-rails-9e368836fac1

© www.soinside.com 2019 - 2024. All rights reserved.