Skip to content

Commit a466912

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> (cherry picked from commit 9eafb53)
1 parent 591a2bf commit a466912

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;
@@ -303,18 +304,23 @@ BIGNUM *BN_mod_sqrt(BIGNUM *in, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx)
303304
goto vrfy;
304305
}
305306

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

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

0 commit comments

Comments
 (0)