GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: crypto/crypto_context.cc Lines: 572 681 84.0 %
Date: 2021-09-16 04:12:46 Branches: 289 468 61.8 %

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::Local;
35
using v8::Object;
36
using v8::PropertyAttribute;
37
using v8::ReadOnly;
38
using v8::Signature;
39
using v8::String;
40
using v8::Value;
41
42
namespace crypto {
43
static const char* const root_certs[] = {
44
#include "node_root_certs.h"  // NOLINT(build/include_order)
45
};
46
47
static const char system_cert_path[] = NODE_OPENSSL_SYSTEM_CERT_PATH;
48
49
static X509_STORE* root_cert_store;
50
51
static bool extra_root_certs_loaded = false;
52
53
// Takes a string or buffer and loads it into a BIO.
54
// Caller responsible for BIO_free_all-ing the returned object.
55
2331
BIOPointer LoadBIO(Environment* env, Local<Value> v) {
56
4662
  HandleScope scope(env->isolate());
57
58
4662
  if (v->IsString()) {
59
2656
    Utf8Value s(env->isolate(), v);
60
1328
    return NodeBIO::NewFixed(*s, s.length());
61
  }
62
63
1003
  if (v->IsArrayBufferView()) {
64
1003
    ArrayBufferViewContents<char> buf(v.As<ArrayBufferView>());
65
1003
    return NodeBIO::NewFixed(buf.data(), buf.length());
66
  }
67
68
  return nullptr;
69
}
70
71
namespace {
72
886
int SSL_CTX_use_certificate_chain(SSL_CTX* ctx,
73
                                  X509Pointer&& x,
74
                                  STACK_OF(X509)* extra_certs,
75
                                  X509Pointer* cert,
76
                                  X509Pointer* issuer_) {
77
886
  CHECK(!*issuer_);
78
886
  CHECK(!*cert);
79
886
  X509* issuer = nullptr;
80
81
886
  int ret = SSL_CTX_use_certificate(ctx, x.get());
82
83
886
  if (ret) {
84
    // If we could set up our certificate, now proceed to
85
    // the CA certificates.
86
886
    SSL_CTX_clear_extra_chain_certs(ctx);
87
88
1305
    for (int i = 0; i < sk_X509_num(extra_certs); i++) {
89
419
      X509* ca = sk_X509_value(extra_certs, i);
90
91
      // NOTE: Increments reference count on `ca`
92
419
      if (!SSL_CTX_add1_chain_cert(ctx, ca)) {
93
        ret = 0;
94
        issuer = nullptr;
95
        break;
96
      }
97
      // Note that we must not free r if it was successfully
98
      // added to the chain (while we must free the main
99
      // certificate, since its reference count is increased
100
      // by SSL_CTX_use_certificate).
101
102
      // Find issuer
103

419
      if (issuer != nullptr || X509_check_issued(ca, x.get()) != X509_V_OK)
104
4
        continue;
105
106
415
      issuer = ca;
107
    }
108
  }
109
110
  // Try getting issuer from a cert store
111
886
  if (ret) {
112
886
    if (issuer == nullptr) {
113
471
      ret = SSL_CTX_get_issuer(ctx, x.get(), &issuer);
114
471
      ret = ret < 0 ? 0 : 1;
115
      // NOTE: get_cert_store doesn't increment reference count,
116
      // no need to free `store`
117
    } else {
118
      // Increment issuer reference count
119
415
      issuer = X509_dup(issuer);
120
415
      if (issuer == nullptr) {
121
        ret = 0;
122
      }
123
    }
124
  }
125
126
886
  issuer_->reset(issuer);
127
128

886
  if (ret && x != nullptr) {
129
886
    cert->reset(X509_dup(x.get()));
130
886
    if (!*cert)
131
      ret = 0;
132
  }
133
886
  return ret;
134
}
135
136
// Read a file that contains our certificate in "PEM" format,
137
// possibly followed by a sequence of CA certificates that should be
138
// sent to the peer in the Certificate message.
139
//
140
// Taken from OpenSSL - edited for style.
141
874
int SSL_CTX_use_certificate_chain(SSL_CTX* ctx,
142
                                  BIOPointer&& in,
143
                                  X509Pointer* cert,
144
                                  X509Pointer* issuer) {
145
  // Just to ensure that `ERR_peek_last_error` below will return only errors
146
  // that we are interested in
147
874
  ERR_clear_error();
148
149
  X509Pointer x(
150
1748
      PEM_read_bio_X509_AUX(in.get(), nullptr, NoPasswordCallback, nullptr));
151
152
874
  if (!x)
153
    return 0;
154
155
874
  unsigned long err = 0;  // NOLINT(runtime/int)
156
157
1748
  StackOfX509 extra_certs(sk_X509_new_null());
158
874
  if (!extra_certs)
159
    return 0;
160
161
  while (X509Pointer extra {PEM_read_bio_X509(in.get(),
162
                                    nullptr,
163
                                    NoPasswordCallback,
164
1284
                                    nullptr)}) {
165
410
    if (sk_X509_push(extra_certs.get(), extra.get())) {
166
410
      extra.release();
167
410
      continue;
168
    }
169
170
    return 0;
171
410
  }
172
173
  // When the while loop ends, it's usually just EOF.
174
874
  err = ERR_peek_last_error();
175
874
  if (ERR_GET_LIB(err) == ERR_LIB_PEM &&
176
874
      ERR_GET_REASON(err) == PEM_R_NO_START_LINE) {
177
874
    ERR_clear_error();
178
  } else {
179
    // some real error
180
    return 0;
181
  }
182
183
1748
  return SSL_CTX_use_certificate_chain(ctx,
184
874
                                       std::move(x),
185
                                       extra_certs.get(),
186
                                       cert,
187
874
                                       issuer);
188
}
189
190
}  // namespace
191
192
276
X509_STORE* NewRootCertStore() {
193

276
  static std::vector<X509*> root_certs_vector;
194

276
  static Mutex root_certs_vector_mutex;
195
552
  Mutex::ScopedLock lock(root_certs_vector_mutex);
196
197

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

713
        sslmethod == "SSLv2_server_method" ||
402
348
        sslmethod == "SSLv2_client_method") {
403
17
      THROW_ERR_TLS_INVALID_PROTOCOL_METHOD(env, "SSLv2 methods disabled");
404
17
      return;
405
679
    } else if (sslmethod == "SSLv3_method" ||
406

679
               sslmethod == "SSLv3_server_method" ||
407
331
               sslmethod == "SSLv3_client_method") {
408
17
      THROW_ERR_TLS_INVALID_PROTOCOL_METHOD(env, "SSLv3 methods disabled");
409
17
      return;
410
330
    } else if (sslmethod == "SSLv23_method") {
411
36
      max_version = TLS1_2_VERSION;
412
294
    } else if (sslmethod == "SSLv23_server_method") {
413
1
      max_version = TLS1_2_VERSION;
414
1
      method = TLS_server_method();
415
293
    } else if (sslmethod == "SSLv23_client_method") {
416
1
      max_version = TLS1_2_VERSION;
417
1
      method = TLS_client_method();
418
292
    } else if (sslmethod == "TLS_method") {
419
53
      min_version = 0;
420
53
      max_version = kMaxSupportedVersion;
421
239
    } else if (sslmethod == "TLS_server_method") {
422
      min_version = 0;
423
      max_version = kMaxSupportedVersion;
424
      method = TLS_server_method();
425
239
    } else if (sslmethod == "TLS_client_method") {
426
      min_version = 0;
427
      max_version = kMaxSupportedVersion;
428
      method = TLS_client_method();
429
239
    } else if (sslmethod == "TLSv1_method") {
430
71
      min_version = TLS1_VERSION;
431
71
      max_version = TLS1_VERSION;
432
168
    } else if (sslmethod == "TLSv1_server_method") {
433
1
      min_version = TLS1_VERSION;
434
1
      max_version = TLS1_VERSION;
435
1
      method = TLS_server_method();
436
167
    } else if (sslmethod == "TLSv1_client_method") {
437
1
      min_version = TLS1_VERSION;
438
1
      max_version = TLS1_VERSION;
439
1
      method = TLS_client_method();
440
166
    } else if (sslmethod == "TLSv1_1_method") {
441
71
      min_version = TLS1_1_VERSION;
442
71
      max_version = TLS1_1_VERSION;
443
95
    } else if (sslmethod == "TLSv1_1_server_method") {
444
1
      min_version = TLS1_1_VERSION;
445
1
      max_version = TLS1_1_VERSION;
446
1
      method = TLS_server_method();
447
94
    } else if (sslmethod == "TLSv1_1_client_method") {
448
1
      min_version = TLS1_1_VERSION;
449
1
      max_version = TLS1_1_VERSION;
450
1
      method = TLS_client_method();
451
93
    } else if (sslmethod == "TLSv1_2_method") {
452
75
      min_version = TLS1_2_VERSION;
453
75
      max_version = TLS1_2_VERSION;
454
18
    } else if (sslmethod == "TLSv1_2_server_method") {
455
2
      min_version = TLS1_2_VERSION;
456
2
      max_version = TLS1_2_VERSION;
457
2
      method = TLS_server_method();
458
16
    } else if (sslmethod == "TLSv1_2_client_method") {
459
1
      min_version = TLS1_2_VERSION;
460
1
      max_version = TLS1_2_VERSION;
461
1
      method = TLS_client_method();
462
    } else {
463
15
      const std::string msg("Unknown method: ");
464
15
      THROW_ERR_TLS_INVALID_PROTOCOL_METHOD(env, (msg + * sslmethod).c_str());
465
15
      return;
466
    }
467
  }
