Skip to content

Commit 6c8ef1d

Browse files
authoredJan 25, 2023
random: Reduce variable scopes in CSPRNG (#10426)
* random: Convert the urandom loop into a while() loop This allows us to more easily reduce the scope of `n` in a future commit and now matches the getrandom(2) loop. * random: Move the errno reset immediately above the getrandom(2) call * random: Reduce the scope of `n` in the CSPRNG * random: Declare `n` outside of preprocessor branch
1 parent 3fe8b09 commit 6c8ef1d

File tree

1 file changed

+8
-5
lines changed

1 file changed

+8
-5
lines changed
 

‎ext/random/random.c

+8-5
Original file line numberDiff line numberDiff line change
@@ -517,16 +517,13 @@ PHPAPI int php_random_bytes(void *bytes, size_t size, bool should_throw)
517517
arc4random_buf(bytes, size);
518518
#else
519519
size_t read_bytes = 0;
520-
ssize_t n;
521520
# if (defined(__linux__) && defined(SYS_getrandom)) || (defined(__FreeBSD__) && __FreeBSD_version >= 1200000) || (defined(__DragonFly__) && __DragonFly_version >= 500700) || \
522521
defined(__sun) || (defined(__NetBSD__) && __NetBSD_Version__ >= 1000000000)
523522
/* Linux getrandom(2) syscall or FreeBSD/DragonFlyBSD/NetBSD getrandom(2) function
524523
* Being a syscall, implemented in the kernel, getrandom offers higher quality output
525524
* compared to the arc4random api albeit a fallback to /dev/urandom is considered.
526525
*/
527526
while (read_bytes < size) {
528-
errno = 0;
529-
530527
/* Below, (bytes + read_bytes) is pointer arithmetic.
531528
532529
bytes read_bytes size
@@ -536,6 +533,9 @@ PHPAPI int php_random_bytes(void *bytes, size_t size, bool should_throw)
536533
amount_to_read
537534
*/
538535
size_t amount_to_read = size - read_bytes;
536+
ssize_t n;
537+
538+
errno = 0;
539539
# if defined(__linux__)
540540
n = syscall(SYS_getrandom, bytes + read_bytes, amount_to_read, 0);
541541
# else
@@ -605,9 +605,10 @@ PHPAPI int php_random_bytes(void *bytes, size_t size, bool should_throw)
605605
RANDOM_G(random_fd) = fd;
606606
}
607607

608-
for (read_bytes = 0; read_bytes < size; read_bytes += (size_t) n) {
608+
read_bytes = 0;
609+
while (read_bytes < size) {
609610
errno = 0;
610-
n = read(fd, bytes + read_bytes, size - read_bytes);
611+
ssize_t n = read(fd, bytes + read_bytes, size - read_bytes);
611612

612613
if (n <= 0) {
613614
if (should_throw) {
@@ -619,6 +620,8 @@ PHPAPI int php_random_bytes(void *bytes, size_t size, bool should_throw)
619620
}
620621
return FAILURE;
621622
}
623+
624+
read_bytes += (size_t) n;
622625
}
623626
}
624627
#endif

0 commit comments

Comments
 (0)