3

I'm developing a social network and to my knowledge, the best way of storing between pages which user is logged on is using cookies. So, suppose I'm storing a cookie of the user ID which is logged in.

Anyway, what's stopping the user from changing the cookie's value in order to trick the website into thinking they're logged in as someone else?

Jacob Garby
  • 215
  • 2
  • 4

3 Answers3

8

So, suppose I'm storing a cookie of the user ID which is logged in.

That's not how session cookies work. The cookie shoudn't just contain the ID of the current user since that would obviously allow an attacker to tamper with the value.

Instead, a common approach is that the web application issues a sufficiently long, random session ID to the user and internally associates this session ID with the actual user account. Since a user is then assigned a new session ID after each login, it won't be feasible to predict the session IDs of other users or manipulate user-specific values by modifying the cookie.

Generally, you shouldn't have to invent your own session management scheme. If you think about how to store a user ID in a cookie, you're probably doing it wrong. Many frameworks already provide abstractions for cookie-based sessions. E.g., PHP has built-in support for session handling. Also have a look at the OWASP Session Management Cheat Sheet to learn about security considerations.

Arminius
  • 44,242
  • 14
  • 143
  • 138
2

It is possible to store information in cookies and prevent users from tampetering with the data in the cookies. The way to do this is to create a HMAC of the cookie value and store that along with the cookie. Then whenever you receive a cookie value, check if it has the correct HMAC. Since HMACs need a secret key to create which only the server has, you know for sure that the cookie value was created by the server.

Some frameworks have this built in (expressjs, rails). This question discusses the concept of signed cookies some more.

Sjoerd
  • 28,897
  • 12
  • 76
  • 102
0

If you authenticate a user based on a plaintext cookie with a username then you can't ensure whoever has the cookie is the person they say they are. Anyone can create a cookie with whatever username they want. It's up to you to ensure that they are who they say they are.

If I knew someone's username I could create a cookie with their username and bypass the login of the application and be whoever I wanted to be if there were no server side checks.

Instead of authenticating a user using a cookie I would suggest using a server side session, and pass an identifier of this session to the user to store as a cookie. Then when they request your page you can identify who the user is using their server-side session variables. The issue with this method is if your session identifier is easily guessable another user's session could be hijacked, but at least in this case the session could be cleared on the server.

anon
  • 301
  • 1
  • 3