Authenticating From Scratch - How Safe Are Cookies?
I am trying to authenticate from scratch using Omniauth.
I followed Ryan Bate screencast . But before I post the implementation, I would like to understand a few things.
In his screencast, he has helper_method
in application_controller
:
helper_method :current_user
private
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
The code above checks for user_id
.
I know sessions are encrypted (and stored in cookies). However, they are readable, but cannot be changed. How difficult would it be for someone to hijack a fake session user_id
? Which prevents someone from creating a cookie from scratch or through some kind of "cookie injector" method (if such a thing exists).
I am trying to understand how these cookies are protected.
source to share
Sessions are usually stored on the server side and the only thing passed to / from the client via cookies is the session ID. Storing the actual session data in this cookie will be a serious security issue, no matter how well encrypted. for example, if you were cheap and used rot-13 "encryption", it would be trivial for the user to make a fiddle and install superuser=1
.
But with a session ID this is not possible - nothing in the cookie can be used to write to the server data. At best, they can send back random session ID values โโand try to hijack someone's session. With a large enough ID hash, the chances of finding another session to capture are vanishingly small.
source to share
Do you think the link you provided gives the best answers. And it covers a lot of much more insidious attacks that I will worry more about sensitive applications.
In Rails, it would be very difficult to send a bogus or scripted cookie containing session data, because the cookies are signed by the server, and the cookie sent is validated to make sure the signature is correct. Changing cookie values โโwill require knowledge of the secret key on which the server signs the cookies.
The best practice is to only store very small bits (preferably IDs) in the session, and if you are concerned that someone might create a session cookie containing a user ID from scratch, the easy answer is: don't put user.id in cookie. Instead, generate a GUID for each user that serves as an identifier in the cookie. This way you can expose user.id in URLs without fear that knowing some user ID would allow an attacker to spoof a cookie that would be useful.
source to share