Deleting a Session automatically

Asked

Viewed 64 times

0

What I’m thinking of doing is "hang out" with a session_destroy() when the same user logs in somewhere else. There’s a way to do it ?

  • What did you mean by the same user logging in elsewhere?

  • @Wendelrodrigues in another browser for example

  • I think SESSION is linked to the browser. So, how would you kill one from another browser?

  • @DVD exactly would like to know about this, I would like to make my site more secure, by performing the following action of undoing the account if it is done elsewhere, I saw a similar question in the stack in English and was curious to implement it, but the explanations were somewhat difficult to understand

  • 1

    I don’t think there’s a way. What you would want to do is an access token on the server (via bank or file), and when the guy logs in to another, check if that token is active and kill him.

  • @DVD I’ll take a look at it, thank you

  • 1

    I think you will have to create a field in a table in the database and will have to work with cookie. Dai vc stores a hash in the cookie and stores it in the bank as well. Dai vc checks if the hash of the cookie and the bank are equal, if different you log out. For this every time you log in you have to generate a hash and store in the bank and cookie.

Show 2 more comments

2 answers

2


Your question was confused, but I will try to dismember some possibilities that I could understand with your question.

Status One/ Logged in User

  • The user is logged in and we currently have a Session for this user.

  • The user tried to log back into another browser the system will create another Session for this same user.

  • The system in this scenario is allowing the user to log in several times without restriction.

Situation two / Validating Session

  • The user is logged in and we currently have a Session for this user.

  • The user tried to log into another browser you made a function to check if the Session exists for this user and if you are logged in do not allow it to log in again.

Situation three / Destroy Session

  • The user is logged in and we currently have a Session for this user.

  • I want to close the Session in PHP we can use session_destroy(), this function will remove the entire Session of this user, all created variables will be destroyed or destroys all data associated with the current session, it does not delete any of the global variables associated with the current session, nor does it delete the session cookie, to use the session variables again, session_start() must be called.

Important note that it is not necessary to call session_destroy(), instead of destroying session data, clear the $_SESSION array and you are done.

Another important point is that if $_SESSION (or $HTTP_SESION_VARS for PHP 4.0.6 or lower) is used, use unset() to deregister the session variable, that is, unset($_SESSION['varname']);.

Care

Do not completely delete $_SESSION with unset($_SESSION) as this will disable logging of session variables through the $_SESSION super global.

You can also use session_unset(void) which releases all registered session variables.

Session in Archive or in Redis

There is the possibility to use Session in file that is already the default configuration currently, or in database like Redis, the behavior is transparent in both cases.

Managing Sesssions of Logged-in Users

In applications we need to manage environments and not allow users logged in multiple times, times of use of the system and prohibit access, need to check if the user is online or overthrow the system.

In this above mentioned scenario of access controls, you will be able to implement by reading the Session file either in file or in database.

I’ll show you how to do this by reading a file for example:

We have the session_decode function it decodes the serialized session data provided in $data and fills the super global $_SESSION with the result.

The code would look like this:

$pathFile = "/tmp/sess_vvk5ff5u1jjabatog0353pce4lc3mpc9";
$conteudo = file_get_contents($pathFile);
session_decode($conteudo);
print_r($_SESSION);

The disadvantage of this feature is that it puts everything into $_SESSION, and will not have a result that would like.

The other and safer way is to decode the file it has a default and using unserialize you will be able to create an array with all the variables that is in Session.

The method or function to decode the session file would be like this:

while ($offset < strlen($conteudo_session)) {
if (!strstr(substr($conteudo_session, $offset), "|")) {
  throw new Exception("invalido o seu conteudo " . substr($conteudo_session, $offset));
    }
    $pos = strpos($conteudo_session, "|", $offset);
    $num = $pos - $offset;
    $varname = substr($conteudo_session, $offset, $num);
    $offset += $num + 1;
    $data = unserialize(substr($conteudo_session, $offset));
    $return_data[$varname] = $data;
    $offset += strlen(serialize($data));

}

return $return_data;

This way you can know if user is online, can take down a user even you connected with another user, can make a script to check if the user can be logged in at that time and several other possibilities.

Well I hope to have helped, although it is not clear the question left some remarks about session_destroy that may be useful.

  • Thank you so much was exactly what I was looking for, when the user logs into my site I save the session_id and wanted to know if there was any way to deploy, with your explanation I managed to see how I can implement in the case was the "situation 3" that you wrote

  • Excellent, I imagined .... success.

1

You can make sessions predictable for yourself. This has a risk involved, but so you could destroy the previous session, knowing the current state.


In theory the idea my idea is simple, in the database you would have:

Id | Usuario | ... | Semente     | Estado
 1 | Alice   | ... | (Aleatório) | 1
 2 | Bob     | ... | (Aleatório) | 5 

It would also have a fixed key, preferably outside the code, as in an environment variable, but not in the same location/server of the database. But to facilitate understanding, something like:

$ChavePrivada = '...'; // Chave de 512 bits aleatória.

Then you’d have to do:

HMAC(HMAC( {ESTADO} , {SEMENTE} ), {CHAVE PRIVADA DA APLICAÇÃO})

So, for example, in Alice’s case:

HMAC(HMAC('0', 'ABCDE... Aleatório'), 'ASDFG... Aleatório'))

When Alice signs in again, you will:

HMAC(HMAC('1', 'ABCDE... Aleatório'), 'ASDFG... Aleatório'))
//...
HMAC(HMAC('2', 'ABCDE... Aleatório'), 'ASDFG... Aleatório'))
//...
HMAC(HMAC('3', 'ABCDE... Aleatório'), 'ASDFG... Aleatório'))

As you noticed, this will be sequential. This indicates that the session will always increment, the user’s last access is in our "Status", so to destroy the previous sessions just do Estado -1 and we will obtain the identifier of the previous session.

The second HMAC, with an application key, has the purpose of preventing anyone from predicting/recovering even if they have access to seed from other users.


In practice:

const ChavePrivada = '...'; // Define uma chave SEGURA de 512 bits.

function calcularSessao(string $semente, int $estado) : string {
    return hash_hmac('sha512',
             hash_hmac('sha512', $estado, $semente, true), 
           ChavePrivada);
}

function encerrarSessoesRecentes(string $semente, int $estado) {
   for($i = ($estado - 6); $i < $estado; $estado++){
      unlink('/tmp/sess_' . calcularSessao($semente, $i));
   }
}

Then to set user session:

mysqli_begin_transaction($link);
mysqli_autocommit($link, false);
mysqli_query($link, 'SELECT ..., Semente, Estado FROM ... WHERE ... FOR UPDATE');

//...
if($SenhaCorreta){

    encerrarSessoesRecentes($Semente, $Estado);

    mysqli_query($link, 'UPDATE ... SET Estado = Estado + 1 WHERE ...');
    if(mysqli_affected_rows($link) !== 1){
        mysqli_rollback($link);
        exit();
    }

    mysqli_commit($link);

    session_id(calcularSessao($Semente, $Estado));
    session_start();

    //...
}

I will improve and test the example later, and update the answer, but I believe I can understand.


/!\ Care:

This was not developed by any security professional. He may have other problems that I haven’t been able to identify, so there are other attacks that will be successful. If you discover any please comment.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.