Cookie stealing - php

I have read many answers on stackoverflow, but none of them could answer my question.
Let's consider a case, where a teacher and the student use the same computer. The teacher uses it to upload marks and the student use the computer to browse the marks. Now, the cookies of the teacher are stored and accessible. The student can easily forge the cookies and present himself as a teacher to the system and create havoc.
What approach should I take to disable this? Is this only possible via sessions? Or there exists a possibility with cookies as well.

The main two suggestions I would have are:
Delete the entire session right before the user logs out or logs in. A new session should always be started when authorization level changes.
Only accept sessions ids you generate. By default PHP will accept and start a new session for any value of the session id you send it. If you receive a session id you haven't seen before, discard it and send the user a new one.

If it's not necessary to have the browser remeber the cookie between browser sessions (eg a login can be 'forgotten' if the browser window is closed), then you could NOT set the expiry date on the cookie which makes it memory-resident only.
When the user closes the web broswer, the cookie is forgotten (standard browser behaviour) so there's no link to the old session, and a new login must be provided. The old session becomes "orphaned" and (assuming you have a 'expire through inactivity' process) will be expired eventually.
If you need the browser to remember the last user even if the window was closed, then a short-but-appropriate timeout is needed - destroy the session making the cookie useless after x minutes/hours inactivity (whatever is appropriate).

Related

how to keep the user logged until user log out himself?

I have php login page that stores the user id in the session once the login is successful. User can navigate to different pages or can even close the page briefly and once user re-open the page, he is still logged in. However the problem is that when the user closes the page for longer time, the session get expired automatically and he has to re-enter the credentials and login again.
How can I keep the user logged in forever and log out ONLY if user decides to do so?
I would like the user to be able to close the page, turn off the pc for weeks and when he or she comes back to visit the page, he or she should be already logged in.
Sound like you need to set the cookie expiration date - as per this wikipedia article on HTTP cookies, if you do not set an expiration date for a cookie it becomes a session cookie. i.e. it expires once the browser closes.
There is no real way to specify that a cookie NEVER expires, however you can set the expiration date for some time far in the future.. i.e. in 10 years, and renew that expiration date every time the user loads a page.
setCookie( name, value, expiration )
Another alternative (which would also require some JS on your pages) would be to use the browser's internal database to store the user session id so that you can retrieve the session from your database (I assume you are using some sort of database, otherwise you will run into other issues as explained below).
If I wanted to achieve this I would probably have a piece of javascript on my page loads that checked for the existence of the session cookie, and if not, I would load the session id from the browser's database, drop the cookie, and force a page reload. There are certainly more elegant ways of achieving this, but this should give you an example of how to get this started.
Lastly, please keep in mind that if you don't use a database (i.e. Redis, Memcached, SQL), all you session information is lost when you restart your application server. This is certainly suboptimal, and you should store session information in a database if you want to have this information survive server restarts (or if you have a load balanced environment).
Hope this helps!

Best expiration setting for cookies in this situation?

I'm creating a relationship table of user sessions (each user regardless of login state gets a new user session unless they already have a cookie denoting the session ID of their current session) and webpages on my site. This will eventually be able to predict interests, in theory.
Now, I've decided that I should use a PHP cookie rather than a PHP session. How long should I set the cookie to be around for? (I currently have it at 24 hours)
Are there any negatives to setting cookies to have a long period of time before expiration? What about non-expiring cookies? How does a major website set cookie expiration times for things like "Most recently viewed items"?
I wouldn't expire them at all (or only in a year or so) if you intend to use the cookies to track users for a long time - as the user visits the page and you find out the cookie data is obsolete, you can delete them using setcookie() (set expiration date to somewhere in the past).
Note that many users have cookies disabled, or have them automatically deleted when they close their browser, for exactly this reason. People don't like to get tracked.
What are you doing to protect from session hijacking? How do you handle people who may visit from a shared computer, do they get the same session?
I would suggest setting up a user login and track information by user. Otherwise, the data you get will not be qualified and can only be guessing at best.

How to manage PHP sessions across browsers

I have the run-of-the-mill login-based PHPSESSID mechanism implemented for my web app. One aspect that bothers me is the simple scenario where a user orphans his session in browser A (on computer A), opens another in browser B (on computer B), orphans this to walk back to browser A and so forth. Possibly all this within the (reasonably lengthy) time span for which the PHPSESSID cookies are valid. If both sessions display the user static data, and the user is manipulating this, then the two browsers will not necessarily show data that is consistent with what's in the database.
My preferred response to this scenario is for the second login two invalidate the first. I can keep one PHPSESSID associated with the userID in the database. That's easy enough. Now the hard part: on the second login, how can I invalidate the PHPSESSID that's written into the database such that a subsequent access from the first sessions (with the now invalidated PHPSESSID) will fail?
(I cannot use session_destroy() because that wants to kill the second PHPSESSID, the one I actually want to keep. And I cannot use setCookie() for exactly the same reason.)
One idea I had involves a database access sequence number. Each new request returns the previous plus one. If out of sequence, session_destroy() the current enquirer. Slight inconvenience I see with this is that it requires an extra database fetch to recover the sequence number before each user access.
Is there any way of associating this sequence number with a userID somewhere inside the server's cache that doesn't involve any cookie transmissions?
Thanks.
I don't understand your question completely, but this is how I should do it.
If you store your session data (including SESSION_ID) in the database and you add a user_id to that table, you can delete all session_data of that user before adding the new session initiated on PC B (by that user) to the database. When the user tries to reload his/her session on PC A, the combination of his/her user_id and session_id is not present and you should log him/her out.
I see no problem in this.
On the second login you just write this second login session id in the database.
That makes previous one invalid.

