From baccea0f7bedcbc47cbec45fd8ecf3c8054b10b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tim=20D=C3=BCsterhus?= Date: Fri, 29 Jul 2022 21:39:36 +0200 Subject: [PATCH] Fix undefined behavior of MT_RAND_PHP if range exceeds ZEND_LONG_MAX RAND_RANGE_BADSCALING() invokes undefined behavior when (max - min) > ZEND_LONG_MAX, because the intermediate `double` might not fit into `zend_long`. Fix this by inlining a fixed version of the macro into Mt19937's range() function. Fixing the macro itself cannot be done in the general case, because the types of the inputs are not known. Instead of replacing one possibly broken version with another possibly broken version, the macro is simply left as is and should be removed in a future version. The fix itself is simple: Instead of storing the "offset" in a `zend_long`, we use a `zend_ulong` which is capable of storing the resulting double by construction. With this fix the implementation of this broken scaling is effectively identical to the implementation of php_random_range from a data type perspective, making it easy to verify the correctness. It was further empirically verified that the broken macro and the fix return the same results for all possible values of `r` for several distinct pairs of (min, max). Fixes GH-9190 Fixes GH-9191 --- NEWS | 2 ++ ext/random/engine_mt19937.c | 12 +++++++++--- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/NEWS b/NEWS index 7fb9b27dc7688..32062ccc298ec 100644 --- a/NEWS +++ b/NEWS @@ -5,6 +5,8 @@ PHP NEWS - Random: . Fixed bug GH-9235 (non-existant $sequence parameter in stub for PcgOneseq128XslRr64::__construct()). (timwolla) + . Fixed bug GH-9190, GH-9191 (undefined behavior for MT_RAND_PHP when + handling large ranges). (timwolla) . Removed redundant RuntimeExceptions from Randomizer methods. The exceptions thrown by the engines will be exposed directly. (timwolla) . Added extension specific Exceptions/Errors (RandomException, RandomError, diff --git a/ext/random/engine_mt19937.c b/ext/random/engine_mt19937.c index d7d355b90d6b4..266ec5ea11c24 100644 --- a/ext/random/engine_mt19937.c +++ b/ext/random/engine_mt19937.c @@ -168,11 +168,17 @@ static zend_long range(php_random_status *status, zend_long min, zend_long max) return php_random_range(&php_random_algo_mt19937, status, min, max); } - uint64_t r = php_random_algo_mt19937.generate(status) >> 1; /* Legacy mode deliberately not inside php_mt_rand_range() * to prevent other functions being affected */ - RAND_RANGE_BADSCALING(r, min, max, PHP_MT_RAND_MAX); - return (zend_long) r; + + uint64_t r = php_random_algo_mt19937.generate(status) >> 1; + + /* This is an inlined version of the RAND_RANGE_BADSCALING macro that does not invoke UB when encountering + * (max - min) > ZEND_LONG_MAX. + */ + zend_ulong offset = (double) ( (double) max - min + 1.0) * (r / (PHP_MT_RAND_MAX + 1.0)); + + return (zend_long) (offset + min); } static bool serialize(php_random_status *status, HashTable *data)