Prashant Sahni Blog

On XSS & Rails

Yesterday I was discussing about security in rails, the reach of web has been expanded so security in web apps can't be overlooked.

I came to know some of the web issues

Cross-Site scripting

I have referred it from Rails security guide. Now a days we have so much user generated content on our websites for example posting comments , searching information on search engines(which we called Web 2.0 style apps)


In cross site scripting an attacker tries to inject a malicious script into the website, he is able to bypass the security mechanisms applied by the browser on the client site, because the malicious script that is inserted in the input come from a trusted site(the browser treats the input as if it is the part of the target page.), so in this way the attacker is able to access the information like cookies or any other info of the true user can be accessed.


The main issue is if we do not validate the input inserted by the user, then when our website tries to display that non-validated input, the malicious script runs in browser as a part of the website, so the input must be filtered before displaying it. If we do not allow user to enter any html data then prevention is easy. But it in some cases it is important. In Rails h() methods escapes all special html characters. eg, as you know it already

<% for comment in @article.comments %>
  <%=h comment %>
<% end %>

It is a good approach to store the content in the original form that is unescaped.

Of course things are not as simple, sometimes the filtering the input is even difficult . Rails provide more help there through sanitize() method, I referred it to bible of Rails railsbrain This method removed all javascript and form tags, this method is used just like h() We can use it in customised fashion,

  <%= sanitize, :tags => %w(img), :attributes => %w(id class style)%>

comments powered byDisqus