GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: crypto/crypto_keys.cc Lines: 692 812 85.2 %
Date: 2022-03-02 04:14:55 Branches: 327 561 58.3 %

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

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

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

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

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



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

4467
      CHECK(args[*offset + 1]->IsNullOrUndefined());
70
1489
      config->type_ = Nothing<PKEncodingType>();
71
    }
72
  }
73
74
4045
  *offset += 2;
75
4045
}
76
77
3241
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
3241
    MarkPopErrorOnReturn mark_pop_error_on_return;
89
3241
    if (PEM_bytes_read_bio(&der_data, &der_len, nullptr, name,
90
3241
                           bp.get(), nullptr, nullptr) != 1)
91
2274
      return ParseKeyResult::kParseKeyNotRecognized;
92
  }
93
94
  // OpenSSL might modify the pointer, so we need to make a copy before parsing.
95
967
  const unsigned char* p = der_data;
96
967
  pkey->reset(parse(&p, der_len));
97
967
  OPENSSL_clear_free(der_data, der_len);
98
99
967
  return *pkey ? ParseKeyResult::kParseKeyOk :
100
1934
                 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
217
      [](const unsigned char** p, long l) {  // NOLINT(runtime/int)
115
217
        return d2i_PUBKEY(nullptr, p, l);
116
      });
117
1230
  if (ret != ParseKeyResult::kParseKeyNotRecognized)
118
217
    return ret;
119
120
  // Maybe it is PKCS#1.
121
1013
  CHECK(BIO_reset(bp.get()));
122
1013
  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
1013
  if (ret != ParseKeyResult::kParseKeyNotRecognized)
127
15
    return ret;
128
129
  // X.509 fallback.
130
998
  CHECK(BIO_reset(bp.get()));
131
1996
  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
998
      });
136
}
137
138
894
ParseKeyResult ParsePublicKey(EVPKeyPointer* pkey,
139
                              const PublicKeyEncodingConfig& config,
140
                              const char* key,
141
                              size_t key_len) {
142
894
  if (config.format_ == kKeyFormatPEM) {
143
    return ParsePublicKeyPEM(pkey, key, key_len);
144
  } else {
145
894
    CHECK_EQ(config.format_, kKeyFormatDER);
146
147
894
    const unsigned char* p = reinterpret_cast<const unsigned char*>(key);
148
1788
    if (config.type_.ToChecked() == kKeyEncodingPKCS1) {
149
22
      pkey->reset(d2i_PublicKey(EVP_PKEY_RSA, nullptr, &p, key_len));
150
    } else {
151
1744
      CHECK_EQ(config.type_.ToChecked(), kKeyEncodingSPKI);
152
872
      pkey->reset(d2i_PUBKEY(nullptr, &p, key_len));
153
    }
154
155
894
    return *pkey ? ParseKeyResult::kParseKeyOk :
156
1788
                   ParseKeyResult::kParseKeyFailed;
157
  }
158
}
159
160
988
bool IsASN1Sequence(const unsigned char* data, size_t size,
161
                    size_t* data_offset, size_t* data_size) {
162

988
  if (size < 2 || data[0] != 0x30)
163
    return false;
164
165
988
  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
32
    *data_offset = 2;
178
32
    *data_size = std::min<size_t>(size - 2, data[1]);
179
  }
180
181
988
  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
