简体   繁体   English

Rails形式的text_field转义html

[英]Rails form text_field escaping html

Experimenting with my Rails form, I find that inserting <scrip>alert("hello")</script> into a text_field gives me two different results. 在我的Rails表单上进行试验,发现将<scrip>alert("hello")</script>插入text_field会给我两个不同的结果。

When I use the value, for example in a display page, it is automagicaly escaped. 当我在显示页面中使用该值时,该值会自动转义。

When I use the value in a new form, for example to allow user editing, it is not escaped and I get the alert pop-up. 当我以新的形式使用该值(例如,允许用户编辑)时,不会转义该值,并且会弹出警报弹出窗口。

After a lot of research, I have found that text_area has an escape boolean that prevents this, but not text_field. 经过大量研究,我发现text_area的转义布尔值可以防止这种情况发生,但是text_field却不能。 Most of the stuff coming up on google is about escaping within erb templates, which does not appear to work when using a form. google上出现的大多数内容都是关于在erb模板中转义,当使用表单时,这似乎无效。 There are a couple of hints that data should be sanitized going into the db, but little guidance on the best way to do this --- aside from using old solutions for example xssterminate which appears to date back to Rails 2. Even the RoR security guide focuses on sanitizing erb output rather than santizing the input. 有一些提示应该将数据清理到db中,但是关于最佳方法的指南很少-除了使用xssterminate这样的旧解决方案外,这似乎可以追溯到Rails2。甚至RoR安全性该指南着重于清理erb输出,而不是清理输入。

Two questions. 两个问题。

  1. What is the current best-practice approach to sanitizing text_field input before it is saved? 在保存text_field输入之前,目前的最佳做法是什么? (eg: in the form, the controller or the model. What gems are still considered current?) (例如:在表单,控制器或模型中。哪些宝石仍被视为当前宝石?)
  2. Regardless, because I am paranoid, how do you sanitize the text_field when displaying db data? 无论如何,由于我很偏执,因此在显示数据库数据时如何清理text_field?

The loofah-activerecord gem ( https://github.com/flavorjones/loofah-activerecord ) looks like your best bet for sanitizing data on its way into the database. 丝瓜络-activerecord宝石( https://github.com/flavorjones/loofah-activerecord )看起来像是最好的选择,它可以清理进入数据库的数据。 Using xss_foliate on your models will strip tags for all columns by default. 在模型上使用xss_foliate会默认剥离所有列的标签。

eg 例如

class User < ActiveRecord::Base
  xss_foliate

  ...
end

I haven't found a solution to the 2nd point, but would be very keen to know about it if there is one! 我还没有找到第二点的解决方案,但是如果有一个解决方案,我将非常想知道!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM