GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: crypto/crypto_keys.cc Lines: 649 761 85.3 %
Date: 2021-09-19 04:12:45 Branches: 321 544 59.0 %

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
4026
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

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

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

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

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



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

4482
      CHECK(args[*offset + 1]->IsNullOrUndefined());
70
1494
      config->type_ = Nothing<PKEncodingType>();
71
    }
72
  }
73
74
4026
  *offset += 2;
75
4026
}
76
77
3245
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
3245
    MarkPopErrorOnReturn mark_pop_error_on_return;
89
3245
    if (PEM_bytes_read_bio(&der_data, &der_len, nullptr, name,
90
3245
                           bp.get(), nullptr, nullptr) != 1)
91
2280
      return ParseKeyResult::kParseKeyNotRecognized;
92
  }
93
94
  // OpenSSL might modify the pointer, so we need to make a copy before parsing.
95
965
  const unsigned char* p = der_data;
96
965
  pkey->reset(parse(&p, der_len));
97
965
  OPENSSL_clear_free(der_data, der_len);
98
99
965
  return *pkey ? ParseKeyResult::kParseKeyOk :
100
1930
                 ParseKeyResult::kParseKeyFailed;
101
}
102
103
1230
ParseKeyResult ParsePublicKeyPEM(EVPKeyPointer* pkey,
104
                                 const char* key_pem,
105
                                 int key_pem_len) {
106
2460
  BIOPointer bp(BIO_new_mem_buf(const_cast<char*>(key_pem), key_pem_len));
107
1230
  if (!bp)
108
    return ParseKeyResult::kParseKeyFailed;
109
110
  ParseKeyResult ret;
111
112
  // Try parsing as a SubjectPublicKeyInfo first.
113
1230
  ret = TryParsePublicKey(pkey, bp, "PUBLIC KEY",
114
215
      [](const unsigned char** p, long l) {  // NOLINT(runtime/int)
115
215
        return d2i_PUBKEY(nullptr, p, l);
116
      });
117
1230
  if (ret != ParseKeyResult::kParseKeyNotRecognized)
118
215
    return ret;
119
120
  // Maybe it is PKCS#1.
121
1015
  CHECK(BIO_reset(bp.get()));
122
1015
  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
1015
  if (ret != ParseKeyResult::kParseKeyNotRecognized)
127
15
    return ret;
128
129
  // X.509 fallback.
130
1000
  CHECK(BIO_reset(bp.get()));
131
2000
  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
1000
      });
