I was wondering whether there is any difference between a session and an encrypted cookie (configured to expire as the session cookie does).
Aren't they the exact same thing? Or Rails provides extra security for sessions?
A session is a higher-level thing than a cookie. Sessions are collections of variables which persist for one user session only. Sessions can be stored in a cookie, in a database, or wherever a session-handling plugin chooses to store them. Cookies are now the default place where sessions are stored in modern versions of Rails. Note: when sessions are stored outside the cookie, there's an ID stored in the cookie so Rails can look up the session data in wherever it's stored (e.g. a database).
Now, let me move on to what I think you want to be asking: what's the difference between Rails' default session-storage (which uses an un-encrypted cookie) and Phusion's EncryptedCookieStore or any other encrypted-cookie session storage implementation? Why do you care about encrypting a session cookie?
According to http://agilewebdevelopment.com/plugins/encrypted_cookie_store, here's the crux of the difference: "EncryptedCookieStore is similar to Ruby on Rails's CookieStore (it saves session data in a cookie), but it uses encryption so that people can't read what's in the session data. This makes it possible to store sensitive data in the session.".
Note that there are multiple different EncryptedCookieStore's. AFAIK, you's want to use Phusion's EncryptedCookieStore and not ThinkRelevance's older EncryptedCookieStore.
If you're not encrypting cookies, then session data is easily readable by anyone with access to the cookie (either via network sniffer, disk access to the client, XSS, etc.) For details about how session vars are stored into cookies (along with security implications), look here: http://www.neeraj.name/2009/05/04/how-cookie-stores-session-data-in-rails.html.
Note that the default (non-encrytped) cookie storage is tamper-resistant (meaning Rails will reject a maliciously changed cookie). So if all you're worried about is preventing people from changing your cookies (but don't care if they see your cookies) then you're OK with the default.
Related
In rails we have something called secret_key_base in config/secrets.yml
What if this production secret is accidentally shared via GitHub (public repo)
What's the worst thing a hacker can do?
Can salted passwords in the users table leak as a result...
Rails by default uses browser cookies as its session store. This means that as opposed to the traditional way of storing session data on the server and only a session id in the cookie, Rails stores the whole session data in the cookie.
This of course would not be very secure in many cases, any user could just see and modify his session contents. So the cookie in Rails is encrypted and signed. The key used for this (encryption and integrity verification) is in secret_key_base.
What this practically means is if this secret_key_base is compromised, any user can decrypt, modify and reencrypt his session cookie (all the data in the session). In some applications this causes no problem as there is nothing interesting stored in the session anyway. But in most cases, it leads to all kinds of problems depending on the actual business logic. For example if privileges were stored in the session, a user could change his privileges in the application, probably an unintended result.
Note that if you use a different session store (like for example Redis), you don't need this secret. Afaik it's only used to encrypt cookies if the cookie store is used for sessions. Using a server-side session store is a good idea and the best practice anyway as it is more secure.
I have been using Devise for a while to handle authentication on my Rails apps, but never really understood how it works. Because Devise also uses the session storage config set on Rails, I'm assuming this is a question on session handling with Rails.
Basically, I'm an auth newbie. I've read a few articles about authentication but most deal with abstracted libraries (they talk about engines, middle ware, etc) that don't make much sense to me. I'm really looking for lower level details.
Here's what I know so far..
I know about cookies and sessions. Cookies are strings stored on client-side which is used to maintain session across multiple HTTP requests.
Here's my basic understanding of authentication (please correct me if I'm wrong):
When user logs in, we send the SSL encrypted request to the server. If the credentials are valid, we save a random string called session id on the database (or any other data store) as the valid session id associated with a user id. This session id changes for each login/logout of the user.
After saving that session id on our data store, we return a response that asks the browser to set a cookie with the session id. This session id along with the user id would then be sent for successive request to the domain until it expires. For each request, our server would check the session id on the headers and verify if that session id is valid for that user id. If it is, then consider that user authenticated.
Here are my questions:
I've read that by default starting from Rails 2, it now uses CookieStore (instead of SessionStore) which generates session hashes with SHA512 (instead of session ids), and all this is stored on a cookie which means multiple user id's can literally have the same session hash and it would just work fine. It seems to me that this is a very dangerous thing, exposing a large number of hashes with a single secret key stored on the server and basing your entire authentication system based on this key. Is there a real world large scale application that uses hashing instead of storing server side session id's?
On the topic of storing active session id's on server side, I've also read that you can switch to use different kinds of session storage for Rails. Based on this, I've heard of systems moving authentication systems out as services and using auth tokens instead. What's an auth token and how does it differ from a session id?
Seems like I can just keep guessing a random string (for both hashing and server side sessions) to grab an existing session. Is there a way to protect against this? Is it normal to use more values stored on a cookie? (such as the username, real name or even another hash for authentication)
I know I'm asking a lot but I believe this will be useful for people like me who do not understand authentication and will be very useful to get a solid foundation about the topic.
I've read that by default starting from Rails 2, it now uses
CookieStore (instead of SessionStore) which generates session hashes
with SHA512 (instead of session ids), and all this is stored on a
cookie which means multiple user id's can literally have the same
session hash and it would just work fine. It seems to me that this is
a very dangerous thing, exposing a large number of hashes with a
single secret key stored on the server and basing your entire
authentication system based on this key.
Yeah, it seems scary at first blush, but I'm not sure what the danger really is. In Rails 4, session data is encrypted using PBKBF2, and then signed with your session secret. This signing helps detect if the contents of the encrypted session have been tampered and the server will reject the session if it detects tampering.
https://cowbell-labs.com/2013-04-10-decrypt-rails-4-session.html
If someone gains access to the session token (which is used to sign the session cookie), you likely have much bigger problems on your hands than end-users attempting to impersonate the wrong user.
Is there a real world large scale application that uses hashing
instead of storing server side session id's?
I honestly don't know the answer to this one offhand, but I suspect that the fact that this is the "default" for Rails means that there are more than a handful of sites out there using cookie session stores.
On the topic of storing active session id's on server side, I've also
read that you can switch to use different kinds of session storage for
Rails. Based on this, I've heard of systems moving authentication
systems out as services and using auth tokens instead. What's an auth
token and how does it differ from a session id?
I'm doing this on a server now - basically a random hash is generated when a user authenticates, and that hash is stored, encrypted and signed, in the cookie. The cookie hash is a key into a server-side datastore (in my case Redis, but it can be in a relational database or memcache or whatever you like), and the actual session data is the stored server-side mapped to that key. This leaves less of your session data in the hands of the client were people could potentially decrypt and analyze it, so it's generally a bit safer.
Seems like I can just keep guessing a random string (for both hashing
and server side sessions) to grab an existing session. Is there a way
to protect against this? Is it normal to use more values stored on a
cookie? (such as the username, real name or even another hash for
authentication)
Yes, you could do that, but it would take a very very long time. You would also need to guess how to sign the newly tampered cookie data so that it'd match what the server expects to see on its side, and it's signed with a pretty large key.
I really don't think there's much alternative for persisting authentication state to using cookies (I suppose HTML5 Local Storage would work if you're feeling exotic and don't care much about legacy browser support).
I would like to know in Rails
what is the difference between
ActionDispatch::Sessions::CookieStore and ActionDispatch::Sessions::CacheStore
For CacheStore, i assume Rails store the session in memory(RAM)?
What about CookieStore, where are they storing?
Kit
CookieStore is stored in the client's browser as a cookie. The cookie is signed with your application's secret key so theoretically they should not be able to tamper with it. See here for more information.
CacheStore is stored in whatever ActiveSupport::Cache::Store is using to store information (i.e. memcached or redis, on the server side not on the client side). See here for more information.
I am learning Rails by reading the online guide(for Rails v2.3). The guide is great, however, there is a confusion for me, that's:
there is a chapter explains the Session of Rails and another chapter explains Cookies of Rails. The explanation is easy to understand separately, but when compare the two, reader like me does not see the significant difference between Session and Cookies . Especially under which situation session should be used and under which situation Cookies should be used ?
Besides, in the session chapter, there is a concept of CookieStore , what is the difference between the CookieStore and Cookies then?
Could someone explain to me these?
Sessions & Cookies both hold the ability to store some information (e.g : the current_user id) in between two or more requests which (in http) are otherwise stateless.
But Session is more of an abstract concept related to the notion of being in a certain state for a specific amount of time : the info it contains can be stored in the database, in a server side file, in a redis hash OR in a cookie.
Cookies are always the little text file navigators have to store some persistent data in between requests... But having some data on the client side can be insecure so that's why it is often encrypted. But it's true the notion can overlap with session.
TL;DR : session the abstract concept of holding temporary data. Cookies one (common) way of doing it.
A cookie is a small text file stored in the browser.
A session is the concept of a state of being "in-use", and that state can have data associated with it. Rails keeps track of sessions with cookies, and lets you choose different storage for associated data and access it with the same session interface.
CookieStore means all the session information is stored inside the cookie itself. You can choose to use various other stores where appropriate, and it'll still be available with your session accessor methods.
In addition to the session, you can set other cookies to store information on the user's browser. These are not tied to the session and can be set, accessed and deleted independently.
Example 1, storing a logged-in user's shopping cart in a session:
session[:embarassing_products] = ['ooh',
'naughty',
'lucky_im_using_activerecord_store',
'only_the_session_id_is_in_the_cookie',
'other_data_arent_in_the_browser']
The shopping cart is preserved for the user's session. You can set the session to end when the browser window is closed, when the user logs out, or when a certain amount of time passes.
Example 2, remembering a browser's last language preference for your domain in a cookie:
cookie[:lang] = 'en-US'
This information is stored inside the cookie itself. Unless the cookie expires or is deleted (by you or the user), it stays inside the browser.
As to me the main difference is that the session data stored on the server, whereas the cookies are stored on the client (browser).
So you can trust the data from the session. Information from the cookie can be manipulated, stolen, and thus should not be relied on for critical use (for right access for example).
Second point, is that cookies have a limited size, and are only text-based. You can store in session many complex objects (but beware of memory consumpation), and you don't have to transfer them to client then back at each request.
And typically the session only persists until the user shuts down their browser. That's useful for typical logins. Whereas if you needed information to persist between sessions you could use a cookie with a longer duration, for example a 'remember me' flag that persists even after the browser is restarted.
I'd like to store some persistent data for each browser (user settings), and don't want to require a login to use the site. What's the bset way to achieve this?
I've considered two approaches:
Store the info in the session cookie. The problem with this approach is that I would need to set the expiration time on the session cookie, which has the side effect of causing a user's login session to not expire when the browser closes.
Store the info in the DB and store a retrieval key in a cookie on the client-side. I'm concerned about performance issues, as this would require additional queries and possibly some deserialization to retrieve the data. It looks like Rails switched its default from ActiveRecordStore a while back due to performance reasons: https://web.archive.org/web/20120102024844/https://www.ryandaigle.com/articles/2007/2/21/what-s-new-in-edge-rails-cookie-based-sessions
What's the recommended way to achieve this?
Why not just use a non-session cookie? You can specify how long it will persist on the client, etc. See http://api.rubyonrails.org/classes/ActionController/Cookies.html
If you're concerned about the user messing with the cookie data, you can encrypt the cookie data using a technique like this (taken from http://www.neeraj.name/blog/articles/834-how-cookie-stores-session-data-in-rails):
cookie_data = {:foo => "bar"}
digest = 'SHA1'
secret = 'my_encryption_secret'
data = ActiveSupport::Base64.encode64s(Marshal.dump(cookie_data))
digest_value = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::Digest.new(digest), secret, data)
escaped_data_value = Rack::Utils.escape(data)
final_output = "#{escaped_data_value}--#{digest_value}"
cookies[:user_data] = final_output
and later to read the cookie data:
Marshal.load(ActiveSupport::Base64.decode64(cookies[:user_data]))
It was actually changed from a file-based session store to a cookie-based session store - not from ActiveRecord. I may be wrong but I believe ActiveRecord was a viable option for web farms or distributed setups when a file-based store was the default. Since the cookie-based store was introduced, the web farm scenario has become a non-issue because it's stored at the client-side. Today ActiveRecord is still a viable option where you want to store a greater quantity of data than a cookie permits, when you want to cutdown the overhead of data transmitted in each request (using ActiveRecord means you're only transmitting the session_id), or if you want a centralized-session setup.
I find that in employing an ActiveRecord session store, speed is not a factor for me. In a cookie-based session you generally limit what you store in your session variables anyway, so they tend to be tokens used to lookup data in the database. If the data doesn't need to be persisted beyond the session, then it's viable to store the object in the session rather than just a token, because you're going to hit the database for the associated records anyway. If the object you want to retrieve involves an expensive retrieval operation, and you need it during the lifetime of the session, it might make sense to store that object in the session rather than just a token, and only hit the db once when the session is first established.
Cookies are great, but remember also that a user can delete them when they want, encrypted or not. With privacy concerns on the rise, and quite a few plugins available for browsers that conditionally block cookies, and software that cleans up cookies, you might want to weigh up the pros and cons of using cookies vs. a db-backed session.
#joshsz makes a good point about using a non-session cookie for persisting data beyond the session too. Remember a session has a finite lifetime.