GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: crypto/crypto_context.cc Lines: 602 717 84.0 %
Date: 2022-09-25 04:23:55 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
787
Local<FunctionTemplate> SecureContext::GetConstructorTemplate(
257
    Environment* env) {
258
787
  Local<FunctionTemplate> tmpl = env->secure_context_constructor_template();
259
787
  if (tmpl.IsEmpty()) {
260
787
    Isolate* isolate = env->isolate();
261
787
    tmpl = NewFunctionTemplate(isolate, New);
262
1574
    tmpl->InstanceTemplate()->SetInternalFieldCount(
263
        SecureContext::kInternalFieldCount);
264
787
    tmpl->Inherit(BaseObject::GetConstructorTemplate(env));
265
787
    tmpl->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "SecureContext"));
266
267
787
    SetProtoMethod(isolate, tmpl, "init", Init);
268
787
    SetProtoMethod(isolate, tmpl, "setKey", SetKey);
269
787
    SetProtoMethod(isolate, tmpl, "setCert", SetCert);
270
787
    SetProtoMethod(isolate, tmpl, "addCACert", AddCACert);
271
787
    SetProtoMethod(isolate, tmpl, "addCRL", AddCRL);
272
787
    SetProtoMethod(isolate, tmpl, "addRootCerts", AddRootCerts);
273
787
    SetProtoMethod(isolate, tmpl, "setCipherSuites", SetCipherSuites);
274
787
    SetProtoMethod(isolate, tmpl, "setCiphers", SetCiphers);
275
787
    SetProtoMethod(isolate, tmpl, "setSigalgs", SetSigalgs);
276
787
    SetProtoMethod(isolate, tmpl, "setECDHCurve", SetECDHCurve);
277
787
    SetProtoMethod(isolate, tmpl, "setDHParam", SetDHParam);
278
787
    SetProtoMethod(isolate, tmpl, "setMaxProto", SetMaxProto);
279
787
    SetProtoMethod(isolate, tmpl, "setMinProto", SetMinProto);
280
787
    SetProtoMethod(isolate, tmpl, "getMaxProto", GetMaxProto);
281
787
    SetProtoMethod(isolate, tmpl, "getMinProto", GetMinProto);
282
787
    SetProtoMethod(isolate, tmpl, "setOptions", SetOptions);
283
787
    SetProtoMethod(isolate, tmpl, "setSessionIdContext", SetSessionIdContext);
284
787
    SetProtoMethod(isolate, tmpl, "setSessionTimeout", SetSessionTimeout);
285
787
    SetProtoMethod(isolate, tmpl, "close", Close);
286
787
    SetProtoMethod(isolate, tmpl, "loadPKCS12", LoadPKCS12);
287
787
    SetProtoMethod(isolate, tmpl, "setTicketKeys", SetTicketKeys);
288
787
    SetProtoMethod(
289
        isolate, tmpl, "enableTicketKeyCallback", EnableTicketKeyCallback);
290
291
787
    SetProtoMethodNoSideEffect(isolate, tmpl, "getTicketKeys", GetTicketKeys);
292
787
    SetProtoMethodNoSideEffect(
293
        isolate, tmpl, "getCertificate", GetCertificate<true>);
294
787
    SetProtoMethodNoSideEffect(
295
        isolate, tmpl, "getIssuer", GetCertificate<false>);
296
297
#ifndef OPENSSL_NO_ENGINE
298
787
    SetProtoMethod(isolate, tmpl, "setEngineKey", SetEngineKey);
299
787
    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
2361
    SET_INTEGER_CONSTANTS("kTicketKeyReturnIndex", kTicketKeyReturnIndex);
306
2361
    SET_INTEGER_CONSTANTS("kTicketKeyHMACIndex", kTicketKeyHMACIndex);
307
2361
    SET_INTEGER_CONSTANTS("kTicketKeyAESIndex", kTicketKeyAESIndex);
308
2361
    SET_INTEGER_CONSTANTS("kTicketKeyNameIndex", kTicketKeyNameIndex);
309
2361
    SET_INTEGER_CONSTANTS("kTicketKeyIVIndex", kTicketKeyIVIndex);
310
  #undef SET_INTEGER_CONSTANTS
311
312
    Local<FunctionTemplate> ctx_getter_templ = FunctionTemplate::New(
313
787
        isolate, CtxGetter, Local<Value>(), Signature::New(isolate, tmpl));
314
315
3148
    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
787
    env->set_secure_context_constructor_template(tmpl);
322
  }
323
787
  return tmpl;
