When and why use session start? [closed]

closed . This question needs to be more objective and is not currently accepting answers.

want to improve this question? update the question to focus on just one problem when edit it .

Closed 4 years ago .

improve this question

Sure that, in short, session_start() "starts a new session or summarizes an existing session", but some questions:

→ the function should only be called once, after the user login?

→ Why start a session when performing login ?

→ What relation to the global variable $_SESSION?

→ does its use concern Information Security?

→ What Would it be like to say: "summarize an existing session"?

→ What does its use and non-use cause in a user authentication system?

If possible, I would like an example MVCE

Author: Comunidade, 2017-01-20

2 answers

A session is what identifies the user. The session_start function uses a file located in the temporary folder, (/tmp/) with the name of sess_*. The * is the same value as the cookie (PHPSESSID) sent by the user or the parameter contained in the url, the method of sending sessions per parameter is not recommended

just to supplement, Sessions may not be AQUIVE, as long as you use session_set_save_handler or create another session method, including to connect directly to the database, see in this example , but logically the default is file storage and therefore does not come to the case, in addition there are other types of session uses, which do not use the default PHP method


Should the function only be called once, after the user login?

Yes. When using session_start() such a function checks if there is a previous session_start() and if there is it prevents it from existing and so it can only be called only once per "page".


Why log in when logging in?

This is done so that it recognizes the user, without the session it becomes impossible to identify who logged in when the user goes to another page. When using the session_start() is created (or used) the cookie of PHPSESSID with a value that must be unique, this allows the user to navigate through several pages and is always recognized by the same cookie and therefore by the same session.

<?php
session_start();
// Ele aqui já vai enviar um cookie ao usuário, independente do que ocorrerá.
// Suponha que o cookie seja "ABC".

if($senhaCorreta === true){

   $_SESSION['id'] = 123;
   // Agora a sessão (o arquivo sess_ABC que está no /tmp/) possui um chave "ID" com "123".

}

the user at this time will have the cookie of "ABC" that will be sent on all requests made in the same domain. On the server side we have a file, named sess_ABC that contain the information of id equal to 123.


What relation to the global variable $_SESSION?

All. The array $_SESSION will only exist when the session_start() is previously called. The $_SESSION will be used to read and write the information of the the respective session, better said, the $_SESSION is used to read the data from the session file.


Does its use concern Information Security?

That's my favorite part! : D

Sessions are safer than cookie, but they're not that far away.

This is a delicate case. The most obvious of all would be if someone has access to the session files. If encryption is not used password to decrypt and store it in the session an attacker could have access to the session data in the temporary folder.

But, that's just a problem. The biggest problem of all is you use someone else's session.

Facebook for example uses the session c_user, xs and presence to perform some actions.

curl
-H "cookie: c_user=?; xs=?; presence=?" 
-H "user-agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36"
"https://www.facebook.com/"

Would be the same as this:

document.cookie = "presence=?;";
document.cookie = "xs=?;";
document.cookie = "c_user=?;";

If or c_user, xs and presence supports a session open you will, without logging in, have access to the user account. This indicates that if you go to someone's House, and quickly open the F12 console and see the HEADER of the Request Headers and send the Cookie to your email, when you get home you can use the session that was opened, if you live reasonably close. I also made a post of a Facebook issue and also mentioned the use of cookie.

So the sessions are not safe. one thing that can to do is to get more and more user data, for example, check if the browser is the same, if the IP is the same, if the location of the connection is the same, even try to see if the user's screen resolution is the same.

For example:

if($_SESSION['seguranca']['ip'] !== $_SERVER['REMOTE_ADDR']){
   session_destroy();
}

Whenever the user changes the IP it will be necessary to re-login, few websites do this. Another option is to have a low timeout, i.e. quickly the session will expire, banks and similar services is common it.

However this is an inconvenience, if someone is with a 3G it (you know how it is right?!) and the connection drop and return will own another IP and therefore... yeah, another login.

But that's just the problem? Nop, we still have some:

  1. generate Sessions allopradamente, in search of an already open
  2. predict the next session that will be started, based on what you got.
  3. Self-XSS, user injects a JS and sends the sessions for"someone"
  4. man-in-the-middle, packet interception

The session is a set of number and letters, you can try to generate to access a person's account and there is a more complex problem that would be predictability.

Imagine using the following cookie:

PHPSESSID = session01

What would be next? Yes, the possibility of being session02 is almost 100%, so just wait a few minutes, depending on the traffic of the website, to access the session of others.

This can also occur when using sessions with low randomness. Actually generating something random is extremely difficult, but some are worse than others.

/dev/random tends to be more predictable than /dev/urandom on some platforms, for example, in addition there is session.hash_bits_per_characterthat defines a greater or lesser variation of characters, if you want see thisand this. ;)

The operating system collects entropia (I don't know if that's the right term!) often this is collected based on hardware usage. For example, on a personal computer, the movement of the mouse, the use of the HDs, the typing of the keyboard, packets sent and received on the internet (...) this information is the basis for randomness, i.e. you (or your software on the server) are the only random thing in this world. This randomness also include the name of the sessions. However, this is scarce and every algorithm will try do something when there is no more entropy needed, or simply ignore generating predictable data, see here.

