1// Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved.
2// Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//     https://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16#include <openssl/ec.h>
17
18#include <assert.h>
19#include <string.h>
20
21#include <openssl/bn.h>
22#include <openssl/err.h>
23#include <openssl/mem.h>
24#include <openssl/nid.h>
25
26#include "../../internal.h"
27#include "../bn/internal.h"
28#include "../delocate.h"
29#include "internal.h"
30
31#include "builtin_curves.h"
32
33
34static void ec_point_free(EC_POINT *point, int free_group);
35
36static void ec_group_init_static_mont(BN_MONT_CTX *mont, size_t num_words,
37                                      const BN_ULONG *modulus,
38                                      const BN_ULONG *rr, uint64_t n0) {
39  bn_set_static_words(&mont->N, modulus, num_words);
40  bn_set_static_words(&mont->RR, rr, num_words);
41#if defined(OPENSSL_64_BIT)
42  mont->n0[0] = n0;
43#elif defined(OPENSSL_32_BIT)
44  mont->n0[0] = (uint32_t)n0;
45  mont->n0[1] = (uint32_t)(n0 >> 32);
46#else
47#error "unknown word length"
48#endif
49}
50
51static void ec_group_set_a_minus3(EC_GROUP *group) {
52  const EC_FELEM *one = ec_felem_one(group);
53  group->a_is_minus3 = 1;
54  ec_felem_neg(group, &group->a, one);
55  ec_felem_sub(group, &group->a, &group->a, one);
56  ec_felem_sub(group, &group->a, &group->a, one);
57}
58
59DEFINE_METHOD_FUNCTION(EC_GROUP, EC_group_p224) {
60  out->curve_name = NID_secp224r1;
61  out->comment = "NIST P-224";
62  // 1.3.132.0.33
63  static const uint8_t kOIDP224[] = {0x2b, 0x81, 0x04, 0x00, 0x21};
64  OPENSSL_memcpy(out->oid, kOIDP224, sizeof(kOIDP224));
65  out->oid_len = sizeof(kOIDP224);
66
67  ec_group_init_static_mont(&out->field, OPENSSL_ARRAY_SIZE(kP224Field),
68                            kP224Field, kP224FieldRR, kP224FieldN0);
69  ec_group_init_static_mont(&out->order, OPENSSL_ARRAY_SIZE(kP224Order),
70                            kP224Order, kP224OrderRR, kP224OrderN0);
71
72#if defined(BORINGSSL_HAS_UINT128) && !defined(OPENSSL_SMALL)
73  out->meth = EC_GFp_nistp224_method();
74  OPENSSL_memcpy(out->generator.raw.X.words, kP224GX, sizeof(kP224GX));
75  OPENSSL_memcpy(out->generator.raw.Y.words, kP224GY, sizeof(kP224GY));
76  out->generator.raw.Z.words[0] = 1;
77  OPENSSL_memcpy(out->b.words, kP224B, sizeof(kP224B));
78#else
79  out->meth = EC_GFp_mont_method();
80  OPENSSL_memcpy(out->generator.raw.X.words, kP224MontGX, sizeof(kP224MontGX));
81  OPENSSL_memcpy(out->generator.raw.Y.words, kP224MontGY, sizeof(kP224MontGY));
82  OPENSSL_memcpy(out->generator.raw.Z.words, kP224FieldR, sizeof(kP224FieldR));
83  OPENSSL_memcpy(out->b.words, kP224MontB, sizeof(kP224MontB));
84#endif
85  out->generator.group = out;
86
87  ec_group_set_a_minus3(out);
88  out->has_order = 1;
89  out->field_greater_than_order = 1;
90}
91
92DEFINE_METHOD_FUNCTION(EC_GROUP, EC_group_p256) {
93  out->curve_name = NID_X9_62_prime256v1;
94  out->comment = "NIST P-256";
95  // 1.2.840.10045.3.1.7
96  static const uint8_t kOIDP256[] = {0x2a, 0x86, 0x48, 0xce,
97                                     0x3d, 0x03, 0x01, 0x07};
98  OPENSSL_memcpy(out->oid, kOIDP256, sizeof(kOIDP256));
99  out->oid_len = sizeof(kOIDP256);
100
101  ec_group_init_static_mont(&out->field, OPENSSL_ARRAY_SIZE(kP256Field),
102                            kP256Field, kP256FieldRR, kP256FieldN0);
103  ec_group_init_static_mont(&out->order, OPENSSL_ARRAY_SIZE(kP256Order),
104                            kP256Order, kP256OrderRR, kP256OrderN0);
105
106#if !defined(OPENSSL_NO_ASM) &&                              \
107    (defined(OPENSSL_X86_64) || defined(OPENSSL_AARCH64)) && \
108    !defined(OPENSSL_SMALL)
109  out->meth = EC_GFp_nistz256_method();
110#else
111  out->meth = EC_GFp_nistp256_method();
112#endif
113  out->generator.group = out;
114  OPENSSL_memcpy(out->generator.raw.X.words, kP256MontGX, sizeof(kP256MontGX));
115  OPENSSL_memcpy(out->generator.raw.Y.words, kP256MontGY, sizeof(kP256MontGY));
116  OPENSSL_memcpy(out->generator.raw.Z.words, kP256FieldR, sizeof(kP256FieldR));
117  OPENSSL_memcpy(out->b.words, kP256MontB, sizeof(kP256MontB));
118
119  ec_group_set_a_minus3(out);
120  out->has_order = 1;
121  out->field_greater_than_order = 1;
122}
123
124DEFINE_METHOD_FUNCTION(EC_GROUP, EC_group_p384) {
125  out->curve_name = NID_secp384r1;
126  out->comment = "NIST P-384";
127  // 1.3.132.0.34
128  static const uint8_t kOIDP384[] = {0x2b, 0x81, 0x04, 0x00, 0x22};
129  OPENSSL_memcpy(out->oid, kOIDP384, sizeof(kOIDP384));
130  out->oid_len = sizeof(kOIDP384);
131
132  ec_group_init_static_mont(&out->field, OPENSSL_ARRAY_SIZE(kP384Field),
133                            kP384Field, kP384FieldRR, kP384FieldN0);
134  ec_group_init_static_mont(&out->order, OPENSSL_ARRAY_SIZE(kP384Order),
135                            kP384Order, kP384OrderRR, kP384OrderN0);
136
137  out->meth = EC_GFp_mont_method();
138  out->generator.group = out;
139  OPENSSL_memcpy(out->generator.raw.X.words, kP384MontGX, sizeof(kP384MontGX));
140  OPENSSL_memcpy(out->generator.raw.Y.words, kP384MontGY, sizeof(kP384MontGY));
141  OPENSSL_memcpy(out->generator.raw.Z.words, kP384FieldR, sizeof(kP384FieldR));
142  OPENSSL_memcpy(out->b.words, kP384MontB, sizeof(kP384MontB));
143
144  ec_group_set_a_minus3(out);
145  out->has_order = 1;
146  out->field_greater_than_order = 1;
147}
148
149DEFINE_METHOD_FUNCTION(EC_GROUP, EC_group_p521) {
150  out->curve_name = NID_secp521r1;
151  out->comment = "NIST P-521";
152  // 1.3.132.0.35
153  static const uint8_t kOIDP521[] = {0x2b, 0x81, 0x04, 0x00, 0x23};
154  OPENSSL_memcpy(out->oid, kOIDP521, sizeof(kOIDP521));
155  out->oid_len = sizeof(kOIDP521);
156
157  ec_group_init_static_mont(&out->field, OPENSSL_ARRAY_SIZE(kP521Field),
158                            kP521Field, kP521FieldRR, kP521FieldN0);
159  ec_group_init_static_mont(&out->order, OPENSSL_ARRAY_SIZE(kP521Order),
160                            kP521Order, kP521OrderRR, kP521OrderN0);
161
162  out->meth = EC_GFp_mont_method();
163  out->generator.group = out;
164  OPENSSL_memcpy(out->generator.raw.X.words, kP521MontGX, sizeof(kP521MontGX));
165  OPENSSL_memcpy(out->generator.raw.Y.words, kP521MontGY, sizeof(kP521MontGY));
166  OPENSSL_memcpy(out->generator.raw.Z.words, kP521FieldR, sizeof(kP521FieldR));
167  OPENSSL_memcpy(out->b.words, kP521MontB, sizeof(kP521MontB));
168
169  ec_group_set_a_minus3(out);
170  out->has_order = 1;
171  out->field_greater_than_order = 1;
172}
173
174EC_GROUP *EC_GROUP_new_curve_GFp(const BIGNUM *p, const BIGNUM *a,
175                                 const BIGNUM *b, BN_CTX *ctx) {
176  if (BN_num_bytes(p) > EC_MAX_BYTES) {
177    OPENSSL_PUT_ERROR(EC, EC_R_INVALID_FIELD);
178    return nullptr;
179  }
180
181  bssl::UniquePtr<BN_CTX> new_ctx;
182  if (ctx == nullptr) {
183    new_ctx.reset(BN_CTX_new());
184    if (new_ctx == nullptr) {
185      return nullptr;
186    }
187    ctx = new_ctx.get();
188  }
189
190  // Historically, |a| and |b| were not required to be fully reduced.
191  // TODO(davidben): Can this be removed?
192  bssl::BN_CTXScope scope(ctx);
193  BIGNUM *a_reduced = BN_CTX_get(ctx);
194  BIGNUM *b_reduced = BN_CTX_get(ctx);
195  if (a_reduced == nullptr || b_reduced == nullptr ||
196      !BN_nnmod(a_reduced, a, p, ctx) ||  //
197      !BN_nnmod(b_reduced, b, p, ctx)) {
198    return nullptr;
199  }
200
201  bssl::UniquePtr<EC_GROUP> ret(
202      reinterpret_cast<EC_GROUP *>(OPENSSL_zalloc(sizeof(EC_GROUP))));
203  if (ret == nullptr) {
204    return nullptr;
205  }
206  ret->references = 1;
207  ret->meth = EC_GFp_mont_method();
208  bn_mont_ctx_init(&ret->field);
209  bn_mont_ctx_init(&ret->order);
210  ret->generator.group = ret.get();
211  if (!ec_GFp_simple_group_set_curve(ret.get(), p, a_reduced, b_reduced, ctx)) {
212    return nullptr;
213  }
214
215  return ret.release();
216}
217
218int EC_GROUP_set_generator(EC_GROUP *group, const EC_POINT *generator,
219                           const BIGNUM *order, const BIGNUM *cofactor) {
220  if (group->curve_name != NID_undef || group->has_order ||
221      generator->group != group) {
222    // |EC_GROUP_set_generator| may only be used with |EC_GROUP|s returned by
223    // |EC_GROUP_new_curve_GFp| and may only used once on each group.
224    // |generator| must have been created from |EC_GROUP_new_curve_GFp|, not a
225    // copy, so that |generator->group->generator| is set correctly.
226    OPENSSL_PUT_ERROR(EC, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
227    return 0;
228  }
229
230  if (BN_num_bytes(order) > EC_MAX_BYTES) {
231    OPENSSL_PUT_ERROR(EC, EC_R_INVALID_GROUP_ORDER);
232    return 0;
233  }
234
235  // Require a cofactor of one for custom curves, which implies prime order.
236  if (!BN_is_one(cofactor)) {
237    OPENSSL_PUT_ERROR(EC, EC_R_INVALID_COFACTOR);
238    return 0;
239  }
240
241  // Require that p < 2×order. This simplifies some ECDSA operations.
242  //
243  // Note any curve which did not satisfy this must have been invalid or use a
244  // tiny prime (less than 17). See the proof in |field_element_to_scalar| in
245  // the ECDSA implementation.
246  bssl::UniquePtr<BIGNUM> tmp(BN_new());
247  if (tmp == nullptr || !BN_lshift1(tmp.get(), order)) {
248    return 0;
249  }
250  if (BN_cmp(tmp.get(), &group->field.N) <= 0) {
251    OPENSSL_PUT_ERROR(EC, EC_R_INVALID_GROUP_ORDER);
252    return 0;
253  }
254
255  EC_AFFINE affine;
256  if (!ec_jacobian_to_affine(group, &affine, &generator->raw) ||
257      !BN_MONT_CTX_set(&group->order, order, NULL)) {
258    return 0;
259  }
260
261  group->field_greater_than_order = BN_cmp(&group->field.N, order) > 0;
262  group->generator.raw.X = affine.X;
263  group->generator.raw.Y = affine.Y;
264  // |raw.Z| was set to 1 by |EC_GROUP_new_curve_GFp|.
265  group->has_order = 1;
266  return 1;
267}
268
269EC_GROUP *EC_GROUP_new_by_curve_name(int nid) {
270  switch (nid) {
271    case NID_secp224r1:
272      return (EC_GROUP *)EC_group_p224();
273    case NID_X9_62_prime256v1:
274      return (EC_GROUP *)EC_group_p256();
275    case NID_secp384r1:
276      return (EC_GROUP *)EC_group_p384();
277    case NID_secp521r1:
278      return (EC_GROUP *)EC_group_p521();
279    default:
280      OPENSSL_PUT_ERROR(EC, EC_R_UNKNOWN_GROUP);
281      return NULL;
282  }
283}
284
285void EC_GROUP_free(EC_GROUP *group) {
286  if (group == NULL ||
287      // Built-in curves are static.
288      group->curve_name != NID_undef ||
289      !CRYPTO_refcount_dec_and_test_zero(&group->references)) {
290    return;
291  }
292
293  bn_mont_ctx_cleanup(&group->order);
294  bn_mont_ctx_cleanup(&group->field);
295  OPENSSL_free(group);
296}
297
298EC_GROUP *EC_GROUP_dup(const EC_GROUP *a) {
299  if (a == NULL ||
300      // Built-in curves are static.
301      a->curve_name != NID_undef) {
302    return (EC_GROUP *)a;
303  }
304
305  // Groups are logically immutable (but for |EC_GROUP_set_generator| which must
306  // be called early on), so we simply take a reference.
307  EC_GROUP *group = (EC_GROUP *)a;
308  CRYPTO_refcount_inc(&group->references);
309  return group;
310}
311
312int EC_GROUP_cmp(const EC_GROUP *a, const EC_GROUP *b, BN_CTX *ignored) {
313  // Note this function returns 0 if equal and non-zero otherwise.
314  if (a == b) {
315    return 0;
316  }
317  if (a->curve_name != b->curve_name) {
318    return 1;
319  }
320  if (a->curve_name != NID_undef) {
321    // Built-in curves may be compared by curve name alone.
322    return 0;
323  }
324
325  // |a| and |b| are both custom curves. We compare the entire curve
326  // structure. If |a| or |b| is incomplete (due to legacy OpenSSL mistakes,
327  // custom curve construction is sadly done in two parts) but otherwise not the
328  // same object, we consider them always unequal.
329  return a->meth != b->meth ||  //
330         !a->has_order || !b->has_order ||
331         BN_cmp(&a->order.N, &b->order.N) != 0 ||
332         BN_cmp(&a->field.N, &b->field.N) != 0 ||
333         !ec_felem_equal(a, &a->a, &b->a) ||  //
334         !ec_felem_equal(a, &a->b, &b->b) ||
335         !ec_GFp_simple_points_equal(a, &a->generator.raw, &b->generator.raw);
336}
337
338const EC_POINT *EC_GROUP_get0_generator(const EC_GROUP *group) {
339  return group->has_order ? &group->generator : NULL;
340}
341
342const BIGNUM *EC_GROUP_get0_order(const EC_GROUP *group) {
343  assert(group->has_order);
344  return &group->order.N;
345}
346
347int EC_GROUP_get_order(const EC_GROUP *group, BIGNUM *order, BN_CTX *ctx) {
348  if (BN_copy(order, EC_GROUP_get0_order(group)) == NULL) {
349    return 0;
350  }
351  return 1;
352}
353
354int EC_GROUP_order_bits(const EC_GROUP *group) {
355  return BN_num_bits(&group->order.N);
356}
357
358int EC_GROUP_get_cofactor(const EC_GROUP *group, BIGNUM *cofactor,
359                          BN_CTX *ctx) {
360  // All |EC_GROUP|s have cofactor 1.
361  return BN_set_word(cofactor, 1);
362}
363
364int EC_GROUP_get_curve_GFp(const EC_GROUP *group, BIGNUM *out_p, BIGNUM *out_a,
365                           BIGNUM *out_b, BN_CTX *ctx) {
366  return ec_GFp_simple_group_get_curve(group, out_p, out_a, out_b);
367}
368
369int EC_GROUP_get_curve_name(const EC_GROUP *group) { return group->curve_name; }
370
371unsigned EC_GROUP_get_degree(const EC_GROUP *group) {
372  return BN_num_bits(&group->field.N);
373}
374
375const char *EC_curve_nid2nist(int nid) {
376  switch (nid) {
377    case NID_secp224r1:
378      return "P-224";
379    case NID_X9_62_prime256v1:
380      return "P-256";
381    case NID_secp384r1:
382      return "P-384";
383    case NID_secp521r1:
384      return "P-521";
385  }
386  return NULL;
387}
388
389int EC_curve_nist2nid(const char *name) {
390  if (strcmp(name, "P-224") == 0) {
391    return NID_secp224r1;
392  }
393  if (strcmp(name, "P-256") == 0) {
394    return NID_X9_62_prime256v1;
395  }
396  if (strcmp(name, "P-384") == 0) {
397    return NID_secp384r1;
398  }
399  if (strcmp(name, "P-521") == 0) {
400    return NID_secp521r1;
401  }
402  return NID_undef;
403}
404
405EC_POINT *EC_POINT_new(const EC_GROUP *group) {
406  if (group == NULL) {
407    OPENSSL_PUT_ERROR(EC, ERR_R_PASSED_NULL_PARAMETER);
408    return NULL;
409  }
410
411  EC_POINT *ret = reinterpret_cast<EC_POINT *>(OPENSSL_malloc(sizeof *ret));
412  if (ret == NULL) {
413    return NULL;
414  }
415
416  ret->group = EC_GROUP_dup(group);
417  ec_GFp_simple_point_init(&ret->raw);
418  return ret;
419}
420
421static void ec_point_free(EC_POINT *point, int free_group) {
422  if (!point) {
423    return;
424  }
425  if (free_group) {
426    EC_GROUP_free(point->group);
427  }
428  OPENSSL_free(point);
429}
430
431void EC_POINT_free(EC_POINT *point) {
432  ec_point_free(point, 1 /* free group */);
433}
434
435void EC_POINT_clear_free(EC_POINT *point) { EC_POINT_free(point); }
436
437int EC_POINT_copy(EC_POINT *dest, const EC_POINT *src) {
438  if (EC_GROUP_cmp(dest->group, src->group, NULL) != 0) {
439    OPENSSL_PUT_ERROR(EC, EC_R_INCOMPATIBLE_OBJECTS);
440    return 0;
441  }
442  if (dest == src) {
443    return 1;
444  }
445  ec_GFp_simple_point_copy(&dest->raw, &src->raw);
446  return 1;
447}
448
449EC_POINT *EC_POINT_dup(const EC_POINT *a, const EC_GROUP *group) {
450  if (a == NULL) {
451    return NULL;
452  }
453
454  EC_POINT *ret = EC_POINT_new(group);
455  if (ret == NULL || !EC_POINT_copy(ret, a)) {
456    EC_POINT_free(ret);
457    return NULL;
458  }
459
460  return ret;
461}
462
463int EC_POINT_set_to_infinity(const EC_GROUP *group, EC_POINT *point) {
464  if (EC_GROUP_cmp(group, point->group, NULL) != 0) {
465    OPENSSL_PUT_ERROR(EC, EC_R_INCOMPATIBLE_OBJECTS);
466    return 0;
467  }
468  ec_GFp_simple_point_set_to_infinity(group, &point->raw);
469  return 1;
470}
471
472int EC_POINT_is_at_infinity(const EC_GROUP *group, const EC_POINT *point) {
473  if (EC_GROUP_cmp(group, point->group, NULL) != 0) {
474    OPENSSL_PUT_ERROR(EC, EC_R_INCOMPATIBLE_OBJECTS);
475    return 0;
476  }
477  return ec_GFp_simple_is_at_infinity(group, &point->raw);
478}
479
480int EC_POINT_is_on_curve(const EC_GROUP *group, const EC_POINT *point,
481                         BN_CTX *ctx) {
482  if (EC_GROUP_cmp(group, point->group, NULL) != 0) {
483    OPENSSL_PUT_ERROR(EC, EC_R_INCOMPATIBLE_OBJECTS);
484    return 0;
485  }
486  return ec_GFp_simple_is_on_curve(group, &point->raw);
487}
488
489int EC_POINT_cmp(const EC_GROUP *group, const EC_POINT *a, const EC_POINT *b,
490                 BN_CTX *ctx) {
491  if (EC_GROUP_cmp(group, a->group, NULL) != 0 ||
492      EC_GROUP_cmp(group, b->group, NULL) != 0) {
493    OPENSSL_PUT_ERROR(EC, EC_R_INCOMPATIBLE_OBJECTS);
494    return -1;
495  }
496
497  // Note |EC_POINT_cmp| returns zero for equality and non-zero for inequality.
498  return ec_GFp_simple_points_equal(group, &a->raw, &b->raw) ? 0 : 1;
499}
500
501int EC_POINT_get_affine_coordinates_GFp(const EC_GROUP *group,
502                                        const EC_POINT *point, BIGNUM *x,
503                                        BIGNUM *y, BN_CTX *ctx) {
504  if (group->meth->point_get_affine_coordinates == 0) {
505    OPENSSL_PUT_ERROR(EC, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
506    return 0;
507  }
508  if (EC_GROUP_cmp(group, point->group, NULL) != 0) {
509    OPENSSL_PUT_ERROR(EC, EC_R_INCOMPATIBLE_OBJECTS);
510    return 0;
511  }
512  EC_FELEM x_felem, y_felem;
513  if (!group->meth->point_get_affine_coordinates(group, &point->raw,
514                                                 x == NULL ? NULL : &x_felem,
515                                                 y == NULL ? NULL : &y_felem) ||
516      (x != NULL && !ec_felem_to_bignum(group, x, &x_felem)) ||
517      (y != NULL && !ec_felem_to_bignum(group, y, &y_felem))) {
518    return 0;
519  }
520  return 1;
521}
522
523int EC_POINT_get_affine_coordinates(const EC_GROUP *group,
524                                    const EC_POINT *point, BIGNUM *x, BIGNUM *y,
525                                    BN_CTX *ctx) {
526  return EC_POINT_get_affine_coordinates_GFp(group, point, x, y, ctx);
527}
528
529void ec_affine_to_jacobian(const EC_GROUP *group, EC_JACOBIAN *out,
530                           const EC_AFFINE *p) {
531  out->X = p->X;
532  out->Y = p->Y;
533  out->Z = *ec_felem_one(group);
534}
535
536int ec_jacobian_to_affine(const EC_GROUP *group, EC_AFFINE *out,
537                          const EC_JACOBIAN *p) {
538  return group->meth->point_get_affine_coordinates(group, p, &out->X, &out->Y);
539}
540
541int ec_jacobian_to_affine_batch(const EC_GROUP *group, EC_AFFINE *out,
542                                const EC_JACOBIAN *in, size_t num) {
543  if (group->meth->jacobian_to_affine_batch == NULL) {
544    OPENSSL_PUT_ERROR(EC, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
545    return 0;
546  }
547  return group->meth->jacobian_to_affine_batch(group, out, in, num);
548}
549
550int ec_point_set_affine_coordinates(const EC_GROUP *group, EC_AFFINE *out,
551                                    const EC_FELEM *x, const EC_FELEM *y) {
552  void (*const felem_mul)(const EC_GROUP *, EC_FELEM *r, const EC_FELEM *a,
553                          const EC_FELEM *b) = group->meth->felem_mul;
554  void (*const felem_sqr)(const EC_GROUP *, EC_FELEM *r, const EC_FELEM *a) =
555      group->meth->felem_sqr;
556
557  // Check if the point is on the curve.
558  EC_FELEM lhs, rhs;
559  felem_sqr(group, &lhs, y);                   // lhs = y^2
560  felem_sqr(group, &rhs, x);                   // rhs = x^2
561  ec_felem_add(group, &rhs, &rhs, &group->a);  // rhs = x^2 + a
562  felem_mul(group, &rhs, &rhs, x);             // rhs = x^3 + ax
563  ec_felem_add(group, &rhs, &rhs, &group->b);  // rhs = x^3 + ax + b
564  if (!ec_felem_equal(group, &lhs, &rhs)) {
565    OPENSSL_PUT_ERROR(EC, EC_R_POINT_IS_NOT_ON_CURVE);
566    // In the event of an error, defend against the caller not checking the
567    // return value by setting a known safe value. Note this may not be possible
568    // if the caller is in the process of constructing an arbitrary group and
569    // the generator is missing.
570    if (group->has_order) {
571      out->X = group->generator.raw.X;
572      out->Y = group->generator.raw.Y;
573    }
574    return 0;
575  }
576
577  out->X = *x;
578  out->Y = *y;
579  return 1;
580}
581
582int EC_POINT_set_affine_coordinates_GFp(const EC_GROUP *group, EC_POINT *point,
583                                        const BIGNUM *x, const BIGNUM *y,
584                                        BN_CTX *ctx) {
585  if (EC_GROUP_cmp(group, point->group, NULL) != 0) {
586    OPENSSL_PUT_ERROR(EC, EC_R_INCOMPATIBLE_OBJECTS);
587    return 0;
588  }
589
590  if (x == NULL || y == NULL) {
591    OPENSSL_PUT_ERROR(EC, ERR_R_PASSED_NULL_PARAMETER);
592    return 0;
593  }
594
595  EC_FELEM x_felem, y_felem;
596  EC_AFFINE affine;
597  if (!ec_bignum_to_felem(group, &x_felem, x) ||
598      !ec_bignum_to_felem(group, &y_felem, y) ||
599      !ec_point_set_affine_coordinates(group, &affine, &x_felem, &y_felem)) {
600    // In the event of an error, defend against the caller not checking the
601    // return value by setting a known safe value.
602    ec_set_to_safe_point(group, &point->raw);
603    return 0;
604  }
605
606  ec_affine_to_jacobian(group, &point->raw, &affine);
607  return 1;
608}
609
610int EC_POINT_set_affine_coordinates(const EC_GROUP *group, EC_POINT *point,
611                                    const BIGNUM *x, const BIGNUM *y,
612                                    BN_CTX *ctx) {
613  return EC_POINT_set_affine_coordinates_GFp(group, point, x, y, ctx);
614}
615
616int EC_POINT_add(const EC_GROUP *group, EC_POINT *r, const EC_POINT *a,
617                 const EC_POINT *b, BN_CTX *ctx) {
618  if (EC_GROUP_cmp(group, r->group, NULL) != 0 ||
619      EC_GROUP_cmp(group, a->group, NULL) != 0 ||
620      EC_GROUP_cmp(group, b->group, NULL) != 0) {
621    OPENSSL_PUT_ERROR(EC, EC_R_INCOMPATIBLE_OBJECTS);
622    return 0;
623  }
624  group->meth->add(group, &r->raw, &a->raw, &b->raw);
625  return 1;
626}
627
628int EC_POINT_dbl(const EC_GROUP *group, EC_POINT *r, const EC_POINT *a,
629                 BN_CTX *ctx) {
630  if (EC_GROUP_cmp(group, r->group, NULL) != 0 ||
631      EC_GROUP_cmp(group, a->group, NULL) != 0) {
632    OPENSSL_PUT_ERROR(EC, EC_R_INCOMPATIBLE_OBJECTS);
633    return 0;
634  }
635  group->meth->dbl(group, &r->raw, &a->raw);
636  return 1;
637}
638
639
640int EC_POINT_invert(const EC_GROUP *group, EC_POINT *a, BN_CTX *ctx) {
641  if (EC_GROUP_cmp(group, a->group, NULL) != 0) {
642    OPENSSL_PUT_ERROR(EC, EC_R_INCOMPATIBLE_OBJECTS);
643    return 0;
644  }
645  ec_GFp_simple_invert(group, &a->raw);
646  return 1;
647}
648
649static int arbitrary_bignum_to_scalar(const EC_GROUP *group, EC_SCALAR *out,
650                                      const BIGNUM *in, BN_CTX *ctx) {
651  if (ec_bignum_to_scalar(group, out, in)) {
652    return 1;
653  }
654
655  ERR_clear_error();
656
657  // This is an unusual input, so we do not guarantee constant-time processing.
658  bssl::BN_CTXScope scope(ctx);
659  BIGNUM *tmp = BN_CTX_get(ctx);
660  return tmp != nullptr && BN_nnmod(tmp, in, EC_GROUP_get0_order(group), ctx) &&
661         ec_bignum_to_scalar(group, out, tmp);
662}
663
664int ec_point_mul_no_self_test(const EC_GROUP *group, EC_POINT *r,
665                              const BIGNUM *g_scalar, const EC_POINT *p,
666                              const BIGNUM *p_scalar, BN_CTX *ctx) {
667  // Previously, this function set |r| to the point at infinity if there was
668  // nothing to multiply. But, nobody should be calling this function with
669  // nothing to multiply in the first place.
670  if ((g_scalar == NULL && p_scalar == NULL) ||
671      (p == NULL) != (p_scalar == NULL)) {
672    OPENSSL_PUT_ERROR(EC, ERR_R_PASSED_NULL_PARAMETER);
673    return 0;
674  }
675
676  if (EC_GROUP_cmp(group, r->group, NULL) != 0 ||
677      (p != NULL && EC_GROUP_cmp(group, p->group, NULL) != 0)) {
678    OPENSSL_PUT_ERROR(EC, EC_R_INCOMPATIBLE_OBJECTS);
679    return 0;
680  }
681
682  bssl::UniquePtr<BN_CTX> new_ctx;
683  if (ctx == NULL) {
684    new_ctx.reset(BN_CTX_new());
685    if (new_ctx == NULL) {
686      return 0;
687    }
688    ctx = new_ctx.get();
689  }
690
691  // If both |g_scalar| and |p_scalar| are non-NULL,
692  // |ec_point_mul_scalar_public| would share the doublings between the two
693  // products, which would be more efficient. However, we conservatively assume
694  // the caller needs a constant-time operation. (ECDSA verification does not
695  // use this function.)
696  //
697  // Previously, the low-level constant-time multiplication function aligned
698  // with this function's calling convention, but this was misleading. Curves
699  // which combined the two multiplications did not avoid the doubling case
700  // in the incomplete addition formula and were not constant-time.
701
702  if (g_scalar != NULL) {
703    EC_SCALAR scalar;
704    if (!arbitrary_bignum_to_scalar(group, &scalar, g_scalar, ctx) ||
705        !ec_point_mul_scalar_base(group, &r->raw, &scalar)) {
706      return 0;
707    }
708  }
709
710  if (p_scalar != NULL) {
711    EC_SCALAR scalar;
712    EC_JACOBIAN tmp;
713    if (!arbitrary_bignum_to_scalar(group, &scalar, p_scalar, ctx) ||
714        !ec_point_mul_scalar(group, &tmp, &p->raw, &scalar)) {
715      return 0;
716    }
717    if (g_scalar == NULL) {
718      OPENSSL_memcpy(&r->raw, &tmp, sizeof(EC_JACOBIAN));
719    } else {
720      group->meth->add(group, &r->raw, &r->raw, &tmp);
721    }
722  }
723
724  return 1;
725}
726
727int EC_POINT_mul(const EC_GROUP *group, EC_POINT *r, const BIGNUM *g_scalar,
728                 const EC_POINT *p, const BIGNUM *p_scalar, BN_CTX *ctx) {
729  boringssl_ensure_ecc_self_test();
730
731  return ec_point_mul_no_self_test(group, r, g_scalar, p, p_scalar, ctx);
732}
733
734int ec_point_mul_scalar_public(const EC_GROUP *group, EC_JACOBIAN *r,
735                               const EC_SCALAR *g_scalar, const EC_JACOBIAN *p,
736                               const EC_SCALAR *p_scalar) {
737  if (g_scalar == NULL || p_scalar == NULL || p == NULL) {
738    OPENSSL_PUT_ERROR(EC, ERR_R_PASSED_NULL_PARAMETER);
739    return 0;
740  }
741
742  if (group->meth->mul_public == NULL) {
743    return group->meth->mul_public_batch(group, r, g_scalar, p, p_scalar, 1);
744  }
745
746  group->meth->mul_public(group, r, g_scalar, p, p_scalar);
747  return 1;
748}
749
750int ec_point_mul_scalar_public_batch(const EC_GROUP *group, EC_JACOBIAN *r,
751                                     const EC_SCALAR *g_scalar,
752                                     const EC_JACOBIAN *points,
753                                     const EC_SCALAR *scalars, size_t num) {
754  if (group->meth->mul_public_batch == NULL) {
755    OPENSSL_PUT_ERROR(EC, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
756    return 0;
757  }
758
759  return group->meth->mul_public_batch(group, r, g_scalar, points, scalars,
760                                       num);
761}
762
763int ec_point_mul_scalar(const EC_GROUP *group, EC_JACOBIAN *r,
764                        const EC_JACOBIAN *p, const EC_SCALAR *scalar) {
765  if (p == NULL || scalar == NULL) {
766    OPENSSL_PUT_ERROR(EC, ERR_R_PASSED_NULL_PARAMETER);
767    return 0;
768  }
769
770  group->meth->mul(group, r, p, scalar);
771
772  // Check the result is on the curve to defend against fault attacks or bugs.
773  // This has negligible cost compared to the multiplication.
774  if (!ec_GFp_simple_is_on_curve(group, r)) {
775    OPENSSL_PUT_ERROR(EC, ERR_R_INTERNAL_ERROR);
776    return 0;
777  }
778
779  return 1;
780}
781
782int ec_point_mul_scalar_base(const EC_GROUP *group, EC_JACOBIAN *r,
783                             const EC_SCALAR *scalar) {
784  if (scalar == NULL) {
785    OPENSSL_PUT_ERROR(EC, ERR_R_PASSED_NULL_PARAMETER);
786    return 0;
787  }
788
789  group->meth->mul_base(group, r, scalar);
790
791  // Check the result is on the curve to defend against fault attacks or bugs.
792  // This has negligible cost compared to the multiplication. This can only
793  // happen on bug or CPU fault, so it okay to leak this. The alternative would
794  // be to proceed with bad data.
795  if (!constant_time_declassify_int(ec_GFp_simple_is_on_curve(group, r))) {
796    OPENSSL_PUT_ERROR(EC, ERR_R_INTERNAL_ERROR);
797    return 0;
798  }
799
800  return 1;
801}
802
803int ec_point_mul_scalar_batch(const EC_GROUP *group, EC_JACOBIAN *r,
804                              const EC_JACOBIAN *p0, const EC_SCALAR *scalar0,
805                              const EC_JACOBIAN *p1, const EC_SCALAR *scalar1,
806                              const EC_JACOBIAN *p2, const EC_SCALAR *scalar2) {
807  if (group->meth->mul_batch == NULL) {
808    OPENSSL_PUT_ERROR(EC, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
809    return 0;
810  }
811
812  group->meth->mul_batch(group, r, p0, scalar0, p1, scalar1, p2, scalar2);
813
814  // Check the result is on the curve to defend against fault attacks or bugs.
815  // This has negligible cost compared to the multiplication.
816  if (!ec_GFp_simple_is_on_curve(group, r)) {
817    OPENSSL_PUT_ERROR(EC, ERR_R_INTERNAL_ERROR);
818    return 0;
819  }
820
821  return 1;
822}
823
824int ec_init_precomp(const EC_GROUP *group, EC_PRECOMP *out,
825                    const EC_JACOBIAN *p) {
826  if (group->meth->init_precomp == NULL) {
827    OPENSSL_PUT_ERROR(EC, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
828    return 0;
829  }
830
831  return group->meth->init_precomp(group, out, p);
832}
833
834int ec_point_mul_scalar_precomp(const EC_GROUP *group, EC_JACOBIAN *r,
835                                const EC_PRECOMP *p0, const EC_SCALAR *scalar0,
836                                const EC_PRECOMP *p1, const EC_SCALAR *scalar1,
837                                const EC_PRECOMP *p2,
838                                const EC_SCALAR *scalar2) {
839  if (group->meth->mul_precomp == NULL) {
840    OPENSSL_PUT_ERROR(EC, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
841    return 0;
842  }
843
844  group->meth->mul_precomp(group, r, p0, scalar0, p1, scalar1, p2, scalar2);
845
846  // Check the result is on the curve to defend against fault attacks or bugs.
847  // This has negligible cost compared to the multiplication.
848  if (!ec_GFp_simple_is_on_curve(group, r)) {
849    OPENSSL_PUT_ERROR(EC, ERR_R_INTERNAL_ERROR);
850    return 0;
851  }
852
853  return 1;
854}
855
856void ec_point_select(const EC_GROUP *group, EC_JACOBIAN *out, BN_ULONG mask,
857                     const EC_JACOBIAN *a, const EC_JACOBIAN *b) {
858  ec_felem_select(group, &out->X, mask, &a->X, &b->X);
859  ec_felem_select(group, &out->Y, mask, &a->Y, &b->Y);
860  ec_felem_select(group, &out->Z, mask, &a->Z, &b->Z);
861}
862
863void ec_affine_select(const EC_GROUP *group, EC_AFFINE *out, BN_ULONG mask,
864                      const EC_AFFINE *a, const EC_AFFINE *b) {
865  ec_felem_select(group, &out->X, mask, &a->X, &b->X);
866  ec_felem_select(group, &out->Y, mask, &a->Y, &b->Y);
867}
868
869void ec_precomp_select(const EC_GROUP *group, EC_PRECOMP *out, BN_ULONG mask,
870                       const EC_PRECOMP *a, const EC_PRECOMP *b) {
871  static_assert(sizeof(out->comb) == sizeof(*out),
872                "out->comb does not span the entire structure");
873  for (size_t i = 0; i < OPENSSL_ARRAY_SIZE(out->comb); i++) {
874    ec_affine_select(group, &out->comb[i], mask, &a->comb[i], &b->comb[i]);
875  }
876}
877
878int ec_cmp_x_coordinate(const EC_GROUP *group, const EC_JACOBIAN *p,
879                        const EC_SCALAR *r) {
880  return group->meth->cmp_x_coordinate(group, p, r);
881}
882
883int ec_get_x_coordinate_as_scalar(const EC_GROUP *group, EC_SCALAR *out,
884                                  const EC_JACOBIAN *p) {
885  uint8_t bytes[EC_MAX_BYTES];
886  size_t len;
887  if (!ec_get_x_coordinate_as_bytes(group, bytes, &len, sizeof(bytes), p)) {
888    return 0;
889  }
890
891  // The x-coordinate is bounded by p, but we need a scalar, bounded by the
892  // order. These may not have the same size. However, we must have p < 2×order,
893  // assuming p is not tiny (p >= 17).
894  //
895  // Thus |bytes| will fit in |order.width + 1| words, and we can reduce by
896  // performing at most one subtraction.
897  //
898  // Proof: We only work with prime order curves, so the number of points on
899  // the curve is the order. Thus Hasse's theorem gives:
900  //
901  //     |order - (p + 1)| <= 2×sqrt(p)
902  //         p + 1 - order <= 2×sqrt(p)
903  //     p + 1 - 2×sqrt(p) <= order
904  //       p + 1 - 2×(p/4)  < order       (p/4 > sqrt(p) for p >= 17)
905  //         p/2 < p/2 + 1  < order
906  //                     p  < 2×order
907  //
908  // Additionally, one can manually check this property for built-in curves. It
909  // is enforced for legacy custom curves in |EC_GROUP_set_generator|.
910  const BIGNUM *order = EC_GROUP_get0_order(group);
911  BN_ULONG words[EC_MAX_WORDS + 1] = {0};
912  bn_big_endian_to_words(words, order->width + 1, bytes, len);
913  bn_reduce_once(out->words, words, /*carry=*/words[order->width], order->d,
914                 order->width);
915  return 1;
916}
917
918int ec_get_x_coordinate_as_bytes(const EC_GROUP *group, uint8_t *out,
919                                 size_t *out_len, size_t max_out,
920                                 const EC_JACOBIAN *p) {
921  size_t len = BN_num_bytes(&group->field.N);
922  assert(len <= EC_MAX_BYTES);
923  if (max_out < len) {
924    OPENSSL_PUT_ERROR(EC, EC_R_BUFFER_TOO_SMALL);
925    return 0;
926  }
927
928  EC_FELEM x;
929  if (!group->meth->point_get_affine_coordinates(group, p, &x, NULL)) {
930    return 0;
931  }
932
933  ec_felem_to_bytes(group, out, out_len, &x);
934  *out_len = len;
935  return 1;
936}
937
938void ec_set_to_safe_point(const EC_GROUP *group, EC_JACOBIAN *out) {
939  if (group->has_order) {
940    ec_GFp_simple_point_copy(out, &group->generator.raw);
941  } else {
942    // The generator can be missing if the caller is in the process of
943    // constructing an arbitrary group. In this case, we give up and use the
944    // point at infinity.
945    ec_GFp_simple_point_set_to_infinity(group, out);
946  }
947}
948
949void EC_GROUP_set_asn1_flag(EC_GROUP *group, int flag) {}
950
951int EC_GROUP_get_asn1_flag(const EC_GROUP *group) {
952  return OPENSSL_EC_NAMED_CURVE;
953}
954
955const EC_METHOD *EC_GROUP_method_of(const EC_GROUP *group) {
956  // This function exists purely to give callers a way to call
957  // |EC_METHOD_get_field_type|. cryptography.io crashes if |EC_GROUP_method_of|
958  // returns NULL, so return some other garbage pointer.
959  return (const EC_METHOD *)0x12340000;
960}
961
962int EC_METHOD_get_field_type(const EC_METHOD *meth) {
963  return NID_X9_62_prime_field;
964}
965
966void EC_GROUP_set_point_conversion_form(EC_GROUP *group,
967                                        point_conversion_form_t form) {
968  if (form != POINT_CONVERSION_UNCOMPRESSED) {
969    abort();
970  }
971}
972