Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

root/trunk/actionpack/lib/action_controller/request_forgery_protection.rb

Revision 8807, 7.1 kB (checked in by rick, 10 months ago)

Correct inconsistencies in RequestForgeryProtection docs. #11032 [mislav]

Line 
1 module ActionController #:nodoc:
2   class InvalidAuthenticityToken < ActionControllerError #:nodoc:
3   end
4
5   module RequestForgeryProtection
6     def self.included(base)
7       base.class_eval do
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?
12       end
13       base.extend(ClassMethods)
14     end
15    
16     # Protecting controller actions from CSRF attacks by ensuring that all forms are coming from the current web application, not a
17     # forged link from another site, is done by embedding a token based on the session (which an attacker wouldn't know) in all
18     # forms and Ajax requests generated by Rails and then verifying the authenticity of that token in the controller.  Only
19     # HTML/JavaScript requests are checked, so this will not protect your XML API (presumably you'll have a different authentication
20     # scheme there anyway).  Also, GET requests are not protected as these should be indempotent anyway.
21     #
22     # This is turned on with the <tt>protect_from_forgery</tt> method, which will check the token and raise an
23     # ActionController::InvalidAuthenticityToken if it doesn't match what was expected. You can customize the error message in
24     # production by editing public/422.html.  A call to this method in ApplicationController is generated by default in post-Rails 2.0
25     # applications.
26     #
27     # The token parameter is named <tt>authenticity_token</tt> by default. If you are generating an HTML form manually (without the
28     # use of Rails' <tt>form_for</tt>, <tt>form_tag</tt> or other helpers), you have to include a hidden field named like that and
29     # set its value to what is returned by <tt>form_authenticity_token</tt>. Same applies to manually constructed Ajax requests. To
30     # make the token available through a global variable to scripts on a certain page, you could add something like this to a view:
31     #
32     #   <%= javascript_tag "window._token = '#{form_authenticity_token}'" %>
33     #
34     # Request forgery protection is disabled by default in test environment.  If you are upgrading from Rails 1.x, add this to
35     # config/environments/test.rb:
36     #
37     #   # Disable request forgery protection in test environment
38     #   config.action_controller.allow_forgery_protection = false
39     #
40     # == Learn more about CSRF (Cross-Site Request Forgery) attacks
41     #
42     # Here are some resources:
43     # * http://isc.sans.org/diary.html?storyid=1750
44     # * http://en.wikipedia.org/wiki/Cross-site_request_forgery
45     #
46     # Keep in mind, this is NOT a silver-bullet, plug 'n' play, warm security blanket for your rails application.
47     # There are a few guidelines you should follow:
48     #
49     # * Keep your GET requests safe and idempotent.  More reading material:
50     #   * http://www.xml.com/pub/a/2002/04/24/deviant.html
51     #   * http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.1
52     # * Make sure the session cookies that Rails creates are non-persistent.  Check in Firefox and look for "Expires: at end of session"
53     #
54     module ClassMethods
55       # Turn on request forgery protection. Bear in mind that only non-GET, HTML/JavaScript requests are checked.
56       #
57       # Example:
58       #
59       #   class FooController < ApplicationController
60       #     # uses the cookie session store (then you don't need a separate :secret)
61       #     protect_from_forgery :except => :index
62       #
63       #     # uses one of the other session stores that uses a session_id value.
64       #     protect_from_forgery :secret => 'my-little-pony', :except => :index
65       #
66       #     # you can disable csrf protection on controller-by-controller basis:
67       #     skip_before_filter :verify_authenticity_token
68       #   end
69       #
70       # Valid Options:
71       #
72       # * <tt>:only/:except</tt> - passed to the <tt>before_filter</tt> call.  Set which actions are verified.
73       # * <tt>:secret</tt> - Custom salt used to generate the <tt>form_authenticity_token</tt>.
74       #   Leave this off if you are using the cookie session store.
75       # * <tt>:digest</tt> - Message digest used for hashing.  Defaults to 'SHA1'
76       def protect_from_forgery(options = {})
77         self.request_forgery_protection_token ||= :authenticity_token
78         before_filter :verify_authenticity_token, :only => options.delete(:only), :except => options.delete(:except)
79         request_forgery_protection_options.update(options)
80       end
81     end
82
83     protected
84       # The actual before_filter that is used.  Modify this to change how you handle unverified requests.
85       def verify_authenticity_token
86         verified_request? || raise(ActionController::InvalidAuthenticityToken)
87       end
88      
89       # Returns true or false if a request is verified.  Checks:
90       #
91       # * is the format restricted?  By default, only HTML and AJAX requests are checked.
92       # * is it a GET request?  Gets should be safe and idempotent
93       # * Does the form_authenticity_token match the given _token value from the params?
94       def verified_request?
95         !protect_against_forgery?     ||
96           request.method == :get      ||
97           !verifiable_request_format? ||
98           form_authenticity_token == params[request_forgery_protection_token]
99       end
100    
101       def verifiable_request_format?
102         request.format.html? || request.format.js?
103       end
104    
105       # Sets the token value for the current session.  Pass a :secret option in #protect_from_forgery to add a custom salt to the hash.
106       def form_authenticity_token
107         @form_authenticity_token ||= if request_forgery_protection_options[:secret]
108           authenticity_token_from_session_id
109         elsif session.respond_to?(:dbman) && session.dbman.respond_to?(:generate_digest)
110           authenticity_token_from_cookie_session
111         elsif session.nil?
112           raise InvalidAuthenticityToken, "Request Forgery Protection requires a valid session.  Use #allow_forgery_protection to disable it, or use a valid session."
113         else
114           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)."
115         end
116       end
117      
118       # Generates a unique digest using the session_id and the CSRF secret.
119       def authenticity_token_from_session_id
120         key = if request_forgery_protection_options[:secret].respond_to?(:call)
121           request_forgery_protection_options[:secret].call(@session)
122         else
123           request_forgery_protection_options[:secret]
124         end
125         digest = request_forgery_protection_options[:digest] ||= 'SHA1'
126         OpenSSL::HMAC.hexdigest(OpenSSL::Digest::Digest.new(digest), key.to_s, session.session_id.to_s)
127       end
128      
129       # No secret was given, so assume this is a cookie session store.
130       def authenticity_token_from_cookie_session
131         session[:csrf_id] ||= CGI::Session.generate_unique_id
132         session.dbman.generate_digest(session[:csrf_id])
133       end
134      
135       def protect_against_forgery?
136         allow_forgery_protection && request_forgery_protection_token
137       end
138   end
139 end
Note: See TracBrowser for help on using the browser.