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