Description
Password reset tokens from uniqid, rand, or mt_rand can be predictable. Use enough cryptographically secure random bytes for each reset link or code.
Potential impact
Someone who guesses a valid link or code may reset the owner’s password and take over the account.
Remediation
- Generate the token with
bin2hex(random_bytes(32)).random_bytessupplies 32 random bytes andbin2hexencodes them as text. - On the server, store the token hash and a short expiry for each user. When the user presents the token, check its hash against the stored value and verify that it has not expired. Invalidate the token after a successful password reset.
- Build the reset link with a domain from trusted configuration. Using the request’s
Hostheader lets the requester influence that domain.
Examples
savePasswordResetToken() is an omitted application function that stores each user’s token hash and expiry. The reset handler must verify the hash and expiry, then prevent reuse of a consumed token.
Before
php
<?php
$resetToken = uniqid();
mail($email, 'Password reset', 'Use token ' . $resetToken);
After
php
<?php
$resetToken = bin2hex(random_bytes(32));
$tokenHash = hash('sha256', $resetToken);
savePasswordResetToken($userId, $tokenHash, time() + 900);
mail($email, 'Password reset', 'Use token ' . $resetToken);
Explanation:
- Before: Uses a predictable value for a password reset token, allowing an attacker to guess a reset link or code.
- After: Generates a cryptographically random reset token and stores its hash with a short expiry on the server.