Cookie replay after logout php CodeIgniter - php

I have an application where the login and logout works correctly. Once the user logs out, and tries to access a page he needs authentication for, he is redirected to the login screen.
Where my problem lies is. If while I am logged in, if I copy the cookie values and save them on a file. After logout, I alter the cookie and add the same values, I get logged back in into the application as the same user.
On logout I have written a function that loops over all the cookies and deletes them.
My understanding is that cookies are both on the client and also on the server side. So if the cookies are getting deleted, they are getting deleted on both the sides and that the server would not recognize them after they have been cleared, even if the browser sends them back again(apparently that is not the case, i think).
The reason why I am doing this is because this is one of the points raised by our security auditor, and I need to get a way to fix this hole. (At this point doing https is not feasible)
I'd be happy if someone can give me pointers on how I can clear out the cookies on the server side as well, so, when the next time someone hits the server with the same cookie, it does not accept it as a valid cookie.
Edit:
I am using codeigniter sessions and tank_auth as the authentication library. At logout, the library itself calls
$this->ci->session->sess_destroy();
to be extra sure, I tried the following after a few attempts :
session_start();
session_unset();
session_destroy();
session_write_close();
setcookie(session_name(),'',0,'/');
session_regenerate_id(true);
My regular logout works, and if I try to access the page directly it does not open.
But if while I am logged in, I take my cookie, save it somewhere -- log-out successfully and replace the cookie with my older one, I get right back into the session.
Is there a way to stop this behavior -- Where the server side will not entertain a session after it has been destroyed. I also made sure that my server and php are on the same timezone (setting it with date_default_timezone_set).

Cookies are not stored on the server at all. Those are stored in the browser and then sent to the server in the request headers. You can easily find software and plugins for browsers that allow you to create/edit/delete cookies. For that reason you should never store sensitive information in cookies. Essentially what you want to do is store the user data in a session and then store the session name in a cookie. Usually this is done automatically in php when you use the function session_start().
If you are using Codeigniter, the php session functions are wrapped in a CI session library that is auto loaded on each page load. So instead of storing data in $_COOKIE you will want to get/set your data via the userdata method in the session library:
//in your controller
//save session data
$userdata = array(
"isLoggedIn"=>true,
"username"=>$_POST['username']
);
$this->session->set_userdata($userdata);
//get session data later
$isLoggedIn = $this->session->userdata("isLoggedIn");
if(!$isLoggedIn){
//if the user is not logged in, destroy the session and send to the login screen
$this->session->sess_destroy();
redirect("/");
}
Note that the code above is not tested and is only supposed to give you an idea on where to go. If the session methods aren't working for you, you may need to load the library in manually:
//in the __construct method of your controller:
$this->load->library("session");
You can find more information here:
http://ellislab.com/codeigniter/user-guide/libraries/sessions.html
and here:
http://www.php.net/manual/en/book.session.php

Thanks for you answers guys.
This is what I figured, later. I am not sure what was causing this but the sessions were not getting invalidated after trying everything. I moved the sessions on codeigniter to the database. Then the logouts started working correctly, where after logout if the 'stolen'/'saved' cookie was put in the browser again it would Not log the user back in.
So, thats what solved it.

Related

Stay logged in through a PHP discord oauth2 (cookie?)

I am working on a site that involves logging in through discord, which uses oauth2. I believe the login is controlled by the phpsessid cookie, from what i can tell. My problem is this cookie resets when the browser is closed, meaning whenever the browser closes, the user has to log back in.
I was wondering if there was a way to keep the session running even after closing the browser, or maybe a different method to keep the user logged in? I found the PHP function session_set_cookie_params() that could be useful, but I'm not sure how I can use this in my situation.
In order to store data even if you close the browser, you need to use cookies. With PHP, you need to use the setcookie() method.
Default example:
<?php
setcookie('yourCookieName', "yourCookieValue");
?>
Another example:
<?php
setcookie('yourCookieName', "yourCookieValue", time() + 365*24*3600, '/', '.yourdomain.com');
?>
I have added some parameters as time and a way to keep the cookie for all the website subdomains.
And then, if you can get the cookie with $_COOKIE['yourCookieName'].
You can try to use javascript to acces that cookie and then save it as a new cookie on your website,and then load it when the user connects.Look on w3school javascript cookies

PHP how to manage multiple session in same browser using cookies?

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 );

php PHPSESSID exists but session destroyed

