ruby中的双等号==问题详解
在Ruby的Slim和ERB模板中,双等号==是raw辅助方法的缩写,直接输出未经HTML转义的内容,易造成跨站脚本(XSS)漏洞。为确保安全,应使用单等号或html_safe方法转义输出。
前两天写代码时,突然收到项目警告——代码里存在 XSS 漏洞。顺着报告里的 URL 排查下去,发现是页面模板中的一个小失误。说实话,同样的问题两年前就有过讨论,按理说有点经验的同学应该都知道这个坑,但既然又碰上了,还是值得拿出来再提醒一下,免得更多人踩进去。

问题根源
漏洞出现的地方,都有类似这样的 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 的内容(比如富文本编辑器编辑的内容),怎么保证安全?
方案其实很简单——用文档推荐的 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 新手)在不了解的情况下照着滥用;
- 尽量不用
rawhelper 或String#html_safe方法,优先用#sanitize; - 多借助自动扫描工具,比如 brakeman,能快速高效检测出 XSS 漏洞在内的多种安全隐患。
Windows 10 是一款微软推出的经典操作系统,拥有硬件兼容性与多任务处理能力。它更偏向把系统状态查看和常用调节动作放在一起,适合需要持续观察和微调设备状态的场景。
极度公式是一款跨平台专业LaTeX公式识别编辑软件,支持OCR公式识别和多平台编辑。和使用说明,避免使用,享受完整功能与稳定支持。做扫描整理、文字提取和表格转换时,它能把识别后的处理步骤接得更顺,资料录入这类场景会省下不少时间。
















