Ruby on Rails Security – CSRF

Analysis:-

This attack method works by including malicious code or a link in a page that accesses a web application that user is believed to have authenticated. If the session for that web application has not timed out, an attacker may execute unauthorized commands.

In rails, session can be stored either as a cookie or as a server-side session hash. In either case the browser will automatically send along the cookie on every request to a domain, if it can find a cookie for that domain. The controversial point is, that it will also send the cookie, if the request comes from a site with a different domain

Solution and Fix:-

The solution to this is including a security token in the requests which will be checked on the server side. This will be done by adding the line ‘protect_from_forgery’ in the application controller. This will automatically include a security token, calculated from the current session and the server-side secret, in all the forms and Ajax requests generated by Rails. The secret is not needed if we use cookie as session storage. If the security token doesn’t match what was expected, the session will be reset.

Once the forgery protection is enabled, the form now will have a hidden ID field. The protect_from_forgery method adds a before_filter called verify_authenticity_token to all actions. It will compare this ID field against an ID stored in the session variable. If they differ, the action will not be executed.

 

Example hidden field in the form with the authenticity token:

<input name=”authenticity_token” type=”hidden” value=”rNZrqiOxWlQw1/3PqKa5+3L1teWbZwLr6ljhLxkXWCc=” />

 

Links for References:-

1)      http://guides.rubyonrails.org/security.html#cross-site-request-forgery-csrf

2)      http://ruby.about.com/od/security/a/forgeryprotect.htm

Note: XSS vulnerabilities bypass all CSRF protections. XSS gives the attacker access to all elements on a page, so he can read the CSRF security token from a form or directly submit the form.

Advertisements

1 thought on “Ruby on Rails Security – CSRF”

Comments are closed.