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