1 module ActionController #:nodoc:
2 class InvalidAuthenticityToken < ActionControllerError #:nodoc:
5 module RequestForgeryProtection
6 def self.included(base)
8 class_inheritable_accessor :request_forgery_protection_options
9 self.request_forgery_protection_options = {}
10 helper_method :form_authenticity_token
11 helper_method :protect_against_forgery?
13 base.extend(ClassMethods)
17 # Protect a controller's actions from CSRF attacks by ensuring that all forms are coming from the current web application, not
18 # a forged link from another site. This is done by embedding a token based on the session (which an attacker wouldn't know) in
19 # all forms and Ajax requests generated by Rails and then verifying the authenticity of that token in the controller. Only
20 # HTML/JavaScript requests are checked, so this will not protect your XML API (presumably you'll have a different authentication
21 # scheme there anyway). Also, GET requests are not protected as these should be indempotent anyway.
23 # You turn this on with the #protect_from_forgery method, which will perform the check and raise
24 # an ActionController::InvalidAuthenticityToken if the token doesn't match what was expected. And it will add
25 # a _authenticity_token parameter to all forms that are automatically generated by Rails. You can customize the error message
26 # given through public/422.html.
28 # Learn more about CSRF (Cross-Site Request Forgery) attacks:
30 # * http://isc.sans.org/diary.html?storyid=1750
31 # * http://en.wikipedia.org/wiki/Cross-site_request_forgery
33 # Keep in mind, this is NOT a silver-bullet, plug 'n' play, warm security blanket for your rails application.
34 # There are a few guidelines you should follow:
36 # * Keep your GET requests safe and idempotent. More reading material:
37 # * http://www.xml.com/pub/a/2002/04/24/deviant.html
38 # * http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.1
39 # * Make sure the session cookies that Rails creates are non-persistent. Check in Firefox and look for "Expires: at end of session"
41 # If you need to construct a request yourself, but still want to take advantage of forgery protection, you can grab the
42 # authenticity_token using the form_authenticity_token helper method and make it part of the parameters yourself.
46 # class FooController < ApplicationController
47 # # uses the cookie session store (then you don't need a separate :secret)
48 # protect_from_forgery :except => :index
50 # # uses one of the other session stores that uses a session_id value.
51 # protect_from_forgery :secret => 'my-little-pony', :except => :index
53 # # you can disable csrf protection on controller-by-controller basis:
54 # skip_before_filter :verify_authenticity_token
59 # * <tt>:only/:except</tt> - passed to the before_filter call. Set which actions are verified.
60 # * <tt>:secret</tt> - Custom salt used to generate the form_authenticity_token.
61 # Leave this off if you are using the cookie session store.
62 # * <tt>:digest</tt> - Message digest used for hashing. Defaults to 'SHA1'
63 def protect_from_forgery(options = {})
64 self.request_forgery_protection_token ||= :authenticity_token
65 before_filter :verify_authenticity_token, :only => options.delete(:only), :except => options.delete(:except)
66 request_forgery_protection_options.update(options)
71 # The actual before_filter that is used. Modify this to change how you handle unverified requests.
72 def verify_authenticity_token
73 verified_request? || raise(ActionController::InvalidAuthenticityToken)
76 # Returns true or false if a request is verified. Checks:
78 # * is the format restricted? By default, only HTML and AJAX requests are checked.
79 # * is it a GET request? Gets should be safe and idempotent
80 # * Does the form_authenticity_token match the given _token value from the params?
82 !protect_against_forgery? ||
83 request.method == :get ||
84 !verifiable_request_format? ||
85 form_authenticity_token == params[request_forgery_protection_token]
88 def verifiable_request_format?
89 request.format.html? || request.format.js?
92 # Sets the token value for the current session. Pass a :secret option in #protect_from_forgery to add a custom salt to the hash.
93 def form_authenticity_token
94 @form_authenticity_token ||= if request_forgery_protection_options[:secret]
95 authenticity_token_from_session_id
96 elsif session.respond_to?(:dbman) && session.dbman.respond_to?(:generate_digest)
97 authenticity_token_from_cookie_session
99 raise InvalidAuthenticityToken, "Request Forgery Protection requires a valid session. Use #allow_forgery_protection to disable it, or use a valid session."
101 raise InvalidAuthenticityToken, "No :secret given to the #protect_from_forgery call. Set that or use a session store capable of generating its own keys (Cookie Session Store)."
105 # Generates a unique digest using the session_id and the CSRF secret.
106 def authenticity_token_from_session_id
107 key = if request_forgery_protection_options[:secret].respond_to?(:call)
108 request_forgery_protection_options[:secret].call(@session)
110 request_forgery_protection_options[:secret]
112 digest = request_forgery_protection_options[:digest] ||= 'SHA1'
113 OpenSSL::HMAC.hexdigest(OpenSSL::Digest::Digest.new(digest), key.to_s, session.session_id.to_s)
116 # No secret was given, so assume this is a cookie session store.
117 def authenticity_token_from_cookie_session
118 session[:csrf_id] ||= CGI::Session.generate_unique_id
119 session.dbman.generate_digest(session[:csrf_id])
122 def protect_against_forgery?
123 allow_forgery_protection && request_forgery_protection_token