Dave Elkins

Search It!

Preventing XSS Attacks in your Rails Application

April 19th, 2007 · 1 Comment

If you're new here, you may want to subscribe to my RSS feed. Thanks for visiting!

Preventing XSS attacks in your Rails application turns out to be fairly easy thanks to some built in functionalities of Rails.

Lets first start out talking about ways to prevent XSS scripting in general before we see how rails can help us. These are three things you can do:

  • Validate all request parameters and form data with what are acceptable values. The best defense against XSS is to state what is allowed and only accept that. Of course that is not possible in every case but a lot of the time is possible - for example, validating numbers, dates, email addresses and using regular expressions.
  • For data that can not be validated easily, it needs to be sanitize or html entity encoded. This will prevent malicious code from being presented to the browser raw.
  • When displaying data make sure to encode it using html entities.

How can Rails help?….

Validating Data

Active Record Validations - Use AR Validations to make sure data complies with what you expect. There are number of built in validations and a ton of plugins that add more.

Use the Validate() method - AR Validations don’t do enough? Then implement the validate method to add more flexible rules.

Use attr_protected - Here is a link to a good article about it [click here].

Learn how to use regular expressions. They can be difficult to understand but they are powerful and are very useful.

HTML Entity Encoding of Data

Use the h() function in views when displaying data from the database or data that has been submitted through a form. This is very important. It will encode the data into HTML entities and this will give you a lot of protection against most XSS attacks.

Use CGI.escapeHTML() in places where the h() function is not available. It does the same thing as the h() function but it just requires a little extra typing.

In JavaScript, if you are going to use something from the URL or from the user and display it then make sure you use the escape() or escapeURI() functions.

Coming up

I am going to write about and find more resources about AR Validations and using validations w/o AR.

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • DZone
  • Wists
  • BlinkList
  • blogmarks
  • Ma.gnolia
  • NewsVine
  • Slashdot
  • StumbleUpon
  • Technorati

Tags: rails · security

1 response so far ↓

Leave a Comment