Read more

`simple_format` does not escape HTML tags

minh
September 18, 2012Software engineer at makandra GmbH

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 Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
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 by minh to makandra dev (2012-09-18 11:04)