Run util/openssl-format-source -v -c .
[openssl.git] / crypto / ecdsa / ecs_ossl.c
1 /* crypto/ecdsa/ecs_ossl.c */
2 /*
3  * Written by Nils Larsch for the OpenSSL project
4  */
5 /* ====================================================================
6  * Copyright (c) 1998-2004 The OpenSSL Project.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  *
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in
17  *    the documentation and/or other materials provided with the
18  *    distribution.
19  *
20  * 3. All advertising materials mentioning features or use of this
21  *    software must display the following acknowledgment:
22  *    "This product includes software developed by the OpenSSL Project
23  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
24  *
25  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
26  *    endorse or promote products derived from this software without
27  *    prior written permission. For written permission, please contact
28  *    openssl-core@OpenSSL.org.
29  *
30  * 5. Products derived from this software may not be called "OpenSSL"
31  *    nor may "OpenSSL" appear in their names without prior written
32  *    permission of the OpenSSL Project.
33  *
34  * 6. Redistributions of any form whatsoever must retain the following
35  *    acknowledgment:
36  *    "This product includes software developed by the OpenSSL Project
37  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
38  *
39  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
40  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
41  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
42  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
43  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
44  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
45  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
46  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
48  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
49  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
50  * OF THE POSSIBILITY OF SUCH DAMAGE.
51  * ====================================================================
52  *
53  * This product includes cryptographic software written by Eric Young
54  * (eay@cryptsoft.com).  This product includes software written by Tim
55  * Hudson (tjh@cryptsoft.com).
56  *
57  */
58
59 #include "ecs_locl.h"
60 #include <openssl/err.h>
61 #include <openssl/obj_mac.h>
62 #include <openssl/bn.h>
63 #include <openssl/rand.h>
64
65 static ECDSA_SIG *ecdsa_do_sign(const unsigned char *dgst, int dlen,
66                                 const BIGNUM *, const BIGNUM *,
67                                 EC_KEY *eckey);
68 static int ecdsa_sign_setup_no_digest(EC_KEY *eckey, BN_CTX *ctx_in,
69                                       BIGNUM **kinvp, BIGNUM **rp);
70 static int ecdsa_sign_setup(EC_KEY *eckey, BN_CTX *ctx_in, BIGNUM **kinvp,
71                             BIGNUM **rp, const unsigned char *dgst, int dlen);
72 static int ecdsa_do_verify(const unsigned char *dgst, int dgst_len,
73                            const ECDSA_SIG *sig, EC_KEY *eckey);
74
75 static ECDSA_METHOD openssl_ecdsa_meth = {
76     "OpenSSL ECDSA method",
77     ecdsa_do_sign,
78     ecdsa_sign_setup_no_digest,
79     ecdsa_do_verify,
80 #if 0
81     NULL,                       /* init */
82     NULL,                       /* finish */
83 #endif
84     ECDSA_FLAG_FIPS_METHOD,     /* flags */
85     NULL                        /* app_data */
86 };
87
88 const ECDSA_METHOD *ECDSA_OpenSSL(void)
89 {
90     return &openssl_ecdsa_meth;
91 }
92
93 static int ecdsa_sign_setup_no_digest(EC_KEY *eckey,
94                                       BN_CTX *ctx_in, BIGNUM **kinvp,
95                                       BIGNUM **rp)
96 {
97     return ecdsa_sign_setup(eckey, ctx_in, kinvp, rp, NULL, 0);
98 }
99
100 static int ecdsa_sign_setup(EC_KEY *eckey, BN_CTX *ctx_in,
101                             BIGNUM **kinvp, BIGNUM **rp,
102                             const unsigned char *dgst, int dlen)
103 {
104     BN_CTX *ctx = NULL;
105     BIGNUM *k = NULL, *r = NULL, *order = NULL, *X = NULL;
106     EC_POINT *tmp_point = NULL;
107     const EC_GROUP *group;
108     int ret = 0;
109
110     if (eckey == NULL || (group = EC_KEY_get0_group(eckey)) == NULL) {
111         ECDSAerr(ECDSA_F_ECDSA_SIGN_SETUP, ERR_R_PASSED_NULL_PARAMETER);
112         return 0;
113     }
114
115     if (ctx_in == NULL) {
116         if ((ctx = BN_CTX_new()) == NULL) {
117             ECDSAerr(ECDSA_F_ECDSA_SIGN_SETUP, ERR_R_MALLOC_FAILURE);
118             return 0;
119         }
120     } else
121         ctx = ctx_in;
122
123     k = BN_new();               /* this value is later returned in *kinvp */
124     r = BN_new();               /* this value is later returned in *rp */
125     order = BN_new();
126     X = BN_new();
127     if (!k || !r || !order || !X) {
128         ECDSAerr(ECDSA_F_ECDSA_SIGN_SETUP, ERR_R_MALLOC_FAILURE);
129         goto err;
130     }
131     if ((tmp_point = EC_POINT_new(group)) == NULL) {
132         ECDSAerr(ECDSA_F_ECDSA_SIGN_SETUP, ERR_R_EC_LIB);
133         goto err;
134     }
135     if (!EC_GROUP_get_order(group, order, ctx)) {
136         ECDSAerr(ECDSA_F_ECDSA_SIGN_SETUP, ERR_R_EC_LIB);
137         goto err;
138     }
139
140     do {
141         /* get random k */
142         do
143 #ifndef OPENSSL_NO_SHA512
144             if (dgst != NULL) {
145                 if (!BN_generate_dsa_nonce
146                     (k, order, EC_KEY_get0_private_key(eckey), dgst, dlen,
147                      ctx)) {
148                     ECDSAerr(ECDSA_F_ECDSA_SIGN_SETUP,
149                              ECDSA_R_RANDOM_NUMBER_GENERATION_FAILED);
150                     goto err;
151                 }
152             } else
153 #endif
154             {
155                 if (!BN_rand_range(k, order)) {
156                     ECDSAerr(ECDSA_F_ECDSA_SIGN_SETUP,
157                              ECDSA_R_RANDOM_NUMBER_GENERATION_FAILED);
158                     goto err;
159                 }
160             }
161         while (BN_is_zero(k));
162
163         /*
164          * We do not want timing information to leak the length of k, so we
165          * compute G*k using an equivalent scalar of fixed bit-length.
166          */
167
168         if (!BN_add(k, k, order))
169             goto err;
170         if (BN_num_bits(k) <= BN_num_bits(order))
171             if (!BN_add(k, k, order))
172                 goto err;
173
174         /* compute r the x-coordinate of generator * k */
175         if (!EC_POINT_mul(group, tmp_point, k, NULL, NULL, ctx)) {
176             ECDSAerr(ECDSA_F_ECDSA_SIGN_SETUP, ERR_R_EC_LIB);
177             goto err;
178         }
179         if (EC_METHOD_get_field_type(EC_GROUP_method_of(group)) ==
180             NID_X9_62_prime_field) {
181             if (!EC_POINT_get_affine_coordinates_GFp
182                 (group, tmp_point, X, NULL, ctx)) {
183                 ECDSAerr(ECDSA_F_ECDSA_SIGN_SETUP, ERR_R_EC_LIB);
184                 goto err;
185             }
186         }
187 #ifndef OPENSSL_NO_EC2M
188         else {                  /* NID_X9_62_characteristic_two_field */
189
190             if (!EC_POINT_get_affine_coordinates_GF2m(group,
191                                                       tmp_point, X, NULL,
192                                                       ctx)) {
193                 ECDSAerr(ECDSA_F_ECDSA_SIGN_SETUP, ERR_R_EC_LIB);
194                 goto err;
195             }
196         }
197 #endif
198         if (!BN_nnmod(r, X, order, ctx)) {
199             ECDSAerr(ECDSA_F_ECDSA_SIGN_SETUP, ERR_R_BN_LIB);
200             goto err;
201         }
202     }
203     while (BN_is_zero(r));
204
205     /* compute the inverse of k */
206     if (EC_GROUP_get_mont_data(group) != NULL) {
207         /*
208          * We want inverse in constant time, therefore we utilize the fact
209          * order must be prime and use Fermats Little Theorem instead.
210          */
211         if (!BN_set_word(X, 2)) {
212             ECDSAerr(ECDSA_F_ECDSA_SIGN_SETUP, ERR_R_BN_LIB);
213             goto err;
214         }
215         if (!BN_mod_sub(X, order, X, order, ctx)) {
216             ECDSAerr(ECDSA_F_ECDSA_SIGN_SETUP, ERR_R_BN_LIB);
217             goto err;
218         }
219         BN_set_flags(X, BN_FLG_CONSTTIME);
220         if (!BN_mod_exp_mont_consttime
221             (k, k, X, order, ctx, EC_GROUP_get_mont_data(group))) {
222             ECDSAerr(ECDSA_F_ECDSA_SIGN_SETUP, ERR_R_BN_LIB);
223             goto err;
224         }
225     } else {
226         if (!BN_mod_inverse(k, k, order, ctx)) {
227             ECDSAerr(ECDSA_F_ECDSA_SIGN_SETUP, ERR_R_BN_LIB);
228             goto err;
229         }
230     }
231
232     /* clear old values if necessary */
233     if (*rp != NULL)
234         BN_clear_free(*rp);
235     if (*kinvp != NULL)
236         BN_clear_free(*kinvp);
237     /* save the pre-computed values  */
238     *rp = r;
239     *kinvp = k;
240     ret = 1;
241  err:
242     if (!ret) {
243         if (k != NULL)
244             BN_clear_free(k);
245         if (r != NULL)
246             BN_clear_free(r);
247     }
248     if (ctx_in == NULL)
249         BN_CTX_free(ctx);
250     if (order != NULL)
251         BN_free(order);
252     if (tmp_point != NULL)
253         EC_POINT_free(tmp_point);
254     if (X)
255         BN_clear_free(X);
256     return (ret);
257 }
258
259 static ECDSA_SIG *ecdsa_do_sign(const unsigned char *dgst, int dgst_len,
260                                 const BIGNUM *in_kinv, const BIGNUM *in_r,
261                                 EC_KEY *eckey)
262 {
263     int ok = 0, i;
264     BIGNUM *kinv = NULL, *s, *m = NULL, *tmp = NULL, *order = NULL;
265     const BIGNUM *ckinv;
266     BN_CTX *ctx = NULL;
267     const EC_GROUP *group;
268     ECDSA_SIG *ret;
269     ECDSA_DATA *ecdsa;
270     const BIGNUM *priv_key;
271
272     ecdsa = ecdsa_check(eckey);
273     group = EC_KEY_get0_group(eckey);
274     priv_key = EC_KEY_get0_private_key(eckey);
275
276     if (group == NULL || priv_key == NULL || ecdsa == NULL) {
277         ECDSAerr(ECDSA_F_ECDSA_DO_SIGN, ERR_R_PASSED_NULL_PARAMETER);
278         return NULL;
279     }
280
281     ret = ECDSA_SIG_new();
282     if (!ret) {
283         ECDSAerr(ECDSA_F_ECDSA_DO_SIGN, ERR_R_MALLOC_FAILURE);
284         return NULL;
285     }
286     s = ret->s;
287
288     if ((ctx = BN_CTX_new()) == NULL || (order = BN_new()) == NULL ||
289         (tmp = BN_new()) == NULL || (m = BN_new()) == NULL) {
290         ECDSAerr(ECDSA_F_ECDSA_DO_SIGN, ERR_R_MALLOC_FAILURE);
291         goto err;
292     }
293
294     if (!EC_GROUP_get_order(group, order, ctx)) {
295         ECDSAerr(ECDSA_F_ECDSA_DO_SIGN, ERR_R_EC_LIB);
296         goto err;
297     }
298     i = BN_num_bits(order);
299     /*
300      * Need to truncate digest if it is too long: first truncate whole bytes.
301      */
302     if (8 * dgst_len > i)
303         dgst_len = (i + 7) / 8;
304     if (!BN_bin2bn(dgst, dgst_len, m)) {
305         ECDSAerr(ECDSA_F_ECDSA_DO_SIGN, ERR_R_BN_LIB);
306         goto err;
307     }
308     /* If still too long truncate remaining bits with a shift */
309     if ((8 * dgst_len > i) && !BN_rshift(m, m, 8 - (i & 0x7))) {
310         ECDSAerr(ECDSA_F_ECDSA_DO_SIGN, ERR_R_BN_LIB);
311         goto err;
312     }
313     do {
314         if (in_kinv == NULL || in_r == NULL) {
315             if (!ecdsa_sign_setup(eckey, ctx, &kinv, &ret->r, dgst, dgst_len)) {
316                 ECDSAerr(ECDSA_F_ECDSA_DO_SIGN, ERR_R_ECDSA_LIB);
317                 goto err;
318             }
319             ckinv = kinv;
320         } else {
321             ckinv = in_kinv;
322             if (BN_copy(ret->r, in_r) == NULL) {
323                 ECDSAerr(ECDSA_F_ECDSA_DO_SIGN, ERR_R_MALLOC_FAILURE);
324                 goto err;
325             }
326         }
327
328         if (!BN_mod_mul(tmp, priv_key, ret->r, order, ctx)) {
329             ECDSAerr(ECDSA_F_ECDSA_DO_SIGN, ERR_R_BN_LIB);
330             goto err;
331         }
332         if (!BN_mod_add_quick(s, tmp, m, order)) {
333             ECDSAerr(ECDSA_F_ECDSA_DO_SIGN, ERR_R_BN_LIB);
334             goto err;
335         }
336         if (!BN_mod_mul(s, s, ckinv, order, ctx)) {
337             ECDSAerr(ECDSA_F_ECDSA_DO_SIGN, ERR_R_BN_LIB);
338             goto err;
339         }
340         if (BN_is_zero(s)) {
341             /*
342              * if kinv and r have been supplied by the caller don't to
343              * generate new kinv and r values
344              */
345             if (in_kinv != NULL && in_r != NULL) {
346                 ECDSAerr(ECDSA_F_ECDSA_DO_SIGN,
347                          ECDSA_R_NEED_NEW_SETUP_VALUES);
348                 goto err;
349             }
350         } else
351             /* s != 0 => we have a valid signature */
352             break;
353     }
354     while (1);
355
356     ok = 1;
357  err:
358     if (!ok) {
359         ECDSA_SIG_free(ret);
360         ret = NULL;
361     }
362     if (ctx)
363         BN_CTX_free(ctx);
364     if (m)
365         BN_clear_free(m);
366     if (tmp)
367         BN_clear_free(tmp);
368     if (order)
369         BN_free(order);
370     if (kinv)
371         BN_clear_free(kinv);
372     return ret;
373 }
374
375 static int ecdsa_do_verify(const unsigned char *dgst, int dgst_len,
376                            const ECDSA_SIG *sig, EC_KEY *eckey)
377 {
378     int ret = -1, i;
379     BN_CTX *ctx;
380     BIGNUM *order, *u1, *u2, *m, *X;
381     EC_POINT *point = NULL;
382     const EC_GROUP *group;
383     const EC_POINT *pub_key;
384
385     /* check input values */
386     if (eckey == NULL || (group = EC_KEY_get0_group(eckey)) == NULL ||
387         (pub_key = EC_KEY_get0_public_key(eckey)) == NULL || sig == NULL) {
388         ECDSAerr(ECDSA_F_ECDSA_DO_VERIFY, ECDSA_R_MISSING_PARAMETERS);
389         return -1;
390     }
391
392     ctx = BN_CTX_new();
393     if (!ctx) {
394         ECDSAerr(ECDSA_F_ECDSA_DO_VERIFY, ERR_R_MALLOC_FAILURE);
395         return -1;
396     }
397     BN_CTX_start(ctx);
398     order = BN_CTX_get(ctx);
399     u1 = BN_CTX_get(ctx);
400     u2 = BN_CTX_get(ctx);
401     m = BN_CTX_get(ctx);
402     X = BN_CTX_get(ctx);
403     if (!X) {
404         ECDSAerr(ECDSA_F_ECDSA_DO_VERIFY, ERR_R_BN_LIB);
405         goto err;
406     }
407
408     if (!EC_GROUP_get_order(group, order, ctx)) {
409         ECDSAerr(ECDSA_F_ECDSA_DO_VERIFY, ERR_R_EC_LIB);
410         goto err;
411     }
412
413     if (BN_is_zero(sig->r) || BN_is_negative(sig->r) ||
414         BN_ucmp(sig->r, order) >= 0 || BN_is_zero(sig->s) ||
415         BN_is_negative(sig->s) || BN_ucmp(sig->s, order) >= 0) {
416         ECDSAerr(ECDSA_F_ECDSA_DO_VERIFY, ECDSA_R_BAD_SIGNATURE);
417         ret = 0;                /* signature is invalid */
418         goto err;
419     }
420     /* calculate tmp1 = inv(S) mod order */
421     if (!BN_mod_inverse(u2, sig->s, order, ctx)) {
422         ECDSAerr(ECDSA_F_ECDSA_DO_VERIFY, ERR_R_BN_LIB);
423         goto err;
424     }
425     /* digest -> m */
426     i = BN_num_bits(order);
427     /*
428      * Need to truncate digest if it is too long: first truncate whole bytes.
429      */
430     if (8 * dgst_len > i)
431         dgst_len = (i + 7) / 8;
432     if (!BN_bin2bn(dgst, dgst_len, m)) {
433         ECDSAerr(ECDSA_F_ECDSA_DO_VERIFY, ERR_R_BN_LIB);
434         goto err;
435     }
436     /* If still too long truncate remaining bits with a shift */
437     if ((8 * dgst_len > i) && !BN_rshift(m, m, 8 - (i & 0x7))) {
438         ECDSAerr(ECDSA_F_ECDSA_DO_VERIFY, ERR_R_BN_LIB);
439         goto err;
440     }
441     /* u1 = m * tmp mod order */
442     if (!BN_mod_mul(u1, m, u2, order, ctx)) {
443         ECDSAerr(ECDSA_F_ECDSA_DO_VERIFY, ERR_R_BN_LIB);
444         goto err;
445     }
446     /* u2 = r * w mod q */
447     if (!BN_mod_mul(u2, sig->r, u2, order, ctx)) {
448         ECDSAerr(ECDSA_F_ECDSA_DO_VERIFY, ERR_R_BN_LIB);
449         goto err;
450     }
451
452     if ((point = EC_POINT_new(group)) == NULL) {
453         ECDSAerr(ECDSA_F_ECDSA_DO_VERIFY, ERR_R_MALLOC_FAILURE);
454         goto err;
455     }
456     if (!EC_POINT_mul(group, point, u1, pub_key, u2, ctx)) {
457         ECDSAerr(ECDSA_F_ECDSA_DO_VERIFY, ERR_R_EC_LIB);
458         goto err;
459     }
460     if (EC_METHOD_get_field_type(EC_GROUP_method_of(group)) ==
461         NID_X9_62_prime_field) {
462         if (!EC_POINT_get_affine_coordinates_GFp(group, point, X, NULL, ctx)) {
463             ECDSAerr(ECDSA_F_ECDSA_DO_VERIFY, ERR_R_EC_LIB);
464             goto err;
465         }
466     }
467 #ifndef OPENSSL_NO_EC2M
468     else {                      /* NID_X9_62_characteristic_two_field */
469
470         if (!EC_POINT_get_affine_coordinates_GF2m(group, point, X, NULL, ctx)) {
471             ECDSAerr(ECDSA_F_ECDSA_DO_VERIFY, ERR_R_EC_LIB);
472             goto err;
473         }
474     }
475 #endif
476     if (!BN_nnmod(u1, X, order, ctx)) {
477         ECDSAerr(ECDSA_F_ECDSA_DO_VERIFY, ERR_R_BN_LIB);
478         goto err;
479     }
480     /*  if the signature is correct u1 is equal to sig->r */
481     ret = (BN_ucmp(u1, sig->r) == 0);
482  err:
483     BN_CTX_end(ctx);
484     BN_CTX_free(ctx);
485     if (point)
486         EC_POINT_free(point);
487     return ret;
488 }