A session is what identifies the user. The function of the session_start
uses a file located in the temporary folder, (/tmp/
) by the name of sess_*
. The *
is the same value as 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 complement, the sessions may NOT BE AVAILABLE, as long as you use the 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 not the case, besides there are other types of session uses, which do not use the standard PHP method
The function should only be called once, after user login?
Yes. When using the session_start()
such a function checks if there is a session_start()
previous and if there is it prevents it from existing and so can only be called once per "page".
Why to log in when logging in?
This is done to recognize 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) cookie
of PHPSESSID
with a value that should be unique, this allows the user to navigate on multiple pages and always be 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 own the cookie
of "ABC" which will be sent in all requests made on the same domain. On the server side we have a file, name sess_ABC
which contain the information of id
equal to 123
.
What relation to the global variable $_SESSION?
Toda. The array $_SESSION
will only exist when the session_start()
was previously called. The $_SESSION
will be used to read and record session information, rather, the $_SESSION
is used to read session file data.
Its use concerns the security of information?
That’s my favorite part! D
The sessions are safer than the cookie
, but they’re not so far away.
This is a delicate case. The most obvious of all would be if someone had access to the session files. If you use encryption in the database and use the usurer’s password to decrypt and store it in the session an attacker could have access to session data in the temporary folder.
But, that’s just a problem. The biggest problem of all is that 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:
document.cookie = "presence=?;";
document.cookie = "xs=?;";
document.cookie = "c_user=?;";
If the c_user
, xs
and the presence
is compatible with an open session you will, without logging in, have access to the user’s account. This indicates that if you go into someone’s home, and quickly open the F12 console and see the HEADER
of Request Headers
and send the Cookie
to your email, when you get home you can use the session that was opened, live reasonably close. I also made a posting of a Facebook issue and also mentioned the use of cookie
.
So the sessions are not safe. One thing you can do is get more and more user data, for example, check if the browser is the same, if the IP is the same, if the connection location is the same, even try to see if the screen resolution of the user 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 redo login, few websites do so. Another option is to have a timeout
low, ie quickly the session will expire, banks and similar services is common that.
However this is an inconvenience, if someone is with a 3G IT (you know how it is right?!) and the connection falls and comes back will have another IP and therefore... is, another login.
But that’s just the problem? nop, we still have a few:
- Generate sessions alopradamente, in search of an already open
- Predict the next session that will start, based on what you got.
- Self-xss, user injects a JS and sends sessions to "someone"
- 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.
Suppose you use 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.
The /dev/random
tends to be more predictable than the /dev/urandom
on some platforms, for example, in addition to session.hash_bits_per_character
which defines a greater or lesser variation of characters, if you like see this and that. ;)
The operating system collects entropia
(I don’t know if it’s the right term!) often, this is collected based on the use of hardware. For example, on a personal computer, the movement of the mouse, the use of Hds, the typing of the keyboard, packets sent and received on the internet (...) this information is the basis for randomness, that is to say you (or your software on the server) is only random thing in this world. This randomness also includes the name of the sessions. However, this is scarce and each algorithm will try to 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 it all in one cookie
.
To prevent "Self-xss", when the user unknowingly injects malicious code using most of the time the F12 CONSOLE. In common situation the JS has access to all cookies on the page, this allows the code to obtain the cookie
of the session and then send it to the external server, controlled by the "invader". To protect against this you must use the session.cookie_httponly=1
, this will prevent the sending of session cookies to another server and also use the 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 you send the link to someone they will have access to the session.
One of the things that can prevent (or hinder) packet interception is only to transmit the data on TLS/HTTPS and use the session.use_only_cookies=1
as an additional to prevent you from only getting the session at the URL. Also use subdomains for static content (estatico.site.com
, img.site.com
...) and thus cookies will only be sent to the site.com
but will not be used for subdomains. This will reduce the number of requests that have session identification. Logico, as stated earlier, limiting by IP among other factors will make it difficult for someone to use the session, even if they capture it.
Which would be to say, "summarize an existing session"?
You mean if there is one 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 continuing an already open session.
What its use and non-use causes in a user authentication system?
If you do not use the standard PHP session system you will not be able to identify the user, except if you use another mechanism to have sessions, such as:
- Cookies
- Websockets
You can save everything on Cookies
, of the kind Nome=Inkeliz
, but this is totally unsafe than using standard PHP sessions, 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 the id
for 2
the signature will not be equal, this is similar to the PGP signature, for comparison. The signature is generated based on the password sua_senha_legal
and there are other types of signatures (and also encryption) that can be done to use as a session. This is a session method, even if you don’t use the default session system.
The use of Websockets
is more complex. When the user logs in he will establish a persistent connection with the device and this connection is the ONLY thing that identifies the user, without use of cookies as identification. If the user gives F5 or goes to another page the connection will be interrupted and therefore have to login again. It theoretically is the most secure, because once the connection is created no other can be created with the same identification and if it falls the session ends.
If you do not use (or cannot use) any of the above solutions and even the common session method will be impossible to identify the user, one way or another you will need to use sessions.
Where Voce needs the
$_SESSION
you must use thestart_session()
before, in order to use– LocalHost
I know that sessions are saved in files. I imagine before giving a
start_session
, session is not loaded. Unable to use it$_SESSION
.– mau humor
Possible duplicate of Why using Sessions is not a good alternative to authentication?
– ShutUpMagda
I believe all your doubts are resolved by the answers to the question I have indicated ;)
– ShutUpMagda
The question is good, it does not deserve negative, but I believe it is broad. It could be divided into other questions, in my opinion.
– Wallace Maxters