xref: /openbsd-src/lib/libcrypto/ec/ec_ameth.c (revision c1a45aed656e7d5627c30c92421893a76f370ccb)
1 /* $OpenBSD: ec_ameth.c,v 1.31 2022/01/10 12:10:26 tb Exp $ */
2 /* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
3  * project 2006.
4  */
5 /* ====================================================================
6  * Copyright (c) 2006 The OpenSSL Project.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  *
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in
17  *    the documentation and/or other materials provided with the
18  *    distribution.
19  *
20  * 3. All advertising materials mentioning features or use of this
21  *    software must display the following acknowledgment:
22  *    "This product includes software developed by the OpenSSL Project
23  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
24  *
25  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
26  *    endorse or promote products derived from this software without
27  *    prior written permission. For written permission, please contact
28  *    licensing@OpenSSL.org.
29  *
30  * 5. Products derived from this software may not be called "OpenSSL"
31  *    nor may "OpenSSL" appear in their names without prior written
32  *    permission of the OpenSSL Project.
33  *
34  * 6. Redistributions of any form whatsoever must retain the following
35  *    acknowledgment:
36  *    "This product includes software developed by the OpenSSL Project
37  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
38  *
39  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
40  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
41  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
42  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
43  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
44  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
45  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
46  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
48  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
49  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
50  * OF THE POSSIBILITY OF SUCH DAMAGE.
51  * ====================================================================
52  *
53  * This product includes cryptographic software written by Eric Young
54  * (eay@cryptsoft.com).  This product includes software written by Tim
55  * Hudson (tjh@cryptsoft.com).
56  *
57  */
58 
59 #include <stdio.h>
60 
61 #include <openssl/opensslconf.h>
62 
63 #include <openssl/bn.h>
64 #include <openssl/cms.h>
65 #include <openssl/ec.h>
66 #include <openssl/err.h>
67 #include <openssl/x509.h>
68 
69 #include "asn1_locl.h"
70 #include "ec_lcl.h"
71 #include "evp_locl.h"
72 
73 #ifndef OPENSSL_NO_CMS
74 static int ecdh_cms_decrypt(CMS_RecipientInfo *ri);
75 static int ecdh_cms_encrypt(CMS_RecipientInfo *ri);
76 #endif
77 
78 static int
79 eckey_param2type(int *pptype, void **ppval, EC_KEY * ec_key)
80 {
81 	const EC_GROUP *group;
82 	int nid;
83 	if (ec_key == NULL || (group = EC_KEY_get0_group(ec_key)) == NULL) {
84 		ECerror(EC_R_MISSING_PARAMETERS);
85 		return 0;
86 	}
87 	if (EC_GROUP_get_asn1_flag(group) &&
88 	    (nid = EC_GROUP_get_curve_name(group))) {
89 		/* we have a 'named curve' => just set the OID */
90 		*ppval = OBJ_nid2obj(nid);
91 		*pptype = V_ASN1_OBJECT;
92 	} else {
93 		/* explicit parameters */
94 		ASN1_STRING *pstr = NULL;
95 		pstr = ASN1_STRING_new();
96 		if (!pstr)
97 			return 0;
98 		pstr->length = i2d_ECParameters(ec_key, &pstr->data);
99 		if (pstr->length <= 0) {
100 			ASN1_STRING_free(pstr);
101 			ECerror(ERR_R_EC_LIB);
102 			return 0;
103 		}
104 		*ppval = pstr;
105 		*pptype = V_ASN1_SEQUENCE;
106 	}
107 	return 1;
108 }
109 
110 static int
111 eckey_pub_encode(X509_PUBKEY * pk, const EVP_PKEY * pkey)
112 {
113 	EC_KEY *ec_key = pkey->pkey.ec;
114 	void *pval = NULL;
115 	int ptype;
116 	unsigned char *penc = NULL, *p;
117 	int penclen;
118 
119 	if (!eckey_param2type(&ptype, &pval, ec_key)) {
120 		ECerror(ERR_R_EC_LIB);
121 		return 0;
122 	}
123 	penclen = i2o_ECPublicKey(ec_key, NULL);
124 	if (penclen <= 0)
125 		goto err;
126 	penc = malloc(penclen);
127 	if (!penc)
128 		goto err;
129 	p = penc;
130 	penclen = i2o_ECPublicKey(ec_key, &p);
131 	if (penclen <= 0)
132 		goto err;
133 	if (X509_PUBKEY_set0_param(pk, OBJ_nid2obj(EVP_PKEY_EC),
134 		ptype, pval, penc, penclen))
135 		return 1;
136  err:
137 	if (ptype == V_ASN1_OBJECT)
138 		ASN1_OBJECT_free(pval);
139 	else
140 		ASN1_STRING_free(pval);
141 	free(penc);
142 	return 0;
143 }
144 
145 static EC_KEY *
146 eckey_type2param(int ptype, const void *pval)
147 {
148 	EC_GROUP *group = NULL;
149 	EC_KEY *eckey = NULL;
150 
151 	if (ptype == V_ASN1_SEQUENCE) {
152 		const ASN1_STRING *pstr = pval;
153 		const unsigned char *pm = NULL;
154 		int pmlen;
155 
156 		pm = pstr->data;
157 		pmlen = pstr->length;
158 		if (!(eckey = d2i_ECParameters(NULL, &pm, pmlen))) {
159 			ECerror(EC_R_DECODE_ERROR);
160 			goto ecerr;
161 		}
162 	} else if (ptype == V_ASN1_OBJECT) {
163 		const ASN1_OBJECT *poid = pval;
164 
165 		/*
166 		 * type == V_ASN1_OBJECT => the parameters are given by an
167 		 * asn1 OID
168 		 */
169 		if ((eckey = EC_KEY_new()) == NULL) {
170 			ECerror(ERR_R_MALLOC_FAILURE);
171 			goto ecerr;
172 		}
173 		group = EC_GROUP_new_by_curve_name(OBJ_obj2nid(poid));
174 		if (group == NULL)
175 			goto ecerr;
176 		EC_GROUP_set_asn1_flag(group, OPENSSL_EC_NAMED_CURVE);
177 		if (EC_KEY_set_group(eckey, group) == 0)
178 			goto ecerr;
179 	} else {
180 		ECerror(EC_R_DECODE_ERROR);
181 		goto ecerr;
182 	}
183 
184 	EC_GROUP_free(group);
185 	return eckey;
186 
187  ecerr:
188 	EC_KEY_free(eckey);
189 	EC_GROUP_free(group);
190 	return NULL;
191 }
192 
193 static int
194 eckey_pub_decode(EVP_PKEY * pkey, X509_PUBKEY * pubkey)
195 {
196 	const unsigned char *p = NULL;
197 	const void *pval;
198 	int ptype, pklen;
199 	EC_KEY *eckey = NULL;
200 	X509_ALGOR *palg;
201 
202 	if (!X509_PUBKEY_get0_param(NULL, &p, &pklen, &palg, pubkey))
203 		return 0;
204 	X509_ALGOR_get0(NULL, &ptype, &pval, palg);
205 
206 	eckey = eckey_type2param(ptype, pval);
207 
208 	if (!eckey) {
209 		ECerror(ERR_R_EC_LIB);
210 		return 0;
211 	}
212 	/* We have parameters now set public key */
213 	if (!o2i_ECPublicKey(&eckey, &p, pklen)) {
214 		ECerror(EC_R_DECODE_ERROR);
215 		goto ecerr;
216 	}
217 	EVP_PKEY_assign_EC_KEY(pkey, eckey);
218 	return 1;
219 
220  ecerr:
221 	if (eckey)
222 		EC_KEY_free(eckey);
223 	return 0;
224 }
225 
226 static int
227 eckey_pub_cmp(const EVP_PKEY * a, const EVP_PKEY * b)
228 {
229 	int r;
230 	const EC_GROUP *group = EC_KEY_get0_group(b->pkey.ec);
231 	const EC_POINT *pa = EC_KEY_get0_public_key(a->pkey.ec), *pb = EC_KEY_get0_public_key(b->pkey.ec);
232 
233 	r = EC_POINT_cmp(group, pa, pb, NULL);
234 	if (r == 0)
235 		return 1;
236 	if (r == 1)
237 		return 0;
238 	return -2;
239 }
240 
241 static int
242 eckey_priv_decode(EVP_PKEY * pkey, const PKCS8_PRIV_KEY_INFO * p8)
243 {
244 	const unsigned char *p = NULL;
245 	const void *pval;
246 	int ptype, pklen;
247 	EC_KEY *eckey = NULL;
248 	const X509_ALGOR *palg;
249 
250 	if (!PKCS8_pkey_get0(NULL, &p, &pklen, &palg, p8))
251 		return 0;
252 	X509_ALGOR_get0(NULL, &ptype, &pval, palg);
253 
254 	eckey = eckey_type2param(ptype, pval);
255 
256 	if (!eckey)
257 		goto ecliberr;
258 
259 	/* We have parameters now set private key */
260 	if (!d2i_ECPrivateKey(&eckey, &p, pklen)) {
261 		ECerror(EC_R_DECODE_ERROR);
262 		goto ecerr;
263 	}
264 	/* calculate public key (if necessary) */
265 	if (EC_KEY_get0_public_key(eckey) == NULL) {
266 		const BIGNUM *priv_key;
267 		const EC_GROUP *group;
268 		EC_POINT *pub_key;
269 		/*
270 		 * the public key was not included in the SEC1 private key =>
271 		 * calculate the public key
272 		 */
273 		group = EC_KEY_get0_group(eckey);
274 		pub_key = EC_POINT_new(group);
275 		if (pub_key == NULL) {
276 			ECerror(ERR_R_EC_LIB);
277 			goto ecliberr;
278 		}
279 		if (!EC_POINT_copy(pub_key, EC_GROUP_get0_generator(group))) {
280 			EC_POINT_free(pub_key);
281 			ECerror(ERR_R_EC_LIB);
282 			goto ecliberr;
283 		}
284 		priv_key = EC_KEY_get0_private_key(eckey);
285 		if (!EC_POINT_mul(group, pub_key, priv_key, NULL, NULL, NULL)) {
286 			EC_POINT_free(pub_key);
287 			ECerror(ERR_R_EC_LIB);
288 			goto ecliberr;
289 		}
290 		if (EC_KEY_set_public_key(eckey, pub_key) == 0) {
291 			EC_POINT_free(pub_key);
292 			ECerror(ERR_R_EC_LIB);
293 			goto ecliberr;
294 		}
295 		EC_POINT_free(pub_key);
296 	}
297 	EVP_PKEY_assign_EC_KEY(pkey, eckey);
298 	return 1;
299 
300  ecliberr:
301 	ECerror(ERR_R_EC_LIB);
302  ecerr:
303 	if (eckey)
304 		EC_KEY_free(eckey);
305 	return 0;
306 }
307 
308 static int
309 eckey_priv_encode(PKCS8_PRIV_KEY_INFO * p8, const EVP_PKEY * pkey)
310 {
311 	EC_KEY *ec_key;
312 	unsigned char *ep, *p;
313 	int eplen, ptype;
314 	void *pval;
315 	unsigned int tmp_flags, old_flags;
316 
317 	ec_key = pkey->pkey.ec;
318 
319 	if (!eckey_param2type(&ptype, &pval, ec_key)) {
320 		ECerror(EC_R_DECODE_ERROR);
321 		return 0;
322 	}
323 	/* set the private key */
324 
325 	/*
326 	 * do not include the parameters in the SEC1 private key see PKCS#11
327 	 * 12.11
328 	 */
329 	old_flags = EC_KEY_get_enc_flags(ec_key);
330 	tmp_flags = old_flags | EC_PKEY_NO_PARAMETERS;
331 	EC_KEY_set_enc_flags(ec_key, tmp_flags);
332 	eplen = i2d_ECPrivateKey(ec_key, NULL);
333 	if (!eplen) {
334 		EC_KEY_set_enc_flags(ec_key, old_flags);
335 		ECerror(ERR_R_EC_LIB);
336 		return 0;
337 	}
338 	ep = malloc(eplen);
339 	if (!ep) {
340 		EC_KEY_set_enc_flags(ec_key, old_flags);
341 		ECerror(ERR_R_MALLOC_FAILURE);
342 		return 0;
343 	}
344 	p = ep;
345 	if (!i2d_ECPrivateKey(ec_key, &p)) {
346 		EC_KEY_set_enc_flags(ec_key, old_flags);
347 		free(ep);
348 		ECerror(ERR_R_EC_LIB);
349 		return 0;
350 	}
351 	/* restore old encoding flags */
352 	EC_KEY_set_enc_flags(ec_key, old_flags);
353 
354 	if (!PKCS8_pkey_set0(p8, OBJ_nid2obj(NID_X9_62_id_ecPublicKey), 0,
355 		ptype, pval, ep, eplen))
356 		return 0;
357 
358 	return 1;
359 }
360 
361 static int
362 int_ec_size(const EVP_PKEY * pkey)
363 {
364 	return ECDSA_size(pkey->pkey.ec);
365 }
366 
367 static int
368 ec_bits(const EVP_PKEY * pkey)
369 {
370 	BIGNUM *order = BN_new();
371 	const EC_GROUP *group;
372 	int ret;
373 
374 	if (!order) {
375 		ERR_clear_error();
376 		return 0;
377 	}
378 	group = EC_KEY_get0_group(pkey->pkey.ec);
379 	if (!EC_GROUP_get_order(group, order, NULL)) {
380 		BN_free(order);
381 		ERR_clear_error();
382 		return 0;
383 	}
384 	ret = BN_num_bits(order);
385 	BN_free(order);
386 	return ret;
387 }
388 
389 static int
390 ec_missing_parameters(const EVP_PKEY * pkey)
391 {
392 	if (EC_KEY_get0_group(pkey->pkey.ec) == NULL)
393 		return 1;
394 	return 0;
395 }
396 
397 static int
398 ec_copy_parameters(EVP_PKEY * to, const EVP_PKEY * from)
399 {
400 	return EC_KEY_set_group(to->pkey.ec, EC_KEY_get0_group(from->pkey.ec));
401 }
402 
403 static int
404 ec_cmp_parameters(const EVP_PKEY * a, const EVP_PKEY * b)
405 {
406 	const EC_GROUP *group_a = EC_KEY_get0_group(a->pkey.ec), *group_b = EC_KEY_get0_group(b->pkey.ec);
407 	if (EC_GROUP_cmp(group_a, group_b, NULL))
408 		return 0;
409 	else
410 		return 1;
411 }
412 
413 static void
414 int_ec_free(EVP_PKEY * pkey)
415 {
416 	EC_KEY_free(pkey->pkey.ec);
417 }
418 
419 static int
420 do_EC_KEY_print(BIO * bp, const EC_KEY * x, int off, int ktype)
421 {
422 	unsigned char *buffer = NULL;
423 	const char *ecstr;
424 	size_t buf_len = 0, i;
425 	int ret = 0, reason = ERR_R_BIO_LIB;
426 	BIGNUM *pub_key = NULL, *order = NULL;
427 	BN_CTX *ctx = NULL;
428 	const EC_GROUP *group;
429 	const EC_POINT *public_key;
430 	const BIGNUM *priv_key;
431 
432 	if (x == NULL || (group = EC_KEY_get0_group(x)) == NULL) {
433 		reason = ERR_R_PASSED_NULL_PARAMETER;
434 		goto err;
435 	}
436 	ctx = BN_CTX_new();
437 	if (ctx == NULL) {
438 		reason = ERR_R_MALLOC_FAILURE;
439 		goto err;
440 	}
441 	if (ktype > 0) {
442 		public_key = EC_KEY_get0_public_key(x);
443 		if (public_key != NULL) {
444 			if ((pub_key = EC_POINT_point2bn(group, public_key,
445 			    EC_KEY_get_conv_form(x), NULL, ctx)) == NULL) {
446 				reason = ERR_R_EC_LIB;
447 				goto err;
448 			}
449 			if (pub_key)
450 				buf_len = (size_t) BN_num_bytes(pub_key);
451 		}
452 	}
453 	if (ktype == 2) {
454 		priv_key = EC_KEY_get0_private_key(x);
455 		if (priv_key && (i = (size_t) BN_num_bytes(priv_key)) > buf_len)
456 			buf_len = i;
457 	} else
458 		priv_key = NULL;
459 
460 	if (ktype > 0) {
461 		buf_len += 10;
462 		if ((buffer = malloc(buf_len)) == NULL) {
463 			reason = ERR_R_MALLOC_FAILURE;
464 			goto err;
465 		}
466 	}
467 	if (ktype == 2)
468 		ecstr = "Private-Key";
469 	else if (ktype == 1)
470 		ecstr = "Public-Key";
471 	else
472 		ecstr = "ECDSA-Parameters";
473 
474 	if (!BIO_indent(bp, off, 128))
475 		goto err;
476 	if ((order = BN_new()) == NULL)
477 		goto err;
478 	if (!EC_GROUP_get_order(group, order, NULL))
479 		goto err;
480 	if (BIO_printf(bp, "%s: (%d bit)\n", ecstr,
481 		BN_num_bits(order)) <= 0)
482 		goto err;
483 
484 	if ((priv_key != NULL) && !ASN1_bn_print(bp, "priv:", priv_key,
485 		buffer, off))
486 		goto err;
487 	if ((pub_key != NULL) && !ASN1_bn_print(bp, "pub: ", pub_key,
488 		buffer, off))
489 		goto err;
490 	if (!ECPKParameters_print(bp, group, off))
491 		goto err;
492 	ret = 1;
493  err:
494 	if (!ret)
495 		ECerror(reason);
496 	BN_free(pub_key);
497 	BN_free(order);
498 	BN_CTX_free(ctx);
499 	free(buffer);
500 	return (ret);
501 }
502 
503 static int
504 eckey_param_decode(EVP_PKEY * pkey,
505     const unsigned char **pder, int derlen)
506 {
507 	EC_KEY *eckey;
508 	if (!(eckey = d2i_ECParameters(NULL, pder, derlen))) {
509 		ECerror(ERR_R_EC_LIB);
510 		return 0;
511 	}
512 	EVP_PKEY_assign_EC_KEY(pkey, eckey);
513 	return 1;
514 }
515 
516 static int
517 eckey_param_encode(const EVP_PKEY * pkey, unsigned char **pder)
518 {
519 	return i2d_ECParameters(pkey->pkey.ec, pder);
520 }
521 
522 static int
523 eckey_param_print(BIO * bp, const EVP_PKEY * pkey, int indent,
524     ASN1_PCTX * ctx)
525 {
526 	return do_EC_KEY_print(bp, pkey->pkey.ec, indent, 0);
527 }
528 
529 static int
530 eckey_pub_print(BIO * bp, const EVP_PKEY * pkey, int indent,
531     ASN1_PCTX * ctx)
532 {
533 	return do_EC_KEY_print(bp, pkey->pkey.ec, indent, 1);
534 }
535 
536 
537 static int
538 eckey_priv_print(BIO * bp, const EVP_PKEY * pkey, int indent,
539     ASN1_PCTX * ctx)
540 {
541 	return do_EC_KEY_print(bp, pkey->pkey.ec, indent, 2);
542 }
543 
544 static int
545 old_ec_priv_decode(EVP_PKEY * pkey,
546     const unsigned char **pder, int derlen)
547 {
548 	EC_KEY *ec;
549 	if (!(ec = d2i_ECPrivateKey(NULL, pder, derlen))) {
550 		ECerror(EC_R_DECODE_ERROR);
551 		return 0;
552 	}
553 	EVP_PKEY_assign_EC_KEY(pkey, ec);
554 	return 1;
555 }
556 
557 static int
558 old_ec_priv_encode(const EVP_PKEY * pkey, unsigned char **pder)
559 {
560 	return i2d_ECPrivateKey(pkey->pkey.ec, pder);
561 }
562 
563 static int
564 ec_pkey_ctrl(EVP_PKEY * pkey, int op, long arg1, void *arg2)
565 {
566 	switch (op) {
567 	case ASN1_PKEY_CTRL_PKCS7_SIGN:
568 		if (arg1 == 0) {
569 			int snid, hnid;
570 			X509_ALGOR *alg1, *alg2;
571 			PKCS7_SIGNER_INFO_get0_algs(arg2, NULL, &alg1, &alg2);
572 			if (alg1 == NULL || alg1->algorithm == NULL)
573 				return -1;
574 			hnid = OBJ_obj2nid(alg1->algorithm);
575 			if (hnid == NID_undef)
576 				return -1;
577 			if (!OBJ_find_sigid_by_algs(&snid, hnid, EVP_PKEY_id(pkey)))
578 				return -1;
579 			X509_ALGOR_set0(alg2, OBJ_nid2obj(snid), V_ASN1_UNDEF, 0);
580 		}
581 		return 1;
582 
583 #ifndef OPENSSL_NO_CMS
584 	case ASN1_PKEY_CTRL_CMS_SIGN:
585 		if (arg1 == 0) {
586 			X509_ALGOR *alg1, *alg2;
587 			int snid, hnid;
588 
589 			CMS_SignerInfo_get0_algs(arg2, NULL, NULL, &alg1, &alg2);
590 			if (alg1 == NULL || alg1->algorithm == NULL)
591 				return -1;
592 			hnid = OBJ_obj2nid(alg1->algorithm);
593 			if (hnid == NID_undef)
594 				return -1;
595 			if (!OBJ_find_sigid_by_algs(&snid, hnid, EVP_PKEY_id(pkey)))
596 				return -1;
597 			X509_ALGOR_set0(alg2, OBJ_nid2obj(snid), V_ASN1_UNDEF, 0);
598 		}
599 		return 1;
600 
601 	case ASN1_PKEY_CTRL_CMS_ENVELOPE:
602 		if (arg1 == 0)
603 			return ecdh_cms_encrypt(arg2);
604 		else if (arg1 == 1)
605 			return ecdh_cms_decrypt(arg2);
606 		return -2;
607 
608 	case ASN1_PKEY_CTRL_CMS_RI_TYPE:
609 		*(int *)arg2 = CMS_RECIPINFO_AGREE;
610 		return 1;
611 #endif
612 
613 	case ASN1_PKEY_CTRL_DEFAULT_MD_NID:
614 		*(int *) arg2 = NID_sha1;
615 		return 2;
616 
617 	default:
618 		return -2;
619 
620 	}
621 
622 }
623 
624 static int
625 ec_pkey_check(const EVP_PKEY *pkey)
626 {
627 	EC_KEY *eckey = pkey->pkey.ec;
628 
629 	if (eckey->priv_key == NULL) {
630 		ECerror(EC_R_MISSING_PRIVATE_KEY);
631 		return 0;
632 	}
633 
634 	return EC_KEY_check_key(eckey);
635 }
636 
637 static int
638 ec_pkey_public_check(const EVP_PKEY *pkey)
639 {
640 	EC_KEY *eckey = pkey->pkey.ec;
641 
642 	/* This also checks the private key, but oh, well... */
643 	return EC_KEY_check_key(eckey);
644 }
645 
646 static int
647 ec_pkey_param_check(const EVP_PKEY *pkey)
648 {
649 	EC_KEY *eckey = pkey->pkey.ec;
650 
651 	if (eckey->group == NULL) {
652 		ECerror(EC_R_MISSING_PARAMETERS);
653 		return 0;
654 	}
655 
656 	return EC_GROUP_check(eckey->group, NULL);
657 }
658 
659 #ifndef OPENSSL_NO_CMS
660 
661 static int
662 ecdh_cms_set_peerkey(EVP_PKEY_CTX *pctx, X509_ALGOR *alg,
663     ASN1_BIT_STRING *pubkey)
664 {
665 	const ASN1_OBJECT *aoid;
666 	int atype;
667 	const void *aval;
668 	int rv = 0;
669 	EVP_PKEY *pkpeer = NULL;
670 	EC_KEY *ecpeer = NULL;
671 	const unsigned char *p;
672 	int plen;
673 
674 	X509_ALGOR_get0(&aoid, &atype, &aval, alg);
675 	if (OBJ_obj2nid(aoid) != NID_X9_62_id_ecPublicKey)
676 		goto err;
677 
678 	/* If absent parameters get group from main key */
679 	if (atype == V_ASN1_UNDEF || atype == V_ASN1_NULL) {
680 		const EC_GROUP *grp;
681 		EVP_PKEY *pk;
682 
683 		pk = EVP_PKEY_CTX_get0_pkey(pctx);
684 		if (!pk)
685 			goto err;
686 		grp = EC_KEY_get0_group(pk->pkey.ec);
687 		ecpeer = EC_KEY_new();
688 		if (ecpeer == NULL)
689 			goto err;
690 		if (!EC_KEY_set_group(ecpeer, grp))
691 			goto err;
692 	} else {
693 		ecpeer = eckey_type2param(atype, aval);
694 		if (!ecpeer)
695 			goto err;
696 	}
697 
698 	/* We have parameters now set public key */
699 	plen = ASN1_STRING_length(pubkey);
700 	p = ASN1_STRING_get0_data(pubkey);
701 	if (!p || !plen)
702 		goto err;
703 	if (!o2i_ECPublicKey(&ecpeer, &p, plen))
704 		goto err;
705 	pkpeer = EVP_PKEY_new();
706 	if (pkpeer == NULL)
707 		goto err;
708 	EVP_PKEY_set1_EC_KEY(pkpeer, ecpeer);
709 	if (EVP_PKEY_derive_set_peer(pctx, pkpeer) > 0)
710 		rv = 1;
711  err:
712 	EC_KEY_free(ecpeer);
713 	EVP_PKEY_free(pkpeer);
714 	return rv;
715 }
716 
717 /* Set KDF parameters based on KDF NID */
718 static int
719 ecdh_cms_set_kdf_param(EVP_PKEY_CTX *pctx, int eckdf_nid)
720 {
721 	int kdf_nid, kdfmd_nid, cofactor;
722 	const EVP_MD *kdf_md;
723 
724 	if (eckdf_nid == NID_undef)
725 		return 0;
726 
727 	/* Lookup KDF type, cofactor mode and digest */
728 	if (!OBJ_find_sigid_algs(eckdf_nid, &kdfmd_nid, &kdf_nid))
729 		return 0;
730 
731 	if (kdf_nid == NID_dh_std_kdf)
732 		cofactor = 0;
733 	else if (kdf_nid == NID_dh_cofactor_kdf)
734 		cofactor = 1;
735 	else
736 		return 0;
737 
738 	if (EVP_PKEY_CTX_set_ecdh_cofactor_mode(pctx, cofactor) <= 0)
739 		return 0;
740 
741 	if (EVP_PKEY_CTX_set_ecdh_kdf_type(pctx, EVP_PKEY_ECDH_KDF_X9_63) <= 0)
742 		return 0;
743 
744 	kdf_md = EVP_get_digestbynid(kdfmd_nid);
745 	if (!kdf_md)
746 		return 0;
747 
748 	if (EVP_PKEY_CTX_set_ecdh_kdf_md(pctx, kdf_md) <= 0)
749 		return 0;
750 
751 	return 1;
752 }
753 
754 static int
755 ecdh_cms_set_shared_info(EVP_PKEY_CTX *pctx, CMS_RecipientInfo *ri)
756 {
757 	X509_ALGOR *alg, *kekalg = NULL;
758 	ASN1_OCTET_STRING *ukm;
759 	const unsigned char *p;
760 	unsigned char *der = NULL;
761 	int plen, keylen;
762 	const EVP_CIPHER *kekcipher;
763 	EVP_CIPHER_CTX *kekctx;
764 	int rv = 0;
765 
766 	if (!CMS_RecipientInfo_kari_get0_alg(ri, &alg, &ukm))
767 		return 0;
768 
769 	if (!ecdh_cms_set_kdf_param(pctx, OBJ_obj2nid(alg->algorithm))) {
770 		ECerror(EC_R_KDF_PARAMETER_ERROR);
771 		return 0;
772 	}
773 
774 	if (alg->parameter->type != V_ASN1_SEQUENCE)
775 		return 0;
776 
777 	p = alg->parameter->value.sequence->data;
778 	plen = alg->parameter->value.sequence->length;
779 	kekalg = d2i_X509_ALGOR(NULL, &p, plen);
780 	if (!kekalg)
781 		goto err;
782 	kekctx = CMS_RecipientInfo_kari_get0_ctx(ri);
783 	if (!kekctx)
784 		goto err;
785 	kekcipher = EVP_get_cipherbyobj(kekalg->algorithm);
786 	if (!kekcipher || EVP_CIPHER_mode(kekcipher) != EVP_CIPH_WRAP_MODE)
787 		goto err;
788 	if (!EVP_EncryptInit_ex(kekctx, kekcipher, NULL, NULL, NULL))
789 		goto err;
790 	if (EVP_CIPHER_asn1_to_param(kekctx, kekalg->parameter) <= 0)
791 		goto err;
792 
793 	keylen = EVP_CIPHER_CTX_key_length(kekctx);
794 	if (EVP_PKEY_CTX_set_ecdh_kdf_outlen(pctx, keylen) <= 0)
795 		goto err;
796 
797 	plen = CMS_SharedInfo_encode(&der, kekalg, ukm, keylen);
798 	if (!plen)
799 		goto err;
800 
801 	if (EVP_PKEY_CTX_set0_ecdh_kdf_ukm(pctx, der, plen) <= 0)
802 		goto err;
803 	der = NULL;
804 
805 	rv = 1;
806  err:
807 	X509_ALGOR_free(kekalg);
808 	free(der);
809 	return rv;
810 }
811 
812 static int
813 ecdh_cms_decrypt(CMS_RecipientInfo *ri)
814 {
815 	EVP_PKEY_CTX *pctx;
816 
817 	pctx = CMS_RecipientInfo_get0_pkey_ctx(ri);
818 	if (!pctx)
819 		return 0;
820 
821 	/* See if we need to set peer key */
822 	if (!EVP_PKEY_CTX_get0_peerkey(pctx)) {
823 		X509_ALGOR *alg;
824 		ASN1_BIT_STRING *pubkey;
825 
826 		if (!CMS_RecipientInfo_kari_get0_orig_id(ri, &alg, &pubkey,
827 		    NULL, NULL, NULL))
828 			return 0;
829 		if (!alg || !pubkey)
830 			return 0;
831 		if (!ecdh_cms_set_peerkey(pctx, alg, pubkey)) {
832 			ECerror(EC_R_PEER_KEY_ERROR);
833 			return 0;
834 		}
835 	}
836 
837 	/* Set ECDH derivation parameters and initialise unwrap context */
838 	if (!ecdh_cms_set_shared_info(pctx, ri)) {
839 		ECerror(EC_R_SHARED_INFO_ERROR);
840 		return 0;
841 	}
842 
843 	return 1;
844 }
845 
846 static int
847 ecdh_cms_encrypt(CMS_RecipientInfo *ri)
848 {
849 	EVP_PKEY_CTX *pctx;
850 	EVP_PKEY *pkey;
851 	EVP_CIPHER_CTX *ctx;
852 	int keylen;
853 	X509_ALGOR *talg, *wrap_alg = NULL;
854 	const ASN1_OBJECT *aoid;
855 	ASN1_BIT_STRING *pubkey;
856 	ASN1_STRING *wrap_str;
857 	ASN1_OCTET_STRING *ukm;
858 	unsigned char *penc = NULL;
859 	int penclen;
860 	int ecdh_nid, kdf_type, kdf_nid, wrap_nid;
861 	const EVP_MD *kdf_md;
862 	int rv = 0;
863 
864 	pctx = CMS_RecipientInfo_get0_pkey_ctx(ri);
865 	if (!pctx)
866 		return 0;
867 	/* Get ephemeral key */
868 	pkey = EVP_PKEY_CTX_get0_pkey(pctx);
869 	if (!CMS_RecipientInfo_kari_get0_orig_id(ri, &talg, &pubkey,
870 	    NULL, NULL, NULL))
871 		goto err;
872 	X509_ALGOR_get0(&aoid, NULL, NULL, talg);
873 
874 	/* Is everything uninitialised? */
875 	if (aoid == OBJ_nid2obj(NID_undef)) {
876 		EC_KEY *eckey = pkey->pkey.ec;
877 		unsigned char *p;
878 
879 		/* Set the key */
880 		penclen = i2o_ECPublicKey(eckey, NULL);
881 		if (penclen <= 0)
882 			goto err;
883 		penc = malloc(penclen);
884 		if (penc == NULL)
885 			goto err;
886 		p = penc;
887 		penclen = i2o_ECPublicKey(eckey, &p);
888 		if (penclen <= 0)
889 			goto err;
890 		ASN1_STRING_set0(pubkey, penc, penclen);
891 		pubkey->flags &= ~(ASN1_STRING_FLAG_BITS_LEFT | 0x07);
892 		pubkey->flags |= ASN1_STRING_FLAG_BITS_LEFT;
893 		penc = NULL;
894 
895 		X509_ALGOR_set0(talg, OBJ_nid2obj(NID_X9_62_id_ecPublicKey),
896 		    V_ASN1_UNDEF, NULL);
897 	}
898 
899 	/* See if custom parameters set */
900 	kdf_type = EVP_PKEY_CTX_get_ecdh_kdf_type(pctx);
901 	if (kdf_type <= 0)
902 		goto err;
903 	if (!EVP_PKEY_CTX_get_ecdh_kdf_md(pctx, &kdf_md))
904 		goto err;
905 	ecdh_nid = EVP_PKEY_CTX_get_ecdh_cofactor_mode(pctx);
906 	if (ecdh_nid < 0)
907 		goto err;
908 	else if (ecdh_nid == 0)
909 		ecdh_nid = NID_dh_std_kdf;
910 	else if (ecdh_nid == 1)
911 		ecdh_nid = NID_dh_cofactor_kdf;
912 
913 	if (kdf_type == EVP_PKEY_ECDH_KDF_NONE) {
914 		kdf_type = EVP_PKEY_ECDH_KDF_X9_63;
915 		if (EVP_PKEY_CTX_set_ecdh_kdf_type(pctx, kdf_type) <= 0)
916 			goto err;
917 	} else {
918 		/* Unknown KDF */
919 		goto err;
920 	}
921 	if (kdf_md == NULL) {
922 		/* Fixme later for better MD */
923 		kdf_md = EVP_sha1();
924 		if (EVP_PKEY_CTX_set_ecdh_kdf_md(pctx, kdf_md) <= 0)
925 			goto err;
926 	}
927 
928 	if (!CMS_RecipientInfo_kari_get0_alg(ri, &talg, &ukm))
929 		goto err;
930 
931 	/* Lookup NID for KDF+cofactor+digest */
932 	if (!OBJ_find_sigid_by_algs(&kdf_nid, EVP_MD_type(kdf_md), ecdh_nid))
933 		goto err;
934 
935 	/* Get wrap NID */
936 	ctx = CMS_RecipientInfo_kari_get0_ctx(ri);
937 	wrap_nid = EVP_CIPHER_CTX_type(ctx);
938 	keylen = EVP_CIPHER_CTX_key_length(ctx);
939 
940 	/* Package wrap algorithm in an AlgorithmIdentifier */
941 
942 	wrap_alg = X509_ALGOR_new();
943 	if (wrap_alg == NULL)
944 		goto err;
945 	wrap_alg->algorithm = OBJ_nid2obj(wrap_nid);
946 	wrap_alg->parameter = ASN1_TYPE_new();
947 	if (wrap_alg->parameter == NULL)
948 		goto err;
949 	if (EVP_CIPHER_param_to_asn1(ctx, wrap_alg->parameter) <= 0)
950 		goto err;
951 	if (ASN1_TYPE_get(wrap_alg->parameter) == NID_undef) {
952 		ASN1_TYPE_free(wrap_alg->parameter);
953 		wrap_alg->parameter = NULL;
954 	}
955 
956 	if (EVP_PKEY_CTX_set_ecdh_kdf_outlen(pctx, keylen) <= 0)
957 		goto err;
958 
959 	penclen = CMS_SharedInfo_encode(&penc, wrap_alg, ukm, keylen);
960 	if (!penclen)
961 		goto err;
962 
963 	if (EVP_PKEY_CTX_set0_ecdh_kdf_ukm(pctx, penc, penclen) <= 0)
964 		goto err;
965 	penc = NULL;
966 
967 	/*
968 	 * Now need to wrap encoding of wrap AlgorithmIdentifier into parameter
969 	 * of another AlgorithmIdentifier.
970 	 */
971 	penclen = i2d_X509_ALGOR(wrap_alg, &penc);
972 	if (!penc || !penclen)
973 		goto err;
974 	wrap_str = ASN1_STRING_new();
975 	if (wrap_str == NULL)
976 		goto err;
977 	ASN1_STRING_set0(wrap_str, penc, penclen);
978 	penc = NULL;
979 	X509_ALGOR_set0(talg, OBJ_nid2obj(kdf_nid), V_ASN1_SEQUENCE, wrap_str);
980 
981 	rv = 1;
982 
983  err:
984 	free(penc);
985 	X509_ALGOR_free(wrap_alg);
986 	return rv;
987 }
988 
989 #endif
990 
991 const EVP_PKEY_ASN1_METHOD eckey_asn1_meth = {
992 	.pkey_id = EVP_PKEY_EC,
993 	.pkey_base_id = EVP_PKEY_EC,
994 
995 	.pem_str = "EC",
996 	.info = "OpenSSL EC algorithm",
997 
998 	.pub_decode = eckey_pub_decode,
999 	.pub_encode = eckey_pub_encode,
1000 	.pub_cmp = eckey_pub_cmp,
1001 	.pub_print = eckey_pub_print,
1002 
1003 	.priv_decode = eckey_priv_decode,
1004 	.priv_encode = eckey_priv_encode,
1005 	.priv_print = eckey_priv_print,
1006 
1007 	.pkey_size = int_ec_size,
1008 	.pkey_bits = ec_bits,
1009 
1010 	.param_decode = eckey_param_decode,
1011 	.param_encode = eckey_param_encode,
1012 	.param_missing = ec_missing_parameters,
1013 	.param_copy = ec_copy_parameters,
1014 	.param_cmp = ec_cmp_parameters,
1015 	.param_print = eckey_param_print,
1016 
1017 	.pkey_free = int_ec_free,
1018 	.pkey_ctrl = ec_pkey_ctrl,
1019 	.old_priv_decode = old_ec_priv_decode,
1020 	.old_priv_encode = old_ec_priv_encode,
1021 
1022 	.pkey_check = ec_pkey_check,
1023 	.pkey_public_check = ec_pkey_public_check,
1024 	.pkey_param_check = ec_pkey_param_check,
1025 };
1026