GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/node_crypto.cc Lines: 3337 3670 90.9 %
Date: 2020-09-03 22:13:26 Branches: 1756 2667 65.8 %

Line Branch Exec Source
1
// Copyright Joyent, Inc. and other Node contributors.
2
//
3
// Permission is hereby granted, free of charge, to any person obtaining a
4
// copy of this software and associated documentation files (the
5
// "Software"), to deal in the Software without restriction, including
6
// without limitation the rights to use, copy, modify, merge, publish,
7
// distribute, sublicense, and/or sell copies of the Software, and to permit
8
// persons to whom the Software is furnished to do so, subject to the
9
// following conditions:
10
//
11
// The above copyright notice and this permission notice shall be included
12
// in all copies or substantial portions of the Software.
13
//
14
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20
// USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22
#include "node_crypto.h"
23
#include "node_buffer.h"
24
#include "node_crypto_bio.h"
25
#include "node_crypto_common.h"
26
#include "node_crypto_clienthello-inl.h"
27
#include "node_crypto_groups.h"
28
#include "node_errors.h"
29
#include "node_mutex.h"
30
#include "node_process.h"
31
#include "allocated_buffer-inl.h"
32
#include "tls_wrap.h"  // TLSWrap
33
34
#include "async_wrap-inl.h"
35
#include "base_object-inl.h"
36
#include "env-inl.h"
37
#include "memory_tracker-inl.h"
38
#include "string_bytes.h"
39
#include "threadpoolwork-inl.h"
40
#include "util-inl.h"
41
#include "v8.h"
42
43
#include <openssl/ec.h>
44
#include <openssl/ecdh.h>
45
#ifndef OPENSSL_NO_ENGINE
46
# include <openssl/engine.h>
47
#endif  // !OPENSSL_NO_ENGINE
48
#include <openssl/evp.h>
49
#include <openssl/pem.h>
50
#include <openssl/x509v3.h>
51
#include <openssl/hmac.h>
52
#include <openssl/rand.h>
53
#include <openssl/pkcs12.h>
54
55
#include <cerrno>
56
#include <climits>  // INT_MAX
57
#include <cstring>
58
59
#include <algorithm>
60
#include <memory>
61
#include <utility>
62
#include <vector>
63
64
namespace node {
65
namespace crypto {
66
67
using node::THROW_ERR_TLS_INVALID_PROTOCOL_METHOD;
68
69
using v8::Array;
70
using v8::ArrayBufferView;
71
using v8::Boolean;
72
using v8::ConstructorBehavior;
73
using v8::Context;
74
using v8::DontDelete;
75
using v8::Exception;
76
using v8::External;
77
using v8::False;
78
using v8::Function;
79
using v8::FunctionCallback;
80
using v8::FunctionCallbackInfo;
81
using v8::FunctionTemplate;
82
using v8::HandleScope;
83
using v8::Int32;
84
using v8::Integer;
85
using v8::Isolate;
86
using v8::Just;
87
using v8::Local;
88
using v8::Maybe;
89
using v8::MaybeLocal;
90
using v8::NewStringType;
91
using v8::Nothing;
92
using v8::Null;
93
using v8::Object;
94
using v8::PropertyAttribute;
95
using v8::ReadOnly;
96
using v8::SideEffectType;
97
using v8::Signature;
98
using v8::String;
99
using v8::Uint32;
100
using v8::Undefined;
101
using v8::Value;
102
103
#ifdef OPENSSL_NO_OCB
104
# define IS_OCB_MODE(mode) false
105
#else
106
# define IS_OCB_MODE(mode) ((mode) == EVP_CIPH_OCB_MODE)
107
#endif
108
109
static const char* const root_certs[] = {
110
#include "node_root_certs.h"  // NOLINT(build/include_order)
111
};
112
113
static const char system_cert_path[] = NODE_OPENSSL_SYSTEM_CERT_PATH;
114
115
static X509_STORE* root_cert_store;
116
117
static bool extra_root_certs_loaded = false;
118
119
// Just to generate static methods
120
template void SSLWrap<TLSWrap>::AddMethods(Environment* env,
121
                                           Local<FunctionTemplate> t);
122
template void SSLWrap<TLSWrap>::ConfigureSecureContext(SecureContext* sc);
123
template int SSLWrap<TLSWrap>::SetCACerts(SecureContext* sc);
124
template void SSLWrap<TLSWrap>::MemoryInfo(MemoryTracker* tracker) const;
125
template SSL_SESSION* SSLWrap<TLSWrap>::GetSessionCallback(
126
    SSL* s,
127
    const unsigned char* key,
128
    int len,
129
    int* copy);
130
template int SSLWrap<TLSWrap>::NewSessionCallback(SSL* s,
131
                                                  SSL_SESSION* sess);
132
template void SSLWrap<TLSWrap>::KeylogCallback(const SSL* s,
133
                                               const char* line);
134
template void SSLWrap<TLSWrap>::OnClientHello(
135
    void* arg,
136
    const ClientHelloParser::ClientHello& hello);
137
template int SSLWrap<TLSWrap>::TLSExtStatusCallback(SSL* s, void* arg);
138
template void SSLWrap<TLSWrap>::DestroySSL();
139
template int SSLWrap<TLSWrap>::SSLCertCallback(SSL* s, void* arg);
140
template void SSLWrap<TLSWrap>::WaitForCertCb(CertCb cb, void* arg);
141
template int SSLWrap<TLSWrap>::SelectALPNCallback(
142
    SSL* s,
143
    const unsigned char** out,
144
    unsigned char* outlen,
145
    const unsigned char* in,
146
    unsigned int inlen,
147
    void* arg);
148
149
template <typename T>
150
356593
void Decode(const FunctionCallbackInfo<Value>& args,
151
            void (*callback)(T*, const FunctionCallbackInfo<Value>&,
152
                             const char*, size_t)) {
153
  T* ctx;
154


356593
  ASSIGN_OR_RETURN_UNWRAP(&ctx, args.Holder());
155
156


1069779
  if (args[0]->IsString()) {
157
710396
    StringBytes::InlineDecoder decoder;
158
355198
    Environment* env = Environment::GetCurrent(args);
159
355198
    enum encoding enc = ParseEncoding(env->isolate(), args[1], UTF8);
160


1065594
    if (decoder.Decode(env, args[0].As<String>(), enc).IsNothing())
161
      return;
162


355198
    callback(ctx, args, decoder.out(), decoder.size());
163
  } else {
164
1395
    ArrayBufferViewContents<char> buf(args[0]);
165
1395
    callback(ctx, args, buf.data(), buf.length());
166
  }
167
}
168
169
94
static int PasswordCallback(char* buf, int size, int rwflag, void* u) {
170
94
  const char* passphrase = static_cast<char*>(u);
171
94
  if (passphrase != nullptr) {
172
85
    size_t buflen = static_cast<size_t>(size);
173
85
    size_t len = strlen(passphrase);
174
85
    if (buflen < len)
175
1
      return -1;
176
84
    memcpy(buf, passphrase, len);
177
84
    return len;
178
  }
179
180
9
  return -1;
181
}
182
183
// Loads OpenSSL engine by engine id and returns it. The loaded engine
184
// gets a reference so remember the corresponding call to ENGINE_free.
185
// In case of error the appropriate js exception is scheduled
186
// and nullptr is returned.
187
#ifndef OPENSSL_NO_ENGINE
188
2
static ENGINE* LoadEngineById(const char* engine_id, char (*errmsg)[1024]) {
189
4
  MarkPopErrorOnReturn mark_pop_error_on_return;
190
191
2
  ENGINE* engine = ENGINE_by_id(engine_id);
192
193
2
  if (engine == nullptr) {
194
    // Engine not found, try loading dynamically.
195
2
    engine = ENGINE_by_id("dynamic");
196
2
    if (engine != nullptr) {
197

4
      if (!ENGINE_ctrl_cmd_string(engine, "SO_PATH", engine_id, 0) ||
198
2
          !ENGINE_ctrl_cmd_string(engine, "LOAD", nullptr, 0)) {
199
2
        ENGINE_free(engine);
200
2
        engine = nullptr;
201
      }
202
    }
203
  }
204
205
2
  if (engine == nullptr) {
206
2
    int err = ERR_get_error();
207
2
    if (err != 0) {
208
2
      ERR_error_string_n(err, *errmsg, sizeof(*errmsg));
209
    } else {
210
      snprintf(*errmsg, sizeof(*errmsg),
211
               "Engine \"%s\" was not found", engine_id);
212
    }
213
  }
214
215
4
  return engine;
216
}
217
#endif  // !OPENSSL_NO_ENGINE
218
219
// This callback is used to avoid the default passphrase callback in OpenSSL
220
// which will typically prompt for the passphrase. The prompting is designed
221
// for the OpenSSL CLI, but works poorly for Node.js because it involves
222
// synchronous interaction with the controlling terminal, something we never
223
// want, and use this function to avoid it.
224
static int NoPasswordCallback(char* buf, int size, int rwflag, void* u) {
225
  return 0;
226
}
227
228
229
// namespace node::crypto::error
230
namespace error {
231
77
Maybe<bool> Decorate(Environment* env, Local<Object> obj,
232
              unsigned long err) {  // NOLINT(runtime/int)
233
77
  if (err == 0) return Just(true);  // No decoration necessary.
234
235
66
  const char* ls = ERR_lib_error_string(err);
236
66
  const char* fs = ERR_func_error_string(err);
237
66
  const char* rs = ERR_reason_error_string(err);
238
239
66
  Isolate* isolate = env->isolate();
240
66
  Local<Context> context = isolate->GetCurrentContext();
241
242
66
  if (ls != nullptr) {
243
198
    if (obj->Set(context, env->library_string(),
244
264
                 OneByteString(isolate, ls)).IsNothing()) {
245
1
      return Nothing<bool>();
246
    }
247
  }
248
65
  if (fs != nullptr) {
249
195
    if (obj->Set(context, env->function_string(),
250
260
                 OneByteString(isolate, fs)).IsNothing()) {
251
      return Nothing<bool>();
252
    }
253
  }
254
65
  if (rs != nullptr) {
255
195
    if (obj->Set(context, env->reason_string(),
256
260
                 OneByteString(isolate, rs)).IsNothing()) {
257
      return Nothing<bool>();
258
    }
259
260
    // SSL has no API to recover the error name from the number, so we
261
    // transform reason strings like "this error" to "ERR_SSL_THIS_ERROR",
262
    // which ends up being close to the original error macro name.
263
130
    std::string reason(rs);
264
265
1161
    for (auto& c : reason) {
266
1096
      if (c == ' ')
267
122
        c = '_';
268
      else
269
974
        c = ToUpper(c);
270
    }
271
272
#define OSSL_ERROR_CODES_MAP(V)                                               \
273
    V(SYS)                                                                    \
274
    V(BN)                                                                     \
275
    V(RSA)                                                                    \
276
    V(DH)                                                                     \
277
    V(EVP)                                                                    \
278
    V(BUF)                                                                    \
279
    V(OBJ)                                                                    \
280
    V(PEM)                                                                    \
281
    V(DSA)                                                                    \
282
    V(X509)                                                                   \
283
    V(ASN1)                                                                   \
284
    V(CONF)                                                                   \
285
    V(CRYPTO)                                                                 \
286
    V(EC)                                                                     \
287
    V(SSL)                                                                    \
288
    V(BIO)                                                                    \
289
    V(PKCS7)                                                                  \
290
    V(X509V3)                                                                 \
291
    V(PKCS12)                                                                 \
292
    V(RAND)                                                                   \
293
    V(DSO)                                                                    \
294
    V(ENGINE)                                                                 \
295
    V(OCSP)                                                                   \
296
    V(UI)                                                                     \
297
    V(COMP)                                                                   \
298
    V(ECDSA)                                                                  \
299
    V(ECDH)                                                                   \
300
    V(OSSL_STORE)                                                             \
301
    V(FIPS)                                                                   \
302
    V(CMS)                                                                    \
303
    V(TS)                                                                     \
304
    V(HMAC)                                                                   \
305
    V(CT)                                                                     \
306
    V(ASYNC)                                                                  \
307
    V(KDF)                                                                    \
308
    V(SM2)                                                                    \
309
    V(USER)                                                                   \
310
311
#define V(name) case ERR_LIB_##name: lib = #name "_"; break;
312
65
    const char* lib = "";
313
65
    const char* prefix = "OSSL_";
314









65
    switch (ERR_GET_LIB(err)) { OSSL_ERROR_CODES_MAP(V) }
315
#undef V
316
#undef OSSL_ERROR_CODES_MAP
317
    // Don't generate codes like "ERR_OSSL_SSL_".
318

65
    if (lib && strcmp(lib, "SSL_") == 0)
319
6
      prefix = "";
320
321
    // All OpenSSL reason strings fit in a single 80-column macro definition,
322
    // all prefix lengths are <= 10, and ERR_OSSL_ is 9, so 128 is more than
323
    // sufficient.
324
    char code[128];
325
65
    snprintf(code, sizeof(code), "ERR_%s%s%s", prefix, lib, reason.c_str());
326
327
195
    if (obj->Set(env->isolate()->GetCurrentContext(),
328
             env->code_string(),
329
325
             OneByteString(env->isolate(), code)).IsNothing())
330
      return Nothing<bool>();
331
  }
332
333
65
  return Just(true);
334
}
335
}  // namespace error
336
337
338
662
struct CryptoErrorVector : public std::vector<std::string> {
339
90
  inline void Capture() {
340
90
    clear();
341
127
    while (auto err = ERR_get_error()) {
342
      char buf[256];
343
37
      ERR_error_string_n(err, buf, sizeof(buf));
344
37
      push_back(buf);
345
37
    }
346
90
    std::reverse(begin(), end());
347
90
  }
348
349
94
  inline MaybeLocal<Value> ToException(
350
      Environment* env,
351
      Local<String> exception_string = Local<String>()) const {
352
94
    if (exception_string.IsEmpty()) {
353
16
      CryptoErrorVector copy(*this);
354
8
      if (copy.empty()) copy.push_back("no error");  // But possibly a bug...
355
      // Use last element as the error message, everything else goes
356
      // into the .opensslErrorStack property on the exception object.
357
      auto exception_string =
358
24
          String::NewFromUtf8(env->isolate(), copy.back().data(),
359
16
                              NewStringType::kNormal, copy.back().size())
360
8
          .ToLocalChecked();
361
8
      copy.pop_back();
362
8
      return copy.ToException(env, exception_string);
363
    }
364
365
86
    Local<Value> exception_v = Exception::Error(exception_string);
366
86
    CHECK(!exception_v.IsEmpty());
367
368
86
    if (!empty()) {
369
21
      CHECK(exception_v->IsObject());
370
21
      Local<Object> exception = exception_v.As<Object>();
371
      Maybe<bool> ok = exception->Set(env->context(),
372
                     env->openssl_error_stack(),
373
84
                     ToV8Value(env->context(), *this).ToLocalChecked());
374
21
      if (ok.IsNothing())
375
1
        return MaybeLocal<Value>();
376
    }
377
378
85
    return exception_v;
379
  }
380
};
381
382
383
78
void ThrowCryptoError(Environment* env,
384
                      unsigned long err,  // NOLINT(runtime/int)
385
                      // Default, only used if there is no SSL `err` which can
386
                      // be used to create a long-style message string.
387
                      const char* message) {
388
78
  char message_buffer[128] = {0};
389

78
  if (err != 0 || message == nullptr) {
390
67
    ERR_error_string_n(err, message_buffer, sizeof(message_buffer));
391
67
    message = message_buffer;
392
  }
393
154
  HandleScope scope(env->isolate());
394
  Local<String> exception_string =
395
156
      String::NewFromUtf8(env->isolate(), message).ToLocalChecked();
396
154
  CryptoErrorVector errors;
397
78
  errors.Capture();
398
  Local<Value> exception;
399
156
  if (!errors.ToException(env, exception_string).ToLocal(&exception))
400
1
    return;
401
  Local<Object> obj;
402
231
  if (!exception->ToObject(env->context()).ToLocal(&obj))
403
    return;
404
154
  if (error::Decorate(env, obj, err).IsNothing())
405
1
    return;
406
76
  env->isolate()->ThrowException(exception);
407
}
408
409
410
// Ensure that OpenSSL has enough entropy (at least 256 bits) for its PRNG.
411
// The entropy pool starts out empty and needs to fill up before the PRNG
412
// can be used securely.  Once the pool is filled, it never dries up again;
413
// its contents is stirred and reused when necessary.
414
//
415
// OpenSSL normally fills the pool automatically but not when someone starts
416
// generating random numbers before the pool is full: in that case OpenSSL
417
// keeps lowering the entropy estimate to thwart attackers trying to guess
418
// the initial state of the PRNG.
419
//
420
// When that happens, we will have to wait until enough entropy is available.
421
// That should normally never take longer than a few milliseconds.
422
//
423
// OpenSSL draws from /dev/random and /dev/urandom.  While /dev/random may
424
// block pending "true" randomness, /dev/urandom is a CSPRNG that doesn't
425
// block under normal circumstances.
426
//
427
// The only time when /dev/urandom may conceivably block is right after boot,
428
// when the whole system is still low on entropy.  That's not something we can
429
// do anything about.
430
9511
inline void CheckEntropy() {
431
  for (;;) {
432
9511
    int status = RAND_status();
433
9511
    CHECK_GE(status, 0);  // Cannot fail.
434
9511
    if (status != 0)
435
19022
      break;
436
437
    // Give up, RAND_poll() not supported.
438
    if (RAND_poll() == 0)
439
      break;
440
  }
441
9511
}
442
443
444
9306
bool EntropySource(unsigned char* buffer, size_t length) {
445
  // Ensure that OpenSSL's PRNG is properly seeded.
446
9306
  CheckEntropy();
447
  // RAND_bytes() can return 0 to indicate that the entropy data is not truly
448
  // random. That's okay, it's still better than V8's stock source of entropy,
449
  // which is /dev/urandom on UNIX platforms and the current time on Windows.
450
9306
  return RAND_bytes(buffer, length) != -1;
451
}
452
453
607
void SecureContext::Initialize(Environment* env, Local<Object> target) {
454
607
  Local<FunctionTemplate> t = env->NewFunctionTemplate(New);
455
1821
  t->InstanceTemplate()->SetInternalFieldCount(
456
607
      SecureContext::kInternalFieldCount);
457
1214
  t->Inherit(BaseObject::GetConstructorTemplate(env));
458
  Local<String> secureContextString =
459
607
      FIXED_ONE_BYTE_STRING(env->isolate(), "SecureContext");
460
607
  t->SetClassName(secureContextString);
461
462
607
  env->SetProtoMethod(t, "init", Init);
463
607
  env->SetProtoMethod(t, "setKey", SetKey);
464
#ifndef OPENSSL_NO_ENGINE
465
607
  env->SetProtoMethod(t, "setEngineKey", SetEngineKey);
466
#endif  // !OPENSSL_NO_ENGINE
467
607
  env->SetProtoMethod(t, "setCert", SetCert);
468
607
  env->SetProtoMethod(t, "addCACert", AddCACert);
469
607
  env->SetProtoMethod(t, "addCRL", AddCRL);
470
607
  env->SetProtoMethod(t, "addRootCerts", AddRootCerts);
471
607
  env->SetProtoMethod(t, "setCipherSuites", SetCipherSuites);
472
607
  env->SetProtoMethod(t, "setCiphers", SetCiphers);
473
607
  env->SetProtoMethod(t, "setSigalgs", SetSigalgs);
474
607
  env->SetProtoMethod(t, "setECDHCurve", SetECDHCurve);
475
607
  env->SetProtoMethod(t, "setDHParam", SetDHParam);
476
607
  env->SetProtoMethod(t, "setMaxProto", SetMaxProto);
477
607
  env->SetProtoMethod(t, "setMinProto", SetMinProto);
478
607
  env->SetProtoMethod(t, "getMaxProto", GetMaxProto);
479
607
  env->SetProtoMethod(t, "getMinProto", GetMinProto);
480
607
  env->SetProtoMethod(t, "setOptions", SetOptions);
481
607
  env->SetProtoMethod(t, "setSessionIdContext", SetSessionIdContext);
482
607
  env->SetProtoMethod(t, "setSessionTimeout", SetSessionTimeout);
483
607
  env->SetProtoMethod(t, "close", Close);
484
607
  env->SetProtoMethod(t, "loadPKCS12", LoadPKCS12);
485
#ifndef OPENSSL_NO_ENGINE
486
607
  env->SetProtoMethod(t, "setClientCertEngine", SetClientCertEngine);
487
#endif  // !OPENSSL_NO_ENGINE
488
607
  env->SetProtoMethodNoSideEffect(t, "getTicketKeys", GetTicketKeys);
489
607
  env->SetProtoMethod(t, "setTicketKeys", SetTicketKeys);
490
607
  env->SetProtoMethod(t, "setFreeListLength", SetFreeListLength);
491
607
  env->SetProtoMethod(t, "enableTicketKeyCallback", EnableTicketKeyCallback);
492
607
  env->SetProtoMethodNoSideEffect(t, "getCertificate", GetCertificate<true>);
493
607
  env->SetProtoMethodNoSideEffect(t, "getIssuer", GetCertificate<false>);
494
495
#define SET_INTEGER_CONSTANTS(name, value)                                     \
496
    t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), name),                        \
497
           Integer::NewFromUnsigned(env->isolate(), value));
