Skip to content

Commit d830a1f

Browse files
committed
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.
1 parent 2047337 commit d830a1f

File tree

3 files changed

+25
-1
lines changed

3 files changed

+25
-1
lines changed

NEWS

+2-1
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,8 @@ PHP NEWS
3535
syntaxe of a valid file). (Dmitry)
3636

3737
- Standard:
38-
. Fixed the crypt_sha256/512 api build with clang > 12. (David Carier)
38+
. Fixed the crypt_sha256/512 api build with clang > 12. (David Carlier)
39+
. Uses CCRandomGenerateBytes instead of arc4random_buf on macOs. (David Carlier).
3940

4041
07 Jul 2022, PHP 8.0.21
4142

ext/standard/config.m4

+6
Original file line numberDiff line numberDiff line change
@@ -385,6 +385,12 @@ dnl Check for arc4random on BSD systems
385385
dnl
386386
AC_CHECK_DECLS([arc4random_buf])
387387

388+
dnl
389+
dnl Check for CCRandomGenerateBytes
390+
dnl header absent in previous macOs releases
391+
dnl
392+
AC_CHECK_HEADERS([CommonCrypto/CommonRandom.h])
393+
388394
dnl
389395
dnl Check for argon2
390396
dnl

ext/standard/random.c

+17
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,10 @@
3535
# include <sys/random.h>
3636
# endif
3737
#endif
38+
#if HAVE_COMMONCRYPTO_COMMONRANDOM_H
39+
# include <CommonCrypto/CommonCryptoError.h>
40+
# include <CommonCrypto/CommonRandom.h>
41+
#endif
3842

3943
#if __has_feature(memory_sanitizer)
4044
# include <sanitizer/msan_interface.h>
@@ -94,6 +98,19 @@ PHPAPI int php_random_bytes(void *bytes, size_t size, zend_bool should_throw)
9498
}
9599
return FAILURE;
96100
}
101+
#elif HAVE_COMMONCRYPTO_COMMONRANDOM_H
102+
/*
103+
* Purposely prioritized upon arc4random_buf for modern macOs releases
104+
* arc4random api on this platform uses `ccrng_generate` which returns
105+
* a status but silented to respect the "no fail" arc4random api interface
106+
* the vast majority of the time, it works fine ; but better make sure we catch failures
107+
*/
108+
if (CCRandomGenerateBytes(bytes, size) != kCCSuccess) {
109+
if (should_throw) {
110+
zend_throw_exception(zend_ce_exception, "Error generating bytes", 0);
111+
}
112+
return FAILURE;
113+
}
97114
#elif HAVE_DECL_ARC4RANDOM_BUF && ((defined(__OpenBSD__) && OpenBSD >= 201405) || (defined(__NetBSD__) && __NetBSD_Version__ >= 700000001) || defined(__APPLE__))
98115
arc4random_buf(bytes, size);
99116
#else

0 commit comments

Comments
 (0)