Skip to content

Commit aaf38ca

Browse files
committed
General: Use functions that are more random to reduce likelihood of UUID collisions.
`mt_rand` produces not fully random numbers which makes it so `wp_generate_uuid4` was more likely to produce a uuid which collides with another uuid it produced. This attempts to make those collisions much less likely. Since `wp_rand` is a pluggable function, it's not loaded until after plugins have been loaded. In order to make it so this function can still be used early, it falls back first to `random_int`, which will throw an exception if it can't find an appropriate source of randomness, and then to the existing, but flawed, `mt_rand`. Props johnbillion, peterwilsoncc, westonruter, mukesh27, siliconforks, alexodiy, juanmaguitar, audrasjb, joppuyo, jorbin. Fixes #59239. git-svn-id: https://develop.svn.wordpress.org/trunk@62054 602fd350-edb4-49c9-b593-d223f7449a82
1 parent d0dfc76 commit aaf38ca

File tree

1 file changed

+22
-8
lines changed

1 file changed

+22
-8
lines changed

src/wp-includes/functions.php

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7990,20 +7990,34 @@ function wp_raise_memory_limit( $context = 'admin' ) {
79907990
* Generates a random UUID (version 4).
79917991
*
79927992
* @since 4.7.0
7993+
* @since 7.0.0 Uses wp_rand if available.
79937994
*
79947995
* @return string UUID.
79957996
*/
79967997
function wp_generate_uuid4() {
7998+
static $backup_randomizer = false;
7999+
$randomizer = function_exists( 'wp_rand' ) ? 'wp_rand' : $backup_randomizer;
8000+
8001+
if ( false === $randomizer ) {
8002+
try {
8003+
random_int( 0, 15705 );
8004+
$backup_randomizer = 'random_int';
8005+
} catch ( Exception $e ) {
8006+
$backup_randomizer = 'mt_rand';
8007+
}
8008+
$randomizer = $backup_randomizer;
8009+
}
8010+
79978011
return sprintf(
79988012
'%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
7999-
mt_rand( 0, 0xffff ),
8000-
mt_rand( 0, 0xffff ),
8001-
mt_rand( 0, 0xffff ),
8002-
mt_rand( 0, 0x0fff ) | 0x4000,
8003-
mt_rand( 0, 0x3fff ) | 0x8000,
8004-
mt_rand( 0, 0xffff ),
8005-
mt_rand( 0, 0xffff ),
8006-
mt_rand( 0, 0xffff )
8013+
$randomizer( 0, 0xffff ),
8014+
$randomizer( 0, 0xffff ),
8015+
$randomizer( 0, 0xffff ),
8016+
$randomizer( 0, 0x0fff ) | 0x4000,
8017+
$randomizer( 0, 0x3fff ) | 0x8000,
8018+
$randomizer( 0, 0xffff ),
8019+
$randomizer( 0, 0xffff ),
8020+
$randomizer( 0, 0xffff )
80078021
);
80088022
}
80098023

0 commit comments

Comments
 (0)