468
469
2311
  sc->ctx_.reset(SSL_CTX_new(method));
470
2311
  SSL_CTX_set_app_data(sc->ctx_.get(), sc);
471
472
  // Disable SSLv2 in the case when method == TLS_method() and the
473
  // cipher list contains SSLv2 ciphers (not the default, should be rare.)
474
  // The bundled OpenSSL doesn't have SSLv2 support but the system OpenSSL may.
475
  // SSLv3 is disabled because it's susceptible to downgrade attacks (POODLE.)
476
2311
  SSL_CTX_set_options(sc->ctx_.get(), SSL_OP_NO_SSLv2);
477
2311
  SSL_CTX_set_options(sc->ctx_.get(), SSL_OP_NO_SSLv3);
478
#if OPENSSL_VERSION_MAJOR >= 3
479
  SSL_CTX_set_options(sc->ctx_.get(), SSL_OP_ALLOW_CLIENT_RENEGOTIATION);
480
#endif
481
482
  // Enable automatic cert chaining. This is enabled by default in OpenSSL, but
483
  // disabled by default in BoringSSL. Enable it explicitly to make the
484
  // behavior match when Node is built with BoringSSL.
485
2311
  SSL_CTX_clear_mode(sc->ctx_.get(), SSL_MODE_NO_AUTO_CHAIN);
