mirror of
https://github.com/php/php-src.git
synced 2025-08-16 05:58:45 +02:00
Add zend_random_bytes(), zend_random_bytes_insecure() functions (#14054)
Co-authored-by: Tim Düsterhus <tim@bastelstu.be>
This commit is contained in:
parent
d545b1d643
commit
d1048a0869
10 changed files with 169 additions and 12 deletions
|
@ -610,7 +610,7 @@ static inline void fallback_seed_add(PHP_SHA1_CTX *c, void *p, size_t l){
|
|||
PHP_SHA1Update(c, p, l);
|
||||
}
|
||||
|
||||
PHPAPI uint64_t php_random_generate_fallback_seed(void)
|
||||
PHPAPI uint64_t php_random_generate_fallback_seed_ex(php_random_fallback_seed_state *state)
|
||||
{
|
||||
/* Mix various values using SHA-1 as a PRF to obtain as
|
||||
* much entropy as possible, hopefully generating an
|
||||
|
@ -628,7 +628,7 @@ PHPAPI uint64_t php_random_generate_fallback_seed(void)
|
|||
char buf[64 + 1];
|
||||
|
||||
PHP_SHA1Init(&c);
|
||||
if (!RANDOM_G(fallback_seed_initialized)) {
|
||||
if (!state->initialized) {
|
||||
/* Current time. */
|
||||
gettimeofday(&tv, NULL);
|
||||
fallback_seed_add(&c, &tv, sizeof(tv));
|
||||
|
@ -644,7 +644,7 @@ PHPAPI uint64_t php_random_generate_fallback_seed(void)
|
|||
fallback_seed_add(&c, &tid, sizeof(tid));
|
||||
#endif
|
||||
/* Pointer values to benefit from ASLR. */
|
||||
pointer = &RANDOM_G(fallback_seed_initialized);
|
||||
pointer = &state;
|
||||
fallback_seed_add(&c, &pointer, sizeof(pointer));
|
||||
pointer = &c;
|
||||
fallback_seed_add(&c, &pointer, sizeof(pointer));
|
||||
|
@ -668,24 +668,29 @@ PHPAPI uint64_t php_random_generate_fallback_seed(void)
|
|||
gettimeofday(&tv, NULL);
|
||||
fallback_seed_add(&c, &tv, sizeof(tv));
|
||||
/* Previous state. */
|
||||
fallback_seed_add(&c, RANDOM_G(fallback_seed), 20);
|
||||
fallback_seed_add(&c, state->seed, 20);
|
||||
}
|
||||
PHP_SHA1Final(RANDOM_G(fallback_seed), &c);
|
||||
RANDOM_G(fallback_seed_initialized) = true;
|
||||
PHP_SHA1Final(state->seed, &c);
|
||||
state->initialized = true;
|
||||
|
||||
uint64_t result = 0;
|
||||
|
||||
for (size_t i = 0; i < sizeof(result); i++) {
|
||||
result = result | (((uint64_t)RANDOM_G(fallback_seed)[i]) << (i * 8));
|
||||
result = result | (((uint64_t)state->seed[i]) << (i * 8));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
PHPAPI uint64_t php_random_generate_fallback_seed(void)
|
||||
{
|
||||
return php_random_generate_fallback_seed_ex(&RANDOM_G(fallback_seed_state));
|
||||
}
|
||||
|
||||
/* {{{ PHP_GINIT_FUNCTION */
|
||||
static PHP_GINIT_FUNCTION(random)
|
||||
{
|
||||
random_globals->fallback_seed_initialized = false;
|
||||
random_globals->fallback_seed_state.initialized = false;
|
||||
}
|
||||
/* }}} */
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue