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
)
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 idempotent anyway.
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
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:
32 # <%= javascript_tag "window._token = '#{form_authenticity_token}'" %>
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:
37 # # Disable request forgery protection in test environment
38 # config.action_controller.allow_forgery_protection = false
40 # == Learn more about CSRF (Cross-Site Request Forgery) attacks
42 # Here are some resources:
43 # * http://isc.sans.org/diary.html?storyid=1750
44 # * http://en.wikipedia.org/wiki/Cross-site_request_forgery
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:
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"
55 # Turn on request forgery protection. Bear in mind that only non-GET, HTML/JavaScript requests are checked.
59 # class FooController < ApplicationController
60 # # uses the cookie session store (then you don't need a separate :secret)
61 # protect_from_forgery :except => :index
63 # # uses one of the other session stores that uses a session_id value.
64 # protect_from_forgery :secret => 'my-little-pony', :except => :index
66 # # you can disable csrf protection on controller-by-controller basis:
67 # skip_before_filter :verify_authenticity_token
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
)
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)
89 # Returns true or false if a request is verified. Checks:
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?
95 !protect_against_forgery
? ||
96 request
.method
== :get ||
97 !verifiable_request_format
? ||
98 form_authenticity_token
== params
[request_forgery_protection_token
]
101 def verifiable_request_format
?
102 !request
.content_type
.nil? && request
.content_type
.verify_request
?
105 # Sets the token value for the current session. Pass a <tt>:secret</tt> option
106 # in +protect_from_forgery+ to add a custom salt to the hash.
107 def form_authenticity_token
108 @form_authenticity_token ||= if !session
.respond_to
?(:session_id)
109 raise InvalidAuthenticityToken
, "Request Forgery Protection requires a valid session. Use #allow_forgery_protection to disable it, or use a valid session."
110 elsif request_forgery_protection_options
[:secret]
111 authenticity_token_from_session_id
112 elsif session
.respond_to
?(:dbman) && session
.dbman
.respond_to
?(:generate_digest)
113 authenticity_token_from_cookie_session
115 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)."
119 # Generates a unique digest using the session_id and the CSRF secret.
120 def authenticity_token_from_session_id
121 key
= if request_forgery_protection_options
[:secret].respond_to
?(:call)
122 request_forgery_protection_options
[:secret].call(@session)
124 request_forgery_protection_options
[:secret]
126 digest
= request_forgery_protection_options
[:digest] ||= 'SHA1'
127 OpenSSL
::HMAC.hexdigest(OpenSSL
::Digest::Digest.new(digest
), key
.to_s
, session
.session_id
.to_s
)
130 # No secret was given, so assume this is a cookie session store.
131 def authenticity_token_from_cookie_session
132 session
[:csrf_id] ||= CGI
::Session.generate_unique_id
133 session
.dbman
.generate_digest(session
[:csrf_id])
136 def protect_against_forgery
?
137 allow_forgery_protection
&& request_forgery_protection_token