11
11
12
12
#include <stdio.h>
13
13
#include "internal/cryptlib.h"
14
+ #include "internal/bn_int.h"
14
15
#include <openssl/bn.h>
15
16
#include <openssl/sha.h>
16
17
#include "dsa_locl.h"
@@ -182,9 +183,9 @@ static int dsa_sign_setup(DSA *dsa, BN_CTX *ctx_in,
182
183
{
183
184
BN_CTX * ctx = NULL ;
184
185
BIGNUM * k , * kinv = NULL , * r = * rp ;
185
- BIGNUM * l , * m ;
186
+ BIGNUM * l ;
186
187
int ret = 0 ;
187
- int q_bits ;
188
+ int q_bits , q_words ;
188
189
189
190
if (!dsa -> p || !dsa -> q || !dsa -> g ) {
190
191
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,
193
194
194
195
k = BN_new ();
195
196
l = BN_new ();
196
- m = BN_new ();
197
- if (k == NULL || l == NULL || m == NULL )
197
+ if (k == NULL || l == NULL )
198
198
goto err ;
199
199
200
200
if (ctx_in == NULL ) {
@@ -205,9 +205,9 @@ static int dsa_sign_setup(DSA *dsa, BN_CTX *ctx_in,
205
205
206
206
/* Preallocate space */
207
207
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 ))
211
211
goto err ;
212
212
213
213
/* Get random k */
@@ -242,14 +242,17 @@ static int dsa_sign_setup(DSA *dsa, BN_CTX *ctx_in,
242
242
* small timing information leakage. We then choose the sum that is
243
243
* one bit longer than the modulus.
244
244
*
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.
247
249
*/
248
250
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 ))
251
252
goto err ;
252
253
254
+ BN_consttime_swap (BN_is_bit_set (l , q_bits ), k , l , q_words + 2 );
255
+
253
256
if ((dsa )-> meth -> bn_mod_exp != NULL ) {
254
257
if (!dsa -> meth -> bn_mod_exp (dsa , r , dsa -> g , k , dsa -> p , ctx ,
255
258
dsa -> method_mont_p ))
@@ -262,7 +265,7 @@ static int dsa_sign_setup(DSA *dsa, BN_CTX *ctx_in,
262
265
if (!BN_mod (r , r , dsa -> q , ctx ))
263
266
goto err ;
264
267
265
- /* Compute part of 's = inv(k) (m + xr) mod q' */
268
+ /* Compute part of 's = inv(k) (m + xr) mod q' */
266
269
if ((kinv = dsa_mod_inverse_fermat (k , dsa -> q , ctx )) == NULL )
267
270
goto err ;
268
271
@@ -277,7 +280,6 @@ static int dsa_sign_setup(DSA *dsa, BN_CTX *ctx_in,
277
280
BN_CTX_free (ctx );
278
281
BN_clear_free (k );
279
282
BN_clear_free (l );
280
- BN_clear_free (m );
281
283
return ret ;
282
284
}
283
285
0 commit comments