486
487
  // SSL session cache configuration
488
2311
  SSL_CTX_set_session_cache_mode(sc->ctx_.get(),
489
                                 SSL_SESS_CACHE_CLIENT |
490
                                 SSL_SESS_CACHE_SERVER |
491
                                 SSL_SESS_CACHE_NO_INTERNAL |
492
                                 SSL_SESS_CACHE_NO_AUTO_CLEAR);
493
494
2311
  SSL_CTX_set_min_proto_version(sc->ctx_.get(), min_version);
495
2311
  SSL_CTX_set_max_proto_version(sc->ctx_.get(), max_version);
496
497
  // OpenSSL 1.1.0 changed the ticket key size, but the OpenSSL 1.0.x size was
498
  // exposed in the public API. To retain compatibility, install a callback
499
  // which restores the old algorithm.
500
4622
  if (RAND_bytes(sc->ticket_key_name_, sizeof(sc->ticket_key_name_)) <= 0 ||
501

4622
      RAND_bytes(sc->ticket_key_hmac_, sizeof(sc->ticket_key_hmac_)) <= 0 ||
502
2311
      RAND_bytes(sc->ticket_key_aes_, sizeof(sc->ticket_key_aes_)) <= 0) {
503
    return THROW_ERR_CRYPTO_OPERATION_FAILED(
504
        env, "Error generating ticket keys");
505
  }
506
2311
  SSL_CTX_set_tlsext_ticket_key_cb(sc->ctx_.get(), TicketCompatibilityCallback);
