CodeIgniter icon indicating copy to clipboard operation
CodeIgniter copied to clipboard

Rapid requests during session updates trigger unexpected session destruction

Open bitbucket-import opened this issue 15 years ago • 45 comments

=== Issue === When using the sessions library and the following conditions exist:

  • $config['sess_use_database'] = true;
  • The period specified in $config['sess_time_to_update'] has expired

It is possible to inadvertently trigger destruction of the session by performing two requests at the same time. An example of a scenario that easily triggers this error is a page which initiates two or more AJAX requests at the same time.

=== Expected Behavior === The CodeIgniter sessions library should not inadvertantly destroy sessions.

=== Cause of Issue === This is what I believe to be occurring.

Two requests are made at the same time, causing them to submit the same cookie data.

When the server receives the request, the session library looks for the session matching the ID submitted on the cookie. (Session.php:192)

The first request finds the session record and updates it since sess_time_to_update has expired. (Session.php:377)

The second request still has the old session id, and fails to find the newly updated database record. This then triggers a sess_destroy. (Session.php:212)

=== To Replicate ===

In config.php: {{{ // Reduce the amount of time we have to wait to see the bug to 5 seconds. $config['sess_time_to_update'] = 5; }}}

Create controller session_error_demo.php: {{{

session->set_userdata('session_alive', 'Hi world!'); echo 'Session initialized.'; } ``` function test() { if ($this->session->userdata('session_alive')) { echo 'Session is alive.'; } else { echo 'Session is dead.'; } } function reset() { $this->session->sess_destroy(); echo 'Session reset.'; } ``` } ?>

}}}

Perform the following tasks:

Call reset() to ensure we start on a clean slate.

Call initialize() to seed a session value.

Wait 5 seconds so that the session will be forced to update on next request.

Call test() twice in rapid succession, so that both requests will be sent before either is fully processed. I used jQuery & Firebug to submit these requests using $.get().

View the responses. The first will report that the session is alive, but the second and all subsequent requests will report that it is dead.

=== Versions Affected === This issue exists back in my version on 1.7.2. I haven't verified that this still exists in 2.0.2, but it appears that the buggy code remains intact.

bitbucket-import avatar Aug 19 '11 14:08 bitbucket-import

I've a similar Issue, my app keep alive making ajax requent periodically, when I open another tab from my web app sometimes I lost my session

sergio-ascanio avatar Aug 22 '11 19:08 sergio-ascanio

I have had this issue too, very annoying and hard to explain to clients. It even happens when sess_time_to_update is set to PHP_MAX_INT (I am not waiting that long either for it to happen)

ghost avatar Sep 08 '11 15:09 ghost

I have a workaround for this based on inspiration from a CI Forum discussion; you can basically disable the session updates when AJAX calls are made. This code should go in /application/libraries/MY_Session.php :

<?php
class MY_Session extends CI_Session {

    /**
     * Update an existing session
     *
     * @access    public
     * @return    void
    */
    function sess_update() {
       // skip the session update if this is an AJAX call! This is a bug in CI; see:
       // https://github.com/EllisLab/CodeIgniter/issues/154
       // http://codeigniter.com/forums/viewthread/102456/P15
       if ( !($this->CI->input->is_ajax_request()) ) {
           parent::sess_update();
       }
    }
}

dordal avatar Oct 25 '11 19:10 dordal

thanks for share your fix dordal I will try it

sergio-ascanio avatar Oct 26 '11 17:10 sergio-ascanio

Am still getting the same problem with 2.0.3

ghost avatar Oct 30 '11 11:10 ghost

What if the web app is mostly made with JS and ajax? No session will ever be updated and the user will just timeout when the expiration has arrived?

samxli avatar Nov 02 '11 15:11 samxli

I use the following code to keep the session alive:

    function sess_update() {
            // skip the session update if this is an AJAX call! This is a bug in CI; see:
            // https://github.com/EllisLab/CodeIgniter/issues/154
            // http://codeigniter.com/forums/viewthread/102456/P15
            if ( !(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') || ( stripos($_SERVER['REQUEST_URI'], 'live/request') != 0 ) ) { 
                    parent::sess_update();
            }
    }

I only allow the request made ​​by the controller that updates the app ( http://localhost/app/live/request ), every 5 minutes the session is updated by an ajax request, is an ugly hack but works fine so far.

sergio-ascanio avatar Nov 03 '11 03:11 sergio-ascanio

Issue is still present in CI >= 2.0, the solution proposed by @dordal, while hacky, does the trick.

yorickpeterse avatar Dec 14 '11 16:12 yorickpeterse

As the original reporter, it should be noted that this is still a fundamental flaw with the way session updates work.

I personally abandoned using database sessions altogether. @dordal has a good workaround, but even with that the bug can be triggered via means other than AJAX requests.

kochb avatar Dec 14 '11 16:12 kochb

@kochb how are you storing your sessions now?

samxli avatar Dec 14 '11 17:12 samxli

I actually don't even use CodeIgniter anymore and switched to another framework. I got fed up with CodeIgniter since there were too many issues getting left unaddressed, and it was harming quality and productivity.

In terms of actual solutions:

As a temporary fix, I turned off database sessions. Note that it will cause the session data to be stored in a cookie, so you need to determine whether that is acceptable to you. (See Saving Session Data to a Database, http://codeigniter.com/user_guide/libraries/sessions.html).

$config['sess_use_database'] = false;

There's also some drop in replacement libraries out there too that I used at various points that may be worth investigating. Haven't used them in a while, so I don't know what their status is.

Otherwise: If neither of those works, @dordal has the best workaround I've seen. You will still be vulnerable to lost sessions, but it will be much less of a problem.

kochb avatar Dec 14 '11 18:12 kochb

What is the best replacement library? The site is complete so i'd ideally just like a drop in replacement with the same functions for flashdata and retrieving data as the codeigniter library. I too have run into this issue so currently database sessions are turned off...

ciribob avatar Dec 14 '11 21:12 ciribob

@kochb are you using database sessions with that new framework? If so, care to share what framework you are now using?

samxli avatar Dec 15 '11 05:12 samxli

I've been using this solution in a production system since 2009 (1.7.2 and 2.0.3 since Sep 2011) without any problems.

For those that have noticed, the thread is from Aug 2010, but this was not first posted there. This approach introduced a config parameter to control the generation of a new session_id.

I can't imagine that the best solution is not to update sessions from ajax requests. What about sites built on ExtJS?

Dentxinho avatar Dec 15 '11 10:12 Dentxinho

Don't switch your framework over the session library. I'm using CakePHP right now; I liked the amount of workload it takes off you by automatically creating the CRUD for your database, its well organized and thorough class structure, and the fast response time when you do report issues. I've mostly trusted Cake's native session library to work and it hasn't given me problems yet.

If you're sticking with CodeIgniter and security is an issue, use the workaround @dordal gave or find a good drop in replacement. I was simply noting that the workaround does not address the fundamental problem; nonetheless the likelihood of triggering that problem drops drastically.

kochb avatar Dec 15 '11 14:12 kochb

The PyroCMS gang are stuck on this too:

https://github.com/pyrocms/pyrocms/issues/1049

This is a CI bug thats been around for ages that I know nothing about but really want to see nailed.

philsturgeon avatar Jan 18 '12 19:01 philsturgeon

@philsturgeon did you saw my post?

Dentxinho avatar Jan 18 '12 20:01 Dentxinho

So not updating the session id on AJAX is a known fix for this but is it secure?

If you leave something on a page it can keep making ajax calls forever and not expire, until somebody tries loading the next page.

philsturgeon avatar Jan 23 '12 01:01 philsturgeon

It would lower the security level a bit, but that's the problem with cookies - the more secure your implementation is, the more you're limiting your own options. Let's see what are the other "standard" techniques for securing cookies that we can use:

  • using HTTPS-only cookies; definately raises the bar, but it's not always possible
  • IP address and user agent string matching; should be enough in 99 out of 100 cases, but are optional and not convenient in some cases
  • using "httponly" cookies; only available with PHP >= 5.2 and can't be used with AJAX requests (that kind of the whole point)
  • enforcing use of non-empty cookie_domain and cookie_path settings; would help increase the possibility of a cookie being stolen, but again - not always really usable

... pretty much nothing that we can always rely on.

What we can do is make session ID regeneration during AJAX requests optional (and enabled by default), so developers that have this issue can disabled it. Probably should've thought of that earlier - I'll update the pull request, but I want to know your thoughts on another idea first ...

Encapsulate "tickets" inside our cookies, ala Kerberos. In order to do that, we need to have an randomly generated token inside the cookie and a list of such tokens + timestamps stored in the database (or whatever server-side storage we are using). Each of those tokens must only be valid for a specified range of time after sess_time_to_update. Here's how it works:

  • each time that the session ID is re-generated, a new token is generated as well and put inside the encrypted cookie data; any old token is invalidated
  • when sess_time_to_update expires, if we have an AJAX request - we still only update last_activity and don't change the session ID, but:
    • we check if the token inside the cookie is inside our server-side tokens list
    • delete any server-side tokens that have expired, although we might leave that to the garbage collector

If the token is found in our list and is inside the allowed timespan - generate a new one, insert it into our list (without deleting the old one) and send it back in the cookie. And here's why we don't delete the old token:

  • new AJAX requests will send the newly generated one back to us
  • any AJAX request received that was initialized by the browser before or while we were creating the new token will still send us the old one and is again checked against it's timestamp for validity

... and of course - if we receive an invalid token, we'll destroy the session.

This might as well be used with non-AJAX requests, but it might be a little too much.

What do you think?

narfbg avatar Jan 23 '12 08:01 narfbg

@narfbg I've patched the session to never regenerate the session ID (we also only use HTTPS so cookie stealing should be harder?) but this is a much better solution! Our site is AJAX heavy so the session disappearing bug happened frequently.

ciribob avatar Jan 24 '12 10:01 ciribob