How Should I Implement Implicit Logouts? - php

My login system currently works as follows:
Grab the user's username and password from a POST form.
Check the username and salted + hashed password against the database.
If authentication is successful, generate a long, random, alphanumeric string.
Store this string in MySQL, as well as in a $_SESSION variable along with the username.
This is opposed to just putting the user's password in $_SESSION. I feel like that's leaving the door wide open for spyware to come in and steal the user's credentials.
On each page that requires authentication (e.g. non-sensitive account settings, members-only areas, etc.), check the $_SESSION username and string against those stored in MySQL.
If they match, go ahead and show the page. Otherwise, show a login form.(?)
When the user explicitly logs out, remove the random strings from MySQL and $_SESSION.
What I'm stuck on is how to handle when the user implicitly logs out. That is, when he/she closes the browser window without hitting any "log out" button on the site. I'm pretty sure I still need to remove the random string from MySQL, so someone can't use a stolen cookie to log in afterwards. But how do I know when the user closes the browser window?
("Remember me" functionality is irrelevant for now.)

How Should I Implement Login Sessions?
Authentication and session management are 2 different things, although they are closely tied together, you seem to be talking about authorization too.
If authentication is successful, generate a long, random, alphanumeric string.
Why? PHP already generates a random identifier (the session id). If you want to differentiate between authenticated/non-authenticated users and/or identify which user owns the current session, just store the username / userid in the session.
putting the user's password in a $_SESSION variable
Why would you ever want to do that - once you've authenticated the user, you never need to use the password again.
check the $_SESSION username and string against those stored in MySQL
Why? How can the session data be changed other than via your code? If you suspect that your serverside code could be tampered with then it doesn't matter what you do, the system will be insecure.
When the user explicitly logs out
...you explicitly destroy the session. That's all.
When you remove the redundancies from your proposition there is no need to clean up after an implicit logout.
BTW: there are a number of security issues you have not addressed in your proposal, notably regenerating the session id after an authentication attempt.

You could use an ajax call on onclose event to kill the session... never tried it but it should work:
$(window).unload( function () {
// ajax to kill the session
} );

Related

Designing a Login system - What's the right way to do it?

I'm somewhat new to web development and I need to develop a user system - so users can register, login etc.
I initially stored the user data in a Session variable upon login, but felt the need to re-architecture that because I realized I would never be able to support 'remember me' functions, and decided to use cookies.
My current system is this:
User logs in: I verify username and password against stored values in DB
I set username and password to their own cookies. username cookie persists so the username field can be populated when the user revisits. Password cookie expires when user leaves.
Each time a page loads, my PHP script checks to see if the password cookie exists, which means the user is logged in.
The problem is, the third step seems somewhat insecure to me. Currently, I only check to see if the password cookie exists, but I do not compare it against the database everytime a page loads. Couldn't an unauthorized user create a password cookie and set it to some random string manually, and get through my authentication system? He would be able to impersonate any user by setting the user cookie manually as well. Should I be comparing the value of the password cookie against my database on every page load?
So, if I use session in conjunction with cookies, I imagine doing something like this:
if (!isset($_SESSION['user']))
{
authenticate_user_from_cookie();
set_session('user');
}
else
{
//user is already logged in
}
When you call session_start() it will reconnect the current request to a session ($_SESSION), or create a new session. Apache saves these sessions to disk (by default in your /tmp folder) and reconnects you to the session automagically with a cookie named PHPSESSID (this can be changed in PHP.INI), that is stored after the first time you call session_start() on the first request.
You can authenticate your user by whatever means you want, but typically you could use lookup the username + (encrypted password - e.g. sha1($password.'salt string that only you know')) pair in your database or permanent storage and then simply set $_SESSION['loggedIn'] = true or $_SESSION['user'] = 1 or whatever flag you want in the $_SESSION.
You can go as far as creating a User class (many frameworks do that), representing everything you know about the logged-in authenticated user and then ask the object $_SESSION['User']->isAuthenticated() or something like that.
If you want to not have the user reenter their password each time you can implement a Remember Me feature (special random cookie that you generated when they authenticated and stored in the database), that will set a special cookie in their browser that won't expire at the end of the session that you look when someone makes a request who isn't authenticated.
This is not php specific but if you're new, I would recommend reading the OWASP guide. OWASP is an excellent resource for secure web development info. The OWASP site will cover much more than we can here.
For a more php specific answer, they have this guide. Point 2.10 addresses your question more directly.
Just checking for a cookie's existence is by no means a way to authenticate a user or validate his identity. So yes, you should be checking on every page load, if you're sticking with the cookie based authentication. As long as there's an index / primary key on the lookup into the user table, the query will be fast to pull the user's information and check against the cookie values.
To be more specific, the cookie(s) that you're setting are just as valuable as the user's username and password, they're nearly synonymous. So, you can also save information about the user when you issue the cookie, such as IP and User-Agent, which you can also verify to try and ensure the cookies match the user.
A few more tips:
1.) Make sure you do input validation for both the password and the userid and make certain that you are validating the values on the server side as any client-side validation can easily be bypassed by malicious users. If you don't validate on the server you will be opening yourself to various types of attacks such as SQL injection and people will be able to compromise your database. Make sure you are escaping any potentially malicious strings
2.) Make sure you have login logouts, so that if people try to to put in too many wrong credentials you block their IP for a few minutes. This will discourage brute force attacks.
Make sure that this works for both bad userids as well as bad passwords as attackers can iterate over either (e.g. they can keep the password the same and try many user ids).
3.) If you are using salts, do not store the salt in the same place as the password hashes. If someone breaks into your database you don't want them to have both the hashes and the salts because it will make the hashes easy to crack using rainbow tables.
4.) Make sure you are using SSL/TLS to encrypt traffic traffic between the server and the user, otherwise an attacker can steal the cookie by sniffing the network and login as your user. (Look up Firesheep, it was a big problem for Facebook and Gmail for a little while...)
5.) Don't do any custom encryption schemes, use only trusted cryptographic libraries and algorithms to perform hashes. (e.g. PHP's sha1 is good, doing your own little rotation on password characters is not).
6.) As recommended, you should check out OWASP, it's the best resource for securing a web application.

