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