Skip to content

Commit 3800854

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: Tim Hudson <tjh@openssl.org> Reviewed-by: Paul Dale <pauli@openssl.org> Reviewed-by: Matt Caswell <matt@openssl.org>
1 parent 7d749ec commit 3800854

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
@@ -64,7 +64,8 @@ BIGNUM *BN_mod_sqrt(BIGNUM *in, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx)
6464
/*
6565
* Returns 'ret' such that ret^2 == a (mod p), using the Tonelli/Shanks
6666
* algorithm (cf. Henri Cohen, "A Course in Algebraic Computational Number
67-
* Theory", algorithm 1.5.1). 'p' must be prime!
67+
* Theory", algorithm 1.5.1). 'p' must be prime, otherwise an error or
68+
* an incorrect "result" will be returned.
6869
*/
6970
{
7071
BIGNUM *ret = in;
@@ -350,18 +351,23 @@ BIGNUM *BN_mod_sqrt(BIGNUM *in, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx)
350351
goto vrfy;
351352
}
352353

353-
/* find smallest i such that b^(2^i) = 1 */
354-
i = 1;
355-
if (!BN_mod_sqr(t, b, p, ctx))
356-
goto end;
357-
while (!BN_is_one(t)) {
358-
i++;
359-
if (i == e) {
360-
BNerr(BN_F_BN_MOD_SQRT, BN_R_NOT_A_SQUARE);
361-
goto end;
354+
/* Find the smallest i, 0 < i < e, such that b^(2^i) = 1. */
355+
for (i = 1; i < e; i++) {
356+
if (i == 1) {
357+
if (!BN_mod_sqr(t, b, p, ctx))
358+
goto end;
359+
360+
} else {
361+
if (!BN_mod_mul(t, t, t, p, ctx))
362+
goto end;
362363
}
363-
if (!BN_mod_mul(t, t, t, p, ctx))
364-
goto end;
364+
if (BN_is_one(t))
365+
break;
366+
}
367+
/* If not found, a is not a square or p is not prime. */
368+
if (i >= e) {
369+
BNerr(BN_F_BN_MOD_SQRT, BN_R_NOT_A_SQUARE);
370+
goto end;
365371
}
366372

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

0 commit comments

Comments
 (0)