324
}
325
326
787
void SecureContext::Initialize(Environment* env, Local<Object> target) {
327
787
  Local<Context> context = env->context();
328
787
  SetConstructorFunction(context,
329
                         target,
330
                         "SecureContext",
331
                         GetConstructorTemplate(env),
332
                         SetConstructorFunctionFlag::NONE);
333
334
787
  SetMethodNoSideEffect(
335
      context, target, "getRootCertificates", GetRootCertificates);
336
  // Exposed for testing purposes only.
337
787
  SetMethodNoSideEffect(context,
338
                        target,
339
                        "isExtraRootCertsFileLoaded",
340
                        IsExtraRootCertsFileLoaded);
341
787
}
342
343
5527
void SecureContext::RegisterExternalReferences(
344
    ExternalReferenceRegistry* registry) {
345
5527
  registry->Register(New);
346
5527
  registry->Register(Init);
347
5527
  registry->Register(SetKey);
348
5527
  registry->Register(SetCert);
349
5527
  registry->Register(AddCACert);
350
5527
  registry->Register(AddCRL);
351
5527
  registry->Register(AddRootCerts);
352
5527
  registry->Register(SetCipherSuites);
353
5527
  registry->Register(SetCiphers);
354
5527
  registry->Register(SetSigalgs);
355
5527
  registry->Register(SetECDHCurve);
356
5527
  registry->Register(SetDHParam);
357
5527
  registry->Register(SetMaxProto);
358
5527
  registry->Register(SetMinProto);
359
5527
  registry->Register(GetMaxProto);
360
5527
  registry->Register(GetMinProto);
361
5527
  registry->Register(SetOptions);
362
5527
  registry->Register(SetSessionIdContext);
363
5527
  registry->Register(SetSessionTimeout);
364
5527
  registry->Register(Close);
365
5527
  registry->Register(LoadPKCS12);
366
5527
  registry->Register(SetTicketKeys);
367
5527
  registry->Register(EnableTicketKeyCallback);
368
5527
  registry->Register(GetTicketKeys);
369
5527
  registry->Register(GetCertificate<true>);
370
5527
  registry->Register(GetCertificate<false>);
371
372
#ifndef OPENSSL_NO_ENGINE
373
5527
  registry->Register(SetEngineKey);
374
5527
  registry->Register(SetClientCertEngine);
375
#endif  // !OPENSSL_NO_ENGINE
376
377
5527
  registry->Register(CtxGetter);
378
379
5527
  registry->Register(GetRootCertificates);
380
5527
  registry->Register(IsExtraRootCertsFileLoaded);
381
5527
}
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
1594
  while (X509* x509 = 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);
709
969
    SSL_CTX_add_client_CA(sc->ctx_.get(), x509);
710
969
    X509_free(x509);
711
969
  }
712
}
713
714
2
void SecureContext::AddCRL(const FunctionCallbackInfo<Value>& args) {
715
2
  Environment* env = Environment::GetCurrent(args);
716
717
  SecureContext* sc;
718
3
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
719
720
2
  CHECK_GE(args.Length(), 1);  // CRL argument is mandatory
721
722
  ClearErrorOnReturn clear_error_on_return;
723
724
2
  BIOPointer bio(LoadBIO(env, args[0]));
725
2
  if (!bio)
726
    return;
727
728
  DeleteFnPtr<X509_CRL, X509_CRL_free> crl(
729
2
      PEM_read_bio_X509_CRL(bio.get(), nullptr, NoPasswordCallback, nullptr));
730
731
2
  if (!crl)
732
1
    return THROW_ERR_CRYPTO_OPERATION_FAILED(env, "Failed to parse CRL");
733
734
1
  X509_STORE* cert_store = SSL_CTX_get_cert_store(sc->ctx_.get());
735
1
  if (cert_store == root_cert_store) {
736
    cert_store = NewRootCertStore();
737
    SSL_CTX_set_cert_store(sc->ctx_.get(), cert_store);
738
  }
739
740
1
  X509_STORE_add_crl(cert_store, crl.get());
741
1
  X509_STORE_set_flags(cert_store,
742
                       X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
743
}
744
745
1843
void SecureContext::AddRootCerts(const FunctionCallbackInfo<Value>& args) {
746
  SecureContext* sc;
747
1843
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
748
1843
  ClearErrorOnReturn clear_error_on_return;
749
750
1843
  if (root_cert_store == nullptr) {
751
268
    root_cert_store = NewRootCertStore();
752
  }
753
754
  // Increment reference count so global store is not deleted along with CTX.
755
1843
  X509_STORE_up_ref(root_cert_store);
756
1843
  SSL_CTX_set_cert_store(sc->ctx_.get(), root_cert_store);
757
}
758
759
1910
void SecureContext::SetCipherSuites(const FunctionCallbackInfo<Value>& args) {
760
  // BoringSSL doesn't allow API config of TLS1.3 cipher suites.
761
#ifndef OPENSSL_IS_BORINGSSL
762
  SecureContext* sc;
763
1911
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
764
1910
  Environment* env = sc->env();
765
  ClearErrorOnReturn clear_error_on_return;
766
767
1910
  CHECK_EQ(args.Length(), 1);
768
3820
  CHECK(args[0]->IsString());
769
770
1910
  const Utf8Value ciphers(env->isolate(), args[0]);
771
1910
  if (!SSL_CTX_set_ciphersuites(sc->ctx_.get(), *ciphers))
772
1
    return ThrowCryptoError(env, ERR_get_error(), "Failed to set ciphers");
773
#endif
774
}
775
776
2374
void SecureContext::SetCiphers(const FunctionCallbackInfo<Value>& args) {
777
  SecureContext* sc;
778
2389
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
779
2374
  Environment* env = sc->env();
780
  ClearErrorOnReturn clear_error_on_return;
781
782
2374
  CHECK_EQ(args.Length(), 1);
783
4748
  CHECK(args[0]->IsString());
784
785
2374
  Utf8Value ciphers(env->isolate(), args[0]);
786
2374
  if (!SSL_CTX_set_cipher_list(sc->ctx_.get(), *ciphers)) {
787
15
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
788
789

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

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

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

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

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


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

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

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

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

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

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