What is the best way to securely authenticate a user ? (session, cookies, php, mysql)

What is the best way to securely authenticate a user ?
So far I was thinking of:
Generate a random $SALT for each successful login and store $logged = md5($hashed_password.$SALT) into database; delete on logout.
Store $logged into a cookie (If user checked "remember me"). Set $_SESSION['user'] = $logged;
On a visit: Check if $_SESSION['user'] is set; if not, check for cookie, if data doesn't match, redirect to login page.
What are the risks ?
The only issue I can see with your existing framework (which I like otherwise) is that there is the possibility of collision for $logged.
It is not mathematically impossible for two valid user log-ins to result in the same hash. So I would just make sure to start storing the User id or some other unique information in the Cookie as well.
You may also want to keep a timestamp of when the $logged was put in the DB, so that you can run cleaning queries where they are older than x days/weeks.
The first step is a bit overkill, as this is what $_SESSION['foo'] basically does client-side for the lifetime of the session. I'd just store a salted and hashed password for each user to begin with, salting with the date or other pseudo-random factors.
Setting the cookie might prove useless if the user clears their cookies, or the session expires. This will leave the user logged in (according to your database) when in reality they're not.
I'd stick to just $_SESSION['foo'] and cookies and leave the database out of the login process.
First No need of doing
Store $logged into a cookie (If user checked "remember me")
Starting the session should be the first thing you should do place session_start() on top of your index.php (file which gets executed) . This way a cookie name "phpsessid" gets created on user browser by default independent of weather user is logged in or not . value of this cookie is unique by which you can identify the user after he logs in. So you dont need to create any other cookie for this purpose.
In first point you have mentioned It create random SALT string when user logged in and clear it when user log out.
Main problem is you have to check SALT string is exist or not in each redirection of page. So it create heavy traffic in Database server.
Yes this is very useful for checkout user already logged in or not.
But in case of power failure in client machine after log in when Salt string remain in database after long time.
In second point to user authentication in cookie it is not secure. Client can easily show authentication cookie in browser
In third point to store authentication in session it means create session variable on server side and store it in file on server side. It is very secure then store it in cookie.
The best way to authentication is combine point number 1 and 3 which you mention.
You can check user already logged in form other pc or not?
You can easily clear SALT string if session is not exist.
You can easily manage Login in case of pc power failure
One problem I can see - your solution sounds annoying for people who load your site in multiple browsers at the same time.

PHP login security

