Thursday, January 9, 2025

CodeSOD: My Identification

Programming LanguageCodeSOD: My Identification


Bejamin's team needed to generate a unique session ID value that can't easily be guessed. The traditional way of doing this would be to generate cryptographically secure random bytes. Most languages, including PHP, have a solution for doing that.

But you could also do this:

protected function _createId()
{
        $id = 0;
        while (strlen($id) < 32)
        {
                $id .= mt_rand(0, mt_getrandmax());
        }

        $id = md5(uniqid($id, true));
        return $id;
}

Now, mt_rand is not cryptographically secure. They generate a random number (of arbitrary size) and concatenate it to a string. When the string is 32 characters long (including a leading zero), we call that enough.

This is not generating random bytes. To the contrary, the bytes it's generating are very not random, seeing as they're constrained to a character between 0 and 9.

We then pass that through the uniqid function. Now, uniqid also generates a non-cryptographically secure unique identifier. Here, we're specifying our large number is the prefix to that unique ID, and asking for more randomness to be added (the true parameter). This is better than what they did with the while loop above, though still not the "correct" way to do it.

Finally, we pass it through the md5 algorithm to reduce it to a hash, because we just love hash collisions.

It's impressive that, given a chance to make a choice about security-related features, they were able to make every single wrong choice.

This is also why you don't implement this stuff yourself. There are far more ways to get it wrong than there are ways to get it right.

[Advertisement]
Keep all your packages and Docker containers in one place, scan for vulnerabilities, and control who can access different feeds. ProGet installs in minutes and has a powerful free version with a lot of great features that you can upgrade when ready.Learn more.

Check out our other content

Check out other tags:

Most Popular Articles