From ec747b4beaa253269b2c18925e90dec4dc91d328 Mon Sep 17 00:00:00 2001 From: jsing Date: Wed, 15 Mar 2023 04:30:20 +0000 Subject: [PATCH] Ensure negative input to BN_mod_exp_mont_consttime() is correctly reduced. A negative input to BN_mod_exp_mont_consttime() is not correctly reduced, remaining negative (when it should be in the range [0, m)). Fix this by unconditionally calling BN_nnmod() on the input. Fixes ossfuzz #55997. ok tb@ --- lib/libcrypto/bn/bn_exp.c | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/lib/libcrypto/bn/bn_exp.c b/lib/libcrypto/bn/bn_exp.c index 4011bb48909..9abf574b576 100644 --- a/lib/libcrypto/bn/bn_exp.c +++ b/lib/libcrypto/bn/bn_exp.c @@ -1,4 +1,4 @@ -/* $OpenBSD: bn_exp.c,v 1.37 2023/02/03 05:30:49 jsing Exp $ */ +/* $OpenBSD: bn_exp.c,v 1.38 2023/03/15 04:30:20 jsing Exp $ */ /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. * @@ -459,12 +459,9 @@ BN_mod_exp_mont_consttime(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p, #endif /* prepare a^1 in Montgomery domain */ - if (a->neg || BN_ucmp(a, m) >= 0) { - if (!BN_mod_ct(&am, a,m, ctx)) - goto err; - if (!BN_to_montgomery(&am, &am, mont, ctx)) - goto err; - } else if (!BN_to_montgomery(&am, a,mont, ctx)) + if (!BN_nnmod(&am, a, m, ctx)) + goto err; + if (!BN_to_montgomery(&am, &am, mont, ctx)) goto err; #if defined(OPENSSL_BN_ASM_MONT5) -- 2.20.1