make EVP_PKEY opaque
[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     /* 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     EC_KEY_free(eckey);
296     return 0;
297 }
298
299 static int eckey_priv_encode(PKCS8_PRIV_KEY_INFO *p8, const EVP_PKEY *pkey)
300 {
301     EC_KEY *ec_key;
302     unsigned char *ep, *p;
303     int eplen, ptype;
304     void *pval;
305     unsigned int tmp_flags, old_flags;
306
307     ec_key = pkey->pkey.ec;
308
309     if (!eckey_param2type(&ptype, &pval, ec_key)) {
310         ECerr(EC_F_ECKEY_PRIV_ENCODE, EC_R_DECODE_ERROR);
311         return 0;
312     }
313
314     /* set the private key */
315
316     /*
317      * do not include the parameters in the SEC1 private key see PKCS#11
318      * 12.11
319      */
320     old_flags = EC_KEY_get_enc_flags(ec_key);
321     tmp_flags = old_flags | EC_PKEY_NO_PARAMETERS;
322     EC_KEY_set_enc_flags(ec_key, tmp_flags);
323     eplen = i2d_ECPrivateKey(ec_key, NULL);
324     if (!eplen) {
325         EC_KEY_set_enc_flags(ec_key, old_flags);
326         ECerr(EC_F_ECKEY_PRIV_ENCODE, ERR_R_EC_LIB);
327         return 0;
328     }
329     ep = OPENSSL_malloc(eplen);
330     if (ep == NULL) {
331         EC_KEY_set_enc_flags(ec_key, old_flags);
332         ECerr(EC_F_ECKEY_PRIV_ENCODE, ERR_R_MALLOC_FAILURE);
333         return 0;
334     }
335     p = ep;
336     if (!i2d_ECPrivateKey(ec_key, &p)) {
337         EC_KEY_set_enc_flags(ec_key, old_flags);
338         OPENSSL_free(ep);
339         ECerr(EC_F_ECKEY_PRIV_ENCODE, ERR_R_EC_LIB);
340         return 0;
341     }
342     /* restore old encoding flags */
343     EC_KEY_set_enc_flags(ec_key, old_flags);
344
345     if (!PKCS8_pkey_set0(p8, OBJ_nid2obj(NID_X9_62_id_ecPublicKey), 0,
346                          ptype, pval, ep, eplen))
347         return 0;
348
349     return 1;
350 }
351
352 static int int_ec_size(const EVP_PKEY *pkey)
353 {
354     return ECDSA_size(pkey->pkey.ec);
355 }
356
357 static int ec_bits(const EVP_PKEY *pkey)
358 {
359     BIGNUM *order = BN_new();
360     const EC_GROUP *group;
361     int ret;
362
363     if (order == NULL) {
364         ERR_clear_error();
365         return 0;
366     }
367     group = EC_KEY_get0_group(pkey->pkey.ec);
368     if (!EC_GROUP_get_order(group, order, NULL)) {
369         ERR_clear_error();
370         return 0;
371     }
372
373     ret = BN_num_bits(order);
374     BN_free(order);
375     return ret;
376 }
377
378 static int ec_security_bits(const EVP_PKEY *pkey)
379 {
380     int ecbits = ec_bits(pkey);
381     if (ecbits >= 512)
382         return 256;
383     if (ecbits >= 384)
384         return 192;
385     if (ecbits >= 256)
386         return 128;
387     if (ecbits >= 224)
388         return 112;
389     if (ecbits >= 160)
390         return 80;
391     return ecbits / 2;
392 }
393
394 static int ec_missing_parameters(const EVP_PKEY *pkey)
395 {
396     if (EC_KEY_get0_group(pkey->pkey.ec) == NULL)
397         return 1;
398     return 0;
399 }
400
401 static int ec_copy_parameters(EVP_PKEY *to, const EVP_PKEY *from)
402 {
403     EC_GROUP *group = EC_GROUP_dup(EC_KEY_get0_group(from->pkey.ec));
404     if (group == NULL)
405         return 0;
406     if (to->pkey.ec == NULL) {
407         to->pkey.ec = EC_KEY_new();
408         if (to->pkey.ec == NULL)
409             return 0;
410     }
411     if (EC_KEY_set_group(to->pkey.ec, group) == 0)
412         return 0;
413     EC_GROUP_free(group);
414     return 1;
415 }
416
417 static int ec_cmp_parameters(const EVP_PKEY *a, const EVP_PKEY *b)
418 {
419     const EC_GROUP *group_a = EC_KEY_get0_group(a->pkey.ec),
420         *group_b = EC_KEY_get0_group(b->pkey.ec);
421     if (EC_GROUP_cmp(group_a, group_b, NULL))
422         return 0;
423     else
424         return 1;
425 }
426
427 static void int_ec_free(EVP_PKEY *pkey)
428 {
429     EC_KEY_free(pkey->pkey.ec);
430 }
431
432 static int do_EC_KEY_print(BIO *bp, const EC_KEY *x, int off, int ktype)
433 {
434     unsigned char *buffer = NULL;
435     const char *ecstr;
436     size_t buf_len = 0, i;
437     int ret = 0, reason = ERR_R_BIO_LIB;
438     BIGNUM *pub_key = NULL, *order = NULL;
439     BN_CTX *ctx = NULL;
440     const EC_GROUP *group;
441     const EC_POINT *public_key;
442     const BIGNUM *priv_key;
443
444     if (x == NULL || (group = EC_KEY_get0_group(x)) == NULL) {
445         reason = ERR_R_PASSED_NULL_PARAMETER;
446         goto err;
447     }
448
449     ctx = BN_CTX_new();
450     if (ctx == NULL) {
451         reason = ERR_R_MALLOC_FAILURE;
452         goto err;
453     }
454
455     if (ktype > 0) {
456         public_key = EC_KEY_get0_public_key(x);
457         if (public_key != NULL) {
458             if ((pub_key = EC_POINT_point2bn(group, public_key,
459                                              EC_KEY_get_conv_form(x), NULL,
460                                              ctx)) == NULL) {
461                 reason = ERR_R_EC_LIB;
462                 goto err;
463             }
464             buf_len = (size_t)BN_num_bytes(pub_key);
465         }
466     }
467
468     if (ktype == 2) {
469         priv_key = EC_KEY_get0_private_key(x);
470         if (priv_key && (i = (size_t)BN_num_bytes(priv_key)) > buf_len)
471             buf_len = i;
472     } else
473         priv_key = NULL;
474
475     if (ktype > 0) {
476         buf_len += 10;
477         if ((buffer = OPENSSL_malloc(buf_len)) == NULL) {
478             reason = ERR_R_MALLOC_FAILURE;
479             goto err;
480         }
481     }
482     if (ktype == 2)
483         ecstr = "Private-Key";
484     else if (ktype == 1)
485         ecstr = "Public-Key";
486     else
487         ecstr = "ECDSA-Parameters";
488
489     if (!BIO_indent(bp, off, 128))
490         goto err;
491     if ((order = BN_new()) == NULL)
492         goto err;
493     if (!EC_GROUP_get_order(group, order, NULL))
494         goto err;
495     if (BIO_printf(bp, "%s: (%d bit)\n", ecstr, BN_num_bits(order)) <= 0)
496         goto err;
497
498     if ((priv_key != NULL) && !ASN1_bn_print(bp, "priv:", priv_key,
499                                              buffer, off))
500         goto err;
501     if ((pub_key != NULL) && !ASN1_bn_print(bp, "pub: ", pub_key,
502                                             buffer, off))
503         goto err;
504     if (!ECPKParameters_print(bp, group, off))
505         goto err;
506     ret = 1;
507  err:
508     if (!ret)
509         ECerr(EC_F_DO_EC_KEY_PRINT, reason);
510     BN_free(pub_key);
511     BN_free(order);
512     BN_CTX_free(ctx);
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
522     if ((eckey = d2i_ECParameters(NULL, pder, derlen)) == NULL) {
523         ECerr(EC_F_ECKEY_PARAM_DECODE, ERR_R_EC_LIB);
524         return 0;
525     }
526     EVP_PKEY_assign_EC_KEY(pkey, eckey);
527     return 1;
528 }
529
530 static int eckey_param_encode(const EVP_PKEY *pkey, unsigned char **pder)
531 {
532     return i2d_ECParameters(pkey->pkey.ec, pder);
533 }
534
535 static int eckey_param_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, 0);
539 }
540
541 static int eckey_pub_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, 1);
545 }
546
547 static int eckey_priv_print(BIO *bp, const EVP_PKEY *pkey, int indent,
548                             ASN1_PCTX *ctx)
549 {
550     return do_EC_KEY_print(bp, pkey->pkey.ec, indent, 2);
551 }
552
553 static int old_ec_priv_decode(EVP_PKEY *pkey,
554                               const unsigned char **pder, int derlen)
555 {
556     EC_KEY *ec;
557
558     if ((ec = d2i_ECPrivateKey(NULL, pder, derlen)) == NULL) {
559         ECerr(EC_F_OLD_EC_PRIV_DECODE, EC_R_DECODE_ERROR);
560         return 0;
561     }
562     EVP_PKEY_assign_EC_KEY(pkey, ec);
563     return 1;
564 }
565
566 static int old_ec_priv_encode(const EVP_PKEY *pkey, unsigned char **pder)
567 {
568     return i2d_ECPrivateKey(pkey->pkey.ec, pder);
569 }
570
571 static int ec_pkey_ctrl(EVP_PKEY *pkey, int op, long arg1, void *arg2)
572 {
573     switch (op) {
574     case ASN1_PKEY_CTRL_PKCS7_SIGN:
575         if (arg1 == 0) {
576             int snid, hnid;
577             X509_ALGOR *alg1, *alg2;
578             PKCS7_SIGNER_INFO_get0_algs(arg2, NULL, &alg1, &alg2);
579             if (alg1 == NULL || alg1->algorithm == NULL)
580                 return -1;
581             hnid = OBJ_obj2nid(alg1->algorithm);
582             if (hnid == NID_undef)
583                 return -1;
584             if (!OBJ_find_sigid_by_algs(&snid, hnid, EVP_PKEY_id(pkey)))
585                 return -1;
586             X509_ALGOR_set0(alg2, OBJ_nid2obj(snid), V_ASN1_UNDEF, 0);
587         }
588         return 1;
589 #ifndef OPENSSL_NO_CMS
590     case ASN1_PKEY_CTRL_CMS_SIGN:
591         if (arg1 == 0) {
592             int snid, hnid;
593             X509_ALGOR *alg1, *alg2;
594             CMS_SignerInfo_get0_algs(arg2, NULL, NULL, &alg1, &alg2);
595             if (alg1 == NULL || alg1->algorithm == NULL)
596                 return -1;
597             hnid = OBJ_obj2nid(alg1->algorithm);
598             if (hnid == NID_undef)
599                 return -1;
600             if (!OBJ_find_sigid_by_algs(&snid, hnid, EVP_PKEY_id(pkey)))
601                 return -1;
602             X509_ALGOR_set0(alg2, OBJ_nid2obj(snid), V_ASN1_UNDEF, 0);
603         }
604         return 1;
605
606     case ASN1_PKEY_CTRL_CMS_ENVELOPE:
607         if (arg1 == 1)
608             return ecdh_cms_decrypt(arg2);
609         else if (arg1 == 0)
610             return ecdh_cms_encrypt(arg2);
611         return -2;
612
613     case ASN1_PKEY_CTRL_CMS_RI_TYPE:
614         *(int *)arg2 = CMS_RECIPINFO_AGREE;
615         return 1;
616 #endif
617
618     case ASN1_PKEY_CTRL_DEFAULT_MD_NID:
619         *(int *)arg2 = NID_sha256;
620         return 2;
621
622     default:
623         return -2;
624
625     }
626
627 }
628
629 const EVP_PKEY_ASN1_METHOD eckey_asn1_meth = {
630     EVP_PKEY_EC,
631     EVP_PKEY_EC,
632     0,
633     "EC",
634     "OpenSSL EC algorithm",
635
636     eckey_pub_decode,
637     eckey_pub_encode,
638     eckey_pub_cmp,
639     eckey_pub_print,
640
641     eckey_priv_decode,
642     eckey_priv_encode,
643     eckey_priv_print,
644
645     int_ec_size,
646     ec_bits,
647     ec_security_bits,
648
649     eckey_param_decode,
650     eckey_param_encode,
651     ec_missing_parameters,
652     ec_copy_parameters,
653     ec_cmp_parameters,
654     eckey_param_print,
655     0,
656
657     int_ec_free,
658     ec_pkey_ctrl,
659     old_ec_priv_decode,
660     old_ec_priv_encode
661 };
662
663 #ifndef OPENSSL_NO_CMS
664
665 static int ecdh_cms_set_peerkey(EVP_PKEY_CTX *pctx,
666                                 X509_ALGOR *alg, ASN1_BIT_STRING *pubkey)
667 {
668     ASN1_OBJECT *aoid;
669     int atype;
670     void *aval;
671     int rv = 0;
672     EVP_PKEY *pkpeer = NULL;
673     EC_KEY *ecpeer = NULL;
674     const unsigned char *p;
675     int plen;
676     X509_ALGOR_get0(&aoid, &atype, &aval, alg);
677     if (OBJ_obj2nid(aoid) != NID_X9_62_id_ecPublicKey)
678         goto err;
679     /* If absent parameters get group from main key */
680     if (atype == V_ASN1_UNDEF || atype == V_ASN1_NULL) {
681         const EC_GROUP *grp;
682         EVP_PKEY *pk;
683         pk = EVP_PKEY_CTX_get0_pkey(pctx);
684         if (!pk)
685             goto err;
686         grp = EC_KEY_get0_group(pk->pkey.ec);
687         ecpeer = EC_KEY_new();
688         if (ecpeer == NULL)
689             goto err;
690         if (!EC_KEY_set_group(ecpeer, grp))
691             goto err;
692     } else {
693         ecpeer = eckey_type2param(atype, aval);
694         if (!ecpeer)
695             goto err;
696     }
697     /* We have parameters now set public key */
698     plen = ASN1_STRING_length(pubkey);
699     p = ASN1_STRING_data(pubkey);
700     if (!p || !plen)
701         goto err;
702     if (!o2i_ECPublicKey(&ecpeer, &p, plen))
703         goto err;
704     pkpeer = EVP_PKEY_new();
705     if (pkpeer == NULL)
706         goto err;
707     EVP_PKEY_set1_EC_KEY(pkpeer, ecpeer);
708     if (EVP_PKEY_derive_set_peer(pctx, pkpeer) > 0)
709         rv = 1;
710  err:
711     EC_KEY_free(ecpeer);
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     X509_ALGOR_free(kekalg);
805     OPENSSL_free(der);
806     return rv;
807 }
808
809 static int ecdh_cms_decrypt(CMS_RecipientInfo *ri)
810 {
811     EVP_PKEY_CTX *pctx;
812     pctx = CMS_RecipientInfo_get0_pkey_ctx(ri);
813     if (!pctx)
814         return 0;
815     /* See if we need to set peer key */
816     if (!EVP_PKEY_CTX_get0_peerkey(pctx)) {
817         X509_ALGOR *alg;
818         ASN1_BIT_STRING *pubkey;
819         if (!CMS_RecipientInfo_kari_get0_orig_id(ri, &alg, &pubkey,
820                                                  NULL, NULL, NULL))
821             return 0;
822         if (!alg || !pubkey)
823             return 0;
824         if (!ecdh_cms_set_peerkey(pctx, alg, pubkey)) {
825             ECerr(EC_F_ECDH_CMS_DECRYPT, EC_R_PEER_KEY_ERROR);
826             return 0;
827         }
828     }
829     /* Set ECDH derivation parameters and initialise unwrap context */
830     if (!ecdh_cms_set_shared_info(pctx, ri)) {
831         ECerr(EC_F_ECDH_CMS_DECRYPT, EC_R_SHARED_INFO_ERROR);
832         return 0;
833     }
834     return 1;
835 }
836
837 static int ecdh_cms_encrypt(CMS_RecipientInfo *ri)
838 {
839     EVP_PKEY_CTX *pctx;
840     EVP_PKEY *pkey;
841     EVP_CIPHER_CTX *ctx;
842     int keylen;
843     X509_ALGOR *talg, *wrap_alg = NULL;
844     ASN1_OBJECT *aoid;
845     ASN1_BIT_STRING *pubkey;
846     ASN1_STRING *wrap_str;
847     ASN1_OCTET_STRING *ukm;
848     unsigned char *penc = NULL;
849     int penclen;
850     int rv = 0;
851     int ecdh_nid, kdf_type, kdf_nid, wrap_nid;
852     const EVP_MD *kdf_md;
853     pctx = CMS_RecipientInfo_get0_pkey_ctx(ri);
854     if (!pctx)
855         return 0;
856     /* Get ephemeral key */
857     pkey = EVP_PKEY_CTX_get0_pkey(pctx);
858     if (!CMS_RecipientInfo_kari_get0_orig_id(ri, &talg, &pubkey,
859                                              NULL, NULL, NULL))
860         goto err;
861     X509_ALGOR_get0(&aoid, NULL, NULL, talg);
862     /* Is everything uninitialised? */
863     if (aoid == OBJ_nid2obj(NID_undef)) {
864
865         EC_KEY *eckey = pkey->pkey.ec;
866         /* Set the key */
867         unsigned char *p;
868
869         penclen = i2o_ECPublicKey(eckey, NULL);
870         if (penclen <= 0)
871             goto err;
872         penc = OPENSSL_malloc(penclen);
873         if (penc == NULL)
874             goto err;
875         p = penc;
876         penclen = i2o_ECPublicKey(eckey, &p);
877         if (penclen <= 0)
878             goto err;
879         ASN1_STRING_set0(pubkey, penc, penclen);
880         pubkey->flags &= ~(ASN1_STRING_FLAG_BITS_LEFT | 0x07);
881         pubkey->flags |= ASN1_STRING_FLAG_BITS_LEFT;
882
883         penc = NULL;
884         X509_ALGOR_set0(talg, OBJ_nid2obj(NID_X9_62_id_ecPublicKey),
885                         V_ASN1_UNDEF, NULL);
886     }
887
888     /* See if custom paraneters set */
889     kdf_type = EVP_PKEY_CTX_get_ecdh_kdf_type(pctx);
890     if (kdf_type <= 0)
891         goto err;
892     if (!EVP_PKEY_CTX_get_ecdh_kdf_md(pctx, &kdf_md))
893         goto err;
894     ecdh_nid = EVP_PKEY_CTX_get_ecdh_cofactor_mode(pctx);
895     if (ecdh_nid < 0)
896         goto err;
897     else if (ecdh_nid == 0)
898         ecdh_nid = NID_dh_std_kdf;
899     else if (ecdh_nid == 1)
900         ecdh_nid = NID_dh_cofactor_kdf;
901
902     if (kdf_type == EVP_PKEY_ECDH_KDF_NONE) {
903         kdf_type = EVP_PKEY_ECDH_KDF_X9_62;
904         if (EVP_PKEY_CTX_set_ecdh_kdf_type(pctx, kdf_type) <= 0)
905             goto err;
906     } else
907         /* Uknown KDF */
908         goto err;
909     if (kdf_md == NULL) {
910         /* Fixme later for better MD */
911         kdf_md = EVP_sha1();
912         if (EVP_PKEY_CTX_set_ecdh_kdf_md(pctx, kdf_md) <= 0)
913             goto err;
914     }
915
916     if (!CMS_RecipientInfo_kari_get0_alg(ri, &talg, &ukm))
917         goto err;
918
919     /* Lookup NID for KDF+cofactor+digest */
920
921     if (!OBJ_find_sigid_by_algs(&kdf_nid, EVP_MD_type(kdf_md), ecdh_nid))
922         goto err;
923     /* Get wrap NID */
924     ctx = CMS_RecipientInfo_kari_get0_ctx(ri);
925     wrap_nid = EVP_CIPHER_CTX_type(ctx);
926     keylen = EVP_CIPHER_CTX_key_length(ctx);
927
928     /* Package wrap algorithm in an AlgorithmIdentifier */
929
930     wrap_alg = X509_ALGOR_new();
931     if (wrap_alg == NULL)
932         goto err;
933     wrap_alg->algorithm = OBJ_nid2obj(wrap_nid);
934     wrap_alg->parameter = ASN1_TYPE_new();
935     if (wrap_alg->parameter == NULL)
936         goto err;
937     if (EVP_CIPHER_param_to_asn1(ctx, wrap_alg->parameter) <= 0)
938         goto err;
939     if (ASN1_TYPE_get(wrap_alg->parameter) == NID_undef) {
940         ASN1_TYPE_free(wrap_alg->parameter);
941         wrap_alg->parameter = NULL;
942     }
943
944     if (EVP_PKEY_CTX_set_ecdh_kdf_outlen(pctx, keylen) <= 0)
945         goto err;
946
947     penclen = CMS_SharedInfo_encode(&penc, wrap_alg, ukm, keylen);
948
949     if (!penclen)
950         goto err;
951
952     if (EVP_PKEY_CTX_set0_ecdh_kdf_ukm(pctx, penc, penclen) <= 0)
953         goto err;
954     penc = NULL;
955
956     /*
957      * Now need to wrap encoding of wrap AlgorithmIdentifier into parameter
958      * of another AlgorithmIdentifier.
959      */
960     penclen = i2d_X509_ALGOR(wrap_alg, &penc);
961     if (!penc || !penclen)
962         goto err;
963     wrap_str = ASN1_STRING_new();
964     if (wrap_str == NULL)
965         goto err;
966     ASN1_STRING_set0(wrap_str, penc, penclen);
967     penc = NULL;
968     X509_ALGOR_set0(talg, OBJ_nid2obj(kdf_nid), V_ASN1_SEQUENCE, wrap_str);
969
970     rv = 1;
971
972  err:
973     OPENSSL_free(penc);
974     X509_ALGOR_free(wrap_alg);
975     return rv;
976 }
977
978 #endif