Make WordPress Core

Changeset 62054


Ignore:
Timestamp:
03/19/2026 03:49:17 AM (8 days ago)
Author:
jorbin
Message:

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.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/functions.php

    r61995 r62054  
    79917991 *
    79927992 * @since 4.7.0
     7993 * @since 7.0.0 Uses wp_rand if available.
    79937994 *
    79947995 * @return string UUID.
    79957996 */
    79967997function 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}
Note: See TracChangeset for help on using the changeset viewer.