954
bool IsEncryptedPrivateKeyInfo(const unsigned char* data, size_t size) {
202
  // Both PrivateKeyInfo and EncryptedPrivateKeyInfo start with a SEQUENCE.
203
  size_t offset, len;
204
954
  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
1908
  return len >= 1 &&
210
1908
         data[offset] != 2;
211
}
212
213
1467
ParseKeyResult ParsePrivateKey(EVPKeyPointer* pkey,
214
                               const PrivateKeyEncodingConfig& config,
215
                               const char* key,
216
                               size_t key_len) {
217
1467
  const ByteSource* passphrase = config.passphrase_.get();
218
219
1467
  if (config.format_ == kKeyFormatPEM) {
220
500
    BIOPointer bio(BIO_new_mem_buf(key, key_len));
221
500
    if (!bio)
222
      return ParseKeyResult::kParseKeyFailed;
223
224
500
    pkey->reset(PEM_read_bio_PrivateKey(bio.get(),
225
                                        nullptr,
226
                                        PasswordCallback,
227
                                        &passphrase));
228
  } else {
229
967
    CHECK_EQ(config.format_, kKeyFormatDER);
230
231
1934
    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
1908
    } else if (config.type_.ToChecked() == kKeyEncodingPKCS8) {
235
954
      BIOPointer bio(BIO_new_mem_buf(key, key_len));
236
954
      if (!bio)
237
        return ParseKeyResult::kParseKeyFailed;
238
239
954
      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
1874
        PKCS8Pointer p8inf(d2i_PKCS8_PRIV_KEY_INFO_bio(bio.get(), nullptr));
247
937
        if (p8inf)
248
937
          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
1467
  unsigned long err = ERR_peek_error();  // NOLINT(runtime/int)
259
1467
  if (err != 0)
260
19
    pkey->reset();
261
262
1467
  if (*pkey)
263
1448
    return ParseKeyResult::kParseKeyOk;
264

21
  if (ERR_GET_LIB(err) == ERR_LIB_PEM &&
265
2
      ERR_GET_REASON(err) == PEM_R_BAD_PASSWORD_READ) {
266
2
    if (config.passphrase_.IsEmpty())
267
2
      return ParseKeyResult::kParseKeyNeedPassphrase;
268
  }
269
17
  return ParseKeyResult::kParseKeyFailed;
270
}
271
272
133
MaybeLocal<Value> BIOToStringOrBuffer(
273
    Environment* env,
274
    BIO* bio,
275
    PKFormatType format) {
276
  BUF_MEM* bptr;
277
133
  BIO_get_mem_ptr(bio, &bptr);
278
133
  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
59
    CHECK_EQ(format, kKeyFormatDER);
285
    // DER is binary, return it as a buffer.
286
59
    return Buffer::Copy(env, bptr->data, bptr->length)
287
59
        .FromMaybe(Local<Value>());
288
  }
289
}
290
291
292
63
MaybeLocal<Value> WritePrivateKey(
293
    Environment* env,
294
    EVP_PKEY* pkey,
295
    const PrivateKeyEncodingConfig& config) {
296
126
  BIOPointer bio(BIO_new(BIO_s_mem()));
297
63
  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
63
  char* pass = nullptr;
306
63
  size_t pass_len = 0;
307
63
  if (!config.passphrase_.IsEmpty()) {
308
9
    pass = const_cast<char*>(config.passphrase_->get());
309
9
    pass_len = config.passphrase_->size();
310
9
    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
      CHECK_EQ(pass_len, 0);
316
      pass = reinterpret_cast<char*>(-1);
317
      CHECK_NE(pass, nullptr);
318
    }
319
  }
320
321
  bool err;
322
323
63
  PKEncodingType encoding_type = config.type_.ToChecked();