136
}
137
138
890
ParseKeyResult ParsePublicKey(EVPKeyPointer* pkey,
139
                              const PublicKeyEncodingConfig& config,
140
                              const char* key,
141
                              size_t key_len) {
142
890
  if (config.format_ == kKeyFormatPEM) {
143
    return ParsePublicKeyPEM(pkey, key, key_len);
144
  } else {
145
890
    CHECK_EQ(config.format_, kKeyFormatDER);
146
147
890
    const unsigned char* p = reinterpret_cast<const unsigned char*>(key);
148
1780
    if (config.type_.ToChecked() == kKeyEncodingPKCS1) {
149
22
      pkey->reset(d2i_PublicKey(EVP_PKEY_RSA, nullptr, &p, key_len));
150
    } else {
151
1736
      CHECK_EQ(config.type_.ToChecked(), kKeyEncodingSPKI);
152
868
      pkey->reset(d2i_PUBKEY(nullptr, &p, key_len));
153
    }
154
155
890
    return *pkey ? ParseKeyResult::kParseKeyOk :
156
1780
                   ParseKeyResult::kParseKeyFailed;
157
  }
158
}
159
160
984
bool IsASN1Sequence(const unsigned char* data, size_t size,
161
                    size_t* data_offset, size_t* data_size) {
162

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

956
    if (n_bytes + 2 > size || n_bytes > sizeof(size_t))
169
      return false;
170
956
    size_t length = 0;
171
2605
    for (size_t i = 0; i < n_bytes; i++)
172
1649
      length = (length << 8) | data[i + 2];
173
956
    *data_offset = 2 + n_bytes;
174
956
    *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
984
  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
950
bool IsEncryptedPrivateKeyInfo(const unsigned char* data, size_t size) {
202
  // Both PrivateKeyInfo and EncryptedPrivateKeyInfo start with a SEQUENCE.
203
  size_t offset, len;
204
950
  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
1900
  return len >= 1 &&
210
1900
         data[offset] != 2;
211
}
212
213
1470
ParseKeyResult ParsePrivateKey(EVPKeyPointer* pkey,
214
                               const PrivateKeyEncodingConfig& config,
215
                               const char* key,
216
                               size_t key_len) {
217
1470
  const ByteSource* passphrase = config.passphrase_.get();
218
219
1470
  if (config.format_ == kKeyFormatPEM) {
220
507
    BIOPointer bio(BIO_new_mem_buf(key, key_len));
221
507
    if (!bio)
222
      return ParseKeyResult::kParseKeyFailed;
223
224
507
    pkey->reset(PEM_read_bio_PrivateKey(bio.get(),
225
                                        nullptr,
226
                                        PasswordCallback,
227
                                        &passphrase));
228
  } else {
229
963
    CHECK_EQ(config.format_, kKeyFormatDER);
230
231
1926
    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
1900
    } else if (config.type_.ToChecked() == kKeyEncodingPKCS8) {
235
950
      BIOPointer bio(BIO_new_mem_buf(key, key_len));
236
950
      if (!bio)
237
        return ParseKeyResult::kParseKeyFailed;
238
239
950
      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
1866
        PKCS8Pointer p8inf(d2i_PKCS8_PRIV_KEY_INFO_bio(bio.get(), nullptr));
247
933
        if (p8inf)
248
933
          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
1470
  unsigned long err = ERR_peek_error();  // NOLINT(runtime/int)
259
1470
  if (err != 0)
260
22
    pkey->reset();
261
262
1470
  if (*pkey)
263
1448
    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
125
MaybeLocal<Value> BIOToStringOrBuffer(
273
    Environment* env,
274
    BIO* bio,
275
    PKFormatType format) {
276
  BUF_MEM* bptr;
277
125
  BIO_get_mem_ptr(bio, &bptr);
278
125
  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
51
    CHECK_EQ(format, kKeyFormatDER);
285
    // DER is binary, return it as a buffer.
286
51
    return Buffer::Copy(env, bptr->data, bptr->length)
287
51
        .FromMaybe(Local<Value>());
288
  }
289
}
290
291
292
60
MaybeLocal<Value> WritePrivateKey(
293
    Environment* env,
294
    EVP_PKEY* pkey,
295
    const PrivateKeyEncodingConfig& config) {
296
120
  BIOPointer bio(BIO_new(BIO_s_mem()));
297
60
  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
60
  char* pass = nullptr;
306
60
  size_t pass_len = 0;
307
60
  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
60
  PKEncodingType encoding_type = config.type_.ToChecked();
324
60
  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
48
  } else if (encoding_type == kKeyEncodingPKCS8) {
344
44
    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
23
      CHECK_EQ(config.format_, kKeyFormatDER);
355
23
      err = i2d_PKCS8PrivateKey_bio(
356
                bio.get(), pkey,
357
23
                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
60
  if (err) {
386
    ThrowCryptoError(env, ERR_get_error(), "Failed to encode private key");
387
    return MaybeLocal<Value>();
388
  }
389
60
  return BIOToStringOrBuffer(env, bio.get(), config.format_);
390
}
391
392
69
bool WritePublicKeyInner(EVP_PKEY* pkey,
393
                         const BIOPointer& bio,
394
                         const PublicKeyEncodingConfig& config) {
395
138
  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
112
    CHECK_EQ(config.type_.ToChecked(), kKeyEncodingSPKI);
409
56
    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
25
      CHECK_EQ(config.format_, kKeyFormatDER);
415
25
      return i2d_PUBKEY_bio(bio.get(), pkey) == 1;
416
    }
417
  }
418
}
419
420
69
MaybeLocal<Value> WritePublicKey(Environment* env,
421
                                 EVP_PKEY* pkey,
422
                                 const PublicKeyEncodingConfig& config) {
423
138
  BIOPointer bio(BIO_new(BIO_s_mem()));
424
69
  CHECK(bio);
425
426
69
  if (!WritePublicKeyInner(pkey, bio, config)) {
427
4
    ThrowCryptoError(env, ERR_get_error(), "Failed to encode public key");
428
4
    return MaybeLocal<Value>();
429
  }
430
65
  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
662
Maybe<bool> ExportJWKAsymmetricKey(
490
    Environment* env,
491
    std::shared_ptr<KeyObjectData> key,
492
    Local<Object> target,
493
    bool handleRsaPss) {
494

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

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

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

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

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

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


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


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


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

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

5670
  if (IsAnyByteSource(args[*offset])) {
763
2189
    Environment* env = Environment::GetCurrent(args);
764
6567
    ArrayBufferOrViewContents<char> data(args[(*offset)++]);
765
2189
    if (UNLIKELY(!data.CheckSizeInt32())) {
766
      THROW_ERR_OUT_OF_RANGE(env, "keyData is too big");
767
      return ManagedEVPPKey();
768
    }
769
    NonCopyableMaybe<PrivateKeyEncodingConfig> config_ =
770
4378
        GetPrivateKeyEncodingFromJs(args, offset, kKeyContextInput);
771
2189
    if (config_.IsEmpty())
772
      return ManagedEVPPKey();
773
774
    ParseKeyResult ret;
775
4378
    PrivateKeyEncodingConfig config = config_.Release();
776
2189
    EVPKeyPointer pkey;
777
2189
    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
1230
      ret = ParsePublicKeyPEM(&pkey, data.data(), data.size());
781
1230
      if (ret == ParseKeyResult::kParseKeyNotRecognized) {
782
265
        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

959
      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
868
        case kKeyEncodingSPKI:
794
868
          is_public = true;
795
868
          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
959
      if (is_public) {
805
890
        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
2189
        env, std::move(pkey), ret, "Failed to read asymmetric key");
813
  } else {
814

1292
    CHECK(args[*offset]->IsObject());
815
1938
    KeyObjectHandle* key = Unwrap<KeyObjectHandle>(args[*offset].As<Object>());
816
646
    CHECK_NOT_NULL(key);
817
646
    CHECK_NE(key->Data()->GetKeyType(), kKeyTypeSecret);
818
646
    (*offset) += 4;
819
646
    return key->Data()->GetAsymmetricKey();
820
  }
821
}
822
823
3325
ManagedEVPPKey ManagedEVPPKey::GetParsedKey(Environment* env,
824
                                            EVPKeyPointer&& pkey,
825
                                            ParseKeyResult ret,
826
                                            const char* default_msg) {
827
3325
  switch (ret) {
828
3303
    case ParseKeyResult::kParseKeyOk:
829
3303
      CHECK(pkey);
830
3303
      break;
831
11
    case ParseKeyResult::kParseKeyNeedPassphrase:
832
11
      THROW_ERR_MISSING_PASSPHRASE(env,
833
                                   "Passphrase required for encrypted key");
834
11
      break;
835
11
    default:
836
11
      ThrowCryptoError(env, ERR_get_error(), default_msg);
837
  }
838
839
3325
  return ManagedEVPPKey(std::move(pkey));
840
}
841
842
1884
KeyObjectData::KeyObjectData(
843
1884
    ByteSource symmetric_key)
844
    : key_type_(KeyType::kKeyTypeSecret),
845
1884
      symmetric_key_(std::move(symmetric_key)),
846
1884
      symmetric_key_len_(symmetric_key_.size()),
847
3768
      asymmetric_key_() {}
848
849
3071
KeyObjectData::KeyObjectData(
850
    KeyType type,
851
3071
    const ManagedEVPPKey& pkey)
852
    : key_type_(type),
853
      symmetric_key_(),
854
      symmetric_key_len_(0),
855
3071
      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
1884
std::shared_ptr<KeyObjectData> KeyObjectData::CreateSecret(ByteSource key) {
873
1884
  CHECK(key);
874
1884
  return std::shared_ptr<KeyObjectData>(new KeyObjectData(std::move(key)));
875
}
876
877
3071
std::shared_ptr<KeyObjectData> KeyObjectData::CreateAsymmetric(
878
    KeyType key_type,
879
    const ManagedEVPPKey& pkey) {
880
3071
  CHECK(pkey);
881
3071
  return std::shared_ptr<KeyObjectData>(new KeyObjectData(key_type, pkey));
882
}
883
884
11590
KeyType KeyObjectData::GetKeyType() const {
885
11590
  return key_type_;
886
}
887
888
10663
ManagedEVPPKey KeyObjectData::GetAsymmetricKey() const {
889
10663
  CHECK_NE(key_type_, kKeyTypeSecret);
890
10663
  return asymmetric_key_;
891
}
892
893
2627
const char* KeyObjectData::GetSymmetricKey() const {
894
2627
  CHECK_EQ(key_type_, kKeyTypeSecret);
895
2627
  return symmetric_key_.get();
896
}
897
898
3901
size_t KeyObjectData::GetSymmetricKeySize() const {
899
3901
  CHECK_EQ(key_type_, kKeyTypeSecret);
900
3901
  return symmetric_key_len_;
901
}
902
903
5032
v8::Local<v8::Function> KeyObjectHandle::Initialize(Environment* env) {
904
5032
  Local<Function> templ = env->crypto_key_object_handle_constructor();
905
5032
  if (!templ.IsEmpty()) {
906
735
    return templ;
907
  }
908
4297
  Local<FunctionTemplate> t = env->NewFunctionTemplate(New);
909
8594
  t->InstanceTemplate()->SetInternalFieldCount(
910
      KeyObjectHandle::kInternalFieldCount);
911
4297
  t->Inherit(BaseObject::GetConstructorTemplate(env));
912
913
4297
  env->SetProtoMethod(t, "init", Init);
914
4297
  env->SetProtoMethodNoSideEffect(t, "getSymmetricKeySize",
915
                                  GetSymmetricKeySize);
916
4297
  env->SetProtoMethodNoSideEffect(t, "getAsymmetricKeyType",
917
                                  GetAsymmetricKeyType);
918
4297
  env->SetProtoMethod(t, "export", Export);
919
4297
  env->SetProtoMethod(t, "exportJwk", ExportJWK);
920
4297
  env->SetProtoMethod(t, "initECRaw", InitECRaw);
921
4297
  env->SetProtoMethod(t, "initEDRaw", InitEDRaw);
922
4297
  env->SetProtoMethod(t, "initJwk", InitJWK);
923
4297
  env->SetProtoMethod(t, "keyDetail", GetKeyDetail);
924
925
4297
  auto function = t->GetFunction(env->context()).ToLocalChecked();
926
4297
  env->set_crypto_key_object_handle_constructor(function);
927
4297
  return function;
928
}
929
930
735
MaybeLocal<Object> KeyObjectHandle::Create(
931
    Environment* env,
932
    std::shared_ptr<KeyObjectData> data) {
933
  Local<Object> obj;
934
735
  Local<Function> ctor = KeyObjectHandle::Initialize(env);
935
1470
  CHECK(!env->crypto_key_object_handle_constructor().IsEmpty());
936
1470
  if (!ctor->NewInstance(env->context(), 0, nullptr).ToLocal(&obj))
937
    return MaybeLocal<Object>();
938
939
735
  KeyObjectHandle* key = Unwrap<KeyObjectHandle>(obj);
940
735
  CHECK_NOT_NULL(key);
941
735
  key->data_ = data;
942
735
  return obj;
943
}
944
945
15187
const std::shared_ptr<KeyObjectData>& KeyObjectHandle::Data() {
946
15187
  return data_;
947
}
948
949
4951
void KeyObjectHandle::New(const FunctionCallbackInfo<Value>& args) {
950
4951
  CHECK(args.IsConstructCall());
951
4951
  Environment* env = Environment::GetCurrent(args);
952
4951
  new KeyObjectHandle(env, args.This());
953
4951
}
954
955
4951
KeyObjectHandle::KeyObjectHandle(Environment* env,
956
4951
                                 Local<Object> wrap)
957
4951
    : BaseObject(env, wrap) {
958
4951
  MakeWeak();
959
4951
}
960
961
3252
void KeyObjectHandle::Init(const FunctionCallbackInfo<Value>& args) {
962
  KeyObjectHandle* key;
963
3257
  ASSIGN_OR_RETURN_UNWRAP(&key, args.Holder());
964
3252
  MarkPopErrorOnReturn mark_pop_error_on_return;
965
966
3252
  CHECK(args[0]->IsInt32());
967
6504
  KeyType type = static_cast<KeyType>(args[0].As<Uint32>()->Value());
968
969
  unsigned int offset;
970
3252
  ManagedEVPPKey pkey;
971
972

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

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


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

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