Invalidate all sessions by a user id with PHP - php

We are using PHP and storing session data in memcached. Is there a way to invalidate all sessions by a given user id? The use-case is, when a user changes their password, we log them out, however we should also be invalidating every other session under that user id as well.
Is this possible?

I think you would have to add a check on every request to make sure the user context is still valid.
First thought is to have a record in a backend store that contains a timestamp that the user password was updated. When a user logs in you can write a cookie with a timestamp or store it in the session. Upon subsequent requests/checks, as long as the cookie/session date is newer than the password change date it passes. When the password changes the date on the backend record is set to current timestamp and the next check will fail and destroy the user session.
So in this context the actual invalidation wouldn't happen until the next request comes from the old session.

Related

Best way to prevent simultaneous login

I know this is a recursive question, but, I haven't found a new solution, or a solution based on the new frontend frameworks or technologies.
I've a Vue + PHP application that users can olny log once per time. My current solution to block concurrent access is making a call to a PHP page with Ajax from 5 to 5 minutes storing the time. I store a flag in DB too, whether it has been registered or not. So, when the user try to log in, I check if the time is greater than 6 minutes or the flag is set to 0.
I think this is not the best way to do this. When the application has too many users it can cause too much load on the server.
There is a way to do like Netflix? An warn when triyng to connect and was logged in another machine.
If your end goal is to have it so that any given account can only be logged into one machine at a time, generate a unique ID at login and write that ID to the database for that user. Set that ID as a cookie for the user. When you receive traffic from that user, only consider them logged in if their cookie matches the value in the database.
When the user logs in to a new device, a new unique ID is generated and sent as a cookie to that new device. The new device's traffic has a cookie that matches the database, and is therefore considered logged in. When the old device visits your application, the login cookie no longer matches the value in the database, so that user is considered logged out.
When the old device logs in again, a new unique ID is generated in the database and sent as a cookie to that device. They are now logged in, because their cookie matches. The second device, having its cookie no longer match the database, is logged out.
This solution doesn't require you to access the database on every page, reducing database load significantly.
Add a field for sessionID to your user table in the database.
Set the default session handler before calling session_start() (needed for the next line of code to work):
session_set_save_handler(new \SessionHandler());
On every successful login, retrieve the stored $sessionID from the database. Destroy the old session with:
(new \SessionHandler())->destroy($sessionID);
Get the new session ID with:
$sessionID = session_id();
Store the new session ID to the database.

Sessions or database access to check if user is logged in?

I use php-sessions to check if users are logged in to my app. Is it significantly better for performance than just keeping the user id in a session and checking against the database if the user is logged in instead?
If the password changes or I want to block/log out a user it is easy to just change the database record, but when it lives in a session, can I do that? How?
You can use both.
Use the session variable as a first check, so that you immediately reject any request where the session variable is not set. This saves doing a costly database check for random door-knocking requests.
But if it's set, you still have to do a database check to see if the user's login session is still valid. When a user logs in, create a random token and store it in a session variable and the database. When processing a new request, check if the session variable matches what's in the DB. If an admin wants to force a user to be logged out, they simply invalidate this database record.
I use php-sessions to check if users are logged in to my app
I'm not sure exactly what that looks like - but it sounds horrendous. Either you've broken the session security model or you must be brute-forcing the session data every time you want to find out whom is logged in. Certainly a requirement to maintain a list of active sessions and user identifiers would be best implemented piggy-backed on a custom session handler (for the purposes of triggering - not for a common storage substrate) but you seem to be implying that you you are not doing this.
If the password changes
You cannot keep the password used to authenticate the session in the session.

Orphaned Session Management Records in Database. How to handle the issue? DB Stability Risk

I have a webapp that uses persistent cookies to allow a user to stay logged it.
I am using the Improved Persistent Login Cookie method.
https://www.programering.com/a/MDO0MzMwATA.html
https://www.experts-exchange.com/questions/29006560/selector-validator-cookies.html
When a user is logging in through the LOGIN form and has asked to be remembered I generate a random selector and a random token and add these to a table called Session in my DB along with the userID and other values(IP,time,browser,whaterver). I also set a cookie called KeepMeLoggedIn with the value selector:token and expire in 30 Days.
When the user returns to the site (before or after the PHP Session/Code Igniter has expired) I check for $_SESSION variable, if none found I look for my KeepMeLoggedIn cookie. If the cookie returns a value I check it against my Session table to see if the selector and token match. If they match I reset the token and store it back in the DB and cookie is updated to the new selector:token value and the login process completes.
When a user logs out I destroy the cookie and session and delete the entry in the DB for the selector.
All this is working great except for when a user deleted the cookies manually. The record in my Session table is orphaned. In testing my system I ended up with 50+ records in my Session table that were from the cookies I manually deleted while testing the logic. Since I manually deleted the cookie the selector was not available to the code to be deleted/removed from the Session DB.
So here is my questions:
1) What is a usable approach to handling these orphaned record?
My first thought is just purge the Session table of any date older then my chosen expiration date for the Remember Me function, either when a user logs in, or in a chron job, or whenever
Are there any other ideas here?
2) Is this a vulnerability in the overall model that can allow a hacker to:
create an account on a website
x=1
while x <2
-> login and ask to be remembered
-> delete the cookie
do();
And end up flooding the website's Session Table till the site is shut down, adding 1,000 and 1,000 of record over time??

