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 "../internal.h"
78 
79 
80 // Primality test according to FIPS PUB 186[-1], Appendix 2.1: 50 rounds of
81 // Miller-Rabin.
82 #define DSS_prime_checks 50
83 
84 static int dsa_sign_setup(const DSA *dsa, BN_CTX *ctx_in, BIGNUM **out_kinv,
85                           BIGNUM **out_r);
86 
87 static CRYPTO_EX_DATA_CLASS g_ex_data_class = CRYPTO_EX_DATA_CLASS_INIT;
88 
DSA_new(void)89 DSA *DSA_new(void) {
90   DSA *dsa = OPENSSL_malloc(sizeof(DSA));
91   if (dsa == NULL) {
92     OPENSSL_PUT_ERROR(DSA, ERR_R_MALLOC_FAILURE);
93     return NULL;
94   }
95 
96   OPENSSL_memset(dsa, 0, sizeof(DSA));
97 
98   dsa->references = 1;
99 
100   CRYPTO_MUTEX_init(&dsa->method_mont_lock);
101   CRYPTO_new_ex_data(&dsa->ex_data);
102 
103   return dsa;
104 }
105 
DSA_free(DSA * dsa)106 void DSA_free(DSA *dsa) {
107   if (dsa == NULL) {
108     return;
109   }
110 
111   if (!CRYPTO_refcount_dec_and_test_zero(&dsa->references)) {
112     return;
113   }
114 
115   CRYPTO_free_ex_data(&g_ex_data_class, dsa, &dsa->ex_data);
116 
117   BN_clear_free(dsa->p);
118   BN_clear_free(dsa->q);
119   BN_clear_free(dsa->g);
120   BN_clear_free(dsa->pub_key);
121   BN_clear_free(dsa->priv_key);
122   BN_MONT_CTX_free(dsa->method_mont_p);
123   BN_MONT_CTX_free(dsa->method_mont_q);
124   CRYPTO_MUTEX_cleanup(&dsa->method_mont_lock);
125   OPENSSL_free(dsa);
126 }
127 
DSA_up_ref(DSA * dsa)128 int DSA_up_ref(DSA *dsa) {
129   CRYPTO_refcount_inc(&dsa->references);
130   return 1;
131 }
132 
DSA_get0_pub_key(const DSA * dsa)133 const BIGNUM *DSA_get0_pub_key(const DSA *dsa) { return dsa->pub_key; }
134 
DSA_get0_priv_key(const DSA * dsa)135 const BIGNUM *DSA_get0_priv_key(const DSA *dsa) { return dsa->priv_key; }
136 
DSA_get0_p(const DSA * dsa)137 const BIGNUM *DSA_get0_p(const DSA *dsa) { return dsa->p; }
138 
DSA_get0_q(const DSA * dsa)139 const BIGNUM *DSA_get0_q(const DSA *dsa) { return dsa->q; }
140 
DSA_get0_g(const DSA * dsa)141 const BIGNUM *DSA_get0_g(const DSA *dsa) { return dsa->g; }
142 
DSA_get0_key(const DSA * dsa,const BIGNUM ** out_pub_key,const BIGNUM ** out_priv_key)143 void DSA_get0_key(const DSA *dsa, const BIGNUM **out_pub_key,
144                   const BIGNUM **out_priv_key) {
145   if (out_pub_key != NULL) {
146     *out_pub_key = dsa->pub_key;
147   }
148   if (out_priv_key != NULL) {
149     *out_priv_key = dsa->priv_key;
150   }
151 }
152 
DSA_get0_pqg(const DSA * dsa,const BIGNUM ** out_p,const BIGNUM ** out_q,const BIGNUM ** out_g)153 void DSA_get0_pqg(const DSA *dsa, const BIGNUM **out_p, const BIGNUM **out_q,
154                   const BIGNUM **out_g) {
155   if (out_p != NULL) {
156     *out_p = dsa->p;
157   }
158   if (out_q != NULL) {
159     *out_q = dsa->q;
160   }
161   if (out_g != NULL) {
162     *out_g = dsa->g;
163   }
164 }
165 
DSA_set0_key(DSA * dsa,BIGNUM * pub_key,BIGNUM * priv_key)166 int DSA_set0_key(DSA *dsa, BIGNUM *pub_key, BIGNUM *priv_key) {
167   if (dsa->pub_key == NULL && pub_key == NULL) {
168     return 0;
169   }
170 
171   if (pub_key != NULL) {
172     BN_free(dsa->pub_key);
173     dsa->pub_key = pub_key;
174   }
175   if (priv_key != NULL) {
176     BN_free(dsa->priv_key);
177     dsa->priv_key = priv_key;
178   }
179 
180   return 1;
181 }
182 
DSA_set0_pqg(DSA * dsa,BIGNUM * p,BIGNUM * q,BIGNUM * g)183 int DSA_set0_pqg(DSA *dsa, BIGNUM *p, BIGNUM *q, BIGNUM *g) {
184   if ((dsa->p == NULL && p == NULL) ||
185       (dsa->q == NULL && q == NULL) ||
186       (dsa->g == NULL && g == NULL)) {
187     return 0;
188   }
189 
190   if (p != NULL) {
191     BN_free(dsa->p);
192     dsa->p = p;
193   }
194   if (q != NULL) {
195     BN_free(dsa->q);
196     dsa->q = q;
197   }
198   if (g != NULL) {
199     BN_free(dsa->g);
200     dsa->g = g;
201   }
202 
203   return 1;
204 }
205 
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)206 int DSA_generate_parameters_ex(DSA *dsa, unsigned bits, const uint8_t *seed_in,
207                                size_t seed_len, int *out_counter,
208                                unsigned long *out_h, BN_GENCB *cb) {
209   int ok = 0;
210   unsigned char seed[SHA256_DIGEST_LENGTH];
211   unsigned char md[SHA256_DIGEST_LENGTH];
212   unsigned char buf[SHA256_DIGEST_LENGTH], buf2[SHA256_DIGEST_LENGTH];
213   BIGNUM *r0, *W, *X, *c, *test;
214   BIGNUM *g = NULL, *q = NULL, *p = NULL;
215   BN_MONT_CTX *mont = NULL;
216   int k, n = 0, m = 0;
217   unsigned i;
218   int counter = 0;
219   int r = 0;
220   BN_CTX *ctx = NULL;
221   unsigned int h = 2;
222   unsigned qsize;
223   const EVP_MD *evpmd;
224 
225   evpmd = (bits >= 2048) ? EVP_sha256() : EVP_sha1();
226   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 < (size_t)qsize) {
236       return 0;
237     }
238     if (seed_len > (size_t)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       } else {
278         // If we come back through, use random seed next time.
279         seed_in = NULL;
280       }
281       OPENSSL_memcpy(buf, seed, qsize);
282       OPENSSL_memcpy(buf2, seed, qsize);
283       // precompute "SEED + 1" for step 7:
284       for (i = qsize - 1; i < qsize; i--) {
285         buf[i]++;
286         if (buf[i] != 0) {
287           break;
288         }
289       }
290 
291       // step 2
292       if (!EVP_Digest(seed, qsize, md, NULL, evpmd, NULL) ||
293           !EVP_Digest(buf, qsize, buf2, NULL, evpmd, NULL)) {
294         goto err;
295       }
296       for (i = 0; i < qsize; i++) {
297         md[i] ^= buf2[i];
298       }
299 
300       // step 3
301       md[0] |= 0x80;
302       md[qsize - 1] |= 0x01;
303       if (!BN_bin2bn(md, qsize, q)) {
304         goto err;
305       }
306 
307       // step 4
308       r = BN_is_prime_fasttest_ex(q, DSS_prime_checks, ctx, use_random_seed, cb);
309       if (r > 0) {
310         break;
311       }
312       if (r != 0) {
313         goto err;
314       }
315 
316       // do a callback call
317       // step 5
318     }
319 
320     if (!BN_GENCB_call(cb, 2, 0) || !BN_GENCB_call(cb, 3, 0)) {
321       goto err;
322     }
323 
324     // step 6
325     counter = 0;
326     // "offset = 2"
327 
328     n = (bits - 1) / 160;
329 
330     for (;;) {
331       if ((counter != 0) && !BN_GENCB_call(cb, BN_GENCB_GENERATED, counter)) {
332         goto err;
333       }
334 
335       // step 7
336       BN_zero(W);
337       // now 'buf' contains "SEED + offset - 1"
338       for (k = 0; k <= n; k++) {
339         // obtain "SEED + offset + k" by incrementing:
340         for (i = qsize - 1; i < qsize; i--) {
341           buf[i]++;
342           if (buf[i] != 0) {
343             break;
344           }
345         }
346 
347         if (!EVP_Digest(buf, qsize, md, NULL, evpmd, NULL)) {
348           goto err;
349         }
350 
351         // step 8
352         if (!BN_bin2bn(md, qsize, r0) ||
353             !BN_lshift(r0, r0, (qsize << 3) * k) ||
354             !BN_add(W, W, r0)) {
355           goto err;
356         }
357       }
358 
359       // more of step 8
360       if (!BN_mask_bits(W, bits - 1) ||
361           !BN_copy(X, W) ||
362           !BN_add(X, X, test)) {
363         goto err;
364       }
365 
366       // step 9
367       if (!BN_lshift1(r0, q) ||
368           !BN_mod(c, X, r0, ctx) ||
369           !BN_sub(r0, c, BN_value_one()) ||
370           !BN_sub(p, X, r0)) {
371         goto err;
372       }
373 
374       // step 10
375       if (BN_cmp(p, test) >= 0) {
376         // step 11
377         r = BN_is_prime_fasttest_ex(p, DSS_prime_checks, ctx, 1, cb);
378         if (r > 0) {
379           goto end;  // found it
380         }
381         if (r != 0) {
382           goto err;
383         }
384       }
385 
386       // step 13
387       counter++;
388       // "offset = offset + n + 1"
389 
390       // step 14
391       if (counter >= 4096) {
392         break;
393       }
394     }
395   }
396 end:
397   if (!BN_GENCB_call(cb, 2, 1)) {
398     goto err;
399   }
400 
401   // We now need to generate g
402   // Set r0=(p-1)/q
403   if (!BN_sub(test, p, BN_value_one()) ||
404       !BN_div(r0, NULL, test, q, ctx)) {
405     goto err;
406   }
407 
408   mont = BN_MONT_CTX_new_for_modulus(p, ctx);
409   if (mont == NULL ||
410       !BN_set_word(test, h)) {
411     goto err;
412   }
413 
414   for (;;) {
415     // g=test^r0%p
416     if (!BN_mod_exp_mont(g, test, r0, p, ctx, mont)) {
417       goto err;
418     }
419     if (!BN_is_one(g)) {
420       break;
421     }
422     if (!BN_add(test, test, BN_value_one())) {
423       goto err;
424     }
425     h++;
426   }
427 
428   if (!BN_GENCB_call(cb, 3, 1)) {
429     goto err;
430   }
431 
432   ok = 1;
433 
434 err:
435   if (ok) {
436     BN_free(dsa->p);
437     BN_free(dsa->q);
438     BN_free(dsa->g);
439     dsa->p = BN_dup(p);
440     dsa->q = BN_dup(q);
441     dsa->g = BN_dup(g);
442     if (dsa->p == NULL || dsa->q == NULL || dsa->g == NULL) {
443       ok = 0;
444       goto err;
445     }
446     if (out_counter != NULL) {
447       *out_counter = counter;
448     }
449     if (out_h != NULL) {
450       *out_h = h;
451     }
452   }
453 
454   if (ctx) {
455     BN_CTX_end(ctx);
456     BN_CTX_free(ctx);
457   }
458 
459   BN_MONT_CTX_free(mont);
460 
461   return ok;
462 }
463 
DSAparams_dup(const DSA * dsa)464 DSA *DSAparams_dup(const DSA *dsa) {
465   DSA *ret = DSA_new();
466   if (ret == NULL) {
467     return NULL;
468   }
469   ret->p = BN_dup(dsa->p);
470   ret->q = BN_dup(dsa->q);
471   ret->g = BN_dup(dsa->g);
472   if (ret->p == NULL || ret->q == NULL || ret->g == NULL) {
473     DSA_free(ret);
474     return NULL;
475   }
476   return ret;
477 }
478 
DSA_generate_key(DSA * dsa)479 int DSA_generate_key(DSA *dsa) {
480   int ok = 0;
481   BN_CTX *ctx = NULL;
482   BIGNUM *pub_key = NULL, *priv_key = NULL;
483 
484   ctx = BN_CTX_new();
485   if (ctx == NULL) {
486     goto err;
487   }
488 
489   priv_key = dsa->priv_key;
490   if (priv_key == NULL) {
491     priv_key = BN_new();
492     if (priv_key == NULL) {
493       goto err;
494     }
495   }
496 
497   if (!BN_rand_range_ex(priv_key, 1, dsa->q)) {
498     goto err;
499   }
500 
501   pub_key = dsa->pub_key;
502   if (pub_key == NULL) {
503     pub_key = BN_new();
504     if (pub_key == NULL) {
505       goto err;
506     }
507   }
508 
509   if (!BN_MONT_CTX_set_locked(&dsa->method_mont_p, &dsa->method_mont_lock,
510                               dsa->p, ctx) ||
511       !BN_mod_exp_mont_consttime(pub_key, dsa->g, priv_key, dsa->p, ctx,
512                                  dsa->method_mont_p)) {
513     goto err;
514   }
515 
516   dsa->priv_key = priv_key;
517   dsa->pub_key = pub_key;
518   ok = 1;
519 
520 err:
521   if (dsa->pub_key == NULL) {
522     BN_free(pub_key);
523   }
524   if (dsa->priv_key == NULL) {
525     BN_free(priv_key);
526   }
527   BN_CTX_free(ctx);
528 
529   return ok;
530 }
531 
DSA_SIG_new(void)532 DSA_SIG *DSA_SIG_new(void) {
533   DSA_SIG *sig;
534   sig = OPENSSL_malloc(sizeof(DSA_SIG));
535   if (!sig) {
536     return NULL;
537   }
538   sig->r = NULL;
539   sig->s = NULL;
540   return sig;
541 }
542 
DSA_SIG_free(DSA_SIG * sig)543 void DSA_SIG_free(DSA_SIG *sig) {
544   if (!sig) {
545     return;
546   }
547 
548   BN_free(sig->r);
549   BN_free(sig->s);
550   OPENSSL_free(sig);
551 }
552 
553 // mod_mul_consttime sets |r| to |a| * |b| modulo |mont->N|, treating |a| and
554 // |b| as secret. This function internally uses Montgomery reduction, but
555 // 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)556 static int mod_mul_consttime(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
557                              const BN_MONT_CTX *mont, BN_CTX *ctx) {
558   BN_CTX_start(ctx);
559   BIGNUM *tmp = BN_CTX_get(ctx);
560   // |BN_mod_mul_montgomery| removes a factor of R, so we cancel it with a
561   // single |BN_to_montgomery| which adds one factor of R.
562   int ok = tmp != NULL &&
563            BN_to_montgomery(tmp, a, mont, ctx) &&
564            BN_mod_mul_montgomery(r, tmp, b, mont, ctx);
565   BN_CTX_end(ctx);
566   return ok;
567 }
568 
DSA_do_sign(const uint8_t * digest,size_t digest_len,const DSA * dsa)569 DSA_SIG *DSA_do_sign(const uint8_t *digest, size_t digest_len, const DSA *dsa) {
570   if (!dsa_check_parameters(dsa)) {
571     return NULL;
572   }
573 
574   BIGNUM *kinv = NULL, *r = NULL, *s = NULL;
575   BIGNUM m;
576   BIGNUM xr;
577   BN_CTX *ctx = NULL;
578   DSA_SIG *ret = NULL;
579 
580   BN_init(&m);
581   BN_init(&xr);
582   s = BN_new();
583   if (s == NULL) {
584     goto err;
585   }
586   ctx = BN_CTX_new();
587   if (ctx == NULL) {
588     goto err;
589   }
590 
591 redo:
592   if (!dsa_sign_setup(dsa, ctx, &kinv, &r)) {
593     goto err;
594   }
595 
596   if (digest_len > BN_num_bytes(dsa->q)) {
597     // If the digest length is greater than the size of |dsa->q| use the
598     // BN_num_bits(dsa->q) leftmost bits of the digest, see FIPS 186-3, 4.2.
599     // Note the above check that |dsa->q| is a multiple of 8 bits.
600     digest_len = BN_num_bytes(dsa->q);
601   }
602 
603   if (BN_bin2bn(digest, digest_len, &m) == NULL) {
604     goto err;
605   }
606 
607   // |m| is bounded by 2^(num_bits(q)), which is slightly looser than q. This
608   // violates |bn_mod_add_consttime| and |mod_mul_consttime|'s preconditions.
609   // (The underlying algorithms could accept looser bounds, but we reduce for
610   // simplicity.)
611   size_t q_width = bn_minimal_width(dsa->q);
612   if (!bn_resize_words(&m, q_width) ||
613       !bn_resize_words(&xr, q_width)) {
614     goto err;
615   }
616   bn_reduce_once_in_place(m.d, 0 /* no carry word */, dsa->q->d,
617                           xr.d /* scratch space */, q_width);
618 
619   // Compute s = inv(k) (m + xr) mod q. Note |dsa->method_mont_q| is
620   // initialized by |dsa_sign_setup|.
621   if (!mod_mul_consttime(&xr, dsa->priv_key, r, dsa->method_mont_q, ctx) ||
622       !bn_mod_add_consttime(s, &xr, &m, dsa->q, ctx) ||
623       !mod_mul_consttime(s, s, kinv, dsa->method_mont_q, ctx)) {
624     goto err;
625   }
626 
627   // Redo if r or s is zero as required by FIPS 186-3: this is
628   // very unlikely.
629   if (BN_is_zero(r) || BN_is_zero(s)) {
630     goto redo;
631   }
632   ret = DSA_SIG_new();
633   if (ret == NULL) {
634     goto err;
635   }
636   ret->r = r;
637   ret->s = s;
638 
639 err:
640   if (ret == NULL) {
641     OPENSSL_PUT_ERROR(DSA, ERR_R_BN_LIB);
642     BN_free(r);
643     BN_free(s);
644   }
645   BN_CTX_free(ctx);
646   BN_clear_free(&m);
647   BN_clear_free(&xr);
648   BN_clear_free(kinv);
649 
650   return ret;
651 }
652 
DSA_do_verify(const uint8_t * digest,size_t digest_len,DSA_SIG * sig,const DSA * dsa)653 int DSA_do_verify(const uint8_t *digest, size_t digest_len, DSA_SIG *sig,
654                   const DSA *dsa) {
655   int valid;
656   if (!DSA_do_check_signature(&valid, digest, digest_len, sig, dsa)) {
657     return -1;
658   }
659   return valid;
660 }
661 
DSA_do_check_signature(int * out_valid,const uint8_t * digest,size_t digest_len,DSA_SIG * sig,const DSA * dsa)662 int DSA_do_check_signature(int *out_valid, const uint8_t *digest,
663                            size_t digest_len, DSA_SIG *sig, const DSA *dsa) {
664   *out_valid = 0;
665   if (!dsa_check_parameters(dsa)) {
666     return 0;
667   }
668 
669   int ret = 0;
670   BIGNUM u1, u2, t1;
671   BN_init(&u1);
672   BN_init(&u2);
673   BN_init(&t1);
674   BN_CTX *ctx = BN_CTX_new();
675   if (ctx == NULL) {
676     goto err;
677   }
678 
679   if (BN_is_zero(sig->r) || BN_is_negative(sig->r) ||
680       BN_ucmp(sig->r, dsa->q) >= 0) {
681     ret = 1;
682     goto err;
683   }
684   if (BN_is_zero(sig->s) || BN_is_negative(sig->s) ||
685       BN_ucmp(sig->s, dsa->q) >= 0) {
686     ret = 1;
687     goto err;
688   }
689 
690   // Calculate W = inv(S) mod Q
691   // save W in u2
692   if (BN_mod_inverse(&u2, sig->s, dsa->q, ctx) == NULL) {
693     goto err;
694   }
695 
696   // save M in u1
697   unsigned q_bits = BN_num_bits(dsa->q);
698   if (digest_len > (q_bits >> 3)) {
699     // if the digest length is greater than the size of q use the
700     // BN_num_bits(dsa->q) leftmost bits of the digest, see
701     // fips 186-3, 4.2
702     digest_len = (q_bits >> 3);
703   }
704 
705   if (BN_bin2bn(digest, digest_len, &u1) == NULL) {
706     goto err;
707   }
708 
709   // u1 = M * w mod q
710   if (!BN_mod_mul(&u1, &u1, &u2, dsa->q, ctx)) {
711     goto err;
712   }
713 
714   // u2 = r * w mod q
715   if (!BN_mod_mul(&u2, sig->r, &u2, dsa->q, ctx)) {
716     goto err;
717   }
718 
719   if (!BN_MONT_CTX_set_locked((BN_MONT_CTX **)&dsa->method_mont_p,
720                               (CRYPTO_MUTEX *)&dsa->method_mont_lock, dsa->p,
721                               ctx)) {
722     goto err;
723   }
724 
725   if (!BN_mod_exp2_mont(&t1, dsa->g, &u1, dsa->pub_key, &u2, dsa->p, ctx,
726                         dsa->method_mont_p)) {
727     goto err;
728   }
729 
730   // BN_copy(&u1,&t1);
731   // let u1 = u1 mod q
732   if (!BN_mod(&u1, &t1, dsa->q, ctx)) {
733     goto err;
734   }
735 
736   // V is now in u1.  If the signature is correct, it will be
737   // equal to R.
738   *out_valid = BN_ucmp(&u1, sig->r) == 0;
739   ret = 1;
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   if (s == NULL) {
786     goto err;
787   }
788 
789   const uint8_t *sigp = sig;
790   if (d2i_DSA_SIG(&s, &sigp, sig_len) == NULL || sigp != sig + sig_len) {
791     goto err;
792   }
793 
794   // Ensure that the signature uses DER and doesn't have trailing garbage.
795   int der_len = i2d_DSA_SIG(s, &der);
796   if (der_len < 0 || (size_t)der_len != sig_len ||
797       OPENSSL_memcmp(sig, der, sig_len)) {
798     goto err;
799   }
800 
801   ret = DSA_do_check_signature(out_valid, digest, digest_len, s, dsa);
802 
803 err:
804   OPENSSL_free(der);
805   DSA_SIG_free(s);
806   return ret;
807 }
808 
809 // der_len_len returns the number of bytes needed to represent a length of |len|
810 // in DER.
der_len_len(size_t len)811 static size_t der_len_len(size_t len) {
812   if (len < 0x80) {
813     return 1;
814   }
815   size_t ret = 1;
816   while (len > 0) {
817     ret++;
818     len >>= 8;
819   }
820   return ret;
821 }
822 
DSA_size(const DSA * dsa)823 int DSA_size(const DSA *dsa) {
824   size_t order_len = BN_num_bytes(dsa->q);
825   // Compute the maximum length of an |order_len| byte integer. Defensively
826   // assume that the leading 0x00 is included.
827   size_t integer_len = 1 /* tag */ + der_len_len(order_len + 1) + 1 + order_len;
828   if (integer_len < order_len) {
829     return 0;
830   }
831   // A DSA signature is two INTEGERs.
832   size_t value_len = 2 * integer_len;
833   if (value_len < integer_len) {
834     return 0;
835   }
836   // Add the header.
837   size_t ret = 1 /* tag */ + der_len_len(value_len) + value_len;
838   if (ret < value_len) {
839     return 0;
840   }
841   return ret;
842 }
843 
dsa_sign_setup(const DSA * dsa,BN_CTX * ctx,BIGNUM ** out_kinv,BIGNUM ** out_r)844 static int dsa_sign_setup(const DSA *dsa, BN_CTX *ctx, BIGNUM **out_kinv,
845                           BIGNUM **out_r) {
846   if (!dsa->p || !dsa->q || !dsa->g) {
847     OPENSSL_PUT_ERROR(DSA, DSA_R_MISSING_PARAMETERS);
848     return 0;
849   }
850 
851   int ret = 0;
852   BIGNUM k;
853   BN_init(&k);
854   BIGNUM *r = BN_new();
855   BIGNUM *kinv = BN_new();
856   if (r == NULL || kinv == NULL ||
857       // Get random k
858       !BN_rand_range_ex(&k, 1, dsa->q) ||
859       !BN_MONT_CTX_set_locked((BN_MONT_CTX **)&dsa->method_mont_p,
860                               (CRYPTO_MUTEX *)&dsa->method_mont_lock, dsa->p,
861                               ctx) ||
862       !BN_MONT_CTX_set_locked((BN_MONT_CTX **)&dsa->method_mont_q,
863                               (CRYPTO_MUTEX *)&dsa->method_mont_lock, dsa->q,
864                               ctx) ||
865       // Compute r = (g^k mod p) mod q
866       !BN_mod_exp_mont_consttime(r, dsa->g, &k, dsa->p, ctx,
867                                  dsa->method_mont_p) ||
868       // Note |BN_mod| below is not constant-time and may leak information about
869       // |r|. |dsa->p| may be significantly larger than |dsa->q|, so this is not
870       // easily performed in constant-time with Montgomery reduction.
871       //
872       // However, |r| at this point is g^k (mod p). It is almost the value of
873       // |r| revealed in the signature anyway (g^k (mod p) (mod q)), going from
874       // it to |k| would require computing a discrete log.
875       !BN_mod(r, r, dsa->q, ctx) ||
876       // Compute part of 's = inv(k) (m + xr) mod q' using Fermat's Little
877       // Theorem.
878       !bn_mod_inverse_prime(kinv, &k, dsa->q, ctx, dsa->method_mont_q)) {
879     OPENSSL_PUT_ERROR(DSA, ERR_R_BN_LIB);
880     goto err;
881   }
882 
883   BN_clear_free(*out_kinv);
884   *out_kinv = kinv;
885   kinv = NULL;
886 
887   BN_clear_free(*out_r);
888   *out_r = r;
889   r = NULL;
890 
891   ret = 1;
892 
893 err:
894   BN_clear_free(&k);
895   BN_clear_free(r);
896   BN_clear_free(kinv);
897   return ret;
898 }
899 
DSA_get_ex_new_index(long argl,void * argp,CRYPTO_EX_unused * unused,CRYPTO_EX_dup * dup_unused,CRYPTO_EX_free * free_func)900 int DSA_get_ex_new_index(long argl, void *argp, CRYPTO_EX_unused *unused,
901                          CRYPTO_EX_dup *dup_unused, CRYPTO_EX_free *free_func) {
902   int index;
903   if (!CRYPTO_get_ex_new_index(&g_ex_data_class, &index, argl, argp,
904                                free_func)) {
905     return -1;
906   }
907   return index;
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