498
1821
  SET_INTEGER_CONSTANTS("kTicketKeyReturnIndex", kTicketKeyReturnIndex);
499
1821
  SET_INTEGER_CONSTANTS("kTicketKeyHMACIndex", kTicketKeyHMACIndex);
500
1821
  SET_INTEGER_CONSTANTS("kTicketKeyAESIndex", kTicketKeyAESIndex);
501
1821
  SET_INTEGER_CONSTANTS("kTicketKeyNameIndex", kTicketKeyNameIndex);
502
1821
  SET_INTEGER_CONSTANTS("kTicketKeyIVIndex", kTicketKeyIVIndex);
503
504
#undef SET_INTEGER_CONSTANTS
505
506
  Local<FunctionTemplate> ctx_getter_templ =
507
      FunctionTemplate::New(env->isolate(),
508
                            CtxGetter,
509
                            Local<Value>(),
510
1214
                            Signature::New(env->isolate(), t));
511
512
513
2428
  t->PrototypeTemplate()->SetAccessorProperty(
514
      FIXED_ONE_BYTE_STRING(env->isolate(), "_external"),
515
      ctx_getter_templ,
516
      Local<FunctionTemplate>(),
517
607
      static_cast<PropertyAttribute>(ReadOnly | DontDelete));
518
519
1214
  target->Set(env->context(), secureContextString,
520
3035
              t->GetFunction(env->context()).ToLocalChecked()).Check();
521
607
  env->set_secure_context_constructor_template(t);
