views:

372

answers:

4

What are the practices to prevent XSS in Ruby on Rails? I found many old docs on the web and most of the time it was all about using h/html_escape helper to escape any variable that comes from users.

I understood from newer docs that in the version 2.0 and above there is sanitize method that is automatically cleaning the input from supposedly malicious input. Is it enough or are you doing something more to secure your applications?

+5  A: 

The Ruby on Rails Security Guide is fairly thorough about the Rails-specific issues that you should consider when designing security for your website.

Oliver N.
+5  A: 

The h method is still the way to go to escape all HTML inside of a string. You should use this method everywhere you are outputting content.

<%=h @recipe.description %>

This behavior will be changing in Rails 3. There all output will be escaped by default and you will need to explicitly specify to not escape it. In the meantime, if you often forget to use this h method you may want to check out the Safe ERB plugin.

The sanitize method is a good way to selectively strip out certain tags from the content. For example, if you want to allow the user to bold and italicize their output along with adding links you could do this.

<%= sanitize @recipe.description, :tags => %w[b i a], :attributes => %w[href] %>

As Oliver mentioned, check out the Security Guide for more information.

ryanb
+1  A: 

As far as best practices, I would recommend the following:

  1. Always use the rails form helpers (form_for, etc), if you write your own form, you open yourself up to CSRF attacks.

  2. While using the h() function will escape text as it is written to a page, you will still end up with XSS exploits saved in your database. Using the XSS_terminate plugin strips input as it is saved.

  3. Don't forget that your app is running on a stack of other applications (Rails, Apache, MySQL, your OS of choice), each of which have their own security concerns.

Mike Buckbee
+1  A: 

The Rails sanitize method is pretty good, but it doesn't guarantee well-formedness, and it's quite likely to be attacked due to the install base. Better practice is to use either html5lib (truly the best, if not the fastest or most rubyish) or Sanitize or Loofah

dasil003