7288832e084149b919fed56a1bacaf2201cf9d18
[openssl.git] / crypto / dsa / dsa_ossl.c
1 /*
2  * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 /*
11  * DSA low level APIs are deprecated for public use, but still ok for
12  * internal use.
13  */
14 #include "internal/deprecated.h"
15
16 #include <stdio.h>
17 #include "internal/cryptlib.h"
18 #include "crypto/bn.h"
19 #include <openssl/bn.h>
20 #include <openssl/sha.h>
21 #include "dsa_local.h"
22 #include <openssl/asn1.h>
23
24 static DSA_SIG *dsa_do_sign(const unsigned char *dgst, int dlen, DSA *dsa);
25 static int dsa_sign_setup_no_digest(DSA *dsa, BN_CTX *ctx_in, BIGNUM **kinvp,
26                                     BIGNUM **rp);
27 static int dsa_sign_setup(DSA *dsa, BN_CTX *ctx_in, BIGNUM **kinvp,
28                           BIGNUM **rp, const unsigned char *dgst, int dlen);
29 static int dsa_do_verify(const unsigned char *dgst, int dgst_len,
30                          DSA_SIG *sig, DSA *dsa);
31 static int dsa_init(DSA *dsa);
32 static int dsa_finish(DSA *dsa);
33 static BIGNUM *dsa_mod_inverse_fermat(const BIGNUM *k, const BIGNUM *q,
34                                       BN_CTX *ctx);
35
36 static DSA_METHOD openssl_dsa_meth = {
37     "OpenSSL DSA method",
38     dsa_do_sign,
39     dsa_sign_setup_no_digest,
40     dsa_do_verify,
41     NULL,                       /* dsa_mod_exp, */
42     NULL,                       /* dsa_bn_mod_exp, */
43     dsa_init,
44     dsa_finish,
45     DSA_FLAG_FIPS_METHOD,
46     NULL,
47     NULL,
48     NULL
49 };
50
51 static const DSA_METHOD *default_DSA_method = &openssl_dsa_meth;
52
53 #ifndef FIPS_MODE
54 void DSA_set_default_method(const DSA_METHOD *meth)
55 {
56     default_DSA_method = meth;
57 }
58 #endif /* FIPS_MODE */
59
60 const DSA_METHOD *DSA_get_default_method(void)
61 {
62     return default_DSA_method;
63 }
64
65 const DSA_METHOD *DSA_OpenSSL(void)
66 {
67     return &openssl_dsa_meth;
68 }
69
70 DSA_SIG *dsa_do_sign_int(const unsigned char *dgst, int dlen, DSA *dsa)
71 {
72     BIGNUM *kinv = NULL;
73     BIGNUM *m, *blind, *blindm, *tmp;
74     BN_CTX *ctx = NULL;
75     int reason = ERR_R_BN_LIB;
76     DSA_SIG *ret = NULL;
77     int rv = 0;
78
79     if (dsa->params.p == NULL
80         || dsa->params.q == NULL
81         || dsa->params.g == NULL) {
82         reason = DSA_R_MISSING_PARAMETERS;
83         goto err;
84     }
85     if (dsa->priv_key == NULL) {
86         reason = DSA_R_MISSING_PRIVATE_KEY;
87         goto err;
88     }
89
90     ret = DSA_SIG_new();
91     if (ret == NULL)
92         goto err;
93     ret->r = BN_new();
94     ret->s = BN_new();
95     if (ret->r == NULL || ret->s == NULL)
96         goto err;
97
98     ctx = BN_CTX_new_ex(dsa->libctx);
99     if (ctx == NULL)
100         goto err;
101     m = BN_CTX_get(ctx);
102     blind = BN_CTX_get(ctx);
103     blindm = BN_CTX_get(ctx);
104     tmp = BN_CTX_get(ctx);
105     if (tmp == NULL)
106         goto err;
107
108  redo:
109     if (!dsa_sign_setup(dsa, ctx, &kinv, &ret->r, dgst, dlen))
110         goto err;
111
112     if (dlen > BN_num_bytes(dsa->params.q))
113         /*
114          * if the digest length is greater than the size of q use the
115          * BN_num_bits(dsa->q) leftmost bits of the digest, see fips 186-3,
116          * 4.2
117          */
118         dlen = BN_num_bytes(dsa->params.q);
119     if (BN_bin2bn(dgst, dlen, m) == NULL)
120         goto err;
121
122     /*
123      * The normal signature calculation is:
124      *
125      *   s := k^-1 * (m + r * priv_key) mod q
126      *
127      * We will blind this to protect against side channel attacks
128      *
129      *   s := blind^-1 * k^-1 * (blind * m + blind * r * priv_key) mod q
130      */
131
132     /* Generate a blinding value */
133     do {
134         if (!BN_priv_rand_ex(blind, BN_num_bits(dsa->params.q) - 1,
135                              BN_RAND_TOP_ANY, BN_RAND_BOTTOM_ANY, ctx))
136             goto err;
137     } while (BN_is_zero(blind));
138     BN_set_flags(blind, BN_FLG_CONSTTIME);
139     BN_set_flags(blindm, BN_FLG_CONSTTIME);
140     BN_set_flags(tmp, BN_FLG_CONSTTIME);
141
142     /* tmp := blind * priv_key * r mod q */
143     if (!BN_mod_mul(tmp, blind, dsa->priv_key, dsa->params.q, ctx))
144         goto err;
145     if (!BN_mod_mul(tmp, tmp, ret->r, dsa->params.q, ctx))
146         goto err;
147
148     /* blindm := blind * m mod q */
149     if (!BN_mod_mul(blindm, blind, m, dsa->params.q, ctx))
150         goto err;
151
152     /* s : = (blind * priv_key * r) + (blind * m) mod q */
153     if (!BN_mod_add_quick(ret->s, tmp, blindm, dsa->params.q))
154         goto err;
155
156     /* s := s * k^-1 mod q */
157     if (!BN_mod_mul(ret->s, ret->s, kinv, dsa->params.q, ctx))
158         goto err;
159
160     /* s:= s * blind^-1 mod q */
161     if (BN_mod_inverse(blind, blind, dsa->params.q, ctx) == NULL)
162         goto err;
163     if (!BN_mod_mul(ret->s, ret->s, blind, dsa->params.q, ctx))
164         goto err;
165
166     /*
167      * Redo if r or s is zero as required by FIPS 186-3: this is very
168      * unlikely.
169      */
170     if (BN_is_zero(ret->r) || BN_is_zero(ret->s))
171         goto redo;
172
173     rv = 1;
174
175  err:
176     if (rv == 0) {
177         DSAerr(0, reason);
178         DSA_SIG_free(ret);
179         ret = NULL;
180     }
181     BN_CTX_free(ctx);
182     BN_clear_free(kinv);
183     return ret;
184 }
185
186 static DSA_SIG *dsa_do_sign(const unsigned char *dgst, int dlen, DSA *dsa)
187 {
188     return dsa_do_sign_int(dgst, dlen, dsa);
189 }
190
191 static int dsa_sign_setup_no_digest(DSA *dsa, BN_CTX *ctx_in,
192                                     BIGNUM **kinvp, BIGNUM **rp)
193 {
194     return dsa_sign_setup(dsa, ctx_in, kinvp, rp, NULL, 0);
195 }
196
197 static int dsa_sign_setup(DSA *dsa, BN_CTX *ctx_in,
198                           BIGNUM **kinvp, BIGNUM **rp,
199                           const unsigned char *dgst, int dlen)
200 {
201     BN_CTX *ctx = NULL;
202     BIGNUM *k, *kinv = NULL, *r = *rp;
203     BIGNUM *l;
204     int ret = 0;
205     int q_bits, q_words;
206
207     if (!dsa->params.p || !dsa->params.q || !dsa->params.g) {
208         DSAerr(DSA_F_DSA_SIGN_SETUP, DSA_R_MISSING_PARAMETERS);
209         return 0;
210     }
211
212     /* Reject obviously invalid parameters */
213     if (BN_is_zero(dsa->params.p)
214         || BN_is_zero(dsa->params.q)
215         || BN_is_zero(dsa->params.g)) {
216         DSAerr(DSA_F_DSA_SIGN_SETUP, DSA_R_INVALID_PARAMETERS);
217         return 0;
218     }
219     if (dsa->priv_key == NULL) {
220         DSAerr(DSA_F_DSA_SIGN_SETUP, DSA_R_MISSING_PRIVATE_KEY);
221         return 0;
222     }
223
224     k = BN_new();
225     l = BN_new();
226     if (k == NULL || l == NULL)
227         goto err;
228
229     if (ctx_in == NULL) {
230         /* if you don't pass in ctx_in you get a default libctx */
231         if ((ctx = BN_CTX_new_ex(NULL)) == NULL)
232             goto err;
233     } else
234         ctx = ctx_in;
235
236     /* Preallocate space */
237     q_bits = BN_num_bits(dsa->params.q);
238     q_words = bn_get_top(dsa->params.q);
239     if (!bn_wexpand(k, q_words + 2)
240         || !bn_wexpand(l, q_words + 2))
241         goto err;
242
243     /* Get random k */
244     do {
245         if (dgst != NULL) {
246             /*
247              * We calculate k from SHA512(private_key + H(message) + random).
248              * This protects the private key from a weak PRNG.
249              */
250             if (!BN_generate_dsa_nonce(k, dsa->params.q, dsa->priv_key, dgst,
251                                        dlen, ctx))
252                 goto err;
253         } else if (!BN_priv_rand_range_ex(k, dsa->params.q, ctx))
254             goto err;
255     } while (BN_is_zero(k));
256
257     BN_set_flags(k, BN_FLG_CONSTTIME);
258     BN_set_flags(l, BN_FLG_CONSTTIME);
259
260     if (dsa->flags & DSA_FLAG_CACHE_MONT_P) {
261         if (!BN_MONT_CTX_set_locked(&dsa->method_mont_p,
262                                     dsa->lock, dsa->params.p, ctx))
263             goto err;
264     }
265
266     /* Compute r = (g^k mod p) mod q */
267
268     /*
269      * We do not want timing information to leak the length of k, so we
270      * compute G^k using an equivalent scalar of fixed bit-length.
271      *
272      * We unconditionally perform both of these additions to prevent a
273      * small timing information leakage.  We then choose the sum that is
274      * one bit longer than the modulus.
275      *
276      * There are some concerns about the efficacy of doing this.  More
277      * specifically refer to the discussion starting with:
278      *     https://github.com/openssl/openssl/pull/7486#discussion_r228323705
279      * The fix is to rework BN so these gymnastics aren't required.
280      */
281     if (!BN_add(l, k, dsa->params.q)
282         || !BN_add(k, l, dsa->params.q))
283         goto err;
284
285     BN_consttime_swap(BN_is_bit_set(l, q_bits), k, l, q_words + 2);
286
287     if ((dsa)->meth->bn_mod_exp != NULL) {
288             if (!dsa->meth->bn_mod_exp(dsa, r, dsa->params.g, k, dsa->params.p,
289                                        ctx, dsa->method_mont_p))
290                 goto err;
291     } else {
292             if (!BN_mod_exp_mont(r, dsa->params.g, k, dsa->params.p, ctx,
293                                  dsa->method_mont_p))
294                 goto err;
295     }
296
297     if (!BN_mod(r, r, dsa->params.q, ctx))
298         goto err;
299
300     /* Compute part of 's = inv(k) (m + xr) mod q' */
301     if ((kinv = dsa_mod_inverse_fermat(k, dsa->params.q, ctx)) == NULL)
302         goto err;
303
304     BN_clear_free(*kinvp);
305     *kinvp = kinv;
306     kinv = NULL;
307     ret = 1;
308  err:
309     if (!ret)
310         DSAerr(DSA_F_DSA_SIGN_SETUP, ERR_R_BN_LIB);
311     if (ctx != ctx_in)
312         BN_CTX_free(ctx);
313     BN_clear_free(k);
314     BN_clear_free(l);
315     return ret;
316 }
317
318 static int dsa_do_verify(const unsigned char *dgst, int dgst_len,
319                          DSA_SIG *sig, DSA *dsa)
320 {
321     BN_CTX *ctx;
322     BIGNUM *u1, *u2, *t1;
323     BN_MONT_CTX *mont = NULL;
324     const BIGNUM *r, *s;
325     int ret = -1, i;
326
327     if (dsa->params.p == NULL
328         || dsa->params.q == NULL
329         || dsa->params.g == NULL) {
330         DSAerr(DSA_F_DSA_DO_VERIFY, DSA_R_MISSING_PARAMETERS);
331         return -1;
332     }
333
334     i = BN_num_bits(dsa->params.q);
335     /* fips 186-3 allows only different sizes for q */
336     if (i != 160 && i != 224 && i != 256) {
337         DSAerr(DSA_F_DSA_DO_VERIFY, DSA_R_BAD_Q_VALUE);
338         return -1;
339     }
340
341     if (BN_num_bits(dsa->params.p) > OPENSSL_DSA_MAX_MODULUS_BITS) {
342         DSAerr(DSA_F_DSA_DO_VERIFY, DSA_R_MODULUS_TOO_LARGE);
343         return -1;
344     }
345     u1 = BN_new();
346     u2 = BN_new();
347     t1 = BN_new();
348     ctx = BN_CTX_new_ex(NULL); /* verify does not need a libctx */
349     if (u1 == NULL || u2 == NULL || t1 == NULL || ctx == NULL)
350         goto err;
351
352     DSA_SIG_get0(sig, &r, &s);
353
354     if (BN_is_zero(r) || BN_is_negative(r) ||
355         BN_ucmp(r, dsa->params.q) >= 0) {
356         ret = 0;
357         goto err;
358     }
359     if (BN_is_zero(s) || BN_is_negative(s) ||
360         BN_ucmp(s, dsa->params.q) >= 0) {
361         ret = 0;
362         goto err;
363     }
364
365     /*
366      * Calculate W = inv(S) mod Q save W in u2
367      */
368     if ((BN_mod_inverse(u2, s, dsa->params.q, ctx)) == NULL)
369         goto err;
370
371     /* save M in u1 */
372     if (dgst_len > (i >> 3))
373         /*
374          * if the digest length is greater than the size of q use the
375          * BN_num_bits(dsa->q) leftmost bits of the digest, see fips 186-3,
376          * 4.2
377          */
378         dgst_len = (i >> 3);
379     if (BN_bin2bn(dgst, dgst_len, u1) == NULL)
380         goto err;
381
382     /* u1 = M * w mod q */
383     if (!BN_mod_mul(u1, u1, u2, dsa->params.q, ctx))
384         goto err;
385
386     /* u2 = r * w mod q */
387     if (!BN_mod_mul(u2, r, u2, dsa->params.q, ctx))
388         goto err;
389
390     if (dsa->flags & DSA_FLAG_CACHE_MONT_P) {
391         mont = BN_MONT_CTX_set_locked(&dsa->method_mont_p,
392                                       dsa->lock, dsa->params.p, ctx);
393         if (!mont)
394             goto err;
395     }
396
397     if (dsa->meth->dsa_mod_exp != NULL) {
398         if (!dsa->meth->dsa_mod_exp(dsa, t1, dsa->params.g, u1, dsa->pub_key, u2,
399                                     dsa->params.p, ctx, mont))
400             goto err;
401     } else {
402         if (!BN_mod_exp2_mont(t1, dsa->params.g, u1, dsa->pub_key, u2,
403                               dsa->params.p, ctx, mont))
404             goto err;
405     }
406
407     /* let u1 = u1 mod q */
408     if (!BN_mod(u1, t1, dsa->params.q, ctx))
409         goto err;
410
411     /*
412      * V is now in u1.  If the signature is correct, it will be equal to R.
413      */
414     ret = (BN_ucmp(u1, r) == 0);
415
416  err:
417     if (ret < 0)
418         DSAerr(DSA_F_DSA_DO_VERIFY, ERR_R_BN_LIB);
419     BN_CTX_free(ctx);
420     BN_free(u1);
421     BN_free(u2);
422     BN_free(t1);
423     return ret;
424 }
425
426 static int dsa_init(DSA *dsa)
427 {
428     dsa->flags |= DSA_FLAG_CACHE_MONT_P;
429     ffc_params_init(&dsa->params);
430     dsa->dirty_cnt++;
431     return 1;
432 }
433
434 static int dsa_finish(DSA *dsa)
435 {
436     BN_MONT_CTX_free(dsa->method_mont_p);
437     return 1;
438 }
439
440 /*
441  * Compute the inverse of k modulo q.
442  * Since q is prime, Fermat's Little Theorem applies, which reduces this to
443  * mod-exp operation.  Both the exponent and modulus are public information
444  * so a mod-exp that doesn't leak the base is sufficient.  A newly allocated
445  * BIGNUM is returned which the caller must free.
446  */
447 static BIGNUM *dsa_mod_inverse_fermat(const BIGNUM *k, const BIGNUM *q,
448                                       BN_CTX *ctx)
449 {
450     BIGNUM *res = NULL;
451     BIGNUM *r, *e;
452
453     if ((r = BN_new()) == NULL)
454         return NULL;
455
456     BN_CTX_start(ctx);
457     if ((e = BN_CTX_get(ctx)) != NULL
458             && BN_set_word(r, 2)
459             && BN_sub(e, q, r)
460             && BN_mod_exp_mont(r, k, e, q, ctx, NULL))
461         res = r;
462     else
463         BN_free(r);
464     BN_CTX_end(ctx);
465     return res;
466 }