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