Is it a good idea to use a combination of cookies and sessions for keeping users logged in

I am looking at the possibilty to set up a option to keep users logged in. Now I understand a session could be used to allow a user to navigate around without re-entering login information on each page only until the browser is closed and the session is lost. A cookie would be stored client side and has a duration until it expires or the user deletes the cookie.
I was thinking that I could use a combination of both
Create a db table (id,user_id,cookie_token,is_active)
User logs in which creates a row in the db table connecting the user to the cookie_token which is stored on the client browser (system) as well.
Each time a token is created, check to see if the user the token is being created for has any active tokens in the system already and set those to inactive before a new one is created.
Only one token can be active per user
So every time the user visits the site, the system looks up that token and checks is_active fields,
If the user_token is found and is_active = 1 or true, the user data is retrieved (id,name,etc) and this then creates the session and the session variables.
I am not able to find any questions or answers that use a combination of both so it could be that this is just overkill or a very bad idea, I just started to read up on sessions and cookies and have been trying to figure out a system that I could implement myself so would be nice to know if this is good or bad.
I can't reply as a comment anymore, because my reply would be too long...
I've implemented something like follows. Unfortunately I can't remember it precisely, but it would give you a pretty good idea:
Visit before manual login:
Start a session.
At successful login, store a user identification into this session and store a token value into the dB and into the cookie.
Next time the browser visits the page:
(re)Start the session.
Check if a user identification is set in this session.
If so, auto-login the user which matches the identification.
If not (session expired due time restriction or browser close), check if a token value is stored in the cookie and if this value matches a token value stored in the dB.
If an (unexpired) match found, auto-login the user and remove old tokens.
If the user identification is invalid and the token value is invalid/expired:
logout the user (which contains all actions to go back to "public" mode like destroying the session, removing tokens, cookies, etc.).

How to automatically re-login a user with a cookie

So on my application login form I've got one of those little boxes like [_]remember me
When the user checks that we set $_COOKIE['rememberMe'] with the value of the username. Now when that user comes back 3 days later, I obviously want to recognize them and re-log them in automatically. It doesn't sound safe to simply check for the existence of that cookie and then use it's value as the username to login without a password. But I'm not sure how else I would log them automatically... Is there a way this usually done?
Your cookie should have three values:
1. username
2. expiration time
3. a session code
When a user logs in, generate a session code and set an expiration time.
Store that session code and expiration time in the cookie and on your database.
Then whenever user returns to the site, and if user is not logged in:
1. check for the cookie
2. check for the cookie against the database
If all three variable matches and the expiration time is not over, log the user in.
Alternatively, if you simply encode the session code as say a md5 of ($username.$expiration_time), then you won't have to set up a database for storing and checking. Although having a database with randomly generated session code is much safer.
This is extremely unsafe. Since the cookie is the only thing you have to go by and the cookie is transferable from system to system, you would be vulnerable to cookie poisoning attacks and cookie copying attacks. If this is indeed the course you're set on, you will need to use some manner of foot-printing the user's system and storing that information in a database somewhere possibly as part of a persistent session on a session state server. This information could then be compared with the new login so if the cookie is transferred to a different system, it will not match and the automatic login will fail. As for accomplishing the login, I would recommend at a minimum to have a session state database where session information could be stored per session ID and username. If these 2 items are stored in the cookie, this information could then be used to get the information out of the database, and the foot-printing could be used as a stop-gap (although a very weak one) to prevent misuse.
The only information you need to store in a cookie is some unique hash that's going to point to the right user session in your system. Storing username or other information is redundant and unsafe considering the fact that username can be captured by an attacker and used with a combination of other information. To make the system more safe, you should implement a layer that'd check user's location by the IP address and his browser details. I suggest you should learn from what companies like Facebook and Google do with user accounts.
Place a random and uniqe hash in the cookie and store it in DB too with the current client's IP address.
If the user comes back, you can search for the hash in your DB.

Categories