How to safely implement the Remember Me button in PHP (persistent login)

First of all, I'm still learning PHP and I'm trying to create a CMS (disclaimer: for my own use only).

I am still testing some things and I have successfully created an admin login system.

So, right now this is how it works:

  • The user logs in after checking and disinfecting the inputs, I check if the user exists, and I use PHP password_verifyto compare the password with the hashed one stored in the database.

  • If the login is successful, I redirect the administrator to dashboard.phpand create a session variable with the name adminId, and I save the user ID in this variable.

Here is my first question:

Can an attacker change the value $_SESSION['adminId']? For example, change the value from 1 to 12 and therefore log in as a different administrator?

In any case, I read this article , which presents several exploits that an attacker can use.

So, if I am not mistaken, should I use cookies to permanently log in?

So, first of all, to never store the user ID in a cookie and use it to verify login, because an attacker can easily change this right?

Ok, so I can create an arbitrary token (with random_bytes and then converted to hex) and map it to the user ID in the table loginsin the database.

, , :

token: 2413e99262bfa13d5bf349b7f4c665ae2e79e357,
userId: 2

, , , userId. , . , , , - cookie : 2413e99262bfa13d5bf349b7f4c665ae2e79e357. , userId: 2 ?

userId: 10, , , .

, : . , : . , , , :

" " - - ( ) , ( " " ).

: , token cookie, selector:validator.

selector - , , , . ( id, .)

enter image description here

validator ; SHA-256 validator, ( selector) cookie . , - auth_tokens , .

:

  • selector validator.
  • auth_tokens . , .
  • validator, cookie SHA-256.
  • - SHA-256, , , hash_equals().
  • 4 , .

, , :

1) selector validator?
2) ?

, , , .

, , scracth, !

+4
1

$_SESSION['adminId']? , 1 12 , , ?

. . , .

cookie ?

, .

, , - , ?

, , .

1) selector validator?

(, openssl_random_pseudo_bytes). selector .

2) ?

.

-, , , cookie . validator . cookie unhashed. .

-, , , . , cookie , , -, .

, , " " . , , .

+3

Source: https://habr.com/ru/post/1685344/


All Articles