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