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