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 } 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 (size_t 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 (size_t 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 (size_t 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) { return OPENSSL_zalloc(sizeof(DSA_SIG)); }
533
DSA_SIG_free(DSA_SIG * sig)534 void DSA_SIG_free(DSA_SIG *sig) {
535 if (!sig) {
536 return;
537 }
538
539 BN_free(sig->r);
540 BN_free(sig->s);
541 OPENSSL_free(sig);
542 }
543
DSA_SIG_get0(const DSA_SIG * sig,const BIGNUM ** out_r,const BIGNUM ** out_s)544 void DSA_SIG_get0(const DSA_SIG *sig, const BIGNUM **out_r,
545 const BIGNUM **out_s) {
546 if (out_r != NULL) {
547 *out_r = sig->r;
548 }
549 if (out_s != NULL) {
550 *out_s = sig->s;
551 }
552 }
553
DSA_SIG_set0(DSA_SIG * sig,BIGNUM * r,BIGNUM * s)554 int DSA_SIG_set0(DSA_SIG *sig, BIGNUM *r, BIGNUM *s) {
555 if (r == NULL || s == NULL) {
556 return 0;
557 }
558 BN_free(sig->r);
559 BN_free(sig->s);
560 sig->r = r;
561 sig->s = s;
562 return 1;
563 }
564
565 // mod_mul_consttime sets |r| to |a| * |b| modulo |mont->N|, treating |a| and
566 // |b| as secret. This function internally uses Montgomery reduction, but
567 // 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)568 static int mod_mul_consttime(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
569 const BN_MONT_CTX *mont, BN_CTX *ctx) {
570 BN_CTX_start(ctx);
571 BIGNUM *tmp = BN_CTX_get(ctx);
572 // |BN_mod_mul_montgomery| removes a factor of R, so we cancel it with a
573 // single |BN_to_montgomery| which adds one factor of R.
574 int ok = tmp != NULL &&
575 BN_to_montgomery(tmp, a, mont, ctx) &&
576 BN_mod_mul_montgomery(r, tmp, b, mont, ctx);
577 BN_CTX_end(ctx);
578 return ok;
579 }
580
DSA_do_sign(const uint8_t * digest,size_t digest_len,const DSA * dsa)581 DSA_SIG *DSA_do_sign(const uint8_t *digest, size_t digest_len, const DSA *dsa) {
582 if (!dsa_check_key(dsa)) {
583 return NULL;
584 }
585
586 if (dsa->priv_key == NULL) {
587 OPENSSL_PUT_ERROR(DSA, DSA_R_MISSING_PARAMETERS);
588 return NULL;
589 }
590
591 BIGNUM *kinv = NULL, *r = NULL, *s = NULL;
592 BIGNUM m;
593 BIGNUM xr;
594 BN_CTX *ctx = NULL;
595 DSA_SIG *ret = NULL;
596
597 BN_init(&m);
598 BN_init(&xr);
599 s = BN_new();
600 if (s == NULL) {
601 goto err;
602 }
603 ctx = BN_CTX_new();
604 if (ctx == NULL) {
605 goto err;
606 }
607
608 // Cap iterations so that invalid parameters do not infinite loop. This does
609 // not impact valid parameters because the probability of requiring even one
610 // retry is negligible, let alone 32. Unfortunately, DSA was mis-specified, so
611 // invalid parameters are reachable from most callers handling untrusted
612 // private keys. (The |dsa_check_key| call above is not sufficient. Checking
613 // whether arbitrary paremeters form a valid DSA group is expensive.)
614 static const int kMaxIterations = 32;
615 int iters = 0;
616 redo:
617 if (!dsa_sign_setup(dsa, ctx, &kinv, &r)) {
618 goto err;
619 }
620
621 if (digest_len > BN_num_bytes(dsa->q)) {
622 // If the digest length is greater than the size of |dsa->q| use the
623 // BN_num_bits(dsa->q) leftmost bits of the digest, see FIPS 186-3, 4.2.
624 // Note the above check that |dsa->q| is a multiple of 8 bits.
625 digest_len = BN_num_bytes(dsa->q);
626 }
627
628 if (BN_bin2bn(digest, digest_len, &m) == NULL) {
629 goto err;
630 }
631
632 // |m| is bounded by 2^(num_bits(q)), which is slightly looser than q. This
633 // violates |bn_mod_add_consttime| and |mod_mul_consttime|'s preconditions.
634 // (The underlying algorithms could accept looser bounds, but we reduce for
635 // simplicity.)
636 size_t q_width = bn_minimal_width(dsa->q);
637 if (!bn_resize_words(&m, q_width) ||
638 !bn_resize_words(&xr, q_width)) {
639 goto err;
640 }
641 bn_reduce_once_in_place(m.d, 0 /* no carry word */, dsa->q->d,
642 xr.d /* scratch space */, q_width);
643
644 // Compute s = inv(k) (m + xr) mod q. Note |dsa->method_mont_q| is
645 // initialized by |dsa_sign_setup|.
646 if (!mod_mul_consttime(&xr, dsa->priv_key, r, dsa->method_mont_q, ctx) ||
647 !bn_mod_add_consttime(s, &xr, &m, dsa->q, ctx) ||
648 !mod_mul_consttime(s, s, kinv, dsa->method_mont_q, ctx)) {
649 goto err;
650 }
651
652 // Redo if r or s is zero as required by FIPS 186-3: this is
653 // very unlikely.
654 if (BN_is_zero(r) || BN_is_zero(s)) {
655 iters++;
656 if (iters > kMaxIterations) {
657 OPENSSL_PUT_ERROR(DSA, DSA_R_TOO_MANY_ITERATIONS);
658 goto err;
659 }
660 goto redo;
661 }
662
663 ret = DSA_SIG_new();
664 if (ret == NULL) {
665 goto err;
666 }
667 ret->r = r;
668 ret->s = s;
669
670 err:
671 if (ret == NULL) {
672 OPENSSL_PUT_ERROR(DSA, ERR_R_BN_LIB);
673 BN_free(r);
674 BN_free(s);
675 }
676 BN_CTX_free(ctx);
677 BN_clear_free(&m);
678 BN_clear_free(&xr);
679 BN_clear_free(kinv);
680
681 return ret;
682 }
683
DSA_do_verify(const uint8_t * digest,size_t digest_len,DSA_SIG * sig,const DSA * dsa)684 int DSA_do_verify(const uint8_t *digest, size_t digest_len, DSA_SIG *sig,
685 const DSA *dsa) {
686 int valid;
687 if (!DSA_do_check_signature(&valid, digest, digest_len, sig, dsa)) {
688 return -1;
689 }
690 return valid;
691 }
692
DSA_do_check_signature(int * out_valid,const uint8_t * digest,size_t digest_len,DSA_SIG * sig,const DSA * dsa)693 int DSA_do_check_signature(int *out_valid, const uint8_t *digest,
694 size_t digest_len, DSA_SIG *sig, const DSA *dsa) {
695 *out_valid = 0;
696 if (!dsa_check_key(dsa)) {
697 return 0;
698 }
699
700 if (dsa->pub_key == NULL) {
701 OPENSSL_PUT_ERROR(DSA, DSA_R_MISSING_PARAMETERS);
702 return 0;
703 }
704
705 int ret = 0;
706 BIGNUM u1, u2, t1;
707 BN_init(&u1);
708 BN_init(&u2);
709 BN_init(&t1);
710 BN_CTX *ctx = BN_CTX_new();
711 if (ctx == NULL) {
712 goto err;
713 }
714
715 if (BN_is_zero(sig->r) || BN_is_negative(sig->r) ||
716 BN_ucmp(sig->r, dsa->q) >= 0) {
717 ret = 1;
718 goto err;
719 }
720 if (BN_is_zero(sig->s) || BN_is_negative(sig->s) ||
721 BN_ucmp(sig->s, dsa->q) >= 0) {
722 ret = 1;
723 goto err;
724 }
725
726 // Calculate W = inv(S) mod Q
727 // save W in u2
728 if (BN_mod_inverse(&u2, sig->s, dsa->q, ctx) == NULL) {
729 goto err;
730 }
731
732 // save M in u1
733 unsigned q_bits = BN_num_bits(dsa->q);
734 if (digest_len > (q_bits >> 3)) {
735 // if the digest length is greater than the size of q use the
736 // BN_num_bits(dsa->q) leftmost bits of the digest, see
737 // fips 186-3, 4.2
738 digest_len = (q_bits >> 3);
739 }
740
741 if (BN_bin2bn(digest, digest_len, &u1) == NULL) {
742 goto err;
743 }
744
745 // u1 = M * w mod q
746 if (!BN_mod_mul(&u1, &u1, &u2, dsa->q, ctx)) {
747 goto err;
748 }
749
750 // u2 = r * w mod q
751 if (!BN_mod_mul(&u2, sig->r, &u2, dsa->q, ctx)) {
752 goto err;
753 }
754
755 if (!BN_MONT_CTX_set_locked((BN_MONT_CTX **)&dsa->method_mont_p,
756 (CRYPTO_MUTEX *)&dsa->method_mont_lock, dsa->p,
757 ctx)) {
758 goto err;
759 }
760
761 if (!BN_mod_exp2_mont(&t1, dsa->g, &u1, dsa->pub_key, &u2, dsa->p, ctx,
762 dsa->method_mont_p)) {
763 goto err;
764 }
765
766 // BN_copy(&u1,&t1);
767 // let u1 = u1 mod q
768 if (!BN_mod(&u1, &t1, dsa->q, ctx)) {
769 goto err;
770 }
771
772 // V is now in u1. If the signature is correct, it will be
773 // equal to R.
774 *out_valid = BN_ucmp(&u1, sig->r) == 0;
775 ret = 1;
776
777 err:
778 if (ret != 1) {
779 OPENSSL_PUT_ERROR(DSA, ERR_R_BN_LIB);
780 }
781 BN_CTX_free(ctx);
782 BN_free(&u1);
783 BN_free(&u2);
784 BN_free(&t1);
785
786 return ret;
787 }
788
DSA_sign(int type,const uint8_t * digest,size_t digest_len,uint8_t * out_sig,unsigned int * out_siglen,const DSA * dsa)789 int DSA_sign(int type, const uint8_t *digest, size_t digest_len,
790 uint8_t *out_sig, unsigned int *out_siglen, const DSA *dsa) {
791 DSA_SIG *s;
792
793 s = DSA_do_sign(digest, digest_len, dsa);
794 if (s == NULL) {
795 *out_siglen = 0;
796 return 0;
797 }
798
799 *out_siglen = i2d_DSA_SIG(s, &out_sig);
800 DSA_SIG_free(s);
801 return 1;
802 }
803
DSA_verify(int type,const uint8_t * digest,size_t digest_len,const uint8_t * sig,size_t sig_len,const DSA * dsa)804 int DSA_verify(int type, const uint8_t *digest, size_t digest_len,
805 const uint8_t *sig, size_t sig_len, const DSA *dsa) {
806 int valid;
807 if (!DSA_check_signature(&valid, digest, digest_len, sig, sig_len, dsa)) {
808 return -1;
809 }
810 return valid;
811 }
812
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)813 int DSA_check_signature(int *out_valid, const uint8_t *digest,
814 size_t digest_len, const uint8_t *sig, size_t sig_len,
815 const DSA *dsa) {
816 DSA_SIG *s = NULL;
817 int ret = 0;
818 uint8_t *der = NULL;
819
820 s = DSA_SIG_new();
821 if (s == NULL) {
822 goto err;
823 }
824
825 const uint8_t *sigp = sig;
826 if (d2i_DSA_SIG(&s, &sigp, sig_len) == NULL || sigp != sig + sig_len) {
827 goto err;
828 }
829
830 // Ensure that the signature uses DER and doesn't have trailing garbage.
831 int der_len = i2d_DSA_SIG(s, &der);
832 if (der_len < 0 || (size_t)der_len != sig_len ||
833 OPENSSL_memcmp(sig, der, sig_len)) {
834 goto err;
835 }
836
837 ret = DSA_do_check_signature(out_valid, digest, digest_len, s, dsa);
838
839 err:
840 OPENSSL_free(der);
841 DSA_SIG_free(s);
842 return ret;
843 }
844
845 // der_len_len returns the number of bytes needed to represent a length of |len|
846 // in DER.
der_len_len(size_t len)847 static size_t der_len_len(size_t len) {
848 if (len < 0x80) {
849 return 1;
850 }
851 size_t ret = 1;
852 while (len > 0) {
853 ret++;
854 len >>= 8;
855 }
856 return ret;
857 }
858
DSA_size(const DSA * dsa)859 int DSA_size(const DSA *dsa) {
860 if (dsa->q == NULL) {
861 return 0;
862 }
863
864 size_t order_len = BN_num_bytes(dsa->q);
865 // Compute the maximum length of an |order_len| byte integer. Defensively
866 // assume that the leading 0x00 is included.
867 size_t integer_len = 1 /* tag */ + der_len_len(order_len + 1) + 1 + order_len;
868 if (integer_len < order_len) {
869 return 0;
870 }
871 // A DSA signature is two INTEGERs.
872 size_t value_len = 2 * integer_len;
873 if (value_len < integer_len) {
874 return 0;
875 }
876 // Add the header.
877 size_t ret = 1 /* tag */ + der_len_len(value_len) + value_len;
878 if (ret < value_len) {
879 return 0;
880 }
881 return ret;
882 }
883
dsa_sign_setup(const DSA * dsa,BN_CTX * ctx,BIGNUM ** out_kinv,BIGNUM ** out_r)884 static int dsa_sign_setup(const DSA *dsa, BN_CTX *ctx, BIGNUM **out_kinv,
885 BIGNUM **out_r) {
886 int ret = 0;
887 BIGNUM k;
888 BN_init(&k);
889 BIGNUM *r = BN_new();
890 BIGNUM *kinv = BN_new();
891 if (r == NULL || kinv == NULL ||
892 // Get random k
893 !BN_rand_range_ex(&k, 1, dsa->q) ||
894 !BN_MONT_CTX_set_locked((BN_MONT_CTX **)&dsa->method_mont_p,
895 (CRYPTO_MUTEX *)&dsa->method_mont_lock, dsa->p,
896 ctx) ||
897 !BN_MONT_CTX_set_locked((BN_MONT_CTX **)&dsa->method_mont_q,
898 (CRYPTO_MUTEX *)&dsa->method_mont_lock, dsa->q,
899 ctx) ||
900 // Compute r = (g^k mod p) mod q
901 !BN_mod_exp_mont_consttime(r, dsa->g, &k, dsa->p, ctx,
902 dsa->method_mont_p) ||
903 // Note |BN_mod| below is not constant-time and may leak information about
904 // |r|. |dsa->p| may be significantly larger than |dsa->q|, so this is not
905 // easily performed in constant-time with Montgomery reduction.
906 //
907 // However, |r| at this point is g^k (mod p). It is almost the value of
908 // |r| revealed in the signature anyway (g^k (mod p) (mod q)), going from
909 // it to |k| would require computing a discrete log.
910 !BN_mod(r, r, dsa->q, ctx) ||
911 // Compute part of 's = inv(k) (m + xr) mod q' using Fermat's Little
912 // Theorem.
913 !bn_mod_inverse_prime(kinv, &k, dsa->q, ctx, dsa->method_mont_q)) {
914 OPENSSL_PUT_ERROR(DSA, ERR_R_BN_LIB);
915 goto err;
916 }
917
918 BN_clear_free(*out_kinv);
919 *out_kinv = kinv;
920 kinv = NULL;
921
922 BN_clear_free(*out_r);
923 *out_r = r;
924 r = NULL;
925
926 ret = 1;
927
928 err:
929 BN_clear_free(&k);
930 BN_clear_free(r);
931 BN_clear_free(kinv);
932 return ret;
933 }
934
DSA_get_ex_new_index(long argl,void * argp,CRYPTO_EX_unused * unused,CRYPTO_EX_dup * dup_unused,CRYPTO_EX_free * free_func)935 int DSA_get_ex_new_index(long argl, void *argp, CRYPTO_EX_unused *unused,
936 CRYPTO_EX_dup *dup_unused, CRYPTO_EX_free *free_func) {
937 int index;
938 if (!CRYPTO_get_ex_new_index(&g_ex_data_class, &index, argl, argp,
939 free_func)) {
940 return -1;
941 }
942 return index;
943 }
944
DSA_set_ex_data(DSA * dsa,int idx,void * arg)945 int DSA_set_ex_data(DSA *dsa, int idx, void *arg) {
946 return CRYPTO_set_ex_data(&dsa->ex_data, idx, arg);
947 }
948
DSA_get_ex_data(const DSA * dsa,int idx)949 void *DSA_get_ex_data(const DSA *dsa, int idx) {
950 return CRYPTO_get_ex_data(&dsa->ex_data, idx);
951 }
952
DSA_dup_DH(const DSA * dsa)953 DH *DSA_dup_DH(const DSA *dsa) {
954 if (dsa == NULL) {
955 return NULL;
956 }
957
958 DH *ret = DH_new();
959 if (ret == NULL) {
960 goto err;
961 }
962 if (dsa->q != NULL) {
963 ret->priv_length = BN_num_bits(dsa->q);
964 if ((ret->q = BN_dup(dsa->q)) == NULL) {
965 goto err;
966 }
967 }
968 if ((dsa->p != NULL && (ret->p = BN_dup(dsa->p)) == NULL) ||
969 (dsa->g != NULL && (ret->g = BN_dup(dsa->g)) == NULL) ||
970 (dsa->pub_key != NULL && (ret->pub_key = BN_dup(dsa->pub_key)) == NULL) ||
971 (dsa->priv_key != NULL &&
972 (ret->priv_key = BN_dup(dsa->priv_key)) == NULL)) {
973 goto err;
974 }
975
976 return ret;
977
978 err:
979 DH_free(ret);
980 return NULL;
981 }
982