`simple_format` does not escape HTML tags

Updated . Posted . Visible to the public. Repeats.

simple_format Show archive.org snapshot ignores Rails' XSS protection. Even when called with an unsafe string, HTML characters will not be escaped or stripped!

Instead simple_format calls sanitize on each of the generated paragraphs.

ActionView::Base.sanitized_allowed_tags
# => #<Set: {"small", "dfn", "sup", "sub", "pre", "blockquote", "ins", "ul", "var", "samp", "del", "h6", "h5", "h4", "h3", "h2", "h1", "span", "br", "hr", "em", "address", "img", "kbd", "tt", "a", "acronym", "abbr", "code", "p", "i", "b", "strong", "dd", "dt", "dl", "ol", "li", "div", "big", "cite"}> 

If you don't want user input with markup to appear as HTML, you need to escape yourself:

simple_format(h(user_input))

If you're using Rails 7.1 you can also customize your sanitize opions that simple_format uses. E.g if you want to disallow all HTML code in the output:

user_input = "
Hello World

<img src="evil.png">

<script>alert(1)</script>
"
simple_format(user_input, { class: 'paragraph' }, { sanitize_options: { tags: [], attributes: [] } })

will result in

<p class="paragraph">Hello World</p>

<p class="paragraph">alert(1)</p>

For Rails versions that don't support this option, consider using a custom method.

minh
Last edit
Dominic Beger
License
Source code in this card is licensed under the MIT License.
Posted by minh to makandra dev (2012-09-18 09:04)