GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: crypto/crypto_keys.cc Lines: 645 757 85.2 %
Date: 2021-08-24 04:12:49 Branches: 316 537 58.8 %

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::Just;
28
using v8::Local;
29
using v8::Maybe;
30
using v8::MaybeLocal;
31
using v8::NewStringType;
32
using v8::Nothing;
33
using v8::Number;
34
using v8::Object;
35
using v8::String;
36
using v8::Uint32;
37
using v8::Undefined;
38
using v8::Value;
39
40
namespace crypto {
41
namespace {
42
3891
void GetKeyFormatAndTypeFromJs(
43
    AsymmetricKeyEncodingConfig* config,
44
    const FunctionCallbackInfo<Value>& args,
45
    unsigned int* offset,
46
    KeyEncodingContext context) {
47
  // During key pair generation, it is possible not to specify a key encoding,
48
  // which will lead to a key object being returned.
49

11673
  if (args[*offset]->IsUndefined()) {
50
535
    CHECK_EQ(context, kKeyContextGenerate);
51

1605
    CHECK(args[*offset + 1]->IsUndefined());
52
535
    config->output_key_object_ = true;
53
  } else {
54
3356
    config->output_key_object_ = false;
55
56

6712
    CHECK(args[*offset]->IsInt32());
57
3356
    config->format_ = static_cast<PKFormatType>(
58
10068
        args[*offset].As<Int32>()->Value());
59
60

6712
    if (args[*offset + 1]->IsInt32()) {
61
3916
      config->type_ = Just<PKEncodingType>(static_cast<PKEncodingType>(
62
5874
          args[*offset + 1].As<Int32>()->Value()));
63
    } else {
64



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

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

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

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

80
         data[offset + 1] == 1 &&
198
46
         !(data[offset + 2] & 0xfe);
199
}
200
201
943
bool IsEncryptedPrivateKeyInfo(const unsigned char* data, size_t size) {
202
  // Both PrivateKeyInfo and EncryptedPrivateKeyInfo start with a SEQUENCE.
203
  size_t offset, len;
204
943
  if (!IsASN1Sequence(data, size, &offset, &len))
205
    return false;
206
207
  // A PrivateKeyInfo sequence always starts with an integer whereas an
208
  // EncryptedPrivateKeyInfo starts with an AlgorithmIdentifier.
209
1886
  return len >= 1 &&
210
1886
         data[offset] != 2;
211
}
212
213
1412
ParseKeyResult ParsePrivateKey(EVPKeyPointer* pkey,
214
                               const PrivateKeyEncodingConfig& config,
215
                               const char* key,
216
                               size_t key_len) {
217
1412
  const ByteSource* passphrase = config.passphrase_.get();
218
219
1412
  if (config.format_ == kKeyFormatPEM) {
220
456
    BIOPointer bio(BIO_new_mem_buf(key, key_len));
221
456
    if (!bio)
222
      return ParseKeyResult::kParseKeyFailed;
223
224
456
    pkey->reset(PEM_read_bio_PrivateKey(bio.get(),
225
                                        nullptr,
226
                                        PasswordCallback,
227
                                        &passphrase));
228
  } else {
229
956
    CHECK_EQ(config.format_, kKeyFormatDER);
230
231
1912
    if (config.type_.ToChecked() == kKeyEncodingPKCS1) {
232
13
      const unsigned char* p = reinterpret_cast<const unsigned char*>(key);
233
13
      pkey->reset(d2i_PrivateKey(EVP_PKEY_RSA, nullptr, &p, key_len));
234
1886
    } else if (config.type_.ToChecked() == kKeyEncodingPKCS8) {
235
943
      BIOPointer bio(BIO_new_mem_buf(key, key_len));
236
943
      if (!bio)
237
        return ParseKeyResult::kParseKeyFailed;
238
239
943
      if (IsEncryptedPrivateKeyInfo(
240
              reinterpret_cast<const unsigned char*>(key), key_len)) {
241
17
        pkey->reset(d2i_PKCS8PrivateKey_bio(bio.get(),
242
                                            nullptr,
243
                                            PasswordCallback,
244
                                            &passphrase));
245
      } else {
246
1852
        PKCS8Pointer p8inf(d2i_PKCS8_PRIV_KEY_INFO_bio(bio.get(), nullptr));
247
926
        if (p8inf)
248
926
          pkey->reset(EVP_PKCS82PKEY(p8inf.get()));
249
      }
250
    } else {
251
      CHECK_EQ(config.type_.ToChecked(), kKeyEncodingSEC1);
252
      const unsigned char* p = reinterpret_cast<const unsigned char*>(key);
253
      pkey->reset(d2i_PrivateKey(EVP_PKEY_EC, nullptr, &p, key_len));
254
    }
255
  }
256
257
  // OpenSSL can fail to parse the key but still return a non-null pointer.
258
1412
  unsigned long err = ERR_peek_error();  // NOLINT(runtime/int)
259
1412
  if (err != 0)
260
22
    pkey->reset();
261
262
1412
  if (*pkey)
263
1390
    return ParseKeyResult::kParseKeyOk;
264
22
  if (ERR_GET_LIB(err) == ERR_LIB_PEM &&
265
14
      ERR_GET_REASON(err) == PEM_R_BAD_PASSWORD_READ) {
266
12
    if (config.passphrase_.IsEmpty())
267
11
      return ParseKeyResult::kParseKeyNeedPassphrase;
268
  }
269
11
  return ParseKeyResult::kParseKeyFailed;
270
}
271
272
112
MaybeLocal<Value> BIOToStringOrBuffer(
273
    Environment* env,
274
    BIO* bio,
275
    PKFormatType format) {
276
  BUF_MEM* bptr;
277
112
  BIO_get_mem_ptr(bio, &bptr);
278
112
  if (format == kKeyFormatPEM) {
279
    // PEM is an ASCII format, so we will return it as a string.
280
148
    return String::NewFromUtf8(env->isolate(), bptr->data,
281
                               NewStringType::kNormal,
282
148
                               bptr->length).FromMaybe(Local<Value>());
283
  } else {
284
38
    CHECK_EQ(format, kKeyFormatDER);
285
    // DER is binary, return it as a buffer.
286
38
    return Buffer::Copy(env, bptr->data, bptr->length)
287
38
        .FromMaybe(Local<Value>());
288
  }
289
}
290
291
292
54
MaybeLocal<Value> WritePrivateKey(
293
    Environment* env,
294
    EVP_PKEY* pkey,
295
    const PrivateKeyEncodingConfig& config) {
296
108
  BIOPointer bio(BIO_new(BIO_s_mem()));
297
54
  CHECK(bio);
298
299
  // If an empty string was passed as the passphrase, the ByteSource might
300
  // contain a null pointer, which OpenSSL will ignore, causing it to invoke its
301
  // default passphrase callback, which would block the thread until the user
302
  // manually enters a passphrase. We could supply our own passphrase callback
303
  // to handle this special case, but it is easier to avoid passing a null
304
  // pointer to OpenSSL.
305
54
  char* pass = nullptr;
306
54
  size_t pass_len = 0;
307
54
  if (!config.passphrase_.IsEmpty()) {
308
11
    pass = const_cast<char*>(config.passphrase_->get());
309
11
    pass_len = config.passphrase_->size();
310
11
    if (pass == nullptr) {
311
      // OpenSSL will not actually dereference this pointer, so it can be any
312
      // non-null pointer. We cannot assert that directly, which is why we
313
      // intentionally use a pointer that will likely cause a segmentation fault
314
      // when dereferenced.
315
2
      CHECK_EQ(pass_len, 0);
316
2
      pass = reinterpret_cast<char*>(-1);
317
2
      CHECK_NE(pass, nullptr);
318
    }
319
  }
320
321
  bool err;
322
323
54
  PKEncodingType encoding_type = config.type_.ToChecked();
324
54
  if (encoding_type == kKeyEncodingPKCS1) {
325
    // PKCS#1 is only permitted for RSA keys.
326
12
    CHECK_EQ(EVP_PKEY_id(pkey), EVP_PKEY_RSA);
327
328
24
    RSAPointer rsa(EVP_PKEY_get1_RSA(pkey));
329
12
    if (config.format_ == kKeyFormatPEM) {
330
      // Encode PKCS#1 as PEM.
331
11
      err = PEM_write_bio_RSAPrivateKey(
332
                bio.get(), rsa.get(),
333
11
                config.cipher_,
334
                reinterpret_cast<unsigned char*>(pass),
335
                pass_len,
336
                nullptr, nullptr) != 1;
337
    } else {
338
      // Encode PKCS#1 as DER. This does not permit encryption.
339
1
      CHECK_EQ(config.format_, kKeyFormatDER);
340
1
      CHECK_NULL(config.cipher_);
341
1
      err = i2d_RSAPrivateKey_bio(bio.get(), rsa.get()) != 1;
342
    }
343
42
  } else if (encoding_type == kKeyEncodingPKCS8) {
344
38
    if (config.format_ == kKeyFormatPEM) {
345
      // Encode PKCS#8 as PEM.
346
21
      err = PEM_write_bio_PKCS8PrivateKey(
347
                bio.get(), pkey,
348
21
                config.cipher_,
349
                pass,
350
                pass_len,
351
                nullptr, nullptr) != 1;
352
    } else {
353
      // Encode PKCS#8 as DER.
354
17
      CHECK_EQ(config.format_, kKeyFormatDER);
355
17
      err = i2d_PKCS8PrivateKey_bio(
356
                bio.get(), pkey,
357
17
                config.cipher_,
358
                pass,
359
                pass_len,
360
                nullptr, nullptr) != 1;
361
    }
362
  } else {
363
4
    CHECK_EQ(encoding_type, kKeyEncodingSEC1);
364
365
    // SEC1 is only permitted for EC keys.
366
4
    CHECK_EQ(EVP_PKEY_id(pkey), EVP_PKEY_EC);
367
368
8
    ECKeyPointer ec_key(EVP_PKEY_get1_EC_KEY(pkey));
369
4
    if (config.format_ == kKeyFormatPEM) {
370
      // Encode SEC1 as PEM.
371
4
      err = PEM_write_bio_ECPrivateKey(
372
                bio.get(), ec_key.get(),
373
4
                config.cipher_,
374
                reinterpret_cast<unsigned char*>(pass),
375
                pass_len,
376
                nullptr, nullptr) != 1;
377
    } else {
378
      // Encode SEC1 as DER. This does not permit encryption.
379
      CHECK_EQ(config.format_, kKeyFormatDER);
380
      CHECK_NULL(config.cipher_);
381
      err = i2d_ECPrivateKey_bio(bio.get(), ec_key.get()) != 1;
382
    }
383
  }
384
385
54
  if (err) {
386
    ThrowCryptoError(env, ERR_get_error(), "Failed to encode private key");
387
    return MaybeLocal<Value>();
388
  }
389
54
  return BIOToStringOrBuffer(env, bio.get(), config.format_);
390
}
391
392
62
bool WritePublicKeyInner(EVP_PKEY* pkey,
393
                         const BIOPointer& bio,
394
                         const PublicKeyEncodingConfig& config) {
395
124
  if (config.type_.ToChecked() == kKeyEncodingPKCS1) {
396
    // PKCS#1 is only valid for RSA keys.
397
13
    CHECK_EQ(EVP_PKEY_id(pkey), EVP_PKEY_RSA);
398
26
    RSAPointer rsa(EVP_PKEY_get1_RSA(pkey));
399
13
    if (config.format_ == kKeyFormatPEM) {
400
      // Encode PKCS#1 as PEM.
401
7
      return PEM_write_bio_RSAPublicKey(bio.get(), rsa.get()) == 1;
402
    } else {
403
      // Encode PKCS#1 as DER.
404
6
      CHECK_EQ(config.format_, kKeyFormatDER);
405
6
      return i2d_RSAPublicKey_bio(bio.get(), rsa.get()) == 1;
406
    }
407
  } else {
408
98
    CHECK_EQ(config.type_.ToChecked(), kKeyEncodingSPKI);
409
49
    if (config.format_ == kKeyFormatPEM) {
410
      // Encode SPKI as PEM.
411
31
      return PEM_write_bio_PUBKEY(bio.get(), pkey) == 1;
412
    } else {
413
      // Encode SPKI as DER.
414
18
      CHECK_EQ(config.format_, kKeyFormatDER);
415
18
      return i2d_PUBKEY_bio(bio.get(), pkey) == 1;
416
    }
417
  }
418
}
419
420
62
MaybeLocal<Value> WritePublicKey(Environment* env,
421
                                 EVP_PKEY* pkey,
422
                                 const PublicKeyEncodingConfig& config) {
423
124
  BIOPointer bio(BIO_new(BIO_s_mem()));
424
62
  CHECK(bio);
425
426
62
  if (!WritePublicKeyInner(pkey, bio, config)) {
427
4
    ThrowCryptoError(env, ERR_get_error(), "Failed to encode public key");
428
4
    return MaybeLocal<Value>();
429
  }
430
58
  return BIOToStringOrBuffer(env, bio.get(), config.format_);
431
}
432
433
291
Maybe<bool> ExportJWKSecretKey(
434
    Environment* env,
435
    std::shared_ptr<KeyObjectData> key,
436
    Local<Object> target) {
437
291
  CHECK_EQ(key->GetKeyType(), kKeyTypeSecret);
438
439
  Local<Value> error;
440
  Local<Value> raw;
441
  MaybeLocal<Value> key_data =
442
      StringBytes::Encode(
443
          env->isolate(),
444
          key->GetSymmetricKey(),
445
          key->GetSymmetricKeySize(),
446
          BASE64URL,
447
291
          &error);
448
291
  if (key_data.IsEmpty()) {
449
    CHECK(!error.IsEmpty());
450
    env->isolate()->ThrowException(error);
451
    return Nothing<bool>();
452
  }
453
291
  if (!key_data.ToLocal(&raw))
454
    return Nothing<bool>();
455
456
582
  if (target->Set(
457
          env->context(),
458
          env->jwk_kty_string(),
459
1455
          env->jwk_oct_string()).IsNothing() ||
460
291
      target->Set(
461
          env->context(),
462
          env->jwk_k_string(),
463

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

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

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

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

201
      if (args[*offset]->IsString()) {
684
24
        Utf8Value cipher_name(env->isolate(), args[*offset]);
685
12
        result.cipher_ = EVP_get_cipherbyname(*cipher_name);
686
12
        if (result.cipher_ == nullptr) {
687
1
          THROW_ERR_CRYPTO_UNKNOWN_CIPHER(env);
688
1
          return NonCopyableMaybe<PrivateKeyEncodingConfig>();
689
        }
690
11
        needs_passphrase = true;
691
      } else {
692

165
        CHECK(args[*offset]->IsNullOrUndefined());
693
55
        result.cipher_ = nullptr;
694
      }
695
66
      (*offset)++;
696
    }
697
698

6562
    if (IsAnyByteSource(args[*offset])) {
699

96
      CHECK_IMPLIES(context != kKeyContextInput, result.cipher_ != nullptr);
700
192
      ArrayBufferOrViewContents<char> passphrase(args[*offset]);
701
96
      if (UNLIKELY(!passphrase.CheckSizeInt32())) {
702
        THROW_ERR_OUT_OF_RANGE(env, "passphrase is too big");
703
        return NonCopyableMaybe<PrivateKeyEncodingConfig>();
704
      }
705
192
      result.passphrase_ = NonCopyableMaybe<ByteSource>(
706
288
          passphrase.ToNullTerminatedCopy());
707
    } else {
708


9555
      CHECK(args[*offset]->IsNullOrUndefined() && !needs_passphrase);
709
    }
710
  }
711
712
3549
  (*offset)++;
713
3549
  return NonCopyableMaybe<PrivateKeyEncodingConfig>(std::move(result));
714
}
715
716
341
PublicKeyEncodingConfig ManagedEVPPKey::GetPublicKeyEncodingFromJs(
717
    const FunctionCallbackInfo<Value>& args,
718
    unsigned int* offset,
719
    KeyEncodingContext context) {
720
341
  PublicKeyEncodingConfig result;
721
341
  GetKeyFormatAndTypeFromJs(&result, args, offset, context);
722
341
  return result;
723
}
724
725
1285
ManagedEVPPKey ManagedEVPPKey::GetPrivateKeyFromJs(
726
    const FunctionCallbackInfo<Value>& args,
727
    unsigned int* offset,
728
    bool allow_key_object) {
729


5140
  if (args[*offset]->IsString() || IsAnyByteSource(args[*offset])) {
730
1097
    Environment* env = Environment::GetCurrent(args);
731
3291
    ByteSource key = ByteSource::FromStringOrBuffer(env, args[(*offset)++]);
732
    NonCopyableMaybe<PrivateKeyEncodingConfig> config =
733
2194
        GetPrivateKeyEncodingFromJs(args, offset, kKeyContextInput);
734
1097
    if (config.IsEmpty())
735
      return ManagedEVPPKey();
736
737
1097
    EVPKeyPointer pkey;
738
    ParseKeyResult ret =
739
1097
        ParsePrivateKey(&pkey, config.Release(), key.get(), key.size());
740
1097
    return GetParsedKey(env, std::move(pkey), ret,
741
1097
                        "Failed to read private key");
742
  } else {
743


376
    CHECK(args[*offset]->IsObject() && allow_key_object);
744
    KeyObjectHandle* key;
745

564
    ASSIGN_OR_RETURN_UNWRAP(&key, args[*offset].As<Object>(), ManagedEVPPKey());
746
188
    CHECK_EQ(key->Data()->GetKeyType(), kKeyTypePrivate);
747
188
    (*offset) += 4;
748
188
    return key->Data()->GetAsymmetricKey();
749
  }
750
}
751
752
2707
ManagedEVPPKey ManagedEVPPKey::GetPublicOrPrivateKeyFromJs(
753
    const FunctionCallbackInfo<Value>& args,
754
    unsigned int* offset) {
755

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

952
      switch (config.type_.ToChecked()) {
782
34
        case kKeyEncodingPKCS1:
783
68
          is_public = !IsRSAPrivateKey(
784
34
              reinterpret_cast<const unsigned char*>(data.data()), data.size());
785
34
          break;
786
861
        case kKeyEncodingSPKI:
787
861
          is_public = true;
788
861
          break;
789
57
        case kKeyEncodingPKCS8:
790
        case kKeyEncodingSEC1:
791
57
          is_public = false;
792
57
          break;
793
        default:
794
          UNREACHABLE("Invalid key encoding type");
795
      }
796
797
952
      if (is_public) {
798
883
        ret = ParsePublicKey(&pkey, config, data.data(), data.size());
799
      } else {
800
69
        ret = ParsePrivateKey(&pkey, config, data.data(), data.size());
801
      }
802
    }
803
804
    return ManagedEVPPKey::GetParsedKey(
805
2118
        env, std::move(pkey), ret, "Failed to read asymmetric key");
806
  } else {
807

1178
    CHECK(args[*offset]->IsObject());
808
1767
    KeyObjectHandle* key = Unwrap<KeyObjectHandle>(args[*offset].As<Object>());
809
589
    CHECK_NOT_NULL(key);
810
589
    CHECK_NE(key->Data()->GetKeyType(), kKeyTypeSecret);
811
589
    (*offset) += 4;
812
589
    return key->Data()->GetAsymmetricKey();
813
  }
814
}
815
816
3215
ManagedEVPPKey ManagedEVPPKey::GetParsedKey(Environment* env,
817
                                            EVPKeyPointer&& pkey,
818
                                            ParseKeyResult ret,
819
                                            const char* default_msg) {
820
3215
  switch (ret) {
821
3193
    case ParseKeyResult::kParseKeyOk:
822
3193
      CHECK(pkey);
823
3193
      break;
824
11
    case ParseKeyResult::kParseKeyNeedPassphrase:
825
11
      THROW_ERR_MISSING_PASSPHRASE(env,
826
                                   "Passphrase required for encrypted key");
827
11
      break;
828
11
    default:
829
11
      ThrowCryptoError(env, ERR_get_error(), default_msg);
830
  }
831
832
3215
  return ManagedEVPPKey(std::move(pkey));
833
}
834
835
1884
KeyObjectData::KeyObjectData(
836
1884
    ByteSource symmetric_key)
837
    : key_type_(KeyType::kKeyTypeSecret),
838
1884
      symmetric_key_(std::move(symmetric_key)),
839
1884
      symmetric_key_len_(symmetric_key_.size()),
840
3768
      asymmetric_key_() {}
841
842
3031
KeyObjectData::KeyObjectData(
843
    KeyType type,
844
3031
    const ManagedEVPPKey& pkey)
845
    : key_type_(type),
846
      symmetric_key_(),
847
      symmetric_key_len_(0),
848
3031
      asymmetric_key_{pkey} {}
849
850
void KeyObjectData::MemoryInfo(MemoryTracker* tracker) const {
851
  switch (GetKeyType()) {
852
    case kKeyTypeSecret:
853
      tracker->TrackFieldWithSize("symmetric_key", symmetric_key_.size());
854
      break;
855
    case kKeyTypePrivate:
856
      // Fall through
857
    case kKeyTypePublic:
858
      tracker->TrackFieldWithSize("key", asymmetric_key_);
859
      break;
860
    default:
861
      UNREACHABLE();
862
  }
863
}
864
865
1884
std::shared_ptr<KeyObjectData> KeyObjectData::CreateSecret(ByteSource key) {
866
1884
  CHECK(key);
867
1884
  return std::shared_ptr<KeyObjectData>(new KeyObjectData(std::move(key)));
868
}
869
870
3031
std::shared_ptr<KeyObjectData> KeyObjectData::CreateAsymmetric(
871
    KeyType key_type,
872
    const ManagedEVPPKey& pkey) {
873
3031
  CHECK(pkey);
874
3031
  return std::shared_ptr<KeyObjectData>(new KeyObjectData(key_type, pkey));
875
}
876
877
11471
KeyType KeyObjectData::GetKeyType() const {
878
11471
  return key_type_;
879
}
880
881
8126
ManagedEVPPKey KeyObjectData::GetAsymmetricKey() const {
882
8126
  CHECK_NE(key_type_, kKeyTypeSecret);
883
8126
  return asymmetric_key_;
884
}
885
886
2627
const char* KeyObjectData::GetSymmetricKey() const {
887
2627
  CHECK_EQ(key_type_, kKeyTypeSecret);
888
2627
  return symmetric_key_.get();
889
}
890
891
3901
size_t KeyObjectData::GetSymmetricKeySize() const {
892
3901
  CHECK_EQ(key_type_, kKeyTypeSecret);
893
3901
  return symmetric_key_len_;
894
}
895
896
5000
v8::Local<v8::Function> KeyObjectHandle::Initialize(Environment* env) {
897
5000
  Local<Function> templ = env->crypto_key_object_handle_constructor();
898
5000
  if (!templ.IsEmpty()) {
899
723
    return templ;
900
  }
901
4277
  Local<FunctionTemplate> t = env->NewFunctionTemplate(New);
902
8554
  t->InstanceTemplate()->SetInternalFieldCount(
903
      KeyObjectHandle::kInternalFieldCount);
904
4277
  t->Inherit(BaseObject::GetConstructorTemplate(env));
905
906
4277
  env->SetProtoMethod(t, "init", Init);
907
4277
  env->SetProtoMethodNoSideEffect(t, "getSymmetricKeySize",
908
                                  GetSymmetricKeySize);
909
4277
  env->SetProtoMethodNoSideEffect(t, "getAsymmetricKeyType",
910
                                  GetAsymmetricKeyType);
911
4277
  env->SetProtoMethod(t, "export", Export);
912
4277
  env->SetProtoMethod(t, "exportJwk", ExportJWK);
913
4277
  env->SetProtoMethod(t, "initECRaw", InitECRaw);
914
4277
  env->SetProtoMethod(t, "initEDRaw", InitEDRaw);
915
4277
  env->SetProtoMethod(t, "initJwk", InitJWK);
916
4277
  env->SetProtoMethod(t, "keyDetail", GetKeyDetail);
917
918
4277
  auto function = t->GetFunction(env->context()).ToLocalChecked();
919
4277
  env->set_crypto_key_object_handle_constructor(function);
920
4277
  return function;
921
}
922
923
723
MaybeLocal<Object> KeyObjectHandle::Create(
924
    Environment* env,
925
    std::shared_ptr<KeyObjectData> data) {
926
  Local<Object> obj;
927
723
  Local<Function> ctor = KeyObjectHandle::Initialize(env);
928
1446
  CHECK(!env->crypto_key_object_handle_constructor().IsEmpty());
929
1446
  if (!ctor->NewInstance(env->context(), 0, nullptr).ToLocal(&obj))
930
    return MaybeLocal<Object>();
931
932
723
  KeyObjectHandle* key = Unwrap<KeyObjectHandle>(obj);
933
723
  CHECK_NOT_NULL(key);
934
723
  key->data_ = data;
935
723
  return obj;
936
}
937
938
14948
const std::shared_ptr<KeyObjectData>& KeyObjectHandle::Data() {
939
14948
  return data_;
940
}
941
942
4911
void KeyObjectHandle::New(const FunctionCallbackInfo<Value>& args) {
943
4911
  CHECK(args.IsConstructCall());
944
4911
  Environment* env = Environment::GetCurrent(args);
945
4911
  new KeyObjectHandle(env, args.This());
946
4911
}
947
948
4911
KeyObjectHandle::KeyObjectHandle(Environment* env,
949
4911
                                 Local<Object> wrap)
950
4911
    : BaseObject(env, wrap) {
951
4911
  MakeWeak();
952
4911
}
953
954
3224
void KeyObjectHandle::Init(const FunctionCallbackInfo<Value>& args) {
955
  KeyObjectHandle* key;
956
3229
  ASSIGN_OR_RETURN_UNWRAP(&key, args.Holder());
957
3224
  MarkPopErrorOnReturn mark_pop_error_on_return;
958
959
3224
  CHECK(args[0]->IsInt32());
960
6448
  KeyType type = static_cast<KeyType>(args[0].As<Uint32>()->Value());
961
962
  unsigned int offset;
963
3224
  ManagedEVPPKey pkey;
964
965

3224
  switch (type) {
966
1431
  case kKeyTypeSecret: {
967
1431
    CHECK_EQ(args.Length(), 2);
968
2862
    ArrayBufferOrViewContents<char> buf(args[1]);
969
1431
    key->data_ = KeyObjectData::CreateSecret(buf.ToCopy());
970
1431
    break;
971
  }
972
882
  case kKeyTypePublic: {
973
882
    CHECK_EQ(args.Length(), 5);
974
975
882
    offset = 1;
976
882
    pkey = ManagedEVPPKey::GetPublicOrPrivateKeyFromJs(args, &offset);
977
882
    if (!pkey)
978
      return;
979
882
    key->data_ = KeyObjectData::CreateAsymmetric(type, pkey);
980
882
    break;
981
  }
982
911
  case kKeyTypePrivate: {
983
911
    CHECK_EQ(args.Length(), 5);
984
985
911
    offset = 1;
986
911
    pkey = ManagedEVPPKey::GetPrivateKeyFromJs(args, &offset, false);
987
911
    if (!pkey)
988
5
      return;
989
906
    key->data_ = KeyObjectData::CreateAsymmetric(type, pkey);
990
906
    break;
991
  }
992
  default:
993
    UNREACHABLE();
994
  }
995
}
996
997
928
void KeyObjectHandle::InitJWK(const FunctionCallbackInfo<Value>& args) {
998
928
  Environment* env = Environment::GetCurrent(args);
999
  KeyObjectHandle* key;
1000
928
  ASSIGN_OR_RETURN_UNWRAP(&key, args.Holder());
1001
928
  MarkPopErrorOnReturn mark_pop_error_on_return;
1002
1003
  // The argument must be a JavaScript object that we will inspect
1004
  // to get the JWK properties from.
1005
928
  CHECK(args[0]->IsObject());
1006
1007
  // Step one, Secret key or not?
1008
1856
  Local<Object> input = args[0].As<Object>();
1009
1010
  Local<Value> kty;
1011

3712
  if (!input->Get(env->context(), env->jwk_kty_string()).ToLocal(&kty) ||
1012
1856
      !kty->IsString()) {
1013
    return THROW_ERR_CRYPTO_INVALID_JWK(env);
1014
  }
1015
1016
928
  Utf8Value kty_string(env->isolate(), kty);
1017
1018
928
  if (strcmp(*kty_string, "oct") == 0) {
1019
    // Secret key
1020
270
    key->data_ = ImportJWKSecretKey(env, input);
1021
270
    if (!key->data_) {
1022
      // ImportJWKSecretKey is responsible for throwing an appropriate error
1023
      return;
1024
    }
1025
  } else {
1026
658
    key->data_ = ImportJWKAsymmetricKey(env, input, *kty_string, args, 1);
1027
658
    if (!key->data_) {
1028
      // ImportJWKAsymmetricKey is responsible for throwing an appropriate error
1029
      return;
1030
    }
1031
  }
1032
1033
1856
  args.GetReturnValue().Set(key->data_->GetKeyType());
1034
}
1035
1036
void KeyObjectHandle::InitECRaw(const FunctionCallbackInfo<Value>& args) {
1037
  Environment* env = Environment::GetCurrent(args);
1038
  KeyObjectHandle* key;
1039
  ASSIGN_OR_RETURN_UNWRAP(&key, args.Holder());
1040
1041
  CHECK(args[0]->IsString());
1042
  Utf8Value name(env->isolate(), args[0]);
1043
1044
  MarkPopErrorOnReturn mark_pop_error_on_return;
1045
1046
  int id = OBJ_txt2nid(*name);
1047
  ECKeyPointer eckey(EC_KEY_new_by_curve_name(id));
1048
  if (!eckey)
1049
    return args.GetReturnValue().Set(false);
1050
1051
  const EC_GROUP* group = EC_KEY_get0_group(eckey.get());
1052
  ECPointPointer pub(ECDH::BufferToPoint(env, group, args[1]));
1053
1054
  if (!pub ||
1055
      !eckey ||
1056
      !EC_KEY_set_public_key(eckey.get(), pub.get())) {
1057
    return args.GetReturnValue().Set(false);
1058
  }
1059
1060
  EVPKeyPointer pkey(EVP_PKEY_new());
1061
  if (!EVP_PKEY_assign_EC_KEY(pkey.get(), eckey.get()))
1062
    args.GetReturnValue().Set(false);
1063
1064
  eckey.release();  // Release ownership of the key
1065
1066
  key->data_ =
1067
      KeyObjectData::CreateAsymmetric(
1068
          kKeyTypePublic,
1069
          ManagedEVPPKey(std::move(pkey)));
1070
1071
  args.GetReturnValue().Set(true);
1072
}
1073
1074
32
void KeyObjectHandle::InitEDRaw(const FunctionCallbackInfo<Value>& args) {
1075
32
  Environment* env = Environment::GetCurrent(args);
1076
  KeyObjectHandle* key;
1077
32
  ASSIGN_OR_RETURN_UNWRAP(&key, args.Holder());
1078
1079
64
  CHECK(args[0]->IsString());
1080
32
  Utf8Value name(env->isolate(), args[0]);
1081
1082
32
  ArrayBufferOrViewContents<unsigned char> key_data(args[1]);
1083
64
  KeyType type = static_cast<KeyType>(args[2].As<Int32>()->Value());
1084
1085
32
  MarkPopErrorOnReturn mark_pop_error_on_return;
1086
1087
  typedef EVP_PKEY* (*new_key_fn)(int, ENGINE*, const unsigned char*, size_t);
1088
32
  new_key_fn fn = type == kKeyTypePrivate
1089
32
      ? EVP_PKEY_new_raw_private_key
1090
      : EVP_PKEY_new_raw_public_key;
1091
1092
32
  int id = GetOKPCurveFromName(*name);
1093
1094
32
  switch (id) {
1095
32
    case EVP_PKEY_X25519:
1096
    case EVP_PKEY_X448:
1097
    case EVP_PKEY_ED25519:
1098
    case EVP_PKEY_ED448: {
1099
32
      EVPKeyPointer pkey(fn(id, nullptr, key_data.data(), key_data.size()));
1100
32
      if (!pkey)
1101
        return args.GetReturnValue().Set(false);
1102
32
      key->data_ =
1103
64
          KeyObjectData::CreateAsymmetric(
1104
              type,
1105
96
              ManagedEVPPKey(std::move(pkey)));
1106
32
      CHECK(key->data_);
1107
32
      break;
1108
    }
1109
    default:
1110
      UNREACHABLE();
1111
  }
1112
1113
64
  args.GetReturnValue().Set(true);
1114
}
1115
1116
3876
void KeyObjectHandle::GetKeyDetail(const FunctionCallbackInfo<Value>& args) {
1117
3876
  Environment* env = Environment::GetCurrent(args);
1118
  KeyObjectHandle* key;
1119
3876
  ASSIGN_OR_RETURN_UNWRAP(&key, args.Holder());
1120
1121
3876
  CHECK(args[0]->IsObject());
1122
1123
3876
  std::shared_ptr<KeyObjectData> data = key->Data();
1124
1125
3876
  switch (data->GetKeyType()) {
1126
1509
    case kKeyTypeSecret:
1127
4527
      if (GetSecretKeyDetail(env, data, args[0].As<Object>()).IsNothing())
1128
        return;
1129
1509
      break;
1130
2367
    case kKeyTypePublic:
1131
      // Fall through
1132
    case kKeyTypePrivate:
1133
7101
      if (GetAsymmetricKeyDetail(env, data, args[0].As<Object>()).IsNothing())
1134
        return;
1135
2367
      break;
1136
    default:
1137
      UNREACHABLE();
1138
  }
1139
1140
7752
  args.GetReturnValue().Set(args[0]);
1141
}
1142
1143
153
Local<Value> KeyObjectHandle::GetAsymmetricKeyType() const {
1144
306
  const ManagedEVPPKey& key = data_->GetAsymmetricKey();
1145


153
  switch (EVP_PKEY_id(key.get())) {
1146
33
  case EVP_PKEY_RSA:
1147
66
    return env()->crypto_rsa_string();
1148
10
  case EVP_PKEY_RSA_PSS:
1149
20
    return env()->crypto_rsa_pss_string();
1150
10
  case EVP_PKEY_DSA:
1151
20
    return env()->crypto_dsa_string();
1152
22
  case EVP_PKEY_DH:
1153
44
    return env()->crypto_dh_string();
1154
36
  case EVP_PKEY_EC:
1155
72
    return env()->crypto_ec_string();
1156
9
  case EVP_PKEY_ED25519:
1157
18
    return env()->crypto_ed25519_string();
1158
9
  case EVP_PKEY_ED448:
1159
18
    return env()->crypto_ed448_string();
1160
12
  case EVP_PKEY_X25519:
1161
24
    return env()->crypto_x25519_string();
1162
12
  case EVP_PKEY_X448:
1163
24
    return env()->crypto_x448_string();
1164
  default:
1165
    return Undefined(env()->isolate());
1166
  }
1167
}
1168
1169
153
void KeyObjectHandle::GetAsymmetricKeyType(
1170
    const FunctionCallbackInfo<Value>& args) {
1171
  KeyObjectHandle* key;
1172
153
  ASSIGN_OR_RETURN_UNWRAP(&key, args.Holder());
1173
1174
306
  args.GetReturnValue().Set(key->GetAsymmetricKeyType());
1175
}
1176
1177
1
void KeyObjectHandle::GetSymmetricKeySize(
1178
    const FunctionCallbackInfo<Value>& args) {
1179
  KeyObjectHandle* key;
1180
1
  ASSIGN_OR_RETURN_UNWRAP(&key, args.Holder());
1181
2
  args.GetReturnValue().Set(
1182
1
      static_cast<uint32_t>(key->Data()->GetSymmetricKeySize()));
1183
}
1184
1185
752
void KeyObjectHandle::Export(const FunctionCallbackInfo<Value>& args) {
1186
  KeyObjectHandle* key;
1187
752
  ASSIGN_OR_RETURN_UNWRAP(&key, args.Holder());
1188
1189
752
  KeyType type = key->Data()->GetKeyType();
1190
1191
  MaybeLocal<Value> result;
1192
752
  if (type == kKeyTypeSecret) {
1193
670
    result = key->ExportSecretKey();
1194
82
  } else if (type == kKeyTypePublic) {
1195
44
    unsigned int offset = 0;
1196
    PublicKeyEncodingConfig config =
1197
        ManagedEVPPKey::GetPublicKeyEncodingFromJs(
1198
44
            args, &offset, kKeyContextExport);
1199
44
    CHECK_EQ(offset, static_cast<unsigned int>(args.Length()));
1200
44
    result = key->ExportPublicKey(config);
1201
  } else {
1202
38
    CHECK_EQ(type, kKeyTypePrivate);
1203
38
    unsigned int offset = 0;
1204
    NonCopyableMaybe<PrivateKeyEncodingConfig> config =
1205
        ManagedEVPPKey::GetPrivateKeyEncodingFromJs(
1206
38
            args, &offset, kKeyContextExport);
1207
38
    if (config.IsEmpty())
1208
      return;
1209
38
    CHECK_EQ(offset, static_cast<unsigned int>(args.Length()));
1210
38
    result = key->ExportPrivateKey(config.Release());
1211
  }
1212
1213
752
  if (!result.IsEmpty())
1214
2256
    args.GetReturnValue().Set(result.FromMaybe(Local<Value>()));
1215
}
1216
1217
670
MaybeLocal<Value> KeyObjectHandle::ExportSecretKey() const {
1218
670
  const char* buf = data_->GetSymmetricKey();
1219
670
  unsigned int len = data_->GetSymmetricKeySize();
1220
1340
  return Buffer::Copy(env(), buf, len).FromMaybe(Local<Value>());
1221
}
1222
1223
44
MaybeLocal<Value> KeyObjectHandle::ExportPublicKey(
1224
    const PublicKeyEncodingConfig& config) const {
1225
44
  return WritePublicKey(env(), data_->GetAsymmetricKey().get(), config);
1226
}
1227
1228
38
MaybeLocal<Value> KeyObjectHandle::ExportPrivateKey(
1229
    const PrivateKeyEncodingConfig& config) const {
1230
38
  return WritePrivateKey(env(), data_->GetAsymmetricKey().get(), config);
1231
}
1232
1233
930
void KeyObjectHandle::ExportJWK(
1234
    const v8::FunctionCallbackInfo<v8::Value>& args) {
1235
930
  Environment* env = Environment::GetCurrent(args);
1236
  KeyObjectHandle* key;
1237
930
  ASSIGN_OR_RETURN_UNWRAP(&key, args.Holder());
1238
1239
930
  CHECK(args[0]->IsObject());
1240
1241
930
  ExportJWKInner(env, key->Data(), args[0]);
1242
1243
1860
  args.GetReturnValue().Set(args[0]);
1244
}
1245
1246
4277
void NativeKeyObject::Initialize(Environment* env, Local<Object> target) {
1247
4277
  env->SetMethod(target, "createNativeKeyObjectClass",
1248
                 NativeKeyObject::CreateNativeKeyObjectClass);
1249
4277
}
1250
1251
4888
void NativeKeyObject::New(const FunctionCallbackInfo<Value>& args) {
1252
4888
  Environment* env = Environment::GetCurrent(args);
1253
4888
  CHECK_EQ(args.Length(), 1);
1254
4888
  CHECK(args[0]->IsObject());
1255
9776
  KeyObjectHandle* handle = Unwrap<KeyObjectHandle>(args[0].As<Object>());
1256
4888
  new NativeKeyObject(env, args.This(), handle->Data());
1257
4888
}
1258
1259
4277
void NativeKeyObject::CreateNativeKeyObjectClass(
1260
    const FunctionCallbackInfo<Value>& args) {
1261
4277
  Environment* env = Environment::GetCurrent(args);
1262
1263
4277
  CHECK_EQ(args.Length(), 1);
1264
4277
  Local<Value> callback = args[0];
1265
4277
  CHECK(callback->IsFunction());
1266
1267
4277
  Local<FunctionTemplate> t = env->NewFunctionTemplate(NativeKeyObject::New);
1268
8554
  t->InstanceTemplate()->SetInternalFieldCount(
1269
      KeyObjectHandle::kInternalFieldCount);
1270
4277
  t->Inherit(BaseObject::GetConstructorTemplate(env));
1271
1272
  Local<Value> ctor;
1273
8554
  if (!t->GetFunction(env->context()).ToLocal(&ctor))
1274
    return;
1275
1276
8554
  Local<Value> recv = Undefined(env->isolate());
1277
  Local<Value> ret_v;
1278
4277
  if (!callback.As<Function>()->Call(
1279
8554
          env->context(), recv, 1, &ctor).ToLocal(&ret_v)) {
1280
    return;
1281
  }
1282
4277
  Local<Array> ret = ret_v.As<Array>();
1283
8554
  if (!ret->Get(env->context(), 1).ToLocal(&ctor)) return;
1284
4277
  env->set_crypto_key_object_secret_constructor(ctor.As<Function>());
1285
8554
  if (!ret->Get(env->context(), 2).ToLocal(&ctor)) return;
1286
4277
  env->set_crypto_key_object_public_constructor(ctor.As<Function>());
1287
8554
  if (!ret->Get(env->context(), 3).ToLocal(&ctor)) return;
1288
4277
  env->set_crypto_key_object_private_constructor(ctor.As<Function>());
1289
8554
  args.GetReturnValue().Set(ret);
1290
}
1291
1292
11
BaseObjectPtr<BaseObject> NativeKeyObject::KeyObjectTransferData::Deserialize(
1293
        Environment* env,
1294
        Local<Context> context,
1295
        std::unique_ptr<worker::TransferData> self) {
1296
22
  if (context != env->context()) {
1297
3
    THROW_ERR_MESSAGE_TARGET_CONTEXT_UNAVAILABLE(env);
1298
3
    return {};
1299
  }
1300
1301
  Local<Value> handle;
1302
16
  if (!KeyObjectHandle::Create(env, data_).ToLocal(&handle))
1303
    return {};
1304
1305
  Local<Function> key_ctor;
1306
  Local<Value> arg = FIXED_ONE_BYTE_STRING(env->isolate(),
1307
8
                                           "internal/crypto/keys");
1308
8
  if (env->native_module_require()->
1309
24
      Call(context, Null(env->isolate()), 1, &arg).IsEmpty()) {
1310
    return {};
1311
  }
1312

8
  switch (data_->GetKeyType()) {
1313
4
    case kKeyTypeSecret:
1314
4
      key_ctor = env->crypto_key_object_secret_constructor();
1315
4
      break;
1316
2
    case kKeyTypePublic:
1317
2
      key_ctor = env->crypto_key_object_public_constructor();
1318
2
      break;
1319
2
    case kKeyTypePrivate:
1320
2
      key_ctor = env->crypto_key_object_private_constructor();
1321
2
      break;
1322
    default:
1323
      CHECK(false);
1324
  }
1325
1326
  Local<Value> key;
1327
16
  if (!key_ctor->NewInstance(context, 1, &handle).ToLocal(&key))
1328
    return {};
1329
1330
8
  return BaseObjectPtr<BaseObject>(Unwrap<KeyObjectHandle>(key.As<Object>()));
1331
}
1332
1333
11
BaseObject::TransferMode NativeKeyObject::GetTransferMode() const {
1334
11
  return BaseObject::TransferMode::kCloneable;
1335
}
1336
1337
11
std::unique_ptr<worker::TransferData> NativeKeyObject::CloneForMessaging()
1338
    const {
1339
11
  return std::make_unique<KeyObjectTransferData>(handle_data_);
1340
}
1341
1342
248
WebCryptoKeyExportStatus PKEY_SPKI_Export(
1343
    KeyObjectData* key_data,
1344
    ByteSource* out) {
1345
248
  CHECK_EQ(key_data->GetKeyType(), kKeyTypePublic);
1346
496
  ManagedEVPPKey m_pkey = key_data->GetAsymmetricKey();
1347
496
  Mutex::ScopedLock lock(*m_pkey.mutex());
1348
496
  BIOPointer bio(BIO_new(BIO_s_mem()));
1349
248
  if (!i2d_PUBKEY_bio(bio.get(), m_pkey.get()))
1350
    return WebCryptoKeyExportStatus::FAILED;
1351
1352
248
  *out = ByteSource::FromBIO(bio);
1353
248
  return WebCryptoKeyExportStatus::OK;
1354
}
1355
1356
255
WebCryptoKeyExportStatus PKEY_PKCS8_Export(
1357
    KeyObjectData* key_data,
1358
    ByteSource* out) {
1359
255
  CHECK_EQ(key_data->GetKeyType(), kKeyTypePrivate);
1360
510
  ManagedEVPPKey m_pkey = key_data->GetAsymmetricKey();
1361
510
  Mutex::ScopedLock lock(*m_pkey.mutex());
1362
1363
510
  BIOPointer bio(BIO_new(BIO_s_mem()));
1364
510
  PKCS8Pointer p8inf(EVP_PKEY2PKCS8(m_pkey.get()));
1365
255
  if (!i2d_PKCS8_PRIV_KEY_INFO_bio(bio.get(), p8inf.get()))
1366
    return WebCryptoKeyExportStatus::FAILED;
1367
1368
255
  *out = ByteSource::FromBIO(bio);
1369
255
  return WebCryptoKeyExportStatus::OK;
1370
}
1371
1372
namespace Keys {
1373
4277
void Initialize(Environment* env, Local<Object> target) {
1374
4277
  target->Set(env->context(),
1375
              FIXED_ONE_BYTE_STRING(env->isolate(), "KeyObjectHandle"),
1376
17108
              KeyObjectHandle::Initialize(env)).Check();
1377
1378
12831
  NODE_DEFINE_CONSTANT(target, kWebCryptoKeyFormatRaw);
1379
12831
  NODE_DEFINE_CONSTANT(target, kWebCryptoKeyFormatPKCS8);
1380
12831
  NODE_DEFINE_CONSTANT(target, kWebCryptoKeyFormatSPKI);
1381
12831
  NODE_DEFINE_CONSTANT(target, kWebCryptoKeyFormatJWK);
1382
1383
12831
  NODE_DEFINE_CONSTANT(target, EVP_PKEY_ED25519);
1384
12831
  NODE_DEFINE_CONSTANT(target, EVP_PKEY_ED448);
1385
12831
  NODE_DEFINE_CONSTANT(target, EVP_PKEY_X25519);
1386
12831
  NODE_DEFINE_CONSTANT(target, EVP_PKEY_X448);
1387
12831
  NODE_DEFINE_CONSTANT(target, kKeyEncodingPKCS1);
1388
12831
  NODE_DEFINE_CONSTANT(target, kKeyEncodingPKCS8);
1389
12831
  NODE_DEFINE_CONSTANT(target, kKeyEncodingSPKI);
1390
12831
  NODE_DEFINE_CONSTANT(target, kKeyEncodingSEC1);
1391
12831
  NODE_DEFINE_CONSTANT(target, kKeyFormatDER);
1392
12831
  NODE_DEFINE_CONSTANT(target, kKeyFormatPEM);
1393
12831
  NODE_DEFINE_CONSTANT(target, kKeyFormatJWK);
1394
12831
  NODE_DEFINE_CONSTANT(target, kKeyTypeSecret);
1395
12831
  NODE_DEFINE_CONSTANT(target, kKeyTypePublic);
1396
12831
  NODE_DEFINE_CONSTANT(target, kKeyTypePrivate);
1397
12831
  NODE_DEFINE_CONSTANT(target, kSigEncDER);
1398
8554
  NODE_DEFINE_CONSTANT(target, kSigEncP1363);
1399
4277
}
1400
}  // namespace Keys
1401
1402
}  // namespace crypto
1403
}  // namespace node