1// Copyright 2002-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_key.h>
17
18#include <string.h>
19
20#include <openssl/ec.h>
21#include <openssl/ecdsa.h>
22#include <openssl/engine.h>
23#include <openssl/err.h>
24#include <openssl/ex_data.h>
25#include <openssl/mem.h>
26
27#include "../../internal.h"
28#include "../bcm_interface.h"
29#include "../delocate.h"
30#include "../ecdsa/internal.h"
31#include "../service_indicator/internal.h"
32#include "internal.h"
33
34
35DEFINE_STATIC_EX_DATA_CLASS(g_ec_ex_data_class)
36
37static EC_WRAPPED_SCALAR *ec_wrapped_scalar_new(const EC_GROUP *group) {
38  EC_WRAPPED_SCALAR *wrapped = reinterpret_cast<EC_WRAPPED_SCALAR *>(
39      OPENSSL_zalloc(sizeof(EC_WRAPPED_SCALAR)));
40  if (wrapped == NULL) {
41    return NULL;
42  }
43
44  wrapped->bignum.d = wrapped->scalar.words;
45  wrapped->bignum.width = group->order.N.width;
46  wrapped->bignum.dmax = group->order.N.width;
47  wrapped->bignum.flags = BN_FLG_STATIC_DATA;
48  return wrapped;
49}
50
51static void ec_wrapped_scalar_free(EC_WRAPPED_SCALAR *scalar) {
52  OPENSSL_free(scalar);
53}
54
55EC_KEY *EC_KEY_new(void) { return EC_KEY_new_method(NULL); }
56
57EC_KEY *EC_KEY_new_method(const ENGINE *engine) {
58  EC_KEY *ret = reinterpret_cast<EC_KEY *>(OPENSSL_zalloc(sizeof(EC_KEY)));
59  if (ret == NULL) {
60    return NULL;
61  }
62
63  if (engine) {
64    ret->ecdsa_meth = ENGINE_get_ECDSA_method(engine);
65  }
66  if (ret->ecdsa_meth) {
67    METHOD_ref(ret->ecdsa_meth);
68  }
69
70  ret->conv_form = POINT_CONVERSION_UNCOMPRESSED;
71  ret->references = 1;
72
73  CRYPTO_new_ex_data(&ret->ex_data);
74
75  if (ret->ecdsa_meth && ret->ecdsa_meth->init && !ret->ecdsa_meth->init(ret)) {
76    CRYPTO_free_ex_data(g_ec_ex_data_class_bss_get(), &ret->ex_data);
77    if (ret->ecdsa_meth) {
78      METHOD_unref(ret->ecdsa_meth);
79    }
80    OPENSSL_free(ret);
81    return NULL;
82  }
83
84  return ret;
85}
86
87EC_KEY *EC_KEY_new_by_curve_name(int nid) {
88  EC_KEY *ret = EC_KEY_new();
89  if (ret == NULL) {
90    return NULL;
91  }
92  ret->group = EC_GROUP_new_by_curve_name(nid);
93  if (ret->group == NULL) {
94    EC_KEY_free(ret);
95    return NULL;
96  }
97  return ret;
98}
99
100void EC_KEY_free(EC_KEY *r) {
101  if (r == NULL) {
102    return;
103  }
104
105  if (!CRYPTO_refcount_dec_and_test_zero(&r->references)) {
106    return;
107  }
108
109  if (r->ecdsa_meth) {
110    if (r->ecdsa_meth->finish) {
111      r->ecdsa_meth->finish(r);
112    }
113    METHOD_unref(r->ecdsa_meth);
114  }
115
116  CRYPTO_free_ex_data(g_ec_ex_data_class_bss_get(), &r->ex_data);
117
118  EC_GROUP_free(r->group);
119  EC_POINT_free(r->pub_key);
120  ec_wrapped_scalar_free(r->priv_key);
121
122  OPENSSL_free(r);
123}
124
125EC_KEY *EC_KEY_dup(const EC_KEY *src) {
126  if (src == NULL) {
127    OPENSSL_PUT_ERROR(EC, ERR_R_PASSED_NULL_PARAMETER);
128    return NULL;
129  }
130
131  EC_KEY *ret = EC_KEY_new();
132  if (ret == NULL) {
133    return NULL;
134  }
135
136  if ((src->group != NULL && !EC_KEY_set_group(ret, src->group)) ||
137      (src->pub_key != NULL && !EC_KEY_set_public_key(ret, src->pub_key)) ||
138      (src->priv_key != NULL &&
139       !EC_KEY_set_private_key(ret, EC_KEY_get0_private_key(src)))) {
140    EC_KEY_free(ret);
141    return NULL;
142  }
143
144  ret->enc_flag = src->enc_flag;
145  ret->conv_form = src->conv_form;
146  return ret;
147}
148
149int EC_KEY_up_ref(EC_KEY *r) {
150  CRYPTO_refcount_inc(&r->references);
151  return 1;
152}
153
154int EC_KEY_is_opaque(const EC_KEY *key) {
155  return key->ecdsa_meth && (key->ecdsa_meth->flags & ECDSA_FLAG_OPAQUE);
156}
157
158const EC_GROUP *EC_KEY_get0_group(const EC_KEY *key) { return key->group; }
159
160int EC_KEY_set_group(EC_KEY *key, const EC_GROUP *group) {
161  // If |key| already has a group, it is an error to switch to another one.
162  if (key->group != NULL) {
163    if (EC_GROUP_cmp(key->group, group, NULL) != 0) {
164      OPENSSL_PUT_ERROR(EC, EC_R_GROUP_MISMATCH);
165      return 0;
166    }
167    return 1;
168  }
169
170  assert(key->priv_key == NULL);
171  assert(key->pub_key == NULL);
172
173  EC_GROUP_free(key->group);
174  key->group = EC_GROUP_dup(group);
175  return key->group != NULL;
176}
177
178const BIGNUM *EC_KEY_get0_private_key(const EC_KEY *key) {
179  return key->priv_key != NULL ? &key->priv_key->bignum : NULL;
180}
181
182int EC_KEY_set_private_key(EC_KEY *key, const BIGNUM *priv_key) {
183  if (key->group == NULL) {
184    OPENSSL_PUT_ERROR(EC, EC_R_MISSING_PARAMETERS);
185    return 0;
186  }
187
188  EC_WRAPPED_SCALAR *scalar = ec_wrapped_scalar_new(key->group);
189  if (scalar == NULL) {
190    return 0;
191  }
192  if (!ec_bignum_to_scalar(key->group, &scalar->scalar, priv_key) ||
193      // Zero is not a valid private key, so it is safe to leak the result of
194      // this comparison.
195      constant_time_declassify_int(
196          ec_scalar_is_zero(key->group, &scalar->scalar))) {
197    OPENSSL_PUT_ERROR(EC, EC_R_INVALID_PRIVATE_KEY);
198    ec_wrapped_scalar_free(scalar);
199    return 0;
200  }
201  ec_wrapped_scalar_free(key->priv_key);
202  key->priv_key = scalar;
203  return 1;
204}
205
206const EC_POINT *EC_KEY_get0_public_key(const EC_KEY *key) {
207  return key->pub_key;
208}
209
210int EC_KEY_set_public_key(EC_KEY *key, const EC_POINT *pub_key) {
211  if (key->group == NULL) {
212    OPENSSL_PUT_ERROR(EC, EC_R_MISSING_PARAMETERS);
213    return 0;
214  }
215
216  if (pub_key != NULL && EC_GROUP_cmp(key->group, pub_key->group, NULL) != 0) {
217    OPENSSL_PUT_ERROR(EC, EC_R_GROUP_MISMATCH);
218    return 0;
219  }
220
221  EC_POINT_free(key->pub_key);
222  key->pub_key = EC_POINT_dup(pub_key, key->group);
223  return (key->pub_key == NULL) ? 0 : 1;
224}
225
226unsigned int EC_KEY_get_enc_flags(const EC_KEY *key) { return key->enc_flag; }
227
228void EC_KEY_set_enc_flags(EC_KEY *key, unsigned int flags) {
229  key->enc_flag = flags;
230}
231
232point_conversion_form_t EC_KEY_get_conv_form(const EC_KEY *key) {
233  return key->conv_form;
234}
235
236void EC_KEY_set_conv_form(EC_KEY *key, point_conversion_form_t cform) {
237  key->conv_form = cform;
238}
239
240int EC_KEY_check_key(const EC_KEY *eckey) {
241  if (!eckey || !eckey->group || !eckey->pub_key) {
242    OPENSSL_PUT_ERROR(EC, ERR_R_PASSED_NULL_PARAMETER);
243    return 0;
244  }
245
246  if (EC_POINT_is_at_infinity(eckey->group, eckey->pub_key)) {
247    OPENSSL_PUT_ERROR(EC, EC_R_POINT_AT_INFINITY);
248    return 0;
249  }
250
251  // Test whether the public key is on the elliptic curve.
252  if (!EC_POINT_is_on_curve(eckey->group, eckey->pub_key, NULL)) {
253    OPENSSL_PUT_ERROR(EC, EC_R_POINT_IS_NOT_ON_CURVE);
254    return 0;
255  }
256
257  // Check the public and private keys match.
258  //
259  // NOTE: this is a FIPS pair-wise consistency check for the ECDH case. See SP
260  // 800-56Ar3, page 36.
261  if (eckey->priv_key != NULL) {
262    EC_JACOBIAN point;
263    if (!ec_point_mul_scalar_base(eckey->group, &point,
264                                  &eckey->priv_key->scalar)) {
265      OPENSSL_PUT_ERROR(EC, ERR_R_EC_LIB);
266      return 0;
267    }
268    // Leaking this comparison only leaks whether |eckey|'s public key was
269    // correct.
270    if (!constant_time_declassify_int(ec_GFp_simple_points_equal(
271            eckey->group, &point, &eckey->pub_key->raw))) {
272      OPENSSL_PUT_ERROR(EC, EC_R_INVALID_PRIVATE_KEY);
273      return 0;
274    }
275  }
276
277  return 1;
278}
279
280int EC_KEY_check_fips(const EC_KEY *key) {
281  int ret = 0;
282  FIPS_service_indicator_lock_state();
283
284  if (!EC_KEY_check_key(key)) {
285    goto end;
286  }
287
288  if (key->priv_key) {
289    uint8_t digest[BCM_SHA256_DIGEST_LENGTH] = {0};
290    uint8_t sig[ECDSA_MAX_FIXED_LEN];
291    size_t sig_len;
292    if (!ecdsa_sign_fixed(digest, sizeof(digest), sig, &sig_len, sizeof(sig),
293                          key)) {
294      goto end;
295    }
296    if (boringssl_fips_break_test("ECDSA_PWCT")) {
297      digest[0] = ~digest[0];
298    }
299    if (!ecdsa_verify_fixed(digest, sizeof(digest), sig, sig_len, key)) {
300      OPENSSL_PUT_ERROR(EC, EC_R_PUBLIC_KEY_VALIDATION_FAILED);
301      goto end;
302    }
303  }
304
305  ret = 1;
306
307end:
308  FIPS_service_indicator_unlock_state();
309  if (ret) {
310    EC_KEY_keygen_verify_service_indicator(key);
311  }
312
313  return ret;
314}
315
316int EC_KEY_set_public_key_affine_coordinates(EC_KEY *key, const BIGNUM *x,
317                                             const BIGNUM *y) {
318  if (!key || !key->group || !x || !y) {
319    OPENSSL_PUT_ERROR(EC, ERR_R_PASSED_NULL_PARAMETER);
320    return 0;
321  }
322
323  bssl::UniquePtr<EC_POINT> point(EC_POINT_new(key->group));
324  if (point == nullptr ||
325      !EC_POINT_set_affine_coordinates_GFp(key->group, point.get(), x, y,
326                                           nullptr) ||
327      !EC_KEY_set_public_key(key, point.get()) ||  //
328      !EC_KEY_check_key(key)) {
329    return 0;
330  }
331
332  return 1;
333}
334
335int EC_KEY_oct2key(EC_KEY *key, const uint8_t *in, size_t len, BN_CTX *ctx) {
336  if (key->group == nullptr) {
337    OPENSSL_PUT_ERROR(EC, EC_R_MISSING_PARAMETERS);
338    return 0;
339  }
340
341  bssl::UniquePtr<EC_POINT> point(EC_POINT_new(key->group));
342  return point != nullptr &&
343         EC_POINT_oct2point(key->group, point.get(), in, len, ctx) &&
344         EC_KEY_set_public_key(key, point.get());
345}
346
347size_t EC_KEY_key2buf(const EC_KEY *key, point_conversion_form_t form,
348                      uint8_t **out_buf, BN_CTX *ctx) {
349  if (key == NULL || key->pub_key == NULL || key->group == NULL) {
350    OPENSSL_PUT_ERROR(EC, EC_R_MISSING_PARAMETERS);
351    return 0;
352  }
353
354  return EC_POINT_point2buf(key->group, key->pub_key, form, out_buf, ctx);
355}
356
357int EC_KEY_oct2priv(EC_KEY *key, const uint8_t *in, size_t len) {
358  if (key->group == NULL) {
359    OPENSSL_PUT_ERROR(EC, EC_R_MISSING_PARAMETERS);
360    return 0;
361  }
362
363  if (len != BN_num_bytes(EC_GROUP_get0_order(key->group))) {
364    OPENSSL_PUT_ERROR(EC, EC_R_DECODE_ERROR);
365    return 0;
366  }
367
368  BIGNUM *priv_key = BN_bin2bn(in, len, NULL);
369  int ok = priv_key != NULL &&  //
370           EC_KEY_set_private_key(key, priv_key);
371  BN_free(priv_key);
372  return ok;
373}
374
375size_t EC_KEY_priv2oct(const EC_KEY *key, uint8_t *out, size_t max_out) {
376  if (key->group == NULL || key->priv_key == NULL) {
377    OPENSSL_PUT_ERROR(EC, EC_R_MISSING_PARAMETERS);
378    return 0;
379  }
380
381  size_t len = BN_num_bytes(EC_GROUP_get0_order(key->group));
382  if (out == NULL) {
383    return len;
384  }
385
386  if (max_out < len) {
387    OPENSSL_PUT_ERROR(EC, EC_R_BUFFER_TOO_SMALL);
388    return 0;
389  }
390
391  size_t bytes_written;
392  ec_scalar_to_bytes(key->group, out, &bytes_written, &key->priv_key->scalar);
393  assert(bytes_written == len);
394  return len;
395}
396
397size_t EC_KEY_priv2buf(const EC_KEY *key, uint8_t **out_buf) {
398  *out_buf = NULL;
399  size_t len = EC_KEY_priv2oct(key, NULL, 0);
400  if (len == 0) {
401    return 0;
402  }
403
404  uint8_t *buf = reinterpret_cast<uint8_t *>(OPENSSL_malloc(len));
405  if (buf == NULL) {
406    return 0;
407  }
408
409  len = EC_KEY_priv2oct(key, buf, len);
410  if (len == 0) {
411    OPENSSL_free(buf);
412    return 0;
413  }
414
415  *out_buf = buf;
416  return len;
417}
418
419int EC_KEY_generate_key(EC_KEY *key) {
420  if (key == NULL || key->group == NULL) {
421    OPENSSL_PUT_ERROR(EC, ERR_R_PASSED_NULL_PARAMETER);
422    return 0;
423  }
424
425  // Check that the group order is FIPS compliant (FIPS 186-4 B.4.2).
426  if (EC_GROUP_order_bits(key->group) < 160) {
427    OPENSSL_PUT_ERROR(EC, EC_R_INVALID_GROUP_ORDER);
428    return 0;
429  }
430
431  static const uint8_t kDefaultAdditionalData[32] = {0};
432  EC_WRAPPED_SCALAR *priv_key = ec_wrapped_scalar_new(key->group);
433  EC_POINT *pub_key = EC_POINT_new(key->group);
434  if (priv_key == NULL || pub_key == NULL ||
435      // Generate the private key by testing candidates (FIPS 186-4 B.4.2).
436      !ec_random_nonzero_scalar(key->group, &priv_key->scalar,
437                                kDefaultAdditionalData) ||
438      !ec_point_mul_scalar_base(key->group, &pub_key->raw, &priv_key->scalar)) {
439    EC_POINT_free(pub_key);
440    ec_wrapped_scalar_free(priv_key);
441    return 0;
442  }
443
444  // The public key is derived from the private key, but it is public.
445  //
446  // TODO(crbug.com/boringssl/677): This isn't quite right. While |pub_key|
447  // represents a public point, it is still in Jacobian form and the exact
448  // Jacobian representation is secret. We need to make it affine first. See
449  // discussion in the bug.
450  CONSTTIME_DECLASSIFY(&pub_key->raw, sizeof(pub_key->raw));
451
452  ec_wrapped_scalar_free(key->priv_key);
453  key->priv_key = priv_key;
454  EC_POINT_free(key->pub_key);
455  key->pub_key = pub_key;
456  return 1;
457}
458
459int EC_KEY_generate_key_fips(EC_KEY *eckey) {
460  if (eckey == NULL || eckey->group == NULL) {
461    OPENSSL_PUT_ERROR(EC, ERR_R_PASSED_NULL_PARAMETER);
462    return 0;
463  }
464
465  boringssl_ensure_ecc_self_test();
466
467  if (EC_KEY_generate_key(eckey) && EC_KEY_check_fips(eckey)) {
468    return 1;
469  }
470
471  EC_POINT_free(eckey->pub_key);
472  ec_wrapped_scalar_free(eckey->priv_key);
473  eckey->pub_key = NULL;
474  eckey->priv_key = NULL;
475  return 0;
476}
477
478int EC_KEY_get_ex_new_index(long argl, void *argp, CRYPTO_EX_unused *unused,
479                            CRYPTO_EX_dup *dup_unused,
480                            CRYPTO_EX_free *free_func) {
481  return CRYPTO_get_ex_new_index_ex(g_ec_ex_data_class_bss_get(), argl, argp,
482                                    free_func);
483}
484
485int EC_KEY_set_ex_data(EC_KEY *d, int idx, void *arg) {
486  return CRYPTO_set_ex_data(&d->ex_data, idx, arg);
487}
488
489void *EC_KEY_get_ex_data(const EC_KEY *d, int idx) {
490  return CRYPTO_get_ex_data(&d->ex_data, idx);
491}
492
493void EC_KEY_set_asn1_flag(EC_KEY *key, int flag) {}
494