I am trying to secure my sessions. While doing some research, I reckoned that PHP's PHPSESSID+random hash based on Agent and IP is good enough to secure against hijacking. What else can you do, really.
I am using HTTPS for the login. As far as I could understand, the session data from PHP is never sent to the user, but rather stored on the server-side. The client only gets the id for the session. The session data holds the actual webapp's user session, which in turn is used to check if the login is valid. All fine and dandy.
However, there is a detail I can't find anywhere. I would like to to know if the cookie containing the PHP session id is automatically marked secure if I am using HTTPS. I did some google searches but never seemed to get the right search string because i only find ways of manually sending cookies. I would like to know because if that cookie is sent clear-text, it would compromise some of the security via man-in-the-middle.
EDIT 1
This is an addition for #ircmaxell
I tried out your method but somehow I still get the cookie when I switch from HTTPS back to HTTP. The way it should work is the following. Whenever the server is aware that a user session is available, it sets the secure flag. This means that the entire site runs on SSL as soon as you are logged in and refuses to give away/use the cookie whenever you don't use SSL. Or at least, that's the idea.
if ($SysKey['user']['session_id'] != '') {
session_set_cookie_params(60*60*24*7, '/', $SysKey['server']['site'], true, true);
}
I assume I need to regenerate the id since the Browser already had the cookie before the login but since I can only try it out in a few hours, I'll ask here before trying
NOTES TO SOLUTION
I just found out that you have to set these settings before starting the session. That was my problem. I am now using 2 different cookies. One for the regular guest that is sent via http, and a second for logged in users that is only sent via ssl.
Don't even think about rolling your own session handler!
PHP's session has been broken many times, and because of this it has been made more secure now than ever before. When a new issue is found it will be fixed quickly and for FREE.
However, you might want to add these options:
session.cookie_secure=True
session.cookie_httponly=True
session.use_cookies=True
session.use_only_cookies=True
I think the function that you're looking for is session_set_cookie_params(...). It will allow you to set the secure cookie flag to make it https only.
You can check via: session_get_cookie_params()
Related
I'm new to PHP, I read other articles without finding the answer I'm looking for, but still don't know if what I want to do makes sense or not.
I'm using PHP 7.
My user authentication page, checks credentials and then executes session_start(), creating the session server-side and a cookie client-side in the browser.
Each other page of the web application then calls session_start() to resume session information, in this case checking the cookie. Everything works fine so far... at least when I have a single login.
I'd like to be able to have more than one user SIMULTANEOUSLY logged in the same browser (on another tab for example.) using cookie. I don't want to append the session ID to the URL.
I managed to create different session on the server-side using session_id() before session_start() in the authentication page based on username, but the problem is on the client side.
The first successful login (session_start()) creates a cookie and the second login updates the same cookie corrupting the previously created session.
Therefore when it comes to resume the session, session_start() will resume only the last session, mixing the data fetched from DB based on session info.
Is there a way to make session_start() create a cookie for each login and make PHP resume the correct session using cookies?
Any ideas?
FURTHER DETAILS:
I'm updating a legacy app trying to fix some security issue. The need for multiple sessions comes from administrative purposeses where admins access the same site. The reason why it's needed a separation of session is that depending of the session info, the data are fetched from a different database. Therefore, a regular usage would only need one session per user, but the administrator he needs to make multiple logins viewing different data depending on that login.
The default PHP behaviour is to handle sessions using cookies.
..and the default behaviour for browsers is to "reuse" the same set of cookies if you revisit an URL in another tab.. So, like mentioned below:
The simple way probably is to start another browser. Not the same browser but like firefox and chrome, if you have multiple browsers installed.
Another way would be to install a browser plugin, like Sessionbox for Chrome or Multifox for Firefox.
Edit, for clarity: I can think of two cases when multiple sessions would be used:
During development. Depends on the application, but an obvious case would be testing communication between two users.
After deployment. Though I've never seen a site that required multiple logins for the same user account.
This is my frame of reference. Based on this I assumed the question was for development. I'm not suggesting that the site should require installing extra packages. Flash would be about the only one that's ever gotten away with that..
You can use the same session but change the variable names that you are looking for:
if ( $_SERVER['REQUEST_URI'] == '/admin/' ):
$session_name = 'session1';
else:
$session_name = 'session2';
endif;
session_start( $session_name );
I am building a website and I am using sessions to check user login. I am wondering if there is any better and safer way to check user login. Because sessions are stored in the clients computer I think they are not very safe and easy to hack. Am I correct?How do big websites like facebook and twitter check if their user is logged in or not. I am new to PHP so dont say my question is too basic.
Sessions are not stored in the client's computer. You must be confused with cookies !
Sessions are definitely the way to go here.
No matter what you use as authentication, if the client computer is compromised, the client's method of authentication can be abused. So in this regard, any other way can only be as safe as sessions are.
All big sites use sessions, usually in conjunction with cookies.
I want you to first understand that Sessions are the only way you can identify a client.
You don't store sessions on either the client or server side. (If you want a secure system.)
First you need to understand the need for sessions, only then you can know what sessions are.
The internet is a stateless network of machines, each with their own identifiers. Most of the communication that we do while sending a request to load a page or visit various links are over the HTTP (Hyper Text Transfer Protocol).
HTTP is a stateless protocol, meaning any communication over this protocol is not required by the protocol to be stored on either the server or client.
Let us understand what this would mean, with an example:
Suppose you try to login to http://example.com
You fill the form, hit the send button.
All the data in your form is then sent to the server.
The server checks if the username and password received was right. If right, it sends you the secure data.
In your next call to the web server, you expect to be logged in. BUT, due to the stateless nature of HTTP, your server does not recognize you anymore.
You can make this work by sending your username and password with every call, but that would mean having to enter it every-time for each request.
Here comes the role of cookies, you set the username cookie as Joe and password cookie as qwerty. Now everytime a request is sent the cookies are sent by the browser and you are happy.
This scenario now again has a problem that you need to make an authentication check everytime on your server thus increasing the load on it.
Enter Sessions. Sessions mean states with some context. It may be a logged in user, it may contain preferences you have set or any other similar stuff.
Here, when the user is logged in the first time, the server generates a session ID. This session ID is then stored by the server in a DB, File or it's Memory (RAM) along with any other data like username of the person who is logged in, preferences etc.
The server response then contains the session ID, which may be in the form of a cookie, HTML5 session states or sometimes even hidden fields.
Now, every call the client makes, contains the session ID. The server then checks its session store for any valid sessions with the same ID and get into context therby giving a pseudo state-like mechanism to communications taking place over HTTP.
How long your browser stores this cookie can also be determined by the server while sending the cookie.
There are advanced techniques for further security like changing the session ID each time a call is made, but lets get into that only if you want me to.
Cheers! :)
Pretty basic question here. In PHP, if the user's browser has cookies disabled, you cannot make use of both server cookies ($_SESSION) AND client cookies ($_COOKIE, setcookie) or only the latter are disabled?
Basically you can't make the user log in or do anything that requires a session, right?
Also, in which case would someone want to have cookies disabled?
Thanks!
Yes, it's true. Both sessions and normal cookies are normal cookies. If a user does not accept cookies, he cannot use any of the functionality enabled by them. Which means pretty much the whole internet would break for that user, which is why in this day and age there's virtually nobody who has cookies disabled entirely.
PHP has a built-in mechanism called transparent session ids, which automagically rewrites all links to contain the session id in a query parameter. I would not suggest using it, since session ids in the URL open up a whole new can of worms.
For user friendliness, I'd recommend you test whether the user has cookies enabled or not (set a cookie, redirect to the next page with a flag in the URL that cookies should be set, see if you get any cookies back) and if not, kindly advise the user to enable them.
You can track the user by $_GET.
Imagine that on every-single-page the user visits you pass a ?user_id=XYZ123 then you would have implemented a very similar server-identification. It has obvious disadvantages:
if you copy/paste a URL you'll give away your session_id
because of 1 session high-jack is even less tech savy
Why do users disable cookies?
Users tend to throw first and third party cookies all in the mix but they come from different breeds.
First party cookies are generally ok. When you visit Facebook it's expected that Facebook keeps a cookie to store your interactions with the server.
What it's not expected is that the advertising company that has adds both on Facebook and on eBay gets your cookie back and checks, ah, so this guy was on eBay looking for xyz so now that he's on Facebook I'm gonna show him up abc to make him buy etc etc...
I think you should read the session reference manual http://www.php.net/manual/en/session.idpassing.php
In short, if your server can't find session_id, he can not restore session. But you can use alternate ways to store session values. Or you can generate session_od base on user's client environment parameters.
I am making a login script that I would like to be as secure as possible. Problem is, security seems to be a never ending battle. So essentially, I am looking for suggestions and improvements to my ideas.
What I have is a login based solely on sessions. Anytime the session information changes, session_regenerate_id() is called to avoid obvious hijacking attempts.
When the session is not set, I check a cookie for valid login, and on success, I update the session.
I attempt to secure the cookie by adding a hash value along with a piece of unique user information (like username or id). This hash is comprised of various information, including the username/id, undecipherable password hash, part of the IP address, etc. By extracting the username/id from the cookie, I can make a new hash from the valid user information and compare that with the hash in the cookie. My hopes here are to prevent fake cookies and cookie hijacking (unless they also spoof the IP address).
EDIT Assume that the login itself will be done via HTTPS/SSL, so the transfer is (reasonably) secure.
Am I on the right track? What else can be done to secure my login?
Thanks for the help!
Stop what you are doing. Do not check the user-agent or the ip address. The user-agent is an attacker controlled variable and checking this value does not increase the security of this system. The ip address will change for legitimate reasons, such as if a user is behind a load balancer or TOR.
A session id must always be a cryptographic nonce. In php just call session_start() and then start using the $_SESSION super global. PHP takes care of all of this for you. If you want to improve php's session handler, use the configurations. Enable use_only_cookies, cookie_httponly and cookie_secure. Also setting the entropy_file to /dev/urandom is a good idea if you are on a *nix system but if your under windows then your in trouble.
For instance to authenticate a user:
//In a header file
session_start();
...
if(check_login($_POST['user_name'],$_POST['password'])){
//Primary key of this user
$_SESSION['user_id']=get_user_id($_POST['user_name']);
$_SESSION['logged_id']=True;
}
And to verify if a user is logged in:
//in a header file
session_start()
...
if(!$_SESSION['logged_id']){
header("location: login.php");
die();//The script will keep executing unless you die()
}
To improve this system read OWASP A9 and use HTTPS for the entire life of the session. Also read OWASP A5: CSRF aka "session riding" and OWASP A2: XSS because they can both be used to compromise a session.
There is no such thing as secure cookie UNLESS it's transmitted over SSL only. It can be mitigated some when using a persistent non-session cookie (like remember me), by doing exactly what you're doing, but not in the same way you're thinking of doing it.
You can indeed store server variables such as the user-agent, the ip address and so forth (and even JavaScript variables), but they are only good for validating that the persistent cookie data matches the client's new connection. The ip address isn't a good idea except when you know that the client (like you only) isn't going to change on every page load (a la AOL).
Modern web browsers and 3rd party services like LastPass can store login credentials that only require a key press (and sometimes not even that) to send the data to the login form. Persistent cookies are only good for those people who refuse to use what's available otherwise. In the end, persistent, non-session cookies are not really required anymore.
I use a cookie based method (using setcookie function) but ....
session_start();
...
if(check_login($_POST['user_name'],$_POST['password'])){
//Primary key of this user
$_SESSION['user_id']=get_user_id($_POST['user_name']);
$_SESSION['logged_id']=True;
}
...these methods are wrooooong !!!!
I crack my website with an attack based on the cookie.
I used cookie option of the WebCruiser vulnerability scanner, so I get my cookie after login.
Then I changed a simply value on cookie
Then I clicked save cookie.
At this point I clicked on webbrowser see on the left panel then I clicked right then I clicked on refresh page, so I got my admin page without using the login page with user and password.
So if someone push you a virus to read the cookie history of IE or Firefox, you'll be happy to find out your admin user and pass can be used by others.
So how to fix the problem? Simple: combine the cookie with session server or session's cookie with sessions server, or session with file session, or cookie with file session....
will be secure but slow :((((
I keep all login data in the users session, this way its all stored server side.
The only thing i would store in a client cookie is stuff like 'auto login', 'session id'
SESSION more secure than cookie
and my advise is to create a unique id for the current login attempted
like :
$id = uniqid();
$_SESSION['username'.$id] = "something ...";
Do i login using cookies or sessions in a login system? I've seen examples using sessions and cookies so i am confused! Can someone please explain this?
What do most sites use? love to know!
Thanks in advance;-)
Sessions - in most cases - use cookies to store their session id so its pretty much always a case that you are using both. Most sites will use sessions as cookies are inherently insecure as data is stored at the client side where as session data is stored on a server. It is largely a matter of security and what data you intend to store but since its so easy to modfify cookie data then you should never really trust anything within cookies.
Login with Sessions because they are safer than cookies in that user's don't have direct access to your cookies.
BUT, when you use sessions, you are also using cookies, so in fact you are using both...
ex:
//query to get username from database
$_SESSION['user_id']=___
$_SESSION['username']=____
DON'T store passwords or anything sensitive in sessions or cookies
A session is your server or applications idea of a person. In default PHP, when you create a session, a cookie is sent to the browser for storage. Every time the browser makes a request, it will send the cookie along and the server will lookup the information it has associated with that cookie. Sessions are good for storing user settings or server information because the user only ever sees the session key.
With cookies you can set a preference independent of the user or session at your site. Like the style of the page or whether this is a shared browser. This information will be sent with requests from that browser, so can be accessible from server scripts. The bonus with cookies is that javascript can use their values for processing without backend support (for static pages), and that the user can change them themselves.
Good advice above should be followed: put nothing in cookies you wouldn't want anyone to see.
Not only can the user see them, anyone with access to the users computer or the network connection between you and the user can see them.
It is a bit of a minimalistic answer but here goes:
- If your login system has a "remember me" feature, it very likely uses cookies but not sessions
- If not, it uses cookies and sessions (because sessions use cookies as per said in above posts)
Hope it helps