How to restore old session when user accidentally closes the browser?

I am planning to create a online examination sytem in PHP. What steps could I take to restore old session, if user has accidentally closed the window?
Suppose he has already answered 49 questions out of 50 and suddenly there is power cut off (and there is no UPS) or he accidentally closes the window (even by mistake, if he clicks yes on javascript's prompt on window.unload event) and then reopens the browser, everything is lost. What could I possibly do to prevent this?
Thanks in advance :)
You would need to do one of two things:
Persist the current state on the user machine - this would have to be done via a cookie.
Persist the current state on the server.
The second option is probably more reliable, it does require that you are in constant contact with the server. It would also allow the session to resume on another machine.
The first option would probably be easier to implement.
Offer a login system where you store the progress tied to the user login, or simply use cookies that do not expire upon closing the browser (i.e. set an expiry date far in the future).
You can store the session parameters in cookie which expires after 30 day e.g.
You could save their state every time they go to the next question - if it's saved in a session, you could serialize the session and save it in the DB, related to their account.
If they open up the browser again, you can then load up the saved session, unserialize it, and continue off where they left it.
Storing the session id as a cookie with a long expire time will solve the problem but will introduce a new issue: on public or shared machines, users will have to explicitly log out (i.e. destroy the session) otherwise everyone that access the site after they quit will continue their session.
Another solution is to bind 'exam sessions' to the user, persist them on the database and continue the session if an user with a pending exam logs in. Obviously this require a bit of coding :-)
continuously save the page state into a cookie (e.g. on every form change - thus you have the state of the current page);
on submit, save the state into session (or even into database of unfinished forms) and clear it from cookie (thus you have the overall state of the exam stored server-side, so you can clear it from the cookie).
When finished, clear both cookie and session.
Of course, if there's a power outage, the cookie may not have been flushed to disk yet, but otherwise (especially if you have multiple questions on one page), the user will lose less state than if you only saved on submit.

Session should never expire by itself

I'm using login function in my site with session.
This session of mine gets expired after a few minutes irrespective of whether the user has logged out or not.
Now what I want is that the session should only get expired when a user logs out. If a user doesn't log out his account and then comes back after 2-3 days, even then he should appear logged in.
I have found some examples where they have increased the time for a session to expire but I want that it should only expire on the log out event by the user irrespective of the time he took to log out.
How can I do that?
In particular, is this the right way to do so?
session_cache_expire(0);
session_start();
A solution that is often used, in this situation, is to:
have a not-too-long session duration: it will expire if the user is not active (that's just the way it works -- and that's better for your server if you have lots of users)
when user logs in, you set a cookie that contains what is needed for him to be recognized
if he comes back on the site (with the cookie, and without having an active session), you use the informations contained in that cookie to auto-log him in, re-creating the session at the same time.
This way:
you don't have thousands of sessions "active" with no good reason
you keep the standard way sessions work
And you have the advantage of "never being logged out", at least from the user's point of view.
Also note that with "normal" sessions, the cookie containing the session id will be deleted when the user closes his browser -- so, he will be disconnected, no matter how long the session's lifetime is.
With the solution I propose, you are the one who sets up how long the cookie should remain on the user's computer ;-)
It means, though, that when a user manually logs-out, you have to delete both his session and the cookie, of course -- so he's not immediatly re-auto-logged-in.
Of course, you have to be careful about what you set in the cookie: a cookie is not quite secure, so don't store a password in it, for instance ;-)
Actually, this way of doing things is how the "remember me" feature often works; except, here, your users will not have to check a checkbox to activate "remember me" ;-)
If you don't have the time to develop that kind of stuff, a pretty quick and dirty way is to use some Ajax request on all your pages, that will just "ping" a PHP page on the server -- this will keep the session active (but it's not quite a good way of doing things: you'll still have LOTS of sessions on the server, you'll have lots of useless requests... and it will only work as long as the user doesn't close his browser).
You can't do that with the PHP internal session handling alone. PHP will always send out the session id in a session-cookie which will expire when the user closes his browser. To achieve some sort of auto-login you'll need some accompanying code that sets a longer-lasting cookie on the user's browser and handles the recognition of these cookies and the mapping between the cookies value and the respective user account.
Please note that this greatly affects security issues so you'll have to take care of a lot of things. Please read the following on how a possible auto-login feature could be working:
Persistent Login Cookie Best Practice
Improved Persistent Login Cookie Best Practice
Do you remove your cookies while testing? Are cookies enabled? Do you destory the session somewhere in your code?
Also, see my answer to another post: Quick question about sessions in PHP which explains how to stay signed in. Just don't do a cronjob/sheduled task if you want the user to stay logged in forever.

Categories