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