Ruby中双等号==的用法与常见问题详解
时间:2026-08-17 | 作者:火苗实验室 | 阅读:0前两天写代码时,突然收到项目警告——代码里存在 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 时怎么办
如果确实需要输出包含 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 漏洞在内的多种安全隐患。
免责声明:文中图文均来自网络,如有侵权请联系删除,心愿游戏发布此文仅为传递信息,不代表心愿游戏认同其观点或证实其描述。
相关文章
更多-
- 使用RVM切换Ruby与Rails版本的实现方法
- 时间:2026-08-18
-
- Ruby语言是什么及入门使用方法
- 时间:2026-08-18
-
- Ruby on Rails网站项目搭建入门指南
- 时间:2026-08-18
-
- Ruby插入排序算法实现与二路插入排序代码示例
- 时间:2026-08-18
-
- Ruby图片滤镜算法实现代码与核心原理
- 时间:2026-08-18
-
- Ruby中Hash哈希结构基本操作方法详解
- 时间:2026-08-18
-
- Ruby面向对象编程:类方法与类扩展详解
- 时间:2026-08-18
-
- Ruby正则表达式语法详解与常用示例代码
- 时间:2026-08-18
精选合集
更多大家都在玩
大家都在看
更多-
- 糖尿病完全不能吃糖吗
- 时间:2026-09-15
-
- 蚂蚁庄园小课堂2026年9月16日最新题目答案
- 时间:2026-09-15
-
- 小鸡答题今天的答案是什么2026年9月16日
- 时间:2026-09-15
-
- 蚂蚁庄园每日答题答案2026年9月16日
- 时间:2026-09-15
-
- 以下哪种粮食是酿造绍兴黄酒的主要原料 蚂蚁庄园今日答案9月16日
- 时间:2026-09-15
-
- 劝学名句“及时当勉励,岁月不待人”出自哪位诗人 蚂蚁庄园今日答案9.16
- 时间:2026-09-15
-
- 蚂蚁庄园今天答题答案2026年9月16日
- 时间:2026-09-15
-
- 蚂蚁庄园答题今日答案2026年9月16日
- 时间:2026-09-15
