Skip to content

Commit afa6eec

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.
1 parent 2b81156 commit afa6eec

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

ext/standard/config.m4

Lines changed: 6 additions & 0 deletions
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

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,9 @@
3535
# include <sys/random.h>
3636
# endif
3737
#endif
38+
#if HAVE_COMMONCRYPTO_COMMONRANDOM_H
39+
# include <CommonCrypto/CommonRandom.h>
40+
#endif
3841

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

0 commit comments

Comments
 (0)