views:

205

answers:

2

how to avoid cross site scripting in "ruby on rails"

i used the code below

<%= link_to h(@user.name), user_url(@user) %>

and, i want to know, how and where do we check this script is working or not.

+2  A: 

You should escape anything in your views that may be manipulated by a third party, such as attributes and parameters.

Given your example, I have created a user with the name <script type="text/javascript">alert("XSS")</script>. Assuming you're only validating the presence of a name, this would be valid.

<!-- Raw output -->
<a href="#"><script type="text/javascript">alert("XSS")</script></a>

Client viewing this page with JavaScript enabled will see the standard alert prompt. This demonstrates that I can inject aribtary JavaScript in to your view.

<!-- Escaped output -->
<a href="#">&lt;script type=&quot;text/javascript&quot;&gt;alert(&quot;XSS&quot;)&lt;/script&gt;</a>

Client viewing this page with JavaScript enabled will not see the standard alert prompt.

This is a technique you can use to verify whether or not a view is vulnerable to a cross site scripting attack.

An alternate option is to consider using HAML. HAML can be configured to always escape output unless you explicitly ask for it to be raw. I'm lead to believe this will be the default behaviour in Rails 3 using ERb.

Tate Johnson
All built in functions in Rails (such as link_to) already escapes output by default. This will also be made the default behaviour for erb in Rails 3.
askegg
`name` parameter is not escaped by default. Only options which is evaluated by `url_for` is escaped.
Tate Johnson
Yes - I should have made that clear :(
askegg
A: 

If you want to add auto-escape to Rails 2.x, take a look at Michael Koziarski's rails_xss. Does exactly what you're looking for :)