I have read about users being able to manipulate website cookie and use it to exploits security loopholes. I did a search and came across an idea posted online. Here is the code below that is, after the username and password of the user are authenticated;

$Separator = '--';
$uniqueID = 'jhlhgjh12u0@345';
$Data = $userID.' '.md5('65748');

$expire=time()+60*24;
setcookie('verify-user', $Data.$Separator.md5($Data.$uniqueID), $expire);

The code above will set the cookie using a uniqueID, the userID, a MD5 hash numbers and a separator. The uniqueID, md5 hash numbers and separator are set by the developer. The idea is that a user won't be able to manipulate the cookie because the don't know the UniqueID, and the md5 hash numbers. The code below is used to test each cookie if they are manipulated or not

if ($_COOKIE) {

$Separator="--";
$uniqueID = 'jhlhgjh12u0@345';

$Cut = explode($Separator, $_COOKIE['verify-user']);
if (md5($Cut[0].$uniqueID) === $Cut[1]) {
   $_COOKIE['verify-user'] = $Cut[0];

 } else {

   echo "fake cookie";

}
}
else {
   echo "fake cookie";
}

I am wondering if this method is security tight or if there are loopholes too. criticism and corrections are welcomed

有帮助吗?

解决方案

This is known as message signing. You hash the message together with a secret and attach that "signature" to the message itself. This allows the recipient to verify that the creator/signer of the message is in possession of the secret, without revealing the secret itself.

The problem with your particular implementation is that

  • the secret is too small
  • the hashing algorithm is unsuitable for the task
  • the cookies never change and never expire; if a cookie is stolen there's no recourse

You should use a longer secret, the longer the better. You should also use a hashing algorithm that is suited for the task, namely something like HMAC (hash-based message authentication). E.g.:

hash_hmac('sha512', $data, $secret)

You can see an implementation of a similar thing, including expiration of values, here.


The most important thing though: think thrice about whether a signed plain text message is the best way to go here in the first place. Perhaps you want a session-like system, in which an entirely meaningless random string is used as an id for data that is stored on the server. This completely eliminates the problem of users manipulating the cookie.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top