Remove the GOST engine
[openssl.git] / crypto / ec / ec_ameth.c
1 /*
2  * Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL project
3  * 2006.
4  */
5 /* ====================================================================
6  * Copyright (c) 2006 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  *    licensing@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 <stdio.h>
60 #include "internal/cryptlib.h"
61 #include <openssl/x509.h>
62 #include <openssl/ec.h>
63 #include <openssl/bn.h>
64 #ifndef OPENSSL_NO_CMS
65 # include <openssl/cms.h>
66 #endif
67 #include <openssl/asn1t.h>
68 #include "internal/asn1_int.h"
69
70 #ifndef OPENSSL_NO_CMS
71 static int ecdh_cms_decrypt(CMS_RecipientInfo *ri);
72 static int ecdh_cms_encrypt(CMS_RecipientInfo *ri);
73 #endif
74
75 static int eckey_param2type(int *pptype, void **ppval, EC_KEY *ec_key)
76 {
77     const EC_GROUP *group;
78     int nid;
79     if (ec_key == NULL || (group = EC_KEY_get0_group(ec_key)) == NULL) {
80         ECerr(EC_F_ECKEY_PARAM2TYPE, EC_R_MISSING_PARAMETERS);
81         return 0;
82     }
83     if (EC_GROUP_get_asn1_flag(group)
84         && (nid = EC_GROUP_get_curve_name(group)))
85         /* we have a 'named curve' => just set the OID */
86     {
87         *ppval = OBJ_nid2obj(nid);
88         *pptype = V_ASN1_OBJECT;
89     } else {                    /* explicit parameters */
90
91         ASN1_STRING *pstr = NULL;
92         pstr = ASN1_STRING_new();
93         if (pstr == NULL)
94             return 0;
95         pstr->length = i2d_ECParameters(ec_key, &pstr->data);
96         if (pstr->length <= 0) {
97             ASN1_STRING_free(pstr);
98             ECerr(EC_F_ECKEY_PARAM2TYPE, ERR_R_EC_LIB);
99             return 0;
100         }
101         *ppval = pstr;
102         *pptype = V_ASN1_SEQUENCE;
103     }
104     return 1;
105 }
106
107 static int eckey_pub_encode(X509_PUBKEY *pk, const EVP_PKEY *pkey)
108 {
109     EC_KEY *ec_key = pkey->pkey.ec;
110     void *pval = NULL;
111     int ptype;
112     unsigned char *penc = NULL, *p;
113     int penclen;
114
115     if (!eckey_param2type(&ptype, &pval, ec_key)) {
116         ECerr(EC_F_ECKEY_PUB_ENCODE, ERR_R_EC_LIB);
117         return 0;
118     }
119     penclen = i2o_ECPublicKey(ec_key, NULL);
120     if (penclen <= 0)
121         goto err;
122     penc = OPENSSL_malloc(penclen);
123     if (penc == NULL)
124         goto err;
125     p = penc;
126     penclen = i2o_ECPublicKey(ec_key, &p);
127     if (penclen <= 0)
128         goto err;
129     if (X509_PUBKEY_set0_param(pk, OBJ_nid2obj(EVP_PKEY_EC),
130                                ptype, pval, penc, penclen))
131         return 1;
132  err:
133     if (ptype == V_ASN1_OBJECT)
134         ASN1_OBJECT_free(pval);
135     else
136         ASN1_STRING_free(pval);
137     OPENSSL_free(penc);
138     return 0;
139 }
140
141 static EC_KEY *eckey_type2param(int ptype, void *pval)
142 {
143     EC_KEY *eckey = NULL;
144     if (ptype == V_ASN1_SEQUENCE) {
145         ASN1_STRING *pstr = pval;
146         const unsigned char *pm = NULL;
147         int pmlen;
148         pm = pstr->data;
149         pmlen = pstr->length;
150         if ((eckey = d2i_ECParameters(NULL, &pm, pmlen)) == NULL) {
151             ECerr(EC_F_ECKEY_TYPE2PARAM, EC_R_DECODE_ERROR);
152             goto ecerr;
153         }
154     } else if (ptype == V_ASN1_OBJECT) {
155         ASN1_OBJECT *poid = pval;
156         EC_GROUP *group;
157
158         /*
159          * type == V_ASN1_OBJECT => the parameters are given by an asn1 OID
160          */
161         if ((eckey = EC_KEY_new()) == NULL) {
162             ECerr(EC_F_ECKEY_TYPE2PARAM, ERR_R_MALLOC_FAILURE);
163             goto ecerr;
164         }
165         group = EC_GROUP_new_by_curve_name(OBJ_obj2nid(poid));
166         if (group == NULL)
167             goto ecerr;
168         EC_GROUP_set_asn1_flag(group, OPENSSL_EC_NAMED_CURVE);
169         if (EC_KEY_set_group(eckey, group) == 0)
170             goto ecerr;
171         EC_GROUP_free(group);
172     } else {
173         ECerr(EC_F_ECKEY_TYPE2PARAM, EC_R_DECODE_ERROR);
174         goto ecerr;
175     }
176
177     return eckey;
178
179  ecerr:
180     EC_KEY_free(eckey);
181     return NULL;
182 }
183
184 static int eckey_pub_decode(EVP_PKEY *pkey, X509_PUBKEY *pubkey)
185 {
186     const unsigned char *p = NULL;
187     void *pval;
188     int ptype, pklen;
189     EC_KEY *eckey = NULL;
190     X509_ALGOR *palg;
191
192     if (!X509_PUBKEY_get0_param(NULL, &p, &pklen, &palg, pubkey))
193         return 0;
194     X509_ALGOR_get0(NULL, &ptype, &pval, palg);
195
196     eckey = eckey_type2param(ptype, pval);
197
198     if (!eckey) {
199         ECerr(EC_F_ECKEY_PUB_DECODE, ERR_R_EC_LIB);
200         return 0;
201     }
202
203     /* We have parameters now set public key */
204     if (!o2i_ECPublicKey(&eckey, &p, pklen)) {
205         ECerr(EC_F_ECKEY_PUB_DECODE, EC_R_DECODE_ERROR);
206         goto ecerr;
207     }
208
209     EVP_PKEY_assign_EC_KEY(pkey, eckey);
210     return 1;
211
212  ecerr:
213     EC_KEY_free(eckey);
214     return 0;
215 }
216
217 static int eckey_pub_cmp(const EVP_PKEY *a, const EVP_PKEY *b)
218 {
219     int r;
220     const EC_GROUP *group = EC_KEY_get0_group(b->pkey.ec);
221     const EC_POINT *pa = EC_KEY_get0_public_key(a->pkey.ec),
222         *pb = EC_KEY_get0_public_key(b->pkey.ec);
223     r = EC_POINT_cmp(group, pa, pb, NULL);
224     if (r == 0)
225         return 1;
226     if (r == 1)
227         return 0;
228     return -2;
229 }
230
231 static int eckey_priv_decode(EVP_PKEY *pkey, PKCS8_PRIV_KEY_INFO *p8)
232 {
233     const unsigned char *p = NULL;
234     void *pval;
235     int ptype, pklen;
236     EC_KEY *eckey = NULL;
237     X509_ALGOR *palg;
238
239     if (!PKCS8_pkey_get0(NULL, &p, &pklen, &palg, p8))
240         return 0;
241     X509_ALGOR_get0(NULL, &ptype, &pval, palg);
242
243     eckey = eckey_type2param(ptype, pval);
244
245     if (!eckey)
246         goto ecliberr;
247
248     /* We have parameters now set private key */
249     if (!d2i_ECPrivateKey(&eckey, &p, pklen)) {
250         ECerr(EC_F_ECKEY_PRIV_DECODE, EC_R_DECODE_ERROR);
251         goto ecerr;
252     }
253
254     /* calculate public key (if necessary) */
255     if (EC_KEY_get0_public_key(eckey) == NULL) {
256         const BIGNUM *priv_key;
257         const EC_GROUP *group;
258         EC_POINT *pub_key;
259         /*
260          * the public key was not included in the SEC1 private key =>
261          * calculate the public key
262          */
263         group = EC_KEY_get0_group(eckey);
264         pub_key = EC_POINT_new(group);
265         if (pub_key == NULL) {
266             ECerr(EC_F_ECKEY_PRIV_DECODE, ERR_R_EC_LIB);
267             goto ecliberr;
268         }
269         if (!EC_POINT_copy(pub_key, EC_GROUP_get0_generator(group))) {
270             EC_POINT_free(pub_key);
271             ECerr(EC_F_ECKEY_PRIV_DECODE, ERR_R_EC_LIB);
272             goto ecliberr;
273         }
274         priv_key = EC_KEY_get0_private_key(eckey);
275         if (!EC_POINT_mul(group, pub_key, priv_key, NULL, NULL, NULL)) {
276             EC_POINT_free(pub_key);
277             ECerr(EC_F_ECKEY_PRIV_DECODE, ERR_R_EC_LIB);
278             goto ecliberr;
279         }
280         if (EC_KEY_set_public_key(eckey, pub_key) == 0) {
281             EC_POINT_free(pub_key);
282             ECerr(EC_F_ECKEY_PRIV_DECODE, ERR_R_EC_LIB);
283             goto ecliberr;
284         }
285         EC_POINT_free(pub_key);
286     }
287
288     EVP_PKEY_assign_EC_KEY(pkey, eckey);
289     return 1;
290
291  ecliberr:
292     ECerr(EC_F_ECKEY_PRIV_DECODE, ERR_R_EC_LIB);
293  ecerr:
294     EC_KEY_free(eckey);
295     return 0;
296 }
297
298 static int eckey_priv_encode(PKCS8_PRIV_KEY_INFO *p8, const EVP_PKEY *pkey)
299 {
300     EC_KEY *ec_key;
301     unsigned char *ep, *p;
302     int eplen, ptype;
303     void *pval;
304     unsigned int tmp_flags, old_flags;
305
306     ec_key = pkey->pkey.ec;
307
308     if (!eckey_param2type(&ptype, &pval, ec_key)) {
309         ECerr(EC_F_ECKEY_PRIV_ENCODE, EC_R_DECODE_ERROR);
310         return 0;
311     }
312
313     /* set the private key */
314
315     /*
316      * do not include the parameters in the SEC1 private key see PKCS#11
317      * 12.11
318      */
319     old_flags = EC_KEY_get_enc_flags(ec_key);
320     tmp_flags = old_flags | EC_PKEY_NO_PARAMETERS;
321     EC_KEY_set_enc_flags(ec_key, tmp_flags);
322     eplen = i2d_ECPrivateKey(ec_key, NULL);
323     if (!eplen) {
324         EC_KEY_set_enc_flags(ec_key, old_flags);
325         ECerr(EC_F_ECKEY_PRIV_ENCODE, ERR_R_EC_LIB);
326         return 0;
327     }
328     ep = OPENSSL_malloc(eplen);
329     if (ep == NULL) {
330         EC_KEY_set_enc_flags(ec_key, old_flags);
331         ECerr(EC_F_ECKEY_PRIV_ENCODE, ERR_R_MALLOC_FAILURE);
332         return 0;
333     }
334     p = ep;
335     if (!i2d_ECPrivateKey(ec_key, &p)) {
336         EC_KEY_set_enc_flags(ec_key, old_flags);
337         OPENSSL_free(ep);
338         ECerr(EC_F_ECKEY_PRIV_ENCODE, ERR_R_EC_LIB);
339         return 0;
340     }
341     /* restore old encoding flags */
342     EC_KEY_set_enc_flags(ec_key, old_flags);
343
344     if (!PKCS8_pkey_set0(p8, OBJ_nid2obj(NID_X9_62_id_ecPublicKey), 0,
345                          ptype, pval, ep, eplen))
346         return 0;
347
348     return 1;
349 }
350
351 static int int_ec_size(const EVP_PKEY *pkey)
352 {
353     return ECDSA_size(pkey->pkey.ec);
354 }
355
356 static int ec_bits(const EVP_PKEY *pkey)
357 {
358     BIGNUM *order = BN_new();
359     const EC_GROUP *group;
360     int ret;
361
362     if (order == NULL) {
363         ERR_clear_error();
364         return 0;
365     }
366     group = EC_KEY_get0_group(pkey->pkey.ec);
367     if (!EC_GROUP_get_order(group, order, NULL)) {
368         ERR_clear_error();
369         return 0;
370     }
371
372     ret = BN_num_bits(order);
373     BN_free(order);
374     return ret;
375 }
376
377 static int ec_security_bits(const EVP_PKEY *pkey)
378 {
379     int ecbits = ec_bits(pkey);
380     if (ecbits >= 512)
381         return 256;
382     if (ecbits >= 384)
383         return 192;
384     if (ecbits >= 256)
385         return 128;
386     if (ecbits >= 224)
387         return 112;
388     if (ecbits >= 160)
389         return 80;
390     return ecbits / 2;
391 }
392
393 static int ec_missing_parameters(const EVP_PKEY *pkey)
394 {
395     if (EC_KEY_get0_group(pkey->pkey.ec) == NULL)
396         return 1;
397     return 0;
398 }
399
400 static int ec_copy_parameters(EVP_PKEY *to, const EVP_PKEY *from)
401 {
402     EC_GROUP *group = EC_GROUP_dup(EC_KEY_get0_group(from->pkey.ec));
403     if (group == NULL)
404         return 0;
405     if (to->pkey.ec == NULL) {
406         to->pkey.ec = EC_KEY_new();
407         if (to->pkey.ec == NULL)
408             return 0;
409     }
410     if (EC_KEY_set_group(to->pkey.ec, group) == 0)
411         return 0;
412     EC_GROUP_free(group);
413     return 1;
414 }
415
416 static int ec_cmp_parameters(const EVP_PKEY *a, const EVP_PKEY *b)
417 {
418     const EC_GROUP *group_a = EC_KEY_get0_group(a->pkey.ec),
419         *group_b = EC_KEY_get0_group(b->pkey.ec);
420     if (EC_GROUP_cmp(group_a, group_b, NULL))
421         return 0;
422     else
423         return 1;
424 }
425
426 static void int_ec_free(EVP_PKEY *pkey)
427 {
428     EC_KEY_free(pkey->pkey.ec);
429 }
430
431 static int do_EC_KEY_print(BIO *bp, const EC_KEY *x, int off, int ktype)
432 {
433     unsigned char *buffer = NULL;
434     const char *ecstr;
435     size_t buf_len = 0, i;
436     int ret = 0, reason = ERR_R_BIO_LIB;
437     BIGNUM *pub_key = NULL, *order = NULL;
438     BN_CTX *ctx = NULL;
439     const EC_GROUP *group;
440     const EC_POINT *public_key;
441     const BIGNUM *priv_key;
442
443     if (x == NULL || (group = EC_KEY_get0_group(x)) == NULL) {
444         reason = ERR_R_PASSED_NULL_PARAMETER;
445         goto err;
446     }
447
448     ctx = BN_CTX_new();
449     if (ctx == NULL) {
450         reason = ERR_R_MALLOC_FAILURE;
451         goto err;
452     }
453
454     if (ktype > 0) {
455         public_key = EC_KEY_get0_public_key(x);
456         if (public_key != NULL) {
457             if ((pub_key = EC_POINT_point2bn(group, public_key,
458                                              EC_KEY_get_conv_form(x), NULL,
459                                              ctx)) == NULL) {
460                 reason = ERR_R_EC_LIB;
461                 goto err;
462             }
463             buf_len = (size_t)BN_num_bytes(pub_key);
464         }
465     }
466
467     if (ktype == 2) {
468         priv_key = EC_KEY_get0_private_key(x);
469         if (priv_key && (i = (size_t)BN_num_bytes(priv_key)) > buf_len)
470             buf_len = i;
471     } else
472         priv_key = NULL;
473
474     if (ktype > 0) {
475         buf_len += 10;
476         if ((buffer = OPENSSL_malloc(buf_len)) == NULL) {
477             reason = ERR_R_MALLOC_FAILURE;
478             goto err;
479         }
480     }
481     if (ktype == 2)
482         ecstr = "Private-Key";
483     else if (ktype == 1)
484         ecstr = "Public-Key";
485     else
486         ecstr = "ECDSA-Parameters";
487
488     if (!BIO_indent(bp, off, 128))
489         goto err;
490     if ((order = BN_new()) == NULL)
491         goto err;
492     if (!EC_GROUP_get_order(group, order, NULL))
493         goto err;
494     if (BIO_printf(bp, "%s: (%d bit)\n", ecstr, BN_num_bits(order)) <= 0)
495         goto err;
496
497     if ((priv_key != NULL) && !ASN1_bn_print(bp, "priv:", priv_key,
498                                              buffer, off))
499         goto err;
500     if ((pub_key != NULL) && !ASN1_bn_print(bp, "pub: ", pub_key,
501                                             buffer, off))
502         goto err;
503     if (!ECPKParameters_print(bp, group, off))
504         goto err;
505     ret = 1;
506  err:
507     if (!ret)
508         ECerr(EC_F_DO_EC_KEY_PRINT, reason);
509     BN_free(pub_key);
510     BN_free(order);
511     BN_CTX_free(ctx);
512     OPENSSL_free(buffer);
513     return (ret);
514 }
515
516 static int eckey_param_decode(EVP_PKEY *pkey,
517                               const unsigned char **pder, int derlen)
518 {
519     EC_KEY *eckey;
520
521     if ((eckey = d2i_ECParameters(NULL, pder, derlen)) == NULL) {
522         ECerr(EC_F_ECKEY_PARAM_DECODE, ERR_R_EC_LIB);
523         return 0;
524     }
525     EVP_PKEY_assign_EC_KEY(pkey, eckey);
526     return 1;
527 }
528
529 static int eckey_param_encode(const EVP_PKEY *pkey, unsigned char **pder)
530 {
531     return i2d_ECParameters(pkey->pkey.ec, pder);
532 }
533
534 static int eckey_param_print(BIO *bp, const EVP_PKEY *pkey, int indent,
535                              ASN1_PCTX *ctx)
536 {
537     return do_EC_KEY_print(bp, pkey->pkey.ec, indent, 0);
538 }
539
540 static int eckey_pub_print(BIO *bp, const EVP_PKEY *pkey, int indent,
541                            ASN1_PCTX *ctx)
542 {
543     return do_EC_KEY_print(bp, pkey->pkey.ec, indent, 1);
544 }
545
546 static int eckey_priv_print(BIO *bp, const EVP_PKEY *pkey, int indent,
547                             ASN1_PCTX *ctx)
548 {
549     return do_EC_KEY_print(bp, pkey->pkey.ec, indent, 2);
550 }
551
552 static int old_ec_priv_decode(EVP_PKEY *pkey,
553                               const unsigned char **pder, int derlen)
554 {
555     EC_KEY *ec;
556
557     if ((ec = d2i_ECPrivateKey(NULL, pder, derlen)) == NULL) {
558         ECerr(EC_F_OLD_EC_PRIV_DECODE, EC_R_DECODE_ERROR);
559         return 0;
560     }
561     EVP_PKEY_assign_EC_KEY(pkey, ec);
562     return 1;
563 }
564
565 static int old_ec_priv_encode(const EVP_PKEY *pkey, unsigned char **pder)
566 {
567     return i2d_ECPrivateKey(pkey->pkey.ec, pder);
568 }
569
570 static int ec_pkey_ctrl(EVP_PKEY *pkey, int op, long arg1, void *arg2)
571 {
572     switch (op) {
573     case ASN1_PKEY_CTRL_PKCS7_SIGN:
574         if (arg1 == 0) {
575             int snid, hnid;
576             X509_ALGOR *alg1, *alg2;
577             PKCS7_SIGNER_INFO_get0_algs(arg2, NULL, &alg1, &alg2);
578             if (alg1 == NULL || alg1->algorithm == NULL)
579                 return -1;
580             hnid = OBJ_obj2nid(alg1->algorithm);
581             if (hnid == NID_undef)
582                 return -1;
583             if (!OBJ_find_sigid_by_algs(&snid, hnid, EVP_PKEY_id(pkey)))
584                 return -1;
585             X509_ALGOR_set0(alg2, OBJ_nid2obj(snid), V_ASN1_UNDEF, 0);
586         }
587         return 1;
588 #ifndef OPENSSL_NO_CMS
589     case ASN1_PKEY_CTRL_CMS_SIGN:
590         if (arg1 == 0) {
591             int snid, hnid;
592             X509_ALGOR *alg1, *alg2;
593             CMS_SignerInfo_get0_algs(arg2, NULL, NULL, &alg1, &alg2);
594             if (alg1 == NULL || alg1->algorithm == NULL)
595                 return -1;
596             hnid = OBJ_obj2nid(alg1->algorithm);
597             if (hnid == NID_undef)
598                 return -1;
599             if (!OBJ_find_sigid_by_algs(&snid, hnid, EVP_PKEY_id(pkey)))
600                 return -1;
601             X509_ALGOR_set0(alg2, OBJ_nid2obj(snid), V_ASN1_UNDEF, 0);
602         }
603         return 1;
604
605     case ASN1_PKEY_CTRL_CMS_ENVELOPE:
606         if (arg1 == 1)
607             return ecdh_cms_decrypt(arg2);
608         else if (arg1 == 0)
609             return ecdh_cms_encrypt(arg2);
610         return -2;
611
612     case ASN1_PKEY_CTRL_CMS_RI_TYPE:
613         *(int *)arg2 = CMS_RECIPINFO_AGREE;
614         return 1;
615 #endif
616
617     case ASN1_PKEY_CTRL_DEFAULT_MD_NID:
618         *(int *)arg2 = NID_sha256;
619         return 2;
620
621     default:
622         return -2;
623
624     }
625
626 }
627
628 const EVP_PKEY_ASN1_METHOD eckey_asn1_meth = {
629     EVP_PKEY_EC,
630     EVP_PKEY_EC,
631     0,
632     "EC",
633     "OpenSSL EC algorithm",
634
635     eckey_pub_decode,
636     eckey_pub_encode,
637     eckey_pub_cmp,
638     eckey_pub_print,
639
640     eckey_priv_decode,
641     eckey_priv_encode,
642     eckey_priv_print,
643
644     int_ec_size,
645     ec_bits,
646     ec_security_bits,
647
648     eckey_param_decode,
649     eckey_param_encode,
650     ec_missing_parameters,
651     ec_copy_parameters,
652     ec_cmp_parameters,
653     eckey_param_print,
654     0,
655
656     int_ec_free,
657     ec_pkey_ctrl,
658     old_ec_priv_decode,
659     old_ec_priv_encode
660 };
661
662 #ifndef OPENSSL_NO_CMS
663
664 static int ecdh_cms_set_peerkey(EVP_PKEY_CTX *pctx,
665                                 X509_ALGOR *alg, ASN1_BIT_STRING *pubkey)
666 {
667     ASN1_OBJECT *aoid;
668     int atype;
669     void *aval;
670     int rv = 0;
671     EVP_PKEY *pkpeer = NULL;
672     EC_KEY *ecpeer = NULL;
673     const unsigned char *p;
674     int plen;
675     X509_ALGOR_get0(&aoid, &atype, &aval, alg);
676     if (OBJ_obj2nid(aoid) != NID_X9_62_id_ecPublicKey)
677         goto err;
678     /* If absent parameters get group from main key */
679     if (atype == V_ASN1_UNDEF || atype == V_ASN1_NULL) {
680         const EC_GROUP *grp;
681         EVP_PKEY *pk;
682         pk = EVP_PKEY_CTX_get0_pkey(pctx);
683         if (!pk)
684             goto err;
685         grp = EC_KEY_get0_group(pk->pkey.ec);
686         ecpeer = EC_KEY_new();
687         if (ecpeer == NULL)
688             goto err;
689         if (!EC_KEY_set_group(ecpeer, grp))
690             goto err;
691     } else {
692         ecpeer = eckey_type2param(atype, aval);
693         if (!ecpeer)
694             goto err;
695     }
696     /* We have parameters now set public key */
697     plen = ASN1_STRING_length(pubkey);
698     p = ASN1_STRING_data(pubkey);
699     if (!p || !plen)
700         goto err;
701     if (!o2i_ECPublicKey(&ecpeer, &p, plen))
702         goto err;
703     pkpeer = EVP_PKEY_new();
704     if (pkpeer == NULL)
705         goto err;
706     EVP_PKEY_set1_EC_KEY(pkpeer, ecpeer);
707     if (EVP_PKEY_derive_set_peer(pctx, pkpeer) > 0)
708         rv = 1;
709  err:
710     EC_KEY_free(ecpeer);
711     EVP_PKEY_free(pkpeer);
712     return rv;
713 }
714
715 /* Set KDF parameters based on KDF NID */
716 static int ecdh_cms_set_kdf_param(EVP_PKEY_CTX *pctx, int eckdf_nid)
717 {
718     int kdf_nid, kdfmd_nid, cofactor;
719     const EVP_MD *kdf_md;
720     if (eckdf_nid == NID_undef)
721         return 0;
722
723     /* Lookup KDF type, cofactor mode and digest */
724     if (!OBJ_find_sigid_algs(eckdf_nid, &kdfmd_nid, &kdf_nid))
725         return 0;
726
727     if (kdf_nid == NID_dh_std_kdf)
728         cofactor = 0;
729     else if (kdf_nid == NID_dh_cofactor_kdf)
730         cofactor = 1;
731     else
732         return 0;
733
734     if (EVP_PKEY_CTX_set_ecdh_cofactor_mode(pctx, cofactor) <= 0)
735         return 0;
736
737     if (EVP_PKEY_CTX_set_ecdh_kdf_type(pctx, EVP_PKEY_ECDH_KDF_X9_62) <= 0)
738         return 0;
739
740     kdf_md = EVP_get_digestbynid(kdfmd_nid);
741     if (!kdf_md)
742         return 0;
743
744     if (EVP_PKEY_CTX_set_ecdh_kdf_md(pctx, kdf_md) <= 0)
745         return 0;
746     return 1;
747 }
748
749 static int ecdh_cms_set_shared_info(EVP_PKEY_CTX *pctx, CMS_RecipientInfo *ri)
750 {
751     int rv = 0;
752
753     X509_ALGOR *alg, *kekalg = NULL;
754     ASN1_OCTET_STRING *ukm;
755     const unsigned char *p;
756     unsigned char *der = NULL;
757     int plen, keylen;
758     const EVP_CIPHER *kekcipher;
759     EVP_CIPHER_CTX *kekctx;
760
761     if (!CMS_RecipientInfo_kari_get0_alg(ri, &alg, &ukm))
762         return 0;
763
764     if (!ecdh_cms_set_kdf_param(pctx, OBJ_obj2nid(alg->algorithm))) {
765         ECerr(EC_F_ECDH_CMS_SET_SHARED_INFO, EC_R_KDF_PARAMETER_ERROR);
766         return 0;
767     }
768
769     if (alg->parameter->type != V_ASN1_SEQUENCE)
770         return 0;
771
772     p = alg->parameter->value.sequence->data;
773     plen = alg->parameter->value.sequence->length;
774     kekalg = d2i_X509_ALGOR(NULL, &p, plen);
775     if (!kekalg)
776         goto err;
777     kekctx = CMS_RecipientInfo_kari_get0_ctx(ri);
778     if (!kekctx)
779         goto err;
780     kekcipher = EVP_get_cipherbyobj(kekalg->algorithm);
781     if (!kekcipher || EVP_CIPHER_mode(kekcipher) != EVP_CIPH_WRAP_MODE)
782         goto err;
783     if (!EVP_EncryptInit_ex(kekctx, kekcipher, NULL, NULL, NULL))
784         goto err;
785     if (EVP_CIPHER_asn1_to_param(kekctx, kekalg->parameter) <= 0)
786         goto err;
787
788     keylen = EVP_CIPHER_CTX_key_length(kekctx);
789     if (EVP_PKEY_CTX_set_ecdh_kdf_outlen(pctx, keylen) <= 0)
790         goto err;
791
792     plen = CMS_SharedInfo_encode(&der, kekalg, ukm, keylen);
793
794     if (!plen)
795         goto err;
796
797     if (EVP_PKEY_CTX_set0_ecdh_kdf_ukm(pctx, der, plen) <= 0)
798         goto err;
799     der = NULL;
800
801     rv = 1;
802  err:
803     X509_ALGOR_free(kekalg);
804     OPENSSL_free(der);
805     return rv;
806 }
807
808 static int ecdh_cms_decrypt(CMS_RecipientInfo *ri)
809 {
810     EVP_PKEY_CTX *pctx;
811     pctx = CMS_RecipientInfo_get0_pkey_ctx(ri);
812     if (!pctx)
813         return 0;
814     /* See if we need to set peer key */
815     if (!EVP_PKEY_CTX_get0_peerkey(pctx)) {
816         X509_ALGOR *alg;
817         ASN1_BIT_STRING *pubkey;
818         if (!CMS_RecipientInfo_kari_get0_orig_id(ri, &alg, &pubkey,
819                                                  NULL, NULL, NULL))
820             return 0;
821         if (!alg || !pubkey)
822             return 0;
823         if (!ecdh_cms_set_peerkey(pctx, alg, pubkey)) {
824             ECerr(EC_F_ECDH_CMS_DECRYPT, EC_R_PEER_KEY_ERROR);
825             return 0;
826         }
827     }
828     /* Set ECDH derivation parameters and initialise unwrap context */
829     if (!ecdh_cms_set_shared_info(pctx, ri)) {
830         ECerr(EC_F_ECDH_CMS_DECRYPT, EC_R_SHARED_INFO_ERROR);
831         return 0;
832     }
833     return 1;
834 }
835
836 static int ecdh_cms_encrypt(CMS_RecipientInfo *ri)
837 {
838     EVP_PKEY_CTX *pctx;
839     EVP_PKEY *pkey;
840     EVP_CIPHER_CTX *ctx;
841     int keylen;
842     X509_ALGOR *talg, *wrap_alg = NULL;
843     ASN1_OBJECT *aoid;
844     ASN1_BIT_STRING *pubkey;
845     ASN1_STRING *wrap_str;
846     ASN1_OCTET_STRING *ukm;
847     unsigned char *penc = NULL;
848     int penclen;
849     int rv = 0;
850     int ecdh_nid, kdf_type, kdf_nid, wrap_nid;
851     const EVP_MD *kdf_md;
852     pctx = CMS_RecipientInfo_get0_pkey_ctx(ri);
853     if (!pctx)
854         return 0;
855     /* Get ephemeral key */
856     pkey = EVP_PKEY_CTX_get0_pkey(pctx);
857     if (!CMS_RecipientInfo_kari_get0_orig_id(ri, &talg, &pubkey,
858                                              NULL, NULL, NULL))
859         goto err;
860     X509_ALGOR_get0(&aoid, NULL, NULL, talg);
861     /* Is everything uninitialised? */
862     if (aoid == OBJ_nid2obj(NID_undef)) {
863
864         EC_KEY *eckey = pkey->pkey.ec;
865         /* Set the key */
866         unsigned char *p;
867
868         penclen = i2o_ECPublicKey(eckey, NULL);
869         if (penclen <= 0)
870             goto err;
871         penc = OPENSSL_malloc(penclen);
872         if (penc == NULL)
873             goto err;
874         p = penc;
875         penclen = i2o_ECPublicKey(eckey, &p);
876         if (penclen <= 0)
877             goto err;
878         ASN1_STRING_set0(pubkey, penc, penclen);
879         pubkey->flags &= ~(ASN1_STRING_FLAG_BITS_LEFT | 0x07);
880         pubkey->flags |= ASN1_STRING_FLAG_BITS_LEFT;
881
882         penc = NULL;
883         X509_ALGOR_set0(talg, OBJ_nid2obj(NID_X9_62_id_ecPublicKey),
884                         V_ASN1_UNDEF, NULL);
885     }
886
887     /* See if custom paraneters set */
888     kdf_type = EVP_PKEY_CTX_get_ecdh_kdf_type(pctx);
889     if (kdf_type <= 0)
890         goto err;
891     if (!EVP_PKEY_CTX_get_ecdh_kdf_md(pctx, &kdf_md))
892         goto err;
893     ecdh_nid = EVP_PKEY_CTX_get_ecdh_cofactor_mode(pctx);
894     if (ecdh_nid < 0)
895         goto err;
896     else if (ecdh_nid == 0)
897         ecdh_nid = NID_dh_std_kdf;
898     else if (ecdh_nid == 1)
899         ecdh_nid = NID_dh_cofactor_kdf;
900
901     if (kdf_type == EVP_PKEY_ECDH_KDF_NONE) {
902         kdf_type = EVP_PKEY_ECDH_KDF_X9_62;
903         if (EVP_PKEY_CTX_set_ecdh_kdf_type(pctx, kdf_type) <= 0)
904             goto err;
905     } else
906         /* Uknown KDF */
907         goto err;
908     if (kdf_md == NULL) {
909         /* Fixme later for better MD */
910         kdf_md = EVP_sha1();
911         if (EVP_PKEY_CTX_set_ecdh_kdf_md(pctx, kdf_md) <= 0)
912             goto err;
913     }
914
915     if (!CMS_RecipientInfo_kari_get0_alg(ri, &talg, &ukm))
916         goto err;
917
918     /* Lookup NID for KDF+cofactor+digest */
919
920     if (!OBJ_find_sigid_by_algs(&kdf_nid, EVP_MD_type(kdf_md), ecdh_nid))
921         goto err;
922     /* Get wrap NID */
923     ctx = CMS_RecipientInfo_kari_get0_ctx(ri);
924     wrap_nid = EVP_CIPHER_CTX_type(ctx);
925     keylen = EVP_CIPHER_CTX_key_length(ctx);
926
927     /* Package wrap algorithm in an AlgorithmIdentifier */
928
929     wrap_alg = X509_ALGOR_new();
930     if (wrap_alg == NULL)
931         goto err;
932     wrap_alg->algorithm = OBJ_nid2obj(wrap_nid);
933     wrap_alg->parameter = ASN1_TYPE_new();
934     if (wrap_alg->parameter == NULL)
935         goto err;
936     if (EVP_CIPHER_param_to_asn1(ctx, wrap_alg->parameter) <= 0)
937         goto err;
938     if (ASN1_TYPE_get(wrap_alg->parameter) == NID_undef) {
939         ASN1_TYPE_free(wrap_alg->parameter);
940         wrap_alg->parameter = NULL;
941     }
942
943     if (EVP_PKEY_CTX_set_ecdh_kdf_outlen(pctx, keylen) <= 0)
944         goto err;
945
946     penclen = CMS_SharedInfo_encode(&penc, wrap_alg, ukm, keylen);
947
948     if (!penclen)
949         goto err;
950
951     if (EVP_PKEY_CTX_set0_ecdh_kdf_ukm(pctx, penc, penclen) <= 0)
952         goto err;
953     penc = NULL;
954
955     /*
956      * Now need to wrap encoding of wrap AlgorithmIdentifier into parameter
957      * of another AlgorithmIdentifier.
958      */
959     penclen = i2d_X509_ALGOR(wrap_alg, &penc);
960     if (!penc || !penclen)
961         goto err;
962     wrap_str = ASN1_STRING_new();
963     if (wrap_str == NULL)
964         goto err;
965     ASN1_STRING_set0(wrap_str, penc, penclen);
966     penc = NULL;
967     X509_ALGOR_set0(talg, OBJ_nid2obj(kdf_nid), V_ASN1_SEQUENCE, wrap_str);
968
969     rv = 1;
970
971  err:
972     OPENSSL_free(penc);
973     X509_ALGOR_free(wrap_alg);
974     return rv;
975 }
976
977 #endif