Coverage Report

Created: 2024-11-21 07:03

/src/boringssl/crypto/dsa/dsa.c
Line
Count
Source (jump to first uncovered line)
1
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
2
 * All rights reserved.
3
 *
4
 * This package is an SSL implementation written
5
 * by Eric Young (eay@cryptsoft.com).
6
 * The implementation was written so as to conform with Netscapes SSL.
7
 *
8
 * This library is free for commercial and non-commercial use as long as
9
 * the following conditions are aheared to.  The following conditions
10
 * apply to all code found in this distribution, be it the RC4, RSA,
11
 * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
12
 * included with this distribution is covered by the same copyright terms
13
 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
14
 *
15
 * Copyright remains Eric Young's, and as such any Copyright notices in
16
 * the code are not to be removed.
17
 * If this package is used in a product, Eric Young should be given attribution
18
 * as the author of the parts of the library used.
19
 * This can be in the form of a textual message at program startup or
20
 * in documentation (online or textual) provided with the package.
21
 *
22
 * Redistribution and use in source and binary forms, with or without
23
 * modification, are permitted provided that the following conditions
24
 * are met:
25
 * 1. Redistributions of source code must retain the copyright
26
 *    notice, this list of conditions and the following disclaimer.
27
 * 2. Redistributions in binary form must reproduce the above copyright
28
 *    notice, this list of conditions and the following disclaimer in the
29
 *    documentation and/or other materials provided with the distribution.
30
 * 3. All advertising materials mentioning features or use of this software
31
 *    must display the following acknowledgement:
32
 *    "This product includes cryptographic software written by
33
 *     Eric Young (eay@cryptsoft.com)"
34
 *    The word 'cryptographic' can be left out if the rouines from the library
35
 *    being used are not cryptographic related :-).
36
 * 4. If you include any Windows specific code (or a derivative thereof) from
37
 *    the apps directory (application code) you must include an acknowledgement:
38
 *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
39
 *
40
 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50
 * SUCH DAMAGE.
51
 *
52
 * The licence and distribution terms for any publically available version or
53
 * derivative of this code cannot be changed.  i.e. this code cannot simply be
54
 * copied and put under another distribution licence
55
 * [including the GNU Public Licence.]
56
 *
57
 * The DSS routines are based on patches supplied by
58
 * Steven Schoch <schoch@sheba.arc.nasa.gov>. */
59
60
#include <openssl/dsa.h>
61
62
#include <string.h>
63
64
#include <openssl/bn.h>
65
#include <openssl/dh.h>
66
#include <openssl/digest.h>
67
#include <openssl/engine.h>
68
#include <openssl/err.h>
69
#include <openssl/ex_data.h>
70
#include <openssl/mem.h>
71
#include <openssl/rand.h>
72
#include <openssl/sha.h>
73
#include <openssl/thread.h>
74
75
#include "internal.h"
76
#include "../fipsmodule/bn/internal.h"
77
#include "../fipsmodule/dh/internal.h"
78
#include "../internal.h"
79
80
81
// Primality test according to FIPS PUB 186[-1], Appendix 2.1: 50 rounds of
82
// Miller-Rabin.
83
2.54k
#define DSS_prime_checks 50
84
85
static int dsa_sign_setup(const DSA *dsa, BN_CTX *ctx_in, BIGNUM **out_kinv,
86
                          BIGNUM **out_r);
