99
1010#include <stdio.h>
1111#include "internal/cryptlib.h"
12+ #include "internal/bn_int.h"
1213#include <openssl/bn.h>
1314#include <openssl/sha.h>
1415#include "dsa_locl.h"
@@ -180,9 +181,9 @@ static int dsa_sign_setup(DSA *dsa, BN_CTX *ctx_in,
180181{
181182 BN_CTX * ctx = NULL ;
182183 BIGNUM * k , * kinv = NULL , * r = * rp ;
183- BIGNUM * l , * m ;
184+ BIGNUM * l ;
184185 int ret = 0 ;
185- int q_bits ;
186+ int q_bits , q_words ;
186187
187188 if (!dsa -> p || !dsa -> q || !dsa -> g ) {
188189 DSAerr (DSA_F_DSA_SIGN_SETUP , DSA_R_MISSING_PARAMETERS );
@@ -191,8 +192,7 @@ static int dsa_sign_setup(DSA *dsa, BN_CTX *ctx_in,
191192
192193 k = BN_new ();
193194 l = BN_new ();
194- m = BN_new ();
195- if (k == NULL || l == NULL || m == NULL )
195+ if (k == NULL || l == NULL )
196196 goto err ;
197197
198198 if (ctx_in == NULL ) {
@@ -203,9 +203,9 @@ static int dsa_sign_setup(DSA *dsa, BN_CTX *ctx_in,
203203
204204 /* Preallocate space */
205205 q_bits = BN_num_bits (dsa -> q );
206- if (! BN_set_bit ( k , q_bits )
207- || ! BN_set_bit ( l , q_bits )
208- || !BN_set_bit ( m , q_bits ))
206+ q_words = bn_get_top ( dsa -> q );
207+ if (! bn_wexpand ( k , q_words + 2 )
208+ || !bn_wexpand ( l , q_words + 2 ))
209209 goto err ;
210210
211211 /* Get random k */
@@ -240,14 +240,17 @@ static int dsa_sign_setup(DSA *dsa, BN_CTX *ctx_in,
240240 * small timing information leakage. We then choose the sum that is
241241 * one bit longer than the modulus.
242242 *
243- * TODO: revisit the BN_copy aiming for a memory access agnostic
244- * conditional copy.
243+ * There are some concerns about the efficacy of doing this. More
244+ * specificly refer to the discussion starting with:
245+ * https://github.com/openssl/openssl/pull/7486#discussion_r228323705
246+ * The fix is to rework BN so these gymnastics aren't required.
245247 */
246248 if (!BN_add (l , k , dsa -> q )
247- || !BN_add (m , l , dsa -> q )
248- || !BN_copy (k , BN_num_bits (l ) > q_bits ? l : m ))
249+ || !BN_add (k , l , dsa -> q ))
249250 goto err ;
250251
252+ BN_consttime_swap (BN_is_bit_set (l , q_bits ), k , l , q_words + 2 );
253+
251254 if ((dsa )-> meth -> bn_mod_exp != NULL ) {
252255 if (!dsa -> meth -> bn_mod_exp (dsa , r , dsa -> g , k , dsa -> p , ctx ,
253256 dsa -> method_mont_p ))
@@ -260,7 +263,7 @@ static int dsa_sign_setup(DSA *dsa, BN_CTX *ctx_in,
260263 if (!BN_mod (r , r , dsa -> q , ctx ))
261264 goto err ;
262265
263- /* Compute part of 's = inv(k) (m + xr) mod q' */
266+ /* Compute part of 's = inv(k) (m + xr) mod q' */
264267 if ((kinv = dsa_mod_inverse_fermat (k , dsa -> q , ctx )) == NULL )
265268 goto err ;
266269
@@ -275,7 +278,6 @@ static int dsa_sign_setup(DSA *dsa, BN_CTX *ctx_in,
275278 BN_CTX_free (ctx );
276279 BN_clear_free (k );
277280 BN_clear_free (l );
278- BN_clear_free (m );
279281 return ret ;
280282}
281283
0 commit comments