Advanced Rails - Building Industrial-Strength Web Apps in Record Time

(Tuis.) #1
Web Issues | 143

However, cross-site request forgery is not limited to GET requests. There are several
ways for an attacker to create a POST request using JavaScript, including
XmlHttpRequestand creating and posting hidden forms. Using the proper HTTP
actions alone is not sufficient to defend your application.


In this case, secret form tokens are helpful. The idea is to generate a token for each
session that is included as a hidden field in every form. The token is an HMAC (hash
message authentication code) of the session ID. This gives the token two important
properties:



  • It is hard or impossible for an attacker to generate a valid token given only the
    session ID, so the token certifies that the server generated the session ID.

  • The token changes with each session.


A valid token corresponding to the current session ID must be included with each
request that has side effects. If the token is not present or invalid, the action is can-
celed. This prevents the attack, because the attacker has no way to include a valid
token with the client’s request to the target application.


Rails 2.0 now incorporates request forgery protection by default. Actions with meth-
ods other than GET are checked for a valid token. The form helpers have been
extended to add a token based on a secret key and the session to each generated
form. By default, it tries to do the right thing. See the documentation on
ActionController::RequestForgeryProtection::ClassMethods for detailed information.


The most important thing that needs to be done if not using cookie-based sessions is
to set a secret:


class ApplicationController < ActionController::Base
protect_from_forgery :secret => 'application-secret-283o39@4%dX963'
end

If you are using cookie-based session storage, ActionController generates a secret
for you anyway; you may omit thesecretparameter. Note that it is important that
the sessioncookie is a true nonpersistent session cookie—that is, it disappears after the
session is over. If the session cookie is persistent, the token ID will be the same
each session and CSRF attacks will still be possible.


Canonicalization: What’s in a Name?


The termcanonicalizationrefers to the process of conforming input to an expected
representation. Loosely,canonicalization issuesare problems that arise because the
same resource can be referenced in different ways.


Canonicalization often comes up when working with filesystem paths. On a Unix-like
system, you’d expect the paths/home/joeuser,~joeuser, and/var/log/../../home/joeuser
to reference the same path, even though they are composed of different characters.

Free download pdf