DEV Community

Cover image for Security sinks in Ruby on Rails Part 1 - XSS
Szymon Lipka
Szymon Lipka

Posted on

Security sinks in Ruby on Rails Part 1 - XSS

In Security, there are such concepts as sinks and sources. Sinks are dangerous functions in the code, whereas sources are arguments of the sinks.

Source and sink

In this case, there is a dangerous function eval and a source is params[:name].

In code reviews, I tend to search for such functions and analyze what can be their argument/source of data. This helps me identify potential vulnerabilities before they reach production.

I want to go with you through some basic sinks, that should turn on the yellow light.

Cross Site Scripting(XSS)

Let's go through Cross Site Scripting first. XSS is a vulnerability that allows execution scripts in browsers with malicious sources. More about them can be read here. The most popular ways of allowing this security issue are methods raw and html_safe. By default in Rails, everything that is being returned by <%= %> is being interpreted as a text, but when you use those methods, you tell that it can be interpreted as HTML.

For example, on code review you see a line in a .erb file:

raw t('user_name', name: user.name)
Enter fullscreen mode Exit fullscreen mode

or

t('user_name', name: user.name).html_safe
Enter fullscreen mode Exit fullscreen mode
# config/locales/en.yml
en:
  user_name: "<p>User name is %{name}</p>"
Enter fullscreen mode Exit fullscreen mode

This is I would say common case because it's from my experience often that we want to introduce HTML into translation. It might result in XSS. user.name is a source and it shouldn't be user input. If it is, a malicious user might define it for example <script>alert(1)</script> and the alert pops at the time of rendering the erb file.

In general, I would avoid html_safe or raw methods, unless they are obligatory.

Sometimes you might say that you know that it is XSS, but it is Self-XSS(the person who can be affected by XSS is the person who writes the script). I don't encourage you to ignore such cases, because in the future there might be a different business logic, which would result in Self-XSS becoming XSS.

When it comes to XSS, it's very important to mention CSP - a policy that is a last resort against XSS. It's rather simple to implement it in Rails, docs you can find here, and more about the policy itself you can find here.

To be continued

Top comments (0)