507
}
508
509
12248
SSLPointer SecureContext::CreateSSL() {
510
12248
  return SSLPointer(SSL_new(ctx_.get()));
511
}
512
513
12248
void SecureContext::SetNewSessionCallback(NewSessionCb cb) {
514
12248
  SSL_CTX_sess_set_new_cb(ctx_.get(), cb);
515
12248
}
516
517
12248
void SecureContext::SetGetSessionCallback(GetSessionCb cb) {
518
12248
  SSL_CTX_sess_set_get_cb(ctx_.get(), cb);
519
12248
}
520
521
874
void SecureContext::SetSelectSNIContextCallback(SelectSNIContextCb cb) {
522
874
  SSL_CTX_set_tlsext_servername_callback(ctx_.get(), cb);
523
874
}
524
525
8
void SecureContext::SetKeylogCallback(KeylogCb cb) {
526
8
  SSL_CTX_set_keylog_callback(ctx_.get(), cb);
527
8
}
528
529
856
void SecureContext::SetKey(const FunctionCallbackInfo<Value>& args) {
530
856
  Environment* env = Environment::GetCurrent(args);
531
532
  SecureContext* sc;
533
864
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
534
535
856
  CHECK_GE(args.Length(), 1);  // Private key argument is mandatory
536
537
856
  BIOPointer bio(LoadBIO(env, args[0]));
538
856
  if (!bio)
539
    return;
540
541
856
  ByteSource passphrase;
542
1712
  if (args[1]->IsString())
543
48
    passphrase = ByteSource::FromString(env, args[1].As<String>());
544
  // This redirection is necessary because the PasswordCallback expects a
545
  // pointer to a pointer to the passphrase ByteSource to allow passing in
546
  // const ByteSources.
547
856
  const ByteSource* pass_ptr = &passphrase;
548
549
  EVPKeyPointer key(
550
      PEM_read_bio_PrivateKey(bio.get(),
551
                              nullptr,
552
                              PasswordCallback,
553
856
                              &pass_ptr));
554
555
856
  if (!key)
556
7
    return ThrowCryptoError(env, ERR_get_error(), "PEM_read_bio_PrivateKey");
557
558
849
  if (!SSL_CTX_use_PrivateKey(sc->ctx_.get(), key.get()))
559
1
    return ThrowCryptoError(env, ERR_get_error(), "SSL_CTX_use_PrivateKey");
560
}
561
562
8
void SecureContext::SetSigalgs(const FunctionCallbackInfo<Value>& args) {
563
  SecureContext* sc;
564
8
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
565
8
  Environment* env = sc->env();
566
  ClearErrorOnReturn clear_error_on_return;
567
568
8
  CHECK_EQ(args.Length(), 1);
569
16
  CHECK(args[0]->IsString());
570
571
8
  const Utf8Value sigalgs(env->isolate(), args[0]);
572
573
8
  if (!SSL_CTX_set1_sigalgs_list(sc->ctx_.get(), *sigalgs))
574
    return ThrowCryptoError(env, ERR_get_error());
575
}
576
577
#ifndef OPENSSL_NO_ENGINE
578
void SecureContext::SetEngineKey(const FunctionCallbackInfo<Value>& args) {
579
  Environment* env = Environment::GetCurrent(args);
580
581
  SecureContext* sc;
582
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
583
584
  CHECK_EQ(args.Length(), 2);
585
586
  CryptoErrorStore errors;
587
  Utf8Value engine_id(env->isolate(), args[1]);
588
  EnginePointer engine = LoadEngineById(*engine_id, &errors);
589
  if (!engine) {
590
    Local<Value> exception;
591
    if (errors.ToException(env).ToLocal(&exception))
592
      env->isolate()->ThrowException(exception);
593
    return;
594
  }
595
596
  if (!ENGINE_init(engine.get())) {
597
    return THROW_ERR_CRYPTO_OPERATION_FAILED(
598
        env, "Failure to initialize engine");
599
  }
600
601
  engine.finish_on_exit = true;
602
603
  Utf8Value key_name(env->isolate(), args[0]);
604
  EVPKeyPointer key(ENGINE_load_private_key(engine.get(), *key_name,
605
                                            nullptr, nullptr));
606
607
  if (!key)
608
    return ThrowCryptoError(env, ERR_get_error(), "ENGINE_load_private_key");
609
610
  if (!SSL_CTX_use_PrivateKey(sc->ctx_.get(), key.get()))
611
    return ThrowCryptoError(env, ERR_get_error(), "SSL_CTX_use_PrivateKey");
612
613
  sc->private_key_engine_ = std::move(engine);
614
}
615
#endif  // !OPENSSL_NO_ENGINE
616
617
874
void SecureContext::SetCert(const FunctionCallbackInfo<Value>& args) {
618
874
  Environment* env = Environment::GetCurrent(args);
619
620
  SecureContext* sc;
621
874
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
622
623
874
  CHECK_GE(args.Length(), 1);  // Certificate argument is mandator
624
625
874
  BIOPointer bio(LoadBIO(env, args[0]));
626
874
  if (!bio)
627
    return;
628
629
874
  sc->cert_.reset();
630
874
  sc->issuer_.reset();
631
632
874
  if (!SSL_CTX_use_certificate_chain(
633
874
          sc->ctx_.get(),
634
874
          std::move(bio),
635
874
          &sc->cert_,
636
874
          &sc->issuer_)) {
637
    return ThrowCryptoError(
638
        env,
639
        ERR_get_error(),
640
        "SSL_CTX_use_certificate_chain");
641
  }
642
}
643
644
569
void SecureContext::AddCACert(const FunctionCallbackInfo<Value>& args) {
645
569
  Environment* env = Environment::GetCurrent(args);
646
647
  SecureContext* sc;
648
569
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
649
  ClearErrorOnReturn clear_error_on_return;
650
651
569
  CHECK_GE(args.Length(), 1);  // CA certificate argument is mandatory
652
653
569
  BIOPointer bio(LoadBIO(env, args[0]));
654
569
  if (!bio)
655
    return;
656
657
569
  X509_STORE* cert_store = SSL_CTX_get_cert_store(sc->ctx_.get());
658
1480
  while (X509* x509 = PEM_read_bio_X509_AUX(
659
1480
      bio.get(), nullptr, NoPasswordCallback, nullptr)) {
660
911
    if (cert_store == root_cert_store) {
661
1
      cert_store = NewRootCertStore();
662
1
      SSL_CTX_set_cert_store(sc->ctx_.get(), cert_store);
663
    }
664
911
    X509_STORE_add_cert(cert_store, x509);
665
911
    SSL_CTX_add_client_CA(sc->ctx_.get(), x509);
666
911
    X509_free(x509);
667
911
  }
668
}
669
670
2
void SecureContext::AddCRL(const FunctionCallbackInfo<Value>& args) {
671
2
  Environment* env = Environment::GetCurrent(args);
672
673
  SecureContext* sc;
674
3
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
675
676
2
  CHECK_GE(args.Length(), 1);  // CRL argument is mandatory
677
678
  ClearErrorOnReturn clear_error_on_return;
679
680
2
  BIOPointer bio(LoadBIO(env, args[0]));
681
2
  if (!bio)
682
    return;
683
684
  DeleteFnPtr<X509_CRL, X509_CRL_free> crl(
685
2
      PEM_read_bio_X509_CRL(bio.get(), nullptr, NoPasswordCallback, nullptr));
686
687
2
  if (!crl)
688
1
    return THROW_ERR_CRYPTO_OPERATION_FAILED(env, "Failed to parse CRL");
689
690
1
  X509_STORE* cert_store = SSL_CTX_get_cert_store(sc->ctx_.get());
691
1
  if (cert_store == root_cert_store) {
692
    cert_store = NewRootCertStore();
693
    SSL_CTX_set_cert_store(sc->ctx_.get(), cert_store);
694
  }
695
696
1
  X509_STORE_add_crl(cert_store, crl.get());
697
1
  X509_STORE_set_flags(cert_store,
698
                       X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
699
}
700
701
1762
void SecureContext::AddRootCerts(const FunctionCallbackInfo<Value>& args) {
702
  SecureContext* sc;
703
1762
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
704
1762
  ClearErrorOnReturn clear_error_on_return;
705
706
1762
  if (root_cert_store == nullptr) {
707
264
    root_cert_store = NewRootCertStore();
708
  }
709
710
  // Increment reference count so global store is not deleted along with CTX.
711
1762
  X509_STORE_up_ref(root_cert_store);
712
1762
  SSL_CTX_set_cert_store(sc->ctx_.get(), root_cert_store);
713
}
714
715
2235
void SecureContext::SetCipherSuites(const FunctionCallbackInfo<Value>& args) {
716
  // BoringSSL doesn't allow API config of TLS1.3 cipher suites.
717
#ifndef OPENSSL_IS_BORINGSSL
718
  SecureContext* sc;
719
2236
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
720
2235
  Environment* env = sc->env();
721
  ClearErrorOnReturn clear_error_on_return;
722
723
2235
  CHECK_EQ(args.Length(), 1);
724
4470
  CHECK(args[0]->IsString());
725
726
2235
  const Utf8Value ciphers(env->isolate(), args[0]);
727
2235
  if (!SSL_CTX_set_ciphersuites(sc->ctx_.get(), *ciphers))
728
1
    return ThrowCryptoError(env, ERR_get_error(), "Failed to set ciphers");
729
#endif
730
}
731
732
2237
void SecureContext::SetCiphers(const FunctionCallbackInfo<Value>& args) {
733
  SecureContext* sc;
734
2252
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
735
2237
  Environment* env = sc->env();
736
  ClearErrorOnReturn clear_error_on_return;
737
738
2237
  CHECK_EQ(args.Length(), 1);
739
4474
  CHECK(args[0]->IsString());
740
741
2237
  Utf8Value ciphers(env->isolate(), args[0]);
742
2237
  if (!SSL_CTX_set_cipher_list(sc->ctx_.get(), *ciphers)) {
743
15
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
744
745

15
    if (strlen(*ciphers) == 0 && ERR_GET_REASON(err) == SSL_R_NO_CIPHER_MATCH) {
746
      // TLS1.2 ciphers were deliberately cleared, so don't consider
747
      // SSL_R_NO_CIPHER_MATCH to be an error (this is how _set_cipher_suites()
748
      // works). If the user actually sets a value (like "no-such-cipher"), then
749
      // that's actually an error.
750
11
      return;
751
    }
752
4
    return ThrowCryptoError(env, err, "Failed to set ciphers");
753
  }
754
}
755
756
2229
void SecureContext::SetECDHCurve(const FunctionCallbackInfo<Value>& args) {
757
  SecureContext* sc;
758
2232
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
759
2229
  Environment* env = sc->env();
760
761
2229
  CHECK_GE(args.Length(), 1);  // ECDH curve name argument is mandatory
762
4458
  CHECK(args[0]->IsString());
763
764
2229
  Utf8Value curve(env->isolate(), args[0]);
765
766

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

46
                                    &sc->issuer_) &&
980
12
      SSL_CTX_use_PrivateKey(sc->ctx_.get(), pkey.get())) {
981
    // Add CA certs too
982
21
    for (int i = 0; i < sk_X509_num(extra_certs.get()); i++) {
983
9
      X509* ca = sk_X509_value(extra_certs.get(), i);
984
985
9
      if (cert_store == root_cert_store) {
986
6
        cert_store = NewRootCertStore();
987
6
        SSL_CTX_set_cert_store(sc->ctx_.get(), cert_store);
988
      }
989
9
      X509_STORE_add_cert(cert_store, ca);
990
9
      SSL_CTX_add_client_CA(sc->ctx_.get(), ca);
991
    }
992
12
    ret = true;
993
  }
