Some quiz about XSS in Rails

Tram Ho


Cross-site scripting (XSS) is a type of computer security hole that allows an attacker to insert code into a website. When a user visits the website after the code is embedded, it will be executed in the user’s browser. Since then, an attacker could steal a user’s cookie, or take advantage of an admin to change information on the system, …

Try testing your knowledge of XSS in Rails!

Some questions

Question 1:

Which of the following is safe with XSS?

The answer is the first 3 options. From Rails 3 onwards, Rails has automatically supported XSS prevention. All strings passed <%= %> have been automatically escaped . Even, option 2 is redundant when escaping twice

The last 2 options are not safe with XSS. When using raw or html_safe , the render @user.comment will not be escaped. Then, if there is an attacker who embeds the JS code and comments via the <script> tag, then all the other users will see the comment, the browser will automatically execute the JS code embedded in the attacker. From there, you can steal cookies or borrow admin hand to change information on the system.

Question 2:

Let’s say we want to implement a method like this in the helper:

Which of the following implementations is safe with XSS?

Only option 1 is right! content_tag (as well as tag ) escape content that is passed in, then include it in the strong tag.

Option 2 will escape content with html_escape, but it will also escape the strong tag passed in. So the code will not execute as we want.

The remaining 2 options are similar to question 1.

The last question

A common XSS attack is to take advantage of the href attribute in tag a . If it starts with javascript: or data: then the code will be executed when the user clicks on the link.

So which of the following is safe for XSS?

Only the last option is safe. sanitize only works with whole HTML tags, not URLs. This means that you should use sanitize with both the a tag and not the href attribute alone.


  • Rails has a mechanism for automatically escaping when the code is within <% =%> tags
  • Only use raw and html_safe when you are sure that you are rendering the html code (for example when taking content from CKEditor ).
  • Rails will not be able to protect your system if you pass what the user enters tag a or link_to . In that case, you need to use sanitize .

To detect XSS vulnerabilities, I recommend you to try brakeman . It will analyze vulnerabilities on your Rails system.

Source of the article

Share the news now

Source : Viblo