GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: crypto/crypto_keys.cc Lines: 718 814 88.2 %
Date: 2022-10-02 04:22:39 Branches: 341 565 60.4 %

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

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

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

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

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



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

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

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

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

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

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

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

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

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

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

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

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

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

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


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


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


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

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

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

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

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

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

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


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


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

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