位置:首页 > Ruby > Ruby中双等号==的用法与常见问题详解

Ruby中双等号==的用法与常见问题详解

时间:2026-08-17  |  作者:火苗实验室  |  阅读:0

前两天写代码时,突然收到项目警告——代码里存在 XSS 漏洞。顺着报告里的 URL 排查下去,发现是页面模板中的一个小失误。

说实话,同样的问题两年前就有过讨论。按理说,有点经验的同学应该都知道这个坑。但既然又碰上了,还是值得拿出来再提醒一下,免得更多人踩进去。

ruby中的双等号==问题详解

问题根源

漏洞出现的地方,通常都有类似这样的 slim 代码:

input class='xxx' value==params[:account]

问题就出在这个双等号 == 上。

在 slim 和 ERB 模板中(HAML 等模板不太清楚),双等号其实是 Rails 中 raw 这个 helper 方法的缩写。官方文档写得很清楚:

To insert something verbatim use the raw helper rather than calling html_safe:
<%= raw @cms.current_template %> <%# inserts @cms.current_template as is %>
or, equivalently, use <%==:
<%== @cms.current_template %> <%# inserts @cms.current_template as is %>

也就是说,上面的代码等价于:

input class='xxx' value=raw(params[:account])

raw 方法在 Rails 文档中的解释是这样的:

This method outputs without escaping a string. Since escaping tags is now default, this can be used when you don't want Rails to automatically escape tags. This is not recommended if the data is coming from the user's input.

意思很直白:这个方法会跳过对传入字符串的标签过滤,直接将其输出到 HTML 中。

所以原因也很清楚了。不小心多敲了一个等号,变成了双等号,导致用户的输入被原封不动地塞进了待渲染的 HTML,在不知情的情况下留下了 XSS 漏洞。

修复方式

修复方案很简单,去掉一个等号就行:

input class='xxx' value=params[:account]

这样 Rails 就会继续自动过滤 :account 参数,自动处理掉恶意内容。

raw、String#html_safe 以及 <%== %>

翻了一下 raw 的源码,极其简单,只有一行:

# File actionview/lib/action_view/helpers/output_safety_helper.rb, line 16
def raw(stringish)
 stringish.to_s.html_safe
end

raw 只是先把参数转成字符串,然后调用了 String#html_safe 方法。

String#html_safe 的文档同样反复强调要慎用:

It will be inserted into HTML with no additional escaping performed. It is your responsibilty to ensure that the string contains no malicious content. This method is equivalent to the raw helper in views.

因此可以总结:以下三种写法完全等价,都是不安全的:

input class='xxx' value==params[:account]
input class='xxx' value=raw(params[:account])
input class='xxx' value=params[:account].html_safe

确实需要输出 HTML 时怎么办

如果确实需要输出包含 HTML 的内容,比如富文本编辑器编辑的内容,怎么保证安全?

方案其实很简单。用文档推荐的 sanitize helper 方法:

It is recommended that you use sanitize instead of this method(html_safe).
(#sanitize)Sanitizes HTML input, stripping all tags and attributes that aren't whitelisted.

或者,也可以引入其他第三方的 gem 来做过滤处理。

总结

  • 不要用双等号缩写,避免项目中其他人,尤其是 Rails 新手,在不了解的情况下照着滥用;
  • 尽量不用 raw helper 或 String#html_safe 方法,优先用 #sanitize
  • 多借助自动扫描工具,比如 brakeman,能快速高效检测出 XSS 漏洞在内的多种安全隐患。

免责声明:文中图文均来自网络,如有侵权请联系删除,心愿游戏发布此文仅为传递信息,不代表心愿游戏认同其观点或证实其描述。

相关文章

更多

精选合集

更多

大家都在玩

热门话题

大家都在看

更多