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