Skip to content

Commit ec3ccb5

Browse files
committed
Fix GH-16501: gmp_random_bits overflow.
we do the same calculation in advance as mpz_realloc overflow check to avoid abort.
1 parent 062837a commit ec3ccb5

File tree

2 files changed

+23
-3
lines changed

2 files changed

+23
-3
lines changed

ext/gmp/gmp.c

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1803,15 +1803,21 @@ ZEND_FUNCTION(gmp_random_bits)
18031803
RETURN_THROWS();
18041804
}
18051805

1806-
if (bits <= 0) {
1807-
zend_argument_value_error(1, "must be greater than or equal to 1");
1806+
#if SIZEOF_SIZE_T == 4
1807+
const zend_long maxbits = ULONG_MAX / GMP_NUMB_BITS;
1808+
#else
1809+
const zend_long maxbits = INT_MAX;
1810+
#endif
1811+
1812+
if (bits <= 0 || bits > maxbits) {
1813+
zend_argument_value_error(1, "must be between 1 and " ZEND_LONG_FMT, maxbits);
18081814
RETURN_THROWS();
18091815
}
18101816

18111817
INIT_GMP_RETVAL(gmpnum_result);
18121818
gmp_init_random();
18131819

1814-
mpz_urandomb(gmpnum_result, GMPG(rand_state), bits);
1820+
mpz_urandomb(gmpnum_result, GMPG(rand_state), (mp_bitcnt_t)bits);
18151821
}
18161822
/* }}} */
18171823

ext/gmp/tests/gh16501.phpt

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
--TEST--
2+
GH-16501 (gmp_random_bits overflow)
3+
--EXTENSIONS--
4+
gmp
5+
--FILE--
6+
<?php
7+
try {
8+
gmp_random_bits(PHP_INT_MAX);
9+
} catch (\ValueError $e) {
10+
echo $e->getMessage();
11+
}
12+
?>
13+
--EXPECTF--
14+
gmp_random_bits(): Argument #1 ($bits) must be between 1 and %d

0 commit comments

Comments
 (0)