Coverage Report

Created: 2025-06-11 06:40

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