Skip to content

Commit 3118eb6

Browse files
t8mmattcaswell
authored andcommitted
Fix possible infinite loop in BN_mod_sqrt()
The calculation in some cases does not finish for non-prime p. This fixes CVE-2022-0778. Based on patch by David Benjamin <davidben@google.com>. Reviewed-by: Paul Dale <pauli@openssl.org> Reviewed-by: Matt Caswell <matt@openssl.org>
1 parent 84a9f7e commit 3118eb6

File tree

1 file changed

+18
-12
lines changed

1 file changed

+18
-12
lines changed

Diff for: crypto/bn/bn_sqrt.c

+18-12
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,8 @@ BIGNUM *BN_mod_sqrt(BIGNUM *in, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx)
1414
/*
1515
* Returns 'ret' such that ret^2 == a (mod p), using the Tonelli/Shanks
1616
* algorithm (cf. Henri Cohen, "A Course in Algebraic Computational Number
17-
* Theory", algorithm 1.5.1). 'p' must be prime!
17+
* Theory", algorithm 1.5.1). 'p' must be prime, otherwise an error or
18+
* an incorrect "result" will be returned.
1819
*/
1920
{
2021
BIGNUM *ret = in;
@@ -301,18 +302,23 @@ BIGNUM *BN_mod_sqrt(BIGNUM *in, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx)
301302
goto vrfy;
302303
}
303304

304-
/* find smallest i such that b^(2^i) = 1 */
305-
i = 1;
306-
if (!BN_mod_sqr(t, b, p, ctx))
307-
goto end;
308-
while (!BN_is_one(t)) {
309-
i++;
310-
if (i == e) {
311-
BNerr(BN_F_BN_MOD_SQRT, BN_R_NOT_A_SQUARE);
312-
goto end;
305+
/* Find the smallest i, 0 < i < e, such that b^(2^i) = 1. */
306+
for (i = 1; i < e; i++) {
307+
if (i == 1) {
308+
if (!BN_mod_sqr(t, b, p, ctx))
309+
goto end;
310+
311+
} else {
312+
if (!BN_mod_mul(t, t, t, p, ctx))
313+
goto end;
313314
}
314-
if (!BN_mod_mul(t, t, t, p, ctx))
315-
goto end;
315+
if (BN_is_one(t))
316+
break;
317+
}
318+
/* If not found, a is not a square or p is not prime. */
319+
if (i >= e) {
320+
BNerr(BN_F_BN_MOD_SQRT, BN_R_NOT_A_SQUARE);
321+
goto end;
316322
}
317323

318324
/* t := y^2^(e - i - 1) */

0 commit comments

Comments
 (0)