Skip to content

Commit

Permalink
Fix possible infinite loop in BN_mod_sqrt()
Browse files Browse the repository at this point in the history
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)
  • Loading branch information
t8m authored and mattcaswell committed Mar 15, 2022
1 parent 591a2bf commit a466912
Showing 1 changed file with 18 additions and 12 deletions.
30 changes: 18 additions & 12 deletions crypto/bn/bn_sqrt.c
Expand Up @@ -14,7 +14,8 @@ BIGNUM *BN_mod_sqrt(BIGNUM *in, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx)
/*
* Returns 'ret' such that ret^2 == a (mod p), using the Tonelli/Shanks
* algorithm (cf. Henri Cohen, "A Course in Algebraic Computational Number
* Theory", algorithm 1.5.1). 'p' must be prime!
* Theory", algorithm 1.5.1). 'p' must be prime, otherwise an error or
* an incorrect "result" will be returned.
*/
{
BIGNUM *ret = in;
Expand Down Expand Up @@ -303,18 +304,23 @@ BIGNUM *BN_mod_sqrt(BIGNUM *in, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx)
goto vrfy;
}

/* find smallest i such that b^(2^i) = 1 */
i = 1;
if (!BN_mod_sqr(t, b, p, ctx))
goto end;
while (!BN_is_one(t)) {
i++;
if (i == e) {
ERR_raise(ERR_LIB_BN, BN_R_NOT_A_SQUARE);
goto end;
/* Find the smallest i, 0 < i < e, such that b^(2^i) = 1. */
for (i = 1; i < e; i++) {
if (i == 1) {
if (!BN_mod_sqr(t, b, p, ctx))
goto end;

} else {
if (!BN_mod_mul(t, t, t, p, ctx))
goto end;
}
if (!BN_mod_mul(t, t, t, p, ctx))
goto end;
if (BN_is_one(t))
break;
}
/* If not found, a is not a square or p is not prime. */
if (i >= e) {
ERR_raise(ERR_LIB_BN, BN_R_NOT_A_SQUARE);
goto end;
}

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

2 comments on commit a466912

@tmshort
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Duplicate a466912

This IS a466912

@mspncp
Copy link
Contributor

@mspncp mspncp commented on a466912 Mar 18, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Duplicate a466912

This IS a466912

Well, if we want "is duplicate of" to be an equivalence relation, then we should allow a466912 to be a duplicate of itself, for the sake of reflexiveness, right? πŸ€”

Please sign in to comment.