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