XSS Protection by Default in Rails 3.0
Michael Koziarski: Switch to on-by-default XSS escaping for rails. This consists of:
- String#html_safe! a method to mark a string as ‘safe’
- ActionView::SafeBuffer a string subclass which escapes anything unsafe which is concatenated to it
- Calls to String#html_safe! throughout the rails helpers
- a 'raw’ helper which lets you concatenate trusted HTML from non-safety-aware sources (e.g. presantized strings in the DB)
- New ERB implementation based on erubis which uses a SafeBuffer instead of a String
Not mentioned in the commit message, but for backwards compatibility, html_escape
and h
helpers still exist, but essentially do nothing. This change is also being backported to 2.3.
For existing applications, the changes needed will tend to be small and easily spotted. The biggest impact will be to books and tutorials. New users will either see what they perceive as line noise being emitted and wonder what they did wrong, or will follow instructions such as the following (from Edition 3) and wonder why it doesn’t work as advertised:
In general, try to get into the habit of typing
<%=h … >
in templates and then removing theh
only when you’ve convinced yourself it’s safe to do so.
For new applications, this is all goodness. Do nothing in most cases. Add raw
or sanitize
only when needed. Edition 4 will be updated to reflect this advice.