add ECDSA_size to ec_asn1.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 "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 (EC_KEY_set_group(to->pkey.ec, group) == 0)
406         return 0;
407     EC_GROUP_free(group);
408     return 1;
409 }
410
411 static int ec_cmp_parameters(const EVP_PKEY *a, const EVP_PKEY *b)
412 {
413     const EC_GROUP *group_a = EC_KEY_get0_group(a->pkey.ec),
414         *group_b = EC_KEY_get0_group(b->pkey.ec);
415     if (EC_GROUP_cmp(group_a, group_b, NULL))
416         return 0;
417     else
418         return 1;
419 }
420
421 static void int_ec_free(EVP_PKEY *pkey)
422 {
423     EC_KEY_free(pkey->pkey.ec);
424 }
425
426 static int do_EC_KEY_print(BIO *bp, const EC_KEY *x, int off, int ktype)
427 {
428     unsigned char *buffer = NULL;
429     const char *ecstr;
430     size_t buf_len = 0, i;
431     int ret = 0, reason = ERR_R_BIO_LIB;
432     BIGNUM *pub_key = NULL, *order = NULL;
433     BN_CTX *ctx = NULL;
434     const EC_GROUP *group;
435     const EC_POINT *public_key;
436     const BIGNUM *priv_key;
437
438     if (x == NULL || (group = EC_KEY_get0_group(x)) == NULL) {
439         reason = ERR_R_PASSED_NULL_PARAMETER;
440         goto err;
441     }
442
443     ctx = BN_CTX_new();
444     if (ctx == NULL) {
445         reason = ERR_R_MALLOC_FAILURE;
446         goto err;
447     }
448
449     if (ktype > 0) {
450         public_key = EC_KEY_get0_public_key(x);
451         if (public_key != NULL) {
452             if ((pub_key = EC_POINT_point2bn(group, public_key,
453                                              EC_KEY_get_conv_form(x), NULL,
454                                              ctx)) == NULL) {
455                 reason = ERR_R_EC_LIB;
456                 goto err;
457             }
458             buf_len = (size_t)BN_num_bytes(pub_key);
459         }
460     }
461
462     if (ktype == 2) {
463         priv_key = EC_KEY_get0_private_key(x);
464         if (priv_key && (i = (size_t)BN_num_bytes(priv_key)) > buf_len)
465             buf_len = i;
466     } else
467         priv_key = NULL;
468
469     if (ktype > 0) {
470         buf_len += 10;
471         if ((buffer = OPENSSL_malloc(buf_len)) == NULL) {
472             reason = ERR_R_MALLOC_FAILURE;
473             goto err;
474         }
475     }
476     if (ktype == 2)
477         ecstr = "Private-Key";
478     else if (ktype == 1)
479         ecstr = "Public-Key";
480     else
481         ecstr = "ECDSA-Parameters";
482
483     if (!BIO_indent(bp, off, 128))
484         goto err;
485     if ((order = BN_new()) == NULL)
486         goto err;
487     if (!EC_GROUP_get_order(group, order, NULL))
488         goto err;
489     if (BIO_printf(bp, "%s: (%d bit)\n", ecstr, BN_num_bits(order)) <= 0)
490         goto err;
491
492     if ((priv_key != NULL) && !ASN1_bn_print(bp, "priv:", priv_key,
493                                              buffer, off))
494         goto err;
495     if ((pub_key != NULL) && !ASN1_bn_print(bp, "pub: ", pub_key,
496                                             buffer, off))
497         goto err;
498     if (!ECPKParameters_print(bp, group, off))
499         goto err;
500     ret = 1;
501  err:
502     if (!ret)
503         ECerr(EC_F_DO_EC_KEY_PRINT, reason);
504     BN_free(pub_key);
505     BN_free(order);
506     BN_CTX_free(ctx);
507     OPENSSL_free(buffer);
508     return (ret);
509 }
510
511 static int eckey_param_decode(EVP_PKEY *pkey,
512                               const unsigned char **pder, int derlen)
513 {
514     EC_KEY *eckey;
515
516     if ((eckey = d2i_ECParameters(NULL, pder, derlen)) == NULL) {
517         ECerr(EC_F_ECKEY_PARAM_DECODE, ERR_R_EC_LIB);
518         return 0;
519     }
520     EVP_PKEY_assign_EC_KEY(pkey, eckey);
521     return 1;
522 }
523
524 static int eckey_param_encode(const EVP_PKEY *pkey, unsigned char **pder)
525 {
526     return i2d_ECParameters(pkey->pkey.ec, pder);
527 }
528
529 static int eckey_param_print(BIO *bp, const EVP_PKEY *pkey, int indent,
530                              ASN1_PCTX *ctx)
531 {
532     return do_EC_KEY_print(bp, pkey->pkey.ec, indent, 0);
533 }
534
535 static int eckey_pub_print(BIO *bp, const EVP_PKEY *pkey, int indent,
536                            ASN1_PCTX *ctx)
537 {
538     return do_EC_KEY_print(bp, pkey->pkey.ec, indent, 1);
539 }
540
541 static int eckey_priv_print(BIO *bp, const EVP_PKEY *pkey, int indent,
542                             ASN1_PCTX *ctx)
543 {
544     return do_EC_KEY_print(bp, pkey->pkey.ec, indent, 2);
545 }
546
547 static int old_ec_priv_decode(EVP_PKEY *pkey,
548                               const unsigned char **pder, int derlen)
549 {
550     EC_KEY *ec;
551
552     if ((ec = d2i_ECPrivateKey(NULL, pder, derlen)) == NULL) {
553         ECerr(EC_F_OLD_EC_PRIV_DECODE, EC_R_DECODE_ERROR);
554         return 0;
555     }
556     EVP_PKEY_assign_EC_KEY(pkey, ec);
557     return 1;
558 }
559
560 static int old_ec_priv_encode(const EVP_PKEY *pkey, unsigned char **pder)
561 {
562     return i2d_ECPrivateKey(pkey->pkey.ec, pder);
563 }
564
565 static int ec_pkey_ctrl(EVP_PKEY *pkey, int op, long arg1, void *arg2)
566 {
567     switch (op) {
568     case ASN1_PKEY_CTRL_PKCS7_SIGN:
569         if (arg1 == 0) {
570             int snid, hnid;
571             X509_ALGOR *alg1, *alg2;
572             PKCS7_SIGNER_INFO_get0_algs(arg2, NULL, &alg1, &alg2);
573             if (alg1 == NULL || alg1->algorithm == NULL)
574                 return -1;
575             hnid = OBJ_obj2nid(alg1->algorithm);
576             if (hnid == NID_undef)
577                 return -1;
578             if (!OBJ_find_sigid_by_algs(&snid, hnid, EVP_PKEY_id(pkey)))
579                 return -1;
580             X509_ALGOR_set0(alg2, OBJ_nid2obj(snid), V_ASN1_UNDEF, 0);
581         }
582         return 1;
583 #ifndef OPENSSL_NO_CMS
584     case ASN1_PKEY_CTRL_CMS_SIGN:
585         if (arg1 == 0) {
586             int snid, hnid;
587             X509_ALGOR *alg1, *alg2;
588             CMS_SignerInfo_get0_algs(arg2, NULL, NULL, &alg1, &alg2);
589             if (alg1 == NULL || alg1->algorithm == NULL)
590                 return -1;
591             hnid = OBJ_obj2nid(alg1->algorithm);
592             if (hnid == NID_undef)
593                 return -1;
594             if (!OBJ_find_sigid_by_algs(&snid, hnid, EVP_PKEY_id(pkey)))
595                 return -1;
596             X509_ALGOR_set0(alg2, OBJ_nid2obj(snid), V_ASN1_UNDEF, 0);
597         }
598         return 1;
599
600     case ASN1_PKEY_CTRL_CMS_ENVELOPE:
601         if (arg1 == 1)
602             return ecdh_cms_decrypt(arg2);
603         else if (arg1 == 0)
604             return ecdh_cms_encrypt(arg2);
605         return -2;
606
607     case ASN1_PKEY_CTRL_CMS_RI_TYPE:
608         *(int *)arg2 = CMS_RECIPINFO_AGREE;
609         return 1;
610 #endif
611
612     case ASN1_PKEY_CTRL_DEFAULT_MD_NID:
613         *(int *)arg2 = NID_sha256;
614         return 2;
615
616     default:
617         return -2;
618
619     }
620
621 }
622
623 const EVP_PKEY_ASN1_METHOD eckey_asn1_meth = {
624     EVP_PKEY_EC,
625     EVP_PKEY_EC,
626     0,
627     "EC",
628     "OpenSSL EC algorithm",
629
630     eckey_pub_decode,
631     eckey_pub_encode,
632     eckey_pub_cmp,
633     eckey_pub_print,
634
635     eckey_priv_decode,
636     eckey_priv_encode,
637     eckey_priv_print,
638
639     int_ec_size,
640     ec_bits,
641     ec_security_bits,
642
643     eckey_param_decode,
644     eckey_param_encode,
645     ec_missing_parameters,
646     ec_copy_parameters,
647     ec_cmp_parameters,
648     eckey_param_print,
649     0,
650
651     int_ec_free,
652     ec_pkey_ctrl,
653     old_ec_priv_decode,
654     old_ec_priv_encode
655 };
656
657 #ifndef OPENSSL_NO_CMS
658
659 static int ecdh_cms_set_peerkey(EVP_PKEY_CTX *pctx,
660                                 X509_ALGOR *alg, ASN1_BIT_STRING *pubkey)
661 {
662     ASN1_OBJECT *aoid;
663     int atype;
664     void *aval;
665     int rv = 0;
666     EVP_PKEY *pkpeer = NULL;
667     EC_KEY *ecpeer = NULL;
668     const unsigned char *p;
669     int plen;
670     X509_ALGOR_get0(&aoid, &atype, &aval, alg);
671     if (OBJ_obj2nid(aoid) != NID_X9_62_id_ecPublicKey)
672         goto err;
673     /* If absent parameters get group from main key */
674     if (atype == V_ASN1_UNDEF || atype == V_ASN1_NULL) {
675         const EC_GROUP *grp;
676         EVP_PKEY *pk;
677         pk = EVP_PKEY_CTX_get0_pkey(pctx);
678         if (!pk)
679             goto err;
680         grp = EC_KEY_get0_group(pk->pkey.ec);
681         ecpeer = EC_KEY_new();
682         if (ecpeer == NULL)
683             goto err;
684         if (!EC_KEY_set_group(ecpeer, grp))
685             goto err;
686     } else {
687         ecpeer = eckey_type2param(atype, aval);
688         if (!ecpeer)
689             goto err;
690     }
691     /* We have parameters now set public key */
692     plen = ASN1_STRING_length(pubkey);
693     p = ASN1_STRING_data(pubkey);
694     if (!p || !plen)
695         goto err;
696     if (!o2i_ECPublicKey(&ecpeer, &p, plen))
697         goto err;
698     pkpeer = EVP_PKEY_new();
699     if (pkpeer == NULL)
700         goto err;
701     EVP_PKEY_set1_EC_KEY(pkpeer, ecpeer);
702     if (EVP_PKEY_derive_set_peer(pctx, pkpeer) > 0)
703         rv = 1;
704  err:
705     EC_KEY_free(ecpeer);
706     EVP_PKEY_free(pkpeer);
707     return rv;
708 }
709
710 /* Set KDF parameters based on KDF NID */
711 static int ecdh_cms_set_kdf_param(EVP_PKEY_CTX *pctx, int eckdf_nid)
712 {
713     int kdf_nid, kdfmd_nid, cofactor;
714     const EVP_MD *kdf_md;
715     if (eckdf_nid == NID_undef)
716         return 0;
717
718     /* Lookup KDF type, cofactor mode and digest */
719     if (!OBJ_find_sigid_algs(eckdf_nid, &kdfmd_nid, &kdf_nid))
720         return 0;
721
722     if (kdf_nid == NID_dh_std_kdf)
723         cofactor = 0;
724     else if (kdf_nid == NID_dh_cofactor_kdf)
725         cofactor = 1;
726     else
727         return 0;
728
729     if (EVP_PKEY_CTX_set_ecdh_cofactor_mode(pctx, cofactor) <= 0)
730         return 0;
731
732     if (EVP_PKEY_CTX_set_ecdh_kdf_type(pctx, EVP_PKEY_ECDH_KDF_X9_62) <= 0)
733         return 0;
734
735     kdf_md = EVP_get_digestbynid(kdfmd_nid);
736     if (!kdf_md)
737         return 0;
738
739     if (EVP_PKEY_CTX_set_ecdh_kdf_md(pctx, kdf_md) <= 0)
740         return 0;
741     return 1;
742 }
743
744 static int ecdh_cms_set_shared_info(EVP_PKEY_CTX *pctx, CMS_RecipientInfo *ri)
745 {
746     int rv = 0;
747
748     X509_ALGOR *alg, *kekalg = NULL;
749     ASN1_OCTET_STRING *ukm;
750     const unsigned char *p;
751     unsigned char *der = NULL;
752     int plen, keylen;
753     const EVP_CIPHER *kekcipher;
754     EVP_CIPHER_CTX *kekctx;
755
756     if (!CMS_RecipientInfo_kari_get0_alg(ri, &alg, &ukm))
757         return 0;
758
759     if (!ecdh_cms_set_kdf_param(pctx, OBJ_obj2nid(alg->algorithm))) {
760         ECerr(EC_F_ECDH_CMS_SET_SHARED_INFO, EC_R_KDF_PARAMETER_ERROR);
761         return 0;
762     }
763
764     if (alg->parameter->type != V_ASN1_SEQUENCE)
765         return 0;
766
767     p = alg->parameter->value.sequence->data;
768     plen = alg->parameter->value.sequence->length;
769     kekalg = d2i_X509_ALGOR(NULL, &p, plen);
770     if (!kekalg)
771         goto err;
772     kekctx = CMS_RecipientInfo_kari_get0_ctx(ri);
773     if (!kekctx)
774         goto err;
775     kekcipher = EVP_get_cipherbyobj(kekalg->algorithm);
776     if (!kekcipher || EVP_CIPHER_mode(kekcipher) != EVP_CIPH_WRAP_MODE)
777         goto err;
778     if (!EVP_EncryptInit_ex(kekctx, kekcipher, NULL, NULL, NULL))
779         goto err;
780     if (EVP_CIPHER_asn1_to_param(kekctx, kekalg->parameter) <= 0)
781         goto err;
782
783     keylen = EVP_CIPHER_CTX_key_length(kekctx);
784     if (EVP_PKEY_CTX_set_ecdh_kdf_outlen(pctx, keylen) <= 0)
785         goto err;
786
787     plen = CMS_SharedInfo_encode(&der, kekalg, ukm, keylen);
788
789     if (!plen)
790         goto err;
791
792     if (EVP_PKEY_CTX_set0_ecdh_kdf_ukm(pctx, der, plen) <= 0)
793         goto err;
794     der = NULL;
795
796     rv = 1;
797  err:
798     X509_ALGOR_free(kekalg);
799     OPENSSL_free(der);
800     return rv;
801 }
802
803 static int ecdh_cms_decrypt(CMS_RecipientInfo *ri)
804 {
805     EVP_PKEY_CTX *pctx;
806     pctx = CMS_RecipientInfo_get0_pkey_ctx(ri);
807     if (!pctx)
808         return 0;
809     /* See if we need to set peer key */
810     if (!EVP_PKEY_CTX_get0_peerkey(pctx)) {
811         X509_ALGOR *alg;
812         ASN1_BIT_STRING *pubkey;
813         if (!CMS_RecipientInfo_kari_get0_orig_id(ri, &alg, &pubkey,
814                                                  NULL, NULL, NULL))
815             return 0;
816         if (!alg || !pubkey)
817             return 0;
818         if (!ecdh_cms_set_peerkey(pctx, alg, pubkey)) {
819             ECerr(EC_F_ECDH_CMS_DECRYPT, EC_R_PEER_KEY_ERROR);
820             return 0;
821         }
822     }
823     /* Set ECDH derivation parameters and initialise unwrap context */
824     if (!ecdh_cms_set_shared_info(pctx, ri)) {
825         ECerr(EC_F_ECDH_CMS_DECRYPT, EC_R_SHARED_INFO_ERROR);
826         return 0;
827     }
828     return 1;
829 }
830
831 static int ecdh_cms_encrypt(CMS_RecipientInfo *ri)
832 {
833     EVP_PKEY_CTX *pctx;
834     EVP_PKEY *pkey;
835     EVP_CIPHER_CTX *ctx;
836     int keylen;
837     X509_ALGOR *talg, *wrap_alg = NULL;
838     ASN1_OBJECT *aoid;
839     ASN1_BIT_STRING *pubkey;
840     ASN1_STRING *wrap_str;
841     ASN1_OCTET_STRING *ukm;
842     unsigned char *penc = NULL;
843     int penclen;
844     int rv = 0;
845     int ecdh_nid, kdf_type, kdf_nid, wrap_nid;
846     const EVP_MD *kdf_md;
847     pctx = CMS_RecipientInfo_get0_pkey_ctx(ri);
848     if (!pctx)
849         return 0;
850     /* Get ephemeral key */
851     pkey = EVP_PKEY_CTX_get0_pkey(pctx);
852     if (!CMS_RecipientInfo_kari_get0_orig_id(ri, &talg, &pubkey,
853                                              NULL, NULL, NULL))
854         goto err;
855     X509_ALGOR_get0(&aoid, NULL, NULL, talg);
856     /* Is everything uninitialised? */
857     if (aoid == OBJ_nid2obj(NID_undef)) {
858
859         EC_KEY *eckey = pkey->pkey.ec;
860         /* Set the key */
861         unsigned char *p;
862
863         penclen = i2o_ECPublicKey(eckey, NULL);
864         if (penclen <= 0)
865             goto err;
866         penc = OPENSSL_malloc(penclen);
867         if (penc == NULL)
868             goto err;
869         p = penc;
870         penclen = i2o_ECPublicKey(eckey, &p);
871         if (penclen <= 0)
872             goto err;
873         ASN1_STRING_set0(pubkey, penc, penclen);
874         pubkey->flags &= ~(ASN1_STRING_FLAG_BITS_LEFT | 0x07);
875         pubkey->flags |= ASN1_STRING_FLAG_BITS_LEFT;
876
877         penc = NULL;
878         X509_ALGOR_set0(talg, OBJ_nid2obj(NID_X9_62_id_ecPublicKey),
879                         V_ASN1_UNDEF, NULL);
880     }
881
882     /* See if custom paraneters set */
883     kdf_type = EVP_PKEY_CTX_get_ecdh_kdf_type(pctx);
884     if (kdf_type <= 0)
885         goto err;
886     if (!EVP_PKEY_CTX_get_ecdh_kdf_md(pctx, &kdf_md))
887         goto err;
888     ecdh_nid = EVP_PKEY_CTX_get_ecdh_cofactor_mode(pctx);
889     if (ecdh_nid < 0)
890         goto err;
891     else if (ecdh_nid == 0)
892         ecdh_nid = NID_dh_std_kdf;
893     else if (ecdh_nid == 1)
894         ecdh_nid = NID_dh_cofactor_kdf;
895
896     if (kdf_type == EVP_PKEY_ECDH_KDF_NONE) {
897         kdf_type = EVP_PKEY_ECDH_KDF_X9_62;
898         if (EVP_PKEY_CTX_set_ecdh_kdf_type(pctx, kdf_type) <= 0)
899             goto err;
900     } else
901         /* Uknown KDF */
902         goto err;
903     if (kdf_md == NULL) {
904         /* Fixme later for better MD */
905         kdf_md = EVP_sha1();
906         if (EVP_PKEY_CTX_set_ecdh_kdf_md(pctx, kdf_md) <= 0)
907             goto err;
908     }
909
910     if (!CMS_RecipientInfo_kari_get0_alg(ri, &talg, &ukm))
911         goto err;
912
913     /* Lookup NID for KDF+cofactor+digest */
914
915     if (!OBJ_find_sigid_by_algs(&kdf_nid, EVP_MD_type(kdf_md), ecdh_nid))
916         goto err;
917     /* Get wrap NID */
918     ctx = CMS_RecipientInfo_kari_get0_ctx(ri);
919     wrap_nid = EVP_CIPHER_CTX_type(ctx);
920     keylen = EVP_CIPHER_CTX_key_length(ctx);
921
922     /* Package wrap algorithm in an AlgorithmIdentifier */
923
924     wrap_alg = X509_ALGOR_new();
925     if (wrap_alg == NULL)
926         goto err;
927     wrap_alg->algorithm = OBJ_nid2obj(wrap_nid);
928     wrap_alg->parameter = ASN1_TYPE_new();
929     if (wrap_alg->parameter == NULL)
930         goto err;
931     if (EVP_CIPHER_param_to_asn1(ctx, wrap_alg->parameter) <= 0)
932         goto err;
933     if (ASN1_TYPE_get(wrap_alg->parameter) == NID_undef) {
934         ASN1_TYPE_free(wrap_alg->parameter);
935         wrap_alg->parameter = NULL;
936     }
937
938     if (EVP_PKEY_CTX_set_ecdh_kdf_outlen(pctx, keylen) <= 0)
939         goto err;
940
941     penclen = CMS_SharedInfo_encode(&penc, wrap_alg, ukm, keylen);
942
943     if (!penclen)
944         goto err;
945
946     if (EVP_PKEY_CTX_set0_ecdh_kdf_ukm(pctx, penc, penclen) <= 0)
947         goto err;
948     penc = NULL;
949
950     /*
951      * Now need to wrap encoding of wrap AlgorithmIdentifier into parameter
952      * of another AlgorithmIdentifier.
953      */
954     penclen = i2d_X509_ALGOR(wrap_alg, &penc);
955     if (!penc || !penclen)
956         goto err;
957     wrap_str = ASN1_STRING_new();
958     if (wrap_str == NULL)
959         goto err;
960     ASN1_STRING_set0(wrap_str, penc, penclen);
961     penc = NULL;
962     X509_ALGOR_set0(talg, OBJ_nid2obj(kdf_nid), V_ASN1_SEQUENCE, wrap_str);
963
964     rv = 1;
965
966  err:
967     OPENSSL_free(penc);
968     X509_ALGOR_free(wrap_alg);
969     return rv;
970 }
971
972 #endif