1. Computing
Send to a Friend via Email

Dealing With Ruby Vulnerabilities: Check HTTP Referrers

Countermeasures for Security Issues in Ruby

By

Though HTTP referrers can be forged and won't help against CSRF attacks launched from your own site (via XSS), it may still be worthwhile to implement. With every HTTP request, a Referer (which is mispelled in the HTTP standard) header is passed. That is, if the HTTP request is the result of a link, form submission, image tag, etc. The Referer header holds the URL of the webpage that generated that request. By checking if the server from which the request originates is the same as the server your application runs on, you can determine if the request was generated from your site or not. If an HTTP request lacks a Referer header you can also tell it was generated by hand or from a location where Refererwould make no sense (such as an email client).

The following method can be used as a before filter. If the Referer header is missing or the server names do not match, it will redirect you to the index action and display a message. By default, it's applied to all actions of all controllers. Since this will block incoming links, it should be skipped on links you expect your users to be accessing.

 class ApplicationController < ActionController::Base
   include AuthenticatedSystem
   before_filter :check_referrer
 
   helper :all # include all helpers, all the time
 
   # See ActionController::RequestForgeryProtection for details
   # Uncomment the :secret if you're not using the cookie session store
   protect_from_forgery # :secret => 'b09ddc8519180659f80e8bb321b7fd26'
 
   protected
   def check_referrer
     if (
       ( request.headers['referer'].nil? ) or
       ( (request.headers['referer'] =~ %r[^http://#{request.host_with_port}/]).nil? )
       )
       flash[:notice] = "Incorrect Referer header"
       redirect_to :action => 'index'
     end
   end
 end
 
 class PostsController < ApplicationController
   before_filter :login_required, :except => [ :index, :show ]
   skip_before_filter :check_referrer, :only => [ :index, :show ]
 
 ...snip...
 end
 

Though checking HTTP referrers won't protect against everything, it is a way to prevent mistakes from going unnoticed. Extra layers of security are never a bad thing as long as they don't interfere with the function of your Web application. If any mistakes do get through (such as forgetting to check HTTP request type on a method), this referrer filter will hopefully catch it before it does any damage. Such errors can also be logged, informing you someone has attempted an attack.

©2014 About.com. All rights reserved.