Saturday, February 26, 2011

How Ruby on Rails Session secret is generated or stored

Ruby on Rails's default session store is cookies, and it has all the info encoded in Base 64. So anybody can look at the info by Base64 decode. Note that often, even the user id of the logged in user is in the cookie, and the authenticated system installed or implemented on Rails will assume that this is the valid user id of the logged in user and fetch all data / settings, allow permission according to this user id. So how can Rails prevent somebody from faking to be another user?

It is by verifying the cookie data by encrypting with a secret key. Then the result is compared to the checksum tagged along in the session cookie. (The session cookie has 2 parts: the data, and the checksum).

When a Rails application is created, the secret key is automatically generated for you. So even if you don't specify a secret key, don't worry, one is already there:

Rails 2.2.2:
in config/environment.rb


# Your secret key for verifying cookie session data integrity.
# If you change this key, all old sessions will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
config.action_controller.session = {
:session_key => '_foobar_session',
:secret => '0d7d7d5ec0680cfd1d716bba057bce35a92a920a4471aa274ef0224ee52ebaa9eae43952418f7954fdef49b63d5b8eacc6efecf4bc2a29c45e8625a07f820e48'
}

Rails 2.3.8
in config/initializers/session_store.rb

# Your secret key for verifying cookie session data integrity.
# If you change this key, all old sessions will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
ActionController::Base.session = {
:key => '_foobar_session',
:secret => '81c3c1e81b899ea2cff8d9321a67df7c88978ad985a4b39118d2061f2f8b946392575cdff2e5e7cd83eb0493ba200eb07c51d11cd191a681dbdb19673f2d0da7'
}

Rails 3.0.4
in config/initializers/secret_token.rb

# Your secret key for verifying the integrity of signed cookies.
# If you change this key, all old signed cookies will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
Foobar::Application.config.secret_token = 'ce90ddf2fb13e290e077fc8a3ac865a52fde53595fe905af032fd07301a1715c2f6efd28c285c3543cbd45b27107fb95ed7d6778c28cc1225c1157e0fa69bf25'



No comments:

Post a Comment

Followers