This is how I'm building a login system:
Login:
Check username and password supplied by user with the database.
If username and password is correct, store only user ID in session, something like:
$_SESSION['userid']=$userid;
If User has checked the option to stay logged in, then set 2 cookies, 1 with userID and other hashed string.
To check if user is logged in:
Check if Session exists, the user is logged. is it ok?
If session does not exist, check if both cookies, userID and hashed string exist.
If Both cookies exist, validate them.
As the Session is stored in the server, is it secure to store only userID ? Can a user pretend to be other user and store his userID in the session and log in as him?
Thanks.
Yes, this method is very insecure. I can sniff traffic, intercept your cookies, and your system will accept me as an authenticated user. You are making the assumption that if you get a cookie with a userid and the hashed string, then that user is the same person that originally authenticated to create the cookie. That is a poor assumption, because cookies travel in plain text (unless you encrypt them), so as long as I can grab a cookie, I can pretend be whoever sent that cookie, and your system doesn't know any better.
Edit:
If you are going to use unencrypted cookies, why not just store the session_id in a database table? That way, at least someone that gets hold of a cookie won't have a valid username. Create a sessions table, and when someone successfully authenticates add a row with their user_id and the session_id. Each time a page is loaded, check to see if the session_id in the cookie matches a row in the sessions table. If yes, you can assume the associated user_id is the authenticated user. This approach is just as secure as the one you suggested (i.e. not very), but it's less complex and doesn't give away valid usernames.
Yes it's possible and very extended, this kind of attacks are called Session fixation and in your system (as David said) anyone who sniff your traffic, or have access to the user's drive and steal his cookies, may supplant a logged user.
The best protection is, of course, SSL, but if you can't use it in your website there are other things that can prevent (but not fully protect against) this attacks:
Save info about the user in the server-side when he login, good candidates for this are the IP and the user agent, but any other data that don't change in the entire session can be valid.
You can regenerate the session ID in every request, with this if the session ID is leaked the attacker must use it before the real user do any other request, but beware because every time the session ID is regenerated (in PHP at least) the user's session data is rewited, so this can be expensive if you have a lot of users or if you save many data of every user (this means that, if you're saving the session data in a file, the file will be deleted, created, and writed again).
Well, right now I can only think in these two, it's not much but at least you will put an extra complication to the attackers.
One more thing, don't trust the user's cookies, they can be changed by the user (or the attacker) at any time, treat it like any other user input.
PD.: Sorry for my horrible english, I'm truly trying to improve it ^_^
you could add an ip that the user id should belong to (in your database), that adds a little extra security - it might not always be the best solution
Yes it is ok to check if the session exists and also check that the user id is greater than zero.
The 'remember me' function is subject to sniffing as it's not over ssl, however that is how 'remember me' functionality is done.
Assuming this is happening via SSL, my biggest concern is your first step:
Check username and password supplied by user with the database.
You should be hashing passwords, and comparing the hash of the user-supplied password against the previously hashed password stored in your database.
You also don't have to worry about storing only the user ID in the session array; the session is stored server-side and is as secure as the rest of your server.
One potential problem is that everything is being stored in cookies. If someone somehow manages to get their hands on the Session ID, then they've also got the username and hashed string.
Chris Shiflett suggests creating some kind of fingerprint from the User-Agent string, or some other regular header, and storing it in a GET variable.
One way to bump up security is to have everything sent over SSL. Any time any kind of potential information is sent or received (such as the Session ID in a cookie), make it encrypted - not just the login form.
It is mostly correct but I don't agree with the cookie-option. This way if someone gets the two cookies can move them to a different computer and still use them.
The "remain logged in" function should be restricted to that computer. A possible solution is that if the user wishes to remain logged in you set the lifetime of the session to 1 week or so. Also you have to store the user's IP address, User-Agent and possibly X-FORWARDED-FOR header, and check them on every pageload against the stored values.

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.

Store "password is ok" in php Session variable?

Is it safe to store a password in a sessions variable?
For example, usage would be in a form which is submitted to itself.
For example a change classifieds page, where users first enter a password, and then if pass=ok, show the form to change the classified. All on same php-page.
But Whenever a picture is uploaded in the "change" part of the php page, the form must submit to itself again.
Should I here use the stores Session password to verify that the user is actually the user, and that it is secure?
In other words, is it safe to store something like this:
if($pass==$row['password']){ // If password was correct
$_SESSION['pass_ok']='1';
}
Thanks
Camran, what you are trying to do is a standard way to maintain php sessions. You are actually not storing the password in the session rather just storing the information that this particuar user has already logged in.
$_SESSION['pass_ok']='1';
On every page you just have to do a session_start() and check of this session is already set to 1, if yes they assume him to be logged and proceeed, else redirect to login page.
If someone gets hold of the session id then they definitely can access the user session. You can do a few things to make it more secure.
Use SSl (https), it will make hard to sniff the data and get your session id
maintain the client ip in the session when user logs in, for every request after logging in, check if the requests are coming from same ip
Set a short session timeout, so that if left idle for a while the session times out automatically.
Use a pre-built authentication system. That your best bet at being secure because they would have (or should have) thought of everything (security issue) already.
What i do is,
Check user logs in correctly
Assign a session to username + userLOGGEDIN session
When a page is clicked, my system searches the DB for username + userLOGGEDIN if its true then allows access to the page, but what it also does is, deletes the record its just searched for, and inserts a new record for the username + userLOGGEDIN with a different MD5 HASH. So hopefully it will be harder to crack.
I would advise against it. If someone logs in and copies the session ID down they can theoretically log in to any page. I would instead advise you check the password is okay on every page refresh as this will be more secure.
Additionally, always store passwords hashed in a database, or better yet, hashed with salts.

Categories