Skip to content

Commit 53ee3f7

Browse files
zeriyoshinikic
authored andcommitted
Use php_random_bytes() in mt_srand() and uniqid()
Use php_random_bytes() to generate the MT19937 seed if none is explicitly given. Also use it to generate more_entry for uniqid(). These changes should not impact user-observable behavior apart from result statistics. Closes GH-6520.
1 parent 2f1d32d commit 53ee3f7

File tree

2 files changed

+20
-4
lines changed

2 files changed

+20
-4
lines changed

ext/standard/mt_rand.c

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424

2525
#include "php.h"
2626
#include "php_rand.h"
27+
#include "php_random.h"
2728
#include "php_mt_rand.h"
2829

2930
/* MT RAND FUNCTIONS */
@@ -161,7 +162,11 @@ PHPAPI uint32_t php_mt_rand(void)
161162
register uint32_t s1;
162163

163164
if (UNEXPECTED(!BG(mt_rand_is_seeded))) {
164-
php_mt_srand(GENERATE_SEED());
165+
zend_long bytes;
166+
if (php_random_bytes_silent(&bytes, sizeof(zend_long)) == FAILURE) {
167+
bytes = GENERATE_SEED();
168+
}
169+
php_mt_srand(bytes);
165170
}
166171

167172
if (BG(left) == 0) {
@@ -189,8 +194,11 @@ PHP_FUNCTION(mt_srand)
189194
Z_PARAM_LONG(mode)
190195
ZEND_PARSE_PARAMETERS_END();
191196

192-
if (ZEND_NUM_ARGS() == 0)
193-
seed = GENERATE_SEED();
197+
if (ZEND_NUM_ARGS() == 0) {
198+
if (php_random_bytes_silent(&seed, sizeof(zend_long)) == FAILURE) {
199+
seed = GENERATE_SEED();
200+
}
201+
}
194202

195203
switch (mode) {
196204
case MT_RAND_PHP:

ext/standard/uniqid.c

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
#endif
3333

3434
#include "php_lcg.h"
35+
#include "php_random.h"
3536

3637
#ifdef HAVE_GETTIMEOFDAY
3738
ZEND_TLS struct timeval prev_tv = { 0, 0 };
@@ -71,7 +72,14 @@ PHP_FUNCTION(uniqid)
7172
* digits for usecs.
7273
*/
7374
if (more_entropy) {
74-
uniqid = strpprintf(0, "%s%08x%05x%.8F", prefix, sec, usec, php_combined_lcg() * 10);
75+
uint32_t bytes;
76+
double seed;
77+
if (php_random_bytes_silent(&bytes, sizeof(uint32_t)) == FAILURE) {
78+
seed = php_combined_lcg() * 10;
79+
} else {
80+
seed = ((double) bytes / UINT32_MAX) * 10.0;
81+
}
82+
uniqid = strpprintf(0, "%s%08x%05x%.8F", prefix, sec, usec, seed);
7583
} else {
7684
uniqid = strpprintf(0, "%s%08x%05x", prefix, sec, usec);
7785
}

0 commit comments

Comments
 (0)