87
88
static CRYPTO_EX_DATA_CLASS g_ex_data_class = CRYPTO_EX_DATA_CLASS_INIT;
89
90
88
DSA *DSA_new(void) {
91
88
  DSA *dsa = OPENSSL_zalloc(sizeof(DSA));
92
88
  if (dsa == NULL) {
93
0
    return NULL;
94
0
  }
95
96
88
  dsa->references = 1;
97
88
  CRYPTO_MUTEX_init(&dsa->method_mont_lock);
98
88
  CRYPTO_new_ex_data(&dsa->ex_data);
99
88
  return dsa;
100
88
}
101
102
94
void DSA_free(DSA *dsa) {
103
94
  if (dsa == NULL) {
104
6
    return;
105
6
  }
106
107
88
  if (!CRYPTO_refcount_dec_and_test_zero(&dsa->references)) {
108
0
    return;
109
0
  }
110
111
88
  CRYPTO_free_ex_data(&g_ex_data_class, dsa, &dsa->ex_data);
112
113
88
  BN_clear_free(dsa->p);
114
88
  BN_clear_free(dsa->q);
115
88
  BN_clear_free(dsa->g);
116
88
  BN_clear_free(dsa->pub_key);
117
88
  BN_clear_free(dsa->priv_key);
118
88
  BN_MONT_CTX_free(dsa->method_mont_p);
119
88
  BN_MONT_CTX_free(dsa->method_mont_q);
120
88
  CRYPTO_MUTEX_cleanup(&dsa->method_mont_lock);
121
88
  OPENSSL_free(dsa);
122
88
}
123
124
0
int DSA_up_ref(DSA *dsa) {
125
0
  CRYPTO_refcount_inc(&dsa->references);
126
0
  return 1;
127
0
}
128
129
0
unsigned DSA_bits(const DSA *dsa) { return BN_num_bits(dsa->p); }
130
131
0
const BIGNUM *DSA_get0_pub_key(const DSA *dsa) { return dsa->pub_key; }
132
133
0
const BIGNUM *DSA_get0_priv_key(const DSA *dsa) { return dsa->priv_key; }
134
135
412
const BIGNUM *DSA_get0_p(const DSA *dsa) { return dsa->p; }
136
137
412
const BIGNUM *DSA_get0_q(const DSA *dsa) { return dsa->q; }
138
139
412
const BIGNUM *DSA_get0_g(const DSA *dsa) { return dsa->g; }
140
141
void DSA_get0_key(const DSA *dsa, const BIGNUM **out_pub_key,
142
8
                  const BIGNUM **out_priv_key) {
143
8
  if (out_pub_key != NULL) {
144
8
    *out_pub_key = dsa->pub_key;
145
8
  }
146
8
  if (out_priv_key != NULL) {
147
0
    *out_priv_key = dsa->priv_key;
148
0
  }
149
8
}
150
151
void DSA_get0_pqg(const DSA *dsa, const BIGNUM **out_p, const BIGNUM **out_q,
152
0
                  const BIGNUM **out_g) {
153
0
  if (out_p != NULL) {
154
0
    *out_p = dsa->p;
155
0
  }
156
0
  if (out_q != NULL) {
157
0
    *out_q = dsa->q;
158
0
  }
159
0
  if (out_g != NULL) {
160
0
    *out_g = dsa->g;
161
0
  }
162
0
}
163
164
83
int DSA_set0_key(DSA *dsa, BIGNUM *pub_key, BIGNUM *priv_key) {
165
83
  if (dsa->pub_key == NULL && pub_key == NULL) {
166
0
    return 0;
167
0
  }
168
169
83
  if (pub_key != NULL) {
170
83
    BN_free(dsa->pub_key);
171
83
    dsa->pub_key = pub_key;
172
83
  }
173
83
  if (priv_key != NULL) {
174
22
    BN_free(dsa->priv_key);
175
22
    dsa->priv_key = priv_key;
176
22
  }
177
178
83
  return 1;
179
83
}
180
181
83
int DSA_set0_pqg(DSA *dsa, BIGNUM *p, BIGNUM *q, BIGNUM *g) {
182
83
  if ((dsa->p == NULL && p == NULL) ||
183
83
      (dsa->q == NULL && q == NULL) ||
184
83
      (dsa->g == NULL && g == NULL)) {
185
0
    return 0;
186
0
  }
187
188
83
  if (p != NULL) {
189
83
    BN_free(dsa->p);
190
83
    dsa->p = p;
191
83
  }
192
83
  if (q != NULL) {
193
83
    BN_free(dsa->q);
194
83
    dsa->q = q;
195
83
  }
196
83
  if (g != NULL) {
197
83
    BN_free(dsa->g);
198
83
    dsa->g = g;
199
83
  }
200
201
83
  BN_MONT_CTX_free(dsa->method_mont_p);
202
83
  dsa->method_mont_p = NULL;
203
83
  BN_MONT_CTX_free(dsa->method_mont_q);
204
83
  dsa->method_mont_q = NULL;
205
83
  return 1;
206
83
}
207
208
int DSA_generate_parameters_ex(DSA *dsa, unsigned bits, const uint8_t *seed_in,
209
                               size_t seed_len, int *out_counter,
210
5
                               unsigned long *out_h, BN_GENCB *cb) {
211
5
  if (bits > OPENSSL_DSA_MAX_MODULUS_BITS) {
212
0
    OPENSSL_PUT_ERROR(DSA, DSA_R_INVALID_PARAMETERS);
213
0
    return 0;
214
0
  }
215
216
5
  int ok = 0;
217
5
  unsigned char seed[SHA256_DIGEST_LENGTH];
218
5
  unsigned char md[SHA256_DIGEST_LENGTH];
219
5
  unsigned char buf[SHA256_DIGEST_LENGTH], buf2[SHA256_DIGEST_LENGTH];
220
5
  BIGNUM *r0, *W, *X, *c, *test;
221
5
  BIGNUM *g = NULL, *q = NULL, *p = NULL;
222
5
  BN_MONT_CTX *mont = NULL;
223
5
  int k, n = 0, m = 0;
224
5
  int counter = 0;
225
5
  int r = 0;
226
5
  BN_CTX *ctx = NULL;
227
5
  unsigned int h = 2;
228
5
  const EVP_MD *evpmd;
229
230
5
  evpmd = (bits >= 2048) ? EVP_sha256() : EVP_sha1();
231
5
  size_t qsize = EVP_MD_size(evpmd);
232
233
5
  if (bits < 512) {
234
0
    bits = 512;
235
0
  }
236
237
5
  bits = (bits + 63) / 64 * 64;
238
239
5
  if (seed_in != NULL) {
240
0
    if (seed_len < qsize) {
241
0
      return 0;
242
0
    }
243
0
    if (seed_len > qsize) {
244
      // Only consume as much seed as is expected.
245
0
      seed_len = qsize;
246
0
    }
247
0
    OPENSSL_memcpy(seed, seed_in, seed_len);
248
0
  }
249
250
5
  ctx = BN_CTX_new();
251
5
  if (ctx == NULL) {
252
0
    goto err;
253
0
  }
254
5
  BN_CTX_start(ctx);
255
256
5
  r0 = BN_CTX_get(ctx);
257
5
  g = BN_CTX_get(ctx);
258
5
  W = BN_CTX_get(ctx);
259
5
  q = BN_CTX_get(ctx);
260
5
  X = BN_CTX_get(ctx);
261
5
  c = BN_CTX_get(ctx);
262
5
  p = BN_CTX_get(ctx);
263
5
  test = BN_CTX_get(ctx);
264
265
5
  if (test == NULL || !BN_lshift(test, BN_value_one(), bits - 1)) {
266
0
    goto err;
267
0
  }
268
269
5
  for (;;) {
270
    // Find q.
271
270
    for (;;) {
272
      // step 1
273
270
      if (!BN_GENCB_call(cb, BN_GENCB_GENERATED, m++)) {
274
0
        goto err;
275
0
      }
276
277
270
      int use_random_seed = (seed_in == NULL);
278
270
      if (use_random_seed) {
279
270
        if (!RAND_bytes(seed, qsize)) {
280
0
          goto err;
281
0
        }
282
        // DSA parameters are public.
283
270
        CONSTTIME_DECLASSIFY(seed, qsize);
284
270
      } else {
285
        // If we come back through, use random seed next time.
286
0
        seed_in = NULL;
287
0
      }
288
270
      OPENSSL_memcpy(buf, seed, qsize);
289
270
      OPENSSL_memcpy(buf2, seed, qsize);
290
      // precompute "SEED + 1" for step 7:
291
271
      for (size_t i = qsize - 1; i < qsize; i--) {
292
271
        buf[i]++;
293
271
        if (buf[i] != 0) {
294
270
          break;
295
270
        }
296
271
      }
297
298
      // step 2
299
270
      if (!EVP_Digest(seed, qsize, md, NULL, evpmd, NULL) ||
300
270
          !EVP_Digest(buf, qsize, buf2, NULL, evpmd, NULL)) {
301
0
        goto err;
302
0
      }
303
5.67k
      for (size_t i = 0; i < qsize; i++) {
304
5.40k
        md[i] ^= buf2[i];
305
5.40k
      }
306
307
      // step 3
308
270
      md[0] |= 0x80;
309
270
      md[qsize - 1] |= 0x01;
310
270
      if (!BN_bin2bn(md, qsize, q)) {
311
0
        goto err;
312
0
      }
313
314
      // step 4
315
270
      r = BN_is_prime_fasttest_ex(q, DSS_prime_checks, ctx, use_random_seed, cb);
316
270
      if (r > 0) {
317
5
        break;
318
5
      }
319
265
      if (r != 0) {
320
0
        goto err;
321
0
      }
322
323
      // do a callback call
324
      // step 5
325
265
    }
326
327
5
    if (!BN_GENCB_call(cb, 2, 0) || !BN_GENCB_call(cb, 3, 0)) {
328
0
      goto err;
329
0
    }
330
331
    // step 6
332
5
    counter = 0;
333
    // "offset = 2"
334
335
5
    n = (bits - 1) / 160;
336
337
2.27k
    for (;;) {
338
2.27k
      if ((counter != 0) && !BN_GENCB_call(cb, BN_GENCB_GENERATED, counter)) {
339
0
        goto err;
340
0
      }
341
342
      // step 7
343
2.27k
      BN_zero(W);
344
      // now 'buf' contains "SEED + offset - 1"
345
18.2k
      for (k = 0; k <= n; k++) {
346
        // obtain "SEED + offset + k" by incrementing:
347
15.9k
        for (size_t i = qsize - 1; i < qsize; i--) {
348
15.9k
          buf[i]++;
349
15.9k
          if (buf[i] != 0) {
350
15.9k
            break;
351
15.9k
          }
352
15.9k
        }
353
354
15.9k
        if (!EVP_Digest(buf, qsize, md, NULL, evpmd, NULL)) {
355
0
          goto err;
356
0
        }
357
358
        // step 8
359
15.9k
        if (!BN_bin2bn(md, qsize, r0) ||
360
15.9k
            !BN_lshift(r0, r0, (qsize << 3) * k) ||
361
15.9k
            !BN_add(W, W, r0)) {
362
0
          goto err;
363
0
        }
364
15.9k
      }
365
366
      // more of step 8
367
2.27k
      if (!BN_mask_bits(W, bits - 1) ||
368
2.27k
          !BN_copy(X, W) ||
369
2.27k
          !BN_add(X, X, test)) {
370
0
        goto err;
371
0
      }
372
373
      // step 9
374
2.27k
      if (!BN_lshift1(r0, q) ||
375
2.27k
          !BN_mod(c, X, r0, ctx) ||
376
2.27k
          !BN_sub(r0, c, BN_value_one()) ||
377
2.27k
          !BN_sub(p, X, r0)) {
378
0
        goto err;
379
0
      }
380
381
      // step 10
382
2.27k
      if (BN_cmp(p, test) >= 0) {
383
        // step 11
384
2.27k
        r = BN_is_prime_fasttest_ex(p, DSS_prime_checks, ctx, 1, cb);
385
2.27k
        if (r > 0) {
386
5
          goto end;  // found it
387
5
        }
388
2.27k
        if (r != 0) {
389
0
          goto err;
390
0
        }
391
2.27k
      }
392
393
      // step 13
394
2.27k
      counter++;
395
      // "offset = offset + n + 1"
396
397
      // step 14
398
2.27k
      if (counter >= 4096) {
399
0
        break;
400
0
      }
401
2.27k
    }
402
5
  }
403
5
end:
404
5
  if (!BN_GENCB_call(cb, 2, 1)) {
405
0
    goto err;
406
0
  }
407
408
  // We now need to generate g
409
  // Set r0=(p-1)/q
410
5
  if (!BN_sub(test, p, BN_value_one()) ||
411
5
      !BN_div(r0, NULL, test, q, ctx)) {
412
0
    goto err;
413
0
  }
414
415
5
  mont = BN_MONT_CTX_new_for_modulus(p, ctx);
416
5
  if (mont == NULL ||
417
5
      !BN_set_word(test, h)) {
418
0
    goto err;
419
0
  }
420
421
5
  for (;;) {
422
    // g=test^r0%p
423
5
    if (!BN_mod_exp_mont(g, test, r0, p, ctx, mont)) {
424
0
      goto err;
425
0
    }
426
5
    if (!BN_is_one(g)) {
427
5
      break;
428
5
    }
429
0
    if (!BN_add(test, test, BN_value_one())) {
430
0
      goto err;
431
0
    }
432
0
    h++;
433
0
  }
434
435
5
  if (!BN_GENCB_call(cb, 3, 1)) {
436
0
    goto err;
437
0
  }
438
439
5
  ok = 1;
440
441
5
err:
442
5
  if (ok) {
443
5
    BN_free(dsa->p);
444
5
    BN_free(dsa->q);
445
5
    BN_free(dsa->g);
446
5
    dsa->p = BN_dup(p);
447
5
    dsa->q = BN_dup(q);
448
5
    dsa->g = BN_dup(g);
449
5
    if (dsa->p == NULL || dsa->q == NULL || dsa->g == NULL) {
450
0
      ok = 0;
451
0
      goto err;
452
0
    }
453
5
    if (out_counter != NULL) {
454
0
      *out_counter = counter;
455
0
    }
456
5
    if (out_h != NULL) {
457
0
      *out_h = h;
458
0
    }
459
5
  }
460
461
5
  if (ctx) {
462
5
    BN_CTX_end(ctx);
463
5
    BN_CTX_free(ctx);
464
5
  }
465
466
5
  BN_MONT_CTX_free(mont);
467
468
5
  return ok;
469
5
}
470
471
0
DSA *DSAparams_dup(const DSA *dsa) {
472
0
  DSA *ret = DSA_new();
473
0
  if (ret == NULL) {
474
0
    return NULL;
475
0
  }
476
0
  ret->p = BN_dup(dsa->p);
477
0
  ret->q = BN_dup(dsa->q);
478
0
  ret->g = BN_dup(dsa->g);
479
0
  if (ret->p == NULL || ret->q == NULL || ret->g == NULL) {
480
0
    DSA_free(ret);
481
0
    return NULL;
482
0
  }
483
0
  return ret;
484
0
}
485
486
int DSA_generate_key(DSA *dsa) {
487
  if (!dsa_check_key(dsa)) {
488
    return 0;
489
  }
490
491
  int ok = 0;
492
  BIGNUM *pub_key = NULL, *priv_key = NULL;
493
  BN_CTX *ctx = BN_CTX_new();
494
  if (ctx == NULL) {
495
    goto err;
496
  }
497
498
  priv_key = dsa->priv_key;
499
  if (priv_key == NULL) {
500
    priv_key = BN_new();
501
    if (priv_key == NULL) {
502
      goto err;
503
    }
504
  }
505
506
  if (!BN_rand_range_ex(priv_key, 1, dsa->q)) {
507
    goto err;
508
  }
509
510
  pub_key = dsa->pub_key;
511
  if (pub_key == NULL) {
512
    pub_key = BN_new();
513
    if (pub_key == NULL) {
514
      goto err;
515
    }
516
  }
517
518
  if (!BN_MONT_CTX_set_locked(&dsa->method_mont_p, &dsa->method_mont_lock,
519
                              dsa->p, ctx) ||
520
      !BN_mod_exp_mont_consttime(pub_key, dsa->g, priv_key, dsa->p, ctx,
521
                                 dsa->method_mont_p)) {
522
    goto err;
523
  }
524
525
  // The public key is computed from the private key, but is public.
526
  bn_declassify(pub_key);
527
528
  dsa->priv_key = priv_key;
529
  dsa->pub_key = pub_key;
530
  ok = 1;
531
532
err:
533
  if (dsa->pub_key == NULL) {
534
    BN_free(pub_key);
535
  }
536
  if (dsa->priv_key == NULL) {
537
    BN_free(priv_key);
538
  }
539
  BN_CTX_free(ctx);
540
541
  return ok;
542
}
543
544
622
DSA_SIG *DSA_SIG_new(void) { return OPENSSL_zalloc(sizeof(DSA_SIG)); }
545
546
211
void DSA_SIG_free(DSA_SIG *sig) {
547
211
  if (!sig) {
548
28
    return;
549
28
  }
550
551
183
  BN_free(sig->r);
552
183
  BN_free(sig->s);
553
183
  OPENSSL_free(sig);
554
183
}
555
556
void DSA_SIG_get0(const DSA_SIG *sig, const BIGNUM **out_r,
557
116
                  const BIGNUM **out_s) {
558
116
  if (out_r != NULL) {
559
116
    *out_r = sig->r;
560
116
  }
561
116
  if (out_s != NULL) {
562
116
    *out_s = sig->s;
563
116
  }
564
116
}
565
566
188
int DSA_SIG_set0(DSA_SIG *sig, BIGNUM *r, BIGNUM *s) {
567
188
  if (r == NULL || s == NULL) {
568
0
    return 0;
569
0
  }
570
188
  BN_free(sig->r);
571
188
  BN_free(sig->s);
572
188
  sig->r = r;
573
188
  sig->s = s;
574
188
  return 1;
575
188
}
576
577
// mod_mul_consttime sets |r| to |a| * |b| modulo |mont->N|, treating |a| and
578
// |b| as secret. This function internally uses Montgomery reduction, but
579
// neither inputs nor outputs are in Montgomery form.
580
static int mod_mul_consttime(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
581
0
                             const BN_MONT_CTX *mont, BN_CTX *ctx) {
582
0
  BN_CTX_start(ctx);
583
0
  BIGNUM *tmp = BN_CTX_get(ctx);
584
  // |BN_mod_mul_montgomery| removes a factor of R, so we cancel it with a
585
  // single |BN_to_montgomery| which adds one factor of R.
586
0
  int ok = tmp != NULL &&
587
0
           BN_to_montgomery(tmp, a, mont, ctx) &&
588
0
           BN_mod_mul_montgomery(r, tmp, b, mont, ctx);
589
0
  BN_CTX_end(ctx);
590
0
  return ok;
591
0
}
592
593
22
DSA_SIG *DSA_do_sign(const uint8_t *digest, size_t digest_len, const DSA *dsa) {
594
22
  if (!dsa_check_key(dsa)) {
595
22
    return NULL;
596
22
  }
597
598
0
  if (dsa->priv_key == NULL) {
599
0
    OPENSSL_PUT_ERROR(DSA, DSA_R_MISSING_PARAMETERS);
600
0
    return NULL;
601
0
  }
602
603
0
  BIGNUM *kinv = NULL, *r = NULL, *s = NULL;
604
0
  BIGNUM m;
605
0
  BIGNUM xr;
606
0
  BN_CTX *ctx = NULL;
607
0
  DSA_SIG *ret = NULL;
608
609
0
  BN_init(&m);
610
0
  BN_init(&xr);
611
0
  s = BN_new();
612
0
  if (s == NULL) {
613
0
    goto err;
614
0
  }
615
0
  ctx = BN_CTX_new();
616
0
  if (ctx == NULL) {
617
0
    goto err;
618
0
  }
619
620
  // Cap iterations so that invalid parameters do not infinite loop. This does
621
  // not impact valid parameters because the probability of requiring even one
622
  // retry is negligible, let alone 32. Unfortunately, DSA was mis-specified, so
623
  // invalid parameters are reachable from most callers handling untrusted
624
  // private keys. (The |dsa_check_key| call above is not sufficient. Checking
625
  // whether arbitrary paremeters form a valid DSA group is expensive.)
626
0
  static const int kMaxIterations = 32;
627
0
  int iters = 0;
628
0
redo:
629
0
  if (!dsa_sign_setup(dsa, ctx, &kinv, &r)) {
630
0
    goto err;
631
0
  }
632
633
0
  if (digest_len > BN_num_bytes(dsa->q)) {
634
    // If the digest length is greater than the size of |dsa->q| use the
635
    // BN_num_bits(dsa->q) leftmost bits of the digest, see FIPS 186-3, 4.2.
636
    // Note the above check that |dsa->q| is a multiple of 8 bits.
637
0
    digest_len = BN_num_bytes(dsa->q);
638
0
  }
639
640
0
  if (BN_bin2bn(digest, digest_len, &m) == NULL) {
641
0
    goto err;
642
0
  }
643
644
  // |m| is bounded by 2^(num_bits(q)), which is slightly looser than q. This
645
  // violates |bn_mod_add_consttime| and |mod_mul_consttime|'s preconditions.
646
  // (The underlying algorithms could accept looser bounds, but we reduce for
647
  // simplicity.)
648
0
  size_t q_width = bn_minimal_width(dsa->q);
649
0
  if (!bn_resize_words(&m, q_width) ||
650
0
      !bn_resize_words(&xr, q_width)) {
651
0
    goto err;
652
0
  }
653
0
  bn_reduce_once_in_place(m.d, 0 /* no carry word */, dsa->q->d,
654
0
                          xr.d /* scratch space */, q_width);
655
656
  // Compute s = inv(k) (m + xr) mod q. Note |dsa->method_mont_q| is
657
  // initialized by |dsa_sign_setup|.
658
0
  if (!mod_mul_consttime(&xr, dsa->priv_key, r, dsa->method_mont_q, ctx) ||
659
0
      !bn_mod_add_consttime(s, &xr, &m, dsa->q, ctx) ||
660
0
      !mod_mul_consttime(s, s, kinv, dsa->method_mont_q, ctx)) {
661
0
    goto err;
662
0
  }
663
664
  // The signature is computed from the private key, but is public.
665
0
  bn_declassify(r);
666
0
  bn_declassify(s);
667
668
  // Redo if r or s is zero as required by FIPS 186-3: this is
669
  // very unlikely.
670
0
  if (BN_is_zero(r) || BN_is_zero(s)) {
671
0
    iters++;
672
0
    if (iters > kMaxIterations) {
673
0
      OPENSSL_PUT_ERROR(DSA, DSA_R_TOO_MANY_ITERATIONS);
674
0
      goto err;
675
0
    }
676
0
    goto redo;
677
0
  }
678
679
0
  ret = DSA_SIG_new();
680
0
  if (ret == NULL) {
681
0
    goto err;
682
0
  }
683
0
  ret->r = r;
684
0
  ret->s = s;
685
686
0
err:
687
0
  if (ret == NULL) {
688
0
    OPENSSL_PUT_ERROR(DSA, ERR_R_BN_LIB);
689
0
    BN_free(r);
690
0
    BN_free(s);
691
0
  }
692
0
  BN_CTX_free(ctx);
693
0
  BN_clear_free(&m);
694
0
  BN_clear_free(&xr);
695
0
  BN_clear_free(kinv);
696
697
0
  return ret;
698
0
}
699
700
int DSA_do_verify(const uint8_t *digest, size_t digest_len, const DSA_SIG *sig,
701
                  const DSA *dsa) {
702
  int valid;
703
  if (!DSA_do_check_signature(&valid, digest, digest_len, sig, dsa)) {
704
    return -1;
705
  }
706
  return valid;
707
}
708
709
int DSA_do_check_signature(int *out_valid, const uint8_t *digest,
710
                           size_t digest_len, const DSA_SIG *sig,
711
61
                           const DSA *dsa) {
712
61
  *out_valid = 0;
713
61
  if (!dsa_check_key(dsa)) {
714
58
    return 0;
715
58
  }
716
717
3
  if (dsa->pub_key == NULL) {
718
0
    OPENSSL_PUT_ERROR(DSA, DSA_R_MISSING_PARAMETERS);
719
0
    return 0;
720
0
  }
721
722
3
  int ret = 0;
723
3
  BIGNUM u1, u2, t1;
724
3
  BN_init(&u1);
725
3
  BN_init(&u2);
726
3
  BN_init(&t1);
727
3
  BN_CTX *ctx = BN_CTX_new();
728
3
  if (ctx == NULL) {
729
0
    goto err;
730
0
  }
731
732
3
  if (BN_is_zero(sig->r) || BN_is_negative(sig->r) ||
733
3
      BN_ucmp(sig->r, dsa->q) >= 0) {
734
2
    ret = 1;
735
2
    goto err;
736
2
  }
737
1
  if (BN_is_zero(sig->s) || BN_is_negative(sig->s) ||
738
1
      BN_ucmp(sig->s, dsa->q) >= 0) {
739
1
    ret = 1;
740
1
    goto err;
741
1
  }
742
743
  // Calculate W = inv(S) mod Q
744
  // save W in u2
745
0
  if (BN_mod_inverse(&u2, sig->s, dsa->q, ctx) == NULL) {
746
0
    goto err;
747
0
  }
748
749
  // save M in u1
750
0
  unsigned q_bits = BN_num_bits(dsa->q);
751
0
  if (digest_len > (q_bits >> 3)) {
752
    // if the digest length is greater than the size of q use the
753
    // BN_num_bits(dsa->q) leftmost bits of the digest, see
754
    // fips 186-3, 4.2
755
0
    digest_len = (q_bits >> 3);
756
0
  }
757
758
0
  if (BN_bin2bn(digest, digest_len, &u1) == NULL) {
759
0
    goto err;
760
0
  }
761
762
  // u1 = M * w mod q
763
0
  if (!BN_mod_mul(&u1, &u1, &u2, dsa->q, ctx)) {
764
0
    goto err;
765
0
  }
766
767
  // u2 = r * w mod q
768
0
  if (!BN_mod_mul(&u2, sig->r, &u2, dsa->q, ctx)) {
769
0
    goto err;
770
0
  }
771
772
0
  if (!BN_MONT_CTX_set_locked((BN_MONT_CTX **)&dsa->method_mont_p,
773
0
                              (CRYPTO_MUTEX *)&dsa->method_mont_lock, dsa->p,
774
0
                              ctx)) {
775
0
    goto err;
776
0
  }
777
778
0
  if (!BN_mod_exp2_mont(&t1, dsa->g, &u1, dsa->pub_key, &u2, dsa->p, ctx,
779
0
                        dsa->method_mont_p)) {
780
0
    goto err;
781
0
  }
782
783
  // BN_copy(&u1,&t1);
784
  // let u1 = u1 mod q
785
0
  if (!BN_mod(&u1, &t1, dsa->q, ctx)) {
786
0
    goto err;
787
0
  }
788
789
  // V is now in u1.  If the signature is correct, it will be
790
  // equal to R.
791
0
  *out_valid = BN_ucmp(&u1, sig->r) == 0;
792
0
  ret = 1;
793
794
3
err:
795
3
  if (ret != 1) {
796
0
    OPENSSL_PUT_ERROR(DSA, ERR_R_BN_LIB);
797
0
  }
798
3
  BN_CTX_free(ctx);
799
3
  BN_free(&u1);
800
3
  BN_free(&u2);
801
3
  BN_free(&t1);
802
803
3
  return ret;
804
0
}
805
806
int DSA_sign(int type, const uint8_t *digest, size_t digest_len,
807
22
             uint8_t *out_sig, unsigned int *out_siglen, const DSA *dsa) {
808
22
  DSA_SIG *s;
809
810
22
  s = DSA_do_sign(digest, digest_len, dsa);
811
22
  if (s == NULL) {
812
22
    *out_siglen = 0;
813
22
    return 0;
814
22
  }
815
816
0
  *out_siglen = i2d_DSA_SIG(s, &out_sig);
817
0
  DSA_SIG_free(s);
818
0
  return 1;
819
22
}
820
821
int DSA_verify(int type, const uint8_t *digest, size_t digest_len,
822
61
               const uint8_t *sig, size_t sig_len, const DSA *dsa) {
823
61
  int valid;
824
61
  if (!DSA_check_signature(&valid, digest, digest_len, sig, sig_len, dsa)) {
825
58
    return -1;
826
58
  }
827
3
  return valid;
828
61
}
829
830
int DSA_check_signature(int *out_valid, const uint8_t *digest,
831
                        size_t digest_len, const uint8_t *sig, size_t sig_len,
832
61
                        const DSA *dsa) {
833
61
  DSA_SIG *s = NULL;
834
61
  int ret = 0;
835
61
  uint8_t *der = NULL;
836
837
61
  s = DSA_SIG_new();
838
61
  if (s == NULL) {
839
0
    goto err;
840
0
  }
841
842
61
  const uint8_t *sigp = sig;
843
61
  if (d2i_DSA_SIG(&s, &sigp, sig_len) == NULL || sigp != sig + sig_len) {
844
0
    goto err;
845
0
  }
846
847
  // Ensure that the signature uses DER and doesn't have trailing garbage.
848
61
  int der_len = i2d_DSA_SIG(s, &der);
849
61
  if (der_len < 0 || (size_t)der_len != sig_len ||
850
61
      OPENSSL_memcmp(sig, der, sig_len)) {
851
0
    goto err;
852
0
  }
853
854
61
  ret = DSA_do_check_signature(out_valid, digest, digest_len, s, dsa);
855
856
61
err:
857
61
  OPENSSL_free(der);
858
61
  DSA_SIG_free(s);
859
61
  return ret;
860
61
}
861
862
// der_len_len returns the number of bytes needed to represent a length of |len|
863
// in DER.
864
44
static size_t der_len_len(size_t len) {
865
44
  if (len < 0x80) {
866
24
    return 1;
867
24
  }
868
20
  size_t ret = 1;
869
56
  while (len > 0) {
870
36
    ret++;
871
36
    len >>= 8;
872
36
  }
873
20
  return ret;
874
44
}
875
876
22
int DSA_size(const DSA *dsa) {
877
22
  if (dsa->q == NULL) {
878
0
    return 0;
879
0
  }
880
881
22
  size_t order_len = BN_num_bytes(dsa->q);
882
  // Compute the maximum length of an |order_len| byte integer. Defensively
883
  // assume that the leading 0x00 is included.
884
22
  size_t integer_len = 1 /* tag */ + der_len_len(order_len + 1) + 1 + order_len;
885
22
  if (integer_len < order_len) {
886
0
    return 0;
887
0
  }
888
  // A DSA signature is two INTEGERs.
889
22
  size_t value_len = 2 * integer_len;
890
22
  if (value_len < integer_len) {
891
0
    return 0;
892
0
  }
893
  // Add the header.
894
22
  size_t ret = 1 /* tag */ + der_len_len(value_len) + value_len;
895
22
  if (ret < value_len) {
896
0
    return 0;
897
0
  }
898
22
  return ret;
899
22
}
900
901
static int dsa_sign_setup(const DSA *dsa, BN_CTX *ctx, BIGNUM **out_kinv,
902
0
                          BIGNUM **out_r) {
903
0
  int ret = 0;
904
0
  BIGNUM k;
905
0
  BN_init(&k);
906
0
  BIGNUM *r = BN_new();
907
0
  BIGNUM *kinv = BN_new();
908
0
  if (r == NULL || kinv == NULL ||
909
      // Get random k
910
0
      !BN_rand_range_ex(&k, 1, dsa->q) ||
911
0
      !BN_MONT_CTX_set_locked((BN_MONT_CTX **)&dsa->method_mont_p,
912
0
                              (CRYPTO_MUTEX *)&dsa->method_mont_lock, dsa->p,
913
0
                              ctx) ||
914
0
      !BN_MONT_CTX_set_locked((BN_MONT_CTX **)&dsa->method_mont_q,
915
0
                              (CRYPTO_MUTEX *)&dsa->method_mont_lock, dsa->q,
916
0
                              ctx) ||
917
      // Compute r = (g^k mod p) mod q
918
0
      !BN_mod_exp_mont_consttime(r, dsa->g, &k, dsa->p, ctx,
919
0
                                 dsa->method_mont_p)) {
920
0
    OPENSSL_PUT_ERROR(DSA, ERR_R_BN_LIB);
921
0
    goto err;
922
0
  }
923
  // Note |BN_mod| below is not constant-time and may leak information about
924
  // |r|. |dsa->p| may be significantly larger than |dsa->q|, so this is not
925
  // easily performed in constant-time with Montgomery reduction.
926
  //
927
  // However, |r| at this point is g^k (mod p). It is almost the value of |r|
928
  // revealed in the signature anyway (g^k (mod p) (mod q)), going from it to
929
  // |k| would require computing a discrete log.
930
0
  bn_declassify(r);
931
0
  if (!BN_mod(r, r, dsa->q, ctx) ||
932
      // Compute part of 's = inv(k) (m + xr) mod q' using Fermat's Little
933
      // Theorem.
934
0
      !bn_mod_inverse_prime(kinv, &k, dsa->q, ctx, dsa->method_mont_q)) {
935
0
    OPENSSL_PUT_ERROR(DSA, ERR_R_BN_LIB);
936
0
    goto err;
937
0
  }
938
939
0
  BN_clear_free(*out_kinv);
940
0
  *out_kinv = kinv;
941
0
  kinv = NULL;
942
943
0
  BN_clear_free(*out_r);
944
0
  *out_r = r;
945
0
  r = NULL;
946
947
0
  ret = 1;
948
949
0
err:
950
0
  BN_clear_free(&k);
951
0
  BN_clear_free(r);
952
0
  BN_clear_free(kinv);
953
0
  return ret;
954
0
}
955
956
int DSA_get_ex_new_index(long argl, void *argp, CRYPTO_EX_unused *unused,
957
0
                         CRYPTO_EX_dup *dup_unused, CRYPTO_EX_free *free_func) {
958
0
  return CRYPTO_get_ex_new_index_ex(&g_ex_data_class, argl, argp, free_func);
959
0
}
960
961
0
int DSA_set_ex_data(DSA *dsa, int idx, void *arg) {
962
0
  return CRYPTO_set_ex_data(&dsa->ex_data, idx, arg);
963
0
}
964
965
0
void *DSA_get_ex_data(const DSA *dsa, int idx) {
966
0
  return CRYPTO_get_ex_data(&dsa->ex_data, idx);
967
0
}
968
969
0
DH *DSA_dup_DH(const DSA *dsa) {
970
0
  if (dsa == NULL) {
971
0
    return NULL;
972
0
  }
973
974
0
  DH *ret = DH_new();
975
0
  if (ret == NULL) {
976
0
    goto err;
977
0
  }
978
0
  if (dsa->q != NULL) {
979
0
    ret->priv_length = BN_num_bits(dsa->q);
980
0
    if ((ret->q = BN_dup(dsa->q)) == NULL) {
981
0
      goto err;
982
0
    }
983
0
  }
984
0
  if ((dsa->p != NULL && (ret->p = BN_dup(dsa->p)) == NULL) ||
985
0
      (dsa->g != NULL && (ret->g = BN_dup(dsa->g)) == NULL) ||
986
0
      (dsa->pub_key != NULL && (ret->pub_key = BN_dup(dsa->pub_key)) == NULL) ||
987
0
      (dsa->priv_key != NULL &&
988
0
       (ret->priv_key = BN_dup(dsa->priv_key)) == NULL)) {
989
0
    goto err;
990
0
  }
991
992
0
  return ret;
993
994
0
err:
995
0
  DH_free(ret);
996
0
  return NULL;
997
0
}