Cakephp/php user sessions swapping for a subset of our customers - php

There's a bug, which we can not replicate, which involves users in one specific region of our enterprise customers swapping. For example, a user logs in as themselves on the login page, and when arriving at the home, they are another user.
It seems like accidental session hijacking, here are the clues:
cakephp security is set to low (this only means the cookie doesn't
rewrite every page load, and the the cookie does not do a user agent
check )
our cookie is set to not care about subdomains (.example.com instead of example.com)
enterprises users areredirected using a 302 if they login to the wrong area (should we use 303?)
there was a 301 accidentally sent out, but users are able to replicate
all the affected users are behind a single router, sharing internet via Sprint MPLS
all the affected users may be using computers issued by the customer
their IT claim there is no proxy cache, and no remote VPN access, yet they claim to be able to replicate the issue from home computers and off the network.
Since we can not replicate the issue in any way, we can only assume that the issue is specific to their network.
How can we prove that their network/computers are causing the session swapping? Or, what configuration on our end could be causing this, when no other users experience this issue?
[edits/updates]
Responding to some direction provided by comment - our traffic is not large enough to send duplicate IDs. (the statistically probability is too low to see what we've seen the customer replicate ).
see also:
Zend Framework Session swapping issue
why is php generating the same session ids everytime in test environment (WAMP)?
Update:
We use FCGI, and apparrently mod_php is required to understand x_forwarded_for
What's wrong with this function call?

This may be a problem with improper session invalidation in the log out. please ensure that all the variables in the session are properly terminated or explicitly null terminate every object in the session and then invalidate the session.
The second reason may be the use of variables check for static variables in your code. improper use of static variables may also cause this intermittent issue.
Use logger to log session id mapped to the user ids that can narrow down your problem and help you understand what exactly happening.
Invalidating the existing session in login action and creating a new session and copying content to the new session will help a lot.

First, do not assume the customer is at fault. It may an issue on their side or yours. Do not make an assumption as to which before testing.
Regardless of who's fault it is, the burden is on you to fix or help fix it.
First, having one user become another is often the result of a Session ID problem. The security level you have set in Cake does not regenerate the Session ID for every request.
I would start by logging the $session->id() as a user both inside and outside your local network. Then compare to see if the session id is ever the same or ever an empty string. One fix for this is to generate a unique id for each user.
If the Session ID is unique for each instance, you may want to test it under load.
The point is to test first and make conclusions based upon findings, not speculation.

Related

Handling PHP Sessions With Multiple Front End's

We have 2x pfSense FW's in HA, behind that, 2x Zen Load Balancers in Master/Slave Cluster, behind those, 3x Front End web stack servers running NGinx, PHP-FPM, PHP-APC. In that same network segment, there are 2x MySQL DB Servers in Master/Slave replication.
PHP sessions on the front ends should be "cleaned up" after 1440 seconds:
session.gc_maxlifetime = 1440
.
Cookies are expired when the users browser closes:
session.cookie_lifetime = 0
Today, we were alerted by an end user that they logged in (PHP based login form on the website), but were authenticated as a completely different user. This is inconvenient to say the least.
The ZLB's are set to use Hash: Sticky Client. They should stick users to a single Front End (FE) for the duration of their session. The only reason I can think of this happening is that two of the FE's generated the same PHP Session ID, and then somehow the user was unlucky enough to be directed to that other FE by the LB's.
My questions are plentiful, but for now, I only have a few:
Could I perhaps set a different SESSID name per front end server? Would this stop the FE's generating session ID's that were the same? This would at least then result in the user getting logged out rather than logged in again as a different user!
We sync the site data using lsyncd and a whole bunch of inotifywatch processes, but we do not sync the /var/lib/php directories that contain the sessions. I deliberately didn't do this... I'm now thinking perhaps I should be syncing that. lsyncd will be able to duplicate session files across all 3 front ends within about 10seconds of the sessions being modified. Good idea as a temporary fix?
Lastly, I know full well that the client should be using the DB to store sessions. This would completely eradicate it being able to duplicate the session ID's. But right now, they are unwilling to prioritise that in the development time-line.
Ideas very much welcome as I'm struggling to see an easy way out, even as a temporary measure. I cant let another client get logged in as a different user. It's a massive no-no.
Thanks!!
Judging by your question you are somewhat confused by the problem - and its not clear exactly what problem you are trying to fix.
Today, we were alerted by an end user that they logged in (PHP based login form on the website), but were authenticated as a completely different user
There's potentially several things happening here.
Cookies are expired when the users browser closes:
Not so. Depending on how the browser is configured, most will retain session cookies across restarts. Since this is controlled at the client, its not something you can do much about.
PHP sessions on the front ends should be "cleaned up" after 1440 seconds
The magic word here is "after" - garbage collection is triggered on a random basis. Session files can persist for much longer and the default handler will happily retrieve and unserialize session data after the TTL has expired.
Do you control the application code? (if not, your post is off-topic here). If so, then its possible you have session fixation and hijack vulnerabilities in your code (but that's based on the description provided by the user - which is typically imprecise and misleading).
Its also possible that content is being cached somewhere in the stack inappropriately.
You didn't say if the site is running on HTTP, HTTPS or mixed, and if HTTPS is involved, where the SSL is terminated. These are key to understanding where the issue may have arisen.
Your next steps are to ensure that:
you have logout functionality in your code which destroys the session data and changes the session id
that you change the session id on authentication
That your session based scripts are returning appropriate caching information (including a Varies: Cookie header)
It is highly improbable that 2 systems would generate the same session id around the same time.
Really you want to get away from using sticky sessions. It's not hard.
You've got 2 layers at your front end that are adding no functional or performance value, and since you are using sticky sessions, effectively no capacity or resillience value!!! Whoever sold you this is laughing all the way to the bank.

php session sometimes not avaliable after passing to another domain

I run a website which can be reached through different domains: domainname.de, domainname.ch, domainname.at, domainname.es etc. ...
When my customer wants to pay we gets to a payment page which is of course https secured. Due to server limitations I am only allowed to have one SSL Certificate which I only put on one domain: domainname-secure.com.
Because I charge different prices I need to know which domain the user belongs to, so when redirecting to domainname-secure.com I save the domain (e.g. domainname.de) in the session variable $_SESSION['domain_default'] and pass the sessionID by adding session_id=[session_id] as a get parameter.
Then I check I take $_GET['session_id'] and run the follow command to have the session available on the domainname-secure.com:
session_id($_GET['session_id']);
session_start();
When I test it myself, it works perfectly fine but I make a log entry when somebody gets to domainname-secure.com and has not have set $_SESSION['domain_default'].
This occurs several times a day but I really have no clue why this does not work! I am testing it again and again from many different links but for me it works perfectly fine.
Can some of you imagine why it sometimes does not work?
Is it not "good" or insecure to pass the session ID to another domain and is it not always readable after redirecting?
I know it is hard for you to determain a mistake but I am searching for some know issues with session or maybe a tip how to do it in a better way?
Session are administered by PHP on a per domain basis meaning they don't mix domains intentionally.
If you would be using another session storage mechanism such as writing into the database or using memcached sessions you'd be able to overcome this limitation.
There are two approaches if you want to be able to access the session info when changing domains either:
Don't use PHP's $_SESSION, setup your own session management with memcached/redis/sql;
Or:
Use PHP's $_SESSION, but when transferring from one domain to another serialize the data in $_SESSION and put it somewhere accessible from both domains like sql;

Sessions without passing SID - is it reliable?

I'm working on a project that keeps some user information (non-sensitive) in a php session. As it is my first time working with sessions, I never bothered to pass any Session ID, but it still works - is that right ? I couldn't find any information about that.
I'm using some parts of the information in the $_SESSION variable to navigate and influence some of the sites' behaviour, and it sometimes is crucial for the page to interact with the user. Meaning without the correct informatin of the current session the navigation will be broken.
So, can I rely on the existence of Sessions ?
And can I rely on the server to automatically pick the right session without passing the SID ?
I'm working only on one server and I don't need the session to be restorable (meaning that when a user leaves the application the session can be destroyed).
If you couldn't find information about that, you probably skipped the most obvious reference: the official PHP manual. It's right there in the Introduction of the Sessions chapter:
Session support in PHP consists of a way to preserve certain data
across subsequent accesses. This enables you to build more customized
applications and increase the appeal of your web site.
A visitor accessing your web site is assigned a unique id, the
so-called session id. This is either stored in a cookie on the user
side or is propagated in the URL.
If your question is whether cookies are reliable for this purpose, in fact it's the de-facto standard nowadays. You'll hardly find PHP-powered sites that still transmit the session ID in the URL. The reason is that it's a problematic technique: it's too easy to give away your session ID. If you copy the URL and send a link to a friend or post it in a forum it's very easy that any stranger is able to access your private data, even inadvertently (you don't need a malicious guy here) if they visit the site before the session has expired and the site does not implement further verifications (which is the usual situation).
Yes you can rely to having the server to pick the correct sessions for you. I have in my 10 years of php coding not experienced a faulty session yet.
However, if you choose to pass the sessionid to the next page, be ware of the risks. Session hijacking is a very serious business if you have any sort of private data.

Editing / updating a user's PHP session without talking to MySQL constantly

I'm currently building a web application that uses a combination of OpenID and uname/pw authentication to authenticate users. Users are supplied a PHP session when they login successfully, and some information about their account (email address, usergroup, blah blah) is written to that session.
However, there may be a need for me or someone else as an administrator to update a users details (or to ban them immediately if they're very naughty). I'm hesitant to use a killsession tag like this (pseudocode):
session_start();
mysql_start(connection_stuff);
if (mysql_query("SELECT FROM users WHERE uid = '$_SESSION['uid']' AND KillSession = true")) { Kill session, force reauthentication };
However, doing it like this has two flaws:
We have to query the database every time someone loads a page to see if something changed
We gotta log the user out which just annoys him (or reload all of his session variables, which doesn't seem efficient)
Is there some way I can modify a user's session while they're still in it without having to resort to forcing them to login again? Some people seem to suggest in this stackoverflow thread using session_id to change to the user and then fiddle with their variables, but that seems like a shoehorn way of doing it. Thanks in advance!
I think instead of storing that stuff along with the session, it should be kept (and cached) separately. That way you avoid data duplication and the issue you're running into right now.
If an admin needs to kill the session, just DELETE it from the table.
Even though you express concerns about having to query the database on every page load, my guess is that it most likely does not affect performance noticeably. If the website is database driven in the first place, them it's just a matter of a single more query. I'd actually say that moving the entire session handling to the database (store session variables in a table) can make your system better in terms on flexibility. It will be much easier to deploy your system on multiple servers and do proper load balancing if that is someting you think will become necessary at son point. That is how the bigger CMS systems handle their sessions. My advise is, in other words, to stick with the extra query and actually consider to move session state to the database.

How to re-initialize a session in PHP?

I am attempting to integrate an existing payment platform into my webshop. After making a succesful transaction, the payment platform sends a request to an URL in my application with the transaction ID included in the query parameters.
However, I need to do some post-processing like sending an order confirmation, etc. In order to do this, I'd need access to the user's session, since a lot of order-related information is stored there. To do this, I include the session_id in the intial request XML and do the following after the transaction is complete:
$sessionId = 'foo'; // the sessionId is succesfully retrieved from the XML response
session_id($sessionId);
session_start();
The above code works fine, but $_SESSION is still empty. Am I overlooking something or this simply not possible?
EDIT:
Thanks for all the answers. The problem has not been solved yet. As said, the strange thing is that I can succesfully start a new session using the session_id that belongs to the user that placed the order. Any other ideas?
Not really what you ask for, but don't you need to persist the order into database before you send the customer to the payment-service? It's better to rely on persisted data in your post-processing of the order when you receive the confirmation of the payment.
Relying on sessions is not reliable since you will have no idea on how long this confirmation will take (usually it's instant, but in rare cases this will have a delay).
Also, in the event of your webserver restarting during this time span, will make you lose relevant data.
A third issue is if you have a load-balancing solution, with individual session-managment (very common) then you will have no guarantee that the payment-server and your client will reach the same webserver (since stickiness is usually source-ip based).
I will venture to guess that since domains are different from where the session is set to where you are trying to read it, php is playing it safe and not retrieving session data set by a different domain. It does so in an effort to preserve security in case somebody were to guess session ID and hijack the data.
Workaround for this, assuming the exchange happens on the same physical disk, is to temporary write order data to a serialized (and possibly encrypted depending on wether or not full credit card number is being tracked, which is a whole another story) file that once read by the receiving end is promptly removed.
In essence all that does is duplicates the functionality that you are trying to get out of sessions without annoying security side-effects.
Many thanks for all the replies.
Smazurov's answer got me thinking and made me overlook my PHP configuration once more.
PHP's default behaviour is not to encrypt the session-related data, which should make it possible to read out the session data after restarting an old session from another client. However, I use Suhosin to patch and prevent some security issues. Suhosin's default behaviour is to encrypt session data based on the User Agent, making it a lot harder to read out other people's sessions.
This was also the cause of my problems; disabling this behaviour has solved the issue.
Make sure you're closing the current session before you attempt to start the new one. So you should be doing:
$id = 'abc123';
session_write_close();
session_id($id);
session_start();
Dirty, but has worked for me:
Tell the payment gateway to use
http://yourdomain.com/callbackurl.php?PHPSESSID=SESSIONIDHERE
PHP uses that method of passing a session around itself if you set certain config vars (session.use_trans_sid), and it seems to work even if PHP has been told not to do that. Its certainly always worked for me.
Edit:
Your problem may be that you have session.auto_start set to true - so the session is starting automatically using whatever ID it generates, before your code runs.
How about do it in another PHP page, and you do a iframe include / redirect user to the second page?
I'm not sure the exact length of time between your transaction and your check; but it certainly seems that your session cookie has expired. Sessions expire usually after 45 minutes or so by default. This is to free up more uniqid's for php to use and prevent potential session hijacking.
I'm not sure if you have a custom session handler and whether it's stored in the database but guessing from your posts and comments on this page I would assume it is stored in server side cookies.
Now the solution to your problem, would be to bite the bullet and store the necessary data in the database and access it via the session id, even if it means creating another table to sit along side your orders table.
If however you are doing the action immediately then the other explanation is that either the user logged out or committed an action which destroyed their session (removing the server side cookie).
You will see these cookies in your servers /tmp folder, try have a look for your cookie, it should be named 'sess' + $session_id.

Categories