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