1111
1212#include <stdio.h>
1313#include "internal/cryptlib.h"
14+ #include "internal/bn_int.h"
1415#include <openssl/bn.h>
1516#include <openssl/sha.h>
1617#include "dsa_locl.h"
@@ -182,9 +183,9 @@ static int dsa_sign_setup(DSA *dsa, BN_CTX *ctx_in,
182183{
183184 BN_CTX * ctx = NULL ;
184185 BIGNUM * k , * kinv = NULL , * r = * rp ;
185- BIGNUM * l , * m ;
186+ BIGNUM * l ;
186187 int ret = 0 ;
187- int q_bits ;
188+ int q_bits , q_words ;
188189
189190 if (!dsa -> p || !dsa -> q || !dsa -> g ) {
190191 DSAerr (DSA_F_DSA_SIGN_SETUP , DSA_R_MISSING_PARAMETERS );
@@ -193,8 +194,7 @@ static int dsa_sign_setup(DSA *dsa, BN_CTX *ctx_in,
193194
194195 k = BN_new ();
195196 l = BN_new ();
196- m = BN_new ();
197- if (k == NULL || l == NULL || m == NULL )
197+ if (k == NULL || l == NULL )
198198 goto err ;
199199
200200 if (ctx_in == NULL ) {
@@ -205,9 +205,9 @@ static int dsa_sign_setup(DSA *dsa, BN_CTX *ctx_in,
205205
206206 /* Preallocate space */
207207 q_bits = BN_num_bits (dsa -> q );
208- if (! BN_set_bit ( k , q_bits )
209- || ! BN_set_bit ( l , q_bits )
210- || !BN_set_bit ( m , q_bits ))
208+ q_words = bn_get_top ( dsa -> q );
209+ if (! bn_wexpand ( k , q_words + 2 )
210+ || !bn_wexpand ( l , q_words + 2 ))
211211 goto err ;
212212
213213 /* Get random k */
@@ -242,14 +242,17 @@ static int dsa_sign_setup(DSA *dsa, BN_CTX *ctx_in,
242242 * small timing information leakage. We then choose the sum that is
243243 * one bit longer than the modulus.
244244 *
245- * TODO: revisit the BN_copy aiming for a memory access agnostic
246- * conditional copy.
245+ * There are some concerns about the efficacy of doing this. More
246+ * specificly refer to the discussion starting with:
247+ * https://github.com/openssl/openssl/pull/7486#discussion_r228323705
248+ * The fix is to rework BN so these gymnastics aren't required.
247249 */
248250 if (!BN_add (l , k , dsa -> q )
249- || !BN_add (m , l , dsa -> q )
250- || !BN_copy (k , BN_num_bits (l ) > q_bits ? l : m ))
251+ || !BN_add (k , l , dsa -> q ))
251252 goto err ;
252253
254+ BN_consttime_swap (BN_is_bit_set (l , q_bits ), k , l , q_words + 2 );
255+
253256 if ((dsa )-> meth -> bn_mod_exp != NULL ) {
254257 if (!dsa -> meth -> bn_mod_exp (dsa , r , dsa -> g , k , dsa -> p , ctx ,
255258 dsa -> method_mont_p ))
@@ -262,7 +265,7 @@ static int dsa_sign_setup(DSA *dsa, BN_CTX *ctx_in,
262265 if (!BN_mod (r , r , dsa -> q , ctx ))
263266 goto err ;
264267
265- /* Compute part of 's = inv(k) (m + xr) mod q' */
268+ /* Compute part of 's = inv(k) (m + xr) mod q' */
266269 if ((kinv = dsa_mod_inverse_fermat (k , dsa -> q , ctx )) == NULL )
267270 goto err ;
268271
@@ -277,7 +280,6 @@ static int dsa_sign_setup(DSA *dsa, BN_CTX *ctx_in,
277280 BN_CTX_free (ctx );
278281 BN_clear_free (k );
279282 BN_clear_free (l );
280- BN_clear_free (m );
281283 return ret ;
282284}
283285
0 commit comments