994
995
18
  if (!ret) {
996
    // TODO(@jasnell): Should this use ThrowCryptoError?
997
6
    unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
998
6
    const char* str = ERR_reason_error_string(err);
999
6
    return env->ThrowError(str);
1000
  }
1001
}
1002
1003
#ifndef OPENSSL_NO_ENGINE
1004
void SecureContext::SetClientCertEngine(
1005
    const FunctionCallbackInfo<Value>& args) {
1006
  Environment* env = Environment::GetCurrent(args);
1007
  CHECK_EQ(args.Length(), 1);
1008
  CHECK(args[0]->IsString());
1009
1010
  SecureContext* sc;
1011
  ASSIGN_OR_RETURN_UNWRAP(&sc, args.Holder());
1012
1013
  MarkPopErrorOnReturn mark_pop_error_on_return;
1014
1015
  // SSL_CTX_set_client_cert_engine does not itself support multiple
1016
  // calls by cleaning up before overwriting the client_cert_engine
1017
  // internal context variable.
1018
  // Instead of trying to fix up this problem we in turn also do not
1019
  // support multiple calls to SetClientCertEngine.
1020
  CHECK(!sc->client_cert_engine_provided_);
1021
1022
  CryptoErrorStore errors;
1023
  const Utf8Value engine_id(env->isolate(), args[0]);
1024
  EnginePointer engine = LoadEngineById(*engine_id, &errors);
1025
  if (!engine) {
1026
    Local<Value> exception;
1027
    if (errors.ToException(env).ToLocal(&exception))
1028
      env->isolate()->ThrowException(exception);
1029
    return;
1030
  }
1031
1032
  // Note that this takes another reference to `engine`.
1033
  if (!SSL_CTX_set_client_cert_engine(sc->ctx_.get(), engine.get()))
1034
    return ThrowCryptoError(env, ERR_get_error());
1035
  sc->client_cert_engine_provided_ = true;
1036
}
1037
#endif  // !OPENSSL_NO_ENGINE
1038
1039
10
void SecureContext::GetTicketKeys(const FunctionCallbackInfo<Value>& args) {
1040
#if !defined(OPENSSL_NO_TLSEXT) && defined(SSL_CTX_get_tlsext_ticket_keys)
1041
1042
  SecureContext* wrap;
1043
10
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1044
1045
  Local<Object> buff;
1046
20
  if (!Buffer::New(wrap->env(), 48).ToLocal(&buff))
1047
    return;
1048
1049
10
  memcpy(Buffer::Data(buff), wrap->ticket_key_name_, 16);
1050
10
  memcpy(Buffer::Data(buff) + 16, wrap->ticket_key_hmac_, 16);
1051
10
  memcpy(Buffer::Data(buff) + 32, wrap->ticket_key_aes_, 16);
1052
1053
20
  args.GetReturnValue().Set(buff);
1054
#endif  // !def(OPENSSL_NO_TLSEXT) && def(SSL_CTX_get_tlsext_ticket_keys)
1055
}
1056
1057
23
void SecureContext::SetTicketKeys(const FunctionCallbackInfo<Value>& args) {
1058
#if !defined(OPENSSL_NO_TLSEXT) && defined(SSL_CTX_get_tlsext_ticket_keys)
1059
  SecureContext* wrap;
1060
23
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1061
1062
23
  CHECK_GE(args.Length(), 1);  // Ticket keys argument is mandatory
1063
23
  CHECK(args[0]->IsArrayBufferView());
1064
46
  ArrayBufferViewContents<char> buf(args[0].As<ArrayBufferView>());
1065
1066
23
  CHECK_EQ(buf.length(), 48);
1067
1068
23
  memcpy(wrap->ticket_key_name_, buf.data(), 16);
1069
23
  memcpy(wrap->ticket_key_hmac_, buf.data() + 16, 16);
1070
23
  memcpy(wrap->ticket_key_aes_, buf.data() + 32, 16);
1071
1072
46
  args.GetReturnValue().Set(true);
1073
#endif  // !def(OPENSSL_NO_TLSEXT) && def(SSL_CTX_get_tlsext_ticket_keys)
1074
}
1075
1076
void SecureContext::SetFreeListLength(const FunctionCallbackInfo<Value>& args) {
1077
}
1078
1079
// Currently, EnableTicketKeyCallback and TicketKeyCallback are only present for
1080
// the regression test in test/parallel/test-https-resume-after-renew.js.
1081
1
void SecureContext::EnableTicketKeyCallback(
1082
    const FunctionCallbackInfo<Value>& args) {
1083
  SecureContext* wrap;
1084
1
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1085
1086
1
  SSL_CTX_set_tlsext_ticket_key_cb(wrap->ctx_.get(), TicketKeyCallback);
1087
}
1088
1089
3
int SecureContext::TicketKeyCallback(SSL* ssl,
1090
                                     unsigned char* name,
1091
                                     unsigned char* iv,
1092
                                     EVP_CIPHER_CTX* ectx,
1093
                                     HMAC_CTX* hctx,
1094
                                     int enc) {
1095
  static const int kTicketPartSize = 16;
1096
1097
  SecureContext* sc = static_cast<SecureContext*>(
1098
3
      SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
1099
1100
3
  Environment* env = sc->env();
1101
6
  HandleScope handle_scope(env->isolate());
1102
3
  Context::Scope context_scope(env->context());
1103
1104
12
  Local<Value> argv[3];
1105
1106
6
  if (!Buffer::Copy(
1107
          env,
1108
          reinterpret_cast<char*>(name),
1109
9
          kTicketPartSize).ToLocal(&argv[0]) ||
1110
3
      !Buffer::Copy(
1111
          env,
1112
          reinterpret_cast<char*>(iv),
1113
6
          kTicketPartSize).ToLocal(&argv[1])) {
1114
    return -1;
1115
  }
1116
1117
6
  argv[2] = env != 0 ? v8::True(env->isolate()) : v8::False(env->isolate());
1118
1119
  Local<Value> ret;
1120
6
  if (!node::MakeCallback(
1121
          env->isolate(),
1122
          sc->object(),
1123
          env->ticketkeycallback_string(),
1124
3
          arraysize(argv),
1125
          argv,
1126

9
          {0, 0}).ToLocal(&ret) ||
1127
3
      !ret->IsArray()) {
1128
    return -1;
1129
  }
1130
3
  Local<Array> arr = ret.As<Array>();
1131
1132
  Local<Value> val;
1133

9
  if (!arr->Get(env->context(), kTicketKeyReturnIndex).ToLocal(&val) ||
1134
3
      !val->IsInt32()) {
1135
    return -1;
1136
  }
1137
1138
3
  int r = val.As<Int32>()->Value();
1139
3
  if (r < 0)
1140
    return r;
1141
1142
  Local<Value> hmac;
1143
  Local<Value> aes;
1144
1145
3
  if (!arr->Get(env->context(), kTicketKeyHMACIndex).ToLocal(&hmac) ||
1146


12
      !arr->Get(env->context(), kTicketKeyAESIndex).ToLocal(&aes) ||
1147
3
      Buffer::Length(aes) != kTicketPartSize) {
1148
    return -1;
1149
  }
1150
1151
3
  if (enc) {
1152
    Local<Value> name_val;
1153
    Local<Value> iv_val;
1154
2
    if (!arr->Get(env->context(), kTicketKeyNameIndex).ToLocal(&name_val) ||
1155

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

6
        Buffer::Length(name_val) != kTicketPartSize ||
1157
2
        Buffer::Length(iv_val) != kTicketPartSize) {
1158
      return -1;
1159
    }
1160
1161
2
    name_val.As<ArrayBufferView>()->CopyContents(name, kTicketPartSize);
1162
2
    iv_val.As<ArrayBufferView>()->CopyContents(iv, kTicketPartSize);
1163
  }
1164
1165
3
  ArrayBufferViewContents<unsigned char> hmac_buf(hmac);
1166
6
  HMAC_Init_ex(hctx,
1167
3
               hmac_buf.data(),
1168
3
               hmac_buf.length(),
1169
               EVP_sha256(),
1170
               nullptr);
1171
1172
3
  ArrayBufferViewContents<unsigned char> aes_key(aes.As<ArrayBufferView>());
1173
3
  if (enc) {
1174
2
    EVP_EncryptInit_ex(ectx,
1175
                       EVP_aes_128_cbc(),
1176
                       nullptr,
1177
                       aes_key.data(),
1178
                       iv);
1179
  } else {
1180
1
    EVP_DecryptInit_ex(ectx,
1181
                       EVP_aes_128_cbc(),
1182
                       nullptr,
1183
                       aes_key.data(),
1184
                       iv);
1185
  }
1186
1187
3
  return r;
1188
}
1189
1190
1203
int SecureContext::TicketCompatibilityCallback(SSL* ssl,
1191
                                               unsigned char* name,
1192
                                               unsigned char* iv,
1193
                                               EVP_CIPHER_CTX* ectx,
1194
                                               HMAC_CTX* hctx,
1195
                                               int enc) {
1196
  SecureContext* sc = static_cast<SecureContext*>(
1197
1203
      SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
1198
1199
1203
  if (enc) {
1200
1149
    memcpy(name, sc->ticket_key_name_, sizeof(sc->ticket_key_name_));
1201
2298
    if (RAND_bytes(iv, 16) <= 0 ||
1202
1149
        EVP_EncryptInit_ex(ectx, EVP_aes_128_cbc(), nullptr,
1203

2298
                           sc->ticket_key_aes_, iv) <= 0 ||
1204
1149
        HMAC_Init_ex(hctx, sc->ticket_key_hmac_, sizeof(sc->ticket_key_hmac_),
1205
                     EVP_sha256(), nullptr) <= 0) {
1206
      return -1;
1207
    }
1208
1149
    return 1;
1209
  }
1210
1211
54
  if (memcmp(name, sc->ticket_key_name_, sizeof(sc->ticket_key_name_)) != 0) {
1212
    // The ticket key name does not match. Discard the ticket.
1213
12
    return 0;
1214
  }
1215
1216
42
  if (EVP_DecryptInit_ex(ectx, EVP_aes_128_cbc(), nullptr, sc->ticket_key_aes_,
1217

84
                         iv) <= 0 ||
1218
42
      HMAC_Init_ex(hctx, sc->ticket_key_hmac_, sizeof(sc->ticket_key_hmac_),
1219
                   EVP_sha256(), nullptr) <= 0) {
1220
    return -1;
1221
  }
1222
42
  return 1;
1223
}
1224
1225
2
void SecureContext::CtxGetter(const FunctionCallbackInfo<Value>& info) {
1226
  SecureContext* sc;
1227
2
  ASSIGN_OR_RETURN_UNWRAP(&sc, info.This());
1228
4
  Local<External> ext = External::New(info.GetIsolate(), sc->ctx_.get());
1229
4
  info.GetReturnValue().Set(ext);
1230
}
1231
1232
template <bool primary>
1233
12
void SecureContext::GetCertificate(const FunctionCallbackInfo<Value>& args) {
1234
  SecureContext* wrap;
1235
12
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1236
12
  Environment* env = wrap->env();
1237
  X509* cert;
1238
1239
  if (primary)
1240
6
    cert = wrap->cert_.get();
1241
  else
1242
6
    cert = wrap->issuer_.get();
1243
12
  if (cert == nullptr)
1244
    return args.GetReturnValue().SetNull();
1245
1246
12
  int size = i2d_X509(cert, nullptr);
1247
  Local<Object> buff;
1248
24
  if (!Buffer::New(env, size).ToLocal(&buff))
1249
    return;
1250
12
  unsigned char* serialized = reinterpret_cast<unsigned char*>(
1251
12
      Buffer::Data(buff));
1252
12
  i2d_X509(cert, &serialized);
1253
1254
24
  args.GetReturnValue().Set(buff);
1255
}
1256
1257
namespace {
1258
4
unsigned long AddCertsFromFile(  // NOLINT(runtime/int)
1259
    X509_STORE* store,
1260
    const char* file) {
1261
4
  ERR_clear_error();
1262
8
  MarkPopErrorOnReturn mark_pop_error_on_return;
1263
1264
8
  BIOPointer bio(BIO_new_file(file, "r"));
1265
4
  if (!bio)
1266
1
    return ERR_get_error();
1267
1268
  while (X509* x509 =
1269
6
      PEM_read_bio_X509(bio.get(), nullptr, NoPasswordCallback, nullptr)) {
1270
3
    X509_STORE_add_cert(store, x509);
1271
3
    X509_free(x509);
1272
3
  }
1273
1274
3
  unsigned long err = ERR_peek_error();  // NOLINT(runtime/int)
1275
  // Ignore error if its EOF/no start line found.
1276
3
  if (ERR_GET_LIB(err) == ERR_LIB_PEM &&
1277
3
      ERR_GET_REASON(err) == PEM_R_NO_START_LINE) {
1278
3
    return 0;
1279
  }
1280
1281
  return err;
1282
}
1283
}  // namespace
1284
1285
// UseExtraCaCerts is called only once at the start of the Node.js process.
1286
4
void UseExtraCaCerts(const std::string& file) {
1287
4
  ClearErrorOnReturn clear_error_on_return;
1288
1289
4
  if (root_cert_store == nullptr) {
1290
4
    root_cert_store = NewRootCertStore();
1291
1292
4
    if (!file.empty()) {
1293
4
      unsigned long err = AddCertsFromFile(  // NOLINT(runtime/int)
1294
                                           root_cert_store,
1295
                                           file.c_str());
1296
4
      if (err) {
1297
1
        fprintf(stderr,
1298
                "Warning: Ignoring extra certs from `%s`, load failed: %s\n",
1299
                file.c_str(),
1300
                ERR_error_string(err, nullptr));
1301
      } else {
1302
3
        extra_root_certs_loaded = true;
1303
      }
1304
    }
1305
  }
1306
4
}
1307
1308
// Exposed to JavaScript strictly for testing purposes.
1309
3
void IsExtraRootCertsFileLoaded(
1310
    const FunctionCallbackInfo<Value>& args) {
1311
6
  return args.GetReturnValue().Set(extra_root_certs_loaded);
1312
}
1313
1314
}  // namespace crypto
1315
}  // namespace node