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