GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: crypto/crypto_keys.cc Lines: 721 817 88.2 %
Date: 2022-08-21 04:19:51 Branches: 341 565 60.4 %

Line Branch Exec Source
1
#include "crypto/crypto_keys.h"
2
#include "crypto/crypto_common.h"
3
#include "crypto/crypto_dsa.h"
4
#include "crypto/crypto_ec.h"
5
#include "crypto/crypto_dh.h"
6
#include "crypto/crypto_rsa.h"
7
#include "crypto/crypto_util.h"
8
#include "async_wrap-inl.h"
9
#include "base_object-inl.h"
10
#include "env-inl.h"
11
#include "memory_tracker-inl.h"
12
#include "node.h"
13
#include "node_buffer.h"
14
#include "string_bytes.h"
15
#include "threadpoolwork-inl.h"
16
#include "util-inl.h"
17
#include "v8.h"
18
19
namespace node {
20
21
using v8::Array;
22
using v8::Context;
23
using v8::Function;
24
using v8::FunctionCallbackInfo;
25
using v8::FunctionTemplate;
26
using v8::Int32;
27
using v8::Isolate;
28
using v8::Just;
29
using v8::Local;
30
using v8::Maybe;
31
using v8::MaybeLocal;
32
using v8::NewStringType;
33
using v8::Nothing;
34
using v8::Number;
35
using v8::Object;
36
using v8::String;
37
using v8::Uint32;
38
using v8::Undefined;
39
using v8::Value;
40
41
namespace crypto {
42
namespace {
43
5050
void GetKeyFormatAndTypeFromJs(
44
    AsymmetricKeyEncodingConfig* config,
45
    const FunctionCallbackInfo<Value>& args,
46
    unsigned int* offset,
47
    KeyEncodingContext context) {
48
  // During key pair generation, it is possible not to specify a key encoding,
49
  // which will lead to a key object being returned.
50

15150
  if (args[*offset]->IsUndefined()) {
51
1488
    CHECK_EQ(context, kKeyContextGenerate);
52

4464
    CHECK(args[*offset + 1]->IsUndefined());
53
1488
    config->output_key_object_ = true;
54
  } else {
55
3562
    config->output_key_object_ = false;
56
57

7124
    CHECK(args[*offset]->IsInt32());
58
3562
    config->format_ = static_cast<PKFormatType>(
59
10686
        args[*offset].As<Int32>()->Value());
60
61

7124
    if (args[*offset + 1]->IsInt32()) {
62
4138
      config->type_ = Just<PKEncodingType>(static_cast<PKEncodingType>(
63
6207
          args[*offset + 1].As<Int32>()->Value()));
64
    } else {
65



1493
      CHECK(
66
          (context == kKeyContextInput &&
67
           config->format_ == kKeyFormatPEM) ||
68
          (context == kKeyContextGenerate &&
69
           config->format_ == kKeyFormatJWK));
70

4479
      CHECK(args[*offset + 1]->IsNullOrUndefined());
71
1493
      config->type_ = Nothing<PKEncodingType>();
72
    }
73
  }
74
75
5050
  *offset += 2;
76
5050
}
77
78
3238
ParseKeyResult TryParsePublicKey(
79
    EVPKeyPointer* pkey,
80
    const BIOPointer& bp,
81
    const char* name,
82
    // NOLINTNEXTLINE(runtime/int)
83
    const std::function<EVP_PKEY*(const unsigned char** p, long l)>& parse) {
84
  unsigned char* der_data;
85
  long der_len;  // NOLINT(runtime/int)
86
87
  // This skips surrounding data and decodes PEM to DER.
88
  {
89
3238
    MarkPopErrorOnReturn mark_pop_error_on_return;
90
3238
    if (PEM_bytes_read_bio(&der_data, &der_len, nullptr, name,
91
3238
                           bp.get(), nullptr, nullptr) != 1)
92
2271
      return ParseKeyResult::kParseKeyNotRecognized;
93
  }
94
95
  // OpenSSL might modify the pointer, so we need to make a copy before parsing.
96
967
  const unsigned char* p = der_data;
97
967
  pkey->reset(parse(&p, der_len));
98
967
  OPENSSL_clear_free(der_data, der_len);
99
100
967
  return *pkey ? ParseKeyResult::kParseKeyOk :
101
1934
                 ParseKeyResult::kParseKeyFailed;
102
}
103
104
1229
ParseKeyResult ParsePublicKeyPEM(EVPKeyPointer* pkey,
105
                                 const char* key_pem,
106
                                 int key_pem_len) {
107
2458
  BIOPointer bp(BIO_new_mem_buf(const_cast<char*>(key_pem), key_pem_len));
108
1229
  if (!bp)
109
    return ParseKeyResult::kParseKeyFailed;
110
111
  ParseKeyResult ret;
112
113
  // Try parsing as a SubjectPublicKeyInfo first.
114
1229
  ret = TryParsePublicKey(pkey, bp, "PUBLIC KEY",
115
217
      [](const unsigned char** p, long l) {  // NOLINT(runtime/int)
116
217
        return d2i_PUBKEY(nullptr, p, l);
117
      });
118
1229
  if (ret != ParseKeyResult::kParseKeyNotRecognized)
119
217
    return ret;
120
121
  // Maybe it is PKCS#1.
122
1012
  CHECK(BIO_reset(bp.get()));
123
1012
  ret = TryParsePublicKey(pkey, bp, "RSA PUBLIC KEY",
124
15
      [](const unsigned char** p, long l) {  // NOLINT(runtime/int)
125
15
        return d2i_PublicKey(EVP_PKEY_RSA, nullptr, p, l);
126
      });
127
1012
  if (ret != ParseKeyResult::kParseKeyNotRecognized)
128
15
    return ret;
129
130
  // X.509 fallback.
131
997
  CHECK(BIO_reset(bp.get()));
132
1994
  return TryParsePublicKey(pkey, bp, "CERTIFICATE",
133
735
      [](const unsigned char** p, long l) {  // NOLINT(runtime/int)
134
735
        X509Pointer x509(d2i_X509(nullptr, p, l));
135
735
        return x509 ? X509_get_pubkey(x509.get()) : nullptr;
136
997
      });
137
}
138
139
932
ParseKeyResult ParsePublicKey(EVPKeyPointer* pkey,
140
                              const PublicKeyEncodingConfig& config,
141
                              const char* key,
142
                              size_t key_len) {
143
932
  if (config.format_ == kKeyFormatPEM) {
144
    return ParsePublicKeyPEM(pkey, key, key_len);
145
  } else {
146
932
    CHECK_EQ(config.format_, kKeyFormatDER);
147
148
932
    const unsigned char* p = reinterpret_cast<const unsigned char*>(key);
149
1864
    if (config.type_.ToChecked() == kKeyEncodingPKCS1) {
150
22
      pkey->reset(d2i_PublicKey(EVP_PKEY_RSA, nullptr, &p, key_len));
151
    } else {
152
1820
      CHECK_EQ(config.type_.ToChecked(), kKeyEncodingSPKI);
153
910
      pkey->reset(d2i_PUBKEY(nullptr, &p, key_len));
154
    }
155
156
932
    return *pkey ? ParseKeyResult::kParseKeyOk :
157
1864
                   ParseKeyResult::kParseKeyFailed;
158
  }
159
}
160
161
1021
bool IsASN1Sequence(const unsigned char* data, size_t size,
162
                    size_t* data_offset, size_t* data_size) {
163

1021
  if (size < 2 || data[0] != 0x30)
164
    return false;
165
166
1021
  if (data[1] & 0x80) {
167
    // Long form.
168
930
    size_t n_bytes = data[1] & ~0x80;
169

930
    if (n_bytes + 2 > size || n_bytes > sizeof(size_t))
170
      return false;
171
930
    size_t length = 0;
172
2528
    for (size_t i = 0; i < n_bytes; i++)
173
1598
      length = (length << 8) | data[i + 2];
174
930
    *data_offset = 2 + n_bytes;
175
930
    *data_size = std::min(size - 2 - n_bytes, length);
176
  } else {
177
    // Short form.
178
91
    *data_offset = 2;
179
91
    *data_size = std::min<size_t>(size - 2, data[1]);
180
  }
181
182
1021
  return true;
183
}
184
185
34
bool IsRSAPrivateKey(const unsigned char* data, size_t size) {
186
  // Both RSAPrivateKey and RSAPublicKey structures start with a SEQUENCE.
187
  size_t offset, len;
188
34
  if (!IsASN1Sequence(data, size, &offset, &len))
189
    return false;
190
191
  // An RSAPrivateKey sequence always starts with a single-byte integer whose
192
  // value is either 0 or 1, whereas an RSAPublicKey starts with the modulus
193
  // (which is the product of two primes and therefore at least 4), so we can
194
  // decide the type of the structure based on the first three bytes of the
195
  // sequence.
196
68
  return len >= 3 &&
197
34
         data[offset] == 2 &&
198

80
         data[offset + 1] == 1 &&
199
46
         !(data[offset + 2] & 0xfe);
200
}
201
202
987
bool IsEncryptedPrivateKeyInfo(const unsigned char* data, size_t size) {
203
  // Both PrivateKeyInfo and EncryptedPrivateKeyInfo start with a SEQUENCE.
204
  size_t offset, len;
205
987
  if (!IsASN1Sequence(data, size, &offset, &len))
206
    return false;
207
208
  // A PrivateKeyInfo sequence always starts with an integer whereas an
209
  // EncryptedPrivateKeyInfo starts with an AlgorithmIdentifier.
210
1974
  return len >= 1 &&
211
1974
         data[offset] != 2;
212
}
213
214
1504
ParseKeyResult ParsePrivateKey(EVPKeyPointer* pkey,
215
                               const PrivateKeyEncodingConfig& config,
216
                               const char* key,
217
                               size_t key_len) {
218
1504
  const ByteSource* passphrase = config.passphrase_.get();
219
220
1504
  if (config.format_ == kKeyFormatPEM) {
221
504
    BIOPointer bio(BIO_new_mem_buf(key, key_len));
222
504
    if (!bio)
223
      return ParseKeyResult::kParseKeyFailed;
224
225
504
    pkey->reset(PEM_read_bio_PrivateKey(bio.get(),
226
                                        nullptr,
227
                                        PasswordCallback,
228
                                        &passphrase));
229
  } else {
230
1000
    CHECK_EQ(config.format_, kKeyFormatDER);
231
232
2000
    if (config.type_.ToChecked() == kKeyEncodingPKCS1) {
233
13
      const unsigned char* p = reinterpret_cast<const unsigned char*>(key);
234
13
      pkey->reset(d2i_PrivateKey(EVP_PKEY_RSA, nullptr, &p, key_len));
235
1974
    } else if (config.type_.ToChecked() == kKeyEncodingPKCS8) {
236
987
      BIOPointer bio(BIO_new_mem_buf(key, key_len));
237
987
      if (!bio)
238
        return ParseKeyResult::kParseKeyFailed;
239
240
987
      if (IsEncryptedPrivateKeyInfo(
241
              reinterpret_cast<const unsigned char*>(key), key_len)) {
242
17
        pkey->reset(d2i_PKCS8PrivateKey_bio(bio.get(),
243
                                            nullptr,
244
                                            PasswordCallback,
245
                                            &passphrase));
246
      } else {
247
1940
        PKCS8Pointer p8inf(d2i_PKCS8_PRIV_KEY_INFO_bio(bio.get(), nullptr));
248
970
        if (p8inf)
249
970
          pkey->reset(EVP_PKCS82PKEY(p8inf.get()));
250
      }
251
    } else {
252
      CHECK_EQ(config.type_.ToChecked(), kKeyEncodingSEC1);
253
      const unsigned char* p = reinterpret_cast<const unsigned char*>(key);
254
      pkey->reset(d2i_PrivateKey(EVP_PKEY_EC, nullptr, &p, key_len));
255
    }
256
  }
257
258
  // OpenSSL can fail to parse the key but still return a non-null pointer.
259
1504
  unsigned long err = ERR_peek_error();  // NOLINT(runtime/int)
260
1504
  if (err != 0)
261
21
    pkey->reset();
262
263
1504
  if (*pkey)
264
1483
    return ParseKeyResult::kParseKeyOk;
265

23
  if (ERR_GET_LIB(err) == ERR_LIB_PEM &&
266
2
      ERR_GET_REASON(err) == PEM_R_BAD_PASSWORD_READ) {
267
2
    if (config.passphrase_.IsEmpty())
268
2
      return ParseKeyResult::kParseKeyNeedPassphrase;
269
  }
270
19
  return ParseKeyResult::kParseKeyFailed;
271
}
272
273
130
MaybeLocal<Value> BIOToStringOrBuffer(
274
    Environment* env,
275
    BIO* bio,
276
    PKFormatType format) {
277
  BUF_MEM* bptr;
278
130
  BIO_get_mem_ptr(bio, &bptr);
279
130
  if (format == kKeyFormatPEM) {
280
    // PEM is an ASCII format, so we will return it as a string.
281
156
    return String::NewFromUtf8(env->isolate(), bptr->data,
282
                               NewStringType::kNormal,
283
156
                               bptr->length).FromMaybe(Local<Value>());
284
  } else {
285
52
    CHECK_EQ(format, kKeyFormatDER);
286
    // DER is binary, return it as a buffer.
287
52
    return Buffer::Copy(env, bptr->data, bptr->length)
288
52
        .FromMaybe(Local<Value>());
289
  }
290
}
291
292
293
62
MaybeLocal<Value> WritePrivateKey(
294
    Environment* env,
295
    EVP_PKEY* pkey,
296
    const PrivateKeyEncodingConfig& config) {
297
124
  BIOPointer bio(BIO_new(BIO_s_mem()));
298
62
  CHECK(bio);
299
300
  // If an empty string was passed as the passphrase, the ByteSource might
301
  // contain a null pointer, which OpenSSL will ignore, causing it to invoke its
302
  // default passphrase callback, which would block the thread until the user
303
  // manually enters a passphrase. We could supply our own passphrase callback
304
  // to handle this special case, but it is easier to avoid passing a null
305
  // pointer to OpenSSL.
306
62
  char* pass = nullptr;
307
62
  size_t pass_len = 0;
308
62
  if (!config.passphrase_.IsEmpty()) {
309
12
    pass = const_cast<char*>(config.passphrase_->data<char>());
310
12
    pass_len = config.passphrase_->size();
311
12
    if (pass == nullptr) {
312
      // OpenSSL will not actually dereference this pointer, so it can be any
313
      // non-null pointer. We cannot assert that directly, which is why we
314
      // intentionally use a pointer that will likely cause a segmentation fault
315
      // when dereferenced.
316
3
      CHECK_EQ(pass_len, 0);
317
3
      pass = reinterpret_cast<char*>(-1);
318
3
      CHECK_NE(pass, nullptr);
319
    }
320
  }
321
322
  bool err;
323
324
62
  PKEncodingType encoding_type = config.type_.ToChecked();
325
62
  if (encoding_type == kKeyEncodingPKCS1) {
326
    // PKCS#1 is only permitted for RSA keys.
327
12
    CHECK_EQ(EVP_PKEY_id(pkey), EVP_PKEY_RSA);
328
329
24
    RSAPointer rsa(EVP_PKEY_get1_RSA(pkey));
330
12
    if (config.format_ == kKeyFormatPEM) {
331
      // Encode PKCS#1 as PEM.
332
11
      err = PEM_write_bio_RSAPrivateKey(
333
11
                bio.get(), rsa.get(),
334
11
                config.cipher_,
335
                reinterpret_cast<unsigned char*>(pass),
336
                pass_len,
337
                nullptr, nullptr) != 1;
338
    } else {
339
      // Encode PKCS#1 as DER. This does not permit encryption.
340
1
      CHECK_EQ(config.format_, kKeyFormatDER);
341
1
      CHECK_NULL(config.cipher_);
342
1
      err = i2d_RSAPrivateKey_bio(bio.get(), rsa.get()) != 1;
343
    }
344
50
  } else if (encoding_type == kKeyEncodingPKCS8) {
345
46
    if (config.format_ == kKeyFormatPEM) {
346
      // Encode PKCS#8 as PEM.
347
23
      err = PEM_write_bio_PKCS8PrivateKey(
348
                bio.get(), pkey,
349
23
                config.cipher_,
350
                pass,
351
                pass_len,
352
                nullptr, nullptr) != 1;
353
    } else {
354
      // Encode PKCS#8 as DER.
355
23
      CHECK_EQ(config.format_, kKeyFormatDER);
356
23
      err = i2d_PKCS8PrivateKey_bio(
357
                bio.get(), pkey,
358
23
                config.cipher_,
359
                pass,
360
                pass_len,
361
                nullptr, nullptr) != 1;
362
    }
363
  } else {
364
4
    CHECK_EQ(encoding_type, kKeyEncodingSEC1);
365
366
    // SEC1 is only permitted for EC keys.
367
4
    CHECK_EQ(EVP_PKEY_id(pkey), EVP_PKEY_EC);
368
369
8
    ECKeyPointer ec_key(EVP_PKEY_get1_EC_KEY(pkey));
370
4
    if (config.format_ == kKeyFormatPEM) {
371
      // Encode SEC1 as PEM.
372
4
      err = PEM_write_bio_ECPrivateKey(
373
4
                bio.get(), ec_key.get(),
374
4
                config.cipher_,
375
                reinterpret_cast<unsigned char*>(pass),
376
                pass_len,
377
                nullptr, nullptr) != 1;
378
    } else {
379
      // Encode SEC1 as DER. This does not permit encryption.
380
      CHECK_EQ(config.format_, kKeyFormatDER);
381
      CHECK_NULL(config.cipher_);
382
      err = i2d_ECPrivateKey_bio(bio.get(), ec_key.get()) != 1;
383
    }
384
  }
385
386
62
  if (err) {
387
    ThrowCryptoError(env, ERR_get_error(), "Failed to encode private key");
388
    return MaybeLocal<Value>();
389
  }
390
62
  return BIOToStringOrBuffer(env, bio.get(), config.format_);
391
}
392
393
72
bool WritePublicKeyInner(EVP_PKEY* pkey,
394
                         const BIOPointer& bio,
395
                         const PublicKeyEncodingConfig& config) {
396
144
  if (config.type_.ToChecked() == kKeyEncodingPKCS1) {
397
    // PKCS#1 is only valid for RSA keys.
398
13
    CHECK_EQ(EVP_PKEY_id(pkey), EVP_PKEY_RSA);
399
26
    RSAPointer rsa(EVP_PKEY_get1_RSA(pkey));
400
13
    if (config.format_ == kKeyFormatPEM) {
401
      // Encode PKCS#1 as PEM.
402
7
      return PEM_write_bio_RSAPublicKey(bio.get(), rsa.get()) == 1;
403
    } else {
404
      // Encode PKCS#1 as DER.
405
6
      CHECK_EQ(config.format_, kKeyFormatDER);
406
6
      return i2d_RSAPublicKey_bio(bio.get(), rsa.get()) == 1;
407
    }
408
  } else {
409
118
    CHECK_EQ(config.type_.ToChecked(), kKeyEncodingSPKI);
410
59
    if (config.format_ == kKeyFormatPEM) {
411
      // Encode SPKI as PEM.
412
33
      return PEM_write_bio_PUBKEY(bio.get(), pkey) == 1;
413
    } else {
414
      // Encode SPKI as DER.
415
26
      CHECK_EQ(config.format_, kKeyFormatDER);
416
26
      return i2d_PUBKEY_bio(bio.get(), pkey) == 1;
417
    }
418
  }
419
}
420
421
72
MaybeLocal<Value> WritePublicKey(Environment* env,
422
                                 EVP_PKEY* pkey,
423
                                 const PublicKeyEncodingConfig& config) {
424
144
  BIOPointer bio(BIO_new(BIO_s_mem()));
425
72
  CHECK(bio);
426
427
72
  if (!WritePublicKeyInner(pkey, bio, config)) {
428
4
    ThrowCryptoError(env, ERR_get_error(), "Failed to encode public key");
429
4
    return MaybeLocal<Value>();
430
  }
431
68
  return BIOToStringOrBuffer(env, bio.get(), config.format_);
432
}
433
434
291
Maybe<bool> ExportJWKSecretKey(
435
    Environment* env,
436
    std::shared_ptr<KeyObjectData> key,
437
    Local<Object> target) {
438
291
  CHECK_EQ(key->GetKeyType(), kKeyTypeSecret);
439
440
  Local<Value> error;
441
  Local<Value> raw;
442
  MaybeLocal<Value> key_data =
443
      StringBytes::Encode(
444
          env->isolate(),
445
          key->GetSymmetricKey(),
446
          key->GetSymmetricKeySize(),
447
          BASE64URL,
448
291
          &error);
449
291
  if (key_data.IsEmpty()) {
450
    CHECK(!error.IsEmpty());
451
    env->isolate()->ThrowException(error);
452
    return Nothing<bool>();
453
  }
454
291
  if (!key_data.ToLocal(&raw))
455
    return Nothing<bool>();
456
457
582
  if (target->Set(
458
          env->context(),
459
          env->jwk_kty_string(),
460
1455
          env->jwk_oct_string()).IsNothing() ||
461
291
      target->Set(
462
          env->context(),
463
          env->jwk_k_string(),
464

1164
          raw).IsNothing()) {
465
    return Nothing<bool>();
466
  }
467
468
291
  return Just(true);
469
}
470
471
270
std::shared_ptr<KeyObjectData> ImportJWKSecretKey(
472
    Environment* env,
473
    Local<Object> jwk) {
474
  Local<Value> key;
475

1080
  if (!jwk->Get(env->context(), env->jwk_k_string()).ToLocal(&key) ||
476
540
      !key->IsString()) {
477
    THROW_ERR_CRYPTO_INVALID_JWK(env, "Invalid JWK secret key format");
478
    return std::shared_ptr<KeyObjectData>();
479
  }
480
481
540
  ByteSource key_data = ByteSource::FromEncodedString(env, key.As<String>());
482
270
  if (key_data.size() > INT_MAX) {
483
    THROW_ERR_CRYPTO_INVALID_KEYLEN(env);
484
    return std::shared_ptr<KeyObjectData>();
485
  }
486
487
270
  return KeyObjectData::CreateSecret(std::move(key_data));
488
}
489
490
662
Maybe<bool> ExportJWKAsymmetricKey(
491
    Environment* env,
492
    std::shared_ptr<KeyObjectData> key,
493
    Local<Object> target,
494
    bool handleRsaPss) {
495

662
  switch (EVP_PKEY_id(key->GetAsymmetricKey().get())) {
496
2
    case EVP_PKEY_RSA_PSS: {
497
2
      if (handleRsaPss) return ExportJWKRsaKey(env, key, target);
498
2
      break;
499
    }
500
409
    case EVP_PKEY_RSA: return ExportJWKRsaKey(env, key, target);
501
398
    case EVP_PKEY_EC: return ExportJWKEcKey(env, key, target).IsJust() ?
502
199
                               Just(true) : Nothing<bool>();
503
48
    case EVP_PKEY_ED25519:
504
      // Fall through
505
    case EVP_PKEY_ED448:
506
      // Fall through
507
    case EVP_PKEY_X25519:
508
      // Fall through
509
48
    case EVP_PKEY_X448: return ExportJWKEdKey(env, key, target);
510
  }
511
6
  THROW_ERR_CRYPTO_JWK_UNSUPPORTED_KEY_TYPE(env);
512
6
  return Just(false);
513
}
514
515
658
std::shared_ptr<KeyObjectData> ImportJWKAsymmetricKey(
516
    Environment* env,
517
    Local<Object> jwk,
518
    const char* kty,
519
    const FunctionCallbackInfo<Value>& args,
520
    unsigned int offset) {
521
658
  if (strcmp(kty, "RSA") == 0) {
522
502
    return ImportJWKRsaKey(env, jwk, args, offset);
523
156
  } else if (strcmp(kty, "EC") == 0) {
524
156
    return ImportJWKEcKey(env, jwk, args, offset);
525
  }
526
527
  THROW_ERR_CRYPTO_INVALID_JWK(env, "%s is not a supported JWK key type", kty);
528
  return std::shared_ptr<KeyObjectData>();
529
}
530
531
4015
Maybe<bool> GetSecretKeyDetail(
532
    Environment* env,
533
    std::shared_ptr<KeyObjectData> key,
534
    Local<Object> target) {
535
  // For the secret key detail, all we care about is the length,
536
  // converted to bits.
537
538
4015
  size_t length = key->GetSymmetricKeySize() * CHAR_BIT;
539
  return target->Set(env->context(),
540
                     env->length_string(),
541
12045
                     Number::New(env->isolate(), static_cast<double>(length)));
542
}
543
544
2355
Maybe<bool> GetAsymmetricKeyDetail(
545
  Environment* env,
546
  std::shared_ptr<KeyObjectData> key,
547
  Local<Object> target) {
548

2355
  switch (EVP_PKEY_id(key->GetAsymmetricKey().get())) {
549
1697
    case EVP_PKEY_RSA:
550
      // Fall through
551
1697
    case EVP_PKEY_RSA_PSS: return GetRsaKeyDetail(env, key, target);
552
2
    case EVP_PKEY_DSA: return GetDsaKeyDetail(env, key, target);
553
656
    case EVP_PKEY_EC: return GetEcKeyDetail(env, key, target);
554
    case EVP_PKEY_DH: return GetDhKeyDetail(env, key, target);
555
  }
556
  THROW_ERR_CRYPTO_INVALID_KEYTYPE(env);
557
  return Nothing<bool>();
558
}
559
}  // namespace
560
561
9646
ManagedEVPPKey::ManagedEVPPKey(EVPKeyPointer&& pkey) : pkey_(std::move(pkey)),
562
4823
    mutex_(std::make_shared<Mutex>()) {}
563
564
18183
ManagedEVPPKey::ManagedEVPPKey(const ManagedEVPPKey& that) {
565
18183
  *this = that;
566
18183
}
567
568
23736
ManagedEVPPKey& ManagedEVPPKey::operator=(const ManagedEVPPKey& that) {
569
23736
  Mutex::ScopedLock lock(*that.mutex_);
570
571
23736
  pkey_.reset(that.get());
572
573
23736
  if (pkey_)
574
22943
    EVP_PKEY_up_ref(pkey_.get());
575
576
23736
  mutex_ = that.mutex_;
577
578
23736
  return *this;
579
}
580
581
9543
ManagedEVPPKey::operator bool() const {
582
9543
  return !!pkey_;
583
}
584
585
47228
EVP_PKEY* ManagedEVPPKey::get() const {
586
47228
  return pkey_.get();
587
}
588
589
6823
Mutex* ManagedEVPPKey::mutex() const {
590
6823
  return mutex_.get();
591
}
592
593
void ManagedEVPPKey::MemoryInfo(MemoryTracker* tracker) const {
594
  tracker->TrackFieldWithSize("pkey",
595
                              !pkey_ ? 0 : kSizeOf_EVP_PKEY +
596
                              size_of_private_key() +
597
                              size_of_public_key());
598
}
599
600
size_t ManagedEVPPKey::size_of_private_key() const {
601
  size_t len = 0;
602
  return (pkey_ && EVP_PKEY_get_raw_private_key(
603
      pkey_.get(), nullptr, &len) == 1) ? len : 0;
604
}
605
606
size_t ManagedEVPPKey::size_of_public_key() const {
607
  size_t len = 0;
608
  return (pkey_ && EVP_PKEY_get_raw_public_key(
609
      pkey_.get(), nullptr, &len) == 1) ? len : 0;
610
}
611
612
// This maps true to Just<bool>(true) and false to Nothing<bool>().
613
1332
static inline Maybe<bool> Tristate(bool b) {
614
1332
  return b ? Just(true) : Nothing<bool>();
615
}
616
617
953
Maybe<bool> ExportJWKInner(Environment* env,
618
                           std::shared_ptr<KeyObjectData> key,
619
                           Local<Value> result,
620
                           bool handleRsaPss) {
621
953
  switch (key->GetKeyType()) {
622
291
    case kKeyTypeSecret:
623
291
      return ExportJWKSecretKey(env, key, result.As<Object>());
624
662
    case kKeyTypePublic:
625
      // Fall through
626
    case kKeyTypePrivate:
627
      return ExportJWKAsymmetricKey(
628
1324
        env, key, result.As<Object>(), handleRsaPss);
629
    default:
630
      UNREACHABLE();
631
  }
632
}
633
634
679
Maybe<bool> ManagedEVPPKey::ToEncodedPublicKey(
635
    Environment* env,
636
    const PublicKeyEncodingConfig& config,
637
    Local<Value>* out) {
638
679
  if (!*this) return Nothing<bool>();
639
679
  if (config.output_key_object_) {
640
    // Note that this has the downside of containing sensitive data of the
641
    // private key.
642
    std::shared_ptr<KeyObjectData> data =
643
648
        KeyObjectData::CreateAsymmetric(kKeyTypePublic, *this);
644
1296
    return Tristate(KeyObjectHandle::Create(env, data).ToLocal(out));
645
31
  } else if (config.format_ == kKeyFormatJWK) {
646
    std::shared_ptr<KeyObjectData> data =
647
11
        KeyObjectData::CreateAsymmetric(kKeyTypePublic, *this);
648
11
    *out = Object::New(env->isolate());
649
11
    return ExportJWKInner(env, data, *out, false);
650
  }
651
652
40
  return Tristate(WritePublicKey(env, get(), config).ToLocal(out));
653
}
654
655
674
Maybe<bool> ManagedEVPPKey::ToEncodedPrivateKey(
656
    Environment* env,
657
    const PrivateKeyEncodingConfig& config,
658
    Local<Value>* out) {
659
674
  if (!*this) return Nothing<bool>();
660
674
  if (config.output_key_object_) {
661
    std::shared_ptr<KeyObjectData> data =
662
647
        KeyObjectData::CreateAsymmetric(kKeyTypePrivate, *this);
663
1294
    return Tristate(KeyObjectHandle::Create(env, data).ToLocal(out));
664
27
  } else if (config.format_ == kKeyFormatJWK) {
665
    std::shared_ptr<KeyObjectData> data =
666
10
        KeyObjectData::CreateAsymmetric(kKeyTypePrivate, *this);
667
10
    *out = Object::New(env->isolate());
668
10
    return ExportJWKInner(env, data, *out, false);
669
  }
670
671
34
  return Tristate(WritePrivateKey(env, get(), config).ToLocal(out));
672
}
673
674
NonCopyableMaybe<PrivateKeyEncodingConfig>
675
4223
ManagedEVPPKey::GetPrivateKeyEncodingFromJs(
676
    const FunctionCallbackInfo<Value>& args,
677
    unsigned int* offset,
678
    KeyEncodingContext context) {
679
4223
  Environment* env = Environment::GetCurrent(args);
680
681
8446
  PrivateKeyEncodingConfig result;
682
4223
  GetKeyFormatAndTypeFromJs(&result, args, offset, context);
683
684
4223
  if (result.output_key_object_) {
685
745
    if (context != kKeyContextInput)
686
745
      (*offset)++;
687
  } else {
688
3478
    bool needs_passphrase = false;
689
3478
    if (context != kKeyContextInput) {
690

225
      if (args[*offset]->IsString()) {
691
26
        Utf8Value cipher_name(env->isolate(), args[*offset]);
692
13
        result.cipher_ = EVP_get_cipherbyname(*cipher_name);
693
13
        if (result.cipher_ == nullptr) {
694
1
          THROW_ERR_CRYPTO_UNKNOWN_CIPHER(env);
695
1
          return NonCopyableMaybe<PrivateKeyEncodingConfig>();
696
        }
697
12
        needs_passphrase = true;
698
      } else {
699

186
        CHECK(args[*offset]->IsNullOrUndefined());
700
62
        result.cipher_ = nullptr;
701
      }
702
74
      (*offset)++;
703
    }
704
705

6954
    if (IsAnyByteSource(args[*offset])) {
706

95
      CHECK_IMPLIES(context != kKeyContextInput, result.cipher_ != nullptr);
707
190
      ArrayBufferOrViewContents<char> passphrase(args[*offset]);
708
95
      if (UNLIKELY(!passphrase.CheckSizeInt32())) {
709
        THROW_ERR_OUT_OF_RANGE(env, "passphrase is too big");
710
        return NonCopyableMaybe<PrivateKeyEncodingConfig>();
711
      }
712
190
      result.passphrase_ = NonCopyableMaybe<ByteSource>(
713
285
          passphrase.ToNullTerminatedCopy());
714
    } else {
715


10146
      CHECK(args[*offset]->IsNullOrUndefined() && !needs_passphrase);
716
    }
717
  }
718
719
4222
  (*offset)++;
720
4222
  return NonCopyableMaybe<PrivateKeyEncodingConfig>(std::move(result));
721
}
722
723
827
PublicKeyEncodingConfig ManagedEVPPKey::GetPublicKeyEncodingFromJs(
724
    const FunctionCallbackInfo<Value>& args,
725
    unsigned int* offset,
726
    KeyEncodingContext context) {
727
827
  PublicKeyEncodingConfig result;
728
827
  GetKeyFormatAndTypeFromJs(&result, args, offset, context);
729
827
  return result;
730
}
731
732
1379
ManagedEVPPKey ManagedEVPPKey::GetPrivateKeyFromJs(
733
    const FunctionCallbackInfo<Value>& args,
734
    unsigned int* offset,
735
    bool allow_key_object) {
736


5516
  if (args[*offset]->IsString() || IsAnyByteSource(args[*offset])) {
737
1173
    Environment* env = Environment::GetCurrent(args);
738
3519
    ByteSource key = ByteSource::FromStringOrBuffer(env, args[(*offset)++]);
739
    NonCopyableMaybe<PrivateKeyEncodingConfig> config =
740
2346
        GetPrivateKeyEncodingFromJs(args, offset, kKeyContextInput);
741
1173
    if (config.IsEmpty())
742
      return ManagedEVPPKey();
743
744
1173
    EVPKeyPointer pkey;
745
    ParseKeyResult ret =
746
1173
        ParsePrivateKey(&pkey, config.Release(), key.data<char>(), key.size());
747
1173
    return GetParsedKey(env, std::move(pkey), ret,
748
1173
                        "Failed to read private key");
749
  } else {
750


412
    CHECK(args[*offset]->IsObject() && allow_key_object);
751
    KeyObjectHandle* key;
752

618
    ASSIGN_OR_RETURN_UNWRAP(&key, args[*offset].As<Object>(), ManagedEVPPKey());
753
206
    CHECK_EQ(key->Data()->GetKeyType(), kKeyTypePrivate);
754
206
    (*offset) += 4;
755
206
    return key->Data()->GetAsymmetricKey();
756
  }
757
}
758
759
2870
ManagedEVPPKey ManagedEVPPKey::GetPublicOrPrivateKeyFromJs(
760
    const FunctionCallbackInfo<Value>& args,
761
    unsigned int* offset) {
762

5740
  if (IsAnyByteSource(args[*offset])) {
763
2230
    Environment* env = Environment::GetCurrent(args);
764
4460
    ArrayBufferOrViewContents<char> data(args[(*offset)++]);
765
2230
    if (UNLIKELY(!data.CheckSizeInt32())) {
766
      THROW_ERR_OUT_OF_RANGE(env, "keyData is too big");
767
      return ManagedEVPPKey();
768
    }
769
    NonCopyableMaybe<PrivateKeyEncodingConfig> config_ =
770
4460
        GetPrivateKeyEncodingFromJs(args, offset, kKeyContextInput);
771
2230
    if (config_.IsEmpty())
772
      return ManagedEVPPKey();
773
774
    ParseKeyResult ret;
775
4460
    PrivateKeyEncodingConfig config = config_.Release();
776
2230
    EVPKeyPointer pkey;
777
2230
    if (config.format_ == kKeyFormatPEM) {
778
      // For PEM, we can easily determine whether it is a public or private key
779
      // by looking for the respective PEM tags.
780
1229
      ret = ParsePublicKeyPEM(&pkey, data.data(), data.size());
781
1229
      if (ret == ParseKeyResult::kParseKeyNotRecognized) {
782
262
        ret = ParsePrivateKey(&pkey, config, data.data(), data.size());
783
      }
784
    } else {
785
      // For DER, the type determines how to parse it. SPKI, PKCS#8 and SEC1 are
786
      // easy, but PKCS#1 can be a public key or a private key.
787
      bool is_public;
788

1001
      switch (config.type_.ToChecked()) {
789
34
        case kKeyEncodingPKCS1:
790
68
          is_public = !IsRSAPrivateKey(
791
34
              reinterpret_cast<const unsigned char*>(data.data()), data.size());
792
34
          break;
793
910
        case kKeyEncodingSPKI:
794
910
          is_public = true;
795
910
          break;
796
57
        case kKeyEncodingPKCS8:
797
        case kKeyEncodingSEC1:
798
57
          is_public = false;
799
57
          break;
800
        default:
801
          UNREACHABLE("Invalid key encoding type");
802
      }
803
804
1001
      if (is_public) {
805
932
        ret = ParsePublicKey(&pkey, config, data.data(), data.size());
806
      } else {
807
69
        ret = ParsePrivateKey(&pkey, config, data.data(), data.size());
808
      }
809
    }
810
811
    return ManagedEVPPKey::GetParsedKey(
812
2230
        env, std::move(pkey), ret, "Failed to read asymmetric key");
813
  } else {
814

1280
    CHECK(args[*offset]->IsObject());
815
1920
    KeyObjectHandle* key = Unwrap<KeyObjectHandle>(args[*offset].As<Object>());
816
640
    CHECK_NOT_NULL(key);
817
640
    CHECK_NE(key->Data()->GetKeyType(), kKeyTypeSecret);
818
640
    (*offset) += 4;
819
640
    return key->Data()->GetAsymmetricKey();
820
  }
821
}
822
823
3403
ManagedEVPPKey ManagedEVPPKey::GetParsedKey(Environment* env,
824
                                            EVPKeyPointer&& pkey,
825
                                            ParseKeyResult ret,
826
                                            const char* default_msg) {
827
3403
  switch (ret) {
828
3382
    case ParseKeyResult::kParseKeyOk:
829
3382
      CHECK(pkey);
830
3382
      break;
831
2
    case ParseKeyResult::kParseKeyNeedPassphrase:
832
2
      THROW_ERR_MISSING_PASSPHRASE(env,
833
                                   "Passphrase required for encrypted key");
834
2
      break;
835
19
    default:
836
19
      ThrowCryptoError(env, ERR_get_error(), default_msg);
837
  }
838
839
3403
  return ManagedEVPPKey(std::move(pkey));
840
}
841
842
5375
KeyObjectData::KeyObjectData(
843
5375
    ByteSource symmetric_key)
844
    : key_type_(KeyType::kKeyTypeSecret),
845
5375
      symmetric_key_(std::move(symmetric_key)),
846
5375
      symmetric_key_len_(symmetric_key_.size()),
847
10750
      asymmetric_key_() {}
848
849
3941
KeyObjectData::KeyObjectData(
850
    KeyType type,
851
3941
    const ManagedEVPPKey& pkey)
852
    : key_type_(type),
853
      symmetric_key_(),
854
      symmetric_key_len_(0),
855
3941
      asymmetric_key_{pkey} {}
856
857
void KeyObjectData::MemoryInfo(MemoryTracker* tracker) const {
858
  switch (GetKeyType()) {
859
    case kKeyTypeSecret:
860
      tracker->TrackFieldWithSize("symmetric_key", symmetric_key_.size());
861
      break;
862
    case kKeyTypePrivate:
863
      // Fall through
864
    case kKeyTypePublic:
865
      tracker->TrackFieldWithSize("key", asymmetric_key_);
866
      break;
867
    default:
868
      UNREACHABLE();
869
  }
870
}
871
872
5375
std::shared_ptr<KeyObjectData> KeyObjectData::CreateSecret(ByteSource key) {
873
5375
  return std::shared_ptr<KeyObjectData>(new KeyObjectData(std::move(key)));
874
}
875
876
3941
std::shared_ptr<KeyObjectData> KeyObjectData::CreateAsymmetric(
877
    KeyType key_type,
878
    const ManagedEVPPKey& pkey) {
879
3941
  CHECK(pkey);
880
3941
  return std::shared_ptr<KeyObjectData>(new KeyObjectData(key_type, pkey));
881
}
882
883
18824
KeyType KeyObjectData::GetKeyType() const {
884
18824
  return key_type_;
885
}
886
887
10782
ManagedEVPPKey KeyObjectData::GetAsymmetricKey() const {
888
10782
  CHECK_NE(key_type_, kKeyTypeSecret);
889
10782
  return asymmetric_key_;
890
}
891
892
7770
const char* KeyObjectData::GetSymmetricKey() const {
893
7770
  CHECK_EQ(key_type_, kKeyTypeSecret);
894
7770
  return symmetric_key_.data<char>();
895
}
896
897
12840
size_t KeyObjectData::GetSymmetricKeySize() const {
898
12840
  CHECK_EQ(key_type_, kKeyTypeSecret);
899
12840
  return symmetric_key_len_;
900
}
901
902
3275
v8::Local<v8::Function> KeyObjectHandle::Initialize(Environment* env) {
903
3275
  Local<Function> templ = env->crypto_key_object_handle_constructor();
904
3275
  if (!templ.IsEmpty()) {
905
2500
    return templ;
906
  }
907
775
  Isolate* isolate = env->isolate();
908
775
  Local<FunctionTemplate> t = NewFunctionTemplate(isolate, New);
909
1550
  t->InstanceTemplate()->SetInternalFieldCount(
910
      KeyObjectHandle::kInternalFieldCount);
911
775
  t->Inherit(BaseObject::GetConstructorTemplate(env));
912
913
775
  SetProtoMethod(isolate, t, "init", Init);
914
775
  SetProtoMethodNoSideEffect(
915
      isolate, t, "getSymmetricKeySize", GetSymmetricKeySize);
916
775
  SetProtoMethodNoSideEffect(
917
      isolate, t, "getAsymmetricKeyType", GetAsymmetricKeyType);
918
775
  SetProtoMethod(isolate, t, "export", Export);
919
775
  SetProtoMethod(isolate, t, "exportJwk", ExportJWK);
920
775
  SetProtoMethod(isolate, t, "initECRaw", InitECRaw);
921
775
  SetProtoMethod(isolate, t, "initEDRaw", InitEDRaw);
922
775
  SetProtoMethod(isolate, t, "initJwk", InitJWK);
923
775
  SetProtoMethod(isolate, t, "keyDetail", GetKeyDetail);
924
775
  SetProtoMethod(isolate, t, "equals", Equals);
925
926
775
  auto function = t->GetFunction(env->context()).ToLocalChecked();
927
775
  env->set_crypto_key_object_handle_constructor(function);
928
775
  return function;
929
}
930
931
5357
void KeyObjectHandle::RegisterExternalReferences(
932
    ExternalReferenceRegistry* registry) {
933
5357
  registry->Register(New);
934
5357
  registry->Register(Init);
935
5357
  registry->Register(GetSymmetricKeySize);
936
5357
  registry->Register(GetAsymmetricKeyType);
937
5357
  registry->Register(Export);
938
5357
  registry->Register(ExportJWK);
939
5357
  registry->Register(InitECRaw);
940
5357
  registry->Register(InitEDRaw);
941
5357
  registry->Register(InitJWK);
942
5357
  registry->Register(GetKeyDetail);
943
5357
  registry->Register(Equals);
944
5357
}
945
946
2500
MaybeLocal<Object> KeyObjectHandle::Create(
947
    Environment* env,
948
    std::shared_ptr<KeyObjectData> data) {
949
  Local<Object> obj;
950
2500
  Local<Function> ctor = KeyObjectHandle::Initialize(env);
951
5000
  CHECK(!env->crypto_key_object_handle_constructor().IsEmpty());
952
5000
  if (!ctor->NewInstance(env->context(), 0, nullptr).ToLocal(&obj))
953
    return MaybeLocal<Object>();
954
955
2500
  KeyObjectHandle* key = Unwrap<KeyObjectHandle>(obj);
956
2500
  CHECK_NOT_NULL(key);
957
2500
  key->data_ = data;
958
2500
  return obj;
959
}
960
961
27589
const std::shared_ptr<KeyObjectData>& KeyObjectHandle::Data() {
962
27589
  return data_;
963
}
964
965
9308
void KeyObjectHandle::New(const FunctionCallbackInfo<Value>& args) {
966
9308
  CHECK(args.IsConstructCall());
967
9308
  Environment* env = Environment::GetCurrent(args);
968
9308
  new KeyObjectHandle(env, args.This());
969
9308
}
970
971
9308
KeyObjectHandle::KeyObjectHandle(Environment* env,
972
9308
                                 Local<Object> wrap)
973
9308
    : BaseObject(env, wrap) {
974
9308
  MakeWeak();
975
9308
}
976
977
5800
void KeyObjectHandle::Init(const FunctionCallbackInfo<Value>& args) {
978
  KeyObjectHandle* key;
979
5805
  ASSIGN_OR_RETURN_UNWRAP(&key, args.Holder());
980
5800
  MarkPopErrorOnReturn mark_pop_error_on_return;
981
982
5800
  CHECK(args[0]->IsInt32());
983
11600
  KeyType type = static_cast<KeyType>(args[0].As<Uint32>()->Value());
984
985
  unsigned int offset;
986
5800
  ManagedEVPPKey pkey;
987
988

5800
  switch (type) {
989
3910
  case kKeyTypeSecret: {
990
3910
    CHECK_EQ(args.Length(), 2);
991
3910
    ArrayBufferOrViewContents<char> buf(args[1]);
992
3910
    key->data_ = KeyObjectData::CreateSecret(buf.ToCopy());
993
3910
    break;
994
  }
995
927
  case kKeyTypePublic: {
996
927
    CHECK_EQ(args.Length(), 5);
997
998
927
    offset = 1;
999
927
    pkey = ManagedEVPPKey::GetPublicOrPrivateKeyFromJs(args, &offset);
1000
927
    if (!pkey)
1001
      return;
1002
927
    key->data_ = KeyObjectData::CreateAsymmetric(type, pkey);
1003
927
    break;
1004
  }
1005
963
  case kKeyTypePrivate: {
1006
963
    CHECK_EQ(args.Length(), 5);
1007
1008
963
    offset = 1;
1009
963
    pkey = ManagedEVPPKey::GetPrivateKeyFromJs(args, &offset, false);
1010
963
    if (!pkey)
1011
5
      return;
1012
958
    key->data_ = KeyObjectData::CreateAsymmetric(type, pkey);
1013
958
    break;
1014
  }
1015
  default:
1016
    UNREACHABLE();
1017
  }
1018
}
1019
1020
928
void KeyObjectHandle::InitJWK(const FunctionCallbackInfo<Value>& args) {
1021
928
  Environment* env = Environment::GetCurrent(args);
1022
  KeyObjectHandle* key;
1023
928
  ASSIGN_OR_RETURN_UNWRAP(&key, args.Holder());
1024
928
  MarkPopErrorOnReturn mark_pop_error_on_return;
1025
1026
  // The argument must be a JavaScript object that we will inspect
1027
  // to get the JWK properties from.
1028
928
  CHECK(args[0]->IsObject());
1029
1030
  // Step one, Secret key or not?
1031
1856
  Local<Object> input = args[0].As<Object>();
1032
1033
  Local<Value> kty;
1034

3712
  if (!input->Get(env->context(), env->jwk_kty_string()).ToLocal(&kty) ||
1035
1856
      !kty->IsString()) {
1036
    return THROW_ERR_CRYPTO_INVALID_JWK(env);
1037
  }
1038
1039
928
  Utf8Value kty_string(env->isolate(), kty);
1040
1041
928
  if (strcmp(*kty_string, "oct") == 0) {
1042
    // Secret key
1043
270
    key->data_ = ImportJWKSecretKey(env, input);
1044
270
    if (!key->data_) {
1045
      // ImportJWKSecretKey is responsible for throwing an appropriate error
1046
      return;
1047
    }
1048
  } else {
1049
658
    key->data_ = ImportJWKAsymmetricKey(env, input, *kty_string, args, 1);
1050
658
    if (!key->data_) {
1051
      // ImportJWKAsymmetricKey is responsible for throwing an appropriate error
1052
      return;
1053
    }
1054
  }
1055
1056
1856
  args.GetReturnValue().Set(key->data_->GetKeyType());
1057
}
1058
1059
12
void KeyObjectHandle::InitECRaw(const FunctionCallbackInfo<Value>& args) {
1060
12
  Environment* env = Environment::GetCurrent(args);
1061
  KeyObjectHandle* key;
1062
12
  ASSIGN_OR_RETURN_UNWRAP(&key, args.Holder());
1063
1064
24
  CHECK(args[0]->IsString());
1065
12
  Utf8Value name(env->isolate(), args[0]);
1066
1067
12
  MarkPopErrorOnReturn mark_pop_error_on_return;
1068
1069
12
  int id = OBJ_txt2nid(*name);
1070
12
  ECKeyPointer eckey(EC_KEY_new_by_curve_name(id));
1071
12
  if (!eckey)
1072
    return args.GetReturnValue().Set(false);
1073
1074
12
  const EC_GROUP* group = EC_KEY_get0_group(eckey.get());
1075
12
  ECPointPointer pub(ECDH::BufferToPoint(env, group, args[1]));
1076
1077
12
  if (!pub ||
1078


24
      !eckey ||
1079
12
      !EC_KEY_set_public_key(eckey.get(), pub.get())) {
1080
    return args.GetReturnValue().Set(false);
1081
  }
1082
1083
12
  EVPKeyPointer pkey(EVP_PKEY_new());
1084
12
  if (!EVP_PKEY_assign_EC_KEY(pkey.get(), eckey.get()))
1085
    args.GetReturnValue().Set(false);
1086
1087
12
  eckey.release();  // Release ownership of the key
1088
1089
12
  key->data_ =
1090
24
      KeyObjectData::CreateAsymmetric(
1091
          kKeyTypePublic,
1092
36
          ManagedEVPPKey(std::move(pkey)));
1093
1094
24
  args.GetReturnValue().Set(true);
1095
}
1096
1097
68
void KeyObjectHandle::InitEDRaw(const FunctionCallbackInfo<Value>& args) {
1098
68
  Environment* env = Environment::GetCurrent(args);
1099
  KeyObjectHandle* key;
1100
68
  ASSIGN_OR_RETURN_UNWRAP(&key, args.Holder());
1101
1102
136
  CHECK(args[0]->IsString());
1103
68
  Utf8Value name(env->isolate(), args[0]);
1104
1105
68
  ArrayBufferOrViewContents<unsigned char> key_data(args[1]);
1106
136
  KeyType type = static_cast<KeyType>(args[2].As<Int32>()->Value());
1107
1108
68
  MarkPopErrorOnReturn mark_pop_error_on_return;
1109
1110
  typedef EVP_PKEY* (*new_key_fn)(int, ENGINE*, const unsigned char*, size_t);
1111
68
  new_key_fn fn = type == kKeyTypePrivate
1112
68
      ? EVP_PKEY_new_raw_private_key
1113
      : EVP_PKEY_new_raw_public_key;
1114
1115
68
  int id = GetOKPCurveFromName(*name);
1116
1117
68
  switch (id) {
1118
68
    case EVP_PKEY_X25519:
1119
    case EVP_PKEY_X448:
1120
    case EVP_PKEY_ED25519:
1121
    case EVP_PKEY_ED448: {
1122
68
      EVPKeyPointer pkey(fn(id, nullptr, key_data.data(), key_data.size()));
1123
68
      if (!pkey)
1124
        return args.GetReturnValue().Set(false);
1125
68
      key->data_ =
1126
136
          KeyObjectData::CreateAsymmetric(
1127
              type,
1128
204
              ManagedEVPPKey(std::move(pkey)));
1129
68
      CHECK(key->data_);
1130
68
      break;
1131
    }
1132
    default:
1133
      UNREACHABLE();
1134
  }
1135
1136
136
  args.GetReturnValue().Set(true);
1137
}
1138
1139
15
void KeyObjectHandle::Equals(const FunctionCallbackInfo<Value>& args) {
1140
  KeyObjectHandle* self_handle;
1141
  KeyObjectHandle* arg_handle;
1142
15
  ASSIGN_OR_RETURN_UNWRAP(&self_handle, args.Holder());
1143
30
  ASSIGN_OR_RETURN_UNWRAP(&arg_handle, args[0].As<Object>());
1144
15
  std::shared_ptr<KeyObjectData> key = self_handle->Data();
1145
15
  std::shared_ptr<KeyObjectData> key2 = arg_handle->Data();
1146
1147
15
  KeyType key_type = key->GetKeyType();
1148
15
  CHECK_EQ(key_type, key2->GetKeyType());
1149
1150
  bool ret;
1151
15
  switch (key_type) {
1152
7
    case kKeyTypeSecret: {
1153
7
      size_t size = key->GetSymmetricKeySize();
1154
7
      if (size == key2->GetSymmetricKeySize()) {
1155
5
        ret = CRYPTO_memcmp(
1156
5
          key->GetSymmetricKey(),
1157
5
          key2->GetSymmetricKey(),
1158
          size) == 0;
1159
      } else {
1160
2
        ret = false;
1161
      }
1162
7
      break;
1163
    }
1164
8
    case kKeyTypePublic:
1165
    case kKeyTypePrivate: {
1166
8
      EVP_PKEY* pkey = key->GetAsymmetricKey().get();
1167
8
      EVP_PKEY* pkey2 = key2->GetAsymmetricKey().get();
1168
#if OPENSSL_VERSION_MAJOR >= 3
1169
8
      int ok = EVP_PKEY_eq(pkey, pkey2);
1170
#else
1171
      int ok = EVP_PKEY_cmp(pkey, pkey2);
1172
#endif
1173
8
      if (ok == -2) {
1174
        Environment* env = Environment::GetCurrent(args);
1175
        return THROW_ERR_CRYPTO_UNSUPPORTED_OPERATION(env);
1176
      }
1177
8
      ret = ok == 1;
1178
8
      break;
1179
    }
1180
    default:
1181
      UNREACHABLE("unsupported key type");
1182
  }
1183
1184
30
  args.GetReturnValue().Set(ret);
1185
}
1186
1187
6370
void KeyObjectHandle::GetKeyDetail(const FunctionCallbackInfo<Value>& args) {
1188
6370
  Environment* env = Environment::GetCurrent(args);
1189
  KeyObjectHandle* key;
1190
6370
  ASSIGN_OR_RETURN_UNWRAP(&key, args.Holder());
1191
1192
6370
  CHECK(args[0]->IsObject());
1193
1194
6370
  std::shared_ptr<KeyObjectData> data = key->Data();
1195
1196
6370
  switch (data->GetKeyType()) {
1197
4015
    case kKeyTypeSecret:
1198
12045
      if (GetSecretKeyDetail(env, data, args[0].As<Object>()).IsNothing())
1199
        return;
1200
4015
      break;
1201
2355
    case kKeyTypePublic:
1202
      // Fall through
1203
    case kKeyTypePrivate:
1204
7065
      if (GetAsymmetricKeyDetail(env, data, args[0].As<Object>()).IsNothing())
1205
        return;
1206
2355
      break;
1207
    default:
1208
      UNREACHABLE();
1209
  }
1210
1211
12740
  args.GetReturnValue().Set(args[0]);
1212
}
1213
1214
2662
Local<Value> KeyObjectHandle::GetAsymmetricKeyType() const {
1215
5324
  const ManagedEVPPKey& key = data_->GetAsymmetricKey();
1216


2662
  switch (EVP_PKEY_id(key.get())) {
1217
1718
  case EVP_PKEY_RSA:
1218
3436
    return env()->crypto_rsa_string();
1219
22
  case EVP_PKEY_RSA_PSS:
1220
44
    return env()->crypto_rsa_pss_string();
1221
10
  case EVP_PKEY_DSA:
1222
20
    return env()->crypto_dsa_string();
1223
18
  case EVP_PKEY_DH:
1224
36
    return env()->crypto_dh_string();
1225
676
  case EVP_PKEY_EC:
1226
1352
    return env()->crypto_ec_string();
1227
58
  case EVP_PKEY_ED25519:
1228
116
    return env()->crypto_ed25519_string();
1229
58
  case EVP_PKEY_ED448:
1230
116
    return env()->crypto_ed448_string();
1231
51
  case EVP_PKEY_X25519:
1232
102
    return env()->crypto_x25519_string();
1233
51
  case EVP_PKEY_X448:
1234
102
    return env()->crypto_x448_string();
1235
  default:
1236
    return Undefined(env()->isolate());
1237
  }
1238
}
1239
1240
2662
void KeyObjectHandle::GetAsymmetricKeyType(
1241
    const FunctionCallbackInfo<Value>& args) {
1242
  KeyObjectHandle* key;
1243
2662
  ASSIGN_OR_RETURN_UNWRAP(&key, args.Holder());
1244
1245
5324
  args.GetReturnValue().Set(key->GetAsymmetricKeyType());
1246
}
1247
1248
3
void KeyObjectHandle::GetSymmetricKeySize(
1249
    const FunctionCallbackInfo<Value>& args) {
1250
  KeyObjectHandle* key;
1251
3
  ASSIGN_OR_RETURN_UNWRAP(&key, args.Holder());
1252
6
  args.GetReturnValue().Set(
1253
3
      static_cast<uint32_t>(key->Data()->GetSymmetricKeySize()));
1254
}
1255
1256
5424
void KeyObjectHandle::Export(const FunctionCallbackInfo<Value>& args) {
1257
  KeyObjectHandle* key;
1258
5424
  ASSIGN_OR_RETURN_UNWRAP(&key, args.Holder());
1259
1260
5424
  KeyType type = key->Data()->GetKeyType();
1261
1262
  MaybeLocal<Value> result;
1263
5424
  if (type == kKeyTypeSecret) {
1264
5327
    result = key->ExportSecretKey();
1265
97
  } else if (type == kKeyTypePublic) {
1266
52
    unsigned int offset = 0;
1267
    PublicKeyEncodingConfig config =
1268
        ManagedEVPPKey::GetPublicKeyEncodingFromJs(
1269
52
            args, &offset, kKeyContextExport);
1270
52
    CHECK_EQ(offset, static_cast<unsigned int>(args.Length()));
1271
52
    result = key->ExportPublicKey(config);
1272
  } else {
1273
45
    CHECK_EQ(type, kKeyTypePrivate);
1274
45
    unsigned int offset = 0;
1275
    NonCopyableMaybe<PrivateKeyEncodingConfig> config =
1276
        ManagedEVPPKey::GetPrivateKeyEncodingFromJs(
1277
45
            args, &offset, kKeyContextExport);
1278
45
    if (config.IsEmpty())
1279
      return;
1280
45
    CHECK_EQ(offset, static_cast<unsigned int>(args.Length()));
1281
45
    result = key->ExportPrivateKey(config.Release());
1282
  }
1283
1284
5424
  if (!result.IsEmpty())
1285
16272
    args.GetReturnValue().Set(result.FromMaybe(Local<Value>()));
1286
}
1287
1288
5327
MaybeLocal<Value> KeyObjectHandle::ExportSecretKey() const {
1289
5327
  const char* buf = data_->GetSymmetricKey();
1290
5327
  unsigned int len = data_->GetSymmetricKeySize();
1291
10654
  return Buffer::Copy(env(), buf, len).FromMaybe(Local<Value>());
1292
}
1293
1294
52
MaybeLocal<Value> KeyObjectHandle::ExportPublicKey(
1295
    const PublicKeyEncodingConfig& config) const {
1296
52
  return WritePublicKey(env(), data_->GetAsymmetricKey().get(), config);
1297
}
1298
1299
45
MaybeLocal<Value> KeyObjectHandle::ExportPrivateKey(
1300
    const PrivateKeyEncodingConfig& config) const {
1301
45
  return WritePrivateKey(env(), data_->GetAsymmetricKey().get(), config);
1302
}
1303
1304
932
void KeyObjectHandle::ExportJWK(
1305
    const v8::FunctionCallbackInfo<v8::Value>& args) {
1306
932
  Environment* env = Environment::GetCurrent(args);
1307
  KeyObjectHandle* key;
1308
932
  ASSIGN_OR_RETURN_UNWRAP(&key, args.Holder());
1309
1310
932
  CHECK(args[0]->IsObject());
1311
932
  CHECK(args[1]->IsBoolean());
1312
1313
1864
  ExportJWKInner(env, key->Data(), args[0], args[1]->IsTrue());
1314
1315
1864
  args.GetReturnValue().Set(args[0]);
1316
}
1317
1318
775
void NativeKeyObject::Initialize(Environment* env, Local<Object> target) {
1319
775
  SetMethod(env->context(),
1320
            target,
1321
            "createNativeKeyObjectClass",
1322
            NativeKeyObject::CreateNativeKeyObjectClass);
1323
775
}
1324
1325
5357
void NativeKeyObject::RegisterExternalReferences(
1326
    ExternalReferenceRegistry* registry) {
1327
5357
  registry->Register(NativeKeyObject::CreateNativeKeyObjectClass);
1328
5357
  registry->Register(NativeKeyObject::New);
1329
5357
}
1330
1331
9289
void NativeKeyObject::New(const FunctionCallbackInfo<Value>& args) {
1332
9289
  Environment* env = Environment::GetCurrent(args);
1333
9289
  CHECK_EQ(args.Length(), 1);
1334
9289
  CHECK(args[0]->IsObject());
1335
18578
  KeyObjectHandle* handle = Unwrap<KeyObjectHandle>(args[0].As<Object>());
1336
9289
  new NativeKeyObject(env, args.This(), handle->Data());
1337
9289
}
1338
1339
775
void NativeKeyObject::CreateNativeKeyObjectClass(
1340
    const FunctionCallbackInfo<Value>& args) {
1341
775
  Environment* env = Environment::GetCurrent(args);
1342
775
  Isolate* isolate = env->isolate();
1343
1344
775
  CHECK_EQ(args.Length(), 1);
1345
775
  Local<Value> callback = args[0];
1346
775
  CHECK(callback->IsFunction());
1347
1348
  Local<FunctionTemplate> t =
1349
775
      NewFunctionTemplate(isolate, NativeKeyObject::New);
1350
1550
  t->InstanceTemplate()->SetInternalFieldCount(
1351
      KeyObjectHandle::kInternalFieldCount);
1352
775
  t->Inherit(BaseObject::GetConstructorTemplate(env));
1353
1354
  Local<Value> ctor;
1355
1550
  if (!t->GetFunction(env->context()).ToLocal(&ctor))
1356
    return;
1357
1358
1550
  Local<Value> recv = Undefined(env->isolate());
1359
  Local<Value> ret_v;
1360
775
  if (!callback.As<Function>()->Call(
1361
1550
          env->context(), recv, 1, &ctor).ToLocal(&ret_v)) {
1362
    return;
1363
  }
1364
775
  Local<Array> ret = ret_v.As<Array>();
1365
1550
  if (!ret->Get(env->context(), 1).ToLocal(&ctor)) return;
1366
775
  env->set_crypto_key_object_secret_constructor(ctor.As<Function>());
1367
1550
  if (!ret->Get(env->context(), 2).ToLocal(&ctor)) return;
1368
775
  env->set_crypto_key_object_public_constructor(ctor.As<Function>());
1369
1550
  if (!ret->Get(env->context(), 3).ToLocal(&ctor)) return;
1370
775
  env->set_crypto_key_object_private_constructor(ctor.As<Function>());
1371
1550
  args.GetReturnValue().Set(ret);
1372
}
1373
1374
11
BaseObjectPtr<BaseObject> NativeKeyObject::KeyObjectTransferData::Deserialize(
1375
        Environment* env,
1376
        Local<Context> context,
1377
        std::unique_ptr<worker::TransferData> self) {
1378
22
  if (context != env->context()) {
1379
3
    THROW_ERR_MESSAGE_TARGET_CONTEXT_UNAVAILABLE(env);
1380
3
    return {};
1381
  }
1382
1383
  Local<Value> handle;
1384
16
  if (!KeyObjectHandle::Create(env, data_).ToLocal(&handle))
1385
    return {};
1386
1387
  Local<Function> key_ctor;
1388
  Local<Value> arg = FIXED_ONE_BYTE_STRING(env->isolate(),
1389
8
                                           "internal/crypto/keys");
1390
8
  if (env->builtin_module_require()
1391
16
          ->Call(context, Null(env->isolate()), 1, &arg)
1392
8
          .IsEmpty()) {
1393
    return {};
1394
  }
1395

8
  switch (data_->GetKeyType()) {
1396
4
    case kKeyTypeSecret:
1397
4
      key_ctor = env->crypto_key_object_secret_constructor();
1398
4
      break;
1399
2
    case kKeyTypePublic:
1400
2
      key_ctor = env->crypto_key_object_public_constructor();
1401
2
      break;
1402
2
    case kKeyTypePrivate:
1403
2
      key_ctor = env->crypto_key_object_private_constructor();
1404
2
      break;
1405
    default:
1406
      CHECK(false);
1407
  }
1408
1409
  Local<Value> key;
1410
16
  if (!key_ctor->NewInstance(context, 1, &handle).ToLocal(&key))
1411
    return {};
1412
1413
8
  return BaseObjectPtr<BaseObject>(Unwrap<KeyObjectHandle>(key.As<Object>()));
1414
}
1415
1416
11
BaseObject::TransferMode NativeKeyObject::GetTransferMode() const {
1417
11
  return BaseObject::TransferMode::kCloneable;
1418
}
1419
1420
11
std::unique_ptr<worker::TransferData> NativeKeyObject::CloneForMessaging()
1421
    const {
1422
11
  return std::make_unique<KeyObjectTransferData>(handle_data_);
1423
}
1424
1425
252
WebCryptoKeyExportStatus PKEY_SPKI_Export(
1426
    KeyObjectData* key_data,
1427
    ByteSource* out) {
1428
252
  CHECK_EQ(key_data->GetKeyType(), kKeyTypePublic);
1429
504
  ManagedEVPPKey m_pkey = key_data->GetAsymmetricKey();
1430
504
  Mutex::ScopedLock lock(*m_pkey.mutex());
1431
504
  BIOPointer bio(BIO_new(BIO_s_mem()));
1432
252
  CHECK(bio);
1433
252
  if (!i2d_PUBKEY_bio(bio.get(), m_pkey.get()))
1434
    return WebCryptoKeyExportStatus::FAILED;
1435
1436
252
  *out = ByteSource::FromBIO(bio);
1437
252
  return WebCryptoKeyExportStatus::OK;
1438
}
1439
1440
263
WebCryptoKeyExportStatus PKEY_PKCS8_Export(
1441
    KeyObjectData* key_data,
1442
    ByteSource* out) {
1443
263
  CHECK_EQ(key_data->GetKeyType(), kKeyTypePrivate);
1444
526
  ManagedEVPPKey m_pkey = key_data->GetAsymmetricKey();
1445
526
  Mutex::ScopedLock lock(*m_pkey.mutex());
1446
1447
526
  BIOPointer bio(BIO_new(BIO_s_mem()));
1448
263
  CHECK(bio);
1449
526
  PKCS8Pointer p8inf(EVP_PKEY2PKCS8(m_pkey.get()));
1450
263
  if (!i2d_PKCS8_PRIV_KEY_INFO_bio(bio.get(), p8inf.get()))
1451
    return WebCryptoKeyExportStatus::FAILED;
1452
1453
263
  *out = ByteSource::FromBIO(bio);
1454
263
  return WebCryptoKeyExportStatus::OK;
1455
}
1456
1457
namespace Keys {
1458
775
void Initialize(Environment* env, Local<Object> target) {
1459
775
  target->Set(env->context(),
1460
              FIXED_ONE_BYTE_STRING(env->isolate(), "KeyObjectHandle"),
1461
3100
              KeyObjectHandle::Initialize(env)).Check();
1462
1463
2325
  NODE_DEFINE_CONSTANT(target, kWebCryptoKeyFormatRaw);
1464
2325
  NODE_DEFINE_CONSTANT(target, kWebCryptoKeyFormatPKCS8);
1465
2325
  NODE_DEFINE_CONSTANT(target, kWebCryptoKeyFormatSPKI);
1466
2325
  NODE_DEFINE_CONSTANT(target, kWebCryptoKeyFormatJWK);
1467
1468
2325
  NODE_DEFINE_CONSTANT(target, EVP_PKEY_ED25519);
1469
2325
  NODE_DEFINE_CONSTANT(target, EVP_PKEY_ED448);
1470
2325
  NODE_DEFINE_CONSTANT(target, EVP_PKEY_X25519);
1471
2325
  NODE_DEFINE_CONSTANT(target, EVP_PKEY_X448);
1472
2325
  NODE_DEFINE_CONSTANT(target, kKeyEncodingPKCS1);
1473
2325
  NODE_DEFINE_CONSTANT(target, kKeyEncodingPKCS8);
1474
2325
  NODE_DEFINE_CONSTANT(target, kKeyEncodingSPKI);
1475
2325
  NODE_DEFINE_CONSTANT(target, kKeyEncodingSEC1);
1476
2325
  NODE_DEFINE_CONSTANT(target, kKeyFormatDER);
1477
2325
  NODE_DEFINE_CONSTANT(target, kKeyFormatPEM);
1478
2325
  NODE_DEFINE_CONSTANT(target, kKeyFormatJWK);
1479
2325
  NODE_DEFINE_CONSTANT(target, kKeyTypeSecret);
1480
2325
  NODE_DEFINE_CONSTANT(target, kKeyTypePublic);
1481
2325
  NODE_DEFINE_CONSTANT(target, kKeyTypePrivate);
1482
2325
  NODE_DEFINE_CONSTANT(target, kSigEncDER);
1483
1550
  NODE_DEFINE_CONSTANT(target, kSigEncP1363);
1484
775
}
1485
1486
5357
void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
1487
5357
  KeyObjectHandle::RegisterExternalReferences(registry);
1488
5357
}
1489
}  // namespace Keys
1490
1491
}  // namespace crypto
1492
}  // namespace node