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