Coverage Report

Created: 2026-02-14 06:34

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