dsa_ossl.c revision 340704
1/* crypto/dsa/dsa_ossl.c */
2/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3 * All rights reserved.
4 *
5 * This package is an SSL implementation written
6 * by Eric Young (eay@cryptsoft.com).
7 * The implementation was written so as to conform with Netscapes SSL.
8 *
9 * This library is free for commercial and non-commercial use as long as
10 * the following conditions are aheared to.  The following conditions
11 * apply to all code found in this distribution, be it the RC4, RSA,
12 * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13 * included with this distribution is covered by the same copyright terms
14 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15 *
16 * Copyright remains Eric Young's, and as such any Copyright notices in
17 * the code are not to be removed.
18 * If this package is used in a product, Eric Young should be given attribution
19 * as the author of the parts of the library used.
20 * This can be in the form of a textual message at program startup or
21 * in documentation (online or textual) provided with the package.
22 *
23 * Redistribution and use in source and binary forms, with or without
24 * modification, are permitted provided that the following conditions
25 * are met:
26 * 1. Redistributions of source code must retain the copyright
27 *    notice, this list of conditions and the following disclaimer.
28 * 2. Redistributions in binary form must reproduce the above copyright
29 *    notice, this list of conditions and the following disclaimer in the
30 *    documentation and/or other materials provided with the distribution.
31 * 3. All advertising materials mentioning features or use of this software
32 *    must display the following acknowledgement:
33 *    "This product includes cryptographic software written by
34 *     Eric Young (eay@cryptsoft.com)"
35 *    The word 'cryptographic' can be left out if the rouines from the library
36 *    being used are not cryptographic related :-).
37 * 4. If you include any Windows specific code (or a derivative thereof) from
38 *    the apps directory (application code) you must include an acknowledgement:
39 *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40 *
41 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51 * SUCH DAMAGE.
52 *
53 * The licence and distribution terms for any publically available version or
54 * derivative of this code cannot be changed.  i.e. this code cannot simply be
55 * copied and put under another distribution licence
56 * [including the GNU Public Licence.]
57 */
58
59/* Original version from Steven Schoch <schoch@sheba.arc.nasa.gov> */
60
61#include <stdio.h>
62#include "cryptlib.h"
63#include <openssl/bn.h>
64#include <openssl/sha.h>
65#include <openssl/dsa.h>
66#include <openssl/rand.h>
67#include <openssl/asn1.h>
68
69static DSA_SIG *dsa_do_sign(const unsigned char *dgst, int dlen, DSA *dsa);
70static int dsa_sign_setup(DSA *dsa, BN_CTX *ctx_in, BIGNUM **kinvp,
71                          BIGNUM **rp);
72static int dsa_do_verify(const unsigned char *dgst, int dgst_len,
73                         DSA_SIG *sig, DSA *dsa);
74static int dsa_init(DSA *dsa);
75static int dsa_finish(DSA *dsa);
76static BIGNUM *dsa_mod_inverse_fermat(const BIGNUM *k, const BIGNUM *q,
77                                      BN_CTX *ctx);
78
79static DSA_METHOD openssl_dsa_meth = {
80    "OpenSSL DSA method",
81    dsa_do_sign,
82    dsa_sign_setup,
83    dsa_do_verify,
84    NULL,                       /* dsa_mod_exp, */
85    NULL,                       /* dsa_bn_mod_exp, */
86    dsa_init,
87    dsa_finish,
88    0,
89    NULL,
90    NULL,
91    NULL
92};
93
94/*-
95 * These macro wrappers replace attempts to use the dsa_mod_exp() and
96 * bn_mod_exp() handlers in the DSA_METHOD structure. We avoid the problem of
97 * having a the macro work as an expression by bundling an "err_instr". So;
98 *
99 *     if (!dsa->meth->bn_mod_exp(dsa, r,dsa->g,&k,dsa->p,ctx,
100 *                 dsa->method_mont_p)) goto err;
101 *
102 * can be replaced by;
103 *
104 *     DSA_BN_MOD_EXP(goto err, dsa, r, dsa->g, &k, dsa->p, ctx,
105 *                 dsa->method_mont_p);
106 */
107
108#define DSA_MOD_EXP(err_instr,dsa,rr,a1,p1,a2,p2,m,ctx,in_mont) \
109        do { \
110        int _tmp_res53; \
111        if ((dsa)->meth->dsa_mod_exp) \
112                _tmp_res53 = (dsa)->meth->dsa_mod_exp((dsa), (rr), (a1), (p1), \
113                                (a2), (p2), (m), (ctx), (in_mont)); \
114        else \
115                _tmp_res53 = BN_mod_exp2_mont((rr), (a1), (p1), (a2), (p2), \
116                                (m), (ctx), (in_mont)); \
117        if (!_tmp_res53) err_instr; \
118        } while(0)
119#define DSA_BN_MOD_EXP(err_instr,dsa,r,a,p,m,ctx,m_ctx) \
120        do { \
121        int _tmp_res53; \
122        if ((dsa)->meth->bn_mod_exp) \
123                _tmp_res53 = (dsa)->meth->bn_mod_exp((dsa), (r), (a), (p), \
124                                (m), (ctx), (m_ctx)); \
125        else \
126                _tmp_res53 = BN_mod_exp_mont((r), (a), (p), (m), (ctx), (m_ctx)); \
127        if (!_tmp_res53) err_instr; \
128        } while(0)
129
130const DSA_METHOD *DSA_OpenSSL(void)
131{
132    return &openssl_dsa_meth;
133}
134
135static DSA_SIG *dsa_do_sign(const unsigned char *dgst, int dlen, DSA *dsa)
136{
137    BIGNUM *kinv = NULL, *r = NULL, *s = NULL;
138    BIGNUM *m, *blind, *blindm, *tmp;
139    BN_CTX *ctx = NULL;
140    int reason = ERR_R_BN_LIB;
141    DSA_SIG *ret = NULL;
142    int noredo = 0;
143
144    if (dsa->p == NULL || dsa->q == NULL || dsa->g == NULL) {
145        reason = DSA_R_MISSING_PARAMETERS;
146        goto err;
147    }
148
149    s = BN_new();
150    if (s == NULL)
151        goto err;
152    ctx = BN_CTX_new();
153    if (ctx == NULL)
154        goto err;
155    m = BN_CTX_get(ctx);
156    blind = BN_CTX_get(ctx);
157    blindm = BN_CTX_get(ctx);
158    tmp = BN_CTX_get(ctx);
159    if (tmp == NULL)
160        goto err;
161
162 redo:
163    if ((dsa->kinv == NULL) || (dsa->r == NULL)) {
164        if (!DSA_sign_setup(dsa, ctx, &kinv, &r))
165            goto err;
166    } else {
167        kinv = dsa->kinv;
168        dsa->kinv = NULL;
169        r = dsa->r;
170        dsa->r = NULL;
171        noredo = 1;
172    }
173
174    if (dlen > BN_num_bytes(dsa->q))
175        /*
176         * if the digest length is greater than the size of q use the
177         * BN_num_bits(dsa->q) leftmost bits of the digest, see fips 186-3,
178         * 4.2
179         */
180        dlen = BN_num_bytes(dsa->q);
181    if (BN_bin2bn(dgst, dlen, m) == NULL)
182        goto err;
183
184    /*
185     * The normal signature calculation is:
186     *
187     *   s := k^-1 * (m + r * priv_key) mod q
188     *
189     * We will blind this to protect against side channel attacks
190     *
191     *   s := blind^-1 * k^-1 * (blind * m + blind * r * priv_key) mod q
192     */
193
194    /* Generate a blinding value */
195    do {
196        if (!BN_rand(blind, BN_num_bits(dsa->q) - 1, -1, 0))
197            goto err;
198    } while (BN_is_zero(blind));
199    BN_set_flags(blind, BN_FLG_CONSTTIME);
200    BN_set_flags(blindm, BN_FLG_CONSTTIME);
201    BN_set_flags(tmp, BN_FLG_CONSTTIME);
202
203    /* tmp := blind * priv_key * r mod q */
204    if (!BN_mod_mul(tmp, blind, dsa->priv_key, dsa->q, ctx))
205        goto err;
206    if (!BN_mod_mul(tmp, tmp, r, dsa->q, ctx))
207        goto err;
208
209    /* blindm := blind * m mod q */
210    if (!BN_mod_mul(blindm, blind, m, dsa->q, ctx))
211        goto err;
212
213    /* s : = (blind * priv_key * r) + (blind * m) mod q */
214    if (!BN_mod_add_quick(s, tmp, blindm, dsa->q))
215        goto err;
216
217    /* s := s * k^-1 mod q */
218    if (!BN_mod_mul(s, s, kinv, dsa->q, ctx))
219        goto err;
220
221    /* s:= s * blind^-1 mod q */
222    if (BN_mod_inverse(blind, blind, dsa->q, ctx) == NULL)
223        goto err;
224    if (!BN_mod_mul(s, s, blind, dsa->q, ctx))
225        goto err;
226
227    /*
228     * Redo if r or s is zero as required by FIPS 186-3: this is very
229     * unlikely.
230     */
231    if (BN_is_zero(r) || BN_is_zero(s)) {
232        if (noredo) {
233            reason = DSA_R_NEED_NEW_SETUP_VALUES;
234            goto err;
235        }
236        goto redo;
237    }
238    ret = DSA_SIG_new();
239    if (ret == NULL)
240        goto err;
241    ret->r = r;
242    ret->s = s;
243
244 err:
245    if (ret == NULL) {
246        DSAerr(DSA_F_DSA_DO_SIGN, reason);
247        BN_free(r);
248        BN_free(s);
249    }
250    BN_CTX_free(ctx);
251    BN_clear_free(kinv);
252    return ret;
253}
254
255static int dsa_sign_setup(DSA *dsa, BN_CTX *ctx_in, BIGNUM **kinvp,
256                          BIGNUM **rp)
257{
258    BN_CTX *ctx;
259    BIGNUM k, kq, *K, *kinv = NULL, *r = NULL;
260    BIGNUM l, m;
261    int ret = 0;
262    int q_bits;
263
264    if (!dsa->p || !dsa->q || !dsa->g) {
265        DSAerr(DSA_F_DSA_SIGN_SETUP, DSA_R_MISSING_PARAMETERS);
266        return 0;
267    }
268
269    BN_init(&k);
270    BN_init(&kq);
271    BN_init(&l);
272    BN_init(&m);
273
274    if (ctx_in == NULL) {
275        if ((ctx = BN_CTX_new()) == NULL)
276            goto err;
277    } else
278        ctx = ctx_in;
279
280    if ((r = BN_new()) == NULL)
281        goto err;
282
283    /* Preallocate space */
284    q_bits = BN_num_bits(dsa->q) + sizeof(dsa->q->d[0]) * 16;
285    if (!BN_set_bit(&k, q_bits)
286        || !BN_set_bit(&l, q_bits)
287        || !BN_set_bit(&m, q_bits))
288        goto err;
289
290    /* Get random k */
291    do
292        if (!BN_rand_range(&k, dsa->q))
293            goto err;
294    while (BN_is_zero(&k));
295
296    if ((dsa->flags & DSA_FLAG_NO_EXP_CONSTTIME) == 0) {
297        BN_set_flags(&k, BN_FLG_CONSTTIME);
298        BN_set_flags(&l, BN_FLG_CONSTTIME);
299    }
300
301    if (dsa->flags & DSA_FLAG_CACHE_MONT_P) {
302        if (!BN_MONT_CTX_set_locked(&dsa->method_mont_p,
303                                    CRYPTO_LOCK_DSA, dsa->p, ctx))
304            goto err;
305    }
306
307    /* Compute r = (g^k mod p) mod q */
308
309    if ((dsa->flags & DSA_FLAG_NO_EXP_CONSTTIME) == 0) {
310        /*
311         * We do not want timing information to leak the length of k, so we
312         * compute G^k using an equivalent scalar of fixed bit-length.
313         *
314         * We unconditionally perform both of these additions to prevent a
315         * small timing information leakage.  We then choose the sum that is
316         * one bit longer than the modulus.
317         *
318         * TODO: revisit the BN_copy aiming for a memory access agnostic
319         * conditional copy.
320         */
321        if (!BN_add(&l, &k, dsa->q)
322            || !BN_add(&m, &l, dsa->q)
323            || !BN_copy(&kq, BN_num_bits(&l) > q_bits ? &l : &m))
324            goto err;
325
326        BN_set_flags(&kq, BN_FLG_CONSTTIME);
327
328        K = &kq;
329    } else {
330        K = &k;
331    }
332
333    DSA_BN_MOD_EXP(goto err, dsa, r, dsa->g, K, dsa->p, ctx,
334                   dsa->method_mont_p);
335    if (!BN_mod(r, r, dsa->q, ctx))
336        goto err;
337
338    /* Compute part of 's = inv(k) (m + xr) mod q' */
339    if ((kinv = dsa_mod_inverse_fermat(&k, dsa->q, ctx)) == NULL)
340        goto err;
341
342    if (*kinvp != NULL)
343        BN_clear_free(*kinvp);
344    *kinvp = kinv;
345    kinv = NULL;
346    if (*rp != NULL)
347        BN_clear_free(*rp);
348    *rp = r;
349    ret = 1;
350 err:
351    if (!ret) {
352        DSAerr(DSA_F_DSA_SIGN_SETUP, ERR_R_BN_LIB);
353        if (r != NULL)
354            BN_clear_free(r);
355    }
356    if (ctx_in == NULL)
357        BN_CTX_free(ctx);
358    BN_clear_free(&k);
359    BN_clear_free(&kq);
360    BN_clear_free(&l);
361    BN_clear_free(&m);
362    return ret;
363}
364
365static int dsa_do_verify(const unsigned char *dgst, int dgst_len,
366                         DSA_SIG *sig, DSA *dsa)
367{
368    BN_CTX *ctx;
369    BIGNUM u1, u2, t1;
370    BN_MONT_CTX *mont = NULL;
371    int ret = -1, i;
372    if (!dsa->p || !dsa->q || !dsa->g) {
373        DSAerr(DSA_F_DSA_DO_VERIFY, DSA_R_MISSING_PARAMETERS);
374        return -1;
375    }
376
377    i = BN_num_bits(dsa->q);
378    /* fips 186-3 allows only different sizes for q */
379    if (i != 160 && i != 224 && i != 256) {
380        DSAerr(DSA_F_DSA_DO_VERIFY, DSA_R_BAD_Q_VALUE);
381        return -1;
382    }
383
384    if (BN_num_bits(dsa->p) > OPENSSL_DSA_MAX_MODULUS_BITS) {
385        DSAerr(DSA_F_DSA_DO_VERIFY, DSA_R_MODULUS_TOO_LARGE);
386        return -1;
387    }
388    BN_init(&u1);
389    BN_init(&u2);
390    BN_init(&t1);
391
392    if ((ctx = BN_CTX_new()) == NULL)
393        goto err;
394
395    if (BN_is_zero(sig->r) || BN_is_negative(sig->r) ||
396        BN_ucmp(sig->r, dsa->q) >= 0) {
397        ret = 0;
398        goto err;
399    }
400    if (BN_is_zero(sig->s) || BN_is_negative(sig->s) ||
401        BN_ucmp(sig->s, dsa->q) >= 0) {
402        ret = 0;
403        goto err;
404    }
405
406    /*
407     * Calculate W = inv(S) mod Q save W in u2
408     */
409    if ((BN_mod_inverse(&u2, sig->s, dsa->q, ctx)) == NULL)
410        goto err;
411
412    /* save M in u1 */
413    if (dgst_len > (i >> 3))
414        /*
415         * if the digest length is greater than the size of q use the
416         * BN_num_bits(dsa->q) leftmost bits of the digest, see fips 186-3,
417         * 4.2
418         */
419        dgst_len = (i >> 3);
420    if (BN_bin2bn(dgst, dgst_len, &u1) == NULL)
421        goto err;
422
423    /* u1 = M * w mod q */
424    if (!BN_mod_mul(&u1, &u1, &u2, dsa->q, ctx))
425        goto err;
426
427    /* u2 = r * w mod q */
428    if (!BN_mod_mul(&u2, sig->r, &u2, dsa->q, ctx))
429        goto err;
430
431    if (dsa->flags & DSA_FLAG_CACHE_MONT_P) {
432        mont = BN_MONT_CTX_set_locked(&dsa->method_mont_p,
433                                      CRYPTO_LOCK_DSA, dsa->p, ctx);
434        if (!mont)
435            goto err;
436    }
437
438    DSA_MOD_EXP(goto err, dsa, &t1, dsa->g, &u1, dsa->pub_key, &u2, dsa->p,
439                ctx, mont);
440    /* BN_copy(&u1,&t1); */
441    /* let u1 = u1 mod q */
442    if (!BN_mod(&u1, &t1, dsa->q, ctx))
443        goto err;
444
445    /*
446     * V is now in u1.  If the signature is correct, it will be equal to R.
447     */
448    ret = (BN_ucmp(&u1, sig->r) == 0);
449
450 err:
451    if (ret < 0)
452        DSAerr(DSA_F_DSA_DO_VERIFY, ERR_R_BN_LIB);
453    if (ctx != NULL)
454        BN_CTX_free(ctx);
455    BN_free(&u1);
456    BN_free(&u2);
457    BN_free(&t1);
458    return (ret);
459}
460
461static int dsa_init(DSA *dsa)
462{
463    dsa->flags |= DSA_FLAG_CACHE_MONT_P;
464    return (1);
465}
466
467static int dsa_finish(DSA *dsa)
468{
469    if (dsa->method_mont_p)
470        BN_MONT_CTX_free(dsa->method_mont_p);
471    return (1);
472}
473
474/*
475 * Compute the inverse of k modulo q.
476 * Since q is prime, Fermat's Little Theorem applies, which reduces this to
477 * mod-exp operation.  Both the exponent and modulus are public information
478 * so a mod-exp that doesn't leak the base is sufficient.  A newly allocated
479 * BIGNUM is returned which the caller must free.
480 */
481static BIGNUM *dsa_mod_inverse_fermat(const BIGNUM *k, const BIGNUM *q,
482                                      BN_CTX *ctx)
483{
484    BIGNUM *res = NULL;
485    BIGNUM *r, e;
486
487    if ((r = BN_new()) == NULL)
488        return NULL;
489
490    BN_init(&e);
491
492    if (BN_set_word(r, 2)
493            && BN_sub(&e, q, r)
494            && BN_mod_exp_mont(r, k, &e, q, ctx, NULL))
495        res = r;
496    else
497        BN_free(r);
498    BN_free(&e);
499    return res;
500}
501