I am trying to login an user for 2 weeks if user login with remember me check then i have set some variables in session and cookie set for 2 weeks. It is set correctly i have printed it and got the value session_cookie_lifetime = 1209600 and session_gc_maxlifetime = 1209600. I also print session and got correct value in $_SESSION.
After login in my site when i shut down my computer and reopen my site it seems that it is working (it is keeping me as login user). But when i shut down my computer and next day when i open my browser it is not working and it is showing that i am not login on my site. I have printed $_COOKIE and $_session . It shows that in cookie there is :
[PHPSESSID] => svikos35bgclmebk2cqraiddt2
But session is empty.
I got this form modx stuff:
MODx automatically starts and ends sessions with each request made to the site. You can simply save values into the $_SESSION array and they will be saved in between requests so you can use them on subsequent pages (so long as you have the same user session). Not really any magic to it other than don’t call the session functions yourself to start, end, or otherwise manipulate the session configuration—that can all be done via settings in MODx.
I am using modx revo. It is a bit descriptive question. let me know you need something else.
Anything that may help me (blog link,any settings, any suggestion ) will be highly appreciated.
Thanks in advance
This only happens after a day?
Could tmpwatch be deleting session files from the server?
session_cookie_lifetime and session_gc_maxlifetime doesn't garantee you, that session will be saved for a week. GC kill unused sessions. Check PHP documentation about this parameters and you see, that you can't be sure, that your session will be on the server and you don't be sure, that your sesssion will be destroed after this time. GC is async.
You need to recreate $_SESSION after login (and autologin) if it doesn't exists.
Check this article (in russian, try google translate:
PHP GC: unexpected behavior
The basic idea behind SESSION is that, When you create or call session_start() method your server generate a session id and store it on server memory. Also the server create a cookie on your client machine that cookie contains an id that is related to your server side session id. When you call session_destroy() method server delete that id on server side but the client side cookie doesn't. That is why your session id still shown. You can also check by cache and cookie clearing. When you clear cookie your session will destroyed.

Destroy session in cakephp when you leave the page?

How and where can I use
$this->Session->destroy()
For the session to be destroyed whenever the page is closed?
And how can I keep the session open until the page is closed, independent of time?
I need this because when the User enters the page, some specific variables are unset in the session, and when he comes out, I need this session to be destroyed.
I'm not able to do this using cakephp.
Sessions are stored on the server, so if the browser is closed or the user goes to a different page, there is no obligation that it informs the server about this action.
Session are stored for a certain time in the server, and after some time of inactivity or if you properly logout, it will be destroyed there automatically.
Check Sessions info in CakePHP cookbook for more info regardin Sessions
You can try to use $(window).unload(function(){alert('Closing browser')});
And do ajax call to server to destroy session , but this may not work on some browsers and already deprecated function in jQuery 1.8 for more info
http://api.jquery.com/unload/
if you have used Auth cakephp 3.0 components then no need to do anything all session and cookie management carried by session core components.
$this->Session->destroy()
it will destroy all cookie and session data but if you want to destroy particular session then you can do by this code
$this->Session->destroy('$val');
here,$val represents particular session to destroy

Showing cached data only to non-members with COOKIE check? (PHP)

Caching the HTML output of non-important pages (like blog posts) really helps to speed up a site by skipping the loading of the entire system (and rendering time) and just spiting out a pre-made copy of the page. This would be one way you can keep large waves of users to your site index or whatever from eating resources.
However, one of the problems of caching pages is that in order to check wither or not you can show the page - you have to load the entire system (and the user lib) to check if the user is logged in. (Wordpress, CodeIgniter, Drupal, etc..)
Then you can determine if it is safe to show a cached version of the page or if you should re-render the page for the logged in user. And vis-versa; a page rendered for a logged-in user shouldn't be shown to a guest!
Anyway, I finally had an idea that I could just use if(empty($_COOKIE)) to test for a user session since I never use the URL to transfer the session ID. Then I remembered that since the session library is loaded on each page that probably won't work since it will create a cookie when session_start() is called.
Does anyone have any ideas about how to test for a user session without loading your database connection -> for your session library -> for your user library?
I just recently learned this, so I hope I have everything straight.
In order to access saved session variables, you have to have a session started. In the project I'm working on, the 'user login' and 'create new user' pages all start out with session_start(). I also tried testing if the cookie was set, which didn't work too well. If the user is logged in or not, it doesn't matter, because there will be a cookie for both guests and logged in users. If you have a session then you'll have a cookie (provided that's how you have php setup, which sounds like you do). So instead of testing the cookie, I test to see if a session variable is set. This variable will only be set once the user successfully logs in.
if (loginSuccess()) { $_SESSION['login']="true"; }
After this, I can now test to see if that session variable is set, and display content appropriately. My user can navigate away from those pages, come back, and it will still remember that session variable.
I'm sure there are better, secure ways of doing this though.
You could set some kind of session variable once the user logs in, i.e.
//user has successfully logged in
$_SESSION['logged_in'] = true;
Then, somewhere very early in your page load (before any libraries have loaded) you could do:
#session_start();
if(!(isset($_SESSION['logged_in']) && $_SESSION['logged_in'] === true))
{
//not a logged in user, show the cache!
load_cache(); //or however this works
exit();
}
On a logout, you'd either do session_destroy() or $_SESSION['logged_in'] = false;
Yes, as I stated the current method involves loading the system, database (assuming your sessions use the database), and finally starting the session which is a waste if you are only going to show cached content.
Perhaps you could set a cookie called "logged_out" (or "logged_in") in addition to the session cookie. Then you could test for "logged_out" cookie on each page load without the need to load the session and database?
Actually, since you would have bots and other non-cookie user agents you it would be better to create a "logged_in" cookie on login and then everywhere else check for a false/non-existent cookie as a sign for a guest.

Categories