Rails security: Sessions  

03 Nov 2010
William Notowidagdo Kiranatama Staff
Knowledge


This is the first post of our Rails security series. Sessions is vulnarable to particular security threats that why it is a good place to start looking at security. Two main rules to be followed are:
  1. Never store large objects in a session. Store them in the database and save their ID in the session. That way it is easier to clear out the sessions.
  2. Never store critical data in session.
Rails provides a number of session storages. In your live applications you might want to ActiveRecordStore due to performance and maintenance reasons. ActiveRecordStore keeps the session ID and hash in a table and saves and retrieves them on every request. For those who still stick with Rails 2 then CookieStore is the default session storage. When using CookieStore always remember
  1. Cookies size limit of 4kB .
  2. It is stored in clear-text, so always put the secret in your environment.rb and to prevent the replays attacks, never store sensitive data in it.
For Rails 2.3 you put the secret in config/initializers/session_store.rb
ActionController::Base.session = {
  :key         => '_app_session',
  :secret      => 'f7c1cbd0c4a79421...'
}
or in Rails 3, in config/initializers/secret_token.rb
MyRailsApp::Application.config.secret_token = 'ae173ce851d...'
Another kind of attack is called session fixation, use
reset_session
to fight them. Use reset_session to issue a new session identifier and declare the previous one is invalid after a successful login, e.g. add reset_session in SessionsController#create action. When using reset_session, remember that it will removes any value from the session.