ecx: update to structure based atomics
[openssl.git] / crypto / ec / ec_lib.c
1 /*
2  * Copyright 2001-2022 The OpenSSL Project Authors. All Rights Reserved.
3  * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
4  *
5  * Licensed under the Apache License 2.0 (the "License").  You may not use
6  * this file except in compliance with the License.  You can obtain a copy
7  * in the file LICENSE in the source distribution or at
8  * https://www.openssl.org/source/license.html
9  */
10
11 /*
12  * EC_GROUP low level APIs are deprecated for public use, but still ok for
13  * internal use.
14  */
15 #include "internal/deprecated.h"
16
17 #include <string.h>
18 #include <openssl/params.h>
19 #include <openssl/core_names.h>
20 #include <openssl/err.h>
21 #include <openssl/opensslv.h>
22 #include <openssl/param_build.h>
23 #include "crypto/ec.h"
24 #include "internal/nelem.h"
25 #include "ec_local.h"
26
27 /* functions for EC_GROUP objects */
28
29 EC_GROUP *ossl_ec_group_new_ex(OSSL_LIB_CTX *libctx, const char *propq,
30                                const EC_METHOD *meth)
31 {
32     EC_GROUP *ret;
33
34     if (meth == NULL) {
35         ERR_raise(ERR_LIB_EC, EC_R_SLOT_FULL);
36         return NULL;
37     }
38     if (meth->group_init == 0) {
39         ERR_raise(ERR_LIB_EC, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
40         return NULL;
41     }
42
43     ret = OPENSSL_zalloc(sizeof(*ret));
44     if (ret == NULL)
45         return NULL;
46
47     ret->libctx = libctx;
48     if (propq != NULL) {
49         ret->propq = OPENSSL_strdup(propq);
50         if (ret->propq == NULL)
51             goto err;
52     }
53     ret->meth = meth;
54     if ((ret->meth->flags & EC_FLAGS_CUSTOM_CURVE) == 0) {
55         ret->order = BN_new();
56         if (ret->order == NULL)
57             goto err;
58         ret->cofactor = BN_new();
59         if (ret->cofactor == NULL)
60             goto err;
61     }
62     ret->asn1_flag = OPENSSL_EC_EXPLICIT_CURVE;
63     ret->asn1_form = POINT_CONVERSION_UNCOMPRESSED;
64     if (!meth->group_init(ret))
65         goto err;
66     return ret;
67
68  err:
69     BN_free(ret->order);
70     BN_free(ret->cofactor);
71     OPENSSL_free(ret->propq);
72     OPENSSL_free(ret);
73     return NULL;
74 }
75
76 #ifndef OPENSSL_NO_DEPRECATED_3_0
77 # ifndef FIPS_MODULE
78 EC_GROUP *EC_GROUP_new(const EC_METHOD *meth)
79 {
80     return ossl_ec_group_new_ex(NULL, NULL, meth);
81 }
82 # endif
83 #endif
84
85 void EC_pre_comp_free(EC_GROUP *group)
86 {
87     switch (group->pre_comp_type) {
88     case PCT_none:
89         break;
90     case PCT_nistz256:
91 #ifdef ECP_NISTZ256_ASM
92         EC_nistz256_pre_comp_free(group->pre_comp.nistz256);
93 #endif
94         break;
95 #ifndef OPENSSL_NO_EC_NISTP_64_GCC_128
96     case PCT_nistp224:
97         EC_nistp224_pre_comp_free(group->pre_comp.nistp224);
98         break;
99     case PCT_nistp256:
100         EC_nistp256_pre_comp_free(group->pre_comp.nistp256);
101         break;
102     case PCT_nistp521:
103         EC_nistp521_pre_comp_free(group->pre_comp.nistp521);
104         break;
105 #else
106     case PCT_nistp224:
107     case PCT_nistp256:
108     case PCT_nistp521:
109         break;
110 #endif
111     case PCT_ec:
112         EC_ec_pre_comp_free(group->pre_comp.ec);
113         break;
114     }
115     group->pre_comp.ec = NULL;
116 }
117
118 void EC_GROUP_free(EC_GROUP *group)
119 {
120     if (!group)
121         return;
122
123     if (group->meth->group_finish != 0)
124         group->meth->group_finish(group);
125
126     EC_pre_comp_free(group);
127     BN_MONT_CTX_free(group->mont_data);
128     EC_POINT_free(group->generator);
129     BN_free(group->order);
130     BN_free(group->cofactor);
131     OPENSSL_free(group->seed);
132     OPENSSL_free(group->propq);
133     OPENSSL_free(group);
134 }
135
136 #ifndef OPENSSL_NO_DEPRECATED_3_0
137 void EC_GROUP_clear_free(EC_GROUP *group)
138 {
139     if (!group)
140         return;
141
142     if (group->meth->group_clear_finish != 0)
143         group->meth->group_clear_finish(group);
144     else if (group->meth->group_finish != 0)
145         group->meth->group_finish(group);
146
147     EC_pre_comp_free(group);
148     BN_MONT_CTX_free(group->mont_data);
149     EC_POINT_clear_free(group->generator);
150     BN_clear_free(group->order);
151     BN_clear_free(group->cofactor);
152     OPENSSL_clear_free(group->seed, group->seed_len);
153     OPENSSL_clear_free(group, sizeof(*group));
154 }
155 #endif
156
157 int EC_GROUP_copy(EC_GROUP *dest, const EC_GROUP *src)
158 {
159     if (dest->meth->group_copy == 0) {
160         ERR_raise(ERR_LIB_EC, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
161         return 0;
162     }
163     if (dest->meth != src->meth) {
164         ERR_raise(ERR_LIB_EC, EC_R_INCOMPATIBLE_OBJECTS);
165         return 0;
166     }
167     if (dest == src)
168         return 1;
169
170     dest->libctx = src->libctx;
171     dest->curve_name = src->curve_name;
172
173     /* Copy precomputed */
174     dest->pre_comp_type = src->pre_comp_type;
175     switch (src->pre_comp_type) {
176     case PCT_none:
177         dest->pre_comp.ec = NULL;
178         break;
179     case PCT_nistz256:
180 #ifdef ECP_NISTZ256_ASM
181         dest->pre_comp.nistz256 = EC_nistz256_pre_comp_dup(src->pre_comp.nistz256);
182 #endif
183         break;
184 #ifndef OPENSSL_NO_EC_NISTP_64_GCC_128
185     case PCT_nistp224:
186         dest->pre_comp.nistp224 = EC_nistp224_pre_comp_dup(src->pre_comp.nistp224);
187         break;
188     case PCT_nistp256:
189         dest->pre_comp.nistp256 = EC_nistp256_pre_comp_dup(src->pre_comp.nistp256);
190         break;
191     case PCT_nistp521:
192         dest->pre_comp.nistp521 = EC_nistp521_pre_comp_dup(src->pre_comp.nistp521);
193         break;
194 #else
195     case PCT_nistp224:
196     case PCT_nistp256:
197     case PCT_nistp521:
198         break;
199 #endif
200     case PCT_ec:
201         dest->pre_comp.ec = EC_ec_pre_comp_dup(src->pre_comp.ec);
202         break;
203     }
204
205     if (src->mont_data != NULL) {
206         if (dest->mont_data == NULL) {
207             dest->mont_data = BN_MONT_CTX_new();
208             if (dest->mont_data == NULL)
209                 return 0;
210         }
211         if (!BN_MONT_CTX_copy(dest->mont_data, src->mont_data))
212             return 0;
213     } else {
214         /* src->generator == NULL */
215         BN_MONT_CTX_free(dest->mont_data);
216         dest->mont_data = NULL;
217     }
218
219     if (src->generator != NULL) {
220         if (dest->generator == NULL) {
221             dest->generator = EC_POINT_new(dest);
222             if (dest->generator == NULL)
223                 return 0;
224         }
225         if (!EC_POINT_copy(dest->generator, src->generator))
226             return 0;
227     } else {
228         /* src->generator == NULL */
229         EC_POINT_clear_free(dest->generator);
230         dest->generator = NULL;
231     }
232
233     if ((src->meth->flags & EC_FLAGS_CUSTOM_CURVE) == 0) {
234         if (!BN_copy(dest->order, src->order))
235             return 0;
236         if (!BN_copy(dest->cofactor, src->cofactor))
237             return 0;
238     }
239
240     dest->asn1_flag = src->asn1_flag;
241     dest->asn1_form = src->asn1_form;
242     dest->decoded_from_explicit_params = src->decoded_from_explicit_params;
243
244     if (src->seed) {
245         OPENSSL_free(dest->seed);
246         if ((dest->seed = OPENSSL_malloc(src->seed_len)) == NULL)
247             return 0;
248         if (!memcpy(dest->seed, src->seed, src->seed_len))
249             return 0;
250         dest->seed_len = src->seed_len;
251     } else {
252         OPENSSL_free(dest->seed);
253         dest->seed = NULL;
254         dest->seed_len = 0;
255     }
256
257     return dest->meth->group_copy(dest, src);
258 }
259
260 EC_GROUP *EC_GROUP_dup(const EC_GROUP *a)
261 {
262     EC_GROUP *t = NULL;
263     int ok = 0;
264
265     if (a == NULL)
266         return NULL;
267
268     if ((t = ossl_ec_group_new_ex(a->libctx, a->propq, a->meth)) == NULL)
269         return NULL;
270     if (!EC_GROUP_copy(t, a))
271         goto err;
272
273     ok = 1;
274
275  err:
276     if (!ok) {
277         EC_GROUP_free(t);
278         return NULL;
279     }
280         return t;
281 }
282
283 #ifndef OPENSSL_NO_DEPRECATED_3_0
284 const EC_METHOD *EC_GROUP_method_of(const EC_GROUP *group)
285 {
286     return group->meth;
287 }
288
289 int EC_METHOD_get_field_type(const EC_METHOD *meth)
290 {
291     return meth->field_type;
292 }
293 #endif
294
295 static int ec_precompute_mont_data(EC_GROUP *);
296
297 /*-
298  * Try computing cofactor from the generator order (n) and field cardinality (q).
299  * This works for all curves of cryptographic interest.
300  *
301  * Hasse thm: q + 1 - 2*sqrt(q) <= n*h <= q + 1 + 2*sqrt(q)
302  * h_min = (q + 1 - 2*sqrt(q))/n
303  * h_max = (q + 1 + 2*sqrt(q))/n
304  * h_max - h_min = 4*sqrt(q)/n
305  * So if n > 4*sqrt(q) holds, there is only one possible value for h:
306  * h = \lfloor (h_min + h_max)/2 \rceil = \lfloor (q + 1)/n \rceil
307  *
308  * Otherwise, zero cofactor and return success.
309  */
310 static int ec_guess_cofactor(EC_GROUP *group) {
311     int ret = 0;
312     BN_CTX *ctx = NULL;
313     BIGNUM *q = NULL;
314
315     /*-
316      * If the cofactor is too large, we cannot guess it.
317      * The RHS of below is a strict overestimate of lg(4 * sqrt(q))
318      */
319     if (BN_num_bits(group->order) <= (BN_num_bits(group->field) + 1) / 2 + 3) {
320         /* default to 0 */
321         BN_zero(group->cofactor);
322         /* return success */
323         return 1;
324     }
325
326     if ((ctx = BN_CTX_new_ex(group->libctx)) == NULL)
327         return 0;
328
329     BN_CTX_start(ctx);
330     if ((q = BN_CTX_get(ctx)) == NULL)
331         goto err;
332
333     /* set q = 2**m for binary fields; q = p otherwise */
334     if (group->meth->field_type == NID_X9_62_characteristic_two_field) {
335         BN_zero(q);
336         if (!BN_set_bit(q, BN_num_bits(group->field) - 1))
337             goto err;
338     } else {
339         if (!BN_copy(q, group->field))
340             goto err;
341     }
342
343     /* compute h = \lfloor (q + 1)/n \rceil = \lfloor (q + 1 + n/2)/n \rfloor */
344     if (!BN_rshift1(group->cofactor, group->order) /* n/2 */
345         || !BN_add(group->cofactor, group->cofactor, q) /* q + n/2 */
346         /* q + 1 + n/2 */
347         || !BN_add(group->cofactor, group->cofactor, BN_value_one())
348         /* (q + 1 + n/2)/n */
349         || !BN_div(group->cofactor, NULL, group->cofactor, group->order, ctx))
350         goto err;
351     ret = 1;
352  err:
353     BN_CTX_end(ctx);
354     BN_CTX_free(ctx);
355     return ret;
356 }
357
358 int EC_GROUP_set_generator(EC_GROUP *group, const EC_POINT *generator,
359                            const BIGNUM *order, const BIGNUM *cofactor)
360 {
361     if (generator == NULL) {
362         ERR_raise(ERR_LIB_EC, ERR_R_PASSED_NULL_PARAMETER);
363         return 0;
364     }
365
366     /* require group->field >= 1 */
367     if (group->field == NULL || BN_is_zero(group->field)
368         || BN_is_negative(group->field)) {
369         ERR_raise(ERR_LIB_EC, EC_R_INVALID_FIELD);
370         return 0;
371     }
372
373     /*-
374      * - require order >= 1
375      * - enforce upper bound due to Hasse thm: order can be no more than one bit
376      *   longer than field cardinality
377      */
378     if (order == NULL || BN_is_zero(order) || BN_is_negative(order)
379         || BN_num_bits(order) > BN_num_bits(group->field) + 1) {
380         ERR_raise(ERR_LIB_EC, EC_R_INVALID_GROUP_ORDER);
381         return 0;
382     }
383
384     /*-
385      * Unfortunately the cofactor is an optional field in many standards.
386      * Internally, the lib uses 0 cofactor as a marker for "unknown cofactor".
387      * So accept cofactor == NULL or cofactor >= 0.
388      */
389     if (cofactor != NULL && BN_is_negative(cofactor)) {
390         ERR_raise(ERR_LIB_EC, EC_R_UNKNOWN_COFACTOR);
391         return 0;
392     }
393
394     if (group->generator == NULL) {
395         group->generator = EC_POINT_new(group);
396         if (group->generator == NULL)
397             return 0;
398     }
399     if (!EC_POINT_copy(group->generator, generator))
400         return 0;
401
402     if (!BN_copy(group->order, order))
403         return 0;
404
405     /* Either take the provided positive cofactor, or try to compute it */
406     if (cofactor != NULL && !BN_is_zero(cofactor)) {
407         if (!BN_copy(group->cofactor, cofactor))
408             return 0;
409     } else if (!ec_guess_cofactor(group)) {
410         BN_zero(group->cofactor);
411         return 0;
412     }
413
414     /*
415      * Some groups have an order with
416      * factors of two, which makes the Montgomery setup fail.
417      * |group->mont_data| will be NULL in this case.
418      */
419     if (BN_is_odd(group->order)) {
420         return ec_precompute_mont_data(group);
421     }
422
423     BN_MONT_CTX_free(group->mont_data);
424     group->mont_data = NULL;
425     return 1;
426 }
427
428 const EC_POINT *EC_GROUP_get0_generator(const EC_GROUP *group)
429 {
430     return group->generator;
431 }
432
433 BN_MONT_CTX *EC_GROUP_get_mont_data(const EC_GROUP *group)
434 {
435     return group->mont_data;
436 }
437
438 int EC_GROUP_get_order(const EC_GROUP *group, BIGNUM *order, BN_CTX *ctx)
439 {
440     if (group->order == NULL)
441         return 0;
442     if (!BN_copy(order, group->order))
443         return 0;
444
445     return !BN_is_zero(order);
446 }
447
448 const BIGNUM *EC_GROUP_get0_order(const EC_GROUP *group)
449 {
450     return group->order;
451 }
452
453 int EC_GROUP_order_bits(const EC_GROUP *group)
454 {
455     return group->meth->group_order_bits(group);
456 }
457
458 int EC_GROUP_get_cofactor(const EC_GROUP *group, BIGNUM *cofactor,
459                           BN_CTX *ctx)
460 {
461
462     if (group->cofactor == NULL)
463         return 0;
464     if (!BN_copy(cofactor, group->cofactor))
465         return 0;
466
467     return !BN_is_zero(group->cofactor);
468 }
469
470 const BIGNUM *EC_GROUP_get0_cofactor(const EC_GROUP *group)
471 {
472     return group->cofactor;
473 }
474
475 void EC_GROUP_set_curve_name(EC_GROUP *group, int nid)
476 {
477     group->curve_name = nid;
478     group->asn1_flag =
479         (nid != NID_undef)
480         ? OPENSSL_EC_NAMED_CURVE
481         : OPENSSL_EC_EXPLICIT_CURVE;
482 }
483
484 int EC_GROUP_get_curve_name(const EC_GROUP *group)
485 {
486     return group->curve_name;
487 }
488
489 const BIGNUM *EC_GROUP_get0_field(const EC_GROUP *group)
490 {
491     return group->field;
492 }
493
494 int EC_GROUP_get_field_type(const EC_GROUP *group)
495 {
496     return group->meth->field_type;
497 }
498
499 void EC_GROUP_set_asn1_flag(EC_GROUP *group, int flag)
500 {
501     group->asn1_flag = flag;
502 }
503
504 int EC_GROUP_get_asn1_flag(const EC_GROUP *group)
505 {
506     return group->asn1_flag;
507 }
508
509 void EC_GROUP_set_point_conversion_form(EC_GROUP *group,
510                                         point_conversion_form_t form)
511 {
512     group->asn1_form = form;
513 }
514
515 point_conversion_form_t EC_GROUP_get_point_conversion_form(const EC_GROUP
516                                                            *group)
517 {
518     return group->asn1_form;
519 }
520
521 size_t EC_GROUP_set_seed(EC_GROUP *group, const unsigned char *p, size_t len)
522 {
523     OPENSSL_free(group->seed);
524     group->seed = NULL;
525     group->seed_len = 0;
526
527     if (!len || !p)
528         return 1;
529
530     if ((group->seed = OPENSSL_malloc(len)) == NULL)
531         return 0;
532     memcpy(group->seed, p, len);
533     group->seed_len = len;
534
535     return len;
536 }
537
538 unsigned char *EC_GROUP_get0_seed(const EC_GROUP *group)
539 {
540     return group->seed;
541 }
542
543 size_t EC_GROUP_get_seed_len(const EC_GROUP *group)
544 {
545     return group->seed_len;
546 }
547
548 int EC_GROUP_set_curve(EC_GROUP *group, const BIGNUM *p, const BIGNUM *a,
549                        const BIGNUM *b, BN_CTX *ctx)
550 {
551     if (group->meth->group_set_curve == 0) {
552         ERR_raise(ERR_LIB_EC, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
553         return 0;
554     }
555     return group->meth->group_set_curve(group, p, a, b, ctx);
556 }
557
558 int EC_GROUP_get_curve(const EC_GROUP *group, BIGNUM *p, BIGNUM *a, BIGNUM *b,
559                        BN_CTX *ctx)
560 {
561     if (group->meth->group_get_curve == NULL) {
562         ERR_raise(ERR_LIB_EC, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
563         return 0;
564     }
565     return group->meth->group_get_curve(group, p, a, b, ctx);
566 }
567
568 #ifndef OPENSSL_NO_DEPRECATED_3_0
569 int EC_GROUP_set_curve_GFp(EC_GROUP *group, const BIGNUM *p, const BIGNUM *a,
570                            const BIGNUM *b, BN_CTX *ctx)
571 {
572     return EC_GROUP_set_curve(group, p, a, b, ctx);
573 }
574
575 int EC_GROUP_get_curve_GFp(const EC_GROUP *group, BIGNUM *p, BIGNUM *a,
576                            BIGNUM *b, BN_CTX *ctx)
577 {
578     return EC_GROUP_get_curve(group, p, a, b, ctx);
579 }
580
581 # ifndef OPENSSL_NO_EC2M
582 int EC_GROUP_set_curve_GF2m(EC_GROUP *group, const BIGNUM *p, const BIGNUM *a,
583                             const BIGNUM *b, BN_CTX *ctx)
584 {
585     return EC_GROUP_set_curve(group, p, a, b, ctx);
586 }
587
588 int EC_GROUP_get_curve_GF2m(const EC_GROUP *group, BIGNUM *p, BIGNUM *a,
589                             BIGNUM *b, BN_CTX *ctx)
590 {
591     return EC_GROUP_get_curve(group, p, a, b, ctx);
592 }
593 # endif
594 #endif
595
596 int EC_GROUP_get_degree(const EC_GROUP *group)
597 {
598     if (group->meth->group_get_degree == 0) {
599         ERR_raise(ERR_LIB_EC, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
600         return 0;
601     }
602     return group->meth->group_get_degree(group);
603 }
604
605 int EC_GROUP_check_discriminant(const EC_GROUP *group, BN_CTX *ctx)
606 {
607     if (group->meth->group_check_discriminant == 0) {
608         ERR_raise(ERR_LIB_EC, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
609         return 0;
610     }
611     return group->meth->group_check_discriminant(group, ctx);
612 }
613
614 int EC_GROUP_cmp(const EC_GROUP *a, const EC_GROUP *b, BN_CTX *ctx)
615 {
616     int r = 0;
617     BIGNUM *a1, *a2, *a3, *b1, *b2, *b3;
618 #ifndef FIPS_MODULE
619     BN_CTX *ctx_new = NULL;
620 #endif
621
622     /* compare the field types */
623     if (EC_GROUP_get_field_type(a) != EC_GROUP_get_field_type(b))
624         return 1;
625     /* compare the curve name (if present in both) */
626     if (EC_GROUP_get_curve_name(a) && EC_GROUP_get_curve_name(b) &&
627         EC_GROUP_get_curve_name(a) != EC_GROUP_get_curve_name(b))
628         return 1;
629     if (a->meth->flags & EC_FLAGS_CUSTOM_CURVE)
630         return 0;
631
632 #ifndef FIPS_MODULE
633     if (ctx == NULL)
634         ctx_new = ctx = BN_CTX_new();
635 #endif
636     if (ctx == NULL)
637         return -1;
638
639     BN_CTX_start(ctx);
640     a1 = BN_CTX_get(ctx);
641     a2 = BN_CTX_get(ctx);
642     a3 = BN_CTX_get(ctx);
643     b1 = BN_CTX_get(ctx);
644     b2 = BN_CTX_get(ctx);
645     b3 = BN_CTX_get(ctx);
646     if (b3 == NULL) {
647         BN_CTX_end(ctx);
648 #ifndef FIPS_MODULE
649         BN_CTX_free(ctx_new);
650 #endif
651         return -1;
652     }
653
654     /*
655      * XXX This approach assumes that the external representation of curves
656      * over the same field type is the same.
657      */
658     if (!a->meth->group_get_curve(a, a1, a2, a3, ctx) ||
659         !b->meth->group_get_curve(b, b1, b2, b3, ctx))
660         r = 1;
661
662     /* return 1 if the curve parameters are different */
663     if (r || BN_cmp(a1, b1) != 0 || BN_cmp(a2, b2) != 0 || BN_cmp(a3, b3) != 0)
664         r = 1;
665
666     /* XXX EC_POINT_cmp() assumes that the methods are equal */
667     /* return 1 if the generators are different */
668     if (r || EC_POINT_cmp(a, EC_GROUP_get0_generator(a),
669                           EC_GROUP_get0_generator(b), ctx) != 0)
670         r = 1;
671
672     if (!r) {
673         const BIGNUM *ao, *bo, *ac, *bc;
674         /* compare the orders */
675         ao = EC_GROUP_get0_order(a);
676         bo = EC_GROUP_get0_order(b);
677         if (ao == NULL || bo == NULL) {
678             /* return an error if either order is NULL */
679             r = -1;
680             goto end;
681         }
682         if (BN_cmp(ao, bo) != 0) {
683             /* return 1 if orders are different */
684             r = 1;
685             goto end;
686         }
687         /*
688          * It gets here if the curve parameters and generator matched.
689          * Now check the optional cofactors (if both are present).
690          */
691         ac = EC_GROUP_get0_cofactor(a);
692         bc = EC_GROUP_get0_cofactor(b);
693         /* Returns 1 (mismatch) if both cofactors are specified and different */
694         if (!BN_is_zero(ac) && !BN_is_zero(bc) && BN_cmp(ac, bc) != 0)
695             r = 1;
696         /* Returns 0 if the parameters matched */
697     }
698 end:
699     BN_CTX_end(ctx);
700 #ifndef FIPS_MODULE
701     BN_CTX_free(ctx_new);
702 #endif
703     return r;
704 }
705
706 /* functions for EC_POINT objects */
707
708 EC_POINT *EC_POINT_new(const EC_GROUP *group)
709 {
710     EC_POINT *ret;
711
712     if (group == NULL) {
713         ERR_raise(ERR_LIB_EC, ERR_R_PASSED_NULL_PARAMETER);
714         return NULL;
715     }
716     if (group->meth->point_init == NULL) {
717         ERR_raise(ERR_LIB_EC, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
718         return NULL;
719     }
720
721     ret = OPENSSL_zalloc(sizeof(*ret));
722     if (ret == NULL)
723         return NULL;
724
725     ret->meth = group->meth;
726     ret->curve_name = group->curve_name;
727
728     if (!ret->meth->point_init(ret)) {
729         OPENSSL_free(ret);
730         return NULL;
731     }
732
733     return ret;
734 }
735
736 void EC_POINT_free(EC_POINT *point)
737 {
738     if (point == NULL)
739         return;
740
741     if (point->meth->point_finish != 0)
742         point->meth->point_finish(point);
743     OPENSSL_free(point);
744 }
745
746 void EC_POINT_clear_free(EC_POINT *point)
747 {
748     if (point == NULL)
749         return;
750
751     if (point->meth->point_clear_finish != 0)
752         point->meth->point_clear_finish(point);
753     else if (point->meth->point_finish != 0)
754         point->meth->point_finish(point);
755     OPENSSL_clear_free(point, sizeof(*point));
756 }
757
758 int EC_POINT_copy(EC_POINT *dest, const EC_POINT *src)
759 {
760     if (dest->meth->point_copy == 0) {
761         ERR_raise(ERR_LIB_EC, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
762         return 0;
763     }
764     if (dest->meth != src->meth
765             || (dest->curve_name != src->curve_name
766                  && dest->curve_name != 0
767                  && src->curve_name != 0)) {
768         ERR_raise(ERR_LIB_EC, EC_R_INCOMPATIBLE_OBJECTS);
769         return 0;
770     }
771     if (dest == src)
772         return 1;
773     return dest->meth->point_copy(dest, src);
774 }
775
776 EC_POINT *EC_POINT_dup(const EC_POINT *a, const EC_GROUP *group)
777 {
778     EC_POINT *t;
779     int r;
780
781     if (a == NULL)
782         return NULL;
783
784     t = EC_POINT_new(group);
785     if (t == NULL)
786         return NULL;
787     r = EC_POINT_copy(t, a);
788     if (!r) {
789         EC_POINT_free(t);
790         return NULL;
791     }
792     return t;
793 }
794
795 #ifndef OPENSSL_NO_DEPRECATED_3_0
796 const EC_METHOD *EC_POINT_method_of(const EC_POINT *point)
797 {
798     return point->meth;
799 }
800 #endif
801
802 int EC_POINT_set_to_infinity(const EC_GROUP *group, EC_POINT *point)
803 {
804     if (group->meth->point_set_to_infinity == 0) {
805         ERR_raise(ERR_LIB_EC, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
806         return 0;
807     }
808     if (group->meth != point->meth) {
809         ERR_raise(ERR_LIB_EC, EC_R_INCOMPATIBLE_OBJECTS);
810         return 0;
811     }
812     return group->meth->point_set_to_infinity(group, point);
813 }
814
815 #ifndef OPENSSL_NO_DEPRECATED_3_0
816 int EC_POINT_set_Jprojective_coordinates_GFp(const EC_GROUP *group,
817                                              EC_POINT *point, const BIGNUM *x,
818                                              const BIGNUM *y, const BIGNUM *z,
819                                              BN_CTX *ctx)
820 {
821     if (group->meth->field_type != NID_X9_62_prime_field) {
822         ERR_raise(ERR_LIB_EC, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
823         return 0;
824     }
825     if (!ec_point_is_compat(point, group)) {
826         ERR_raise(ERR_LIB_EC, EC_R_INCOMPATIBLE_OBJECTS);
827         return 0;
828     }
829     return ossl_ec_GFp_simple_set_Jprojective_coordinates_GFp(group, point,
830                                                               x, y, z, ctx);
831 }
832
833 int EC_POINT_get_Jprojective_coordinates_GFp(const EC_GROUP *group,
834                                              const EC_POINT *point, BIGNUM *x,
835                                              BIGNUM *y, BIGNUM *z,
836                                              BN_CTX *ctx)
837 {
838     if (group->meth->field_type != NID_X9_62_prime_field) {
839         ERR_raise(ERR_LIB_EC, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
840         return 0;
841     }
842     if (!ec_point_is_compat(point, group)) {
843         ERR_raise(ERR_LIB_EC, EC_R_INCOMPATIBLE_OBJECTS);
844         return 0;
845     }
846     return ossl_ec_GFp_simple_get_Jprojective_coordinates_GFp(group, point,
847                                                               x, y, z, ctx);
848 }
849 #endif
850
851 int EC_POINT_set_affine_coordinates(const EC_GROUP *group, EC_POINT *point,
852                                     const BIGNUM *x, const BIGNUM *y,
853                                     BN_CTX *ctx)
854 {
855     if (group->meth->point_set_affine_coordinates == NULL) {
856         ERR_raise(ERR_LIB_EC, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
857         return 0;
858     }
859     if (!ec_point_is_compat(point, group)) {
860         ERR_raise(ERR_LIB_EC, EC_R_INCOMPATIBLE_OBJECTS);
861         return 0;
862     }
863     if (!group->meth->point_set_affine_coordinates(group, point, x, y, ctx))
864         return 0;
865
866     if (EC_POINT_is_on_curve(group, point, ctx) <= 0) {
867         ERR_raise(ERR_LIB_EC, EC_R_POINT_IS_NOT_ON_CURVE);
868         return 0;
869     }
870     return 1;
871 }
872
873 #ifndef OPENSSL_NO_DEPRECATED_3_0
874 int EC_POINT_set_affine_coordinates_GFp(const EC_GROUP *group,
875                                         EC_POINT *point, const BIGNUM *x,
876                                         const BIGNUM *y, BN_CTX *ctx)
877 {
878     return EC_POINT_set_affine_coordinates(group, point, x, y, ctx);
879 }
880
881 # ifndef OPENSSL_NO_EC2M
882 int EC_POINT_set_affine_coordinates_GF2m(const EC_GROUP *group,
883                                          EC_POINT *point, const BIGNUM *x,
884                                          const BIGNUM *y, BN_CTX *ctx)
885 {
886     return EC_POINT_set_affine_coordinates(group, point, x, y, ctx);
887 }
888 # endif
889 #endif
890
891 int EC_POINT_get_affine_coordinates(const EC_GROUP *group,
892                                     const EC_POINT *point, BIGNUM *x, BIGNUM *y,
893                                     BN_CTX *ctx)
894 {
895     if (group->meth->point_get_affine_coordinates == NULL) {
896         ERR_raise(ERR_LIB_EC, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
897         return 0;
898     }
899     if (!ec_point_is_compat(point, group)) {
900         ERR_raise(ERR_LIB_EC, EC_R_INCOMPATIBLE_OBJECTS);
901         return 0;
902     }
903     if (EC_POINT_is_at_infinity(group, point)) {
904         ERR_raise(ERR_LIB_EC, EC_R_POINT_AT_INFINITY);
905         return 0;
906     }
907     return group->meth->point_get_affine_coordinates(group, point, x, y, ctx);
908 }
909
910 #ifndef OPENSSL_NO_DEPRECATED_3_0
911 int EC_POINT_get_affine_coordinates_GFp(const EC_GROUP *group,
912                                         const EC_POINT *point, BIGNUM *x,
913                                         BIGNUM *y, BN_CTX *ctx)
914 {
915     return EC_POINT_get_affine_coordinates(group, point, x, y, ctx);
916 }
917
918 # ifndef OPENSSL_NO_EC2M
919 int EC_POINT_get_affine_coordinates_GF2m(const EC_GROUP *group,
920                                          const EC_POINT *point, BIGNUM *x,
921                                          BIGNUM *y, BN_CTX *ctx)
922 {
923     return EC_POINT_get_affine_coordinates(group, point, x, y, ctx);
924 }
925 # endif
926 #endif
927
928 int EC_POINT_add(const EC_GROUP *group, EC_POINT *r, const EC_POINT *a,
929                  const EC_POINT *b, BN_CTX *ctx)
930 {
931     if (group->meth->add == 0) {
932         ERR_raise(ERR_LIB_EC, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
933         return 0;
934     }
935     if (!ec_point_is_compat(r, group) || !ec_point_is_compat(a, group)
936         || !ec_point_is_compat(b, group)) {
937         ERR_raise(ERR_LIB_EC, EC_R_INCOMPATIBLE_OBJECTS);
938         return 0;
939     }
940     return group->meth->add(group, r, a, b, ctx);
941 }
942
943 int EC_POINT_dbl(const EC_GROUP *group, EC_POINT *r, const EC_POINT *a,
944                  BN_CTX *ctx)
945 {
946     if (group->meth->dbl == 0) {
947         ERR_raise(ERR_LIB_EC, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
948         return 0;
949     }
950     if (!ec_point_is_compat(r, group) || !ec_point_is_compat(a, group)) {
951         ERR_raise(ERR_LIB_EC, EC_R_INCOMPATIBLE_OBJECTS);
952         return 0;
953     }
954     return group->meth->dbl(group, r, a, ctx);
955 }
956
957 int EC_POINT_invert(const EC_GROUP *group, EC_POINT *a, BN_CTX *ctx)
958 {
959     if (group->meth->invert == 0) {
960         ERR_raise(ERR_LIB_EC, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
961         return 0;
962     }
963     if (!ec_point_is_compat(a, group)) {
964         ERR_raise(ERR_LIB_EC, EC_R_INCOMPATIBLE_OBJECTS);
965         return 0;
966     }
967     return group->meth->invert(group, a, ctx);
968 }
969
970 int EC_POINT_is_at_infinity(const EC_GROUP *group, const EC_POINT *point)
971 {
972     if (group->meth->is_at_infinity == 0) {
973         ERR_raise(ERR_LIB_EC, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
974         return 0;
975     }
976     if (!ec_point_is_compat(point, group)) {
977         ERR_raise(ERR_LIB_EC, EC_R_INCOMPATIBLE_OBJECTS);
978         return 0;
979     }
980     return group->meth->is_at_infinity(group, point);
981 }
982
983 /*
984  * Check whether an EC_POINT is on the curve or not. Note that the return
985  * value for this function should NOT be treated as a boolean. Return values:
986  *  1: The point is on the curve
987  *  0: The point is not on the curve
988  * -1: An error occurred
989  */
990 int EC_POINT_is_on_curve(const EC_GROUP *group, const EC_POINT *point,
991                          BN_CTX *ctx)
992 {
993     if (group->meth->is_on_curve == 0) {
994         ERR_raise(ERR_LIB_EC, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
995         return 0;
996     }
997     if (!ec_point_is_compat(point, group)) {
998         ERR_raise(ERR_LIB_EC, EC_R_INCOMPATIBLE_OBJECTS);
999         return 0;
1000     }
1001     return group->meth->is_on_curve(group, point, ctx);
1002 }
1003
1004 int EC_POINT_cmp(const EC_GROUP *group, const EC_POINT *a, const EC_POINT *b,
1005                  BN_CTX *ctx)
1006 {
1007     if (group->meth->point_cmp == 0) {
1008         ERR_raise(ERR_LIB_EC, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1009         return -1;
1010     }
1011     if (!ec_point_is_compat(a, group) || !ec_point_is_compat(b, group)) {
1012         ERR_raise(ERR_LIB_EC, EC_R_INCOMPATIBLE_OBJECTS);
1013         return -1;
1014     }
1015     return group->meth->point_cmp(group, a, b, ctx);
1016 }
1017
1018 #ifndef OPENSSL_NO_DEPRECATED_3_0
1019 int EC_POINT_make_affine(const EC_GROUP *group, EC_POINT *point, BN_CTX *ctx)
1020 {
1021     if (group->meth->make_affine == 0) {
1022         ERR_raise(ERR_LIB_EC, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1023         return 0;
1024     }
1025     if (!ec_point_is_compat(point, group)) {
1026         ERR_raise(ERR_LIB_EC, EC_R_INCOMPATIBLE_OBJECTS);
1027         return 0;
1028     }
1029     return group->meth->make_affine(group, point, ctx);
1030 }
1031
1032 int EC_POINTs_make_affine(const EC_GROUP *group, size_t num,
1033                           EC_POINT *points[], BN_CTX *ctx)
1034 {
1035     size_t i;
1036
1037     if (group->meth->points_make_affine == 0) {
1038         ERR_raise(ERR_LIB_EC, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1039         return 0;
1040     }
1041     for (i = 0; i < num; i++) {
1042         if (!ec_point_is_compat(points[i], group)) {
1043             ERR_raise(ERR_LIB_EC, EC_R_INCOMPATIBLE_OBJECTS);
1044             return 0;
1045         }
1046     }
1047     return group->meth->points_make_affine(group, num, points, ctx);
1048 }
1049 #endif
1050
1051 /*
1052  * Functions for point multiplication. If group->meth->mul is 0, we use the
1053  * wNAF-based implementations in ec_mult.c; otherwise we dispatch through
1054  * methods.
1055  */
1056
1057 #ifndef OPENSSL_NO_DEPRECATED_3_0
1058 int EC_POINTs_mul(const EC_GROUP *group, EC_POINT *r, const BIGNUM *scalar,
1059                   size_t num, const EC_POINT *points[],
1060                   const BIGNUM *scalars[], BN_CTX *ctx)
1061 {
1062     int ret = 0;
1063     size_t i = 0;
1064 #ifndef FIPS_MODULE
1065     BN_CTX *new_ctx = NULL;
1066 #endif
1067
1068     if (!ec_point_is_compat(r, group)) {
1069         ERR_raise(ERR_LIB_EC, EC_R_INCOMPATIBLE_OBJECTS);
1070         return 0;
1071     }
1072
1073     if (scalar == NULL && num == 0)
1074         return EC_POINT_set_to_infinity(group, r);
1075
1076     for (i = 0; i < num; i++) {
1077         if (!ec_point_is_compat(points[i], group)) {
1078             ERR_raise(ERR_LIB_EC, EC_R_INCOMPATIBLE_OBJECTS);
1079             return 0;
1080         }
1081     }
1082
1083 #ifndef FIPS_MODULE
1084     if (ctx == NULL)
1085         ctx = new_ctx = BN_CTX_secure_new();
1086 #endif
1087     if (ctx == NULL) {
1088         ERR_raise(ERR_LIB_EC, ERR_R_INTERNAL_ERROR);
1089         return 0;
1090     }
1091
1092     if (group->meth->mul != NULL)
1093         ret = group->meth->mul(group, r, scalar, num, points, scalars, ctx);
1094     else
1095         /* use default */
1096         ret = ossl_ec_wNAF_mul(group, r, scalar, num, points, scalars, ctx);
1097
1098 #ifndef FIPS_MODULE
1099     BN_CTX_free(new_ctx);
1100 #endif
1101     return ret;
1102 }
1103 #endif
1104
1105 int EC_POINT_mul(const EC_GROUP *group, EC_POINT *r, const BIGNUM *g_scalar,
1106                  const EC_POINT *point, const BIGNUM *p_scalar, BN_CTX *ctx)
1107 {
1108     int ret = 0;
1109     size_t num;
1110 #ifndef FIPS_MODULE
1111     BN_CTX *new_ctx = NULL;
1112 #endif
1113
1114     if (!ec_point_is_compat(r, group)
1115         || (point != NULL && !ec_point_is_compat(point, group))) {
1116         ERR_raise(ERR_LIB_EC, EC_R_INCOMPATIBLE_OBJECTS);
1117         return 0;
1118     }
1119
1120     if (g_scalar == NULL && p_scalar == NULL)
1121         return EC_POINT_set_to_infinity(group, r);
1122
1123 #ifndef FIPS_MODULE
1124     if (ctx == NULL)
1125         ctx = new_ctx = BN_CTX_secure_new();
1126 #endif
1127     if (ctx == NULL) {
1128         ERR_raise(ERR_LIB_EC, ERR_R_INTERNAL_ERROR);
1129         return 0;
1130     }
1131
1132     num = (point != NULL && p_scalar != NULL) ? 1 : 0;
1133     if (group->meth->mul != NULL)
1134         ret = group->meth->mul(group, r, g_scalar, num, &point, &p_scalar, ctx);
1135     else
1136         /* use default */
1137         ret = ossl_ec_wNAF_mul(group, r, g_scalar, num, &point, &p_scalar, ctx);
1138
1139 #ifndef FIPS_MODULE
1140     BN_CTX_free(new_ctx);
1141 #endif
1142     return ret;
1143 }
1144
1145 #ifndef OPENSSL_NO_DEPRECATED_3_0
1146 int EC_GROUP_precompute_mult(EC_GROUP *group, BN_CTX *ctx)
1147 {
1148     if (group->meth->mul == 0)
1149         /* use default */
1150         return ossl_ec_wNAF_precompute_mult(group, ctx);
1151
1152     if (group->meth->precompute_mult != 0)
1153         return group->meth->precompute_mult(group, ctx);
1154     else
1155         return 1;               /* nothing to do, so report success */
1156 }
1157
1158 int EC_GROUP_have_precompute_mult(const EC_GROUP *group)
1159 {
1160     if (group->meth->mul == 0)
1161         /* use default */
1162         return ossl_ec_wNAF_have_precompute_mult(group);
1163
1164     if (group->meth->have_precompute_mult != 0)
1165         return group->meth->have_precompute_mult(group);
1166     else
1167         return 0;               /* cannot tell whether precomputation has
1168                                  * been performed */
1169 }
1170 #endif
1171
1172 /*
1173  * ec_precompute_mont_data sets |group->mont_data| from |group->order| and
1174  * returns one on success. On error it returns zero.
1175  */
1176 static int ec_precompute_mont_data(EC_GROUP *group)
1177 {
1178     BN_CTX *ctx = BN_CTX_new_ex(group->libctx);
1179     int ret = 0;
1180
1181     BN_MONT_CTX_free(group->mont_data);
1182     group->mont_data = NULL;
1183
1184     if (ctx == NULL)
1185         goto err;
1186
1187     group->mont_data = BN_MONT_CTX_new();
1188     if (group->mont_data == NULL)
1189         goto err;
1190
1191     if (!BN_MONT_CTX_set(group->mont_data, group->order, ctx)) {
1192         BN_MONT_CTX_free(group->mont_data);
1193         group->mont_data = NULL;
1194         goto err;
1195     }
1196
1197     ret = 1;
1198
1199  err:
1200
1201     BN_CTX_free(ctx);
1202     return ret;
1203 }
1204
1205 #ifndef FIPS_MODULE
1206 int EC_KEY_set_ex_data(EC_KEY *key, int idx, void *arg)
1207 {
1208     return CRYPTO_set_ex_data(&key->ex_data, idx, arg);
1209 }
1210
1211 void *EC_KEY_get_ex_data(const EC_KEY *key, int idx)
1212 {
1213     return CRYPTO_get_ex_data(&key->ex_data, idx);
1214 }
1215 #endif
1216
1217 int ossl_ec_group_simple_order_bits(const EC_GROUP *group)
1218 {
1219     if (group->order == NULL)
1220         return 0;
1221     return BN_num_bits(group->order);
1222 }
1223
1224 static int ec_field_inverse_mod_ord(const EC_GROUP *group, BIGNUM *r,
1225                                     const BIGNUM *x, BN_CTX *ctx)
1226 {
1227     BIGNUM *e = NULL;
1228     int ret = 0;
1229 #ifndef FIPS_MODULE
1230     BN_CTX *new_ctx = NULL;
1231 #endif
1232
1233     if (group->mont_data == NULL)
1234         return 0;
1235
1236 #ifndef FIPS_MODULE
1237     if (ctx == NULL)
1238         ctx = new_ctx = BN_CTX_secure_new();
1239 #endif
1240     if (ctx == NULL)
1241         return 0;
1242
1243     BN_CTX_start(ctx);
1244     if ((e = BN_CTX_get(ctx)) == NULL)
1245         goto err;
1246
1247     /*-
1248      * We want inverse in constant time, therefore we utilize the fact
1249      * order must be prime and use Fermats Little Theorem instead.
1250      */
1251     if (!BN_set_word(e, 2))
1252         goto err;
1253     if (!BN_sub(e, group->order, e))
1254         goto err;
1255     /*-
1256      * Exponent e is public.
1257      * No need for scatter-gather or BN_FLG_CONSTTIME.
1258      */
1259     if (!BN_mod_exp_mont(r, x, e, group->order, ctx, group->mont_data))
1260         goto err;
1261
1262     ret = 1;
1263
1264  err:
1265     BN_CTX_end(ctx);
1266 #ifndef FIPS_MODULE
1267     BN_CTX_free(new_ctx);
1268 #endif
1269     return ret;
1270 }
1271
1272 /*-
1273  * Default behavior, if group->meth->field_inverse_mod_ord is NULL:
1274  * - When group->order is even, this function returns an error.
1275  * - When group->order is otherwise composite, the correctness
1276  *   of the output is not guaranteed.
1277  * - When x is outside the range [1, group->order), the correctness
1278  *   of the output is not guaranteed.
1279  * - Otherwise, this function returns the multiplicative inverse in the
1280  *   range [1, group->order).
1281  *
1282  * EC_METHODs must implement their own field_inverse_mod_ord for
1283  * other functionality.
1284  */
1285 int ossl_ec_group_do_inverse_ord(const EC_GROUP *group, BIGNUM *res,
1286                                  const BIGNUM *x, BN_CTX *ctx)
1287 {
1288     if (group->meth->field_inverse_mod_ord != NULL)
1289         return group->meth->field_inverse_mod_ord(group, res, x, ctx);
1290     else
1291         return ec_field_inverse_mod_ord(group, res, x, ctx);
1292 }
1293
1294 /*-
1295  * Coordinate blinding for EC_POINT.
1296  *
1297  * The underlying EC_METHOD can optionally implement this function:
1298  * underlying implementations should return 0 on errors, or 1 on
1299  * success.
1300  *
1301  * This wrapper returns 1 in case the underlying EC_METHOD does not
1302  * support coordinate blinding.
1303  */
1304 int ossl_ec_point_blind_coordinates(const EC_GROUP *group, EC_POINT *p,
1305                                     BN_CTX *ctx)
1306 {
1307     if (group->meth->blind_coordinates == NULL)
1308         return 1; /* ignore if not implemented */
1309
1310     return group->meth->blind_coordinates(group, p, ctx);
1311 }
1312
1313 int EC_GROUP_get_basis_type(const EC_GROUP *group)
1314 {
1315     int i;
1316
1317     if (EC_GROUP_get_field_type(group) != NID_X9_62_characteristic_two_field)
1318         /* everything else is currently not supported */
1319         return 0;
1320
1321     /* Find the last non-zero element of group->poly[] */
1322     for (i = 0;
1323          i < (int)OSSL_NELEM(group->poly) && group->poly[i] != 0;
1324          i++)
1325         continue;
1326
1327     if (i == 4)
1328         return NID_X9_62_ppBasis;
1329     else if (i == 2)
1330         return NID_X9_62_tpBasis;
1331     else
1332         /* everything else is currently not supported */
1333         return 0;
1334 }
1335
1336 #ifndef OPENSSL_NO_EC2M
1337 int EC_GROUP_get_trinomial_basis(const EC_GROUP *group, unsigned int *k)
1338 {
1339     if (group == NULL)
1340         return 0;
1341
1342     if (EC_GROUP_get_field_type(group) != NID_X9_62_characteristic_two_field
1343         || !((group->poly[0] != 0) && (group->poly[1] != 0)
1344              && (group->poly[2] == 0))) {
1345         ERR_raise(ERR_LIB_EC, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1346         return 0;
1347     }
1348
1349     if (k)
1350         *k = group->poly[1];
1351
1352     return 1;
1353 }
1354
1355 int EC_GROUP_get_pentanomial_basis(const EC_GROUP *group, unsigned int *k1,
1356                                    unsigned int *k2, unsigned int *k3)
1357 {
1358     if (group == NULL)
1359         return 0;
1360
1361     if (EC_GROUP_get_field_type(group) != NID_X9_62_characteristic_two_field
1362         || !((group->poly[0] != 0) && (group->poly[1] != 0)
1363              && (group->poly[2] != 0) && (group->poly[3] != 0)
1364              && (group->poly[4] == 0))) {
1365         ERR_raise(ERR_LIB_EC, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1366         return 0;
1367     }
1368
1369     if (k1)
1370         *k1 = group->poly[3];
1371     if (k2)
1372         *k2 = group->poly[2];
1373     if (k3)
1374         *k3 = group->poly[1];
1375
1376     return 1;
1377 }
1378 #endif
1379
1380 #ifndef FIPS_MODULE
1381 /*
1382  * Check if the explicit parameters group matches any built-in curves.
1383  *
1384  * We create a copy of the group just built, so that we can remove optional
1385  * fields for the lookup: we do this to avoid the possibility that one of
1386  * the optional parameters is used to force the library into using a less
1387  * performant and less secure EC_METHOD instead of the specialized one.
1388  * In any case, `seed` is not really used in any computation, while a
1389  * cofactor different from the one in the built-in table is just
1390  * mathematically wrong anyway and should not be used.
1391  */
1392 static EC_GROUP *ec_group_explicit_to_named(const EC_GROUP *group,
1393                                             OSSL_LIB_CTX *libctx,
1394                                             const char *propq,
1395                                             BN_CTX *ctx)
1396 {
1397     EC_GROUP *ret_group = NULL, *dup = NULL;
1398     int curve_name_nid;
1399
1400     const EC_POINT *point = EC_GROUP_get0_generator(group);
1401     const BIGNUM *order = EC_GROUP_get0_order(group);
1402     int no_seed = (EC_GROUP_get0_seed(group) == NULL);
1403
1404     if ((dup = EC_GROUP_dup(group)) == NULL
1405             || EC_GROUP_set_seed(dup, NULL, 0) != 1
1406             || !EC_GROUP_set_generator(dup, point, order, NULL))
1407         goto err;
1408     if ((curve_name_nid = ossl_ec_curve_nid_from_params(dup, ctx)) != NID_undef) {
1409         /*
1410          * The input explicit parameters successfully matched one of the
1411          * built-in curves: often for built-in curves we have specialized
1412          * methods with better performance and hardening.
1413          *
1414          * In this case we replace the `EC_GROUP` created through explicit
1415          * parameters with one created from a named group.
1416          */
1417
1418 # ifndef OPENSSL_NO_EC_NISTP_64_GCC_128
1419         /*
1420          * NID_wap_wsg_idm_ecid_wtls12 and NID_secp224r1 are both aliases for
1421          * the same curve, we prefer the SECP nid when matching explicit
1422          * parameters as that is associated with a specialized EC_METHOD.
1423          */
1424         if (curve_name_nid == NID_wap_wsg_idm_ecid_wtls12)
1425             curve_name_nid = NID_secp224r1;
1426 # endif /* !def(OPENSSL_NO_EC_NISTP_64_GCC_128) */
1427
1428         ret_group = EC_GROUP_new_by_curve_name_ex(libctx, propq, curve_name_nid);
1429         if (ret_group == NULL)
1430             goto err;
1431
1432         /*
1433          * Set the flag so that EC_GROUPs created from explicit parameters are
1434          * serialized using explicit parameters by default.
1435          */
1436         EC_GROUP_set_asn1_flag(ret_group, OPENSSL_EC_EXPLICIT_CURVE);
1437
1438         /*
1439          * If the input params do not contain the optional seed field we make
1440          * sure it is not added to the returned group.
1441          *
1442          * The seed field is not really used inside libcrypto anyway, and
1443          * adding it to parsed explicit parameter keys would alter their DER
1444          * encoding output (because of the extra field) which could impact
1445          * applications fingerprinting keys by their DER encoding.
1446          */
1447         if (no_seed) {
1448             if (EC_GROUP_set_seed(ret_group, NULL, 0) != 1)
1449                 goto err;
1450         }
1451     } else {
1452         ret_group = (EC_GROUP *)group;
1453     }
1454     EC_GROUP_free(dup);
1455     return ret_group;
1456 err:
1457     EC_GROUP_free(dup);
1458     EC_GROUP_free(ret_group);
1459     return NULL;
1460 }
1461 #endif /* FIPS_MODULE */
1462
1463 static EC_GROUP *group_new_from_name(const OSSL_PARAM *p,
1464                                      OSSL_LIB_CTX *libctx, const char *propq)
1465 {
1466     int ok = 0, nid;
1467     const char *curve_name = NULL;
1468
1469     switch (p->data_type) {
1470     case OSSL_PARAM_UTF8_STRING:
1471         /* The OSSL_PARAM functions have no support for this */
1472         curve_name = p->data;
1473         ok = (curve_name != NULL);
1474         break;
1475     case OSSL_PARAM_UTF8_PTR:
1476         ok = OSSL_PARAM_get_utf8_ptr(p, &curve_name);
1477         break;
1478     }
1479
1480     if (ok) {
1481         nid = ossl_ec_curve_name2nid(curve_name);
1482         if (nid == NID_undef) {
1483             ERR_raise(ERR_LIB_EC, EC_R_INVALID_CURVE);
1484             return NULL;
1485         } else {
1486             return EC_GROUP_new_by_curve_name_ex(libctx, propq, nid);
1487         }
1488     }
1489     return NULL;
1490 }
1491
1492 /* These parameters can be set directly into an EC_GROUP */
1493 int ossl_ec_group_set_params(EC_GROUP *group, const OSSL_PARAM params[])
1494 {
1495     int encoding_flag = -1, format = -1;
1496     const OSSL_PARAM *p;
1497
1498     p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_EC_POINT_CONVERSION_FORMAT);
1499     if (p != NULL) {
1500         if (!ossl_ec_pt_format_param2id(p, &format)) {
1501             ERR_raise(ERR_LIB_EC, EC_R_INVALID_FORM);
1502             return 0;
1503         }
1504         EC_GROUP_set_point_conversion_form(group, format);
1505     }
1506
1507     p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_EC_ENCODING);
1508     if (p != NULL) {
1509         if (!ossl_ec_encoding_param2id(p, &encoding_flag)) {
1510             ERR_raise(ERR_LIB_EC, EC_R_INVALID_FORM);
1511             return 0;
1512         }
1513         EC_GROUP_set_asn1_flag(group, encoding_flag);
1514     }
1515     /* Optional seed */
1516     p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_EC_SEED);
1517     if (p != NULL) {
1518         /* The seed is allowed to be NULL */
1519         if (p->data_type != OSSL_PARAM_OCTET_STRING
1520             || !EC_GROUP_set_seed(group, p->data, p->data_size)) {
1521             ERR_raise(ERR_LIB_EC, EC_R_INVALID_SEED);
1522             return 0;
1523         }
1524     }
1525     return 1;
1526 }
1527
1528 EC_GROUP *EC_GROUP_new_from_params(const OSSL_PARAM params[],
1529                                    OSSL_LIB_CTX *libctx, const char *propq)
1530 {
1531     const OSSL_PARAM *ptmp;
1532     EC_GROUP *group = NULL;
1533
1534 #ifndef FIPS_MODULE
1535     const OSSL_PARAM *pa, *pb;
1536     int ok = 0;
1537     EC_GROUP *named_group = NULL;
1538     BIGNUM *p = NULL, *a = NULL, *b = NULL, *order = NULL, *cofactor = NULL;
1539     EC_POINT *point = NULL;
1540     int field_bits = 0;
1541     int is_prime_field = 1;
1542     BN_CTX *bnctx = NULL;
1543     const unsigned char *buf = NULL;
1544     int encoding_flag = -1;
1545 #endif
1546
1547     /* This is the simple named group case */
1548     ptmp = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_GROUP_NAME);
1549     if (ptmp != NULL) {
1550         int decoded = 0;
1551
1552         if ((group = group_new_from_name(ptmp, libctx, propq)) == NULL)
1553             return NULL;
1554         if (!ossl_ec_group_set_params(group, params)) {
1555             EC_GROUP_free(group);
1556             return NULL;
1557         }
1558
1559         ptmp = OSSL_PARAM_locate_const(params,
1560                                        OSSL_PKEY_PARAM_EC_DECODED_FROM_EXPLICIT_PARAMS);
1561         if (ptmp != NULL && !OSSL_PARAM_get_int(ptmp, &decoded)) {
1562             ERR_raise(ERR_LIB_EC, EC_R_WRONG_CURVE_PARAMETERS);
1563             EC_GROUP_free(group);
1564             return NULL;
1565         }
1566         group->decoded_from_explicit_params = decoded > 0;
1567         return group;
1568     }
1569 #ifdef FIPS_MODULE
1570     ERR_raise(ERR_LIB_EC, EC_R_EXPLICIT_PARAMS_NOT_SUPPORTED);
1571     return NULL;
1572 #else
1573     /* If it gets here then we are trying explicit parameters */
1574     bnctx = BN_CTX_new_ex(libctx);
1575     if (bnctx == NULL) {
1576         ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB);
1577         return 0;
1578     }
1579     BN_CTX_start(bnctx);
1580
1581     p = BN_CTX_get(bnctx);
1582     a = BN_CTX_get(bnctx);
1583     b = BN_CTX_get(bnctx);
1584     order = BN_CTX_get(bnctx);
1585     if (order == NULL) {
1586         ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB);
1587         goto err;
1588     }
1589
1590     ptmp = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_EC_FIELD_TYPE);
1591     if (ptmp == NULL || ptmp->data_type != OSSL_PARAM_UTF8_STRING) {
1592         ERR_raise(ERR_LIB_EC, EC_R_INVALID_FIELD);
1593         goto err;
1594     }
1595     if (OPENSSL_strcasecmp(ptmp->data, SN_X9_62_prime_field) == 0) {
1596         is_prime_field = 1;
1597     } else if (OPENSSL_strcasecmp(ptmp->data,
1598                                   SN_X9_62_characteristic_two_field) == 0) {
1599         is_prime_field = 0;
1600     } else {
1601         /* Invalid field */
1602         ERR_raise(ERR_LIB_EC, EC_R_UNSUPPORTED_FIELD);
1603         goto err;
1604     }
1605
1606     pa = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_EC_A);
1607     if (!OSSL_PARAM_get_BN(pa, &a)) {
1608         ERR_raise(ERR_LIB_EC, EC_R_INVALID_A);
1609         goto err;
1610     }
1611     pb = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_EC_B);
1612     if (!OSSL_PARAM_get_BN(pb, &b)) {
1613         ERR_raise(ERR_LIB_EC, EC_R_INVALID_B);
1614         goto err;
1615     }
1616
1617     /* extract the prime number or irreducible polynomial */
1618     ptmp = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_EC_P);
1619     if (!OSSL_PARAM_get_BN(ptmp, &p)) {
1620         ERR_raise(ERR_LIB_EC, EC_R_INVALID_P);
1621         goto err;
1622     }
1623
1624     if (is_prime_field) {
1625         if (BN_is_negative(p) || BN_is_zero(p)) {
1626             ERR_raise(ERR_LIB_EC, EC_R_INVALID_P);
1627             goto err;
1628         }
1629         field_bits = BN_num_bits(p);
1630         if (field_bits > OPENSSL_ECC_MAX_FIELD_BITS) {
1631             ERR_raise(ERR_LIB_EC, EC_R_FIELD_TOO_LARGE);
1632             goto err;
1633         }
1634
1635         /* create the EC_GROUP structure */
1636         group = EC_GROUP_new_curve_GFp(p, a, b, bnctx);
1637     } else {
1638 # ifdef OPENSSL_NO_EC2M
1639         ERR_raise(ERR_LIB_EC, EC_R_GF2M_NOT_SUPPORTED);
1640         goto err;
1641 # else
1642         /* create the EC_GROUP structure */
1643         group = EC_GROUP_new_curve_GF2m(p, a, b, NULL);
1644         if (group != NULL) {
1645             field_bits = EC_GROUP_get_degree(group);
1646             if (field_bits > OPENSSL_ECC_MAX_FIELD_BITS) {
1647                 ERR_raise(ERR_LIB_EC, EC_R_FIELD_TOO_LARGE);
1648                 goto err;
1649             }
1650         }
1651 # endif /* OPENSSL_NO_EC2M */
1652     }
1653
1654     if (group == NULL) {
1655         ERR_raise(ERR_LIB_EC, ERR_R_EC_LIB);
1656         goto err;
1657     }
1658
1659     /* Optional seed */
1660     ptmp = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_EC_SEED);
1661     if (ptmp != NULL) {
1662         if (ptmp->data_type != OSSL_PARAM_OCTET_STRING) {
1663             ERR_raise(ERR_LIB_EC, EC_R_INVALID_SEED);
1664             goto err;
1665         }
1666         if (!EC_GROUP_set_seed(group, ptmp->data, ptmp->data_size))
1667             goto err;
1668     }
1669
1670     /* generator base point */
1671     ptmp = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_EC_GENERATOR);
1672     if (ptmp == NULL
1673         || ptmp->data_type != OSSL_PARAM_OCTET_STRING) {
1674         ERR_raise(ERR_LIB_EC, EC_R_INVALID_GENERATOR);
1675         goto err;
1676     }
1677     buf = (const unsigned char *)(ptmp->data);
1678     if ((point = EC_POINT_new(group)) == NULL)
1679         goto err;
1680     EC_GROUP_set_point_conversion_form(group,
1681                                        (point_conversion_form_t)buf[0] & ~0x01);
1682     if (!EC_POINT_oct2point(group, point, buf, ptmp->data_size, bnctx)) {
1683         ERR_raise(ERR_LIB_EC, EC_R_INVALID_GENERATOR);
1684         goto err;
1685     }
1686
1687     /* order */
1688     ptmp = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_EC_ORDER);
1689     if (!OSSL_PARAM_get_BN(ptmp, &order)
1690         || (BN_is_negative(order) || BN_is_zero(order))
1691         || (BN_num_bits(order) > (int)field_bits + 1)) { /* Hasse bound */
1692         ERR_raise(ERR_LIB_EC, EC_R_INVALID_GROUP_ORDER);
1693         goto err;
1694     }
1695
1696     /* Optional cofactor */
1697     ptmp = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_EC_COFACTOR);
1698     if (ptmp != NULL) {
1699         cofactor = BN_CTX_get(bnctx);
1700         if (cofactor == NULL || !OSSL_PARAM_get_BN(ptmp, &cofactor)) {
1701             ERR_raise(ERR_LIB_EC, EC_R_INVALID_COFACTOR);
1702             goto err;
1703         }
1704     }
1705
1706     /* set the generator, order and cofactor (if present) */
1707     if (!EC_GROUP_set_generator(group, point, order, cofactor)) {
1708         ERR_raise(ERR_LIB_EC, EC_R_INVALID_GENERATOR);
1709         goto err;
1710     }
1711
1712     named_group = ec_group_explicit_to_named(group, libctx, propq, bnctx);
1713     if (named_group == NULL) {
1714         ERR_raise(ERR_LIB_EC, EC_R_INVALID_NAMED_GROUP_CONVERSION);
1715         goto err;
1716     }
1717     if (named_group == group) {
1718         /*
1719          * If we did not find a named group then the encoding should be explicit
1720          * if it was specified
1721          */
1722         ptmp = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_EC_ENCODING);
1723         if (ptmp != NULL
1724             && !ossl_ec_encoding_param2id(ptmp, &encoding_flag)) {
1725             ERR_raise(ERR_LIB_EC, EC_R_INVALID_ENCODING);
1726             goto err;
1727         }
1728         if (encoding_flag == OPENSSL_EC_NAMED_CURVE) {
1729             ERR_raise(ERR_LIB_EC, EC_R_INVALID_ENCODING);
1730             goto err;
1731         }
1732         EC_GROUP_set_asn1_flag(group, OPENSSL_EC_EXPLICIT_CURVE);
1733     } else {
1734         EC_GROUP_free(group);
1735         group = named_group;
1736     }
1737     /* We've imported the group from explicit parameters, set it so. */
1738     group->decoded_from_explicit_params = 1;
1739     ok = 1;
1740  err:
1741     if (!ok) {
1742         EC_GROUP_free(group);
1743         group = NULL;
1744     }
1745     EC_POINT_free(point);
1746     BN_CTX_end(bnctx);
1747     BN_CTX_free(bnctx);
1748
1749     return group;
1750 #endif /* FIPS_MODULE */
1751 }
1752
1753 OSSL_PARAM *EC_GROUP_to_params(const EC_GROUP *group, OSSL_LIB_CTX *libctx,
1754                                const char *propq, BN_CTX *bnctx)
1755 {
1756     OSSL_PARAM_BLD *tmpl = NULL;
1757     BN_CTX *new_bnctx = NULL;
1758     unsigned char *gen_buf = NULL;
1759     OSSL_PARAM *params = NULL;
1760
1761     if (group == NULL)
1762         goto err;
1763
1764     tmpl = OSSL_PARAM_BLD_new();
1765     if (tmpl == NULL)
1766         goto err;
1767
1768     if (bnctx == NULL)
1769         bnctx = new_bnctx = BN_CTX_new_ex(libctx);
1770     if (bnctx == NULL)
1771         goto err;
1772     BN_CTX_start(bnctx);
1773
1774     if (!ossl_ec_group_todata(
1775             group, tmpl, NULL, libctx, propq, bnctx, &gen_buf))
1776         goto err;
1777
1778     params = OSSL_PARAM_BLD_to_param(tmpl);
1779
1780  err:
1781     OSSL_PARAM_BLD_free(tmpl);
1782     OPENSSL_free(gen_buf);
1783     BN_CTX_end(bnctx);
1784     BN_CTX_free(new_bnctx);
1785     return params;
1786 }