15

我可以在我计划向其他用户显示的用户输入文本上使用ActionView::Helpers::SanitizeHelper#sanitize吗?例如,它会正确处理本网站上描述的所有案例吗?

此外,文档还提到:

请注意,清理用户提供的文本并不能保证生成的标记是有效的(符合文档类型)甚至是格式正确的。输出可能仍包含例如未转义的 '<'、'>'、'&' 字符和混淆浏览器。

处理这个问题的最佳方法是什么?在显示之前通过已清理的文本Hpricot

4

3 回答 3

16

Ryan Grove 的Sanitize比 Rails 3 走得更远sanitize。它确保输出 HTML 格式正确,并具有三个内置白名单:

Sanitize::Config::RESTRICTED 只允许非常简单的内联格式标记。没有链接、图像或块元素。

Sanitize::Config::BASIC 允许各种标记,包括格式化标签、链接和列表。不允许使用图像和表格,链接仅限于 FTP、HTTP、HTTPS 和 mailto 协议,并为所有链接添加属性以减少 SEO 垃圾邮件。

Sanitize::Config::RELAXED允许比 BASIC 更广泛的标记,包括图像和表格。链接仍然仅限于 FTP、HTTP、HTTPS 和 mailto 协议,而图像仅限于 HTTP 和 HTTPS。在这种模式下,不会添加到链接中。

于 2011-02-17T17:15:43.510 回答
11

Sanitize 肯定比“h”助手好。它实际上允许您指定的 html 标记,而不是转义所有内容。是的,它确实阻止了跨站点脚本,因为它完全从混合中删除了 javascript。

简而言之,两者都会完成工作。当您不期望纯文本以外的任何内容时使用“h”,并在您想要允许某些内容时使用 sanitize,或者您认为人们可能会尝试输入它。即使您禁止所有带有 sanitize 的标签,它也会通过删除它们而不是像“h”那样转义它们来“美化”代码。

至于不完整的标签:您可以在通过 hpricot 传递包含 html 的字段的模型上运行验证,但我认为这在大多数应用程序中是多余的。

于 2010-10-27T01:55:34.160 回答
4

The best course of action depends on two things:

  • Your rails version (2.x or 3.x)
  • Whether your users are supposed to enter any html at all on the input or not.

As a general rule, I don't allow my users to input html - instead I let them input textile.

On rails 3.x:

User input is sanitized by default. You don't have to do anything, unless you want your users to be able to send some html. In that case, keep reading.

This railscast deals with XSS attacks on rails 3.

On rails 2.x:

If you don't allow any html from your users, just protect your output with the h method, like this:

<%= h post.text %>

If you want your users to send some html: you can use rails' sanitize method or HTML::StathamSanitizer

于 2010-06-07T07:41:09.583 回答