Question

What is the best solution to sanitize output HTML in Rails (to avoid XSS attacks)?

I have two options: white_list plugin or sanitize method from Sanitize Helper http://api.rubyonrails.com/classes/ActionView/Helpers/SanitizeHelper.html . For me until today the white_list plugin worked better and in the past, Sanitize was very buggy, but as part of the Core, probably it will be under development and be supported for a while.

Was it helpful?

Solution

I think the h helper method will work here:

<%= h @user.profile %>

This will escape angle brackets and therefore neutralize any embedded JavaScript. Of course this will also eliminate any formatting your users might use.

If you want formatting, maybe look at markdown.

OTHER TIPS

Personally I think it's not a small decision to accept any HTML entry in any web app. You can test for white/blacklisted tags as much as you like, but unless you're testing for correct nesting, someone could enter a series of closing tags, for example

</td></tr></span></div>

and really mess with your layout.

I'd usually give people something like Textile to enter their markup, since I'd rather spend my time working on business logic than HTML parsing.

Of course, if this text entry is more fundamental to your app (as for example it is for stackoverflow) then you probably should give more attention to hand-rolling your own.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top