324
63
  if (encoding_type == kKeyEncodingPKCS1) {
325
    // PKCS#1 is only permitted for RSA keys.
326
11
    CHECK_EQ(EVP_PKEY_id(pkey), EVP_PKEY_RSA);
327
328
22
    RSAPointer rsa(EVP_PKEY_get1_RSA(pkey));
329
11
    if (config.format_ == kKeyFormatPEM) {
330
      // Encode PKCS#1 as PEM.
331
10
      err = PEM_write_bio_RSAPrivateKey(
332
10
                bio.get(), rsa.get(),
333
10
                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
52
  } else if (encoding_type == kKeyEncodingPKCS8) {
344
48
    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
27
      CHECK_EQ(config.format_, kKeyFormatDER);
355
27
      err = i2d_PKCS8PrivateKey_bio(
356
                bio.get(), pkey,
357
27
                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
4
                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
63
  if (err) {
386
    ThrowCryptoError(env, ERR_get_error(), "Failed to encode private key");
387
    return MaybeLocal<Value>();
388
  }
389
63
  return BIOToStringOrBuffer(env, bio.get(), config.format_);
390
}
391
392
74
bool WritePublicKeyInner(EVP_PKEY* pkey,
393
                         const BIOPointer& bio,
394
                         const PublicKeyEncodingConfig& config) {
395
148
  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
122
    CHECK_EQ(config.type_.ToChecked(), kKeyEncodingSPKI);
409
61
    if (config.format_ == kKeyFormatPEM) {
410
      // Encode SPKI as PEM.
411
32
      return PEM_write_bio_PUBKEY(bio.get(), pkey) == 1;
412
    } else {
413
      // Encode SPKI as DER.
414
29
      CHECK_EQ(config.format_, kKeyFormatDER);
415
29
      return i2d_PUBKEY_bio(bio.get(), pkey) == 1;
416
    }
417
  }
418
}
419
420
74
MaybeLocal<Value> WritePublicKey(Environment* env,
421
                                 EVP_PKEY* pkey,
422
                                 const PublicKeyEncodingConfig& config) {
423
148
  BIOPointer bio(BIO_new(BIO_s_mem()));
424
74
  CHECK(bio);
425
426
74
  if (!WritePublicKeyInner(pkey, bio, config)) {
427
4
    ThrowCryptoError(env, ERR_get_error(), "Failed to encode public key");
428
4
    return MaybeLocal<Value>();
429
  }
430
70
  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
8650
ManagedEVPPKey::ManagedEVPPKey(EVPKeyPointer&& pkey) : pkey_(std::move(pkey)),
560
4325
    mutex_(std::make_shared<Mutex>()) {}
561
562
17379
ManagedEVPPKey::ManagedEVPPKey(const ManagedEVPPKey& that) {
563
17379
  *this = that;
564
17379
}
565
566
22510
ManagedEVPPKey& ManagedEVPPKey::operator=(const ManagedEVPPKey& that) {
567
22510
  Mutex::ScopedLock lock(*that.mutex_);
568
569
22510
  pkey_.reset(that.get());
570
571
22510
  if (pkey_)
572
22186
    EVP_PKEY_up_ref(pkey_.get());
573
574
22510
  mutex_ = that.mutex_;
575
576
22510
  return *this;
577
}
578
579
7887
ManagedEVPPKey::operator bool() const {
580
7887
  return !!pkey_;
581
}
582
583
45943
EVP_PKEY* ManagedEVPPKey::get() const {
584
45943
  return pkey_.get();
585
}
586
587
5867
Mutex* ManagedEVPPKey::mutex() const {
588
5867
  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
582
static inline Maybe<bool> Tristate(bool b) {
612
582
  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
304
Maybe<bool> ManagedEVPPKey::ToEncodedPublicKey(
633
    Environment* env,
634
    ManagedEVPPKey key,
635
    const PublicKeyEncodingConfig& config,
636
    Local<Value>* out) {
637
304
  if (!key) return Nothing<bool>();
638
304
  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
275
          KeyObjectData::CreateAsymmetric(kKeyTypePublic, std::move(key));
643
550
    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
299
Maybe<bool> ManagedEVPPKey::ToEncodedPrivateKey(
655
    Environment* env,
656
    ManagedEVPPKey key,
657
    const PrivateKeyEncodingConfig& config,
658
    Local<Value>* out) {
659
299
  if (!key) return Nothing<bool>();
660
299
  if (config.output_key_object_) {
661
    std::shared_ptr<KeyObjectData> data =
662
275
        KeyObjectData::CreateAsymmetric(kKeyTypePrivate, std::move(key));
663
550
    return Tristate(KeyObjectHandle::Create(env, data).ToLocal(out));
664
24
  } 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
28
  return Tristate(WritePrivateKey(env, key.get(), config).ToLocal(out));
672
}
673
674
NonCopyableMaybe<PrivateKeyEncodingConfig>
675
3683
ManagedEVPPKey::GetPrivateKeyEncodingFromJs(
676
    const FunctionCallbackInfo<Value>& args,
677
    unsigned int* offset,
678
    KeyEncodingContext context) {
679
3683
  Environment* env = Environment::GetCurrent(args);
680
681
7366
  PrivateKeyEncodingConfig result;
682
3683
  GetKeyFormatAndTypeFromJs(&result, args, offset, context);
683
684
3683
  if (result.output_key_object_) {
685
279
    if (context != kKeyContextInput)
686
279
      (*offset)++;
687
  } else {
688
3404
    bool needs_passphrase = false;
689
3404
    if (context != kKeyContextInput) {
690

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

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

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

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


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


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


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

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

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

963
      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
872
        case kKeyEncodingSPKI:
794
872
          is_public = true;
795
872
          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
963
      if (is_public) {
805
894
        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
2193
        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
3328
ManagedEVPPKey ManagedEVPPKey::GetParsedKey(Environment* env,
824
                                            EVPKeyPointer&& pkey,
825
                                            ParseKeyResult ret,
826
                                            const char* default_msg) {
827
3328
  switch (ret) {
828
3309
    case ParseKeyResult::kParseKeyOk:
829
3309
      CHECK(pkey);
830
3309
      break;
831
2
    case ParseKeyResult::kParseKeyNeedPassphrase:
832
2
      THROW_ERR_MISSING_PASSPHRASE(env,
833
                                   "Passphrase required for encrypted key");
834
2
      break;
835
17
    default:
836
17
      ThrowCryptoError(env, ERR_get_error(), default_msg);
837
  }
838
839
3328
  return ManagedEVPPKey(std::move(pkey));
840
}
841
842
1822
KeyObjectData::KeyObjectData(
843
1822
    ByteSource symmetric_key)
844
    : key_type_(KeyType::kKeyTypeSecret),
845
1822
      symmetric_key_(std::move(symmetric_key)),
846
1822
      symmetric_key_len_(symmetric_key_.size()),
847
3644
      asymmetric_key_() {}
848
849
3087
KeyObjectData::KeyObjectData(
850
    KeyType type,
851
3087
    const ManagedEVPPKey& pkey)
852
    : key_type_(type),
853
      symmetric_key_(),
854
      symmetric_key_len_(0),
855
3087
      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
1822
std::shared_ptr<KeyObjectData> KeyObjectData::CreateSecret(ByteSource key) {
873
1822
  CHECK(key);
874
1822
  return std::shared_ptr<KeyObjectData>(new KeyObjectData(std::move(key)));
875
}
876
877
3087
std::shared_ptr<KeyObjectData> KeyObjectData::CreateAsymmetric(
878
    KeyType key_type,
879
    const ManagedEVPPKey& pkey) {
880
3087
  CHECK(pkey);
881
3087
  return std::shared_ptr<KeyObjectData>(new KeyObjectData(key_type, pkey));
882
}
883
884
11621
KeyType KeyObjectData::GetKeyType() const {
885
11621
  return key_type_;
886
}
887
888
10690
ManagedEVPPKey KeyObjectData::GetAsymmetricKey() const {
889
10690
  CHECK_NE(key_type_, kKeyTypeSecret);
890
10690
  return asymmetric_key_;
891
}
892
893
2564
const char* KeyObjectData::GetSymmetricKey() const {
894
2564
  CHECK_EQ(key_type_, kKeyTypeSecret);
895
2564
  return symmetric_key_.get();
896
}
897
898
3838
size_t KeyObjectData::GetSymmetricKeySize() const {
899
3838
  CHECK_EQ(key_type_, kKeyTypeSecret);
900
3838
  return symmetric_key_len_;
901
}
902
903
5134
v8::Local<v8::Function> KeyObjectHandle::Initialize(Environment* env) {
904
5134
  Local<Function> templ = env->crypto_key_object_handle_constructor();
905
5134
  if (!templ.IsEmpty()) {
906
744
    return templ;
907
  }
908
4390
  Local<FunctionTemplate> t = env->NewFunctionTemplate(New);
909
8780
  t->InstanceTemplate()->SetInternalFieldCount(
910
      KeyObjectHandle::kInternalFieldCount);
911
4390
  t->Inherit(BaseObject::GetConstructorTemplate(env));
912
913
4390
  env->SetProtoMethod(t, "init", Init);
914
4390
  env->SetProtoMethodNoSideEffect(t, "getSymmetricKeySize",
915
                                  GetSymmetricKeySize);
916
4390
  env->SetProtoMethodNoSideEffect(t, "getAsymmetricKeyType",
917
                                  GetAsymmetricKeyType);
918
4390
  env->SetProtoMethod(t, "export", Export);
919
4390
  env->SetProtoMethod(t, "exportJwk", ExportJWK);
920
4390
  env->SetProtoMethod(t, "initECRaw", InitECRaw);
921
4390
  env->SetProtoMethod(t, "initEDRaw", InitEDRaw);
922
4390
  env->SetProtoMethod(t, "initJwk", InitJWK);
923
4390
  env->SetProtoMethod(t, "keyDetail", GetKeyDetail);
924
4390
  env->SetProtoMethod(t, "equals", Equals);
925
926
4390
  auto function = t->GetFunction(env->context()).ToLocalChecked();
927
4390
  env->set_crypto_key_object_handle_constructor(function);
928
4390
  return function;
929
}
930
931
4950
void KeyObjectHandle::RegisterExternalReferences(
932
    ExternalReferenceRegistry* registry) {
933
4950
  registry->Register(New);
934
4950
  registry->Register(Init);
935
4950
  registry->Register(GetSymmetricKeySize);
936
4950
  registry->Register(GetAsymmetricKeyType);
937
4950
  registry->Register(Export);
938
4950
  registry->Register(ExportJWK);
939
4950
  registry->Register(InitECRaw);
940
4950
  registry->Register(InitEDRaw);
941
4950
  registry->Register(InitJWK);
942
4950
  registry->Register(GetKeyDetail);
943
4950
  registry->Register(Equals);
944
4950
}
945
946
744
MaybeLocal<Object> KeyObjectHandle::Create(
947
    Environment* env,
948
    std::shared_ptr<KeyObjectData> data) {
949
  Local<Object> obj;
950
744
  Local<Function> ctor = KeyObjectHandle::Initialize(env);
951
1488
  CHECK(!env->crypto_key_object_handle_constructor().IsEmpty());
952
1488
  if (!ctor->NewInstance(env->context(), 0, nullptr).ToLocal(&obj))
953
    return MaybeLocal<Object>();
954
955
744
  KeyObjectHandle* key = Unwrap<KeyObjectHandle>(obj);
956
744
  CHECK_NOT_NULL(key);
957
744
  key->data_ = data;
958
744
  return obj;
959
}
960
961
15102
const std::shared_ptr<KeyObjectData>& KeyObjectHandle::Data() {
962
15102
  return data_;
963
}
964
965
4905
void KeyObjectHandle::New(const FunctionCallbackInfo<Value>& args) {
966
4905
  CHECK(args.IsConstructCall());
967
4905
  Environment* env = Environment::GetCurrent(args);
968
4905
  new KeyObjectHandle(env, args.This());
969
4905
}
970
971
4905
KeyObjectHandle::KeyObjectHandle(Environment* env,
972
4905
                                 Local<Object> wrap)
973
4905
    : BaseObject(env, wrap) {
974
4905
  MakeWeak();
975
4905
}
976
977
3197
void KeyObjectHandle::Init(const FunctionCallbackInfo<Value>& args) {
978
  KeyObjectHandle* key;
979
3202
  ASSIGN_OR_RETURN_UNWRAP(&key, args.Holder());
980
3197
  MarkPopErrorOnReturn mark_pop_error_on_return;
981
982
3197
  CHECK(args[0]->IsInt32());
983
6394
  KeyType type = static_cast<KeyType>(args[0].As<Uint32>()->Value());
984
985
  unsigned int offset;
986
3197
  ManagedEVPPKey pkey;
987
988

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

3712
  if (!input->Get(env->context(), env->jwk_kty_string()).ToLocal(&kty) ||
1035
1856
      !kty->IsString()) {
1036
    return THROW_ERR_CRYPTO_INVALID_JWK(env);
1037
  }
1038
1039
928
  Utf8Value kty_string(env->isolate(), kty);
1040
1041
928
  if (strcmp(*kty_string, "oct") == 0) {
1042
    // Secret key
1043
270
    key->data_ = ImportJWKSecretKey(env, input);
1044
270
    if (!key->data_) {
1045
      // ImportJWKSecretKey is responsible for throwing an appropriate error
1046
      return;
1047
    }
1048
  } else {
1049
658
    key->data_ = ImportJWKAsymmetricKey(env, input, *kty_string, args, 1);
1050
658
    if (!key->data_) {
1051
      // ImportJWKAsymmetricKey is responsible for throwing an appropriate error
1052
      return;
1053
    }
1054
  }
1055
1056
1856
  args.GetReturnValue().Set(key->data_->GetKeyType());
1057
}
1058
1059
void KeyObjectHandle::InitECRaw(const FunctionCallbackInfo<Value>& args) {
1060
  Environment* env = Environment::GetCurrent(args);
1061
  KeyObjectHandle* key;
1062
  ASSIGN_OR_RETURN_UNWRAP(&key, args.Holder());
1063
1064
  CHECK(args[0]->IsString());
1065
  Utf8Value name(env->isolate(), args[0]);
1066
1067
  MarkPopErrorOnReturn mark_pop_error_on_return;
1068
1069
  int id = OBJ_txt2nid(*name);
1070
  ECKeyPointer eckey(EC_KEY_new_by_curve_name(id));
1071
  if (!eckey)
1072
    return args.GetReturnValue().Set(false);
1073
1074
  const EC_GROUP* group = EC_KEY_get0_group(eckey.get());
1075
  ECPointPointer pub(ECDH::BufferToPoint(env, group, args[1]));
1076
1077
  if (!pub ||
1078
      !eckey ||
1079
      !EC_KEY_set_public_key(eckey.get(), pub.get())) {
1080
    return args.GetReturnValue().Set(false);
1081
  }
1082
1083
  EVPKeyPointer pkey(EVP_PKEY_new());
1084
  if (!EVP_PKEY_assign_EC_KEY(pkey.get(), eckey.get()))
1085
    args.GetReturnValue().Set(false);
1086
1087
  eckey.release();  // Release ownership of the key
1088
1089
  key->data_ =
1090
      KeyObjectData::CreateAsymmetric(
1091
          kKeyTypePublic,
1092
          ManagedEVPPKey(std::move(pkey)));
1093
1094
  args.GetReturnValue().Set(true);
1095
}
1096
1097
32
void KeyObjectHandle::InitEDRaw(const FunctionCallbackInfo<Value>& args) {
1098
32
  Environment* env = Environment::GetCurrent(args);
1099
  KeyObjectHandle* key;
1100
32
  ASSIGN_OR_RETURN_UNWRAP(&key, args.Holder());
1101
1102
64
  CHECK(args[0]->IsString());
1103
32
  Utf8Value name(env->isolate(), args[0]);
1104
1105
32
  ArrayBufferOrViewContents<unsigned char> key_data(args[1]);
1106
64
  KeyType type = static_cast<KeyType>(args[2].As<Int32>()->Value());
1107
1108
32
  MarkPopErrorOnReturn mark_pop_error_on_return;
1109
1110
  typedef EVP_PKEY* (*new_key_fn)(int, ENGINE*, const unsigned char*, size_t);
1111
32
  new_key_fn fn = type == kKeyTypePrivate
1112
32
      ? EVP_PKEY_new_raw_private_key
1113
      : EVP_PKEY_new_raw_public_key;
1114
1115
32
  int id = GetOKPCurveFromName(*name);
1116
1117
32
  switch (id) {
1118
32
    case EVP_PKEY_X25519:
1119
    case EVP_PKEY_X448:
1120
    case EVP_PKEY_ED25519:
1121
    case EVP_PKEY_ED448: {
1122
32
      EVPKeyPointer pkey(fn(id, nullptr, key_data.data(), key_data.size()));
1123
32
      if (!pkey)
1124
        return args.GetReturnValue().Set(false);
1125
32
      key->data_ =
1126
64
          KeyObjectData::CreateAsymmetric(
1127
              type,
1128
96
              ManagedEVPPKey(std::move(pkey)));
1129
32
      CHECK(key->data_);
1130
32
      break;
1131
    }
1132
    default:
1133
      UNREACHABLE();
1134
  }
1135
1136
64
  args.GetReturnValue().Set(true);
1137
}
1138
1139
11
void KeyObjectHandle::Equals(const FunctionCallbackInfo<Value>& args) {
1140
  KeyObjectHandle* self_handle;
1141
  KeyObjectHandle* arg_handle;
1142
11
  ASSIGN_OR_RETURN_UNWRAP(&self_handle, args.Holder());
1143
22
  ASSIGN_OR_RETURN_UNWRAP(&arg_handle, args[0].As<Object>());
1144
11
  std::shared_ptr<KeyObjectData> key = self_handle->Data();
1145
11
  std::shared_ptr<KeyObjectData> key2 = arg_handle->Data();
1146
1147
11
  KeyType key_type = key->GetKeyType();
1148
11
  CHECK_EQ(key_type, key2->GetKeyType());
1149
1150
  bool ret;
1151
11
  switch (key_type) {
1152
3
    case kKeyTypeSecret: {
1153
3
      size_t size = key->GetSymmetricKeySize();
1154
3
      if (size == key2->GetSymmetricKeySize()) {
1155
3
        ret = CRYPTO_memcmp(
1156
3
          key->GetSymmetricKey(),
1157
3
          key2->GetSymmetricKey(),
1158
          size) == 0;
1159
      } else {
1160
        ret = false;
1161
      }
1162
3
      break;
1163
    }
1164
8
    case kKeyTypePublic:
1165
    case kKeyTypePrivate: {
1166
8
      EVP_PKEY* pkey = key->GetAsymmetricKey().get();
1167
8
      EVP_PKEY* pkey2 = key2->GetAsymmetricKey().get();
1168
#if OPENSSL_VERSION_MAJOR >= 3
1169
8
      int ok = EVP_PKEY_eq(pkey, pkey2);
1170
#else
1171
      int ok = EVP_PKEY_cmp(pkey, pkey2);
1172
#endif
1173
8
      if (ok == -2) {
1174
        Environment* env = Environment::GetCurrent(args);
1175
        return THROW_ERR_CRYPTO_UNSUPPORTED_OPERATION(env);
1176
      }
1177
8
      ret = ok == 1;
1178
8
      break;
1179
    }
1180
    default:
1181
      UNREACHABLE("unsupported key type");
1182
  }
1183
1184
22
  args.GetReturnValue().Set(ret);
1185
}
1186
1187
3896
void KeyObjectHandle::GetKeyDetail(const FunctionCallbackInfo<Value>& args) {
1188
3896
  Environment* env = Environment::GetCurrent(args);
1189
  KeyObjectHandle* key;
1190
3896
  ASSIGN_OR_RETURN_UNWRAP(&key, args.Holder());
1191
1192
3896
  CHECK(args[0]->IsObject());
1193
1194
3896
  std::shared_ptr<KeyObjectData> data = key->Data();
1195
1196
3896
  switch (data->GetKeyType()) {
1197
1509
    case kKeyTypeSecret:
1198
4527
      if (GetSecretKeyDetail(env, data, args[0].As<Object>()).IsNothing())
1199
        return;
1200
1509
      break;
1201
2387
    case kKeyTypePublic:
1202
      // Fall through
1203
    case kKeyTypePrivate:
1204
7161
      if (GetAsymmetricKeyDetail(env, data, args[0].As<Object>()).IsNothing())
1205
        return;
1206
2387
      break;
1207
    default:
1208
      UNREACHABLE();
1209
  }
1210
1211
7792
  args.GetReturnValue().Set(args[0]);
1212
}
1213
1214
2553
Local<Value> KeyObjectHandle::GetAsymmetricKeyType() const {
1215
5106
  const ManagedEVPPKey& key = data_->GetAsymmetricKey();
1216


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

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