Skip to content

Commit 666fe16

Browse files
committed
ext/gmp: Fix crash in gmp_pow with excessively large exponent
1 parent 2223bc6 commit 666fe16

3 files changed

Lines changed: 13 additions & 5 deletions

File tree

ext/gmp/gmp.c

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1126,14 +1126,22 @@ ZEND_FUNCTION(gmp_pow)
11261126
mpz_ptr gmpnum_result;
11271127
mpz_ptr gmpnum_base;
11281128
zend_long exp;
1129+
size_t bits;
11291130

11301131
ZEND_PARSE_PARAMETERS_START(2, 2)
11311132
GMP_Z_PARAM_INTO_MPZ_PTR(gmpnum_base)
11321133
Z_PARAM_LONG(exp)
11331134
ZEND_PARSE_PARAMETERS_END();
11341135

1135-
if (exp < 0 || exp > GMP_POW_MAX_EXP) {
1136-
zend_argument_value_error(2, "must be between 0 and %lu", GMP_POW_MAX_EXP);
1136+
if (exp < 0) {
1137+
zend_argument_value_error(2, "must be greater than or equal to 0");
1138+
RETURN_THROWS();
1139+
}
1140+
1141+
bits = mpz_sizeinbase(gmpnum_base, 2);
1142+
1143+
if (exp < 0 || exp > (SIZE_MAX - 5) / bits) {
1144+
zend_argument_value_error(2, "results in a value that exceeds the supported size");
11371145
RETURN_THROWS();
11381146
}
11391147

ext/gmp/tests/gh22351.phpt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,5 +18,5 @@ echo "Done\n";
1818
?>
1919
--EXPECTF--
2020
Testing gmp_pow overflow safety
21-
ValueError: gmp_pow(): Argument #2 ($exponent) must be between 0 and 1000000
21+
ValueError: gmp_pow(): Argument #2 ($exponent) results in a value that exceeds the supported size
2222
Done

ext/gmp/tests/gmp_pow.phpt

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -49,11 +49,11 @@ string(4) "1024"
4949
string(5) "-2048"
5050
string(4) "1024"
5151
string(1) "1"
52-
gmp_pow(): Argument #2 ($exponent) must be between 0 and %d
52+
gmp_pow(): Argument #2 ($exponent) must be greater than or equal to 0
5353
string(4) "1024"
5454
string(14) "10240000000000"
5555
string(17) "97656250000000000"
56-
gmp_pow(): Argument #2 ($exponent) must be between 0 and %d
56+
gmp_pow(): Argument #2 ($exponent) must be greater than or equal to 0
5757
string(14) "10240000000000"
5858
string(14) "10240000000000"
5959
gmp_pow(): Argument #2 ($exponent) must be of type int, array given

0 commit comments

Comments
 (0)