Ruby on Rails and XSS Prevention

What are the methods to prevent XSS in Ruby on Rails? I found a lot of old documents on the Internet, and most of the time it was all about using h / html_escape to avoid any variable coming from users.

I realized from new documents that in version 2.0 and above there is a sanitized method that automatically cleans up input from supposedly malicious input. Is it enough, or are you doing something else to the application?

+6
security ruby ruby-on-rails xss
source share
4 answers

The Ruby on Rails Security Guide describes in sufficient detail the Rails- related issues you should consider when designing security for your website.

+10
source share

The h method is still suitable for removing all HTML inside a string. This method should be used wherever you display content.

 <%=h @recipe.description %> 

This behavior will change in Rails 3. There, all output will be escaped by default, and you will need to explicitly specify so as not to avoid this. At the same time, if you often forget to use this h method, you can check the secure ERB plugin .

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

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

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

+15
source share

As for best practices, I would recommend the following:

  • Always use rail form helpers (form_for, etc.), if you write your own form, you open yourself up for CSRF attacks.

  • When you use the h () function, the text comes out when it is written to the page, you will still get the XSS exploits stored in your database. Using the XSS_terminate plugin, it is saved when it is saved.

  • Do not forget that your application runs on the stack of other applications (Rails, Apache, MySQL, your OS of choice), each of which has its own security problems.

+4
source share

The Rails sanitation method is pretty good, but it does not guarantee correctness and will most likely be attacked due to the installation base. Best practice is to use either html5lib (truly the best, if not the fastest or the most ruby), or Sanitize or Loofah

+2
source share

All Articles