What is a relatively safe way to use a cookie to sign in?

I was wondering what is the safest way to log in to cookies? If you just store the pass (encrypted with salt) and the username in the cookie and confirm it against the user table, a potential attacker could steal the cookie and log in. Usually people don’t check "last time online."

So is there a better way to ā€œremember me cookiesā€? IP is not a good option, is it? (Some machines change IP all the time).

+8
php cookies autologin
source share
3 answers

I think I found a smart solution!

Advantages of this (complicated?) Script:

  • When the user successfully logs in with Remember me checked, a cookie login is issued in addition to the standard cookie session management. [2]
  • The login cookie contains the username, batch ID, and token. Series and tokens are irrefutable random numbers from a fairly large space. All three are stored together in a database table.
  • When a non-registered user visits the site and presents a cookie for login, the username, series and token are viewed in the database.
  • If a triplet is present, the user is considered authenticated. The token used is deleted from the database. a new token is generated, stored in the database with the username and identifier of the same series, and a new cookie containing all three is issued to the user.
  • If the username and series are present, but the token does not match, theft is assumed. The user receives a strictly worded warning and all user remembered sessions are deleted.
  • If the username and series are not present, the login cookie is ignored.

I created a table in the database with the following information:

session | token | username | expire 

Remember that a cookie will have this setting:

  $value = "$session|$token|$userhash"; //Total length = 106 
  • Session will be a string of 40 (sha1) characters.
  • Token will be a string of 32 (md5) characters.
  • Userhash in the cookie will be a string of 32 (md5 username) characters.
  • Username in the database will be the normal username.
  • Expire will now be + 60 days.

script:

 if(isset($_SESSION['check']) || $_SESSION['check']){ //User is logged in }else if(isset($_COOKIE['remember']) && strlen($_COOKIE['remember'])==106){ //THERE is a cookie, which is the right length 40session+32token+32user+2'|' //Now lets go check it... conncectdb(); //Sets connection //How do I protect this script form harmful user input? $plode = explode('|',$_COOKIE['remember']); $session = mysql_real_escape_string($plode[0]); $token = mysql_real_escape_string($plode[1]); $userhash = mysql_real_escape_string($plode[2]); $result = mysql_query(" SELECT user FROM tokens WHERE session = '$session' AND token = '$token' AND md5(user) = '$userhash';") if(mysql_num_rows($result)==1){ //COOKIE is completely valid! //Make a new cookie with the same session and another token. $newusername = mysql_result($result,0,0); $newsession = $session; $newtoken = md5(uniqid(rand(), true)); $newuserhash = md5($username); $value = "$newsession|$newtoken|$newuserhash"; $expire = time()+4184000; setcookie('remember', $value, $expire, '/', 'www.example.com', isset($_SERVER["HTTPS"]), true); mysql_query(" UPDATE tokens SET token='$newtoken', expire='$expire' WHERE session = '$session' AND token = '$token' AND md5(user)='$userhash';"); //Set-up the whole session (with user details from database) etc... } else if(mysql_num_rows(mysql_query("SELECT user FROM tokens WHERE session = '$session' AND md5(user) = '$userhash';"))==1)){ //TOKEN is different, session is valid //This user is probably under attack //Put up a warning, and let the user re-validate (login) //Remove the whole session (also the other sessions from this user?) } else { //Cookie expired in database? Unlikely... //Invalid in what way? } } else { //No cookie, rest of the script } 

Benefits of the script:

  • Several logins. You can create new sessions for each computer on which you are located.
  • The cookie and database will remain clean. Active users update cookies every login.
  • Checking the session at the beginning ensures that the database will not receive useless queries.
  • If an attacker steals a cookie, he receives a new token, but not a new session. Therefore, when real visitors visit a website with an old (invalid) but with a valid user session, the combination the user receives a warning of a potential theft. After re-checking by entering a new session and the session, the tricks of the attacker are invalid. re-validation ensures the victim is indeed the victim, not the cracker.

Link: http://jaspan.com/improved_persistent_login_cookie_best_practice

+19
source share

The Remember Me feature is always an added security risk.

Because, like in a session, you have only one identifier, which is sufficient not only to identify the user (who is this?), But also to authenticate this user (is he / she really?) Without actual authentication.

But in contrast to a session that has (or should have) just a short lifespan (basically less than an hour), and the identifier (or should be) changed periodically (based on time and as necessary due to the authenticity / authority of the state change), the identifier "remember me" is valid for several days, if not even months or years! And this long duration creates an additional security risk.

So, before asking how to implement this ā€œremember meā€ feature, you should ask yourself if you really need an extra security risk. It mainly depends on the assets that your application has, and what authentication is for, and if you want to risk the impersonations / theft of personal data that the "remember me" function represents.

If so, make sure you provide basic security using HTTPS and set the HTTPOnly flag and the safe flag in your cookies . Then you can do the following to create such a ā€œremember meā€ function:

  • Authentication Request
    If the user authenticated via HTTPS and set the ā€œremember meā€ option, generate a random storage token, save it on the server side in the ā€œremember meā€ database and set a cookie for me with a saved flag with this value. Then start a new session and set the Remember Me flag.

  • Any other requests

    • If there is no current session, redirect to the Remember Me page via HTTPS, which checks if I have a cookie. If there is a token that I remember, it is valid, invalid, generates a new one, stores it in the ā€œremember meā€ database, sets a cookie with this new token and creates a new session with the ā€œremember meā€ checkbox selected. Otherwise, redirect to the login page.
    • If the current session is invalid (be sure to use the invalid session ), redirect to the Remember Me page via HTTPS if the Remember Me flag is set; otherwise redirect to the login page.

At the same time, authentication is provided through HTTPS, both the initial authentication and the ā€œremember meā€ authentication. And the user is authentic only during the current session; if it expires, the user must re-authenticate either with the remember me token or with his credentials. And since you remember that tokens are stored in the database, the user can cancel any existing commemorative token.

+6
source share

Most popular ways:

  • Many scripts use some kind of session tracking. When a user first visits a website, he generates a unique random identifier for the user and stores the session information on the server and the identifier in a cookie. The server then identifies the user using a unique identifier (called a session identifier). Session ID information can only be seen by the server. PHP uses this by default,

  • Some store user data in the cookie itself, but with an HMAC signature, using a secret string as a key. The script drops the cookie if the signature does not match. Therefore, the server does not have to store session data on the server. The user sees that he is viewing a cookie in this session, so you should not store sensitive data in it. Only the user ID (and possibly the login time and cookie expiration time) should be sufficient. Although the user can see that in the session information, the signature in the cookie ensures that the user himself cannot change the session data.

These methods provide some security that the user cannot interfere with session data, but does not protect the user from eavesdropping. They can always use a packet sniffer and steal a session from any open WiFi network. Some applications rely on the user's IP address, but it does not matter if the attacker is on the same network. Some applications rely on the User-Agent, but there will be problems when the user updates their browser or imports data from another browser.

If you are really concerned about security, use HTTPS .

Also read this article , especially the section "How do site operators fix the problem?"

+3
source share

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


All Articles