在 Rails 中转义 HTML [英] Escaping HTML in Rails

查看:51
本文介绍了在 Rails 中转义 HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

推荐的转义 HTML 以防止 Rails 应用程序中的 XSS 漏洞的方法是什么?

What is the recommended way to escape HTML to prevent XSS vulnerabilities in Rails apps?

您是否应该允许用户将任何文本放入数据库但在显示时将其转义?您是否应该添加 before_save 过滤器来转义输入?

Should you allow the user to put any text into the database but escape it when displaying it? Should you add before_save filters to escape the input?

推荐答案

解决这个问题有三种基本方法.

There are three basic approaches to this problem.

  1. 在您的视图中使用 h().这里的缺点是如果你忘记了,你就会得到 pwnd.
  2. 使用可在保存内容时对其进行转义的插件.我的插件 xss_terminate 就是这样做的.然后你不必在你的视图中使用 h() (大部分).还有其他一些在控制器级别上工作.这里的缺点是 (a) 如果转义代码中存在错误,您的数据库中可能会出现 XSS;(b) 在某些极端情况下,您仍然希望使用 h().
  3. 使用可在内容显示时对其进行转义的插件.CrossSiteSniper 可能是其中最著名的.这会为您的属性设置别名,以便在您调用 foo.name 时它会转义内容.如果您需要未转义的内容,有一种解决方法.我喜欢这个插件,但一开始我并不想让 XSS 进入我的数据库......
  1. use h() in your views. The downside here is that if you forget, you get pwnd.
  2. Use a plugin that escapes content when it is saved. My plugin xss_terminate does this. Then you don't have to use h() in your views (mostly). There are others that work on the controller level. The downsides here are (a) if there's a bug in the escaping code, you could get XSS in your database; and (b) There are corner cases where you'll still want to use h().
  3. Use a plugin that escapes content when it is displayed. CrossSiteSniper is probably the best known of these. This aliases your attributes so that when you call foo.name it escapes the content. There's a way around it if you need the content unescaped. I like this plugin but I'm not wild about letting XSS into my database in the first place...

还有一些混合方法.

您没有理由不能同时使用 xss_terminate 和 CrossSiteSniper.

There's no reason why you can't use xss_terminate and CrossSiteSniper at the same time.

还有一个名为 Erubis 的 ERb 实现,可以对其进行配置,以便像 <%= foo.name %> 被转义——相当于 <%= h(foo.name) %>.不幸的是,Erubis 似乎总是落后于 Rails,因此使用它会减慢您的速度.

There's also a ERb implementation called Erubis that can be configured so that any call like <%= foo.name %> is escaped -- the equivalent of <%= h(foo.name) %>. Unfortunately, Erubis always seems to lag behind Rails and so using it can slow you down.

如果您想阅读更多内容,我写了一篇关于 使用 xss_terminate.

If you want to read more, I wrote a blog post (which Xavor kindly linked to) about using xss_terminate.

这篇关于在 Rails 中转义 HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