random extension macOs handling update.

Not such as fix but taking more precautions.
Indeed, the arc4random has two little flaws in this platform,
one already caught upfront by the extension (ie size 0), also
internal use of ccrng_generate which can silently fail in few rare
cases.

Closes #7824.
This commit is contained in:
David CARLIER 2021-12-24 18:27:24 +00:00 committed by David Carlier
parent 20473374fa
commit d830a1f6f0
3 changed files with 25 additions and 1 deletions

3
NEWS
View file

@ -35,7 +35,8 @@ PHP NEWS
syntaxe of a valid file). (Dmitry)
- Standard:
. Fixed the crypt_sha256/512 api build with clang > 12. (David Carier)
. Fixed the crypt_sha256/512 api build with clang > 12. (David Carlier)
. Uses CCRandomGenerateBytes instead of arc4random_buf on macOs. (David Carlier).
07 Jul 2022, PHP 8.0.21

View file

@ -385,6 +385,12 @@ dnl Check for arc4random on BSD systems
dnl
AC_CHECK_DECLS([arc4random_buf])
dnl
dnl Check for CCRandomGenerateBytes
dnl header absent in previous macOs releases
dnl
AC_CHECK_HEADERS([CommonCrypto/CommonRandom.h])
dnl
dnl Check for argon2
dnl

View file

@ -35,6 +35,10 @@
# include <sys/random.h>
# endif
#endif
#if HAVE_COMMONCRYPTO_COMMONRANDOM_H
# include <CommonCrypto/CommonCryptoError.h>
# include <CommonCrypto/CommonRandom.h>
#endif
#if __has_feature(memory_sanitizer)
# include <sanitizer/msan_interface.h>
@ -94,6 +98,19 @@ PHPAPI int php_random_bytes(void *bytes, size_t size, zend_bool should_throw)
}
return FAILURE;
}
#elif HAVE_COMMONCRYPTO_COMMONRANDOM_H
/*
* Purposely prioritized upon arc4random_buf for modern macOs releases
* arc4random api on this platform uses `ccrng_generate` which returns
* a status but silented to respect the "no fail" arc4random api interface
* the vast majority of the time, it works fine ; but better make sure we catch failures
*/
if (CCRandomGenerateBytes(bytes, size) != kCCSuccess) {
if (should_throw) {
zend_throw_exception(zend_ce_exception, "Error generating bytes", 0);
}
return FAILURE;
}
#elif HAVE_DECL_ARC4RANDOM_BUF && ((defined(__OpenBSD__) && OpenBSD >= 201405) || (defined(__NetBSD__) && __NetBSD_Version__ >= 700000001) || defined(__APPLE__))
arc4random_buf(bytes, size);
#else