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