GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: crypto/crypto_context.cc Lines: 599 714 83.9 %
Date: 2022-10-23 04:21:34 Branches: 289 476 60.7 %

Line Branch Exec Source
1
#include "crypto/crypto_context.h"
2
#include "crypto/crypto_bio.h"
3
#include "crypto/crypto_common.h"
4
#include "crypto/crypto_util.h"
5
#include "base_object-inl.h"
6
#include "env-inl.h"
7
#include "memory_tracker-inl.h"
8
#include "node.h"
9
#include "node_buffer.h"
10
#include "node_options.h"
11
#include "util.h"
12
#include "v8.h"
13
14
#include <openssl/x509.h>
15
#include <openssl/pkcs12.h>
16
#include <openssl/rand.h>
17
#ifndef OPENSSL_NO_ENGINE
18
#include <openssl/engine.h>
19
#endif  // !OPENSSL_NO_ENGINE
20
21
namespace node {
22
23
using v8::Array;
24
using v8::ArrayBufferView;
25
using v8::Context;
26
using v8::DontDelete;
27
using v8::Exception;
28
using v8::External;
29
using v8::FunctionCallbackInfo;
30
using v8::FunctionTemplate;
31
using v8::HandleScope;
32
using v8::Int32;
33
using v8::Integer;
34
using v8::Isolate;
35
using v8::Local;
36
using v8::Object;
37
using v8::PropertyAttribute;
38
using v8::ReadOnly;
39
using v8::Signature;
40
using v8::String;
41
using v8::Value;
42
43
namespace crypto {
44
static const char* const root_certs[] = {
45
#include "node_root_certs.h"  // NOLINT(build/include_order)
46
};
47
48
static const char system_cert_path[] = NODE_OPENSSL_SYSTEM_CERT_PATH;
49
50
static X509_STORE* root_cert_store;
51
52
static bool extra_root_certs_loaded = false;
53
54
// Takes a string or buffer and loads it into a BIO.
55
// Caller responsible for BIO_free_all-ing the returned object.
56
2565
BIOPointer LoadBIO(Environment* env, Local<Value> v) {
57
5130
  HandleScope scope(env->isolate());
58
59
5130
  if (v->IsString()) {
60
2962
    Utf8Value s(env->isolate(), v);
61
1481
    return NodeBIO::NewFixed(*s, s.length());
62
  }
63
64
1084
  if (v->IsArrayBufferView()) {
65
1084
    ArrayBufferViewContents<char> buf(v.As<ArrayBufferView>());
66
1084
    return NodeBIO::NewFixed(buf.data(), buf.length());
67
  }
68
69
  return nullptr;
70
}
71
72
namespace {
73
951
int SSL_CTX_use_certificate_chain(SSL_CTX* ctx,
74
                                  X509Pointer&& x,
75
                                  STACK_OF(X509)* extra_certs,
76
                                  X509Pointer* cert,
77
                                  X509Pointer* issuer_) {
78
951
  CHECK(!*issuer_);
79
951
  CHECK(!*cert);
80
951
  X509* issuer = nullptr;
81
82
951
  int ret = SSL_CTX_use_certificate(ctx, x.get());
83
84
951
  if (ret) {
85
    // If we could set up our certificate, now proceed to
86
    // the CA certificates.
87
951
    SSL_CTX_clear_extra_chain_certs(ctx);
88
89
1377
    for (int i = 0; i < sk_X509_num(extra_certs); i++) {
90
426
      X509* ca = sk_X509_value(extra_certs, i);
91
92
      // NOTE: Increments reference count on `ca`
93
426
      if (!SSL_CTX_add1_chain_cert(ctx, ca)) {
94
        ret = 0;
95
        issuer = nullptr;
96
        break;
97
      }
98
      // Note that we must not free r if it was successfully
99
      // added to the chain (while we must free the main
100
      // certificate, since its reference count is increased
101
      // by SSL_CTX_use_certificate).
102
103
      // Find issuer
104

426
      if (issuer != nullptr || X509_check_issued(ca, x.get()) != X509_V_OK)
105
4
        continue;
106
107
422
      issuer = ca;
108
    }
109
  }
110
111
  // Try getting issuer from a cert store
112
951
  if (ret) {
113
951
    if (issuer == nullptr) {
114
      // TODO(tniessen): SSL_CTX_get_issuer does not allow the caller to
115
      // distinguish between a failed operation and an empty result. Fix that
116
      // and then handle the potential error properly here (set ret to 0).
117
529
      *issuer_ = SSL_CTX_get_issuer(ctx, x.get());
118
      // NOTE: get_cert_store doesn't increment reference count,
119
      // no need to free `store`
120
    } else {
121
      // Increment issuer reference count
122
422
      issuer_->reset(X509_dup(issuer));
123
422
      if (!*issuer_) {
124
        ret = 0;
125
      }
126
    }
127
  }
128
129

951
  if (ret && x != nullptr) {
130
951
    cert->reset(X509_dup(x.get()));
131
951
    if (!*cert)
132
      ret = 0;
133
  }
134
951
  return ret;
135
}
136
137
// Read a file that contains our certificate in "PEM" format,
138
// possibly followed by a sequence of CA certificates that should be
139
// sent to the peer in the Certificate message.
140
//
141
// Taken from OpenSSL - edited for style.
142
939
int SSL_CTX_use_certificate_chain(SSL_CTX* ctx,
143
                                  BIOPointer&& in,
144
                                  X509Pointer* cert,
145
                                  X509Pointer* issuer) {
146
  // Just to ensure that `ERR_peek_last_error` below will return only errors
147
  // that we are interested in
148
939
  ERR_clear_error();
149
150
  X509Pointer x(
151
1878
      PEM_read_bio_X509_AUX(in.get(), nullptr, NoPasswordCallback, nullptr));
152
153
939
  if (!x)
154
    return 0;
155
156
939
  unsigned long err = 0;  // NOLINT(runtime/int)
157
158
1878
  StackOfX509 extra_certs(sk_X509_new_null());
159
939
  if (!extra_certs)
160
    return 0;
161
162
  while (X509Pointer extra {PEM_read_bio_X509(in.get(),
163
                                    nullptr,
164
                                    NoPasswordCallback,
165
1356
                                    nullptr)}) {
166
417
    if (sk_X509_push(extra_certs.get(), extra.get())) {
167
417
      extra.release();
168
417
      continue;
169
    }
170
171
    return 0;
172
417
  }
173
174
  // When the while loop ends, it's usually just EOF.
175
939
  err = ERR_peek_last_error();
176

1878
  if (ERR_GET_LIB(err) == ERR_LIB_PEM &&
177
939
      ERR_GET_REASON(err) == PEM_R_NO_START_LINE) {
178
939
    ERR_clear_error();
179
  } else {
180
    // some real error
181
    return 0;
182
  }
183
184
1878
  return SSL_CTX_use_certificate_chain(ctx,
185
939
                                       std::move(x),
186
                                       extra_certs.get(),
187
                                       cert,
188
939
                                       issuer);
189
}
190
191
}  // namespace
192
193
280
X509_STORE* NewRootCertStore() {
194

280
  static std::vector<X509*> root_certs_vector;
195

280
  static Mutex root_certs_vector_mutex;
196
560
  Mutex::ScopedLock lock(root_certs_vector_mutex);
197
198

553
  if (root_certs_vector.empty() &&
199
273
      per_process::cli_options->ssl_openssl_cert_store == false) {
200
35904
    for (size_t i = 0; i < arraysize(root_certs); i++) {
201
      X509* x509 =
202
35632
          PEM_read_bio_X509(NodeBIO::NewFixed(root_certs[i],
203
35632
                                              strlen(root_certs[i])).get(),
204
                            nullptr,   // no re-use of X509 structure
205
                            NoPasswordCallback,
206
35632
                            nullptr);  // no callback data
207
208
      // Parse errors from the built-in roots are fatal.
209
35632
      CHECK_NOT_NULL(x509);
210
211
35632
      root_certs_vector.push_back(x509);
212
    }
213
  }
214
215
280
  X509_STORE* store = X509_STORE_new();
216
280
  if (*system_cert_path != '\0') {
217
    ERR_set_mark();
218
    X509_STORE_load_locations(store, system_cert_path, nullptr);
219
    ERR_pop_to_mark();
220
  }
221
222
280
  Mutex::ScopedLock cli_lock(node::per_process::cli_options_mutex);
223
280
  if (per_process::cli_options->ssl_openssl_cert_store) {
224
1
    X509_STORE_set_default_paths(store);
225
  } else {
226
36828
    for (X509* cert : root_certs_vector) {
227
36549
      X509_up_ref(cert);
228
36549
      X509_STORE_add_cert(store, cert);
229
    }
230
  }
231
232
280
  return store;
233
}
234
235
226
void GetRootCertificates(const FunctionCallbackInfo<Value>& args) {
236
226
  Environment* env = Environment::GetCurrent(args);
237
29832
  Local<Value> result[arraysize(root_certs)];
238
239
29832
  for (size_t i = 0; i < arraysize(root_certs); i++) {
240
29606
    if (!String::NewFromOneByte(
241
            env->isolate(),
242
29606
            reinterpret_cast<const uint8_t*>(root_certs[i]))
243
59212
            .ToLocal(&result[i])) {
244
      return;
245
    }
246
  }
247
248
452
  args.GetReturnValue().Set(
249
      Array::New(env->isolate(), result, arraysize(root_certs)));
250
}
251
252
bool SecureContext::HasInstance(Environment* env, const Local<Value>& value) {
253
  return GetConstructorTemplate(env)->HasInstance(value);
254
}
255
256
788
Local<FunctionTemplate> SecureContext::GetConstructorTemplate(
257
    Environment* env) {
258
788
  Local<FunctionTemplate> tmpl = env->secure_context_constructor_template();
259
788
  if (tmpl.IsEmpty()) {
260
788
    Isolate* isolate = env->isolate();
261
788
    tmpl = NewFunctionTemplate(isolate, New);
262
1576
    tmpl->InstanceTemplate()->SetInternalFieldCount(
263
        SecureContext::kInternalFieldCount);
264
788
    tmpl->Inherit(BaseObject::GetConstructorTemplate(env));
265
788
    tmpl->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "SecureContext"));
266
267
788
    SetProtoMethod(isolate, tmpl, "init", Init);
268
788
    SetProtoMethod(isolate, tmpl, "setKey", SetKey);
269
788
    SetProtoMethod(isolate, tmpl, "setCert", SetCert);
270
788
    SetProtoMethod(isolate, tmpl, "addCACert", AddCACert);
271
788
    SetProtoMethod(isolate, tmpl, "addCRL", AddCRL);
272
788
    SetProtoMethod(isolate, tmpl, "addRootCerts", AddRootCerts);
273
788
    SetProtoMethod(isolate, tmpl, "setCipherSuites", SetCipherSuites);
274
788
    SetProtoMethod(isolate, tmpl, "setCiphers", SetCiphers);
275
788
    SetProtoMethod(isolate, tmpl, "setSigalgs", SetSigalgs);
276
788
    SetProtoMethod(isolate, tmpl, "setECDHCurve", SetECDHCurve);
277
788
    SetProtoMethod(isolate, tmpl, "setDHParam", SetDHParam);
278
788
    SetProtoMethod(isolate, tmpl, "setMaxProto", SetMaxProto);
279
788
    SetProtoMethod(isolate, tmpl, "setMinProto", SetMinProto);
280
788
    SetProtoMethod(isolate, tmpl, "getMaxProto", GetMaxProto);
281
788
    SetProtoMethod(isolate, tmpl, "getMinProto", GetMinProto);
282
788
    SetProtoMethod(isolate, tmpl, "setOptions", SetOptions);
283
788
    SetProtoMethod(isolate, tmpl, "setSessionIdContext", SetSessionIdContext);
284
788
    SetProtoMethod(isolate, tmpl, "setSessionTimeout", SetSessionTimeout);
285
788
    SetProtoMethod(isolate, tmpl, "close", Close);
286
788
    SetProtoMethod(isolate, tmpl, "loadPKCS12", LoadPKCS12);
287
788
    SetProtoMethod(isolate, tmpl, "setTicketKeys", SetTicketKeys);
288
788
    SetProtoMethod(
289
        isolate, tmpl, "enableTicketKeyCallback", EnableTicketKeyCallback);
290
291
788
    SetProtoMethodNoSideEffect(isolate, tmpl, "getTicketKeys", GetTicketKeys);
292
788
    SetProtoMethodNoSideEffect(
293
        isolate, tmpl, "getCertificate", GetCertificate<true>);
294
788
    SetProtoMethodNoSideEffect(
295
        isolate, tmpl, "getIssuer", GetCertificate<false>);
296
297
#ifndef OPENSSL_NO_ENGINE
298
788
    SetProtoMethod(isolate, tmpl, "setEngineKey", SetEngineKey);
299
788
    SetProtoMethod(isolate, tmpl, "setClientCertEngine", SetClientCertEngine);
300
#endif  // !OPENSSL_NO_ENGINE
301
302
#define SET_INTEGER_CONSTANTS(name, value)                                     \
303
  tmpl->Set(FIXED_ONE_BYTE_STRING(isolate, name),                              \
304
            Integer::NewFromUnsigned(isolate, value));
305
2364
    SET_INTEGER_CONSTANTS("kTicketKeyReturnIndex", kTicketKeyReturnIndex);
306
2364
    SET_INTEGER_CONSTANTS("kTicketKeyHMACIndex", kTicketKeyHMACIndex);
307
2364
    SET_INTEGER_CONSTANTS("kTicketKeyAESIndex", kTicketKeyAESIndex);
308
2364
    SET_INTEGER_CONSTANTS("kTicketKeyNameIndex", kTicketKeyNameIndex);
309
2364
    SET_INTEGER_CONSTANTS("kTicketKeyIVIndex", kTicketKeyIVIndex);
310
  #undef SET_INTEGER_CONSTANTS
311
312
    Local<FunctionTemplate> ctx_getter_templ = FunctionTemplate::New(
313
788
        isolate, CtxGetter, Local<Value>(), Signature::New(isolate, tmpl));
314
315
3152
    tmpl->PrototypeTemplate()->SetAccessorProperty(
316
        FIXED_ONE_BYTE_STRING(isolate, "_external"),
317
        ctx_getter_templ,
318
        Local<FunctionTemplate>(),
319
        static_cast<PropertyAttribute>(ReadOnly | DontDelete));
320
321
788
    env->set_secure_context_constructor_template(tmpl);
322
  }
323
788
  return tmpl;
324
}
325
326
788
void SecureContext::Initialize(Environment* env, Local<Object> target) {
327
788
  Local<Context> context = env->context();
328
788
  SetConstructorFunction(context,
329
                         target,
330
                         "SecureContext",
331
                         GetConstructorTemplate(env),
332
                         SetConstructorFunctionFlag::NONE);
333
334
788
  SetMethodNoSideEffect(
335
      context, target, "getRootCertificates", GetRootCertificates);
336
  // Exposed for testing purposes only.
337
788
  SetMethodNoSideEffect(context,
338
                        target,
339
                        "isExtraRootCertsFileLoaded",
340
                        IsExtraRootCertsFileLoaded);
341
788
}
342
343
5574
void SecureContext::RegisterExternalReferences(
344
    ExternalReferenceRegistry* registry) {
345
5574
  registry->Register(New);
346
5574
  registry->Register(Init);
347
5574
  registry->Register(SetKey);
348
5574
  registry->Register(SetCert);
349
5574
  registry->Register(AddCACert);
350
5574
  registry->Register(AddCRL);
351
5574
  registry->Register(AddRootCerts);
352
5574
  registry->Register(SetCipherSuites);
353
5574
  registry->Register(SetCiphers);
354
5574
  registry->Register(SetSigalgs);
355
5574
  registry->Register(SetECDHCurve);
356
5574
  registry->Register(SetDHParam);
357
5574
  registry->Register(SetMaxProto);
358
5574
  registry->Register(SetMinProto);
359
5574
  registry->Register(GetMaxProto);
360
5574
  registry->Register(GetMinProto);
361
5574
  registry->Register(SetOptions);
362
5574
  registry->Register(SetSessionIdContext);
363
5574
  registry->Register(SetSessionTimeout);
364
5574
  registry->Register(Close);
365
5574
  registry->Register(LoadPKCS12);
366
5574
  registry->Register(SetTicketKeys);
367
5574
  registry->Register(EnableTicketKeyCallback);
368
5574
  registry->Register(GetTicketKeys);
369
5574
  registry->Register(GetCertificate<true>);
370
5574
  registry->Register(GetCertificate<false>);
371
372
#ifndef OPENSSL_NO_ENGINE
373
5574
  registry->Register(SetEngineKey);
374
5574
  registry->Register(SetClientCertEngine);
375
#endif  // !OPENSSL_NO_ENGINE
376
377
5574
  registry->Register(CtxGetter);
378
379
5574
  registry->Register(GetRootCertificates);
380
5574
  registry->Register(IsExtraRootCertsFileLoaded);
381
5574
}
382
383
SecureContext* SecureContext::Create(Environment* env) {
384
  Local<Object> obj;
385
  if (!GetConstructorTemplate(env)
386
          ->InstanceTemplate()
387
          ->NewInstance(env->context()).ToLocal(&obj)) {
388
    return nullptr;
389
  }
390
391
  return new SecureContext(env, obj);
392
}
393
394
2506
SecureContext::SecureContext(Environment* env, Local<Object> wrap)
395
2506
    : BaseObject(env, wrap) {
396
2506
  MakeWeak();
397
2506
  env->isolate()->AdjustAmountOfExternalAllocatedMemory(kExternalSize);
398
2506
}
399
400
2497
inline void SecureContext::Reset() {
401
2497
  if (ctx_ != nullptr) {
402
2439
    env()->isolate()->AdjustAmountOfExternalAllocatedMemory(-kExternalSize);
403
  }
404
2497
  ctx_.reset();
405
2497
  cert_.reset();
406
2497
  issuer_.reset();
407
2497
}
408
409
9988
SecureContext::~SecureContext() {
410
4994
  Reset();
411
9988
}
412
413
2506
void SecureContext::New(const FunctionCallbackInfo<Value>& args) {
414
2506
  Environment* env = Environment::GetCurrent(args);
415
2506
  new SecureContext(env, args.This());
416
2506
}
417
418
2504
void SecureContext::Init(const FunctionCallbackInfo<Value>& args) {
419
  SecureContext* sc;
420
2560
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
421
2504
  Environment* env = sc->env();
422
423
2504
  CHECK_EQ(args.Length(), 3);
424
2504
  CHECK(args[1]->IsInt32());
425
2504
  CHECK(args[2]->IsInt32());
426
427
5008
  int min_version = args[1].As<Int32>()->Value();
428
5008
  int max_version = args[2].As<Int32>()->Value();
429
2504
  const SSL_METHOD* method = TLS_method();
430
431
2504
  if (max_version == 0)
432
    max_version = kMaxSupportedVersion;
433
434
5008
  if (args[0]->IsString()) {
435
371
    Utf8Value sslmethod(env->isolate(), args[0]);
436
437
    // Note that SSLv2 and SSLv3 are disallowed but SSLv23_method and friends
438
    // are still accepted.  They are OpenSSL's way of saying that all known
439
    // protocols below TLS 1.3 are supported unless explicitly disabled (which
440
    // we do below for SSLv2 and SSLv3.)
441
727
    if (sslmethod == "SSLv2_method" ||
442

727
        sslmethod == "SSLv2_server_method" ||
443
355
        sslmethod == "SSLv2_client_method") {
444
17
      THROW_ERR_TLS_INVALID_PROTOCOL_METHOD(env, "SSLv2 methods disabled");
445
17
      return;
446
693
    } else if (sslmethod == "SSLv3_method" ||
447

693
               sslmethod == "SSLv3_server_method" ||
448
338
               sslmethod == "SSLv3_client_method") {
449
17
      THROW_ERR_TLS_INVALID_PROTOCOL_METHOD(env, "SSLv3 methods disabled");
450
17
      return;
451
337
    } else if (sslmethod == "SSLv23_method") {
452
36
      max_version = TLS1_2_VERSION;
453
301
    } else if (sslmethod == "SSLv23_server_method") {
454
1
      max_version = TLS1_2_VERSION;
455
1
      method = TLS_server_method();
456
300
    } else if (sslmethod == "SSLv23_client_method") {
457
1
      max_version = TLS1_2_VERSION;
458
1
      method = TLS_client_method();
459
299
    } else if (sslmethod == "TLS_method") {
460
53
      min_version = 0;
461
53
      max_version = kMaxSupportedVersion;
462
246
    } else if (sslmethod == "TLS_server_method") {
463
      min_version = 0;
464
      max_version = kMaxSupportedVersion;
465
      method = TLS_server_method();
466
246
    } else if (sslmethod == "TLS_client_method") {
467
      min_version = 0;
468
      max_version = kMaxSupportedVersion;
469
      method = TLS_client_method();
470
246
    } else if (sslmethod == "TLSv1_method") {
471
71
      min_version = TLS1_VERSION;
472
71
      max_version = TLS1_VERSION;
473
175
    } else if (sslmethod == "TLSv1_server_method") {
474
1
      min_version = TLS1_VERSION;
475
1
      max_version = TLS1_VERSION;
476
1
      method = TLS_server_method();
477
174
    } else if (sslmethod == "TLSv1_client_method") {
478
1
      min_version = TLS1_VERSION;
479
1
      max_version = TLS1_VERSION;
480
1
      method = TLS_client_method();
481
173
    } else if (sslmethod == "TLSv1_1_method") {
482
71
      min_version = TLS1_1_VERSION;
483
71
      max_version = TLS1_1_VERSION;
484
102
    } else if (sslmethod == "TLSv1_1_server_method") {
485
1
      min_version = TLS1_1_VERSION;
486
1
      max_version = TLS1_1_VERSION;
487
1
      method = TLS_server_method();
488
101
    } else if (sslmethod == "TLSv1_1_client_method") {
489
1
      min_version = TLS1_1_VERSION;
490
1
      max_version = TLS1_1_VERSION;
491
1
      method = TLS_client_method();
492
100
    } else if (sslmethod == "TLSv1_2_method") {
493
75
      min_version = TLS1_2_VERSION;
494
75
      max_version = TLS1_2_VERSION;
495
25
    } else if (sslmethod == "TLSv1_2_server_method") {
496
2
      min_version = TLS1_2_VERSION;
497
2
      max_version = TLS1_2_VERSION;
498
2
      method = TLS_server_method();
499
23
    } else if (sslmethod == "TLSv1_2_client_method") {
500
1
      min_version = TLS1_2_VERSION;
501
1
      max_version = TLS1_2_VERSION;
502
1
      method = TLS_client_method();
503
    } else {
504
22
      THROW_ERR_TLS_INVALID_PROTOCOL_METHOD(
505
22
          env, "Unknown method: %s", *sslmethod);
506
22
      return;
507
    }
508
  }
509
510
2448
  sc->ctx_.reset(SSL_CTX_new(method));
511
2448
  if (!sc->ctx_) {
512
    return ThrowCryptoError(env, ERR_get_error(), "SSL_CTX_new");
513
  }
514
2448
  SSL_CTX_set_app_data(sc->ctx_.get(), sc);
515
516
  // Disable SSLv2 in the case when method == TLS_method() and the
517
  // cipher list contains SSLv2 ciphers (not the default, should be rare.)
518
  // The bundled OpenSSL doesn't have SSLv2 support but the system OpenSSL may.
519
  // SSLv3 is disabled because it's susceptible to downgrade attacks (POODLE.)
520
2448
  SSL_CTX_set_options(sc->ctx_.get(), SSL_OP_NO_SSLv2);
521
2448
  SSL_CTX_set_options(sc->ctx_.get(), SSL_OP_NO_SSLv3);
522
#if OPENSSL_VERSION_MAJOR >= 3
523
2448
  SSL_CTX_set_options(sc->ctx_.get(), SSL_OP_ALLOW_CLIENT_RENEGOTIATION);
524
#endif
525
526
  // Enable automatic cert chaining. This is enabled by default in OpenSSL, but
527
  // disabled by default in BoringSSL. Enable it explicitly to make the
528
  // behavior match when Node is built with BoringSSL.
529
2448
  SSL_CTX_clear_mode(sc->ctx_.get(), SSL_MODE_NO_AUTO_CHAIN);
530
531
  // SSL session cache configuration
532
2448
  SSL_CTX_set_session_cache_mode(sc->ctx_.get(),
533
                                 SSL_SESS_CACHE_CLIENT |
534
                                 SSL_SESS_CACHE_SERVER |
535
                                 SSL_SESS_CACHE_NO_INTERNAL |
536
                                 SSL_SESS_CACHE_NO_AUTO_CLEAR);
537
538
2448
  SSL_CTX_set_min_proto_version(sc->ctx_.get(), min_version);
539
2448
  SSL_CTX_set_max_proto_version(sc->ctx_.get(), max_version);
540
541
  // OpenSSL 1.1.0 changed the ticket key size, but the OpenSSL 1.0.x size was
542
  // exposed in the public API. To retain compatibility, install a callback
543
  // which restores the old algorithm.
544
4896
  if (CSPRNG(sc->ticket_key_name_, sizeof(sc->ticket_key_name_)).is_err() ||
545

4896
      CSPRNG(sc->ticket_key_hmac_, sizeof(sc->ticket_key_hmac_)).is_err() ||
546
4896
      CSPRNG(sc->ticket_key_aes_, sizeof(sc->ticket_key_aes_)).is_err()) {
547
    return THROW_ERR_CRYPTO_OPERATION_FAILED(
548
        env, "Error generating ticket keys");
549
  }
550
2448
  SSL_CTX_set_tlsext_ticket_key_cb(sc->ctx_.get(), TicketCompatibilityCallback);
551
}
552
553
12399
SSLPointer SecureContext::CreateSSL() {
554
12399
  return SSLPointer(SSL_new(ctx_.get()));
555
}
556
557
12399
void SecureContext::SetNewSessionCallback(NewSessionCb cb) {
558
12399
  SSL_CTX_sess_set_new_cb(ctx_.get(), cb);
559
12399
}
560
561
12399
void SecureContext::SetGetSessionCallback(GetSessionCb cb) {
562
12399
  SSL_CTX_sess_set_get_cb(ctx_.get(), cb);
563
12399
}
564
565
951
void SecureContext::SetSelectSNIContextCallback(SelectSNIContextCb cb) {
566
951
  SSL_CTX_set_tlsext_servername_callback(ctx_.get(), cb);
567
951
}
568
569
8
void SecureContext::SetKeylogCallback(KeylogCb cb) {
570
8
  SSL_CTX_set_keylog_callback(ctx_.get(), cb);
571
8
}
572
573
921
void SecureContext::SetKey(const FunctionCallbackInfo<Value>& args) {
574
921
  Environment* env = Environment::GetCurrent(args);
575
576
  SecureContext* sc;
577
929
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
578
579
921
  CHECK_GE(args.Length(), 1);  // Private key argument is mandatory
580
581
921
  BIOPointer bio(LoadBIO(env, args[0]));
582
921
  if (!bio)
583
    return;
584
585
921
  ByteSource passphrase;
586
1842
  if (args[1]->IsString())
587
48
    passphrase = ByteSource::FromString(env, args[1].As<String>());
588
  // This redirection is necessary because the PasswordCallback expects a
589
  // pointer to a pointer to the passphrase ByteSource to allow passing in
590
  // const ByteSources.
591
921
  const ByteSource* pass_ptr = &passphrase;
592
593
  EVPKeyPointer key(
594
      PEM_read_bio_PrivateKey(bio.get(),
595
                              nullptr,
596
                              PasswordCallback,
597
921
                              &pass_ptr));
598
599
921
  if (!key)
600
7
    return ThrowCryptoError(env, ERR_get_error(), "PEM_read_bio_PrivateKey");
601
602
914
  if (!SSL_CTX_use_PrivateKey(sc->ctx_.get(), key.get()))
603
1
    return ThrowCryptoError(env, ERR_get_error(), "SSL_CTX_use_PrivateKey");
604
}
605
606
8
void SecureContext::SetSigalgs(const FunctionCallbackInfo<Value>& args) {
607
  SecureContext* sc;
608
8
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
609
8
  Environment* env = sc->env();
610
  ClearErrorOnReturn clear_error_on_return;
611
612
8
  CHECK_EQ(args.Length(), 1);
613
16
  CHECK(args[0]->IsString());
614
615
8
  const Utf8Value sigalgs(env->isolate(), args[0]);
616
617
8
  if (!SSL_CTX_set1_sigalgs_list(sc->ctx_.get(), *sigalgs))
618
    return ThrowCryptoError(env, ERR_get_error());
619
}
620
621
#ifndef OPENSSL_NO_ENGINE
622
void SecureContext::SetEngineKey(const FunctionCallbackInfo<Value>& args) {
623
  Environment* env = Environment::GetCurrent(args);
624
625
  SecureContext* sc;
626
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
627
628
  CHECK_EQ(args.Length(), 2);
629
630
  CryptoErrorStore errors;
631
  Utf8Value engine_id(env->isolate(), args[1]);
632
  EnginePointer engine = LoadEngineById(*engine_id, &errors);
633
  if (!engine) {
634
    Local<Value> exception;
635
    if (errors.ToException(env).ToLocal(&exception))
636
      env->isolate()->ThrowException(exception);
637
    return;
638
  }
639
640
  if (!ENGINE_init(engine.get())) {
641
    return THROW_ERR_CRYPTO_OPERATION_FAILED(
642
        env, "Failure to initialize engine");
643
  }
644
645
  engine.finish_on_exit = true;
646
647
  Utf8Value key_name(env->isolate(), args[0]);
648
  EVPKeyPointer key(ENGINE_load_private_key(engine.get(), *key_name,
649
                                            nullptr, nullptr));
650
651
  if (!key)
652
    return ThrowCryptoError(env, ERR_get_error(), "ENGINE_load_private_key");
653
654
  if (!SSL_CTX_use_PrivateKey(sc->ctx_.get(), key.get()))
655
    return ThrowCryptoError(env, ERR_get_error(), "SSL_CTX_use_PrivateKey");
656
657
  sc->private_key_engine_ = std::move(engine);
658
}
659
#endif  // !OPENSSL_NO_ENGINE
660
661
939
void SecureContext::SetCert(const FunctionCallbackInfo<Value>& args) {
662
939
  Environment* env = Environment::GetCurrent(args);
663
664
  SecureContext* sc;
665
939
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
666
667
939
  CHECK_GE(args.Length(), 1);  // Certificate argument is mandator
668
669
939
  BIOPointer bio(LoadBIO(env, args[0]));
670
939
  if (!bio)
671
    return;
672
673
939
  sc->cert_.reset();
674
939
  sc->issuer_.reset();
675
676
939
  if (!SSL_CTX_use_certificate_chain(
677
939
          sc->ctx_.get(),
678
939
          std::move(bio),
679
939
          &sc->cert_,
680
939
          &sc->issuer_)) {
681
    return ThrowCryptoError(
682
        env,
683
        ERR_get_error(),
684
        "SSL_CTX_use_certificate_chain");
685
  }
686
}
687
688
625
void SecureContext::AddCACert(const FunctionCallbackInfo<Value>& args) {
689
625
  Environment* env = Environment::GetCurrent(args);
690
691
  SecureContext* sc;
692
625
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
693
  ClearErrorOnReturn clear_error_on_return;
694
695
625
  CHECK_GE(args.Length(), 1);  // CA certificate argument is mandatory
696
697
625
  BIOPointer bio(LoadBIO(env, args[0]));
698
625
  if (!bio)
699
    return;
700
701
625
  X509_STORE* cert_store = SSL_CTX_get_cert_store(sc->ctx_.get());
702
  while (X509Pointer x509 = X509Pointer(PEM_read_bio_X509_AUX(
703
1594
             bio.get(), nullptr, NoPasswordCallback, nullptr))) {
704
969
    if (cert_store == root_cert_store) {
705
1
      cert_store = NewRootCertStore();
706
1
      SSL_CTX_set_cert_store(sc->ctx_.get(), cert_store);
707
    }
708
969
    X509_STORE_add_cert(cert_store, x509.get());
709
969
    SSL_CTX_add_client_CA(sc->ctx_.get(), x509.get());
710
969
  }
711
}
712
713
2
void SecureContext::AddCRL(const FunctionCallbackInfo<Value>& args) {
714
2
  Environment* env = Environment::GetCurrent(args);
715
716
  SecureContext* sc;
717
3
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
718
719
2
  CHECK_GE(args.Length(), 1);  // CRL argument is mandatory
720
721
  ClearErrorOnReturn clear_error_on_return;
722
723
2
  BIOPointer bio(LoadBIO(env, args[0]));
724
2
  if (!bio)
725
    return;
726
727
  DeleteFnPtr<X509_CRL, X509_CRL_free> crl(
728
2
      PEM_read_bio_X509_CRL(bio.get(), nullptr, NoPasswordCallback, nullptr));
729
730
2
  if (!crl)
731
1
    return THROW_ERR_CRYPTO_OPERATION_FAILED(env, "Failed to parse CRL");
732
733
1
  X509_STORE* cert_store = SSL_CTX_get_cert_store(sc->ctx_.get());
734
1
  if (cert_store == root_cert_store) {
735
    cert_store = NewRootCertStore();
736
    SSL_CTX_set_cert_store(sc->ctx_.get(), cert_store);
737
  }
738
739
1
  X509_STORE_add_crl(cert_store, crl.get());
740
1
  X509_STORE_set_flags(cert_store,
741
                       X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
742
}
743
744
1843
void SecureContext::AddRootCerts(const FunctionCallbackInfo<Value>& args) {
745
  SecureContext* sc;
746
1843
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
747
1843
  ClearErrorOnReturn clear_error_on_return;
748
749
1843
  if (root_cert_store == nullptr) {
750
268
    root_cert_store = NewRootCertStore();
751
  }
752
753
  // Increment reference count so global store is not deleted along with CTX.
754
1843
  X509_STORE_up_ref(root_cert_store);
755
1843
  SSL_CTX_set_cert_store(sc->ctx_.get(), root_cert_store);
756
}
757
758
1910
void SecureContext::SetCipherSuites(const FunctionCallbackInfo<Value>& args) {
759
  // BoringSSL doesn't allow API config of TLS1.3 cipher suites.
760
#ifndef OPENSSL_IS_BORINGSSL
761
  SecureContext* sc;
762
1911
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
763
1910
  Environment* env = sc->env();
764
  ClearErrorOnReturn clear_error_on_return;
765
766
1910
  CHECK_EQ(args.Length(), 1);
767
3820
  CHECK(args[0]->IsString());
768
769
1910
  const Utf8Value ciphers(env->isolate(), args[0]);
770
1910
  if (!SSL_CTX_set_ciphersuites(sc->ctx_.get(), *ciphers))
771
1
    return ThrowCryptoError(env, ERR_get_error(), "Failed to set ciphers");
772
#endif
773
}
774
775
2374
void SecureContext::SetCiphers(const FunctionCallbackInfo<Value>& args) {
776
  SecureContext* sc;
777
2389
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
778
2374
  Environment* env = sc->env();
779
  ClearErrorOnReturn clear_error_on_return;
780
781
2374
  CHECK_EQ(args.Length(), 1);
782
4748
  CHECK(args[0]->IsString());
783
784
2374
  Utf8Value ciphers(env->isolate(), args[0]);
785
2374
  if (!SSL_CTX_set_cipher_list(sc->ctx_.get(), *ciphers)) {
786
15
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
787
788

15
    if (strlen(*ciphers) == 0 && ERR_GET_REASON(err) == SSL_R_NO_CIPHER_MATCH) {
789
      // TLS1.2 ciphers were deliberately cleared, so don't consider
790
      // SSL_R_NO_CIPHER_MATCH to be an error (this is how _set_cipher_suites()
791
      // works). If the user actually sets a value (like "no-such-cipher"), then
792
      // that's actually an error.
793
11
      return;
794
    }
795
4
    return ThrowCryptoError(env, err, "Failed to set ciphers");
796
  }
797
}
798
799
2366
void SecureContext::SetECDHCurve(const FunctionCallbackInfo<Value>& args) {
800
  SecureContext* sc;
801
2369
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
802
2366
  Environment* env = sc->env();
803
804
2366
  CHECK_GE(args.Length(), 1);  // ECDH curve name argument is mandatory
805
4732
  CHECK(args[0]->IsString());
806
807
2366
  Utf8Value curve(env->isolate(), args[0]);
808
809

2376
  if (strcmp(*curve, "auto") != 0 &&
810
10
      !SSL_CTX_set1_curves_list(sc->ctx_.get(), *curve)) {
811
3
    return THROW_ERR_CRYPTO_OPERATION_FAILED(env, "Failed to set ECDH curve");
812
  }
813
}
814
815
10
void SecureContext::SetDHParam(const FunctionCallbackInfo<Value>& args) {
816
  SecureContext* sc;
817
13
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.This());
818
10
  Environment* env = sc->env();
819
  ClearErrorOnReturn clear_error_on_return;
820
821
10
  CHECK_GE(args.Length(), 1);  // DH argument is mandatory
822
823
10
  DHPointer dh;
824
  {
825
10
    BIOPointer bio(LoadBIO(env, args[0]));
826
10
    if (!bio)
827
      return;
828
829
10
    dh.reset(PEM_read_bio_DHparams(bio.get(), nullptr, nullptr, nullptr));
830
  }
831
832
  // Invalid dhparam is silently discarded and DHE is no longer used.
833
10
  if (!dh)
834
1
    return;
835
836
  const BIGNUM* p;
837
9
  DH_get0_pqg(dh.get(), &p, nullptr, nullptr);
838
9
  const int size = BN_num_bits(p);
839
9
  if (size < 1024) {
840
2
    return THROW_ERR_INVALID_ARG_VALUE(
841
2
        env, "DH parameter is less than 1024 bits");
842
7
  } else if (size < 2048) {
843
6
    args.GetReturnValue().Set(FIXED_ONE_BYTE_STRING(
844
        env->isolate(), "DH parameter is less than 2048 bits"));
845
  }
846
847
7
  SSL_CTX_set_options(sc->ctx_.get(), SSL_OP_SINGLE_DH_USE);
848
849
7
  if (!SSL_CTX_set_tmp_dh(sc->ctx_.get(), dh.get())) {
850
    return THROW_ERR_CRYPTO_OPERATION_FAILED(
851
        env, "Error setting temp DH parameter");
852
  }
853
}
854
855
11
void SecureContext::SetMinProto(const FunctionCallbackInfo<Value>& args) {
856
  SecureContext* sc;
857
11
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
858
859
11
  CHECK_EQ(args.Length(), 1);
860
11
  CHECK(args[0]->IsInt32());
861
862
22
  int version = args[0].As<Int32>()->Value();
863
864
11
  CHECK(SSL_CTX_set_min_proto_version(sc->ctx_.get(), version));
865
}
866
867
void SecureContext::SetMaxProto(const FunctionCallbackInfo<Value>& args) {
868
  SecureContext* sc;
869
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
870
871
  CHECK_EQ(args.Length(), 1);
872
  CHECK(args[0]->IsInt32());
873
874
  int version = args[0].As<Int32>()->Value();
875
876
  CHECK(SSL_CTX_set_max_proto_version(sc->ctx_.get(), version));
877
}
878
879
11
void SecureContext::GetMinProto(const FunctionCallbackInfo<Value>& args) {
880
  SecureContext* sc;
881
11
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
882
883
11
  CHECK_EQ(args.Length(), 0);
884
885
  long version =  // NOLINT(runtime/int)
886
11
    SSL_CTX_get_min_proto_version(sc->ctx_.get());
887
22
  args.GetReturnValue().Set(static_cast<uint32_t>(version));
888
}
889
890
11
void SecureContext::GetMaxProto(const FunctionCallbackInfo<Value>& args) {
891
  SecureContext* sc;
892
11
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
893
894
11
  CHECK_EQ(args.Length(), 0);
895
896
  long version =  // NOLINT(runtime/int)
897
11
    SSL_CTX_get_max_proto_version(sc->ctx_.get());
898
22
  args.GetReturnValue().Set(static_cast<uint32_t>(version));
899
}
900
901
922
void SecureContext::SetOptions(const FunctionCallbackInfo<Value>& args) {
902
922
  Environment* env = Environment::GetCurrent(args);
903
  SecureContext* sc;
904
922
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
905
906
922
  CHECK_GE(args.Length(), 1);
907
922
  CHECK(args[0]->IsNumber());
908
909
922
  int64_t val = args[0]->IntegerValue(env->context()).FromMaybe(0);
910
911
922
  SSL_CTX_set_options(sc->ctx_.get(),
912
                      static_cast<long>(val));  // NOLINT(runtime/int)
913
}
914
915
851
void SecureContext::SetSessionIdContext(
916
    const FunctionCallbackInfo<Value>& args) {
917
  SecureContext* sc;
918
1702
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
919
851
  Environment* env = sc->env();
920
921
851
  CHECK_GE(args.Length(), 1);
922
1702
  CHECK(args[0]->IsString());
923
924
851
  const Utf8Value sessionIdContext(env->isolate(), args[0]);
925
  const unsigned char* sid_ctx =
926
851
      reinterpret_cast<const unsigned char*>(*sessionIdContext);
927
851
  unsigned int sid_ctx_len = sessionIdContext.length();
928
929
851
  if (SSL_CTX_set_session_id_context(sc->ctx_.get(), sid_ctx, sid_ctx_len) == 1)
930
851
    return;
931
932
  BUF_MEM* mem;
933
  Local<String> message;
934
935
  BIOPointer bio(BIO_new(BIO_s_mem()));
936
  if (!bio) {
937
    message = FIXED_ONE_BYTE_STRING(env->isolate(),
938
                                    "SSL_CTX_set_session_id_context error");
939
  } else {
940
    ERR_print_errors(bio.get());
941
    BIO_get_mem_ptr(bio.get(), &mem);
942
    message = OneByteString(env->isolate(), mem->data, mem->length);
943
  }
944
945
  env->isolate()->ThrowException(Exception::TypeError(message));
946
}
947
948
1
void SecureContext::SetSessionTimeout(const FunctionCallbackInfo<Value>& args) {
949
  SecureContext* sc;
950
1
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
951
952
1
  CHECK_GE(args.Length(), 1);
953
1
  CHECK(args[0]->IsInt32());
954
955
2
  int32_t sessionTimeout = args[0].As<Int32>()->Value();
956
1
  SSL_CTX_set_timeout(sc->ctx_.get(), sessionTimeout);
957
}
958
959
void SecureContext::Close(const FunctionCallbackInfo<Value>& args) {
960
  SecureContext* sc;
961
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
962
  sc->Reset();
963
}
964
965
// Takes .pfx or .p12 and password in string or buffer format
966
18
void SecureContext::LoadPKCS12(const FunctionCallbackInfo<Value>& args) {
967
18
  Environment* env = Environment::GetCurrent(args);
968
969
18
  std::vector<char> pass;
970
18
  bool ret = false;
971
972
  SecureContext* sc;
973
18
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
974
  ClearErrorOnReturn clear_error_on_return;
975
976
18
  if (args.Length() < 1) {
977
    return THROW_ERR_MISSING_ARGS(env, "PFX certificate argument is mandatory");
978
  }
979
980
18
  BIOPointer in(LoadBIO(env, args[0]));
981
18
  if (!in) {
982
    return THROW_ERR_CRYPTO_OPERATION_FAILED(
983
        env, "Unable to load PFX certificate");
984
  }
985
986
18
  if (args.Length() >= 2) {
987
15
    THROW_AND_RETURN_IF_NOT_BUFFER(env, args[1], "Pass phrase");
988
30
    Local<ArrayBufferView> abv = args[1].As<ArrayBufferView>();
989
15
    size_t passlen = abv->ByteLength();
990
15
    pass.resize(passlen + 1);
991
15
    abv->CopyContents(pass.data(), passlen);
992
15
    pass[passlen] = '\0';
993
  }
994
995
  // Free previous certs
996
18
  sc->issuer_.reset();
997
18
  sc->cert_.reset();
998
999
18
  X509_STORE* cert_store = SSL_CTX_get_cert_store(sc->ctx_.get());
1000
1001
18
  DeleteFnPtr<PKCS12, PKCS12_free> p12;
1002
18
  EVPKeyPointer pkey;
1003
18
  X509Pointer cert;
1004
18
  StackOfX509 extra_certs;
1005
1006
18
  PKCS12* p12_ptr = nullptr;
1007
18
  EVP_PKEY* pkey_ptr = nullptr;
1008
18
  X509* cert_ptr = nullptr;
1009
18
  STACK_OF(X509)* extra_certs_ptr = nullptr;
1010
18
  if (d2i_PKCS12_bio(in.get(), &p12_ptr) &&
1011
32
      (p12.reset(p12_ptr), true) &&  // Move ownership to the smart pointer.
1012
16
      PKCS12_parse(p12.get(), pass.data(),
1013
                   &pkey_ptr,
1014
                   &cert_ptr,
1015
                   &extra_certs_ptr) &&
1016
12
      (pkey.reset(pkey_ptr), cert.reset(cert_ptr),
1017
24
       extra_certs.reset(extra_certs_ptr), true) &&  // Move ownership.
1018
12
      SSL_CTX_use_certificate_chain(sc->ctx_.get(),
1019
12
                                    std::move(cert),
1020
                                    extra_certs.get(),
1021
12
                                    &sc->cert_,
1022

46
                                    &sc->issuer_) &&
1023
12
      SSL_CTX_use_PrivateKey(sc->ctx_.get(), pkey.get())) {
1024
    // Add CA certs too
1025
21
    for (int i = 0; i < sk_X509_num(extra_certs.get()); i++) {
1026
9
      X509* ca = sk_X509_value(extra_certs.get(), i);
1027
1028
9
      if (cert_store == root_cert_store) {
1029
6
        cert_store = NewRootCertStore();
1030
6
        SSL_CTX_set_cert_store(sc->ctx_.get(), cert_store);
1031
      }
1032
9
      X509_STORE_add_cert(cert_store, ca);
1033
9
      SSL_CTX_add_client_CA(sc->ctx_.get(), ca);
1034
    }
1035
12
    ret = true;
1036
  }
1037
1038
18
  if (!ret) {
1039
    // TODO(@jasnell): Should this use ThrowCryptoError?
1040
6
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
1041
6
    const char* str = ERR_reason_error_string(err);
1042
6
    str = str != nullptr ? str : "Unknown error";
1043
1044
6
    return env->ThrowError(str);
1045
  }
1046
}
1047
1048
#ifndef OPENSSL_NO_ENGINE
1049
void SecureContext::SetClientCertEngine(
1050
    const FunctionCallbackInfo<Value>& args) {
1051
  Environment* env = Environment::GetCurrent(args);
1052
  CHECK_EQ(args.Length(), 1);
1053
  CHECK(args[0]->IsString());
1054
1055
  SecureContext* sc;
1056
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1057
1058
  MarkPopErrorOnReturn mark_pop_error_on_return;
1059
1060
  // SSL_CTX_set_client_cert_engine does not itself support multiple
1061
  // calls by cleaning up before overwriting the client_cert_engine
1062
  // internal context variable.
1063
  // Instead of trying to fix up this problem we in turn also do not
1064
  // support multiple calls to SetClientCertEngine.
1065
  CHECK(!sc->client_cert_engine_provided_);
1066
1067
  CryptoErrorStore errors;
1068
  const Utf8Value engine_id(env->isolate(), args[0]);
1069
  EnginePointer engine = LoadEngineById(*engine_id, &errors);
1070
  if (!engine) {
1071
    Local<Value> exception;
1072
    if (errors.ToException(env).ToLocal(&exception))
1073
      env->isolate()->ThrowException(exception);
1074
    return;
1075
  }
1076
1077
  // Note that this takes another reference to `engine`.
1078
  if (!SSL_CTX_set_client_cert_engine(sc->ctx_.get(), engine.get()))
1079
    return ThrowCryptoError(env, ERR_get_error());
1080
  sc->client_cert_engine_provided_ = true;
1081
}
1082
#endif  // !OPENSSL_NO_ENGINE
1083
1084
10
void SecureContext::GetTicketKeys(const FunctionCallbackInfo<Value>& args) {
1085
#if !defined(OPENSSL_NO_TLSEXT) && defined(SSL_CTX_get_tlsext_ticket_keys)
1086
1087
  SecureContext* wrap;
1088
10
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1089
1090
  Local<Object> buff;
1091
20
  if (!Buffer::New(wrap->env(), 48).ToLocal(&buff))
1092
    return;
1093
1094
10
  memcpy(Buffer::Data(buff), wrap->ticket_key_name_, 16);
1095
10
  memcpy(Buffer::Data(buff) + 16, wrap->ticket_key_hmac_, 16);
1096
10
  memcpy(Buffer::Data(buff) + 32, wrap->ticket_key_aes_, 16);
1097
1098
20
  args.GetReturnValue().Set(buff);
1099
#endif  // !def(OPENSSL_NO_TLSEXT) && def(SSL_CTX_get_tlsext_ticket_keys)
1100
}
1101
1102
23
void SecureContext::SetTicketKeys(const FunctionCallbackInfo<Value>& args) {
1103
#if !defined(OPENSSL_NO_TLSEXT) && defined(SSL_CTX_get_tlsext_ticket_keys)
1104
  SecureContext* wrap;
1105
23
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1106
1107
23
  CHECK_GE(args.Length(), 1);  // Ticket keys argument is mandatory
1108
23
  CHECK(args[0]->IsArrayBufferView());
1109
46
  ArrayBufferViewContents<char> buf(args[0].As<ArrayBufferView>());
1110
1111
23
  CHECK_EQ(buf.length(), 48);
1112
1113
23
  memcpy(wrap->ticket_key_name_, buf.data(), 16);
1114
23
  memcpy(wrap->ticket_key_hmac_, buf.data() + 16, 16);
1115
23
  memcpy(wrap->ticket_key_aes_, buf.data() + 32, 16);
1116
1117
46
  args.GetReturnValue().Set(true);
1118
#endif  // !def(OPENSSL_NO_TLSEXT) && def(SSL_CTX_get_tlsext_ticket_keys)
1119
}
1120
1121
// Currently, EnableTicketKeyCallback and TicketKeyCallback are only present for
1122
// the regression test in test/parallel/test-https-resume-after-renew.js.
1123
1
void SecureContext::EnableTicketKeyCallback(
1124
    const FunctionCallbackInfo<Value>& args) {
1125
  SecureContext* wrap;
1126
1
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1127
1128
1
  SSL_CTX_set_tlsext_ticket_key_cb(wrap->ctx_.get(), TicketKeyCallback);
1129
}
1130
1131
4
int SecureContext::TicketKeyCallback(SSL* ssl,
1132
                                     unsigned char* name,
1133
                                     unsigned char* iv,
1134
                                     EVP_CIPHER_CTX* ectx,
1135
                                     HMAC_CTX* hctx,
1136
                                     int enc) {
1137
  static const int kTicketPartSize = 16;
1138
1139
  SecureContext* sc = static_cast<SecureContext*>(
1140
4
      SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
1141
1142
4
  Environment* env = sc->env();
1143
8
  HandleScope handle_scope(env->isolate());
1144
4
  Context::Scope context_scope(env->context());
1145
1146
16
  Local<Value> argv[3];
1147
1148
8
  if (!Buffer::Copy(
1149
          env,
1150
          reinterpret_cast<char*>(name),
1151
12
          kTicketPartSize).ToLocal(&argv[0]) ||
1152
4
      !Buffer::Copy(
1153
          env,
1154
          reinterpret_cast<char*>(iv),
1155
8
          kTicketPartSize).ToLocal(&argv[1])) {
1156
    return -1;
1157
  }
1158
1159
8
  argv[2] = enc != 0 ? v8::True(env->isolate()) : v8::False(env->isolate());
1160
1161
  Local<Value> ret;
1162
8
  if (!node::MakeCallback(
1163
          env->isolate(),
1164
          sc->object(),
1165
          env->ticketkeycallback_string(),
1166
4
          arraysize(argv),
1167
          argv,
1168

12
          {0, 0}).ToLocal(&ret) ||
1169
4
      !ret->IsArray()) {
1170
    return -1;
1171
  }
1172
4
  Local<Array> arr = ret.As<Array>();
1173
1174
  Local<Value> val;
1175

12
  if (!arr->Get(env->context(), kTicketKeyReturnIndex).ToLocal(&val) ||
1176
4
      !val->IsInt32()) {
1177
    return -1;
1178
  }
1179
1180
4
  int r = val.As<Int32>()->Value();
1181
4
  if (r < 0)
1182
    return r;
1183
1184
  Local<Value> hmac;
1185
  Local<Value> aes;
1186
1187
4
  if (!arr->Get(env->context(), kTicketKeyHMACIndex).ToLocal(&hmac) ||
1188


16
      !arr->Get(env->context(), kTicketKeyAESIndex).ToLocal(&aes) ||
1189
4
      Buffer::Length(aes) != kTicketPartSize) {
1190
    return -1;
1191
  }
1192
1193
4
  if (enc) {
1194
    Local<Value> name_val;
1195
    Local<Value> iv_val;
1196
3
    if (!arr->Get(env->context(), kTicketKeyNameIndex).ToLocal(&name_val) ||
1197

9
        !arr->Get(env->context(), kTicketKeyIVIndex).ToLocal(&iv_val) ||
1198

9
        Buffer::Length(name_val) != kTicketPartSize ||
1199
3
        Buffer::Length(iv_val) != kTicketPartSize) {
1200
      return -1;
1201
    }
1202
1203
3
    name_val.As<ArrayBufferView>()->CopyContents(name, kTicketPartSize);
1204
3
    iv_val.As<ArrayBufferView>()->CopyContents(iv, kTicketPartSize);
1205
  }
1206
1207
4
  ArrayBufferViewContents<unsigned char> hmac_buf(hmac);
1208
8
  HMAC_Init_ex(hctx,
1209
4
               hmac_buf.data(),
1210
4
               hmac_buf.length(),
1211
               EVP_sha256(),
1212
               nullptr);
1213
1214
4
  ArrayBufferViewContents<unsigned char> aes_key(aes.As<ArrayBufferView>());
1215
4
  if (enc) {
1216
3
    EVP_EncryptInit_ex(ectx,
1217
                       EVP_aes_128_cbc(),
1218
                       nullptr,
1219
                       aes_key.data(),
1220
                       iv);
1221
  } else {
1222
1
    EVP_DecryptInit_ex(ectx,
1223
                       EVP_aes_128_cbc(),
1224
                       nullptr,
1225
                       aes_key.data(),
1226
                       iv);
1227
  }
1228
1229
4
  return r;
1230
}
1231
1232
1336
int SecureContext::TicketCompatibilityCallback(SSL* ssl,
1233
                                               unsigned char* name,
1234
                                               unsigned char* iv,
1235
                                               EVP_CIPHER_CTX* ectx,
1236
                                               HMAC_CTX* hctx,
1237
                                               int enc) {
1238
  SecureContext* sc = static_cast<SecureContext*>(
1239
1336
      SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
1240
1241
1336
  if (enc) {
1242
1276
    memcpy(name, sc->ticket_key_name_, sizeof(sc->ticket_key_name_));
1243
2552
    if (CSPRNG(iv, 16).is_err() ||
1244
1276
        EVP_EncryptInit_ex(
1245

2552
            ectx, EVP_aes_128_cbc(), nullptr, sc->ticket_key_aes_, iv) <= 0 ||
1246
1276
        HMAC_Init_ex(hctx,
1247
1276
                     sc->ticket_key_hmac_,
1248
                     sizeof(sc->ticket_key_hmac_),
1249
                     EVP_sha256(),
1250
                     nullptr) <= 0) {
1251
      return -1;
1252
    }
1253
1276
    return 1;
1254
  }
1255
1256
60
  if (memcmp(name, sc->ticket_key_name_, sizeof(sc->ticket_key_name_)) != 0) {
1257
    // The ticket key name does not match. Discard the ticket.
1258
9
    return 0;
1259
  }
1260
1261
51
  if (EVP_DecryptInit_ex(ectx, EVP_aes_128_cbc(), nullptr, sc->ticket_key_aes_,
1262

102
                         iv) <= 0 ||
1263
51
      HMAC_Init_ex(hctx, sc->ticket_key_hmac_, sizeof(sc->ticket_key_hmac_),
1264
                   EVP_sha256(), nullptr) <= 0) {
1265
    return -1;
1266
  }
1267
51
  return 1;
1268
}
1269
1270
2
void SecureContext::CtxGetter(const FunctionCallbackInfo<Value>& info) {
1271
  SecureContext* sc;
1272
2
  ASSIGN_OR_RETURN_UNWRAP(&sc, info.This());
1273
4
  Local<External> ext = External::New(info.GetIsolate(), sc->ctx_.get());
1274
4
  info.GetReturnValue().Set(ext);
1275
}
1276
1277
template <bool primary>
1278
12
void SecureContext::GetCertificate(const FunctionCallbackInfo<Value>& args) {
1279
  SecureContext* wrap;
1280
12
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1281
12
  Environment* env = wrap->env();
1282
  X509* cert;
1283
1284
  if (primary)
1285
6
    cert = wrap->cert_.get();
1286
  else
1287
6
    cert = wrap->issuer_.get();
1288
12
  if (cert == nullptr)
1289
    return args.GetReturnValue().SetNull();
1290
1291
12
  int size = i2d_X509(cert, nullptr);
1292
  Local<Object> buff;
1293
24
  if (!Buffer::New(env, size).ToLocal(&buff))
1294
    return;
1295
12
  unsigned char* serialized = reinterpret_cast<unsigned char*>(
1296
12
      Buffer::Data(buff));
1297
12
  i2d_X509(cert, &serialized);
1298
1299
24
  args.GetReturnValue().Set(buff);
1300
}
1301
1302
namespace {
1303
4
unsigned long AddCertsFromFile(  // NOLINT(runtime/int)
1304
    X509_STORE* store,
1305
    const char* file) {
1306
4
  ERR_clear_error();
1307
8
  MarkPopErrorOnReturn mark_pop_error_on_return;
1308
1309
8
  BIOPointer bio(BIO_new_file(file, "r"));
1310
4
  if (!bio)
1311
1
    return ERR_get_error();
1312
1313
  while (X509Pointer x509 = X509Pointer(PEM_read_bio_X509(
1314
6
             bio.get(), nullptr, NoPasswordCallback, nullptr))) {
1315
3
    X509_STORE_add_cert(store, x509.get());
1316
3
  }
1317
1318
3
  unsigned long err = ERR_peek_error();  // NOLINT(runtime/int)
1319
  // Ignore error if its EOF/no start line found.
1320

6
  if (ERR_GET_LIB(err) == ERR_LIB_PEM &&
1321
3
      ERR_GET_REASON(err) == PEM_R_NO_START_LINE) {
1322
3
    return 0;
1323
  }
1324
1325
  return err;
1326
}
1327
}  // namespace
1328
1329
// UseExtraCaCerts is called only once at the start of the Node.js process.
1330
4
void UseExtraCaCerts(const std::string& file) {
1331
4
  ClearErrorOnReturn clear_error_on_return;
1332
1333
4
  if (root_cert_store == nullptr) {
1334
4
    root_cert_store = NewRootCertStore();
1335
1336
4
    if (!file.empty()) {
1337
4
      unsigned long err = AddCertsFromFile(  // NOLINT(runtime/int)
1338
                                           root_cert_store,
1339
                                           file.c_str());
1340
4
      if (err) {
1341
1
        fprintf(stderr,
1342
                "Warning: Ignoring extra certs from `%s`, load failed: %s\n",
1343
                file.c_str(),
1344
                ERR_error_string(err, nullptr));
1345
      } else {
1346
3
        extra_root_certs_loaded = true;
1347
      }
1348
    }
1349
  }
1350
4
}
1351
1352
// Exposed to JavaScript strictly for testing purposes.
1353
3
void IsExtraRootCertsFileLoaded(
1354
    const FunctionCallbackInfo<Value>& args) {
1355
6
  return args.GetReturnValue().Set(extra_root_certs_loaded);
1356
}
1357
1358
}  // namespace crypto
1359
}  // namespace node