Sessions are not invulnerable, they also have (or may have) a lot of problems and you will have to do something to try to minimize that, but they are safer than keeping everything in one cookie.

To prevent "Self-XSS", when the user unknowingly injects malicious code, most often using the F12 CONSOLE. In situation common JS has access to all cookies on the page, This allows the code to get the cookie from the session and then send it to the external server, controlled by the "attacker". To protect against this you must use session.cookie_httponly=1, this will prevent sending session cookies to another server and also use session.cookie_secure=1. As additional also use the session.use_only_cookies=1, otherwise someone may have the session in the URL parameter, so when sending the link to someone this someone will have access to session.

One of the things that can prevent (or hinder) packet interception is to only transmit the data in TLS/HTTPS and use session.use_only_cookies=1 as an additional to prevent you from getting the session only at the URL. Also use subdomains for static content(estatico.site.com, img.site.com...) and thus cookies will only be sent to site.com but will not be used for subdomains. This will reduce the number of requests that the session ID has. logic, as stated earlier, limiting by IP among other factors will make it difficult for someone to use the session, even if it captures it.


What Would it be like to say, "summarize an existing session"?

Means that if there is a cookie of PHPSESSID sent by the client PHP will use the session that was previously opened.

If you do:

curl 
-H "Cookie: PHPSESSID=ABC" 
meusite.com/perfil.php

The meusite will use the PHPSESSID of ABC, So basically you're giving continuity in an already open session.

What does its use and non-use cause in a user authentication system?

If you do not use the default PHP Session system you will not have the ability to identify the user, except if you use another mechanism to have sessions, such as:

  1. Cookies
  2. Websockets

You can save everything in Cookies, of type Nome=Inkeliz, but this is totally unsafe than using sessions PHP standards, because the user has full control of the values that are saved. This is good if you have a website that does not have an authentication system, only. But cookies can be improved, an alternative is to encrypt or sign a cookie, for example using JWT :

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjEiLCJub21lIjoiSW5rZWxpeiJ9.Z3mq41cyKyQzO/aS+6zmHElygGabWCsa3U44Yfpu5RU=

This was generated using:

$headers = [
    "alg" => "HS256",
    "typ" => "JWT"
];


$payload = [
    "id" => '1',
    "nome" => 'Inkeliz'
];

$chave = 'sua_senha_legal';

$conteudo = base64_encode(json_encode($headers)) . '.' . base64_encode(json_encode($payload));

$assinatura = base64_encode(hash_hmac('SHA256', $conteudo, $chave, true));

$token = $conteudo . '.' . $assinatura;

This means that if the user changes id to 2 the signature will not be equal, this is similar to the PGP signature, for comparison. The signature is generated based on the sua_senha_legal password and there are other types of signatures (and also encryptions) that can be made to use as a session. This is a session method, even if you do not use the default session system.

The use of Websockets is more complex. When the user logs in it will establish a persistent connection with the device and this connection is the only thing that identifies the user, without the use of cookies as identification. If the user gives F5 or go to another page the connection will be interrupted and therefore you will have to log in again. It is theoretically the safest, because once the connection is created no other can be created with the same ID and if dropped the session ends.

If you do not use (or cannot use) any of the above solutions and not even the common session method it will be impossible to identify the user, one way or another you will have to use Sessions.

 20
Author: Inkeliz, 2017-05-23 12:37:23

→ should the function only be called once, after user login?

In this context, the session has nothing to do with the user logging in or not.

A server session starts when a user enters the site. At this time, the server reserves a space in memory, where it stores session state information, so that even when switching pages, session information is kept.

The session_start () function is used so that your code has access to the session variable $_SESSION, so it only needs to be called once.

Is like telling the server that it wants access to this user's session.

→ why start a session ( https://pt.stackoverflow.com/tags/session/info ) when logging in?

When a user logs in, the session they start occurs at the application level and is controlled by the application. It has nothing to do with the server session, which was started when he entered the site.

However, the application will use the server session to save login information, thus the system remembers that the user has logged in.

→ What relation to the global variable $_SESSION?

$_SESSION is an array that stores session information. session_start () allows access to your content.

Note that the session will exist anyway.

→ does its use concern Information Security?

Each user initiates a private session when entering the site. One user does not have access to another's information. However, the application can have access to the information of all sessions.

For example, the 'WHO's online' feature that some applications have will use session variables to access information such as qtde. of users connected on the site, IP, etc.

→ What Would it be like to say: "summarize an existing session"?

A server session has a lifecycle. Starts when a new visitor enters the site and lasts a while, after he has left the site.

However, if it returns to the site, within the lifetime of the session, it restarts (resumes).

→ What does its use and non-use cause in a user authentication system?

Many systems use the session to control authentication. Otherwise, you would have to pass a variable from page to Page and that would be quite risky.

More information in http://php.net/manual/pt_BR/reserved.variables.server.php

 -3
Author: Rene Freak, 2017-04-13 12:59:44