Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails and XSS prevention

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?

like image 669
Jakub Troszok Avatar asked Aug 12 '09 14:08

Jakub Troszok


3 Answers

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.

like image 87
ryanb Avatar answered Oct 04 '22 10:10

ryanb


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

like image 24
Oliver N. Avatar answered Oct 04 '22 11:10

Oliver N.


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.

like image 40
Mike Buckbee Avatar answered Oct 04 '22 09:10

Mike Buckbee