3312faa336ded84cddde097c0f0af1ec95522421
[openssl.git] / crypto / ec / ec_ameth.c
1 /*
2  * Copyright 2006-2020 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 /*
11  * ECDH and ECDSA low level APIs are deprecated for public use, but still ok
12  * for internal use.
13  */
14 #include "internal/deprecated.h"
15
16 #include <stdio.h>
17 #include "internal/cryptlib.h"
18 #include <openssl/x509.h>
19 #include <openssl/ec.h>
20 #include <openssl/bn.h>
21 #include <openssl/cms.h>
22 #include <openssl/asn1t.h>
23 #include "crypto/asn1.h"
24 #include "crypto/evp.h"
25 #include "crypto/x509.h"
26 #include <openssl/core_names.h>
27 #include "openssl/param_build.h"
28 #include "ec_local.h"
29
30 #ifndef OPENSSL_NO_CMS
31 static int ecdh_cms_decrypt(CMS_RecipientInfo *ri);
32 static int ecdh_cms_encrypt(CMS_RecipientInfo *ri);
33 #endif
34
35 static int eckey_param2type(int *pptype, void **ppval, const EC_KEY *ec_key)
36 {
37     const EC_GROUP *group;
38     int nid;
39
40     if (ec_key == NULL || (group = EC_KEY_get0_group(ec_key)) == NULL) {
41         ECerr(EC_F_ECKEY_PARAM2TYPE, EC_R_MISSING_PARAMETERS);
42         return 0;
43     }
44     if (EC_GROUP_get_asn1_flag(group)
45         && (nid = EC_GROUP_get_curve_name(group)))
46         /* we have a 'named curve' => just set the OID */
47     {
48         ASN1_OBJECT *asn1obj = OBJ_nid2obj(nid);
49
50         if (asn1obj == NULL || OBJ_length(asn1obj) == 0) {
51             ASN1_OBJECT_free(asn1obj);
52             ECerr(EC_F_ECKEY_PARAM2TYPE, EC_R_MISSING_OID);
53             return 0;
54         }
55         *ppval = asn1obj;
56         *pptype = V_ASN1_OBJECT;
57     } else {                    /* explicit parameters */
58
59         ASN1_STRING *pstr = NULL;
60         pstr = ASN1_STRING_new();
61         if (pstr == NULL)
62             return 0;
63         pstr->length = i2d_ECParameters(ec_key, &pstr->data);
64         if (pstr->length <= 0) {
65             ASN1_STRING_free(pstr);
66             ECerr(EC_F_ECKEY_PARAM2TYPE, ERR_R_EC_LIB);
67             return 0;
68         }
69         *ppval = pstr;
70         *pptype = V_ASN1_SEQUENCE;
71     }
72     return 1;
73 }
74
75 static int eckey_pub_encode(X509_PUBKEY *pk, const EVP_PKEY *pkey)
76 {
77     const EC_KEY *ec_key = pkey->pkey.ec;
78     void *pval = NULL;
79     int ptype;
80     unsigned char *penc = NULL, *p;
81     int penclen;
82
83     if (!eckey_param2type(&ptype, &pval, ec_key)) {
84         ECerr(EC_F_ECKEY_PUB_ENCODE, ERR_R_EC_LIB);
85         return 0;
86     }
87     penclen = i2o_ECPublicKey(ec_key, NULL);
88     if (penclen <= 0)
89         goto err;
90     penc = OPENSSL_malloc(penclen);
91     if (penc == NULL)
92         goto err;
93     p = penc;
94     penclen = i2o_ECPublicKey(ec_key, &p);
95     if (penclen <= 0)
96         goto err;
97     if (X509_PUBKEY_set0_param(pk, OBJ_nid2obj(EVP_PKEY_EC),
98                                ptype, pval, penc, penclen))
99         return 1;
100  err:
101     if (ptype == V_ASN1_OBJECT)
102         ASN1_OBJECT_free(pval);
103     else
104         ASN1_STRING_free(pval);
105     OPENSSL_free(penc);
106     return 0;
107 }
108
109 static EC_KEY *eckey_type2param(int ptype, const void *pval,
110                                 OPENSSL_CTX *libctx, const char *propq)
111 {
112     EC_KEY *eckey = NULL;
113     EC_GROUP *group = NULL;
114
115     if ((eckey = EC_KEY_new_with_libctx(libctx, propq)) == NULL) {
116         ECerr(EC_F_ECKEY_TYPE2PARAM, ERR_R_MALLOC_FAILURE);
117         goto ecerr;
118     }
119
120     if (ptype == V_ASN1_SEQUENCE) {
121         const ASN1_STRING *pstr = pval;
122         const unsigned char *pm = pstr->data;
123         int pmlen = pstr->length;
124
125
126         if (d2i_ECParameters(&eckey, &pm, pmlen) == NULL) {
127             ECerr(EC_F_ECKEY_TYPE2PARAM, EC_R_DECODE_ERROR);
128             goto ecerr;
129         }
130     } else if (ptype == V_ASN1_OBJECT) {
131         const ASN1_OBJECT *poid = pval;
132
133         /*
134          * type == V_ASN1_OBJECT => the parameters are given by an asn1 OID
135          */
136
137         group = EC_GROUP_new_by_curve_name_with_libctx(libctx, propq,
138                                                        OBJ_obj2nid(poid));
139         if (group == NULL)
140             goto ecerr;
141         EC_GROUP_set_asn1_flag(group, OPENSSL_EC_NAMED_CURVE);
142         if (EC_KEY_set_group(eckey, group) == 0)
143             goto ecerr;
144         EC_GROUP_free(group);
145     } else {
146         ECerr(EC_F_ECKEY_TYPE2PARAM, EC_R_DECODE_ERROR);
147         goto ecerr;
148     }
149
150     return eckey;
151
152  ecerr:
153     EC_KEY_free(eckey);
154     EC_GROUP_free(group);
155     return NULL;
156 }
157
158 static int eckey_pub_decode(EVP_PKEY *pkey, const X509_PUBKEY *pubkey)
159 {
160     const unsigned char *p = NULL;
161     const void *pval;
162     int ptype, pklen;
163     EC_KEY *eckey = NULL;
164     X509_ALGOR *palg;
165     OPENSSL_CTX *libctx = NULL;
166     const char *propq = NULL;
167
168     if (!X509_PUBKEY_get0_libctx(&libctx, &propq, pubkey)
169         || !X509_PUBKEY_get0_param(NULL, &p, &pklen, &palg, pubkey))
170         return 0;
171     X509_ALGOR_get0(NULL, &ptype, &pval, palg);
172
173     eckey = eckey_type2param(ptype, pval, libctx, propq);
174
175     if (!eckey)
176         return 0;
177
178     /* We have parameters now set public key */
179     if (!o2i_ECPublicKey(&eckey, &p, pklen)) {
180         ECerr(EC_F_ECKEY_PUB_DECODE, EC_R_DECODE_ERROR);
181         goto ecerr;
182     }
183
184     EVP_PKEY_assign_EC_KEY(pkey, eckey);
185     return 1;
186
187  ecerr:
188     EC_KEY_free(eckey);
189     return 0;
190 }
191
192 static int eckey_pub_cmp(const EVP_PKEY *a, const EVP_PKEY *b)
193 {
194     int r;
195     const EC_GROUP *group = EC_KEY_get0_group(b->pkey.ec);
196     const EC_POINT *pa = EC_KEY_get0_public_key(a->pkey.ec),
197         *pb = EC_KEY_get0_public_key(b->pkey.ec);
198
199     if (group == NULL || pa == NULL || pb == NULL)
200         return -2;
201     r = EC_POINT_cmp(group, pa, pb, NULL);
202     if (r == 0)
203         return 1;
204     if (r == 1)
205         return 0;
206     return -2;
207 }
208
209 static int eckey_priv_decode_with_libctx(EVP_PKEY *pkey,
210                                          const PKCS8_PRIV_KEY_INFO *p8,
211                                          OPENSSL_CTX *libctx,
212                                          const char *propq)
213 {
214     const unsigned char *p = NULL;
215     const void *pval;
216     int ptype, pklen;
217     EC_KEY *eckey = NULL;
218     const X509_ALGOR *palg;
219
220     if (!PKCS8_pkey_get0(NULL, &p, &pklen, &palg, p8))
221         return 0;
222     X509_ALGOR_get0(NULL, &ptype, &pval, palg);
223
224     eckey = eckey_type2param(ptype, pval, libctx, propq);
225     if (eckey == NULL)
226         goto err;
227
228     /* We have parameters now set private key */
229     if (!d2i_ECPrivateKey(&eckey, &p, pklen)) {
230         ECerr(0, EC_R_DECODE_ERROR);
231         goto err;
232     }
233
234     EVP_PKEY_assign_EC_KEY(pkey, eckey);
235     return 1;
236
237  err:
238     EC_KEY_free(eckey);
239     return 0;
240 }
241
242 static int eckey_priv_encode(PKCS8_PRIV_KEY_INFO *p8, const EVP_PKEY *pkey)
243 {
244     EC_KEY ec_key = *(pkey->pkey.ec);
245     unsigned char *ep, *p;
246     int eplen, ptype;
247     void *pval;
248     unsigned int old_flags;
249
250     if (!eckey_param2type(&ptype, &pval, &ec_key)) {
251         ECerr(EC_F_ECKEY_PRIV_ENCODE, EC_R_DECODE_ERROR);
252         return 0;
253     }
254
255     /* set the private key */
256
257     /*
258      * do not include the parameters in the SEC1 private key see PKCS#11
259      * 12.11
260      */
261     old_flags = EC_KEY_get_enc_flags(&ec_key);
262     EC_KEY_set_enc_flags(&ec_key, old_flags | EC_PKEY_NO_PARAMETERS);
263
264     eplen = i2d_ECPrivateKey(&ec_key, NULL);
265     if (!eplen) {
266         ECerr(EC_F_ECKEY_PRIV_ENCODE, ERR_R_EC_LIB);
267         return 0;
268     }
269     ep = OPENSSL_malloc(eplen);
270     if (ep == NULL) {
271         ECerr(EC_F_ECKEY_PRIV_ENCODE, ERR_R_MALLOC_FAILURE);
272         return 0;
273     }
274     p = ep;
275     if (!i2d_ECPrivateKey(&ec_key, &p)) {
276         OPENSSL_free(ep);
277         ECerr(EC_F_ECKEY_PRIV_ENCODE, ERR_R_EC_LIB);
278         return 0;
279     }
280
281     if (!PKCS8_pkey_set0(p8, OBJ_nid2obj(NID_X9_62_id_ecPublicKey), 0,
282                          ptype, pval, ep, eplen)) {
283         OPENSSL_free(ep);
284         return 0;
285     }
286
287     return 1;
288 }
289
290 static int int_ec_size(const EVP_PKEY *pkey)
291 {
292     return ECDSA_size(pkey->pkey.ec);
293 }
294
295 static int ec_bits(const EVP_PKEY *pkey)
296 {
297     return EC_GROUP_order_bits(EC_KEY_get0_group(pkey->pkey.ec));
298 }
299
300 static int ec_security_bits(const EVP_PKEY *pkey)
301 {
302     int ecbits = ec_bits(pkey);
303
304     if (ecbits >= 512)
305         return 256;
306     if (ecbits >= 384)
307         return 192;
308     if (ecbits >= 256)
309         return 128;
310     if (ecbits >= 224)
311         return 112;
312     if (ecbits >= 160)
313         return 80;
314     return ecbits / 2;
315 }
316
317 static int ec_missing_parameters(const EVP_PKEY *pkey)
318 {
319     if (pkey->pkey.ec == NULL || EC_KEY_get0_group(pkey->pkey.ec) == NULL)
320         return 1;
321     return 0;
322 }
323
324 static int ec_copy_parameters(EVP_PKEY *to, const EVP_PKEY *from)
325 {
326     EC_GROUP *group = EC_GROUP_dup(EC_KEY_get0_group(from->pkey.ec));
327
328     if (group == NULL)
329         return 0;
330     if (to->pkey.ec == NULL) {
331         to->pkey.ec = EC_KEY_new();
332         if (to->pkey.ec == NULL)
333             goto err;
334     }
335     if (EC_KEY_set_group(to->pkey.ec, group) == 0)
336         goto err;
337     EC_GROUP_free(group);
338     return 1;
339  err:
340     EC_GROUP_free(group);
341     return 0;
342 }
343
344 static int ec_cmp_parameters(const EVP_PKEY *a, const EVP_PKEY *b)
345 {
346     const EC_GROUP *group_a = EC_KEY_get0_group(a->pkey.ec),
347         *group_b = EC_KEY_get0_group(b->pkey.ec);
348
349     if (group_a == NULL || group_b == NULL)
350         return -2;
351     if (EC_GROUP_cmp(group_a, group_b, NULL))
352         return 0;
353     else
354         return 1;
355 }
356
357 static void int_ec_free(EVP_PKEY *pkey)
358 {
359     EC_KEY_free(pkey->pkey.ec);
360 }
361
362 typedef enum {
363     EC_KEY_PRINT_PRIVATE,
364     EC_KEY_PRINT_PUBLIC,
365     EC_KEY_PRINT_PARAM
366 } ec_print_t;
367
368 static int do_EC_KEY_print(BIO *bp, const EC_KEY *x, int off, ec_print_t ktype)
369 {
370     const char *ecstr;
371     unsigned char *priv = NULL, *pub = NULL;
372     size_t privlen = 0, publen = 0;
373     int ret = 0;
374     const EC_GROUP *group;
375
376     if (x == NULL || (group = EC_KEY_get0_group(x)) == NULL) {
377         ECerr(EC_F_DO_EC_KEY_PRINT, ERR_R_PASSED_NULL_PARAMETER);
378         return 0;
379     }
380
381     if (ktype != EC_KEY_PRINT_PARAM && EC_KEY_get0_public_key(x) != NULL) {
382         publen = EC_KEY_key2buf(x, EC_KEY_get_conv_form(x), &pub, NULL);
383         if (publen == 0)
384             goto err;
385     }
386
387     if (ktype == EC_KEY_PRINT_PRIVATE && EC_KEY_get0_private_key(x) != NULL) {
388         privlen = EC_KEY_priv2buf(x, &priv);
389         if (privlen == 0)
390             goto err;
391     }
392
393     if (ktype == EC_KEY_PRINT_PRIVATE)
394         ecstr = "Private-Key";
395     else if (ktype == EC_KEY_PRINT_PUBLIC)
396         ecstr = "Public-Key";
397     else
398         ecstr = "ECDSA-Parameters";
399
400     if (!BIO_indent(bp, off, 128))
401         goto err;
402     if (BIO_printf(bp, "%s: (%d bit)\n", ecstr,
403                    EC_GROUP_order_bits(group)) <= 0)
404         goto err;
405
406     if (privlen != 0) {
407         if (BIO_printf(bp, "%*spriv:\n", off, "") <= 0)
408             goto err;
409         if (ASN1_buf_print(bp, priv, privlen, off + 4) == 0)
410             goto err;
411     }
412
413     if (publen != 0) {
414         if (BIO_printf(bp, "%*spub:\n", off, "") <= 0)
415             goto err;
416         if (ASN1_buf_print(bp, pub, publen, off + 4) == 0)
417             goto err;
418     }
419
420     if (!ECPKParameters_print(bp, group, off))
421         goto err;
422     ret = 1;
423  err:
424     if (!ret)
425         ECerr(EC_F_DO_EC_KEY_PRINT, ERR_R_EC_LIB);
426     OPENSSL_clear_free(priv, privlen);
427     OPENSSL_free(pub);
428     return ret;
429 }
430
431 static int eckey_param_decode(EVP_PKEY *pkey,
432                               const unsigned char **pder, int derlen)
433 {
434     EC_KEY *eckey;
435
436     if ((eckey = d2i_ECParameters(NULL, pder, derlen)) == NULL)
437         return 0;
438     EVP_PKEY_assign_EC_KEY(pkey, eckey);
439     return 1;
440 }
441
442 static int eckey_param_encode(const EVP_PKEY *pkey, unsigned char **pder)
443 {
444     return i2d_ECParameters(pkey->pkey.ec, pder);
445 }
446
447 static int eckey_param_print(BIO *bp, const EVP_PKEY *pkey, int indent,
448                              ASN1_PCTX *ctx)
449 {
450     return do_EC_KEY_print(bp, pkey->pkey.ec, indent, EC_KEY_PRINT_PARAM);
451 }
452
453 static int eckey_pub_print(BIO *bp, const EVP_PKEY *pkey, int indent,
454                            ASN1_PCTX *ctx)
455 {
456     return do_EC_KEY_print(bp, pkey->pkey.ec, indent, EC_KEY_PRINT_PUBLIC);
457 }
458
459 static int eckey_priv_print(BIO *bp, const EVP_PKEY *pkey, int indent,
460                             ASN1_PCTX *ctx)
461 {
462     return do_EC_KEY_print(bp, pkey->pkey.ec, indent, EC_KEY_PRINT_PRIVATE);
463 }
464
465 static int old_ec_priv_decode(EVP_PKEY *pkey,
466                               const unsigned char **pder, int derlen)
467 {
468     EC_KEY *ec;
469
470     if ((ec = d2i_ECPrivateKey(NULL, pder, derlen)) == NULL)
471         return 0;
472     EVP_PKEY_assign_EC_KEY(pkey, ec);
473     return 1;
474 }
475
476 static int old_ec_priv_encode(const EVP_PKEY *pkey, unsigned char **pder)
477 {
478     return i2d_ECPrivateKey(pkey->pkey.ec, pder);
479 }
480
481 static int ec_pkey_ctrl(EVP_PKEY *pkey, int op, long arg1, void *arg2)
482 {
483     switch (op) {
484     case ASN1_PKEY_CTRL_PKCS7_SIGN:
485         if (arg1 == 0) {
486             int snid, hnid;
487             X509_ALGOR *alg1, *alg2;
488
489             PKCS7_SIGNER_INFO_get0_algs(arg2, NULL, &alg1, &alg2);
490             if (alg1 == NULL || alg1->algorithm == NULL)
491                 return -1;
492             hnid = OBJ_obj2nid(alg1->algorithm);
493             if (hnid == NID_undef)
494                 return -1;
495             if (!OBJ_find_sigid_by_algs(&snid, hnid, EVP_PKEY_id(pkey)))
496                 return -1;
497             X509_ALGOR_set0(alg2, OBJ_nid2obj(snid), V_ASN1_UNDEF, 0);
498         }
499         return 1;
500 #ifndef OPENSSL_NO_CMS
501     case ASN1_PKEY_CTRL_CMS_SIGN:
502         if (arg1 == 0) {
503             int snid, hnid;
504             X509_ALGOR *alg1, *alg2;
505             CMS_SignerInfo_get0_algs(arg2, NULL, NULL, &alg1, &alg2);
506             if (alg1 == NULL || alg1->algorithm == NULL)
507                 return -1;
508             hnid = OBJ_obj2nid(alg1->algorithm);
509             if (hnid == NID_undef)
510                 return -1;
511             if (!OBJ_find_sigid_by_algs(&snid, hnid, EVP_PKEY_id(pkey)))
512                 return -1;
513             X509_ALGOR_set0(alg2, OBJ_nid2obj(snid), V_ASN1_UNDEF, 0);
514         }
515         return 1;
516
517     case ASN1_PKEY_CTRL_CMS_ENVELOPE:
518         if (arg1 == 1)
519             return ecdh_cms_decrypt(arg2);
520         else if (arg1 == 0)
521             return ecdh_cms_encrypt(arg2);
522         return -2;
523
524     case ASN1_PKEY_CTRL_CMS_RI_TYPE:
525         *(int *)arg2 = CMS_RECIPINFO_AGREE;
526         return 1;
527 #endif
528
529     case ASN1_PKEY_CTRL_DEFAULT_MD_NID:
530         if (EVP_PKEY_id(pkey) == EVP_PKEY_SM2) {
531             /* For SM2, the only valid digest-alg is SM3 */
532             *(int *)arg2 = NID_sm3;
533             return 2;            /* Make it mandatory */
534         }
535         *(int *)arg2 = NID_sha256;
536         return 1;
537
538     case ASN1_PKEY_CTRL_SET1_TLS_ENCPT:
539         return EC_KEY_oct2key(EVP_PKEY_get0_EC_KEY(pkey), arg2, arg1, NULL);
540
541     case ASN1_PKEY_CTRL_GET1_TLS_ENCPT:
542         return EC_KEY_key2buf(EVP_PKEY_get0_EC_KEY(pkey),
543                               POINT_CONVERSION_UNCOMPRESSED, arg2, NULL);
544
545     default:
546         return -2;
547
548     }
549
550 }
551
552 static int ec_pkey_check(const EVP_PKEY *pkey)
553 {
554     EC_KEY *eckey = pkey->pkey.ec;
555
556     /* stay consistent to what EVP_PKEY_check demands */
557     if (eckey->priv_key == NULL) {
558         ECerr(EC_F_EC_PKEY_CHECK, EC_R_MISSING_PRIVATE_KEY);
559         return 0;
560     }
561
562     return EC_KEY_check_key(eckey);
563 }
564
565 static int ec_pkey_public_check(const EVP_PKEY *pkey)
566 {
567     EC_KEY *eckey = pkey->pkey.ec;
568
569     /*
570      * Note: it unnecessary to check eckey->pub_key here since
571      * it will be checked in EC_KEY_check_key(). In fact, the
572      * EC_KEY_check_key() mainly checks the public key, and checks
573      * the private key optionally (only if there is one). So if
574      * someone passes a whole EC key (public + private), this
575      * will also work...
576      */
577
578     return EC_KEY_check_key(eckey);
579 }
580
581 static int ec_pkey_param_check(const EVP_PKEY *pkey)
582 {
583     EC_KEY *eckey = pkey->pkey.ec;
584
585     /* stay consistent to what EVP_PKEY_check demands */
586     if (eckey->group == NULL) {
587         ECerr(EC_F_EC_PKEY_PARAM_CHECK, EC_R_MISSING_PARAMETERS);
588         return 0;
589     }
590
591     return EC_GROUP_check(eckey->group, NULL);
592 }
593
594 static
595 size_t ec_pkey_dirty_cnt(const EVP_PKEY *pkey)
596 {
597     return pkey->pkey.ec->dirty_cnt;
598 }
599
600 static
601 int ec_pkey_export_to(const EVP_PKEY *from, void *to_keydata,
602                       EVP_KEYMGMT *to_keymgmt, OPENSSL_CTX *libctx,
603                       const char *propq)
604 {
605     const EC_KEY *eckey = NULL;
606     const EC_GROUP *ecg = NULL;
607     unsigned char *pub_key_buf = NULL, *gen_buf = NULL;
608     size_t pub_key_buflen;
609     OSSL_PARAM_BLD *tmpl;
610     OSSL_PARAM *params = NULL;
611     const BIGNUM *priv_key = NULL;
612     const EC_POINT *pub_point = NULL;
613     int selection = 0;
614     int rv = 0;
615     BN_CTX *bnctx = NULL;
616
617     if (from == NULL
618             || (eckey = from->pkey.ec) == NULL
619             || (ecg = EC_KEY_get0_group(eckey)) == NULL)
620         return 0;
621
622     /*
623      * If the EC_KEY method is foreign, then we can't be sure of anything,
624      * and can therefore not export or pretend to export.
625      */
626     if (EC_KEY_get_method(eckey) != EC_KEY_OpenSSL())
627         return 0;
628
629     tmpl = OSSL_PARAM_BLD_new();
630     if (tmpl == NULL)
631         return 0;
632
633     /*
634      * EC_POINT_point2buf() can generate random numbers in some
635      * implementations so we need to ensure we use the correct libctx.
636      */
637     bnctx = BN_CTX_new_ex(libctx);
638     if (bnctx == NULL)
639         goto err;
640     BN_CTX_start(bnctx);
641
642     /* export the domain parameters */
643     if (!ec_group_todata(ecg, tmpl, NULL, libctx, propq, bnctx, &gen_buf))
644         goto err;
645     selection |= OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS;
646
647     priv_key = EC_KEY_get0_private_key(eckey);
648     pub_point = EC_KEY_get0_public_key(eckey);
649
650     if (pub_point != NULL) {
651         /* convert pub_point to a octet string according to the SECG standard */
652         if ((pub_key_buflen = EC_POINT_point2buf(ecg, pub_point,
653                                                  POINT_CONVERSION_COMPRESSED,
654                                                  &pub_key_buf, bnctx)) == 0
655             || !OSSL_PARAM_BLD_push_octet_string(tmpl,
656                                                  OSSL_PKEY_PARAM_PUB_KEY,
657                                                  pub_key_buf,
658                                                  pub_key_buflen))
659             goto err;
660         selection |= OSSL_KEYMGMT_SELECT_PUBLIC_KEY;
661     }
662
663     if (priv_key != NULL) {
664         size_t sz;
665         int ecbits;
666         int ecdh_cofactor_mode;
667
668         /*
669          * Key import/export should never leak the bit length of the secret
670          * scalar in the key.
671          *
672          * For this reason, on export we use padded BIGNUMs with fixed length.
673          *
674          * When importing we also should make sure that, even if short lived,
675          * the newly created BIGNUM is marked with the BN_FLG_CONSTTIME flag as
676          * soon as possible, so that any processing of this BIGNUM might opt for
677          * constant time implementations in the backend.
678          *
679          * Setting the BN_FLG_CONSTTIME flag alone is never enough, we also have
680          * to preallocate the BIGNUM internal buffer to a fixed public size big
681          * enough that operations performed during the processing never trigger
682          * a realloc which would leak the size of the scalar through memory
683          * accesses.
684          *
685          * Fixed Length
686          * ------------
687          *
688          * The order of the large prime subgroup of the curve is our choice for
689          * a fixed public size, as that is generally the upper bound for
690          * generating a private key in EC cryptosystems and should fit all valid
691          * secret scalars.
692          *
693          * For padding on export we just use the bit length of the order
694          * converted to bytes (rounding up).
695          *
696          * For preallocating the BIGNUM storage we look at the number of "words"
697          * required for the internal representation of the order, and we
698          * preallocate 2 extra "words" in case any of the subsequent processing
699          * might temporarily overflow the order length.
700          */
701         ecbits = EC_GROUP_order_bits(ecg);
702         if (ecbits <= 0)
703             goto err;
704
705         sz = (ecbits + 7 ) / 8;
706         if (!OSSL_PARAM_BLD_push_BN_pad(tmpl,
707                                         OSSL_PKEY_PARAM_PRIV_KEY,
708                                         priv_key, sz))
709             goto err;
710         selection |= OSSL_KEYMGMT_SELECT_PRIVATE_KEY;
711
712         /*
713          * The ECDH Cofactor Mode is defined only if the EC_KEY actually
714          * contains a private key, so we check for the flag and export it only
715          * in this case.
716          */
717         ecdh_cofactor_mode =
718             (EC_KEY_get_flags(eckey) & EC_FLAG_COFACTOR_ECDH) ? 1 : 0;
719
720         /* Export the ECDH_COFACTOR_MODE parameter */
721         if (!OSSL_PARAM_BLD_push_int(tmpl,
722                                      OSSL_PKEY_PARAM_USE_COFACTOR_ECDH,
723                                      ecdh_cofactor_mode))
724             goto err;
725         selection |= OSSL_KEYMGMT_SELECT_OTHER_PARAMETERS;
726     }
727
728     params = OSSL_PARAM_BLD_to_param(tmpl);
729
730     /* We export, the provider imports */
731     rv = evp_keymgmt_import(to_keymgmt, to_keydata, selection, params);
732
733  err:
734     OSSL_PARAM_BLD_free(tmpl);
735     OSSL_PARAM_BLD_free_params(params);
736     OPENSSL_free(pub_key_buf);
737     OPENSSL_free(gen_buf);
738     BN_CTX_end(bnctx);
739     BN_CTX_free(bnctx);
740     return rv;
741 }
742
743 static int ec_pkey_import_from(const OSSL_PARAM params[], void *vpctx)
744 {
745     EVP_PKEY_CTX *pctx = vpctx;
746     EVP_PKEY *pkey = EVP_PKEY_CTX_get0_pkey(pctx);
747     EC_KEY *ec = EC_KEY_new_with_libctx(pctx->libctx, pctx->propquery);
748
749     if (ec == NULL) {
750         ERR_raise(ERR_LIB_DH, ERR_R_MALLOC_FAILURE);
751         return 0;
752     }
753
754     if (!ec_group_fromdata(ec, params)
755         || !ec_key_otherparams_fromdata(ec, params)
756         || !ec_key_fromdata(ec, params, 1)
757         || !EVP_PKEY_assign_EC_KEY(pkey, ec)) {
758         EC_KEY_free(ec);
759         return 0;
760     }
761     return 1;
762 }
763
764 const EVP_PKEY_ASN1_METHOD eckey_asn1_meth = {
765     EVP_PKEY_EC,
766     EVP_PKEY_EC,
767     0,
768     "EC",
769     "OpenSSL EC algorithm",
770
771     eckey_pub_decode,
772     eckey_pub_encode,
773     eckey_pub_cmp,
774     eckey_pub_print,
775
776     NULL,
777     eckey_priv_encode,
778     eckey_priv_print,
779
780     int_ec_size,
781     ec_bits,
782     ec_security_bits,
783
784     eckey_param_decode,
785     eckey_param_encode,
786     ec_missing_parameters,
787     ec_copy_parameters,
788     ec_cmp_parameters,
789     eckey_param_print,
790     0,
791
792     int_ec_free,
793     ec_pkey_ctrl,
794     old_ec_priv_decode,
795     old_ec_priv_encode,
796
797     0, 0, 0,
798
799     ec_pkey_check,
800     ec_pkey_public_check,
801     ec_pkey_param_check,
802
803     0, /* set_priv_key */
804     0, /* set_pub_key */
805     0, /* get_priv_key */
806     0, /* get_pub_key */
807
808     ec_pkey_dirty_cnt,
809     ec_pkey_export_to,
810     ec_pkey_import_from,
811     eckey_priv_decode_with_libctx
812 };
813
814 #if !defined(OPENSSL_NO_SM2)
815 const EVP_PKEY_ASN1_METHOD sm2_asn1_meth = {
816    EVP_PKEY_SM2,
817    EVP_PKEY_EC,
818    ASN1_PKEY_ALIAS
819 };
820 #endif
821
822 int EC_KEY_print(BIO *bp, const EC_KEY *x, int off)
823 {
824     int private = EC_KEY_get0_private_key(x) != NULL;
825
826     return do_EC_KEY_print(bp, x, off,
827                 private ? EC_KEY_PRINT_PRIVATE : EC_KEY_PRINT_PUBLIC);
828 }
829
830 int ECParameters_print(BIO *bp, const EC_KEY *x)
831 {
832     return do_EC_KEY_print(bp, x, 4, EC_KEY_PRINT_PARAM);
833 }
834
835 #ifndef OPENSSL_NO_CMS
836
837 static int ecdh_cms_set_peerkey(EVP_PKEY_CTX *pctx,
838                                 X509_ALGOR *alg, ASN1_BIT_STRING *pubkey)
839 {
840     const ASN1_OBJECT *aoid;
841     int atype;
842     const void *aval;
843     int rv = 0;
844     EVP_PKEY *pkpeer = NULL;
845     EC_KEY *ecpeer = NULL;
846     const unsigned char *p;
847     int plen;
848
849     X509_ALGOR_get0(&aoid, &atype, &aval, alg);
850     if (OBJ_obj2nid(aoid) != NID_X9_62_id_ecPublicKey)
851         goto err;
852     /* If absent parameters get group from main key */
853     if (atype == V_ASN1_UNDEF || atype == V_ASN1_NULL) {
854         const EC_GROUP *grp;
855         EVP_PKEY *pk;
856         pk = EVP_PKEY_CTX_get0_pkey(pctx);
857         if (pk == NULL)
858             goto err;
859         grp = EC_KEY_get0_group(pk->pkey.ec);
860         ecpeer = EC_KEY_new();
861         if (ecpeer == NULL)
862             goto err;
863         if (!EC_KEY_set_group(ecpeer, grp))
864             goto err;
865     } else {
866         ecpeer = eckey_type2param(atype, aval, pctx->libctx, pctx->propquery);
867         if (!ecpeer)
868             goto err;
869     }
870     /* We have parameters now set public key */
871     plen = ASN1_STRING_length(pubkey);
872     p = ASN1_STRING_get0_data(pubkey);
873     if (p == NULL || plen == 0)
874         goto err;
875     if (!o2i_ECPublicKey(&ecpeer, &p, plen))
876         goto err;
877     pkpeer = EVP_PKEY_new();
878     if (pkpeer == NULL)
879         goto err;
880     EVP_PKEY_set1_EC_KEY(pkpeer, ecpeer);
881     if (EVP_PKEY_derive_set_peer(pctx, pkpeer) > 0)
882         rv = 1;
883  err:
884     EC_KEY_free(ecpeer);
885     EVP_PKEY_free(pkpeer);
886     return rv;
887 }
888
889 /* Set KDF parameters based on KDF NID */
890 static int ecdh_cms_set_kdf_param(EVP_PKEY_CTX *pctx, int eckdf_nid)
891 {
892     int kdf_nid, kdfmd_nid, cofactor;
893     const EVP_MD *kdf_md;
894     if (eckdf_nid == NID_undef)
895         return 0;
896
897     /* Lookup KDF type, cofactor mode and digest */
898     if (!OBJ_find_sigid_algs(eckdf_nid, &kdfmd_nid, &kdf_nid))
899         return 0;
900
901     if (kdf_nid == NID_dh_std_kdf)
902         cofactor = 0;
903     else if (kdf_nid == NID_dh_cofactor_kdf)
904         cofactor = 1;
905     else
906         return 0;
907
908     if (EVP_PKEY_CTX_set_ecdh_cofactor_mode(pctx, cofactor) <= 0)
909         return 0;
910
911     if (EVP_PKEY_CTX_set_ecdh_kdf_type(pctx, EVP_PKEY_ECDH_KDF_X9_63) <= 0)
912         return 0;
913
914     kdf_md = EVP_get_digestbynid(kdfmd_nid);
915     if (!kdf_md)
916         return 0;
917
918     if (EVP_PKEY_CTX_set_ecdh_kdf_md(pctx, kdf_md) <= 0)
919         return 0;
920     return 1;
921 }
922
923 static int ecdh_cms_set_shared_info(EVP_PKEY_CTX *pctx, CMS_RecipientInfo *ri)
924 {
925     int rv = 0;
926
927     X509_ALGOR *alg, *kekalg = NULL;
928     ASN1_OCTET_STRING *ukm;
929     const unsigned char *p;
930     unsigned char *der = NULL;
931     int plen, keylen;
932     EVP_CIPHER *kekcipher = NULL;
933     EVP_CIPHER_CTX *kekctx;
934     const char *name;
935
936     if (!CMS_RecipientInfo_kari_get0_alg(ri, &alg, &ukm))
937         return 0;
938
939     if (!ecdh_cms_set_kdf_param(pctx, OBJ_obj2nid(alg->algorithm))) {
940         ECerr(EC_F_ECDH_CMS_SET_SHARED_INFO, EC_R_KDF_PARAMETER_ERROR);
941         return 0;
942     }
943
944     if (alg->parameter->type != V_ASN1_SEQUENCE)
945         return 0;
946
947     p = alg->parameter->value.sequence->data;
948     plen = alg->parameter->value.sequence->length;
949     kekalg = d2i_X509_ALGOR(NULL, &p, plen);
950     if (kekalg == NULL)
951         goto err;
952     kekctx = CMS_RecipientInfo_kari_get0_ctx(ri);
953     if (kekctx == NULL)
954         goto err;
955     name = OBJ_nid2sn(OBJ_obj2nid(kekalg->algorithm));
956     kekcipher = EVP_CIPHER_fetch(pctx->libctx, name, pctx->propquery);
957     if (kekcipher == NULL || EVP_CIPHER_mode(kekcipher) != EVP_CIPH_WRAP_MODE)
958         goto err;
959     if (!EVP_EncryptInit_ex(kekctx, kekcipher, NULL, NULL, NULL))
960         goto err;
961     if (EVP_CIPHER_asn1_to_param(kekctx, kekalg->parameter) <= 0)
962         goto err;
963
964     keylen = EVP_CIPHER_CTX_key_length(kekctx);
965     if (EVP_PKEY_CTX_set_ecdh_kdf_outlen(pctx, keylen) <= 0)
966         goto err;
967
968     plen = CMS_SharedInfo_encode(&der, kekalg, ukm, keylen);
969
970     if (plen <= 0)
971         goto err;
972
973     if (EVP_PKEY_CTX_set0_ecdh_kdf_ukm(pctx, der, plen) <= 0)
974         goto err;
975     der = NULL;
976
977     rv = 1;
978  err:
979     EVP_CIPHER_free(kekcipher);
980     X509_ALGOR_free(kekalg);
981     OPENSSL_free(der);
982     return rv;
983 }
984
985 static int ecdh_cms_decrypt(CMS_RecipientInfo *ri)
986 {
987     EVP_PKEY_CTX *pctx;
988
989     pctx = CMS_RecipientInfo_get0_pkey_ctx(ri);
990     if (pctx == NULL)
991         return 0;
992     /* See if we need to set peer key */
993     if (!EVP_PKEY_CTX_get0_peerkey(pctx)) {
994         X509_ALGOR *alg;
995         ASN1_BIT_STRING *pubkey;
996
997         if (!CMS_RecipientInfo_kari_get0_orig_id(ri, &alg, &pubkey,
998                                                  NULL, NULL, NULL))
999             return 0;
1000         if (!alg || !pubkey)
1001             return 0;
1002         if (!ecdh_cms_set_peerkey(pctx, alg, pubkey)) {
1003             ECerr(EC_F_ECDH_CMS_DECRYPT, EC_R_PEER_KEY_ERROR);
1004             return 0;
1005         }
1006     }
1007     /* Set ECDH derivation parameters and initialise unwrap context */
1008     if (!ecdh_cms_set_shared_info(pctx, ri)) {
1009         ECerr(EC_F_ECDH_CMS_DECRYPT, EC_R_SHARED_INFO_ERROR);
1010         return 0;
1011     }
1012     return 1;
1013 }
1014
1015 static int ecdh_cms_encrypt(CMS_RecipientInfo *ri)
1016 {
1017     EVP_PKEY_CTX *pctx;
1018     EVP_PKEY *pkey;
1019     EVP_CIPHER_CTX *ctx;
1020     int keylen;
1021     X509_ALGOR *talg, *wrap_alg = NULL;
1022     const ASN1_OBJECT *aoid;
1023     ASN1_BIT_STRING *pubkey;
1024     ASN1_STRING *wrap_str;
1025     ASN1_OCTET_STRING *ukm;
1026     unsigned char *penc = NULL;
1027     int penclen;
1028     int rv = 0;
1029     int ecdh_nid, kdf_type, kdf_nid, wrap_nid;
1030     const EVP_MD *kdf_md;
1031
1032     pctx = CMS_RecipientInfo_get0_pkey_ctx(ri);
1033     if (pctx == NULL)
1034         return 0;
1035     /* Get ephemeral key */
1036     pkey = EVP_PKEY_CTX_get0_pkey(pctx);
1037     if (!CMS_RecipientInfo_kari_get0_orig_id(ri, &talg, &pubkey,
1038                                              NULL, NULL, NULL))
1039         goto err;
1040     X509_ALGOR_get0(&aoid, NULL, NULL, talg);
1041     /* Is everything uninitialised? */
1042     if (aoid == OBJ_nid2obj(NID_undef)) {
1043
1044         EC_KEY *eckey = pkey->pkey.ec;
1045         /* Set the key */
1046         unsigned char *p;
1047
1048         penclen = i2o_ECPublicKey(eckey, NULL);
1049         if (penclen <= 0)
1050             goto err;
1051         penc = OPENSSL_malloc(penclen);
1052         if (penc == NULL)
1053             goto err;
1054         p = penc;
1055         penclen = i2o_ECPublicKey(eckey, &p);
1056         if (penclen <= 0)
1057             goto err;
1058         ASN1_STRING_set0(pubkey, penc, penclen);
1059         pubkey->flags &= ~(ASN1_STRING_FLAG_BITS_LEFT | 0x07);
1060         pubkey->flags |= ASN1_STRING_FLAG_BITS_LEFT;
1061
1062         penc = NULL;
1063         X509_ALGOR_set0(talg, OBJ_nid2obj(NID_X9_62_id_ecPublicKey),
1064                         V_ASN1_UNDEF, NULL);
1065     }
1066
1067     /* See if custom parameters set */
1068     kdf_type = EVP_PKEY_CTX_get_ecdh_kdf_type(pctx);
1069     if (kdf_type <= 0)
1070         goto err;
1071     if (!EVP_PKEY_CTX_get_ecdh_kdf_md(pctx, &kdf_md))
1072         goto err;
1073     ecdh_nid = EVP_PKEY_CTX_get_ecdh_cofactor_mode(pctx);
1074     if (ecdh_nid < 0)
1075         goto err;
1076     else if (ecdh_nid == 0)
1077         ecdh_nid = NID_dh_std_kdf;
1078     else if (ecdh_nid == 1)
1079         ecdh_nid = NID_dh_cofactor_kdf;
1080
1081     if (kdf_type == EVP_PKEY_ECDH_KDF_NONE) {
1082         kdf_type = EVP_PKEY_ECDH_KDF_X9_63;
1083         if (EVP_PKEY_CTX_set_ecdh_kdf_type(pctx, kdf_type) <= 0)
1084             goto err;
1085     } else
1086         /* Unknown KDF */
1087         goto err;
1088     if (kdf_md == NULL) {
1089         /* Fixme later for better MD */
1090         kdf_md = EVP_sha1();
1091         if (EVP_PKEY_CTX_set_ecdh_kdf_md(pctx, kdf_md) <= 0)
1092             goto err;
1093     }
1094
1095     if (!CMS_RecipientInfo_kari_get0_alg(ri, &talg, &ukm))
1096         goto err;
1097
1098     /* Lookup NID for KDF+cofactor+digest */
1099
1100     if (!OBJ_find_sigid_by_algs(&kdf_nid, EVP_MD_type(kdf_md), ecdh_nid))
1101         goto err;
1102     /* Get wrap NID */
1103     ctx = CMS_RecipientInfo_kari_get0_ctx(ri);
1104     wrap_nid = EVP_CIPHER_CTX_type(ctx);
1105     keylen = EVP_CIPHER_CTX_key_length(ctx);
1106
1107     /* Package wrap algorithm in an AlgorithmIdentifier */
1108
1109     wrap_alg = X509_ALGOR_new();
1110     if (wrap_alg == NULL)
1111         goto err;
1112     wrap_alg->algorithm = OBJ_nid2obj(wrap_nid);
1113     wrap_alg->parameter = ASN1_TYPE_new();
1114     if (wrap_alg->parameter == NULL)
1115         goto err;
1116     if (EVP_CIPHER_param_to_asn1(ctx, wrap_alg->parameter) <= 0)
1117         goto err;
1118     if (ASN1_TYPE_get(wrap_alg->parameter) == NID_undef) {
1119         ASN1_TYPE_free(wrap_alg->parameter);
1120         wrap_alg->parameter = NULL;
1121     }
1122
1123     if (EVP_PKEY_CTX_set_ecdh_kdf_outlen(pctx, keylen) <= 0)
1124         goto err;
1125
1126     penclen = CMS_SharedInfo_encode(&penc, wrap_alg, ukm, keylen);
1127
1128     if (!penclen)
1129         goto err;
1130
1131     if (EVP_PKEY_CTX_set0_ecdh_kdf_ukm(pctx, penc, penclen) <= 0)
1132         goto err;
1133     penc = NULL;
1134
1135     /*
1136      * Now need to wrap encoding of wrap AlgorithmIdentifier into parameter
1137      * of another AlgorithmIdentifier.
1138      */
1139     penclen = i2d_X509_ALGOR(wrap_alg, &penc);
1140     if (!penc || !penclen)
1141         goto err;
1142     wrap_str = ASN1_STRING_new();
1143     if (wrap_str == NULL)
1144         goto err;
1145     ASN1_STRING_set0(wrap_str, penc, penclen);
1146     penc = NULL;
1147     X509_ALGOR_set0(talg, OBJ_nid2obj(kdf_nid), V_ASN1_SEQUENCE, wrap_str);
1148
1149     rv = 1;
1150
1151  err:
1152     OPENSSL_free(penc);
1153     X509_ALGOR_free(wrap_alg);
1154     return rv;
1155 }
1156
1157 #endif