Coverage Report

Created: 2025-11-03 06:30

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