522
607
}
523
524
2293
SecureContext::SecureContext(Environment* env, Local<Object> wrap)
525
2293
    : BaseObject(env, wrap) {
526
2293
  MakeWeak();
527
2293
  env->isolate()->AdjustAmountOfExternalAllocatedMemory(kExternalSize);
528
2293
}
529
530
3543
inline void SecureContext::Reset() {
531
3543
  if (ctx_ != nullptr) {
532
2229
    env()->isolate()->AdjustAmountOfExternalAllocatedMemory(-kExternalSize);
533
  }
534
3543
  ctx_.reset();
535
3543
  cert_.reset();
536
3543
  issuer_.reset();
537
3543
}
538
539
6840
SecureContext::~SecureContext() {
540
2280
  Reset();
541
4560
}
542
543
2293
void SecureContext::New(const FunctionCallbackInfo<Value>& args) {
544
2293
  Environment* env = Environment::GetCurrent(args);
545
2293
  new SecureContext(env, args.This());
546
2293
}
547
548
// A maxVersion of 0 means "any", but OpenSSL may support TLS versions that
549
// Node.js doesn't, so pin the max to what we do support.
550
const int MAX_SUPPORTED_VERSION = TLS1_3_VERSION;
551
552
2291
void SecureContext::Init(const FunctionCallbackInfo<Value>& args) {
553
  SecureContext* sc;
554
2340
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
555
2291
  Environment* env = sc->env();
556
557
2291
  CHECK_EQ(args.Length(), 3);
558
4582
  CHECK(args[1]->IsInt32());
559
4582
  CHECK(args[2]->IsInt32());
560
561
6873
  int min_version = args[1].As<Int32>()->Value();
562
6873
  int max_version = args[2].As<Int32>()->Value();
563
2291
  const SSL_METHOD* method = TLS_method();
564
565
2291
  if (max_version == 0)
566
    max_version = MAX_SUPPORTED_VERSION;
567
568
6873
  if (args[0]->IsString()) {
569
679
    const node::Utf8Value sslmethod(env->isolate(), args[0]);
570
571
    // Note that SSLv2 and SSLv3 are disallowed but SSLv23_method and friends
572
    // are still accepted.  They are OpenSSL's way of saying that all known
573
    // protocols below TLS 1.3 are supported unless explicitly disabled (which
574
    // we do below for SSLv2 and SSLv3.)
575

1077
    if (sslmethod == "SSLv2_method" ||
576

712
        sslmethod == "SSLv2_server_method" ||
577
348
        sslmethod == "SSLv2_client_method") {
578
17
      THROW_ERR_TLS_INVALID_PROTOCOL_METHOD(env, "SSLv2 methods disabled");
579
17
      return;
580

1026
    } else if (sslmethod == "SSLv3_method" ||
581

678
               sslmethod == "SSLv3_server_method" ||
582
331
               sslmethod == "SSLv3_client_method") {
583
17
      THROW_ERR_TLS_INVALID_PROTOCOL_METHOD(env, "SSLv3 methods disabled");
584
17
      return;
585
330
    } else if (sslmethod == "SSLv23_method") {
586
36
      max_version = TLS1_2_VERSION;
587
294
    } else if (sslmethod == "SSLv23_server_method") {
588
1
      max_version = TLS1_2_VERSION;
589
1
      method = TLS_server_method();
590
293
    } else if (sslmethod == "SSLv23_client_method") {
591
1
      max_version = TLS1_2_VERSION;
592
1
      method = TLS_client_method();
593
292
    } else if (sslmethod == "TLS_method") {
594
53
      min_version = 0;
595
53
      max_version = MAX_SUPPORTED_VERSION;
596
239
    } else if (sslmethod == "TLS_server_method") {
597
      min_version = 0;
598
      max_version = MAX_SUPPORTED_VERSION;
599
      method = TLS_server_method();
600
239
    } else if (sslmethod == "TLS_client_method") {
601
      min_version = 0;
602
      max_version = MAX_SUPPORTED_VERSION;
603
      method = TLS_client_method();
604
239
    } else if (sslmethod == "TLSv1_method") {
605
71
      min_version = TLS1_VERSION;
606
71
      max_version = TLS1_VERSION;
607
168
    } else if (sslmethod == "TLSv1_server_method") {
608
1
      min_version = TLS1_VERSION;
609
1
      max_version = TLS1_VERSION;
610
1
      method = TLS_server_method();
611
167
    } else if (sslmethod == "TLSv1_client_method") {
612
1
      min_version = TLS1_VERSION;
613
1
      max_version = TLS1_VERSION;
614
1
      method = TLS_client_method();
615
166
    } else if (sslmethod == "TLSv1_1_method") {
616
71
      min_version = TLS1_1_VERSION;
617
71
      max_version = TLS1_1_VERSION;
618
95
    } else if (sslmethod == "TLSv1_1_server_method") {
619
1
      min_version = TLS1_1_VERSION;
620
1
      max_version = TLS1_1_VERSION;
621
1
      method = TLS_server_method();
622
94
    } else if (sslmethod == "TLSv1_1_client_method") {
623
1
      min_version = TLS1_1_VERSION;
624
1
      max_version = TLS1_1_VERSION;
625
1
      method = TLS_client_method();
626
93
    } else if (sslmethod == "TLSv1_2_method") {
627
75
      min_version = TLS1_2_VERSION;
628
75
      max_version = TLS1_2_VERSION;
629
18
    } else if (sslmethod == "TLSv1_2_server_method") {
630
2
      min_version = TLS1_2_VERSION;
631
2
      max_version = TLS1_2_VERSION;
632
2
      method = TLS_server_method();
633
16
    } else if (sslmethod == "TLSv1_2_client_method") {
634
1
      min_version = TLS1_2_VERSION;
635
1
      max_version = TLS1_2_VERSION;
636
1
      method = TLS_client_method();
637
    } else {
638
30
      const std::string msg("Unknown method: ");
639
15
      THROW_ERR_TLS_INVALID_PROTOCOL_METHOD(env, (msg + * sslmethod).c_str());
640
15
      return;
641
    }
642
  }
643
644
2242
  sc->ctx_.reset(SSL_CTX_new(method));
645
2242
  SSL_CTX_set_app_data(sc->ctx_.get(), sc);
646
647
  // Disable SSLv2 in the case when method == TLS_method() and the
648
  // cipher list contains SSLv2 ciphers (not the default, should be rare.)
649
  // The bundled OpenSSL doesn't have SSLv2 support but the system OpenSSL may.
650
  // SSLv3 is disabled because it's susceptible to downgrade attacks (POODLE.)
651
2242
  SSL_CTX_set_options(sc->ctx_.get(), SSL_OP_NO_SSLv2);
652
2242
  SSL_CTX_set_options(sc->ctx_.get(), SSL_OP_NO_SSLv3);
653
654
  // Enable automatic cert chaining. This is enabled by default in OpenSSL, but
655
  // disabled by default in BoringSSL. Enable it explicitly to make the
656
  // behavior match when Node is built with BoringSSL.
657
2242
  SSL_CTX_clear_mode(sc->ctx_.get(), SSL_MODE_NO_AUTO_CHAIN);
658
659
  // SSL session cache configuration
660
2242
  SSL_CTX_set_session_cache_mode(sc->ctx_.get(),
661
                                 SSL_SESS_CACHE_CLIENT |
662
                                 SSL_SESS_CACHE_SERVER |
663
                                 SSL_SESS_CACHE_NO_INTERNAL |
664
2242
                                 SSL_SESS_CACHE_NO_AUTO_CLEAR);
665
666
2242
  SSL_CTX_set_min_proto_version(sc->ctx_.get(), min_version);
667
2242
  SSL_CTX_set_max_proto_version(sc->ctx_.get(), max_version);
668
669
  // OpenSSL 1.1.0 changed the ticket key size, but the OpenSSL 1.0.x size was
670
  // exposed in the public API. To retain compatibility, install a callback
671
  // which restores the old algorithm.
672

6726
  if (RAND_bytes(sc->ticket_key_name_, sizeof(sc->ticket_key_name_)) <= 0 ||
673

4484
      RAND_bytes(sc->ticket_key_hmac_, sizeof(sc->ticket_key_hmac_)) <= 0 ||
674
2242
      RAND_bytes(sc->ticket_key_aes_, sizeof(sc->ticket_key_aes_)) <= 0) {
675
    return env->ThrowError("Error generating ticket keys");
676
  }
677
2242
  SSL_CTX_set_tlsext_ticket_key_cb(sc->ctx_.get(), TicketCompatibilityCallback);
678
}
679
680
681
// Takes a string or buffer and loads it into a BIO.
682
// Caller responsible for BIO_free_all-ing the returned object.
683
2247
static BIOPointer LoadBIO(Environment* env, Local<Value> v) {
684
4494
  HandleScope scope(env->isolate());
685
686
4494
  if (v->IsString()) {
687
2630
    const node::Utf8Value s(env->isolate(), v);
688
1315
    return NodeBIO::NewFixed(*s, s.length());
689
  }
690
691
932
  if (v->IsArrayBufferView()) {
692
932
    ArrayBufferViewContents<char> buf(v.As<ArrayBufferView>());
693
932
    return NodeBIO::NewFixed(buf.data(), buf.length());
694
  }
695
696
  return nullptr;
697
}
698
699
700
825
void SecureContext::SetKey(const FunctionCallbackInfo<Value>& args) {
701
825
  Environment* env = Environment::GetCurrent(args);
702
703
  SecureContext* sc;
704
835
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
705
706
825
  unsigned int len = args.Length();
707
825
  if (len < 1) {
708
    return THROW_ERR_MISSING_ARGS(env, "Private key argument is mandatory");
709
  }
710
711
825
  if (len > 2) {
712
    return env->ThrowError("Only private key and pass phrase are expected");
713
  }
714
715
825
  if (len == 2) {
716

2553
    if (args[1]->IsUndefined() || args[1]->IsNull())
717
799
      len = 1;
718
    else
719
78
      THROW_AND_RETURN_IF_NOT_STRING(env, args[1], "Pass phrase");
720
  }
721
722
1638
  BIOPointer bio(LoadBIO(env, args[0]));
723
823
  if (!bio)
724
    return;
725
726
1638
  node::Utf8Value passphrase(env->isolate(), args[1]);
727
728
  EVPKeyPointer key(
729
      PEM_read_bio_PrivateKey(bio.get(),
730
                              nullptr,
731
                              PasswordCallback,
732
1638
                              *passphrase));
733
734
823
  if (!key) {
735
7
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
736
7
    return ThrowCryptoError(env, err, "PEM_read_bio_PrivateKey");
737
  }
738
739
816
  int rv = SSL_CTX_use_PrivateKey(sc->ctx_.get(), key.get());
740
741
816
  if (!rv) {
742
1
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
743
1
    return ThrowCryptoError(env, err, "SSL_CTX_use_PrivateKey");
744
  }
745
}
746
747
8
void SecureContext::SetSigalgs(const FunctionCallbackInfo<Value>& args) {
748
  SecureContext* sc;
749
8
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
750
8
  Environment* env = sc->env();
751
8
  ClearErrorOnReturn clear_error_on_return;
752
753
8
  CHECK_EQ(args.Length(), 1);
754
24
  CHECK(args[0]->IsString());
755
756
16
  const node::Utf8Value sigalgs(env->isolate(), args[0]);
757
758
8
  int rv = SSL_CTX_set1_sigalgs_list(sc->ctx_.get(), *sigalgs);
759
760
8
  if (rv == 0) {
761
    return ThrowCryptoError(env, ERR_get_error());
762
  }
763
}
764
765
#ifndef OPENSSL_NO_ENGINE
766
// Helpers for the smart pointer.
767
void ENGINE_free_fn(ENGINE* engine) { ENGINE_free(engine); }
768
769
void ENGINE_finish_and_free_fn(ENGINE* engine) {
770
  ENGINE_finish(engine);
771
  ENGINE_free(engine);
772
}
773
774
void SecureContext::SetEngineKey(const FunctionCallbackInfo<Value>& args) {
775
  Environment* env = Environment::GetCurrent(args);
776
777
  SecureContext* sc;
778
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
779
780
  CHECK_EQ(args.Length(), 2);
781
782
  char errmsg[1024];
783
  const node::Utf8Value engine_id(env->isolate(), args[1]);
784
  std::unique_ptr<ENGINE, std::function<void(ENGINE*)>> e =
785
                         { LoadEngineById(*engine_id, &errmsg),
786
                           ENGINE_free_fn };
787
  if (e.get() == nullptr) {
788
    return env->ThrowError(errmsg);
789
  }
790
791
  if (!ENGINE_init(e.get())) {
792
    return env->ThrowError("ENGINE_init");
793
  }
794
795
  e.get_deleter() = ENGINE_finish_and_free_fn;
796
797
  const node::Utf8Value key_name(env->isolate(), args[0]);
798
  EVPKeyPointer key(ENGINE_load_private_key(e.get(), *key_name,
799
                                            nullptr, nullptr));
800
801
  if (!key) {
802
    return ThrowCryptoError(env, ERR_get_error(), "ENGINE_load_private_key");
803
  }
804
805
  int rv = SSL_CTX_use_PrivateKey(sc->ctx_.get(), key.get());
806
807
  if (rv == 0) {
808
    return ThrowCryptoError(env, ERR_get_error(), "SSL_CTX_use_PrivateKey");
809
  }
810
811
  sc->private_key_engine_ = std::move(e);
812
}
813
#endif  // !OPENSSL_NO_ENGINE
814
815
853
int SSL_CTX_use_certificate_chain(SSL_CTX* ctx,
816
                                  X509Pointer&& x,
817
                                  STACK_OF(X509)* extra_certs,
818
                                  X509Pointer* cert,
819
                                  X509Pointer* issuer_) {
820
853
  CHECK(!*issuer_);
821
853
  CHECK(!*cert);
822
853
  X509* issuer = nullptr;
823
824
853
  int ret = SSL_CTX_use_certificate(ctx, x.get());
825
826
853
  if (ret) {
827
    // If we could set up our certificate, now proceed to
828
    // the CA certificates.
829
853
    SSL_CTX_clear_extra_chain_certs(ctx);
830
831
1269
    for (int i = 0; i < sk_X509_num(extra_certs); i++) {
832
416
      X509* ca = sk_X509_value(extra_certs, i);
833
834
      // NOTE: Increments reference count on `ca`
835
416
      if (!SSL_CTX_add1_chain_cert(ctx, ca)) {
836
        ret = 0;
837
        issuer = nullptr;
838
        break;
839
      }
840
      // Note that we must not free r if it was successfully
841
      // added to the chain (while we must free the main
842
      // certificate, since its reference count is increased
843
      // by SSL_CTX_use_certificate).
844
845
      // Find issuer
846

416
      if (issuer != nullptr || X509_check_issued(ca, x.get()) != X509_V_OK)
847
4
        continue;
848
849
412
      issuer = ca;
850
    }
851
  }
852
853
  // Try getting issuer from a cert store
854
853
  if (ret) {
855
853
    if (issuer == nullptr) {
856
441
      ret = SSL_CTX_get_issuer(ctx, x.get(), &issuer);
857
441
      ret = ret < 0 ? 0 : 1;
858
      // NOTE: get_cert_store doesn't increment reference count,
859
      // no need to free `store`
860
    } else {
861
      // Increment issuer reference count
862
412
      issuer = X509_dup(issuer);
863
412
      if (issuer == nullptr) {
864
        ret = 0;
865
      }
866
    }
867
  }
868
869
853
  issuer_->reset(issuer);
870
871

853
  if (ret && x != nullptr) {
872
853
    cert->reset(X509_dup(x.get()));
873
853
    if (!*cert)
874
      ret = 0;
875
  }
876
853
  return ret;
877
}
878
879
880
// Read a file that contains our certificate in "PEM" format,
881
// possibly followed by a sequence of CA certificates that should be
882
// sent to the peer in the Certificate message.
883
//
884
// Taken from OpenSSL - edited for style.
885
841
int SSL_CTX_use_certificate_chain(SSL_CTX* ctx,
886
                                  BIOPointer&& in,
887
                                  X509Pointer* cert,
888
                                  X509Pointer* issuer) {
889
  // Just to ensure that `ERR_peek_last_error` below will return only errors
890
  // that we are interested in
891
841
  ERR_clear_error();
892
893
  X509Pointer x(
894
1682
      PEM_read_bio_X509_AUX(in.get(), nullptr, NoPasswordCallback, nullptr));
895
896
841
  if (!x)
897
    return 0;
898
899
841
  unsigned long err = 0;  // NOLINT(runtime/int)
900
901
1682
  StackOfX509 extra_certs(sk_X509_new_null());
902
841
  if (!extra_certs)
903
    return 0;
904
905
  while (X509Pointer extra {PEM_read_bio_X509(in.get(),
906
                                    nullptr,
907
                                    NoPasswordCallback,
908
1248
                                    nullptr)}) {
909
407
    if (sk_X509_push(extra_certs.get(), extra.get())) {
910
407
      extra.release();
911
407
      continue;
912
    }
913
914
    return 0;
915
407
  }
916
917
  // When the while loop ends, it's usually just EOF.
918
841
  err = ERR_peek_last_error();
919

1682
  if (ERR_GET_LIB(err) == ERR_LIB_PEM &&
920
841
      ERR_GET_REASON(err) == PEM_R_NO_START_LINE) {
921
841
    ERR_clear_error();
922
  } else {
923
    // some real error
924
    return 0;
925
  }
926
927
841
  return SSL_CTX_use_certificate_chain(ctx,
928
841
                                       std::move(x),
929
                                       extra_certs.get(),
930
                                       cert,
931
841
                                       issuer);
932
}
933
934
935
841
void SecureContext::SetCert(const FunctionCallbackInfo<Value>& args) {
936
841
  Environment* env = Environment::GetCurrent(args);
937
938
  SecureContext* sc;
939
841
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
940
941
841
  if (args.Length() != 1) {
942
    return THROW_ERR_MISSING_ARGS(env, "Certificate argument is mandatory");
943
  }
944
945
1682
  BIOPointer bio(LoadBIO(env, args[0]));
946
841
  if (!bio)
947
    return;
948
949
841
  sc->cert_.reset();
950
841
  sc->issuer_.reset();
951
952
2523
  int rv = SSL_CTX_use_certificate_chain(sc->ctx_.get(),
953
841
                                         std::move(bio),
954
841
                                         &sc->cert_,
955
1682
                                         &sc->issuer_);
956
957
841
  if (!rv) {
958
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
959
    return ThrowCryptoError(env, err, "SSL_CTX_use_certificate_chain");
960
  }
961
}
962
963
964
254
static X509_STORE* NewRootCertStore() {
965

254
  static std::vector<X509*> root_certs_vector;
966

254
  static Mutex root_certs_vector_mutex;
967
508
  Mutex::ScopedLock lock(root_certs_vector_mutex);
968
969
254
  if (root_certs_vector.empty()) {
970
34333
    for (size_t i = 0; i < arraysize(root_certs); i++) {
971
      X509* x509 =
972
68172
          PEM_read_bio_X509(NodeBIO::NewFixed(root_certs[i],
973
34086
                                              strlen(root_certs[i])).get(),
974
                            nullptr,   // no re-use of X509 structure
975
                            NoPasswordCallback,
976
34086
                            nullptr);  // no callback data
977
978
      // Parse errors from the built-in roots are fatal.
979
34086
      CHECK_NOT_NULL(x509);
980
981
34086
      root_certs_vector.push_back(x509);
982
    }
983
  }
984
985
254
  X509_STORE* store = X509_STORE_new();
986
254
  if (*system_cert_path != '\0') {
987
    X509_STORE_load_locations(store, system_cert_path, nullptr);
988
  }
989
990
508
  Mutex::ScopedLock cli_lock(node::per_process::cli_options_mutex);
991
254
  if (per_process::cli_options->ssl_openssl_cert_store) {
992
    X509_STORE_set_default_paths(store);
993
  } else {
994
35306
    for (X509* cert : root_certs_vector) {
995
35052
      X509_up_ref(cert);
996
35052
      X509_STORE_add_cert(store, cert);
997
    }
998
  }
999
1000
508
  return store;
1001
}
1002
1003
1004
208
void GetRootCertificates(const FunctionCallbackInfo<Value>& args) {
1005
208
  Environment* env = Environment::GetCurrent(args);
1006
28912
  Local<Value> result[arraysize(root_certs)];
1007
1008
28912
  for (size_t i = 0; i < arraysize(root_certs); i++) {
1009
57408
    if (!String::NewFromOneByte(
1010
            env->isolate(),
1011
28704
            reinterpret_cast<const uint8_t*>(root_certs[i]))
1012
57408
            .ToLocal(&result[i])) {
1013
      return;
1014
    }
1015
  }
1016
1017
624
  args.GetReturnValue().Set(
1018
      Array::New(env->isolate(), result, arraysize(root_certs)));
1019
}
1020
1021
1022
553
void SecureContext::AddCACert(const FunctionCallbackInfo<Value>& args) {
1023
553
  Environment* env = Environment::GetCurrent(args);
1024
1025
  SecureContext* sc;
1026
553
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1027
553
  ClearErrorOnReturn clear_error_on_return;
1028
1029
553
  if (args.Length() != 1) {
1030
    return THROW_ERR_MISSING_ARGS(env, "CA certificate argument is mandatory");
1031
  }
1032
1033
1106
  BIOPointer bio(LoadBIO(env, args[0]));
1034
553
  if (!bio)
1035
    return;
1036
1037
553
  X509_STORE* cert_store = SSL_CTX_get_cert_store(sc->ctx_.get());
1038
1446
  while (X509* x509 = PEM_read_bio_X509_AUX(
1039
1446
      bio.get(), nullptr, NoPasswordCallback, nullptr)) {
1040
893
    if (cert_store == root_cert_store) {
1041
1
      cert_store = NewRootCertStore();
1042
1
      SSL_CTX_set_cert_store(sc->ctx_.get(), cert_store);
1043
    }
1044
893
    X509_STORE_add_cert(cert_store, x509);
1045
893
    SSL_CTX_add_client_CA(sc->ctx_.get(), x509);
1046
893
    X509_free(x509);
1047
893
  }
1048
}
1049
1050
1051
2
void SecureContext::AddCRL(const FunctionCallbackInfo<Value>& args) {
1052
2
  Environment* env = Environment::GetCurrent(args);
1053
1054
  SecureContext* sc;
1055
3
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1056
1057
2
  if (args.Length() != 1) {
1058
    return THROW_ERR_MISSING_ARGS(env, "CRL argument is mandatory");
1059
  }
1060
1061
1
  ClearErrorOnReturn clear_error_on_return;
1062
1063
3
  BIOPointer bio(LoadBIO(env, args[0]));
1064
2
  if (!bio)
1065
    return;
1066
1067
  DeleteFnPtr<X509_CRL, X509_CRL_free> crl(
1068
3
      PEM_read_bio_X509_CRL(bio.get(), nullptr, NoPasswordCallback, nullptr));
1069
1070
2
  if (!crl)
1071
1
    return env->ThrowError("Failed to parse CRL");
1072
1073
1
  X509_STORE* cert_store = SSL_CTX_get_cert_store(sc->ctx_.get());
1074
1
  if (cert_store == root_cert_store) {
1075
    cert_store = NewRootCertStore();
1076
    SSL_CTX_set_cert_store(sc->ctx_.get(), cert_store);
1077
  }
1078
1079
1
  X509_STORE_add_crl(cert_store, crl.get());
1080
  X509_STORE_set_flags(cert_store,
1081
1
                       X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
1082
}
1083
1084
1085
4
static unsigned long AddCertsFromFile(  // NOLINT(runtime/int)
1086
    X509_STORE* store,
1087
    const char* file) {
1088
4
  ERR_clear_error();
1089
8
  MarkPopErrorOnReturn mark_pop_error_on_return;
1090
1091
8
  BIOPointer bio(BIO_new_file(file, "r"));
1092
4
  if (!bio)
1093
1
    return ERR_get_error();
1094
1095
  while (X509* x509 =
1096
6
      PEM_read_bio_X509(bio.get(), nullptr, NoPasswordCallback, nullptr)) {
1097
3
    X509_STORE_add_cert(store, x509);
1098
3
    X509_free(x509);
1099
3
  }
1100
1101
3
  unsigned long err = ERR_peek_error();  // NOLINT(runtime/int)
1102
  // Ignore error if its EOF/no start line found.
1103

6
  if (ERR_GET_LIB(err) == ERR_LIB_PEM &&
1104
3
      ERR_GET_REASON(err) == PEM_R_NO_START_LINE) {
1105
3
    return 0;
1106
  }
1107
1108
  return err;
1109
}
1110
1111
1112
4
void UseExtraCaCerts(const std::string& file) {
1113
4
  ClearErrorOnReturn clear_error_on_return;
1114
1115
4
  if (root_cert_store == nullptr) {
1116
4
    root_cert_store = NewRootCertStore();
1117
1118
4
    if (!file.empty()) {
1119
4
      unsigned long err = AddCertsFromFile(  // NOLINT(runtime/int)
1120
                                           root_cert_store,
1121
4
                                           file.c_str());
1122
4
      if (err) {
1123
1
        fprintf(stderr,
1124
                "Warning: Ignoring extra certs from `%s`, load failed: %s\n",
1125
                file.c_str(),
1126
1
                ERR_error_string(err, nullptr));
1127
      } else {
1128
3
        extra_root_certs_loaded = true;
1129
      }
1130
    }
1131
  }
1132
4
}
1133
1134
1135
3
static void IsExtraRootCertsFileLoaded(
1136
    const FunctionCallbackInfo<Value>& args) {
1137
9
  return args.GetReturnValue().Set(extra_root_certs_loaded);
1138
}
1139
1140
1141
1709
void SecureContext::AddRootCerts(const FunctionCallbackInfo<Value>& args) {
1142
  SecureContext* sc;
1143
1709
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1144
1709
  ClearErrorOnReturn clear_error_on_return;
1145
1146
1709
  if (root_cert_store == nullptr) {
1147
243
    root_cert_store = NewRootCertStore();
1148
  }
1149
1150
  // Increment reference count so global store is not deleted along with CTX.
1151
1709
  X509_STORE_up_ref(root_cert_store);
1152
1709
  SSL_CTX_set_cert_store(sc->ctx_.get(), root_cert_store);
1153
}
1154
1155
1156
2166
void SecureContext::SetCipherSuites(const FunctionCallbackInfo<Value>& args) {
1157
  // BoringSSL doesn't allow API config of TLS1.3 cipher suites.
1158
#ifndef OPENSSL_IS_BORINGSSL
1159
  SecureContext* sc;
1160
2167
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1161
2166
  Environment* env = sc->env();
1162
2165
  ClearErrorOnReturn clear_error_on_return;
1163
1164
2166
  CHECK_EQ(args.Length(), 1);
1165
6498
  CHECK(args[0]->IsString());
1166
1167
4331
  const node::Utf8Value ciphers(args.GetIsolate(), args[0]);
1168
2166
  if (!SSL_CTX_set_ciphersuites(sc->ctx_.get(), *ciphers)) {
1169
1
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
1170
1
    return ThrowCryptoError(env, err, "Failed to set ciphers");
1171
  }
1172
#endif
1173
}
1174
1175
1176
2168
void SecureContext::SetCiphers(const FunctionCallbackInfo<Value>& args) {
1177
  SecureContext* sc;
1178
2183
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1179
2168
  Environment* env = sc->env();
1180
2153
  ClearErrorOnReturn clear_error_on_return;
1181
1182
2168
  CHECK_EQ(args.Length(), 1);
1183
6504
  CHECK(args[0]->IsString());
1184
1185
4321
  const node::Utf8Value ciphers(args.GetIsolate(), args[0]);
1186
2168
  if (!SSL_CTX_set_cipher_list(sc->ctx_.get(), *ciphers)) {
1187
15
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
1188
1189

15
    if (strlen(*ciphers) == 0 && ERR_GET_REASON(err) == SSL_R_NO_CIPHER_MATCH) {
1190
      // TLS1.2 ciphers were deliberately cleared, so don't consider
1191
      // SSL_R_NO_CIPHER_MATCH to be an error (this is how _set_cipher_suites()
1192
      // works). If the user actually sets a value (like "no-such-cipher"), then
1193
      // that's actually an error.
1194
11
      return;
1195
    }
1196
4
    return ThrowCryptoError(env, err, "Failed to set ciphers");
1197
  }
1198
}
1199
1200
1201
2161
void SecureContext::SetECDHCurve(const FunctionCallbackInfo<Value>& args) {
1202
  SecureContext* sc;
1203
4315
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1204
2161
  Environment* env = sc->env();
1205
1206
2161
  if (args.Length() != 1)
1207
    return THROW_ERR_MISSING_ARGS(env, "ECDH curve name argument is mandatory");
1208
1209
6483
  THROW_AND_RETURN_IF_NOT_STRING(env, args[0], "ECDH curve name");
1210
1211
2167
  node::Utf8Value curve(env->isolate(), args[0]);
1212
1213
2160
  if (strcmp(*curve, "auto") == 0)
1214
2150
    return;
1215
1216
10
  if (!SSL_CTX_set1_curves_list(sc->ctx_.get(), *curve))
1217
3
    return env->ThrowError("Failed to set ECDH curve");
1218
}
1219
1220
1221
10
void SecureContext::SetDHParam(const FunctionCallbackInfo<Value>& args) {
1222
  SecureContext* sc;
1223
13
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.This());
1224
10
  Environment* env = sc->env();
1225
7
  ClearErrorOnReturn clear_error_on_return;
1226
1227
  // Auto DH is not supported in openssl 1.0.1, so dhparam needs
1228
  // to be specified explicitly
1229
10
  if (args.Length() != 1)
1230
    return THROW_ERR_MISSING_ARGS(env, "DH argument is mandatory");
1231
1232
17
  DHPointer dh;
1233
  {
1234
20
    BIOPointer bio(LoadBIO(env, args[0]));
1235
10
    if (!bio)
1236
      return;
1237
1238
10
    dh.reset(PEM_read_bio_DHparams(bio.get(), nullptr, nullptr, nullptr));
1239
  }
1240
1241
  // Invalid dhparam is silently discarded and DHE is no longer used.
1242
10
  if (!dh)
1243
1
    return;
1244
1245
  const BIGNUM* p;
1246
9
  DH_get0_pqg(dh.get(), &p, nullptr, nullptr);
1247
9
  const int size = BN_num_bits(p);
1248
9
  if (size < 1024) {
1249
    return THROW_ERR_INVALID_ARG_VALUE(
1250
2
        env, "DH parameter is less than 1024 bits");
1251
7
  } else if (size < 2048) {
1252
9
    args.GetReturnValue().Set(FIXED_ONE_BYTE_STRING(
1253
        env->isolate(), "DH parameter is less than 2048 bits"));
1254
  }
1255
1256
7
  SSL_CTX_set_options(sc->ctx_.get(), SSL_OP_SINGLE_DH_USE);
1257
7
  int r = SSL_CTX_set_tmp_dh(sc->ctx_.get(), dh.get());
1258
1259
7
  if (!r)
1260
    return env->ThrowTypeError("Error setting temp DH parameter");
1261
}
1262
1263
1264
11
void SecureContext::SetMinProto(const FunctionCallbackInfo<Value>& args) {
1265
  SecureContext* sc;
1266
11
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1267
1268
11
  CHECK_EQ(args.Length(), 1);
1269
22
  CHECK(args[0]->IsInt32());
1270
1271
33
  int version = args[0].As<Int32>()->Value();
1272
1273
11
  CHECK(SSL_CTX_set_min_proto_version(sc->ctx_.get(), version));
1274
}
1275
1276
1277
46
void SecureContext::SetMaxProto(const FunctionCallbackInfo<Value>& args) {
1278
  SecureContext* sc;
1279
46
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1280
1281
46
  CHECK_EQ(args.Length(), 1);
1282
92
  CHECK(args[0]->IsInt32());
1283
1284
138
  int version = args[0].As<Int32>()->Value();
1285
1286
46
  CHECK(SSL_CTX_set_max_proto_version(sc->ctx_.get(), version));
1287
}
1288
1289
1290
57
void SecureContext::GetMinProto(const FunctionCallbackInfo<Value>& args) {
1291
  SecureContext* sc;
1292
57
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1293
1294
57
  CHECK_EQ(args.Length(), 0);
1295
1296
  long version =  // NOLINT(runtime/int)
1297
57
    SSL_CTX_get_min_proto_version(sc->ctx_.get());
1298
171
  args.GetReturnValue().Set(static_cast<uint32_t>(version));
1299
}
1300
1301
1302
76
void SecureContext::GetMaxProto(const FunctionCallbackInfo<Value>& args) {
1303
  SecureContext* sc;
1304
76
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1305
1306
76
  CHECK_EQ(args.Length(), 0);
1307
1308
  long version =  // NOLINT(runtime/int)
1309
76
    SSL_CTX_get_max_proto_version(sc->ctx_.get());
1310
228
  args.GetReturnValue().Set(static_cast<uint32_t>(version));
1311
}
1312
1313
1314
827
void SecureContext::SetOptions(const FunctionCallbackInfo<Value>& args) {
1315
  SecureContext* sc;
1316
827
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1317
  int64_t val;
1318
1319

2481
  if (args.Length() != 1 ||
1320
4135
      !args[0]->IntegerValue(args.GetIsolate()->GetCurrentContext()).To(&val)) {
1321
    return THROW_ERR_INVALID_ARG_TYPE(
1322
        sc->env(), "Options must be an integer value");
1323
  }
1324
1325
827
  SSL_CTX_set_options(sc->ctx_.get(),
1326
827
                      static_cast<long>(val));  // NOLINT(runtime/int)
1327
}
1328
1329
1330
756
void SecureContext::SetSessionIdContext(
1331
    const FunctionCallbackInfo<Value>& args) {
1332
  SecureContext* sc;
1333
1512
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1334
756
  Environment* env = sc->env();
1335
1336
756
  if (args.Length() != 1) {
1337
    return THROW_ERR_MISSING_ARGS(
1338
        env, "Session ID context argument is mandatory");
1339
  }
1340
1341
2268
  THROW_AND_RETURN_IF_NOT_STRING(env, args[0], "Session ID context");
1342
1343
756
  const node::Utf8Value sessionIdContext(args.GetIsolate(), args[0]);
1344
  const unsigned char* sid_ctx =
1345
756
      reinterpret_cast<const unsigned char*>(*sessionIdContext);
1346
756
  unsigned int sid_ctx_len = sessionIdContext.length();
1347
1348
756
  int r = SSL_CTX_set_session_id_context(sc->ctx_.get(), sid_ctx, sid_ctx_len);
1349
756
  if (r == 1)
1350
756
    return;
1351
1352
  BUF_MEM* mem;
1353
  Local<String> message;
1354
1355
  BIOPointer bio(BIO_new(BIO_s_mem()));
1356
  if (!bio) {
1357
    message = FIXED_ONE_BYTE_STRING(args.GetIsolate(),
1358
                                    "SSL_CTX_set_session_id_context error");
1359
  } else {
1360
    ERR_print_errors(bio.get());
1361
    BIO_get_mem_ptr(bio.get(), &mem);
1362
    message = OneByteString(args.GetIsolate(), mem->data, mem->length);
1363
  }
1364
1365
  args.GetIsolate()->ThrowException(Exception::TypeError(message));
1366
}
1367
1368
1369
2
void SecureContext::SetSessionTimeout(const FunctionCallbackInfo<Value>& args) {
1370
  SecureContext* sc;
1371
3
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1372
1373

6
  if (args.Length() != 1 || !args[0]->IsInt32()) {
1374
1
    return THROW_ERR_INVALID_ARG_TYPE(
1375
1
        sc->env(), "Session timeout must be a 32-bit integer");
1376
  }
1377
1378
3
  int32_t sessionTimeout = args[0].As<Int32>()->Value();
1379
1
  SSL_CTX_set_timeout(sc->ctx_.get(), sessionTimeout);
1380
}
1381
1382
1383
1263
void SecureContext::Close(const FunctionCallbackInfo<Value>& args) {
1384
  SecureContext* sc;
1385
1263
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1386
1263
  sc->Reset();
1387
}
1388
1389
1390
// Takes .pfx or .p12 and password in string or buffer format
1391
18
void SecureContext::LoadPKCS12(const FunctionCallbackInfo<Value>& args) {
1392
18
  Environment* env = Environment::GetCurrent(args);
1393
1394
30
  std::vector<char> pass;
1395
18
  bool ret = false;
1396
1397
  SecureContext* sc;
1398
18
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1399
12
  ClearErrorOnReturn clear_error_on_return;
1400
1401
18
  if (args.Length() < 1) {
1402
    return THROW_ERR_MISSING_ARGS(env, "PFX certificate argument is mandatory");
1403
  }
1404
1405
30
  BIOPointer in(LoadBIO(env, args[0]));
1406
18
  if (!in)
1407
    return env->ThrowError("Unable to load BIO");
1408
1409
18
  if (args.Length() >= 2) {
1410
15
    THROW_AND_RETURN_IF_NOT_BUFFER(env, args[1], "Pass phrase");
1411
30
    Local<ArrayBufferView> abv = args[1].As<ArrayBufferView>();
1412
15
    size_t passlen = abv->ByteLength();
1413
15
    pass.resize(passlen + 1);
1414
30
    abv->CopyContents(pass.data(), passlen);
1415
15
    pass[passlen] = '\0';
1416
  }
1417
1418
  // Free previous certs
1419
18
  sc->issuer_.reset();
1420
18
  sc->cert_.reset();
1421
1422
18
  X509_STORE* cert_store = SSL_CTX_get_cert_store(sc->ctx_.get());
1423
1424
30
  DeleteFnPtr<PKCS12, PKCS12_free> p12;
1425
30
  EVPKeyPointer pkey;
1426
30
  X509Pointer cert;
1427
30
  StackOfX509 extra_certs;
1428
1429
18
  PKCS12* p12_ptr = nullptr;
1430
18
  EVP_PKEY* pkey_ptr = nullptr;
1431
18
  X509* cert_ptr = nullptr;
1432
18
  STACK_OF(X509)* extra_certs_ptr = nullptr;
1433
36
  if (d2i_PKCS12_bio(in.get(), &p12_ptr) &&
1434
32
      (p12.reset(p12_ptr), true) &&  // Move ownership to the smart pointer.
1435
16
      PKCS12_parse(p12.get(), pass.data(),
1436
                   &pkey_ptr,
1437
                   &cert_ptr,
1438
                   &extra_certs_ptr) &&
1439
12
      (pkey.reset(pkey_ptr), cert.reset(cert_ptr),
1440
24
       extra_certs.reset(extra_certs_ptr), true) &&  // Move ownership.
1441
36
      SSL_CTX_use_certificate_chain(sc->ctx_.get(),
1442
12
                                    std::move(cert),
1443
                                    extra_certs.get(),
1444
12
                                    &sc->cert_,
1445

42
                                    &sc->issuer_) &&
1446
12
      SSL_CTX_use_PrivateKey(sc->ctx_.get(), pkey.get())) {
1447
    // Add CA certs too
1448
21
    for (int i = 0; i < sk_X509_num(extra_certs.get()); i++) {
1449
9
      X509* ca = sk_X509_value(extra_certs.get(), i);
1450
1451
9
      if (cert_store == root_cert_store) {
1452
6
        cert_store = NewRootCertStore();
1453
6
        SSL_CTX_set_cert_store(sc->ctx_.get(), cert_store);
1454
      }
1455
9
      X509_STORE_add_cert(cert_store, ca);
1456
9
      SSL_CTX_add_client_CA(sc->ctx_.get(), ca);
1457
    }
1458
12
    ret = true;
1459
  }
1460
1461
18
  if (!ret) {
1462
6
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
1463
6
    const char* str = ERR_reason_error_string(err);
1464
6
    return env->ThrowError(str);
1465
  }
1466
}
1467
1468
1469
#ifndef OPENSSL_NO_ENGINE
1470
void SecureContext::SetClientCertEngine(
1471
    const FunctionCallbackInfo<Value>& args) {
1472
  Environment* env = Environment::GetCurrent(args);
1473
  CHECK_EQ(args.Length(), 1);
1474
  CHECK(args[0]->IsString());
1475
1476
  SecureContext* sc;
1477
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1478
1479
  MarkPopErrorOnReturn mark_pop_error_on_return;
1480
1481
  // SSL_CTX_set_client_cert_engine does not itself support multiple
1482
  // calls by cleaning up before overwriting the client_cert_engine
1483
  // internal context variable.
1484
  // Instead of trying to fix up this problem we in turn also do not
1485
  // support multiple calls to SetClientCertEngine.
1486
  if (sc->client_cert_engine_provided_) {
1487
    return env->ThrowError(
1488
        "Multiple calls to SetClientCertEngine are not allowed");
1489
  }
1490
1491
  const node::Utf8Value engine_id(env->isolate(), args[0]);
1492
  char errmsg[1024];
1493
  DeleteFnPtr<ENGINE, ENGINE_free_fn> engine(
1494
      LoadEngineById(*engine_id, &errmsg));
1495
1496
  if (!engine)
1497
    return env->ThrowError(errmsg);
1498
1499
  // Note that this takes another reference to `engine`.
1500
  int r = SSL_CTX_set_client_cert_engine(sc->ctx_.get(), engine.get());
1501
  if (r == 0)
1502
    return ThrowCryptoError(env, ERR_get_error());
1503
  sc->client_cert_engine_provided_ = true;
1504
}
1505
#endif  // !OPENSSL_NO_ENGINE
1506
1507
1508
10
void SecureContext::GetTicketKeys(const FunctionCallbackInfo<Value>& args) {
1509
#if !defined(OPENSSL_NO_TLSEXT) && defined(SSL_CTX_get_tlsext_ticket_keys)
1510
1511
  SecureContext* wrap;
1512
10
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1513
1514
20
  Local<Object> buff = Buffer::New(wrap->env(), 48).ToLocalChecked();
1515
10
  memcpy(Buffer::Data(buff), wrap->ticket_key_name_, 16);
1516
10
  memcpy(Buffer::Data(buff) + 16, wrap->ticket_key_hmac_, 16);
1517
10
  memcpy(Buffer::Data(buff) + 32, wrap->ticket_key_aes_, 16);
1518
1519
20
  args.GetReturnValue().Set(buff);
1520
#endif  // !def(OPENSSL_NO_TLSEXT) && def(SSL_CTX_get_tlsext_ticket_keys)
1521
}
1522
1523
1524
25
void SecureContext::SetTicketKeys(const FunctionCallbackInfo<Value>& args) {
1525
#if !defined(OPENSSL_NO_TLSEXT) && defined(SSL_CTX_get_tlsext_ticket_keys)
1526
  SecureContext* wrap;
1527
27
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1528
25
  Environment* env = wrap->env();
1529
1530
  // TODO(@sam-github) Move type and len check to js, and CHECK() in C++.
1531
25
  if (args.Length() < 1) {
1532
    return THROW_ERR_MISSING_ARGS(env, "Ticket keys argument is mandatory");
1533
  }
1534
1535
25
  THROW_AND_RETURN_IF_NOT_BUFFER(env, args[0], "Ticket keys");
1536
48
  ArrayBufferViewContents<char> buf(args[0].As<ArrayBufferView>());
1537
1538
24
  if (buf.length() != 48) {
1539
    return THROW_ERR_INVALID_ARG_VALUE(
1540
1
        env, "Ticket keys length must be 48 bytes");
1541
  }
1542
1543
23
  memcpy(wrap->ticket_key_name_, buf.data(), 16);
1544
23
  memcpy(wrap->ticket_key_hmac_, buf.data() + 16, 16);
1545
23
  memcpy(wrap->ticket_key_aes_, buf.data() + 32, 16);
1546
1547
46
  args.GetReturnValue().Set(true);
1548
#endif  // !def(OPENSSL_NO_TLSEXT) && def(SSL_CTX_get_tlsext_ticket_keys)
1549
}
1550
1551
1552
1289
void SecureContext::SetFreeListLength(const FunctionCallbackInfo<Value>& args) {
1553
1289
}
1554
1555
1556
// Currently, EnableTicketKeyCallback and TicketKeyCallback are only present for
1557
// the regression test in test/parallel/test-https-resume-after-renew.js.
1558
1
void SecureContext::EnableTicketKeyCallback(
1559
    const FunctionCallbackInfo<Value>& args) {
1560
  SecureContext* wrap;
1561
1
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1562
1563
1
  SSL_CTX_set_tlsext_ticket_key_cb(wrap->ctx_.get(), TicketKeyCallback);
1564
}
1565
1566
1567
4
int SecureContext::TicketKeyCallback(SSL* ssl,
1568
                                     unsigned char* name,
1569
                                     unsigned char* iv,
1570
                                     EVP_CIPHER_CTX* ectx,
1571
                                     HMAC_CTX* hctx,
1572
                                     int enc) {
1573
  static const int kTicketPartSize = 16;
1574
1575
  SecureContext* sc = static_cast<SecureContext*>(
1576
4
      SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
1577
1578
4
  Environment* env = sc->env();
1579
8
  HandleScope handle_scope(env->isolate());
1580
4
  Context::Scope context_scope(env->context());
1581
1582
  Local<Value> argv[] = {
1583
8
    Buffer::Copy(env,
1584
                 reinterpret_cast<char*>(name),
1585
                 kTicketPartSize).ToLocalChecked(),
1586
8
    Buffer::Copy(env,
1587
                 reinterpret_cast<char*>(iv),
1588
                 kTicketPartSize).ToLocalChecked(),
1589
    Boolean::New(env->isolate(), enc != 0)
1590
16
  };
1591
1592
8
  Local<Value> ret = node::MakeCallback(env->isolate(),
1593
                                        sc->object(),
1594
                                        env->ticketkeycallback_string(),
1595
4
                                        arraysize(argv),
1596
                                        argv,
1597
12
                                        {0, 0}).ToLocalChecked();
1598
4
  Local<Array> arr = ret.As<Array>();
1599
1600
  int r =
1601
8
      arr->Get(env->context(),
1602
12
               kTicketKeyReturnIndex).ToLocalChecked()
1603
12
               ->Int32Value(env->context()).FromJust();
1604
4
  if (r < 0)
1605
    return r;
1606
1607
8
  Local<Value> hmac = arr->Get(env->context(),
1608
8
                               kTicketKeyHMACIndex).ToLocalChecked();
1609
8
  Local<Value> aes = arr->Get(env->context(),
1610
8
                              kTicketKeyAESIndex).ToLocalChecked();
1611
4
  if (Buffer::Length(aes) != kTicketPartSize)
1612
    return -1;
1613
1614
4
  if (enc) {
1615
6
    Local<Value> name_val = arr->Get(env->context(),
1616
6
                                     kTicketKeyNameIndex).ToLocalChecked();
1617
6
    Local<Value> iv_val = arr->Get(env->context(),
1618
6
                                   kTicketKeyIVIndex).ToLocalChecked();
1619
1620

6
    if (Buffer::Length(name_val) != kTicketPartSize ||
1621
3
        Buffer::Length(iv_val) != kTicketPartSize) {
1622
      return -1;
1623
    }
1624
1625
6
    name_val.As<ArrayBufferView>()->CopyContents(name, kTicketPartSize);
1626
6
    iv_val.As<ArrayBufferView>()->CopyContents(iv, kTicketPartSize);
1627
  }
1628
1629
4
  ArrayBufferViewContents<unsigned char> hmac_buf(hmac);
1630
8
  HMAC_Init_ex(hctx,
1631
4
               hmac_buf.data(),
1632
4
               hmac_buf.length(),
1633
               EVP_sha256(),
1634
4
               nullptr);
1635
1636
4
  ArrayBufferViewContents<unsigned char> aes_key(aes.As<ArrayBufferView>());
1637
4
  if (enc) {
1638
3
    EVP_EncryptInit_ex(ectx,
1639
                       EVP_aes_128_cbc(),
1640
                       nullptr,
1641
                       aes_key.data(),
1642
3
                       iv);
1643
  } else {
1644
1
    EVP_DecryptInit_ex(ectx,
1645
                       EVP_aes_128_cbc(),
1646
                       nullptr,
1647
                       aes_key.data(),
1648
1
                       iv);
1649
  }
1650
1651
4
  return r;
1652
}
1653
1654
1655
1159
int SecureContext::TicketCompatibilityCallback(SSL* ssl,
1656
                                               unsigned char* name,
1657
                                               unsigned char* iv,
1658
                                               EVP_CIPHER_CTX* ectx,
1659
                                               HMAC_CTX* hctx,
1660
                                               int enc) {
1661
  SecureContext* sc = static_cast<SecureContext*>(
1662
1159
      SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
1663
1664
1159
  if (enc) {
1665
1105
    memcpy(name, sc->ticket_key_name_, sizeof(sc->ticket_key_name_));
1666

3315
    if (RAND_bytes(iv, 16) <= 0 ||
1667
1105
        EVP_EncryptInit_ex(ectx, EVP_aes_128_cbc(), nullptr,
1668

2210
                           sc->ticket_key_aes_, iv) <= 0 ||
1669
1105
        HMAC_Init_ex(hctx, sc->ticket_key_hmac_, sizeof(sc->ticket_key_hmac_),
1670
                     EVP_sha256(), nullptr) <= 0) {
1671
      return -1;
1672
    }
1673
1105
    return 1;
1674
  }
1675
1676
54
  if (memcmp(name, sc->ticket_key_name_, sizeof(sc->ticket_key_name_)) != 0) {
1677
    // The ticket key name does not match. Discard the ticket.
1678
12
    return 0;
1679
  }
1680
1681
84
  if (EVP_DecryptInit_ex(ectx, EVP_aes_128_cbc(), nullptr, sc->ticket_key_aes_,
1682

84
                         iv) <= 0 ||
1683
42
      HMAC_Init_ex(hctx, sc->ticket_key_hmac_, sizeof(sc->ticket_key_hmac_),
1684
                   EVP_sha256(), nullptr) <= 0) {
1685
    return -1;
1686
  }
1687
42
  return 1;
1688
}
1689
1690
1691
2
void SecureContext::CtxGetter(const FunctionCallbackInfo<Value>& info) {
1692
  SecureContext* sc;
1693
2
  ASSIGN_OR_RETURN_UNWRAP(&sc, info.This());
1694
4
  Local<External> ext = External::New(info.GetIsolate(), sc->ctx_.get());
1695
4
  info.GetReturnValue().Set(ext);
1696
}
1697
1698
1699
template <bool primary>
1700
6
void SecureContext::GetCertificate(const FunctionCallbackInfo<Value>& args) {
1701
  SecureContext* wrap;
1702

6
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1703
6
  Environment* env = wrap->env();
1704
  X509* cert;
1705
1706
  if (primary)
1707
3
    cert = wrap->cert_.get();
1708
  else
1709
3
    cert = wrap->issuer_.get();
1710

6
  if (cert == nullptr)
1711
    return args.GetReturnValue().SetNull();
1712
1713
6
  int size = i2d_X509(cert, nullptr);
1714
12
  Local<Object> buff = Buffer::New(env, size).ToLocalChecked();
1715
  unsigned char* serialized = reinterpret_cast<unsigned char*>(
1716
6
      Buffer::Data(buff));
1717
6
  i2d_X509(cert, &serialized);
1718
1719
12
  args.GetReturnValue().Set(buff);
1720
}
1721
1722
1723
template <class Base>
1724
506
void SSLWrap<Base>::AddMethods(Environment* env, Local<FunctionTemplate> t) {
1725
1012
  HandleScope scope(env->isolate());
1726
1727
506
  env->SetProtoMethodNoSideEffect(t, "getPeerCertificate", GetPeerCertificate);
1728
506
  env->SetProtoMethodNoSideEffect(t, "getCertificate", GetCertificate);
1729
506
  env->SetProtoMethodNoSideEffect(t, "getFinished", GetFinished);
1730
506
  env->SetProtoMethodNoSideEffect(t, "getPeerFinished", GetPeerFinished);
1731
506
  env->SetProtoMethodNoSideEffect(t, "getSession", GetSession);
1732
506
  env->SetProtoMethod(t, "setSession", SetSession);
1733
506
  env->SetProtoMethod(t, "loadSession", LoadSession);
1734
506
  env->SetProtoMethodNoSideEffect(t, "isSessionReused", IsSessionReused);
1735
506
  env->SetProtoMethodNoSideEffect(t, "verifyError", VerifyError);
1736
506
  env->SetProtoMethodNoSideEffect(t, "getCipher", GetCipher);
1737
506
  env->SetProtoMethodNoSideEffect(t, "getSharedSigalgs", GetSharedSigalgs);
1738
506
  env->SetProtoMethodNoSideEffect(
1739
      t, "exportKeyingMaterial", ExportKeyingMaterial);
1740
506
  env->SetProtoMethod(t, "endParser", EndParser);
1741
506
  env->SetProtoMethod(t, "certCbDone", CertCbDone);
1742
506
  env->SetProtoMethod(t, "renegotiate", Renegotiate);
1743
506
  env->SetProtoMethodNoSideEffect(t, "getTLSTicket", GetTLSTicket);
1744
506
  env->SetProtoMethod(t, "newSessionDone", NewSessionDone);
1745
506
  env->SetProtoMethod(t, "setOCSPResponse", SetOCSPResponse);
1746
506
  env->SetProtoMethod(t, "requestOCSP", RequestOCSP);
1747
506
  env->SetProtoMethodNoSideEffect(t, "getEphemeralKeyInfo",
1748
                                  GetEphemeralKeyInfo);
1749
506
  env->SetProtoMethodNoSideEffect(t, "getProtocol", GetProtocol);
1750
1751
506
  env->SetProtoMethod(t, "setMaxSendFragment", SetMaxSendFragment);
1752
1753
506
  env->SetProtoMethodNoSideEffect(t, "getALPNNegotiatedProtocol",
1754
                                  GetALPNNegotiatedProto);
1755
506
  env->SetProtoMethod(t, "setALPNProtocols", SetALPNProtocols);
1756
506
}
1757
1758
1759
template <class Base>
1760
12181
void SSLWrap<Base>::ConfigureSecureContext(SecureContext* sc) {
1761
  // OCSP stapling
1762
12181
  SSL_CTX_set_tlsext_status_cb(sc->ctx_.get(), TLSExtStatusCallback);
1763
12181
  SSL_CTX_set_tlsext_status_arg(sc->ctx_.get(), nullptr);
1764
12181
}
1765
1766
1767
template <class Base>
1768
97
SSL_SESSION* SSLWrap<Base>::GetSessionCallback(SSL* s,
1769
                                               const unsigned char* key,
1770
                                               int len,
1771
                                               int* copy) {
1772
97
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
1773
1774
97
  *copy = 0;
1775
97
  return w->next_sess_.release();
1776
}
1777
1778
1779
template <class Base>
1780
1724
int SSLWrap<Base>::NewSessionCallback(SSL* s, SSL_SESSION* sess) {
1781
1724
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
1782
1724
  Environment* env = w->ssl_env();
1783
3448
  HandleScope handle_scope(env->isolate());
1784
1724
  Context::Scope context_scope(env->context());
1785
1786
1724
  if (!w->session_callbacks_)
1787
1435
    return 0;
1788
1789
  // Check if session is small enough to be stored
1790
289
  int size = i2d_SSL_SESSION(sess, nullptr);
1791
289
  if (size > SecureContext::kMaxSessionSize)
1792
    return 0;
1793
1794
  // Serialize session
1795
578
  Local<Object> session = Buffer::New(env, size).ToLocalChecked();
1796
  unsigned char* session_data = reinterpret_cast<unsigned char*>(
1797
289
      Buffer::Data(session));
1798
289
  memset(session_data, 0, size);
1799
289
  i2d_SSL_SESSION(sess, &session_data);
1800
1801
  unsigned int session_id_length;
1802
  const unsigned char* session_id_data = SSL_SESSION_get_id(sess,
1803
289
                                                            &session_id_length);
1804
578
  Local<Object> session_id = Buffer::Copy(
1805
      env,
1806
      reinterpret_cast<const char*>(session_id_data),
1807
289
      session_id_length).ToLocalChecked();
1808
867
  Local<Value> argv[] = { session_id, session };
1809
  // On servers, we pause the handshake until callback of 'newSession', which
1810
  // calls NewSessionDoneCb(). On clients, there is no callback to wait for.
1811
289
  if (w->is_server())
1812
8
    w->awaiting_new_session_ = true;
1813
289
  w->MakeCallback(env->onnewsession_string(), arraysize(argv), argv);
1814
1815
289
  return 0;
1816
}
1817
1818
1819
template <class Base>
1820
32
void SSLWrap<Base>::KeylogCallback(const SSL* s, const char* line) {
1821
32
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
1822
32
  Environment* env = w->ssl_env();
1823
64
  HandleScope handle_scope(env->isolate());
1824
32
  Context::Scope context_scope(env->context());
1825
1826
32
  const size_t size = strlen(line);
1827
64
  Local<Value> line_bf = Buffer::Copy(env, line, 1 + size).ToLocalChecked();
1828
32
  char* data = Buffer::Data(line_bf);
1829
32
  data[size] = '\n';
1830
32
  w->MakeCallback(env->onkeylog_string(), 1, &line_bf);
1831
32
}
1832
1833
1834
template <class Base>
1835
20
void SSLWrap<Base>::OnClientHello(void* arg,
1836
                                  const ClientHelloParser::ClientHello& hello) {
1837
20
  Base* w = static_cast<Base*>(arg);
1838
20
  Environment* env = w->ssl_env();
1839
40
  HandleScope handle_scope(env->isolate());
1840
20
  Local<Context> context = env->context();
1841
  Context::Scope context_scope(context);
1842
1843
20
  Local<Object> hello_obj = Object::New(env->isolate());
1844
60
  Local<Object> buff = Buffer::Copy(
1845
      env,
1846
20
      reinterpret_cast<const char*>(hello.session_id()),
1847
40
      hello.session_size()).ToLocalChecked();
1848
60
  hello_obj->Set(context, env->session_id_string(), buff).Check();
1849
20
  if (hello.servername() == nullptr) {
1850
8
    hello_obj->Set(context,
1851
                   env->servername_string(),
1852
                   String::Empty(env->isolate())).Check();
1853
  } else {
1854
18
    Local<String> servername = OneByteString(env->isolate(),
1855
                                             hello.servername(),
1856
36
                                             hello.servername_size());
1857
54
    hello_obj->Set(context, env->servername_string(), servername).Check();
1858
  }
1859
80
  hello_obj->Set(context,
1860
                 env->tls_ticket_string(),
1861
20
                 Boolean::New(env->isolate(), hello.has_ticket())).Check();
1862
1863
40
  Local<Value> argv[] = { hello_obj };
1864
20
  w->MakeCallback(env->onclienthello_string(), arraysize(argv), argv);
1865
20
}
1866
1867
template <class Base>
1868
436
void SSLWrap<Base>::GetPeerCertificate(
1869
    const FunctionCallbackInfo<Value>& args) {
1870
  Base* w;
1871
436
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1872
436
  Environment* env = w->ssl_env();
1873
1874

1308
  bool abbreviated = args.Length() < 1 || !args[0]->IsTrue();
1875
1876
  Local<Value> ret;
1877
872
  if (GetPeerCert(env, w->ssl_, abbreviated, w->is_server()).ToLocal(&ret))
1878
872
    args.GetReturnValue().Set(ret);
1879
}
1880
1881
1882
template <class Base>
1883
12
void SSLWrap<Base>::GetCertificate(
1884
    const FunctionCallbackInfo<Value>& args) {
1885
  Base* w;
1886
12
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1887
12
  Environment* env = w->ssl_env();
1888
1889
  Local<Value> ret;
1890
24
  if (GetCert(env, w->ssl_).ToLocal(&ret))
1891
24
    args.GetReturnValue().Set(ret);
1892
}
1893
1894
1895
template <class Base>
1896
3
void SSLWrap<Base>::GetFinished(const FunctionCallbackInfo<Value>& args) {
1897
3
  Environment* env = Environment::GetCurrent(args);
1898
1899
  Base* w;
1900
4
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1901
1902
  // We cannot just pass nullptr to SSL_get_finished()
1903
  // because it would further be propagated to memcpy(),
1904
  // where the standard requirements as described in ISO/IEC 9899:2011
1905
  // sections 7.21.2.1, 7.21.1.2, and 7.1.4, would be violated.
1906
  // Thus, we use a dummy byte.
1907
  char dummy[1];
1908
3
  size_t len = SSL_get_finished(w->ssl_.get(), dummy, sizeof dummy);
1909
3
  if (len == 0)
1910
1
    return;
1911
1912
4
  AllocatedBuffer buf = AllocatedBuffer::AllocateManaged(env, len);
1913
2
  CHECK_EQ(len, SSL_get_finished(w->ssl_.get(), buf.data(), len));
1914
6
  args.GetReturnValue().Set(buf.ToBuffer().ToLocalChecked());
1915
}
1916
1917
1918
template <class Base>
1919
3
void SSLWrap<Base>::GetPeerFinished(const FunctionCallbackInfo<Value>& args) {
1920
3
  Environment* env = Environment::GetCurrent(args);
1921
1922
  Base* w;
1923
4
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1924
1925
  // We cannot just pass nullptr to SSL_get_peer_finished()
1926
  // because it would further be propagated to memcpy(),
1927
  // where the standard requirements as described in ISO/IEC 9899:2011
1928
  // sections 7.21.2.1, 7.21.1.2, and 7.1.4, would be violated.
1929
  // Thus, we use a dummy byte.
1930
  char dummy[1];
1931
3
  size_t len = SSL_get_peer_finished(w->ssl_.get(), dummy, sizeof dummy);
1932
3
  if (len == 0)
1933
1
    return;
1934
1935
4
  AllocatedBuffer buf = AllocatedBuffer::AllocateManaged(env, len);
1936
2
  CHECK_EQ(len, SSL_get_peer_finished(w->ssl_.get(), buf.data(), len));
1937
6
  args.GetReturnValue().Set(buf.ToBuffer().ToLocalChecked());
1938
}
1939
1940
1941
template <class Base>
1942
19
void SSLWrap<Base>::GetSession(const FunctionCallbackInfo<Value>& args) {
1943
19
  Environment* env = Environment::GetCurrent(args);
1944
1945
  Base* w;
1946
19
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1947
1948
19
  SSL_SESSION* sess = SSL_get_session(w->ssl_.get());
1949
19
  if (sess == nullptr)
1950
    return;
1951
1952
19
  int slen = i2d_SSL_SESSION(sess, nullptr);
1953
19
  if (slen <= 0)
1954
    return;  // Invalid or malformed session.
1955
1956
38
  AllocatedBuffer sbuf = AllocatedBuffer::AllocateManaged(env, slen);
1957
19
  unsigned char* p = reinterpret_cast<unsigned char*>(sbuf.data());
1958
19
  CHECK_LT(0, i2d_SSL_SESSION(sess, &p));
1959
57
  args.GetReturnValue().Set(sbuf.ToBuffer().ToLocalChecked());
1960
}
1961
1962
1963
template <class Base>
1964
114
void SSLWrap<Base>::SetSession(const FunctionCallbackInfo<Value>& args) {
1965
114
  Environment* env = Environment::GetCurrent(args);
1966
1967
  Base* w;
1968
114
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1969
1970
114
  if (args.Length() < 1)
1971
    return THROW_ERR_MISSING_ARGS(env, "Session argument is mandatory");
1972
1973
114
  THROW_AND_RETURN_IF_NOT_BUFFER(env, args[0], "Session");
1974
1975
228
  SSLSessionPointer sess = GetTLSSession(args[0]);
1976
114
  if (sess == nullptr)
1977
    return;
1978
1979
114
  if (!SetTLSSession(w->ssl_, sess))
1980
    return env->ThrowError("SSL_set_session error");
1981
}
1982
1983
1984
template <class Base>
1985
10
void SSLWrap<Base>::LoadSession(const FunctionCallbackInfo<Value>& args) {
1986
  Base* w;
1987
10
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1988
1989
  // TODO(@sam-github) check arg length and types in js, and CHECK in c++
1990

20
  if (args.Length() >= 1 && Buffer::HasInstance(args[0])) {
1991
10
    ArrayBufferViewContents<unsigned char> sbuf(args[0]);
1992
1993
10
    const unsigned char* p = sbuf.data();
1994
10
    SSL_SESSION* sess = d2i_SSL_SESSION(nullptr, &p, sbuf.length());
1995
1996
    // Setup next session and move hello to the BIO buffer
1997
10
    w->next_sess_.reset(sess);
1998
  }
1999
}
2000
2001
2002
template <class Base>
2003
469
void SSLWrap<Base>::IsSessionReused(const FunctionCallbackInfo<Value>& args) {
2004
  Base* w;
2005
469
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2006
469
  bool yes = SSL_session_reused(w->ssl_.get());
2007
1407
  args.GetReturnValue().Set(yes);
2008
}
2009
2010
2011
template <class Base>
2012
19
void SSLWrap<Base>::EndParser(const FunctionCallbackInfo<Value>& args) {
2013
  Base* w;
2014
19
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2015
19
  w->hello_parser_.End();
2016
}
2017
2018
2019
template <class Base>
2020
92
void SSLWrap<Base>::Renegotiate(const FunctionCallbackInfo<Value>& args) {
2021
  Base* w;
2022
93
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2023
2024
91
  ClearErrorOnReturn clear_error_on_return;
2025
2026
92
  if (SSL_renegotiate(w->ssl_.get()) != 1) {
2027
1
    return ThrowCryptoError(w->ssl_env(), ERR_get_error());
2028
  }
2029
}
2030
2031
2032
template <class Base>
2033
18
void SSLWrap<Base>::GetTLSTicket(const FunctionCallbackInfo<Value>& args) {
2034
  Base* w;
2035
18
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2036
18
  Environment* env = w->ssl_env();
2037
2038
18
  SSL_SESSION* sess = SSL_get_session(w->ssl_.get());
2039
18
  if (sess == nullptr)
2040
    return;
2041
2042
  const unsigned char* ticket;
2043
  size_t length;
2044
18
  SSL_SESSION_get0_ticket(sess, &ticket, &length);
2045
2046
18
  if (ticket == nullptr)
2047
    return;
2048
2049
36
  Local<Object> buff = Buffer::Copy(
2050
18
      env, reinterpret_cast<const char*>(ticket), length).ToLocalChecked();
2051
2052
36
  args.GetReturnValue().Set(buff);
2053
}
2054
2055
2056
template <class Base>
2057
8
void SSLWrap<Base>::NewSessionDone(const FunctionCallbackInfo<Value>& args) {
2058
  Base* w;
2059
8
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2060
8
  w->awaiting_new_session_ = false;
2061
8
  w->NewSessionDoneCb();
2062
}
2063
2064
2065
template <class Base>
2066
2
void SSLWrap<Base>::SetOCSPResponse(const FunctionCallbackInfo<Value>& args) {
2067
  Base* w;
2068
2
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2069
2
  Environment* env = w->env();
2070
2071
2
  if (args.Length() < 1)
2072
    return THROW_ERR_MISSING_ARGS(env, "OCSP response argument is mandatory");
2073
2074
2
  THROW_AND_RETURN_IF_NOT_BUFFER(env, args[0], "OCSP response");
2075
2076
8
  w->ocsp_response_.Reset(args.GetIsolate(), args[0].As<ArrayBufferView>());
2077
}
2078
2079
2080
template <class Base>
2081
4
void SSLWrap<Base>::RequestOCSP(const FunctionCallbackInfo<Value>& args) {
2082
  Base* w;
2083
4
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2084
2085
4
  SSL_set_tlsext_status_type(w->ssl_.get(), TLSEXT_STATUSTYPE_ocsp);
2086
}
2087
2088
2089
template <class Base>
2090
810
void SSLWrap<Base>::GetEphemeralKeyInfo(
2091
    const FunctionCallbackInfo<Value>& args) {
2092
  Base* w;
2093
817
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2094
810
  Environment* env = Environment::GetCurrent(args);
2095
2096
810
  CHECK(w->ssl_);
2097
2098
  // tmp key is available on only client
2099
810
  if (w->is_server())
2100
14
    return args.GetReturnValue().SetNull();
2101
2102
  Local<Object> ret;
2103
1606
  if (GetEphemeralKey(env, w->ssl_).ToLocal(&ret))
2104
1606
    args.GetReturnValue().Set(ret);
2105
2106
  // TODO(@sam-github) semver-major: else return ThrowCryptoError(env,
2107
  // ERR_get_error())
2108
}
2109
2110
template <class Base>
2111
3
void SSLWrap<Base>::SetMaxSendFragment(
2112
    const FunctionCallbackInfo<Value>& args) {
2113

9
  CHECK(args.Length() >= 1 && args[0]->IsNumber());
2114
2115
  Base* w;
2116
3
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2117
2118
12
  int rv = SSL_set_max_send_fragment(
2119
      w->ssl_.get(),
2120
      args[0]->Int32Value(w->ssl_env()->context()).FromJust());
2121
6
  args.GetReturnValue().Set(rv);
2122
}
2123
2124
2125
template <class Base>
2126
873
void SSLWrap<Base>::VerifyError(const FunctionCallbackInfo<Value>& args) {
2127
  Base* w;
2128
1332
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2129
2130
  // XXX(bnoordhuis) The UNABLE_TO_GET_ISSUER_CERT error when there is no
2131
  // peer certificate is questionable but it's compatible with what was
2132
  // here before.
2133
  long x509_verify_error =  // NOLINT(runtime/int)
2134
873
      VerifyPeerCertificate(w->ssl_, X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT);
2135
2136
873
  if (x509_verify_error == X509_V_OK)
2137
918
    return args.GetReturnValue().SetNull();
2138
2139
414
  const char* reason = X509_verify_cert_error_string(x509_verify_error);
2140
414
  const char* code = reason;
2141
414
  code = X509ErrorCode(x509_verify_error);
2142
2143
414
  Isolate* isolate = args.GetIsolate();
2144
414
  Local<String> reason_string = OneByteString(isolate, reason);
2145
414
  Local<Value> exception_value = Exception::Error(reason_string);
2146
  Local<Object> exception_object =
2147
1242
    exception_value->ToObject(isolate->GetCurrentContext()).ToLocalChecked();
2148
  exception_object->Set(w->env()->context(), w->env()->code_string(),
2149
2070
                        OneByteString(isolate, code)).Check();
2150
828
  args.GetReturnValue().Set(exception_object);
2151
}
2152
2153
2154
template <class Base>
2155
49
void SSLWrap<Base>::GetCipher(const FunctionCallbackInfo<Value>& args) {
2156
  Base* w;
2157
49
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2158
49
  Environment* env = w->ssl_env();
2159
2160
49
  const SSL_CIPHER* c = SSL_get_current_cipher(w->ssl_.get());
2161
49
  if (c == nullptr)
2162
    return;
2163
2164
  Local<Object> ret;
2165
98
  if (GetCipherInfo(env, w->ssl_).ToLocal(&ret))
2166
98
    args.GetReturnValue().Set(ret);
2167
}
2168
2169
2170
template <class Base>
2171
2
void SSLWrap<Base>::GetSharedSigalgs(const FunctionCallbackInfo<Value>& args) {
2172
  Base* w;
2173
2
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2174
2
  Environment* env = w->ssl_env();
2175
2176
2
  SSL* ssl = w->ssl_.get();
2177
  int nsig = SSL_get_shared_sigalgs(ssl, 0, nullptr, nullptr, nullptr, nullptr,
2178
2
                                    nullptr);
2179
4
  MaybeStackBuffer<Local<Value>, 16> ret_arr(nsig);
2180
2181
5
  for (int i = 0; i < nsig; i++) {
2182
    int hash_nid;
2183
    int sign_nid;
2184
6
    std::string sig_with_md;
2185
2186
3
    SSL_get_shared_sigalgs(ssl, i, &sign_nid, &hash_nid, nullptr, nullptr,
2187
                           nullptr);
2188
2189

3
    switch (sign_nid) {
2190
      case EVP_PKEY_RSA:
2191
        sig_with_md = "RSA+";
2192
        break;
2193
2194
      case EVP_PKEY_RSA_PSS:
2195
2
        sig_with_md = "RSA-PSS+";
2196
2
        break;
2197
2198
      case EVP_PKEY_DSA:
2199
        sig_with_md = "DSA+";
2200
        break;
2201
2202
      case EVP_PKEY_EC:
2203
1
        sig_with_md = "ECDSA+";
2204
1
        break;
2205
2206
      case NID_ED25519:
2207
        sig_with_md = "Ed25519+";
2208
        break;
2209
2210
      case NID_ED448:
2211
        sig_with_md = "Ed448+";
2212
        break;
2213
#ifndef OPENSSL_NO_GOST
2214
      case NID_id_GostR3410_2001:
2215
        sig_with_md = "gost2001+";
2216
        break;
2217
2218
      case NID_id_GostR3410_2012_256:
2219
        sig_with_md = "gost2012_256+";
2220
        break;
2221
2222
      case NID_id_GostR3410_2012_512:
2223
        sig_with_md = "gost2012_512+";
2224
        break;
2225
#endif  // !OPENSSL_NO_GOST
2226
      default:
2227
        const char* sn = OBJ_nid2sn(sign_nid);
2228
2229
        if (sn != nullptr) {
2230
          sig_with_md = std::string(sn) + "+";
2231
        } else {
2232
          sig_with_md = "UNDEF+";
2233
        }
2234
        break;
2235
    }
2236
2237
3
    const char* sn_hash = OBJ_nid2sn(hash_nid);
2238
3
    if (sn_hash != nullptr) {
2239
3
      sig_with_md += std::string(sn_hash);
2240
    } else {
2241
      sig_with_md += "UNDEF";
2242
    }
2243
6
    ret_arr[i] = OneByteString(env->isolate(), sig_with_md.c_str());
2244
  }
2245
2246
6
  args.GetReturnValue().Set(
2247
                 Array::New(env->isolate(), ret_arr.out(), ret_arr.length()));
2248
}
2249
2250
template <class Base>
2251
3
void SSLWrap<Base>::ExportKeyingMaterial(
2252
    const FunctionCallbackInfo<Value>& args) {
2253
6
  CHECK(args[0]->IsInt32());
2254
9
  CHECK(args[1]->IsString());
2255
2256
  Base* w;
2257
3
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2258
3
  Environment* env = w->ssl_env();
2259
2260
9
  uint32_t olen = args[0].As<Uint32>()->Value();
2261
6
  node::Utf8Value label(env->isolate(), args[1]);
2262
2263
6
  AllocatedBuffer out = AllocatedBuffer::AllocateManaged(env, olen);
2264
2265
6
  ByteSource context;
2266
9
  bool use_context = !args[2]->IsUndefined();
2267
3
  if (use_context)
2268
2
    context = ByteSource::FromBuffer(args[2]);
2269
2270
12
  if (SSL_export_keying_material(w->ssl_.get(),
2271
3
                                 reinterpret_cast<unsigned char*>(out.data()),
2272
                                 olen,
2273
3
                                 *label,
2274
                                 label.length(),
2275
                                 reinterpret_cast<const unsigned char*>(
2276
3
                                     context.get()),
2277
                                 context.size(),
2278
                                 use_context) != 1) {
2279
    return ThrowCryptoError(env, ERR_get_error(), "SSL_export_keying_material");
2280
  }
2281
2282
9
  args.GetReturnValue().Set(out.ToBuffer().ToLocalChecked());
2283
}
2284
2285
template <class Base>
2286
547
void SSLWrap<Base>::GetProtocol(const FunctionCallbackInfo<Value>& args) {
2287
  Base* w;
2288
547
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2289
2290
547
  const char* tls_version = SSL_get_version(w->ssl_.get());
2291
1641
  args.GetReturnValue().Set(OneByteString(args.GetIsolate(), tls_version));
2292
}
2293
2294
2295
template <class Base>
2296
26
int SSLWrap<Base>::SelectALPNCallback(SSL* s,
2297
                                      const unsigned char** out,
2298
                                      unsigned char* outlen,
2299
                                      const unsigned char* in,
2300
                                      unsigned int inlen,
2301
                                      void* arg) {
2302
26
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2303
26
  Environment* env = w->env();
2304
52
  HandleScope handle_scope(env->isolate());
2305
26
  Context::Scope context_scope(env->context());
2306
2307
  Local<Value> alpn_buffer =
2308
52
      w->object()->GetPrivate(
2309
          env->context(),
2310
78
          env->alpn_buffer_private_symbol()).ToLocalChecked();
2311
26
  ArrayBufferViewContents<unsigned char> alpn_protos(alpn_buffer);
2312
26
  int status = SSL_select_next_proto(const_cast<unsigned char**>(out), outlen,
2313
26
                                     alpn_protos.data(), alpn_protos.length(),
2314
26
                                     in, inlen);
2315
  // According to 3.2. Protocol Selection of RFC7301, fatal
2316
  // no_application_protocol alert shall be sent but OpenSSL 1.0.2 does not
2317
  // support it yet. See
2318
  // https://rt.openssl.org/Ticket/Display.html?id=3463&user=guest&pass=guest
2319
  return status == OPENSSL_NPN_NEGOTIATED ? SSL_TLSEXT_ERR_OK
2320
52
                                          : SSL_TLSEXT_ERR_NOACK;
2321
}
2322
2323
2324
template <class Base>
2325
1623
void SSLWrap<Base>::GetALPNNegotiatedProto(
2326
    const FunctionCallbackInfo<Value>& args) {
2327
  Base* w;
2328
1623
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2329
2330
  const unsigned char* alpn_proto;
2331
  unsigned int alpn_proto_len;
2332
2333
1623
  SSL_get0_alpn_selected(w->ssl_.get(), &alpn_proto, &alpn_proto_len);
2334
2335
  Local<Value> result;
2336
1623
  if (alpn_proto_len == 0) {
2337
3150
    result = False(args.GetIsolate());
2338

90
  } else if (alpn_proto_len == sizeof("h2") - 1 &&
2339
42
             0 == memcmp(alpn_proto, "h2", sizeof("h2") - 1)) {
2340
84
    result = w->env()->h2_string();
2341

8
  } else if (alpn_proto_len == sizeof("http/1.1") - 1 &&
2342
2
             0 == memcmp(alpn_proto, "http/1.1", sizeof("http/1.1") - 1)) {
2343
4
    result = w->env()->http_1_1_string();
2344
  } else {
2345
12
    result = OneByteString(args.GetIsolate(), alpn_proto, alpn_proto_len);
2346
  }
2347
2348
3246
  args.GetReturnValue().Set(result);
2349
}
2350
2351
2352
template <class Base>
2353
205
void SSLWrap<Base>::SetALPNProtocols(const FunctionCallbackInfo<Value>& args) {
2354
  Base* w;
2355
205
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2356
205
  Environment* env = w->env();
2357

410
  if (args.Length() < 1 || !Buffer::HasInstance(args[0]))
2358
    return env->ThrowTypeError("Must give a Buffer as first argument");
2359
2360
205
  if (w->is_client()) {
2361
31
    CHECK(SetALPN(w->ssl_, args[0]));
2362
  } else {
2363
522
    CHECK(
2364
        w->object()->SetPrivate(
2365
            env->context(),
2366
            env->alpn_buffer_private_symbol(),
2367
            args[0]).FromJust());
2368
    // Server should select ALPN protocol from list of advertised by client
2369
174
    SSL_CTX_set_alpn_select_cb(SSL_get_SSL_CTX(w->ssl_.get()),
2370
                               SelectALPNCallback,
2371
                               nullptr);
2372
  }
2373
}
2374
2375
2376
template <class Base>
2377
8
int SSLWrap<Base>::TLSExtStatusCallback(SSL* s, void* arg) {
2378
8
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2379
8
  Environment* env = w->env();
2380
16
  HandleScope handle_scope(env->isolate());
2381
2382
8
  if (w->is_client()) {
2383
    // Incoming response
2384
    Local<Value> arg;
2385
8
    MaybeLocal<Value> ret = GetSSLOCSPResponse(env, s, Null(env->isolate()));
2386
4
    if (ret.ToLocal(&arg))
2387
4
      w->MakeCallback(env->onocspresponse_string(), 1, &arg);
2388
2389
    // No async acceptance is possible, so always return 1 to accept the
2390
    // response.  The listener for 'OCSPResponse' event has no control over
2391
    // return value, but it can .destroy() the connection if the response is not
2392
    // acceptable.
2393
4
    return 1;
2394
  } else {
2395
    // Outgoing response
2396
8
    if (w->ocsp_response_.IsEmpty())
2397
2
      return SSL_TLSEXT_ERR_NOACK;
2398
2399
2
    Local<ArrayBufferView> obj = PersistentToLocal::Default(env->isolate(),
2400
2
                                                            w->ocsp_response_);
2401
2
    size_t len = obj->ByteLength();
2402
2403
    // OpenSSL takes control of the pointer after accepting it
2404
2
    unsigned char* data = MallocOpenSSL<unsigned char>(len);
2405
2
    obj->CopyContents(data, len);
2406
2407
2
    if (!SSL_set_tlsext_status_ocsp_resp(s, data, len))
2408
      OPENSSL_free(data);
2409
2
    w->ocsp_response_.Reset();
2410
2411
2
    return SSL_TLSEXT_ERR_OK;
2412
  }
2413
}
2414
2415
2416
template <class Base>
2417
22
void SSLWrap<Base>::WaitForCertCb(CertCb cb, void* arg) {
2418
22
  cert_cb_ = cb;
2419
22
  cert_cb_arg_ = arg;
2420
22
}
2421
2422
2423
template <class Base>
2424
880
int SSLWrap<Base>::SSLCertCallback(SSL* s, void* arg) {
2425
880
  Base* w = static_cast<Base*>(SSL_get_app_data(s));
2426
2427
880
  if (!w->is_server())
2428
41
    return 1;
2429
2430
839
  if (!w->is_waiting_cert_cb())
2431
817
    return 1;
2432
2433
22
  if (w->cert_cb_running_)
2434
    // Not an error. Suspend handshake with SSL_ERROR_WANT_X509_LOOKUP, and
2435
    // handshake will continue after certcb is done.
2436
    return -1;
2437
2438
22
  Environment* env = w->env();
2439
22
  Local<Context> context = env->context();
2440
44
  HandleScope handle_scope(env->isolate());
2441
  Context::Scope context_scope(context);
2442
22
  w->cert_cb_running_ = true;
2443
2444
22
  Local<Object> info = Object::New(env->isolate());
2445
2446
22
  const char* servername = GetServerName(s);
2447
22
  if (servername == nullptr) {
2448
16
    info->Set(context,
2449
              env->servername_string(),
2450
              String::Empty(env->isolate())).Check();
2451
  } else {
2452
18
    Local<String> str = OneByteString(env->isolate(), servername,
2453
36
                                      strlen(servername));
2454
54
    info->Set(context, env->servername_string(), str).Check();
2455
  }
2456
2457
22
  const bool ocsp = (SSL_get_tlsext_status_type(s) == TLSEXT_STATUSTYPE_ocsp);
2458
88
  info->Set(context, env->ocsp_request_string(),
2459
            Boolean::New(env->isolate(), ocsp)).Check();
2460
2461
44
  Local<Value> argv[] = { info };
2462
22
  w->MakeCallback(env->oncertcb_string(), arraysize(argv), argv);
2463
2464
22
  if (!w->cert_cb_running_)
2465
10
    return 1;
2466
2467
  // Performing async action, wait...
2468
12
  return -1;
2469
}
2470
2471
2472
template <class Base>
2473
19
void SSLWrap<Base>::CertCbDone(const FunctionCallbackInfo<Value>& args) {
2474
  Base* w;
2475
21
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2476
19
  Environment* env = w->env();
2477
2478

19
  CHECK(w->is_waiting_cert_cb() && w->cert_cb_running_);
2479
2480
19
  Local<Object> object = w->object();
2481
76
  Local<Value> ctx = object->Get(env->context(),
2482
19
                                 env->sni_context_string()).ToLocalChecked();
2483
19
  Local<FunctionTemplate> cons = env->secure_context_constructor_template();
2484
2485
19
  if (cons->HasInstance(ctx)) {
2486
9
    SecureContext* sc = Unwrap<SecureContext>(ctx.As<Object>());
2487
9
    CHECK_NOT_NULL(sc);
2488
    // Store the SNI context for later use.
2489
9
    w->sni_context_ = BaseObjectPtr<SecureContext>(sc);
2490
2491


9
    if (UseSNIContext(w->ssl_, w->sni_context_) && !w->SetCACerts(sc)) {
2492
      // Not clear why sometimes we throw error, and sometimes we call
2493
      // onerror(). Both cause .destroy(), but onerror does a bit more.
2494
      unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
2495
      return ThrowCryptoError(env, err, "CertCbDone");
2496
    }
2497
10
  } else if (ctx->IsObject()) {
2498
    // Failure: incorrect SNI context object
2499
2
    Local<Value> err = Exception::TypeError(env->sni_context_err_string());
2500
2
    w->MakeCallback(env->onerror_string(), 1, &err);
2501
2
    return;
2502
  }
2503
2504
  CertCb cb;
2505
  void* arg;
2506
2507
17
  cb = w->cert_cb_;
2508
17
  arg = w->cert_cb_arg_;
2509
2510
17
  w->cert_cb_running_ = false;
2511
17
  w->cert_cb_ = nullptr;
2512
17
  w->cert_cb_arg_ = nullptr;
2513
2514
17
  cb(arg);
2515
}
2516
2517
2518
template <class Base>
2519
24273
void SSLWrap<Base>::DestroySSL() {
2520
24273
  if (!ssl_)
2521
12101
    return;
2522
2523
12172
  env_->isolate()->AdjustAmountOfExternalAllocatedMemory(-kExternalSize);
2524
12172
  ssl_.reset();
2525
}
2526
2527
2528
template <class Base>
2529
8
int SSLWrap<Base>::SetCACerts(SecureContext* sc) {
2530
8
  int err = SSL_set1_verify_cert_store(ssl_.get(),
2531
                                       SSL_CTX_get_cert_store(sc->ctx_.get()));
2532
8
  if (err != 1)
2533
    return err;
2534
2535
  STACK_OF(X509_NAME)* list = SSL_dup_CA_list(
2536
8
      SSL_CTX_get_client_CA_list(sc->ctx_.get()));
2537
2538
  // NOTE: `SSL_set_client_CA_list` takes the ownership of `list`
2539
8
  SSL_set_client_CA_list(ssl_.get(), list);
2540
8
  return 1;
2541
}
2542
2543
template <class Base>
2544
void SSLWrap<Base>::MemoryInfo(MemoryTracker* tracker) const {
2545
  tracker->TrackField("ocsp_response", ocsp_response_);
2546
  tracker->TrackField("sni_context", sni_context_);
2547
}
2548
2549
1941
int VerifyCallback(int preverify_ok, X509_STORE_CTX* ctx) {
2550
  // From https://www.openssl.org/docs/man1.1.1/man3/SSL_verify_cb:
2551
  //
2552
  //   If VerifyCallback returns 1, the verification process is continued. If
2553
  //   VerifyCallback always returns 1, the TLS/SSL handshake will not be
2554
  //   terminated with respect to verification failures and the connection will
2555
  //   be established. The calling process can however retrieve the error code
2556
  //   of the last verification error using SSL_get_verify_result(3) or by
2557
  //   maintaining its own error storage managed by VerifyCallback.
2558
  //
2559
  // Since we cannot perform I/O quickly enough with X509_STORE_CTX_ APIs in
2560
  // this callback, we ignore all preverify_ok errors and let the handshake
2561
  // continue. It is imperative that the user use Connection::VerifyError after
2562
  // the 'secure' callback has been made.
2563
1941
  return 1;
2564
}
2565
2566
3474
static bool IsSupportedAuthenticatedMode(const EVP_CIPHER* cipher) {
2567
3474
  const int mode = EVP_CIPHER_mode(cipher);
2568
  // Check `chacha20-poly1305` separately, it is also an AEAD cipher,
2569
  // but its mode is 0 which doesn't indicate
2570
6901
  return EVP_CIPHER_nid(cipher) == NID_chacha20_poly1305 ||
2571
6202
         mode == EVP_CIPH_CCM_MODE ||
2572

7591
         mode == EVP_CIPH_GCM_MODE ||
2573
4816
         IS_OCB_MODE(mode);
2574
}
2575
2576
1538
static bool IsSupportedAuthenticatedMode(const EVP_CIPHER_CTX* ctx) {
2577
1538
  const EVP_CIPHER* cipher = EVP_CIPHER_CTX_cipher(ctx);
2578
1538
  return IsSupportedAuthenticatedMode(cipher);
2579
}
2580
2581
enum class ParseKeyResult {
2582
  kParseKeyOk,
2583
  kParseKeyNotRecognized,
2584
  kParseKeyNeedPassphrase,
2585
  kParseKeyFailed
2586
};
2587
2588
2927
static ParseKeyResult TryParsePublicKey(
2589
    EVPKeyPointer* pkey,
2590
    const BIOPointer& bp,
2591
    const char* name,
2592
    // NOLINTNEXTLINE(runtime/int)
2593
    const std::function<EVP_PKEY*(const unsigned char** p, long l)>& parse) {
2594
  unsigned char* der_data;
2595
  long der_len;  // NOLINT(runtime/int)
2596
2597
  // This skips surrounding data and decodes PEM to DER.
2598
  {
2599
3799
    MarkPopErrorOnReturn mark_pop_error_on_return;
2600
2927
    if (PEM_bytes_read_bio(&der_data, &der_len, nullptr, name,
2601
                           bp.get(), nullptr, nullptr) != 1)
2602
2055
      return ParseKeyResult::kParseKeyNotRecognized;
2603
  }
2604
2605
  // OpenSSL might modify the pointer, so we need to make a copy before parsing.
2606
872
  const unsigned char* p = der_data;
2607
872
  pkey->reset(parse(&p, der_len));
2608
872
  OPENSSL_clear_free(der_data, der_len);
2609
2610
872
  return *pkey ? ParseKeyResult::kParseKeyOk :
2611
1744
                 ParseKeyResult::kParseKeyFailed;
2612
}
2613
2614
1062
static ParseKeyResult ParsePublicKeyPEM(EVPKeyPointer* pkey,
2615
                                        const char* key_pem,
2616
                                        int key_pem_len) {
2617
2124
  BIOPointer bp(BIO_new_mem_buf(const_cast<char*>(key_pem), key_pem_len));
2618
1062
  if (!bp)
2619
    return ParseKeyResult::kParseKeyFailed;
2620
2621
  ParseKeyResult ret;
2622
2623
  // Try parsing as a SubjectPublicKeyInfo first.
2624
2124
  ret = TryParsePublicKey(pkey, bp, "PUBLIC KEY",
2625
122
      [](const unsigned char** p, long l) {  // NOLINT(runtime/int)
2626
        return d2i_PUBKEY(nullptr, p, l);
2627
1184
      });
2628
1062
  if (ret != ParseKeyResult::kParseKeyNotRecognized)
2629
122
    return ret;
2630
2631
  // Maybe it is PKCS#1.
2632
940
  CHECK(BIO_reset(bp.get()));
2633
1880
  ret = TryParsePublicKey(pkey, bp, "RSA PUBLIC KEY",
2634
15
      [](const unsigned char** p, long l) {  // NOLINT(runtime/int)
2635
        return d2i_PublicKey(EVP_PKEY_RSA, nullptr, p, l);
2636
955
      });
2637
940
  if (ret != ParseKeyResult::kParseKeyNotRecognized)
2638
15
    return ret;
2639
2640
  // X.509 fallback.
2641
925
  CHECK(BIO_reset(bp.get()));
2642
1850
  return TryParsePublicKey(pkey, bp, "CERTIFICATE",
2643
735
      [](const unsigned char** p, long l) {  // NOLINT(runtime/int)
2644
1470
        X509Pointer x509(d2i_X509(nullptr, p, l));
2645
1470
        return x509 ? X509_get_pubkey(x509.get()) : nullptr;
2646
925
      });
2647
}
2648
2649
22
static ParseKeyResult ParsePublicKey(EVPKeyPointer* pkey,
2650
                                     const PublicKeyEncodingConfig& config,
2651
                                     const char* key,
2652
                                     size_t key_len) {
2653
22
  if (config.format_ == kKeyFormatPEM) {
2654
    return ParsePublicKeyPEM(pkey, key, key_len);
2655
  } else {
2656
22
    CHECK_EQ(config.format_, kKeyFormatDER);
2657
2658
22
    const unsigned char* p = reinterpret_cast<const unsigned char*>(key);
2659
44
    if (config.type_.ToChecked() == kKeyEncodingPKCS1) {
2660
22
      pkey->reset(d2i_PublicKey(EVP_PKEY_RSA, nullptr, &p, key_len));
2661
    } else {
2662
      CHECK_EQ(config.type_.ToChecked(), kKeyEncodingSPKI);
2663
      pkey->reset(d2i_PUBKEY(nullptr, &p, key_len));
2664
    }
2665
2666
22
    return *pkey ? ParseKeyResult::kParseKeyOk :
2667
44
                   ParseKeyResult::kParseKeyFailed;
2668
  }
2669
}
2670
2671
57
static inline Local<Value> BIOToStringOrBuffer(Environment* env,
2672
                                               BIO* bio,
2673
                                               PKFormatType format) {
2674
  BUF_MEM* bptr;
2675
57
  BIO_get_mem_ptr(bio, &bptr);
2676
57
  if (format == kKeyFormatPEM) {
2677
    // PEM is an ASCII format, so we will return it as a string.
2678
141
    return String::NewFromUtf8(env->isolate(), bptr->data,
2679
                               NewStringType::kNormal,
2680
141
                               bptr->length).ToLocalChecked();
2681
  } else {
2682
10
    CHECK_EQ(format, kKeyFormatDER);
2683
    // DER is binary, return it as a buffer.
2684
20
    return Buffer::Copy(env, bptr->data, bptr->length).ToLocalChecked();
2685
  }
2686
}
2687
2688
30
static bool WritePublicKeyInner(EVP_PKEY* pkey,
2689
                                const BIOPointer& bio,
2690
                                const PublicKeyEncodingConfig& config) {
2691
60
  if (config.type_.ToChecked() == kKeyEncodingPKCS1) {
2692
    // PKCS#1 is only valid for RSA keys.
2693
13
    CHECK_EQ(EVP_PKEY_id(pkey), EVP_PKEY_RSA);
2694
26
    RSAPointer rsa(EVP_PKEY_get1_RSA(pkey));
2695
13
    if (config.format_ == kKeyFormatPEM) {
2696
      // Encode PKCS#1 as PEM.
2697
7
      return PEM_write_bio_RSAPublicKey(bio.get(), rsa.get()) == 1;
2698
    } else {
2699
      // Encode PKCS#1 as DER.
2700
6
      CHECK_EQ(config.format_, kKeyFormatDER);
2701
6
      return i2d_RSAPublicKey_bio(bio.get(), rsa.get()) == 1;
2702
    }
2703
  } else {
2704
34
    CHECK_EQ(config.type_.ToChecked(), kKeyEncodingSPKI);
2705
17
    if (config.format_ == kKeyFormatPEM) {
2706
      // Encode SPKI as PEM.
2707
17
      return PEM_write_bio_PUBKEY(bio.get(), pkey) == 1;
2708
    } else {
2709
      // Encode SPKI as DER.
2710
      CHECK_EQ(config.format_, kKeyFormatDER);
2711
      return i2d_PUBKEY_bio(bio.get(), pkey) == 1;
2712
    }
2713
  }
2714
}
2715
2716
30
static MaybeLocal<Value> WritePublicKey(Environment* env,
2717
                                        EVP_PKEY* pkey,
2718
                                        const PublicKeyEncodingConfig& config) {
2719
60
  BIOPointer bio(BIO_new(BIO_s_mem()));
2720
30
  CHECK(bio);
2721
2722
30
  if (!WritePublicKeyInner(pkey, bio, config)) {
2723
    ThrowCryptoError(env, ERR_get_error(), "Failed to encode public key");
2724
    return MaybeLocal<Value>();
2725
  }
2726
60
  return BIOToStringOrBuffer(env, bio.get(), config.format_);
2727
}
2728
2729
58
static bool IsASN1Sequence(const unsigned char* data, size_t size,
2730
                           size_t* data_offset, size_t* data_size) {
2731

58
  if (size < 2 || data[0] != 0x30)
2732
    return false;
2733
2734
58
  if (data[1] & 0x80) {
2735
    // Long form.
2736
38
    size_t n_bytes = data[1] & ~0x80;
2737

38
    if (n_bytes + 2 > size || n_bytes > sizeof(size_t))
2738
      return false;
2739
38
    size_t length = 0;
2740
114
    for (size_t i = 0; i < n_bytes; i++)
2741
76
      length = (length << 8) | data[i + 2];
2742
38
    *data_offset = 2 + n_bytes;
2743
38
    *data_size = std::min(size - 2 - n_bytes, length);
2744
  } else {
2745
    // Short form.
2746
20
    *data_offset = 2;
2747
20
    *data_size = std::min<size_t>(size - 2, data[1]);
2748
  }
2749
2750
58
  return true;
2751
}
2752
2753
32
static bool IsRSAPrivateKey(const unsigned char* data, size_t size) {
2754
  // Both RSAPrivateKey and RSAPublicKey structures start with a SEQUENCE.
2755
  size_t offset, len;
2756
32
  if (!IsASN1Sequence(data, size, &offset, &len))
2757
    return false;
2758
2759
  // An RSAPrivateKey sequence always starts with a single-byte integer whose
2760
  // value is either 0 or 1, whereas an RSAPublicKey starts with the modulus
2761
  // (which is the product of two primes and therefore at least 4), so we can
2762
  // decide the type of the structure based on the first three bytes of the
2763
  // sequence.
2764
64
  return len >= 3 &&
2765
64
         data[offset] == 2 &&
2766

74
         data[offset + 1] == 1 &&
2767
42
         !(data[offset + 2] & 0xfe);
2768
}
2769
2770
26
static bool IsEncryptedPrivateKeyInfo(const unsigned char* data, size_t size) {
2771
  // Both PrivateKeyInfo and EncryptedPrivateKeyInfo start with a SEQUENCE.
2772
  size_t offset, len;
2773
26
  if (!IsASN1Sequence(data, size, &offset, &len))
2774
    return false;
2775
2776
  // A PrivateKeyInfo sequence always starts with an integer whereas an
2777
  // EncryptedPrivateKeyInfo starts with an AlgorithmIdentifier.
2778

52
  return len >= 1 &&
2779
52
         data[offset] != 2;
2780
}
2781
2782
398
static ParseKeyResult ParsePrivateKey(EVPKeyPointer* pkey,
2783
                                      const PrivateKeyEncodingConfig& config,
2784
                                      const char* key,
2785
                                      size_t key_len) {
2786
  // OpenSSL needs a non-const pointer, that's why the const_cast is required.
2787
398
  char* const passphrase = const_cast<char*>(config.passphrase_.get());
2788
2789
398
  if (config.format_ == kKeyFormatPEM) {
2790
721
    BIOPointer bio(BIO_new_mem_buf(key, key_len));
2791
361
    if (!bio)
2792
1
      return ParseKeyResult::kParseKeyFailed;
2793
2794
360
    pkey->reset(PEM_read_bio_PrivateKey(bio.get(),
2795
                                        nullptr,
2796
                                        PasswordCallback,
2797
360
                                        passphrase));
2798
  } else {
2799
37
    CHECK_EQ(config.format_, kKeyFormatDER);
2800
2801
74
    if (config.type_.ToChecked() == kKeyEncodingPKCS1) {
2802
11
      const unsigned char* p = reinterpret_cast<const unsigned char*>(key);
2803
11
      pkey->reset(d2i_PrivateKey(EVP_PKEY_RSA, nullptr, &p, key_len));
2804
52
    } else if (config.type_.ToChecked() == kKeyEncodingPKCS8) {
2805
52
      BIOPointer bio(BIO_new_mem_buf(key, key_len));
2806
26
      if (!bio)
2807
        return ParseKeyResult::kParseKeyFailed;
2808
2809
26
      if (IsEncryptedPrivateKeyInfo(
2810
              reinterpret_cast<const unsigned char*>(key), key_len)) {
2811
17
        pkey->reset(d2i_PKCS8PrivateKey_bio(bio.get(),
2812
                                            nullptr,
2813
                                            PasswordCallback,
2814
17
                                            passphrase));
2815
      } else {
2816
18
        PKCS8Pointer p8inf(d2i_PKCS8_PRIV_KEY_INFO_bio(bio.get(), nullptr));
2817
9
        if (p8inf)
2818
9
          pkey->reset(EVP_PKCS82PKEY(p8inf.get()));
2819
      }
2820
    } else {
2821
      CHECK_EQ(config.type_.ToChecked(), kKeyEncodingSEC1);
2822
      const unsigned char* p = reinterpret_cast<const unsigned char*>(key);
2823
      pkey->reset(d2i_PrivateKey(EVP_PKEY_EC, nullptr, &p, key_len));
2824
    }
2825
  }
2826
2827
  // OpenSSL can fail to parse the key but still return a non-null pointer.
2828
397
  unsigned long err = ERR_peek_error();  // NOLINT(runtime/int)
2829
397
  if (err != 0)
2830
19
    pkey->reset();
2831
2832
397
  if (*pkey)
2833
378
    return ParseKeyResult::kParseKeyOk;
2834

30
  if (ERR_GET_LIB(err) == ERR_LIB_PEM &&
2835
11
      ERR_GET_REASON(err) == PEM_R_BAD_PASSWORD_READ) {
2836
10
    if (config.passphrase_.get() == nullptr)
2837
9
      return ParseKeyResult::kParseKeyNeedPassphrase;
2838
  }
2839
10
  return ParseKeyResult::kParseKeyFailed;
2840
}
2841
2842
2507
ByteSource::ByteSource(ByteSource&& other)
2843
2507
      : data_(other.data_),
2844
2507
        allocated_data_(other.allocated_data_),
2845
5014
        size_(other.size_) {
2846
2507
  other.allocated_data_ = nullptr;
2847
2507
}
2848
2849
15340
ByteSource::~ByteSource() {
2850
7670
  OPENSSL_clear_free(allocated_data_, size_);
2851
7670
}
2852
2853
109
ByteSource& ByteSource::operator=(ByteSource&& other) {
2854
109
  if (&other != this) {
2855
109
    OPENSSL_clear_free(allocated_data_, size_);
2856
109
    data_ = other.data_;
2857
109
    allocated_data_ = other.allocated_data_;
2858
109
    other.allocated_data_ = nullptr;
2859
109
    size_ = other.size_;
2860
  }
2861
109
  return *this;
2862
}
2863
2864
4351
const char* ByteSource::get() const {
2865
4351
  return data_;
2866
}
2867
2868
3939
size_t ByteSource::size() const {
2869
3939
  return size_;
2870
}
2871
2872
2625
ByteSource ByteSource::FromStringOrBuffer(Environment* env,
2873
                                          Local<Value> value) {
2874
2625
  return Buffer::HasInstance(value) ? FromBuffer(value)
2875
3011
                                    : FromString(env, value.As<String>());
2876
}
2877
2878
461
ByteSource ByteSource::FromString(Environment* env, Local<String> str,
2879
                                  bool ntc) {
2880
922
  CHECK(str->IsString());
2881
922
  size_t size = str->Utf8Length(env->isolate());
2882
461
  size_t alloc_size = ntc ? size + 1 : size;
2883
461
  char* data = MallocOpenSSL<char>(alloc_size);
2884
461
  int opts = String::NO_OPTIONS;
2885
461
  if (!ntc) opts |= String::NO_NULL_TERMINATION;
2886
922
  str->WriteUtf8(env->isolate(), data, alloc_size, nullptr, opts);
2887
461
  return Allocated(data, size);
2888
}
2889
2890
2252
ByteSource ByteSource::FromBuffer(Local<Value> buffer, bool ntc) {
2891
2252
  CHECK(buffer->IsArrayBufferView());
2892
2252
  Local<ArrayBufferView> abv = buffer.As<ArrayBufferView>();
2893
2252
  size_t size = abv->ByteLength();
2894
2252
  if (ntc) {
2895
11
    char* data = MallocOpenSSL<char>(size + 1);
2896
11
    abv->CopyContents(data, size);
2897
11
    data[size] = 0;
2898
11
    return Allocated(data, size);
2899
  }
2900
2241
  return Foreign(Buffer::Data(buffer), size);
2901
}
2902
2903
86
ByteSource ByteSource::NullTerminatedCopy(Environment* env,
2904
                                          Local<Value> value) {
2905
86
  return Buffer::HasInstance(value) ? FromBuffer(value, true)
2906
161
                                    : FromString(env, value.As<String>(), true);
2907
}
2908
2909
14
ByteSource ByteSource::FromSymmetricKeyObjectHandle(Local<Value> handle) {
2910
14
  CHECK(handle->IsObject());
2911
14
  KeyObjectHandle* key = Unwrap<KeyObjectHandle>(handle.As<Object>());
2912
14
  CHECK_NOT_NULL(key);
2913
14
  return Foreign(key->Data()->GetSymmetricKey(),
2914
28
                 key->Data()->GetSymmetricKeySize());
2915
}
2916
2917
3797
ByteSource::ByteSource(const char* data, char* allocated_data, size_t size)
2918
      : data_(data),
2919
        allocated_data_(allocated_data),
2920
3797
        size_(size) {}
2921
2922
480
ByteSource ByteSource::Allocated(char* data, size_t size) {
2923
480
  return ByteSource(data, data, size);
2924
}
2925
2926
3317
ByteSource ByteSource::Foreign(const char* data, size_t size) {
2927
3317
  return ByteSource(data, nullptr, size);
2928
}
2929
2930
enum KeyEncodingContext {
2931
  kKeyContextInput,
2932
  kKeyContextExport,
2933
  kKeyContextGenerate
2934
};
2935
2936
1411
static void GetKeyFormatAndTypeFromJs(
2937
    AsymmetricKeyEncodingConfig* config,
2938
    const FunctionCallbackInfo<Value>& args,
2939
    unsigned int* offset,
2940
    KeyEncodingContext context) {
2941
  // During key pair generation, it is possible not to specify a key encoding,
2942
  // which will lead to a key object being returned.
2943
5644
  if (args[*offset]->IsUndefined()) {
2944
60
    CHECK_EQ(context, kKeyContextGenerate);
2945
240
    CHECK(args[*offset + 1]->IsUndefined());
2946
60
    config->output_key_object_ = true;
2947
  } else {
2948
1351
    config->output_key_object_ = false;
2949
2950
4053
    CHECK(args[*offset]->IsInt32());
2951
1351
    config->format_ = static_cast<PKFormatType>(
2952
6755
        args[*offset].As<Int32>()->Value());
2953
2954
4053
    if (args[*offset + 1]->IsInt32()) {
2955
236
      config->type_ = Just<PKEncodingType>(static_cast<PKEncodingType>(
2956
708
          args[*offset + 1].As<Int32>()->Value()));
2957
    } else {
2958

1233
      CHECK(context == kKeyContextInput && config->format_ == kKeyFormatPEM);
2959
4932
      CHECK(args[*offset + 1]->IsNullOrUndefined());
2960
1233
      config->type_ = Nothing<PKEncodingType>();
2961
    }
2962
  }
2963
2964
1411
  *offset += 2;
2965
1411
}
2966
2967
61
static PublicKeyEncodingConfig GetPublicKeyEncodingFromJs(
2968
    const FunctionCallbackInfo<Value>& args,
2969
    unsigned int* offset,
2970
    KeyEncodingContext context) {
2971
61
  PublicKeyEncodingConfig result;
2972
61
  GetKeyFormatAndTypeFromJs(&result, args, offset, context);
2973
61
  return result;
2974
}
2975
2976
1292
static inline ManagedEVPPKey GetParsedKey(Environment* env,
2977
                                          EVPKeyPointer&& pkey,
2978
                                          ParseKeyResult ret,
2979
                                          const char* default_msg) {
2980
1292
  switch (ret) {
2981
    case ParseKeyResult::kParseKeyOk:
2982
1272
      CHECK(pkey);
2983
1272
      break;
2984
    case ParseKeyResult::kParseKeyNeedPassphrase:
2985
      THROW_ERR_MISSING_PASSPHRASE(env,
2986
9
                                   "Passphrase required for encrypted key");
2987
9
      break;
2988
    default:
2989
11
      ThrowCryptoError(env, ERR_get_error(), default_msg);
2990
  }
2991
2992
1292
  return ManagedEVPPKey(std::move(pkey));
2993
}
2994
2995
1350
static NonCopyableMaybe<PrivateKeyEncodingConfig> GetPrivateKeyEncodingFromJs(
2996
    const FunctionCallbackInfo<Value>& args,
2997
    unsigned int* offset,
2998
    KeyEncodingContext context) {
2999
1350
  Environment* env = Environment::GetCurrent(args);
3000
3001
2700
  PrivateKeyEncodingConfig result;
3002
1350
  GetKeyFormatAndTypeFromJs(&result, args, offset, context);
3003
3004
1350
  if (result.output_key_object_) {
3005
30
    if (context != kKeyContextInput)
3006
30
      (*offset)++;
3007
  } else {
3008
1320
    bool needs_passphrase = false;
3009
1320
    if (context != kKeyContextInput) {
3010
112
      if (args[*offset]->IsString()) {
3011
        String::Utf8Value cipher_name(env->isolate(),
3012
35
                                      args[*offset].As<String>());
3013
9
        result.cipher_ = EVP_get_cipherbyname(*cipher_name);
3014
9
        if (result.cipher_ == nullptr) {
3015
1
          THROW_ERR_CRYPTO_UNKNOWN_CIPHER(env);
3016
1
          return NonCopyableMaybe<PrivateKeyEncodingConfig>();
3017
        }
3018
8
        needs_passphrase = true;
3019
      } else {
3020
76
        CHECK(args[*offset]->IsNullOrUndefined());
3021
19
        result.cipher_ = nullptr;
3022
      }
3023
27
      (*offset)++;
3024
    }
3025
3026

6520
    if (args[*offset]->IsString() || Buffer::HasInstance(args[*offset])) {
3027

86
      CHECK_IMPLIES(context != kKeyContextInput, result.cipher_ != nullptr);
3028
3029
172
      result.passphrase_ = ByteSource::NullTerminatedCopy(env, args[*offset]);
3030
    } else {
3031

4932
      CHECK(args[*offset]->IsNullOrUndefined() && !needs_passphrase);
3032
    }
3033
  }
3034
3035
1349
  (*offset)++;
3036
1349
  return NonCopyableMaybe<PrivateKeyEncodingConfig>(std::move(result));
3037
}
3038
3039
213
static ManagedEVPPKey GetPrivateKeyFromJs(
3040
    const FunctionCallbackInfo<Value>& args,
3041
    unsigned int* offset,
3042
    bool allow_key_object) {
3043

986
  if (args[*offset]->IsString() || Buffer::HasInstance(args[*offset])) {
3044
180
    Environment* env = Environment::GetCurrent(args);
3045
540
    ByteSource key = ByteSource::FromStringOrBuffer(env, args[(*offset)++]);
3046
    NonCopyableMaybe<PrivateKeyEncodingConfig> config =
3047
360
        GetPrivateKeyEncodingFromJs(args, offset, kKeyContextInput);
3048
180
    if (config.IsEmpty())
3049
      return ManagedEVPPKey();
3050
3051
360
    EVPKeyPointer pkey;
3052
    ParseKeyResult ret =
3053
180
        ParsePrivateKey(&pkey, config.Release(), key.get(), key.size());
3054
180
    return GetParsedKey(env, std::move(pkey), ret,
3055
180
                        "Failed to read private key");
3056
  } else {
3057

99
    CHECK(args[*offset]->IsObject() && allow_key_object);
3058
    KeyObjectHandle* key;
3059
99
    ASSIGN_OR_RETURN_UNWRAP(&key, args[*offset].As<Object>(), ManagedEVPPKey());
3060
33
    CHECK_EQ(key->Data()->GetKeyType(), kKeyTypePrivate);
3061
33
    (*offset) += 4;
3062
33
    return key->Data()->GetAsymmetricKey();
3063
  }
3064
}
3065
3066
1215
static ManagedEVPPKey GetPublicOrPrivateKeyFromJs(
3067
    const FunctionCallbackInfo<Value>& args,
3068
    unsigned int* offset) {
3069

5863
  if (args[*offset]->IsString() || Buffer::HasInstance(args[*offset])) {
3070
1112
    Environment* env = Environment::GetCurrent(args);
3071
3336
    ByteSource data = ByteSource::FromStringOrBuffer(env, args[(*offset)++]);
3072
    NonCopyableMaybe<PrivateKeyEncodingConfig> config_ =
3073
2224
        GetPrivateKeyEncodingFromJs(args, offset, kKeyContextInput);
3074
1112
    if (config_.IsEmpty())
3075
      return ManagedEVPPKey();
3076
3077
    ParseKeyResult ret;
3078
2224
    PrivateKeyEncodingConfig config = config_.Release();
3079
2224
    EVPKeyPointer pkey;
3080
1112
    if (config.format_ == kKeyFormatPEM) {
3081
      // For PEM, we can easily determine whether it is a public or private key
3082
      // by looking for the respective PEM tags.
3083
1062
      ret = ParsePublicKeyPEM(&pkey, data.get(), data.size());
3084
1062
      if (ret == ParseKeyResult::kParseKeyNotRecognized) {
3085
190
        ret = ParsePrivateKey(&pkey, config, data.get(), data.size());
3086
      }
3087
    } else {
3088
      // For DER, the type determines how to parse it. SPKI, PKCS#8 and SEC1 are
3089
      // easy, but PKCS#1 can be a public key or a private key.
3090
      bool is_public;
3091

50
      switch (config.type_.ToChecked()) {
3092
        case kKeyEncodingPKCS1:
3093
64
          is_public = !IsRSAPrivateKey(
3094
32
              reinterpret_cast<const unsigned char*>(data.get()), data.size());
3095
32
          break;
3096
        case kKeyEncodingSPKI:
3097
          is_public = true;
3098
          break;
3099
        case kKeyEncodingPKCS8:
3100
        case kKeyEncodingSEC1:
3101
18
          is_public = false;
3102
18
          break;
3103
        default:
3104
          UNREACHABLE("Invalid key encoding type");
3105
      }
3106
3107
50
      if (is_public) {
3108
22
        ret = ParsePublicKey(&pkey, config, data.get(), data.size());
3109
      } else {
3110
28
        ret = ParsePrivateKey(&pkey, config, data.get(), data.size());
3111
      }
3112
    }
3113
3114
1112
    return GetParsedKey(env, std::move(pkey), ret,
3115
1112
                        "Failed to read asymmetric key");
3116
  } else {
3117
309
    CHECK(args[*offset]->IsObject());
3118
309
    KeyObjectHandle* key = Unwrap<KeyObjectHandle>(args[*offset].As<Object>());
3119
103
    CHECK_NOT_NULL(key);
3120
103
    CHECK_NE(key->Data()->GetKeyType(), kKeyTypeSecret);
3121
103
    (*offset) += 4;
3122
103
    return key->Data()->GetAsymmetricKey();
3123
  }
3124
}
3125
3126
27
static MaybeLocal<Value> WritePrivateKey(
3127
    Environment* env,
3128
    EVP_PKEY* pkey,
3129
    const PrivateKeyEncodingConfig& config) {
3130
54
  BIOPointer bio(BIO_new(BIO_s_mem()));
3131
27
  CHECK(bio);
3132
3133
  bool err;
3134
3135
54
  PKEncodingType encoding_type = config.type_.ToChecked();
3136
27
  if (encoding_type == kKeyEncodingPKCS1) {
3137
    // PKCS#1 is only permitted for RSA keys.
3138
11
    CHECK_EQ(EVP_PKEY_id(pkey), EVP_PKEY_RSA);
3139
3140
22
    RSAPointer rsa(EVP_PKEY_get1_RSA(pkey));
3141
11
    if (config.format_ == kKeyFormatPEM) {
3142
      // Encode PKCS#1 as PEM.
3143
10
      const char* pass = config.passphrase_.get();
3144
20
      err = PEM_write_bio_RSAPrivateKey(
3145
                bio.get(), rsa.get(),
3146
10
                config.cipher_,
3147
                reinterpret_cast<unsigned char*>(const_cast<char*>(pass)),
3148
10
                config.passphrase_.size(),
3149
                nullptr, nullptr) != 1;
3150
    } else {
3151
      // Encode PKCS#1 as DER. This does not permit encryption.
3152
1
      CHECK_EQ(config.format_, kKeyFormatDER);
3153
1
      CHECK_NULL(config.cipher_);
3154
1
      err = i2d_RSAPrivateKey_bio(bio.get(), rsa.get()) != 1;
3155
    }
3156
16
  } else if (encoding_type == kKeyEncodingPKCS8) {
3157
12
    if (config.format_ == kKeyFormatPEM) {
3158
      // Encode PKCS#8 as PEM.
3159
18
      err = PEM_write_bio_PKCS8PrivateKey(
3160
                bio.get(), pkey,
3161
9
                config.cipher_,
3162
9
                const_cast<char*>(config.passphrase_.get()),
3163
9
                config.passphrase_.size(),
3164
                nullptr, nullptr) != 1;
3165
    } else {
3166
      // Encode PKCS#8 as DER.
3167
3
      CHECK_EQ(config.format_, kKeyFormatDER);
3168
6
      err = i2d_PKCS8PrivateKey_bio(
3169
                bio.get(), pkey,
3170
3
                config.cipher_,
3171
3
                const_cast<char*>(config.passphrase_.get()),
3172
3
                config.passphrase_.size(),
3173
                nullptr, nullptr) != 1;
3174
    }
3175
  } else {
3176
4
    CHECK_EQ(encoding_type, kKeyEncodingSEC1);
3177
3178
    // SEC1 is only permitted for EC keys.
3179
4
    CHECK_EQ(EVP_PKEY_id(pkey), EVP_PKEY_EC);
3180
3181
8
    ECKeyPointer ec_key(EVP_PKEY_get1_EC_KEY(pkey));
3182
4
    if (config.format_ == kKeyFormatPEM) {
3183
      // Encode SEC1 as PEM.
3184
4
      const char* pass = config.passphrase_.get();
3185
8
      err = PEM_write_bio_ECPrivateKey(
3186
                bio.get(), ec_key.get(),
3187
4
                config.cipher_,
3188
                reinterpret_cast<unsigned char*>(const_cast<char*>(pass)),
3189
4
                config.passphrase_.size(),
3190
                nullptr, nullptr) != 1;
3191
    } else {
3192
      // Encode SEC1 as DER. This does not permit encryption.
3193
      CHECK_EQ(config.format_, kKeyFormatDER);
3194
      CHECK_NULL(config.cipher_);
3195
      err = i2d_ECPrivateKey_bio(bio.get(), ec_key.get()) != 1;
3196
    }
3197
  }
3198
3199
27
  if (err) {
3200
    ThrowCryptoError(env, ERR_get_error(), "Failed to encode private key");
3201
    return MaybeLocal<Value>();
3202
  }
3203
54
  return BIOToStringOrBuffer(env, bio.get(), config.format_);
3204
}
3205
3206
1384
ManagedEVPPKey::ManagedEVPPKey(EVPKeyPointer&& pkey) : pkey_(std::move(pkey)) {}
3207
3208
413
ManagedEVPPKey::ManagedEVPPKey(const ManagedEVPPKey& that) {
3209
413
  *this = that;
3210
413
}
3211
3212
504
ManagedEVPPKey& ManagedEVPPKey::operator=(const ManagedEVPPKey& that) {
3213
504
  pkey_.reset(that.get());
3214
3215
504
  if (pkey_)
3216
499
    EVP_PKEY_up_ref(pkey_.get());
3217
3218
504
  return *this;
3219
}
3220
3221
1574
ManagedEVPPKey::operator bool() const {
3222
1574
  return !!pkey_;
3223
}
3224
3225
5528
EVP_PKEY* ManagedEVPPKey::get() const {
3226
5528
  return pkey_.get();
3227
}
3228
3229
14
std::shared_ptr<KeyObjectData> KeyObjectData::CreateSecret(
3230
    Local<ArrayBufferView> abv) {
3231
14
  size_t key_len = abv->ByteLength();
3232
14
  char* mem = MallocOpenSSL<char>(key_len);
3233
14
  abv->CopyContents(mem, key_len);
3234
  return std::shared_ptr<KeyObjectData>(new KeyObjectData(
3235
28
      std::unique_ptr<char, std::function<void(char*)>>(mem,
3236
14
          [key_len](char* p) {
3237
14
            OPENSSL_clear_free(p, key_len);
3238
14
          }),
3239
28
      key_len));
3240
}
3241
3242
100
std::shared_ptr<KeyObjectData> KeyObjectData::CreateAsymmetric(
3243
    KeyType key_type,
3244
    const ManagedEVPPKey& pkey) {
3245
100
  CHECK(pkey);
3246
100
  return std::shared_ptr<KeyObjectData>(new KeyObjectData(key_type, pkey));
3247
}
3248
3249
206
KeyType KeyObjectData::GetKeyType() const {
3250
206
  return key_type_;
3251
}
3252
3253
279
ManagedEVPPKey KeyObjectData::GetAsymmetricKey() const {
3254
279
  CHECK_NE(key_type_, kKeyTypeSecret);
3255
279
  return asymmetric_key_;
3256
}
3257
3258
19
const char* KeyObjectData::GetSymmetricKey() const {
3259
19
  CHECK_EQ(key_type_, kKeyTypeSecret);
3260
19
  return symmetric_key_.get();
3261
}
3262
3263
20
size_t KeyObjectData::GetSymmetricKeySize() const {
3264
20
  CHECK_EQ(key_type_, kKeyTypeSecret);
3265
20
  return symmetric_key_len_;
3266
}
3267
3268
607
Local<Function> KeyObjectHandle::Initialize(Environment* env,
3269
                                            Local<Object> target) {
3270
607
  Local<FunctionTemplate> t = env->NewFunctionTemplate(New);
3271
1821
  t->InstanceTemplate()->SetInternalFieldCount(
3272
607
      KeyObjectHandle::kInternalFieldCount);
3273
1214
  t->Inherit(BaseObject::GetConstructorTemplate(env));
3274
3275
607
  env->SetProtoMethod(t, "init", Init);
3276
  env->SetProtoMethodNoSideEffect(t, "getSymmetricKeySize",
3277
607
                                  GetSymmetricKeySize);
3278
  env->SetProtoMethodNoSideEffect(t, "getAsymmetricKeyType",
3279
607
                                  GetAsymmetricKeyType);
3280
607
  env->SetProtoMethod(t, "export", Export);
3281
3282
1821
  auto function = t->GetFunction(env->context()).ToLocalChecked();
3283
1214
  target->Set(env->context(),
3284
              FIXED_ONE_BYTE_STRING(env->isolate(), "KeyObjectHandle"),
3285
2428
              function).Check();
3286
3287
607
  return function;
3288
}
3289
3290
66
MaybeLocal<Object> KeyObjectHandle::Create(
3291
    Environment* env,
3292
    std::shared_ptr<KeyObjectData> data) {
3293
  Local<Object> obj;
3294
198
  if (!env->crypto_key_object_handle_constructor()
3295
198
           ->NewInstance(env->context(), 0, nullptr)
3296
66
           .ToLocal(&obj)) {
3297
    return MaybeLocal<Object>();
3298
  }
3299
3300
66
  KeyObjectHandle* key = Unwrap<KeyObjectHandle>(obj);
3301
66
  CHECK_NOT_NULL(key);
3302
66
  key->data_ = data;
3303
66
  return obj;
3304
}
3305
3306
519
const std::shared_ptr<KeyObjectData>& KeyObjectHandle::Data() {
3307
519
  return data_;
3308
}
3309
3310
125
void KeyObjectHandle::New(const FunctionCallbackInfo<Value>& args) {
3311
125
  CHECK(args.IsConstructCall());
3312
125
  Environment* env = Environment::GetCurrent(args);
3313
125
  new KeyObjectHandle(env, args.This());
3314
125
}
3315
3316
125
KeyObjectHandle::KeyObjectHandle(Environment* env,
3317
125
                                 Local<Object> wrap)
3318
125
    : BaseObject(env, wrap) {
3319
125
  MakeWeak();
3320
125
}
3321
3322
59
void KeyObjectHandle::Init(const FunctionCallbackInfo<Value>& args) {
3323
  KeyObjectHandle* key;
3324
64
  ASSIGN_OR_RETURN_UNWRAP(&key, args.Holder());
3325
113
  MarkPopErrorOnReturn mark_pop_error_on_return;
3326
3327
118
  CHECK(args[0]->IsInt32());
3328
177
  KeyType type = static_cast<KeyType>(args[0].As<Uint32>()->Value());
3329
3330
  unsigned int offset;
3331
113
  ManagedEVPPKey pkey;
3332
3333

59
  switch (type) {
3334
  case kKeyTypeSecret:
3335
14
    CHECK_EQ(args.Length(), 2);
3336
28
    CHECK(args[1]->IsArrayBufferView());
3337
28
    key->data_ = KeyObjectData::CreateSecret(args[1].As<ArrayBufferView>());
3338
14
    break;
3339
  case kKeyTypePublic:
3340
23
    CHECK_EQ(args.Length(), 4);
3341
3342
23
    offset = 1;
3343
23
    pkey = GetPublicOrPrivateKeyFromJs(args, &offset);
3344
23
    if (!pkey)
3345
      return;
3346
23
    key->data_ = KeyObjectData::CreateAsymmetric(type, pkey);
3347
23
    break;
3348
  case kKeyTypePrivate:
3349
22
    CHECK_EQ(args.Length(), 5);
3350
3351
22
    offset = 1;
3352
22
    pkey = GetPrivateKeyFromJs(args, &offset, false);
3353
22
    if (!pkey)
3354
5
      return;
3355
17
    key->data_ = KeyObjectData::CreateAsymmetric(type, pkey);
3356
17
    break;
3357
  default:
3358
    CHECK(false);
3359
  }
3360
}
3361
3362
84
Local<Value> KeyObjectHandle::GetAsymmetricKeyType() const {
3363
168
  const ManagedEVPPKey& key = data_->GetAsymmetricKey();
3364


84
  switch (EVP_PKEY_id(key.get())) {
3365
  case EVP_PKEY_RSA:
3366
32
    return env()->crypto_rsa_string();
3367
  case EVP_PKEY_RSA_PSS:
3368
16
    return env()->crypto_rsa_pss_string();
3369
  case EVP_PKEY_DSA:
3370
4
    return env()->crypto_dsa_string();
3371
  case EVP_PKEY_DH:
3372
44
    return env()->crypto_dh_string();
3373
  case EVP_PKEY_EC:
3374
12
    return env()->crypto_ec_string();
3375
  case EVP_PKEY_ED25519:
3376
10
    return env()->crypto_ed25519_string();
3377
  case EVP_PKEY_ED448:
3378
10
    return env()->crypto_ed448_string();
3379
  case EVP_PKEY_X25519:
3380
20
    return env()->crypto_x25519_string();
3381
  case EVP_PKEY_X448:
3382
20
    return env()->crypto_x448_string();
3383
  default:
3384
    return Undefined(env()->isolate());
3385
  }
3386
}
3387
3388
84
void KeyObjectHandle::GetAsymmetricKeyType(
3389
    const FunctionCallbackInfo<Value>& args) {
3390
  KeyObjectHandle* key;
3391
84
  ASSIGN_OR_RETURN_UNWRAP(&key, args.Holder());
3392
3393
252
  args.GetReturnValue().Set(key->GetAsymmetricKeyType());
3394
}
3395
3396
1
void KeyObjectHandle::GetSymmetricKeySize(
3397
    const FunctionCallbackInfo<Value>& args) {
3398
  KeyObjectHandle* key;
3399
1
  ASSIGN_OR_RETURN_UNWRAP(&key, args.Holder());
3400
3
  args.GetReturnValue().Set(
3401
1
      static_cast<uint32_t>(key->Data()->GetSymmetricKeySize()));
3402
}
3403
3404
30
void KeyObjectHandle::Export(const FunctionCallbackInfo<Value>& args) {
3405
  KeyObjectHandle* key;
3406
30
  ASSIGN_OR_RETURN_UNWRAP(&key, args.Holder());
3407
3408
30
  KeyType type = key->Data()->GetKeyType();
3409
3410
  MaybeLocal<Value> result;
3411
30
  if (type == kKeyTypeSecret) {
3412
10
    result = key->ExportSecretKey();
3413
25
  } else if (type == kKeyTypePublic) {
3414
14
    unsigned int offset = 0;
3415
    PublicKeyEncodingConfig config =
3416
14
        GetPublicKeyEncodingFromJs(args, &offset, kKeyContextExport);
3417
14
    CHECK_EQ(offset, static_cast<unsigned int>(args.Length()));
3418
14
    result = key->ExportPublicKey(config);
3419
  } else {
3420
11
    CHECK_EQ(type, kKeyTypePrivate);
3421
11
    unsigned int offset = 0;
3422
    NonCopyableMaybe<PrivateKeyEncodingConfig> config =
3423
22
        GetPrivateKeyEncodingFromJs(args, &offset, kKeyContextExport);
3424
11
    if (config.IsEmpty())
3425
      return;
3426
11
    CHECK_EQ(offset, static_cast<unsigned int>(args.Length()));
3427
11
    result = key->ExportPrivateKey(config.Release());
3428
  }
3429
3430
30
  if (!result.IsEmpty())
3431
60
    args.GetReturnValue().Set(result.ToLocalChecked());
3432
}
3433
3434
5
Local<Value> KeyObjectHandle::ExportSecretKey() const {
3435
5
  const char* buf = data_->GetSymmetricKey();
3436
5
  unsigned int len = data_->GetSymmetricKeySize();
3437
10
  return Buffer::Copy(env(), buf, len).ToLocalChecked();
3438
}
3439
3440
14
MaybeLocal<Value> KeyObjectHandle::ExportPublicKey(
3441
    const PublicKeyEncodingConfig& config) const {
3442
14
  return WritePublicKey(env(), data_->GetAsymmetricKey().get(), config);