Read more

`simple_format` does not escape HTML tags

Deleted user #2735
September 18, 2012Software engineer

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!

Illustration online protection

Rails professionals since 2007

Our laser focus on a single technology has made us a leader in this space. Need help?

  • We build a solid first version of your product
  • We train your development team
  • We rescue your project in trouble
Read more Show archive.org snapshot

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.

Posted to makandra dev (2012-09-18 11:04)