About Rails 3 cross-origin <script> tag vulnerability
About half a year ago when I was working at datarockets we had a project written in Rails 3.2.
One day we encountered one very interesting vulnerability. So, in this article I want to tell you about it and also provide you with a tool which will help you to fix it if you still using old Rails 3 on your project. So, let’s go.
Here is your JS view file called new.js.coffee which creates your view and is accessible by GET.
In the @partial variable we have a simple HTML Rails form for creating some kind of stuff, for example books.
So, let’s imagine that I’m a hacker (LOL) and I want to get access to your account at http://example.com/ and have an ability to send some forms from you. So all I need is your valid CSRF token. So, let’s do it.
Let’s create my own webpage which will help us.
So, what is happening here?
I’ve created a form which sends a comment to the book.
I’ve also added a JS file index.js to our <head>. It will hack our http://example.com/ and steal your CSRF token.
In our index.js we have:
So, what’s going on here?
The most important part is:
We redefine a simple jQuery $ function to perform our getSecureInfo() function.
After that we write a script into our HTML which gets a JS-generated view.
As you remember in our JS view we use $ function.
But we have already redefined the $ function to perform our getSecureInfo function:
So, right now in this function we have access to your HTML from our @partial. And, as you remember, there is a real form for creating a book in that partial with real and valid CSRF token.
So, all we do is just find that token in our HTML and add it to our form for posting a comment.
So, right now it is a valid form for http://example.com/ and you can easily send it.
Creating a comment is one of the most harmless things. Using this vulnerability you can easily delete some important data, update some data with wrong info and etc.
So, when Rails users encountered this issue they quickly wrote some code to fix it.
You can look through the discussion here and the code here:
It is included by default in Rails 4, but is not included in Rails 3. So, if you have no ability to move to new Rails, but you want to patch your application, here is a gem with a very clear name rails3_csrf_patcher.
You can download it here:
Just include this gem into your Rails application and that’s it.
Thanks for recommending this article to your friends at Medium :)