GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: crypto/crypto_tls.cc Lines: 1045 1135 92.1 %
Date: 2022-05-31 04:15:47 Branches: 444 680 65.3 %

Line Branch Exec Source
1
// Copyright Joyent, Inc. and other Node contributors.
2
//
3
// Permission is hereby granted, free of charge, to any person obtaining a
4
// copy of this software and associated documentation files (the
5
// "Software"), to deal in the Software without restriction, including
6
// without limitation the rights to use, copy, modify, merge, publish,
7
// distribute, sublicense, and/or sell copies of the Software, and to permit
8
// persons to whom the Software is furnished to do so, subject to the
9
// following conditions:
10
//
11
// The above copyright notice and this permission notice shall be included
12
// in all copies or substantial portions of the Software.
13
//
14
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20
// USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22
#include "crypto/crypto_tls.h"
23
#include "crypto/crypto_context.h"
24
#include "crypto/crypto_common.h"
25
#include "crypto/crypto_util.h"
26
#include "crypto/crypto_bio.h"
27
#include "crypto/crypto_clienthello-inl.h"
28
#include "async_wrap-inl.h"
29
#include "debug_utils-inl.h"
30
#include "memory_tracker-inl.h"
31
#include "node_buffer.h"
32
#include "node_errors.h"
33
#include "stream_base-inl.h"
34
#include "util-inl.h"
35
36
namespace node {
37
38
using v8::Array;
39
using v8::ArrayBuffer;
40
using v8::ArrayBufferView;
41
using v8::BackingStore;
42
using v8::Context;
43
using v8::DontDelete;
44
using v8::Exception;
45
using v8::False;
46
using v8::Function;
47
using v8::FunctionCallbackInfo;
48
using v8::FunctionTemplate;
49
using v8::HandleScope;
50
using v8::Integer;
51
using v8::Isolate;
52
using v8::Local;
53
using v8::MaybeLocal;
54
using v8::Null;
55
using v8::Object;
56
using v8::PropertyAttribute;
57
using v8::ReadOnly;
58
using v8::Signature;
59
using v8::String;
60
using v8::True;
61
using v8::Uint32;
62
using v8::Value;
63
64
namespace crypto {
65
66
namespace {
67
54
SSL_SESSION* GetSessionCallback(
68
    SSL* s,
69
    const unsigned char* key,
70
    int len,
71
    int* copy) {
72
54
  TLSWrap* w = static_cast<TLSWrap*>(SSL_get_app_data(s));
73
54
  *copy = 0;
74
54
  return w->ReleaseSession();
75
}
76
77
20
void OnClientHello(
78
    void* arg,
79
    const ClientHelloParser::ClientHello& hello) {
80
20
  TLSWrap* w = static_cast<TLSWrap*>(arg);
81
20
  Environment* env = w->env();
82
20
  HandleScope handle_scope(env->isolate());
83
20
  Context::Scope context_scope(env->context());
84
85
20
  Local<Object> hello_obj = Object::New(env->isolate());
86
20
  Local<String> servername = (hello.servername() == nullptr)
87
4
      ? String::Empty(env->isolate())
88
      : OneByteString(env->isolate(),
89
                      hello.servername(),
90
20
                      hello.servername_size());
91
  Local<Object> buf =
92
20
      Buffer::Copy(
93
          env,
94
20
          reinterpret_cast<const char*>(hello.session_id()),
95
40
          hello.session_size()).FromMaybe(Local<Object>());
96
97
60
  if ((buf.IsEmpty() ||
98
40
       hello_obj->Set(env->context(), env->session_id_string(), buf)
99
20
          .IsNothing()) ||
100
40
      hello_obj->Set(env->context(), env->servername_string(), servername)
101

60
          .IsNothing() ||
102
20
      hello_obj->Set(
103
          env->context(),
104
          env->tls_ticket_string(),
105
20
          hello.has_ticket()
106
5
              ? True(env->isolate())
107

100
              : False(env->isolate())).IsNothing()) {
108
    return;
109
  }
110
111
20
  Local<Value> argv[] = { hello_obj };
112
20
  w->MakeCallback(env->onclienthello_string(), arraysize(argv), argv);
113
}
114
115
32
void KeylogCallback(const SSL* s, const char* line) {
116
32
  TLSWrap* w = static_cast<TLSWrap*>(SSL_get_app_data(s));
117
32
  Environment* env = w->env();
118
32
  HandleScope handle_scope(env->isolate());
119
32
  Context::Scope context_scope(env->context());
120
121
32
  const size_t size = strlen(line);
122
32
  Local<Value> line_bf = Buffer::Copy(env, line, 1 + size)
123
32
      .FromMaybe(Local<Value>());
124
32
  if (UNLIKELY(line_bf.IsEmpty()))
125
    return;
126
127
32
  char* data = Buffer::Data(line_bf);
128
32
  data[size] = '\n';
129
32
  w->MakeCallback(env->onkeylog_string(), 1, &line_bf);
130
}
131
132
1917
int NewSessionCallback(SSL* s, SSL_SESSION* sess) {
133
1917
  TLSWrap* w = static_cast<TLSWrap*>(SSL_get_app_data(s));
134
1917
  Environment* env = w->env();
135
3834
  HandleScope handle_scope(env->isolate());
136
1917
  Context::Scope context_scope(env->context());
137
138
1917
  if (!w->has_session_callbacks())
139
1626
    return 0;
140
141
  // Check if session is small enough to be stored
142
291
  int size = i2d_SSL_SESSION(sess, nullptr);
143
291
  if (UNLIKELY(size > SecureContext::kMaxSessionSize))
144
    return 0;
145
146
  // Serialize session
147
582
  Local<Object> session = Buffer::New(env, size).FromMaybe(Local<Object>());
148
291
  if (UNLIKELY(session.IsEmpty()))
149
    return 0;
150
151
  unsigned char* session_data =
152
291
      reinterpret_cast<unsigned char*>(Buffer::Data(session));
153
154
291
  CHECK_EQ(i2d_SSL_SESSION(sess, &session_data), size);
155
156
  unsigned int session_id_length;
157
  const unsigned char* session_id_data =
158
291
      SSL_SESSION_get_id(sess, &session_id_length);
159
160
291
  Local<Object> session_id = Buffer::Copy(
161
      env,
162
      reinterpret_cast<const char*>(session_id_data),
163
582
      session_id_length).FromMaybe(Local<Object>());
164
291
  if (UNLIKELY(session_id.IsEmpty()))
165
    return 0;
166
167
  Local<Value> argv[] = {
168
    session_id,
169
    session
170
291
  };
171
172
  // On servers, we pause the handshake until callback of 'newSession', which
173
  // calls NewSessionDoneCb(). On clients, there is no callback to wait for.
174
291
  if (w->is_server())
175
8
    w->set_awaiting_new_session(true);
176
177
291
  w->MakeCallback(env->onnewsession_string(), arraysize(argv), argv);
178
179
291
  return 0;
180
}
181
182
973
int SSLCertCallback(SSL* s, void* arg) {
183
973
  TLSWrap* w = static_cast<TLSWrap*>(SSL_get_app_data(s));
184
185

973
  if (!w->is_server() || !w->is_waiting_cert_cb())
186
948
    return 1;
187
188
25
  if (w->is_cert_cb_running())
189
    // Not an error. Suspend handshake with SSL_ERROR_WANT_X509_LOOKUP, and
190
    // handshake will continue after certcb is done.
191
    return -1;
192
193
25
  Environment* env = w->env();
194
50
  HandleScope handle_scope(env->isolate());
195
25
  Context::Scope context_scope(env->context());
196
25
  w->set_cert_cb_running();
197
198
25
  Local<Object> info = Object::New(env->isolate());
199
200
25
  const char* servername = GetServerName(s);
201
  Local<String> servername_str = (servername == nullptr)
202
8
      ? String::Empty(env->isolate())
203
25
      : OneByteString(env->isolate(), servername, strlen(servername));
204
205
25
  Local<Value> ocsp = (SSL_get_tlsext_status_type(s) == TLSEXT_STATUSTYPE_ocsp)
206
6
      ? True(env->isolate())
207
50
      : False(env->isolate());
208
209
50
  if (info->Set(env->context(), env->servername_string(), servername_str)
210
50
          .IsNothing() ||
211

100
      info->Set(env->context(), env->ocsp_request_string(), ocsp).IsNothing()) {
212
    return 1;
213
  }
214
215
25
  Local<Value> argv[] = { info };
216
25
  w->MakeCallback(env->oncertcb_string(), arraysize(argv), argv);
217
218
25
  return w->is_cert_cb_running() ? -1 : 1;
219
}
220
221
35
int SelectALPNCallback(
222
    SSL* s,
223
    const unsigned char** out,
224
    unsigned char* outlen,
225
    const unsigned char* in,
226
    unsigned int inlen,
227
    void* arg) {
228
35
  TLSWrap* w = static_cast<TLSWrap*>(SSL_get_app_data(s));
229
35
  Environment* env = w->env();
230
70
  HandleScope handle_scope(env->isolate());
231
35
  Context::Scope context_scope(env->context());
232
233
  Local<Value> alpn_buffer =
234
35
      w->object()->GetPrivate(
235
          env->context(),
236
70
          env->alpn_buffer_private_symbol()).FromMaybe(Local<Value>());
237

70
  if (UNLIKELY(alpn_buffer.IsEmpty()) || !alpn_buffer->IsArrayBufferView())
238
    return SSL_TLSEXT_ERR_NOACK;
239
240
35
  ArrayBufferViewContents<unsigned char> alpn_protos(alpn_buffer);
241
35
  int status = SSL_select_next_proto(
242
      const_cast<unsigned char**>(out),
243
      outlen,
244
      alpn_protos.data(),
245
35
      alpn_protos.length(),
246
      in,
247
      inlen);
248
249
  // According to 3.2. Protocol Selection of RFC7301, fatal
250
  // no_application_protocol alert shall be sent but OpenSSL 1.0.2 does not
251
  // support it yet. See
252
  // https://rt.openssl.org/Ticket/Display.html?id=3463&user=guest&pass=guest
253
  return status == OPENSSL_NPN_NEGOTIATED
254
35
      ? SSL_TLSEXT_ERR_OK
255
35
      : SSL_TLSEXT_ERR_NOACK;
256
}
257
258
8
int TLSExtStatusCallback(SSL* s, void* arg) {
259
8
  TLSWrap* w = static_cast<TLSWrap*>(SSL_get_app_data(s));
260
8
  Environment* env = w->env();
261
16
  HandleScope handle_scope(env->isolate());
262
263
8
  if (w->is_client()) {
264
    // Incoming response
265
    Local<Value> arg;
266
12
    if (GetSSLOCSPResponse(env, s, Null(env->isolate())).ToLocal(&arg))
267
4
      w->MakeCallback(env->onocspresponse_string(), 1, &arg);
268
269
    // No async acceptance is possible, so always return 1 to accept the
270
    // response.  The listener for 'OCSPResponse' event has no control over
271
    // return value, but it can .destroy() the connection if the response is not
272
    // acceptable.
273
4
    return 1;
274
  }
275
276
  // Outgoing response
277
  Local<ArrayBufferView> obj =
278
8
      w->ocsp_response().FromMaybe(Local<ArrayBufferView>());
279
4
  if (UNLIKELY(obj.IsEmpty()))
280
2
    return SSL_TLSEXT_ERR_NOACK;
281
282
2
  size_t len = obj->ByteLength();
283
284
  // OpenSSL takes control of the pointer after accepting it
285
2
  unsigned char* data = MallocOpenSSL<unsigned char>(len);
286
2
  obj->CopyContents(data, len);
287
288
2
  if (!SSL_set_tlsext_status_ocsp_resp(s, data, len))
289
    OPENSSL_free(data);
290
291
2
  w->ClearOcspResponse();
292
293
2
  return SSL_TLSEXT_ERR_OK;
294
}
295
296
12386
void ConfigureSecureContext(SecureContext* sc) {
297
  // OCSP stapling
298
12386
  SSL_CTX_set_tlsext_status_cb(sc->ctx().get(), TLSExtStatusCallback);
299
12386
  SSL_CTX_set_tlsext_status_arg(sc->ctx().get(), nullptr);
300
12386
}
301
302
3981
inline bool Set(
303
    Environment* env,
304
    Local<Object> target,
305
    Local<String> name,
306
    const char* value,
307
    bool ignore_null = true) {
308
3981
  if (value == nullptr)
309
1337
    return ignore_null;
310
2644
  return !target->Set(
311
      env->context(),
312
      name,
313
5288
      OneByteString(env->isolate(), value))
314
2644
          .IsNothing();
315
}
316
317
635
std::string GetBIOError() {
318
635
  std::string ret;
319
635
  ERR_print_errors_cb(
320
631
      [](const char* str, size_t len, void* opaque) {
321
631
        static_cast<std::string*>(opaque)->assign(str, len);
322
631
        return 0;
323
      },
324
      static_cast<void*>(&ret));
325
635
  return ret;
326
}
327
}  // namespace
328
329
12386
TLSWrap::TLSWrap(Environment* env,
330
                 Local<Object> obj,
331
                 Kind kind,
332
                 StreamBase* stream,
333
12386
                 SecureContext* sc)
334
    : AsyncWrap(env, obj, AsyncWrap::PROVIDER_TLSWRAP),
335
      StreamBase(env),
336
      env_(env),
337
      kind_(kind),
338
12386
      sc_(sc) {
339
12386
  MakeWeak();
340
12386
  CHECK(sc_);
341
12386
  ssl_ = sc_->CreateSSL();
342
12386
  CHECK(ssl_);
343
344
12386
  sc_->SetGetSessionCallback(GetSessionCallback);
345
12386
  sc_->SetNewSessionCallback(NewSessionCallback);
346
347
12386
  StreamBase::AttachToObject(GetObject());
348
12386
  stream->PushStreamListener(this);
349
350
12386
  env_->isolate()->AdjustAmountOfExternalAllocatedMemory(kExternalSize);
351
352
12386
  InitSSL();
353
12386
  Debug(this, "Created new TLSWrap");
354
12386
}
355
356
74286
TLSWrap::~TLSWrap() {
357
24762
  Destroy();
358
49524
}
359
360
4
MaybeLocal<ArrayBufferView> TLSWrap::ocsp_response() const {
361
4
  if (ocsp_response_.IsEmpty())
362
2
    return MaybeLocal<ArrayBufferView>();
363
4
  return PersistentToLocal::Default(env()->isolate(), ocsp_response_);
364
}
365
366
2
void TLSWrap::ClearOcspResponse() {
367
2
  ocsp_response_.Reset();
368
2
}
369
370
54
SSL_SESSION* TLSWrap::ReleaseSession() {
371
54
  return next_sess_.release();
372
}
373
374
21065
void TLSWrap::InvokeQueued(int status, const char* error_str) {
375
21065
  Debug(this, "Invoking queued write callbacks (%d, %s)", status, error_str);
376
21065
  if (!write_callback_scheduled_)
377
4825
    return;
378
379
16240
  if (current_write_) {
380
5422
    BaseObjectPtr<AsyncWrap> current_write = std::move(current_write_);
381
2711
    current_write_.reset();
382
2711
    WriteWrap* w = WriteWrap::FromObject(current_write);
383
2711
    w->Done(status, error_str);
384
  }
385
}
386
387
8
void TLSWrap::NewSessionDoneCb() {
388
8
  Debug(this, "New session callback done");
389
8
  Cycle();
390
8
}
391
392
12386
void TLSWrap::InitSSL() {
393
  // Initialize SSL – OpenSSL takes ownership of these.
394
12386
  enc_in_ = NodeBIO::New(env()).release();
395
12386
  enc_out_ = NodeBIO::New(env()).release();
396
397
12386
  SSL_set_bio(ssl_.get(), enc_in_, enc_out_);
398
399
  // NOTE: This could be overridden in SetVerifyMode
400
12386
  SSL_set_verify(ssl_.get(), SSL_VERIFY_NONE, VerifyCallback);
401
402
#ifdef SSL_MODE_RELEASE_BUFFERS
403
12386
  SSL_set_mode(ssl_.get(), SSL_MODE_RELEASE_BUFFERS);
404
#endif  // SSL_MODE_RELEASE_BUFFERS
405
406
  // This is default in 1.1.1, but set it anyway, Cycle() doesn't currently
407
  // re-call ClearIn() if SSL_read() returns SSL_ERROR_WANT_READ, so data can be
408
  // left sitting in the incoming enc_in_ and never get processed.
409
  // - https://wiki.openssl.org/index.php/TLS1.3#Non-application_data_records
410
12386
  SSL_set_mode(ssl_.get(), SSL_MODE_AUTO_RETRY);
411
412
#ifdef OPENSSL_IS_BORINGSSL
413
  // OpenSSL allows renegotiation by default, but BoringSSL disables it.
414
  // Configure BoringSSL to match OpenSSL's behavior.
415
  SSL_set_renegotiate_mode(ssl_.get(), ssl_renegotiate_freely);
416
#endif
417
418
12386
  SSL_set_app_data(ssl_.get(), this);
419
  // Using InfoCallback isn't how we are supposed to check handshake progress:
420
  //   https://github.com/openssl/openssl/issues/7199#issuecomment-420915993
421
  //
422
  // Note on when this gets called on various openssl versions:
423
  //   https://github.com/openssl/openssl/issues/7199#issuecomment-420670544
424
12386
  SSL_set_info_callback(ssl_.get(), SSLInfoCallback);
425
426
12386
  if (is_server())
427
944
    sc_->SetSelectSNIContextCallback(SelectSNIContextCallback);
428
429
12386
  ConfigureSecureContext(sc_.get());
430
431
12386
  SSL_set_cert_cb(ssl_.get(), SSLCertCallback, this);
432
433
12386
  if (is_server()) {
434
944
    SSL_set_accept_state(ssl_.get());
435
11442
  } else if (is_client()) {
436
    // Enough space for server response (hello, cert)
437
11442
    NodeBIO::FromBIO(enc_in_)->set_initial(kInitialClientBufferLength);
438
11442
    SSL_set_connect_state(ssl_.get());
439
  } else {
440
    // Unexpected
441
    ABORT();
442
  }
443
12386
}
444
445
12386
void TLSWrap::Wrap(const FunctionCallbackInfo<Value>& args) {
446
12386
  Environment* env = Environment::GetCurrent(args);
447
448
12386
  CHECK_EQ(args.Length(), 3);
449
12386
  CHECK(args[0]->IsObject());
450
12386
  CHECK(args[1]->IsObject());
451
12386
  CHECK(args[2]->IsBoolean());
452
453
24772
  Local<Object> sc = args[1].As<Object>();
454

12386
  Kind kind = args[2]->IsTrue() ? Kind::kServer : Kind::kClient;
455
456
24772
  StreamBase* stream = StreamBase::FromObject(args[0].As<Object>());
457
12386
  CHECK_NOT_NULL(stream);
458
459
  Local<Object> obj;
460
12386
  if (!env->tls_wrap_constructor_function()
461
12386
           ->NewInstance(env->context())
462
12386
           .ToLocal(&obj)) {
463
    return;
464
  }
465
466
12386
  TLSWrap* res = new TLSWrap(env, obj, kind, stream, Unwrap<SecureContext>(sc));
467
468
24772
  args.GetReturnValue().Set(res->object());
469
}
470
471
3
void TLSWrap::Receive(const FunctionCallbackInfo<Value>& args) {
472
  TLSWrap* wrap;
473
3
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
474
475
3
  ArrayBufferViewContents<char> buffer(args[0]);
476
3
  const char* data = buffer.data();
477
3
  size_t len = buffer.length();
478
3
  Debug(wrap, "Receiving %zu bytes injected from JS", len);
479
480
  // Copy given buffer entirely or partiall if handle becomes closed
481


6
  while (len > 0 && wrap->IsAlive() && !wrap->IsClosing()) {
482
3
    uv_buf_t buf = wrap->OnStreamAlloc(len);
483
3
    size_t copy = buf.len > len ? len : buf.len;
484
3
    memcpy(buf.base, data, copy);
485
3
    buf.len = copy;
486
3
    wrap->OnStreamRead(copy, buf);
487
488
3
    data += copy;
489
3
    len -= copy;
490
  }
491
}
492
493
1390
void TLSWrap::Start(const FunctionCallbackInfo<Value>& args) {
494
  TLSWrap* wrap;
495
1390
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
496
497
1390
  CHECK(!wrap->started_);
498
1390
  wrap->started_ = true;
499
500
  // Send ClientHello handshake
501
1390
  CHECK(wrap->is_client());
502
  // Seems odd to read when when we want to send, but SSL_read() triggers a
503
  // handshake if a session isn't established, and handshake will cause
504
  // encrypted data to become available for output.
505
1390
  wrap->ClearOut();
506
1390
  wrap->EncOut();
507
}
508
509
40521
void TLSWrap::SSLInfoCallback(const SSL* ssl_, int where, int ret) {
510
40521
  if (!(where & (SSL_CB_HANDSHAKE_START | SSL_CB_HANDSHAKE_DONE)))
511
36199
    return;
512
513
  // SSL_renegotiate_pending() should take `const SSL*`, but it does not.
514
4322
  SSL* ssl = const_cast<SSL*>(ssl_);
515
4322
  TLSWrap* c = static_cast<TLSWrap*>(SSL_get_app_data(ssl_));
516
4322
  Environment* env = c->env();
517
8644
  HandleScope handle_scope(env->isolate());
518
4322
  Context::Scope context_scope(env->context());
519
4322
  Local<Object> object = c->object();
520
521
4322
  if (where & SSL_CB_HANDSHAKE_START) {
522
    Debug(c, "SSLInfoCallback(SSL_CB_HANDSHAKE_START);");
523
    // Start is tracked to limit number and frequency of renegotiation attempts,
524
    // since excessive renegotiation may be an attack.
525
    Local<Value> callback;
526
527
5034
    if (object->Get(env->context(), env->onhandshakestart_string())
528

5034
            .ToLocal(&callback) && callback->IsFunction()) {
529
2517
      Local<Value> argv[] = { env->GetNow() };
530
5034
      c->MakeCallback(callback.As<Function>(), arraysize(argv), argv);
531
    }
532
  }
533
534
  // SSL_CB_HANDSHAKE_START and SSL_CB_HANDSHAKE_DONE are called
535
  // sending HelloRequest in OpenSSL-1.1.1.
536
  // We need to check whether this is in a renegotiation state or not.
537

4322
  if (where & SSL_CB_HANDSHAKE_DONE && !SSL_renegotiate_pending(ssl)) {
538
    Debug(c, "SSLInfoCallback(SSL_CB_HANDSHAKE_DONE);");
539
1804
    CHECK(!SSL_renegotiate_pending(ssl));
540
    Local<Value> callback;
541
542
1804
    c->established_ = true;
543
544
3608
    if (object->Get(env->context(), env->onhandshakedone_string())
545

3608
          .ToLocal(&callback) && callback->IsFunction()) {
546
3608
      c->MakeCallback(callback.As<Function>(), 0, nullptr);
547
    }
548
  }
549
}
550
551
20062
void TLSWrap::EncOut() {
552
20062
  Debug(this, "Trying to write encrypted output");
553
554
  // Ignore cycling data if ClientHello wasn't yet parsed
555
20062
  if (!hello_parser_.IsEnded()) {
556
1
    Debug(this, "Returning from EncOut(), hello_parser_ active");
557
12530
    return;
558
  }
559
560
  // Write in progress
561
20061
  if (write_size_ != 0) {
562
3629
    Debug(this, "Returning from EncOut(), write currently in progress");
563
3629
    return;
564
  }
565
566
  // Wait for `newSession` callback to be invoked
567
16432
  if (is_awaiting_new_session()) {
568
7
    Debug(this, "Returning from EncOut(), awaiting new session");
569
7
    return;
570
  }
571
572
  // Split-off queue
573

16425
  if (established_ && current_write_) {
574
5391
    Debug(this, "EncOut() write is scheduled");
575
5391
    write_callback_scheduled_ = true;
576
  }
577
578
16425
  if (ssl_ == nullptr) {
579
2
    Debug(this, "Returning from EncOut(), ssl_ == nullptr");
580
2
    return;
581
  }
582
583
  // No encrypted output ready to write to the underlying stream.
584
16423
  if (BIO_pending(enc_out_) == 0) {
585
8712
    Debug(this, "No pending encrypted output");
586

8923
    if (!pending_cleartext_input_ ||
587
211
        pending_cleartext_input_->ByteLength() == 0) {
588
8501
      if (!in_dowrite_) {
589
8439
        Debug(this, "No pending cleartext input, not inside DoWrite()");
590
8439
        InvokeQueued(0);
591
      } else {
592
62
        Debug(this, "No pending cleartext input, inside DoWrite()");
593
        // TODO(@sam-github, @addaleax) If in_dowrite_ is true, appdata was
594
        // passed to SSL_write().  If we are here, the data was not encrypted to
595
        // enc_out_ yet.  Calling Done() "works", but since the write is not
596
        // flushed, its too soon.  Just returning and letting the next EncOut()
597
        // call Done() passes the test suite, but without more careful analysis,
598
        // its not clear if it is always correct. Not calling Done() could block
599
        // data flow, so for now continue to call Done(), just do it in the next
600
        // tick.
601
62
        BaseObjectPtr<TLSWrap> strong_ref{this};
602
62
        env()->SetImmediate([this, strong_ref](Environment* env) {
603
62
          InvokeQueued(0);
604
62
        });
605
      }
606
    }
607
8712
    return;
608
  }
609
610
  char* data[kSimultaneousBufferCount];
611
  size_t size[arraysize(data)];
612
7711
  size_t count = arraysize(data);
613
7711
  write_size_ = NodeBIO::FromBIO(enc_out_)->PeekMultiple(data, size, &count);
614

7711
  CHECK(write_size_ != 0 && count != 0);
615
616
  uv_buf_t buf[arraysize(data)];
617
7711
  uv_buf_t* bufs = buf;
618
15558
  for (size_t i = 0; i < count; i++)
619
7847
    buf[i] = uv_buf_init(data[i], size[i]);
620
621
7711
  Debug(this, "Writing %zu buffers to the underlying stream", count);
622
7711
  StreamWriteResult res = underlying_stream()->Write(bufs, count);
623
7710
  if (res.err != 0) {
624
179
    InvokeQueued(res.err);
625
179
    return;
626
  }
627
628
7531
  if (!res.async) {
629
6972
    Debug(this, "Write finished synchronously");
630
13944
    HandleScope handle_scope(env()->isolate());
631
632
    // Simulate asynchronous finishing, TLS cannot handle this at the moment.
633
6972
    BaseObjectPtr<TLSWrap> strong_ref{this};
634
6972
    env()->SetImmediate([this, strong_ref](Environment* env) {
635
6972
      OnStreamAfterWrite(nullptr, 0);
636
6972
    });
637
  }
638
}
639
640
7630
void TLSWrap::OnStreamAfterWrite(WriteWrap* req_wrap, int status) {
641
7630
  Debug(this, "OnStreamAfterWrite(status = %d)", status);
642
7630
  if (current_empty_write_) {
643
100
    Debug(this, "Had empty write");
644
    BaseObjectPtr<AsyncWrap> current_empty_write =
645
100
        std::move(current_empty_write_);
646
100
    current_empty_write_.reset();
647
100
    WriteWrap* finishing = WriteWrap::FromObject(current_empty_write);
648
100
    finishing->Done(status);
649
100
    return;
650
  }
651
652
7530
  if (ssl_ == nullptr) {
653
    Debug(this, "ssl_ == nullptr, marking as cancelled");
654
    status = UV_ECANCELED;
655
  }
656
657
  // Handle error
658
7530
  if (status) {
659
3
    if (shutdown_) {
660
1
      Debug(this, "Ignoring error after shutdown");
661
1
      return;
662
    }
663
664
    // Notify about error
665
2
    InvokeQueued(status);
666
2
    return;
667
  }
668
669
  // Commit
670
7527
  NodeBIO::FromBIO(enc_out_)->Read(nullptr, write_size_);
671
672
  // Ensure that the progress will be made and `InvokeQueued` will be called.
673
7527
  ClearIn();
674
675
  // Try writing more data
676
7527
  write_size_ = 0;
677
7527
  EncOut();
678
}
679
680
8629
int TLSWrap::GetSSLError(int status) const {
681
  // ssl_ might already be destroyed for reading EOF from a close notify alert.
682
8629
  return ssl_ != nullptr ? SSL_get_error(ssl_.get(), status) : 0;
683
}
684
685
8206
void TLSWrap::ClearOut() {
686
8206
  Debug(this, "Trying to read cleartext output");
687
  // Ignore cycling data if ClientHello wasn't yet parsed
688
8206
  if (!hello_parser_.IsEnded()) {
689
1
    Debug(this, "Returning from ClearOut(), hello_parser_ active");
690
7576
    return;
691
  }
692
693
  // No reads after EOF
694
8205
  if (eof_) {
695
    Debug(this, "Returning from ClearOut(), EOF reached");
696
    return;
697
  }
698
699
8205
  if (ssl_ == nullptr) {
700
1
    Debug(this, "Returning from ClearOut(), ssl_ == nullptr");
701
1
    return;
702
  }
703
704
8204
  MarkPopErrorOnReturn mark_pop_error_on_return;
705
706
  char out[kClearOutChunkSize];
707
  int read;
708
  for (;;) {
709
11392
    read = SSL_read(ssl_.get(), out, sizeof(out));
710
11392
    Debug(this, "Read %d bytes of cleartext output", read);
711
712
11392
    if (read <= 0)
713
8202
      break;
714
715
3190
    char* current = out;
716
8432
    while (read > 0) {
717
5244
      int avail = read;
718
719
5244
      uv_buf_t buf = EmitAlloc(avail);
720
5244
      if (static_cast<int>(buf.len) < avail)
721
2054
        avail = buf.len;
722
5244
      memcpy(buf.base, current, avail);
723
5244
      EmitRead(avail, buf);
724
725
      // Caveat emptor: OnRead() calls into JS land which can result in
726
      // the SSL context object being destroyed.  We have to carefully
727
      // check that ssl_ != nullptr afterwards.
728
5243
      if (ssl_ == nullptr) {
729
1
        Debug(this, "Returning from read loop, ssl_ == nullptr");
730
1
        return;
731
      }
732
733
5242
      read -= avail;
734
5242
      current += avail;
735
    }
736
3188
  }
737
738
8202
  int flags = SSL_get_shutdown(ssl_.get());
739

8202
  if (!eof_ && flags & SSL_RECEIVED_SHUTDOWN) {
740
1196
    eof_ = true;
741
1196
    EmitRead(UV_EOF);
742
  }
743
744
  // We need to check whether an error occurred or the connection was
745
  // shutdown cleanly (SSL_ERROR_ZERO_RETURN) even when read == 0.
746
  // See node#1642 and SSL_read(3SSL) for details.
747
8202
  if (read <= 0) {
748
8202
    HandleScope handle_scope(env()->isolate());
749
    Local<Value> error;
750
8202
    int err = GetSSLError(read);
751
8202
    switch (err) {
752
1140
      case SSL_ERROR_ZERO_RETURN:
753
        // Ignore ZERO_RETURN after EOF, it is basically not an error.
754
1140
        if (eof_) return;
755
        error = env()->zero_return_string();
756
        break;
757
758
633
      case SSL_ERROR_SSL:
759
      case SSL_ERROR_SYSCALL:
760
        {
761
633
          unsigned long ssl_err = ERR_peek_error();  // NOLINT(runtime/int)
762
763
633
          Local<Context> context = env()->isolate()->GetCurrentContext();
764
633
          if (UNLIKELY(context.IsEmpty())) return;
765
633
          const std::string error_str = GetBIOError();
766
          Local<String> message = OneByteString(
767
633
              env()->isolate(), error_str.c_str(), error_str.size());
768
633
          if (UNLIKELY(message.IsEmpty())) return;
769
633
          error = Exception::Error(message);
770
633
          if (UNLIKELY(error.IsEmpty())) return;
771
          Local<Object> obj;
772
1266
          if (UNLIKELY(!error->ToObject(context).ToLocal(&obj))) return;
773
774
633
          const char* ls = ERR_lib_error_string(ssl_err);
775
633
          const char* fs = ERR_func_error_string(ssl_err);
776
633
          const char* rs = ERR_reason_error_string(ssl_err);
777
633
          if (!Set(env(), obj, env()->library_string(), ls) ||
778

1266
              !Set(env(), obj, env()->function_string(), fs) ||
779
637
              !Set(env(), obj, env()->reason_string(), rs, false)) return;
780
          // SSL has no API to recover the error name from the number, so we
781
          // transform reason strings like "this error" to "ERR_SSL_THIS_ERROR",
782
          // which ends up being close to the original error macro name.
783
629
          std::string code(rs);
784
          // TODO(RaisinTen): Pass an appropriate execution policy when it is
785
          // implemented in our supported compilers.
786
          std::transform(code.begin(), code.end(), code.begin(),
787
13638
                         [](char c) { return c == ' ' ? '_' : ToUpper(c); });
788
629
          if (!Set(env(), obj,
789
1891
                   env()->code_string(), ("ERR_SSL_" + code).c_str())) return;
790
        }
791
629
        break;
792
793
6429
      default:
794
6429
        return;
795
    }
796
797
629
    Debug(this, "Got SSL error (%d), calling onerror", err);
798
    // When TLS Alert are stored in wbio,
799
    // it should be flushed to socket before destroyed.
800
629
    if (BIO_pending(enc_out_) != 0)
801
572
      EncOut();
802
803
629
    MakeCallback(env()->onerror_string(), 1, &error);
804
  }
805
}
806
807
13901
void TLSWrap::ClearIn() {
808
13901
  Debug(this, "Trying to write cleartext input");
809
  // Ignore cycling data if ClientHello wasn't yet parsed
810
13901
  if (!hello_parser_.IsEnded()) {
811
    Debug(this, "Returning from ClearIn(), hello_parser_ active");
812
13662
    return;
813
  }
814
815
13901
  if (ssl_ == nullptr) {
816
    Debug(this, "Returning from ClearIn(), ssl_ == nullptr");
817
    return;
818
  }
819
820

14321
  if (!pending_cleartext_input_ ||
821
420
      pending_cleartext_input_->ByteLength() == 0) {
822
13481
    Debug(this, "Returning from ClearIn(), no pending data");
823
13481
    return;
824
  }
825
826
420
  std::unique_ptr<BackingStore> bs = std::move(pending_cleartext_input_);
827
420
  MarkPopErrorOnReturn mark_pop_error_on_return;
828
829
420
  NodeBIO::FromBIO(enc_out_)->set_allocate_tls_hint(bs->ByteLength());
830
420
  int written = SSL_write(ssl_.get(), bs->Data(), bs->ByteLength());
831
420
  Debug(this, "Writing %zu bytes, written = %d", bs->ByteLength(), written);
832

420
  CHECK(written == -1 || written == static_cast<int>(bs->ByteLength()));
833
834
  // All written
835
420
  if (written != -1) {
836
179
    Debug(this, "Successfully wrote all data to SSL");
837
179
    return;
838
  }
839
840
  // Error or partial write
841
241
  int err = GetSSLError(written);
842

241
  if (err == SSL_ERROR_SSL || err == SSL_ERROR_SYSCALL) {
843
2
    Debug(this, "Got SSL error (%d)", err);
844
2
    write_callback_scheduled_ = true;
845
    // TODO(@sam-github) Should forward an error object with
846
    // .code/.function/.etc, if possible.
847
2
    InvokeQueued(UV_EPROTO, GetBIOError().c_str());
848
2
    return;
849
  }
850
851
239
  Debug(this, "Pushing data back");
852
  // Push back the not-yet-written data. This can be skipped in the error
853
  // case because no further writes would succeed anyway.
854
239
  pending_cleartext_input_ = std::move(bs);
855
}
856
857
std::string TLSWrap::diagnostic_name() const {
858
  std::string name = "TLSWrap ";
859
  name += is_server() ? "server (" : "client (";
860
  name += std::to_string(static_cast<int64_t>(get_async_id())) + ")";
861
  return name;
862
}
863
864
26496
AsyncWrap* TLSWrap::GetAsyncWrap() {
865
26496
  return static_cast<AsyncWrap*>(this);
866
}
867
868
1134
bool TLSWrap::IsIPCPipe() {
869
1134
  return underlying_stream()->IsIPCPipe();
870
}
871
872
4
int TLSWrap::GetFD() {
873
4
  return underlying_stream()->GetFD();
874
}
875
876
4125
bool TLSWrap::IsAlive() {
877
4124
  return ssl_ &&
878

8249
      underlying_stream() != nullptr &&
879
8248
      underlying_stream()->IsAlive();
880
}
881
882
3
bool TLSWrap::IsClosing() {
883
3
  return underlying_stream()->IsClosing();
884
}
885
886
2460
int TLSWrap::ReadStart() {
887
2460
  Debug(this, "ReadStart()");
888

2460
  if (underlying_stream() != nullptr && !eof_)
889
2459
    return underlying_stream()->ReadStart();
890
1
  return 0;
891
}
892
893
1686
int TLSWrap::ReadStop() {
894
1686
  Debug(this, "ReadStop()");
895
1686
  return underlying_stream() != nullptr ? underlying_stream()->ReadStop() : 0;
896
}
897
898
5656
const char* TLSWrap::Error() const {
899
5656
  return error_.empty() ? nullptr : error_.c_str();
900
}
901
902
8
void TLSWrap::ClearError() {
903
8
  error_.clear();
904
8
}
905
906
// Called by StreamBase::Write() to request async write of clear text into SSL.
907
// TODO(@sam-github) Should there be a TLSWrap::DoTryWrite()?
908
2819
int TLSWrap::DoWrite(WriteWrap* w,
909
                     uv_buf_t* bufs,
910
                     size_t count,
911
                     uv_stream_t* send_handle) {
912
2819
  CHECK_NULL(send_handle);
913
2819
  Debug(this, "DoWrite()");
914
915
2819
  if (ssl_ == nullptr) {
916
4
    ClearError();
917
4
    error_ = "Write after DestroySSL";
918
4
    return UV_EPROTO;
919
  }
920
921
2815
  size_t length = 0;
922
  size_t i;
923
2815
  size_t nonempty_i = 0;
924
2815
  size_t nonempty_count = 0;
925
12965
  for (i = 0; i < count; i++) {
926
10150
    length += bufs[i].len;
927
10150
    if (bufs[i].len > 0) {
928
9847
      nonempty_i = i;
929
9847
      nonempty_count += 1;
930
    }
931
  }
932
933
  // We want to trigger a Write() on the underlying stream to drive the stream
934
  // system, but don't want to encrypt empty buffers into a TLS frame, so see
935
  // if we can find something to Write().
936
  // First, call ClearOut(). It does an SSL_read(), which might cause handshake
937
  // or other internal messages to be encrypted. If it does, write them later
938
  // with EncOut().
939
  // If there is still no encrypted output, call Write(bufs) on the underlying
940
  // stream. Since the bufs are empty, it won't actually write non-TLS data
941
  // onto the socket, we just want the side-effects. After, make sure the
942
  // WriteWrap was accepted by the stream, or that we call Done() on it.
943
2815
  if (length == 0) {
944
201
    Debug(this, "Empty write");
945
201
    ClearOut();
946
201
    if (BIO_pending(enc_out_) == 0) {
947
100
      Debug(this, "No pending encrypted output, writing to underlying stream");
948
100
      CHECK(!current_empty_write_);
949
100
      current_empty_write_.reset(w->GetAsyncWrap());
950
      StreamWriteResult res =
951
100
          underlying_stream()->Write(bufs, count, send_handle);
952
100
      if (!res.async) {
953
100
        BaseObjectPtr<TLSWrap> strong_ref{this};
954
100
        env()->SetImmediate([this, strong_ref](Environment* env) {
955
100
          OnStreamAfterWrite(WriteWrap::FromObject(current_empty_write_), 0);
956
100
        });
957
      }
958
100
      return 0;
959
    }
960
  }
961
962
  // Store the current write wrap
963
2715
  CHECK(!current_write_);
964
2715
  current_write_.reset(w->GetAsyncWrap());
965
966
  // Write encrypted data to underlying stream and call Done().
967
2715
  if (length == 0) {
968
101
    EncOut();
969
101
    return 0;
970
  }
971
972
2614
  std::unique_ptr<BackingStore> bs;
973
5228
  MarkPopErrorOnReturn mark_pop_error_on_return;
974
975
2614
  int written = 0;
976
977
  // It is common for zero length buffers to be written,
978
  // don't copy data if there there is one buffer with data
979
  // and one or more zero length buffers.
980
  // _http_outgoing.js writes a zero length buffer in
981
  // in OutgoingMessage.prototype.end.  If there was a large amount
982
  // of data supplied to end() there is no sense allocating
983
  // and copying it when it could just be used.
984
985
2614
  if (nonempty_count != 1) {
986
    {
987
1614
      NoArrayBufferZeroFillScope no_zero_fill_scope(env()->isolate_data());
988
1614
      bs = ArrayBuffer::NewBackingStore(env()->isolate(), length);
989
    }
990
1614
    size_t offset = 0;
991
10463
    for (i = 0; i < count; i++) {
992
8849
      memcpy(static_cast<char*>(bs->Data()) + offset,
993
8849
             bufs[i].base, bufs[i].len);
994
8849
      offset += bufs[i].len;
995
    }
996
997
1614
    NodeBIO::FromBIO(enc_out_)->set_allocate_tls_hint(length);
998
1614
    written = SSL_write(ssl_.get(), bs->Data(), length);
999
  } else {
1000
    // Only one buffer: try to write directly, only store if it fails
1001
1000
    uv_buf_t* buf = &bufs[nonempty_i];
1002
1000
    NodeBIO::FromBIO(enc_out_)->set_allocate_tls_hint(buf->len);
1003
1000
    written = SSL_write(ssl_.get(), buf->base, buf->len);
1004
1005
1000
    if (written == -1) {
1006
181
      NoArrayBufferZeroFillScope no_zero_fill_scope(env()->isolate_data());
1007
181
      bs = ArrayBuffer::NewBackingStore(env()->isolate(), length);
1008
181
      memcpy(bs->Data(), buf->base, buf->len);
1009
    }
1010
  }
1011
1012

2614
  CHECK(written == -1 || written == static_cast<int>(length));
1013
2614
  Debug(this, "Writing %zu bytes, written = %d", length, written);
1014
1015
2614
  if (written == -1) {
1016
    // If we stopped writing because of an error, it's fatal, discard the data.
1017
186
    int err = GetSSLError(written);
1018

186
    if (err == SSL_ERROR_SSL || err == SSL_ERROR_SYSCALL) {
1019
      // TODO(@jasnell): What are we doing with the error?
1020
3
      Debug(this, "Got SSL error (%d), returning UV_EPROTO", err);
1021
3
      current_write_.reset();
1022
3
      return UV_EPROTO;
1023
    }
1024
1025
183
    Debug(this, "Saving data for later write");
1026
    // Otherwise, save unwritten data so it can be written later by ClearIn().
1027

183
    CHECK(!pending_cleartext_input_ ||
1028
          pending_cleartext_input_->ByteLength() == 0);
1029
183
    pending_cleartext_input_ = std::move(bs);
1030
  }
1031
1032
  // Write any encrypted/handshake output that may be ready.
1033
  // Guard against sync call of current_write_->Done(), its unsupported.
1034
2611
  in_dowrite_ = true;
1035
2611
  EncOut();
1036
2611
  in_dowrite_ = false;
1037
1038
2611
  return 0;
1039
}
1040
1041
7175
uv_buf_t TLSWrap::OnStreamAlloc(size_t suggested_size) {
1042
7175
  CHECK_NOT_NULL(ssl_);
1043
1044
7175
  size_t size = suggested_size;
1045
7175
  char* base = NodeBIO::FromBIO(enc_in_)->PeekWritable(&size);
1046
7175
  return uv_buf_init(base, size);
1047
}
1048
1049
7199
void TLSWrap::OnStreamRead(ssize_t nread, const uv_buf_t& buf) {
1050
7199
  Debug(this, "Read %zd bytes from underlying stream", nread);
1051
1052
  // Ignore everything after close_notify (rfc5246#section-7.2.1)
1053
7199
  if (eof_)
1054
611
    return;
1055
1056
6588
  if (nread < 0)  {
1057
    // Error should be emitted only after all data was read
1058
241
    ClearOut();
1059
1060
241
    if (nread == UV_EOF) {
1061
      // underlying stream already should have also called ReadStop on itself
1062
237
      eof_ = true;
1063
    }
1064
1065
241
    EmitRead(nread);
1066
241
    return;
1067
  }
1068
1069
  // DestroySSL() is the only thing that un-sets ssl_, but that also removes
1070
  // this TLSWrap as a stream listener, so we should not receive OnStreamRead()
1071
  // calls anymore.
1072
6347
  CHECK(ssl_);
1073
1074
  // Commit the amount of data actually read into the peeked/allocated buffer
1075
  // from the underlying stream.
1076
6347
  NodeBIO* enc_in = NodeBIO::FromBIO(enc_in_);
1077
6347
  enc_in->Commit(nread);
1078
1079
  // Parse ClientHello first, if we need to. It's only parsed if session event
1080
  // listeners are used on the server side.  "ended" is the initial state, so
1081
  // can mean parsing was never started, or that parsing is finished. Either
1082
  // way, ended means we can give the buffered data to SSL.
1083
6347
  if (!hello_parser_.IsEnded()) {
1084
20
    size_t avail = 0;
1085
20
    uint8_t* data = reinterpret_cast<uint8_t*>(enc_in->Peek(&avail));
1086

20
    CHECK_IMPLIES(data == nullptr, avail == 0);
1087
20
    Debug(this, "Passing %zu bytes to the hello parser", avail);
1088
20
    return hello_parser_.Parse(data, avail);
1089
  }
1090
1091
  // Cycle OpenSSL's state
1092
6327
  Cycle();
1093
}
1094
1095
1488
ShutdownWrap* TLSWrap::CreateShutdownWrap(Local<Object> req_wrap_object) {
1096
1488
  return underlying_stream()->CreateShutdownWrap(req_wrap_object);
1097
}
1098
1099
1488
int TLSWrap::DoShutdown(ShutdownWrap* req_wrap) {
1100
1488
  Debug(this, "DoShutdown()");
1101
2976
  MarkPopErrorOnReturn mark_pop_error_on_return;
1102
1103

1488
  if (ssl_ && SSL_shutdown(ssl_.get()) == 0)
1104
951
    SSL_shutdown(ssl_.get());
1105
1106
1488
  shutdown_ = true;
1107
1488
  EncOut();
1108
1488
  return underlying_stream()->DoShutdown(req_wrap);
1109
}
1110
1111
12364
void TLSWrap::SetVerifyMode(const FunctionCallbackInfo<Value>& args) {
1112
  TLSWrap* wrap;
1113
12364
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1114
1115
12364
  CHECK_EQ(args.Length(), 2);
1116
12364
  CHECK(args[0]->IsBoolean());
1117
12364
  CHECK(args[1]->IsBoolean());
1118
12364
  CHECK_NOT_NULL(wrap->ssl_);
1119
1120
  int verify_mode;
1121
12364
  if (wrap->is_server()) {
1122
922
    bool request_cert = args[0]->IsTrue();
1123
922
    if (!request_cert) {
1124
      // If no cert is requested, there will be none to reject as unauthorized.
1125
838
      verify_mode = SSL_VERIFY_NONE;
1126
    } else {
1127
84
      bool reject_unauthorized = args[1]->IsTrue();
1128
84
      verify_mode = SSL_VERIFY_PEER;
1129
84
      if (reject_unauthorized)
1130
48
        verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1131
    }
1132
  } else {
1133
    // Servers always send a cert if the cipher is not anonymous (anon is
1134
    // disabled by default), so use VERIFY_NONE and check the cert after the
1135
    // handshake has completed.
1136
11442
    verify_mode = SSL_VERIFY_NONE;
1137
  }
1138
1139
  // Always allow a connection. We'll reject in javascript.
1140
12364
  SSL_set_verify(wrap->ssl_.get(), verify_mode, VerifyCallback);
1141
}
1142
1143
220
void TLSWrap::EnableSessionCallbacks(const FunctionCallbackInfo<Value>& args) {
1144
  TLSWrap* wrap;
1145
420
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1146
220
  CHECK_NOT_NULL(wrap->ssl_);
1147
220
  wrap->enable_session_callbacks();
1148
1149
  // Clients don't use the HelloParser.
1150
220
  if (wrap->is_client())
1151
200
    return;
1152
1153
20
  NodeBIO::FromBIO(wrap->enc_in_)->set_initial(kMaxHelloLength);
1154
20
  wrap->hello_parser_.Start(OnClientHello,
1155
                            OnClientHelloParseEnd,
1156
                            wrap);
1157
}
1158
1159
8
void TLSWrap::EnableKeylogCallback(const FunctionCallbackInfo<Value>& args) {
1160
  TLSWrap* wrap;
1161
8
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1162
8
  CHECK(wrap->sc_);
1163
8
  wrap->sc_->SetKeylogCallback(KeylogCallback);
1164
}
1165
1166
// Check required capabilities were not excluded from the OpenSSL build:
1167
// - OPENSSL_NO_SSL_TRACE excludes SSL_trace()
1168
// - OPENSSL_NO_STDIO excludes BIO_new_fp()
1169
// HAVE_SSL_TRACE is available on the internal tcp_wrap binding for the tests.
1170
#if defined(OPENSSL_NO_SSL_TRACE) || defined(OPENSSL_NO_STDIO)
1171
# define HAVE_SSL_TRACE 0
1172
#else
1173
# define HAVE_SSL_TRACE 1
1174
#endif
1175
1176
4
void TLSWrap::EnableTrace(const FunctionCallbackInfo<Value>& args) {
1177
  TLSWrap* wrap;
1178
4
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1179
1180
#if HAVE_SSL_TRACE
1181
4
  if (wrap->ssl_) {
1182
4
    wrap->bio_trace_.reset(BIO_new_fp(stderr,  BIO_NOCLOSE | BIO_FP_TEXT));
1183
4
    SSL_set_msg_callback(wrap->ssl_.get(), [](int write_p, int version, int
1184
          content_type, const void* buf, size_t len, SSL* ssl, void* arg)
1185
114
        -> void {
1186
        // BIO_write(), etc., called by SSL_trace, may error. The error should
1187
        // be ignored, trace is a "best effort", and its usually because stderr
1188
        // is a non-blocking pipe, and its buffer has overflowed. Leaving errors
1189
        // on the stack that can get picked up by later SSL_ calls causes
1190
        // unwanted failures in SSL_ calls, so keep the error stack unchanged.
1191
228
        MarkPopErrorOnReturn mark_pop_error_on_return;
1192
114
        SSL_trace(write_p,  version, content_type, buf, len, ssl, arg);
1193
114
    });
1194
4
    SSL_set_msg_callback_arg(wrap->ssl_.get(), wrap->bio_trace_.get());
1195
  }
1196
#endif
1197
}
1198
1199
12323
void TLSWrap::DestroySSL(const FunctionCallbackInfo<Value>& args) {
1200
  TLSWrap* wrap;
1201
12323
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1202
12323
  wrap->Destroy();
1203
12323
  Debug(wrap, "DestroySSL() finished");
1204
}
1205
1206
24704
void TLSWrap::Destroy() {
1207
24704
  if (!ssl_)
1208
12323
    return;
1209
1210
  // If there is a write happening, mark it as finished.
1211
12381
  write_callback_scheduled_ = true;
1212
1213
  // And destroy
1214
12381
  InvokeQueued(UV_ECANCELED, "Canceled because of SSL destruction");
1215
1216
12381
  env()->isolate()->AdjustAmountOfExternalAllocatedMemory(-kExternalSize);
1217
12381
  ssl_.reset();
1218
1219
12381
  enc_in_ = nullptr;
1220
12381
  enc_out_ = nullptr;
1221
1222
12381
  if (underlying_stream() != nullptr)
1223
12340
    underlying_stream()->RemoveStreamListener(this);
1224
1225
12381
  sc_.reset();
1226
}
1227
1228
25
void TLSWrap::EnableCertCb(const FunctionCallbackInfo<Value>& args) {
1229
  TLSWrap* wrap;
1230
25
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1231
25
  wrap->WaitForCertCb(OnClientHelloParseEnd, wrap);
1232
}
1233
1234
25
void TLSWrap::WaitForCertCb(CertCb cb, void* arg) {
1235
25
  cert_cb_ = cb;
1236
25
  cert_cb_arg_ = arg;
1237
25
}
1238
1239
39
void TLSWrap::OnClientHelloParseEnd(void* arg) {
1240
39
  TLSWrap* c = static_cast<TLSWrap*>(arg);
1241
  Debug(c, "OnClientHelloParseEnd()");
1242
39
  c->Cycle();
1243
39
}
1244
1245
1425
void TLSWrap::GetServername(const FunctionCallbackInfo<Value>& args) {
1246
1425
  Environment* env = Environment::GetCurrent(args);
1247
1248
  TLSWrap* wrap;
1249
1425
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1250
1251
1425
  CHECK_NOT_NULL(wrap->ssl_);
1252
1253
1425
  const char* servername = GetServerName(wrap->ssl_.get());
1254
1425
  if (servername != nullptr) {
1255
462
    args.GetReturnValue().Set(OneByteString(env->isolate(), servername));
1256
  } else {
1257
2388
    args.GetReturnValue().Set(false);
1258
  }
1259
}
1260
1261
250
void TLSWrap::SetServername(const FunctionCallbackInfo<Value>& args) {
1262
250
  Environment* env = Environment::GetCurrent(args);
1263
1264
  TLSWrap* wrap;
1265
250
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1266
1267
250
  CHECK_EQ(args.Length(), 1);
1268
500
  CHECK(args[0]->IsString());
1269
250
  CHECK(!wrap->started_);
1270
250
  CHECK(wrap->is_client());
1271
1272
250
  CHECK(wrap->ssl_);
1273
1274
750
  Utf8Value servername(env->isolate(), args[0].As<String>());
1275
250
  SSL_set_tlsext_host_name(wrap->ssl_.get(), *servername);
1276
}
1277
1278
985
int TLSWrap::SelectSNIContextCallback(SSL* s, int* ad, void* arg) {
1279
985
  TLSWrap* p = static_cast<TLSWrap*>(SSL_get_app_data(s));
1280
985
  Environment* env = p->env();
1281
1970
  HandleScope handle_scope(env->isolate());
1282
985
  Context::Scope context_scope(env->context());
1283
1284
985
  const char* servername = GetServerName(s);
1285
985
  if (!Set(env, p->GetOwner(), env->servername_string(), servername))
1286
    return SSL_TLSEXT_ERR_NOACK;
1287
1288
2955
  Local<Value> ctx = p->object()->Get(env->context(), env->sni_context_string())
1289
985
      .FromMaybe(Local<Value>());
1290
1291

1970
  if (UNLIKELY(ctx.IsEmpty()) || !ctx->IsObject())
1292
985
    return SSL_TLSEXT_ERR_NOACK;
1293
1294
  if (!env->secure_context_constructor_template()->HasInstance(ctx)) {
1295
    // Failure: incorrect SNI context object
1296
    Local<Value> err = Exception::TypeError(env->sni_context_err_string());
1297
    p->MakeCallback(env->onerror_string(), 1, &err);
1298
    return SSL_TLSEXT_ERR_NOACK;
1299
  }
1300
1301
  SecureContext* sc = Unwrap<SecureContext>(ctx.As<Object>());
1302
  CHECK_NOT_NULL(sc);
1303
  p->sni_context_ = BaseObjectPtr<SecureContext>(sc);
1304
1305
  ConfigureSecureContext(sc);
1306
  CHECK_EQ(SSL_set_SSL_CTX(p->ssl_.get(), sc->ctx().get()), sc->ctx().get());
1307
  p->SetCACerts(sc);
1308
1309
  return SSL_TLSEXT_ERR_OK;
1310
}
1311
1312
11
int TLSWrap::SetCACerts(SecureContext* sc) {
1313
11
  int err = SSL_set1_verify_cert_store(ssl_.get(),
1314
                                       SSL_CTX_get_cert_store(sc->ctx().get()));
1315
11
  if (err != 1)
1316
    return err;
1317
1318
  STACK_OF(X509_NAME)* list =
1319
11
      SSL_dup_CA_list(SSL_CTX_get_client_CA_list(sc->ctx().get()));
1320
1321
  // NOTE: `SSL_set_client_CA_list` takes the ownership of `list`
1322
11
  SSL_set_client_CA_list(ssl_.get(), list);
1323
11
  return 1;
1324
}
1325
1326
#ifndef OPENSSL_NO_PSK
1327
1328
2
void TLSWrap::SetPskIdentityHint(const FunctionCallbackInfo<Value>& args) {
1329
  TLSWrap* p;
1330
2
  ASSIGN_OR_RETURN_UNWRAP(&p, args.Holder());
1331
2
  CHECK_NOT_NULL(p->ssl_);
1332
1333
2
  Environment* env = p->env();
1334
2
  Isolate* isolate = env->isolate();
1335
1336
4
  CHECK(args[0]->IsString());
1337
6
  Utf8Value hint(isolate, args[0].As<String>());
1338
1339
2
  if (!SSL_use_psk_identity_hint(p->ssl_.get(), *hint)) {
1340
1
    Local<Value> err = node::ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED(isolate);
1341
1
    p->MakeCallback(env->onerror_string(), 1, &err);
1342
  }
1343
}
1344
1345
20
void TLSWrap::EnablePskCallback(const FunctionCallbackInfo<Value>& args) {
1346
  TLSWrap* wrap;
1347
20
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1348
20
  CHECK_NOT_NULL(wrap->ssl_);
1349
1350
20
  SSL_set_psk_server_callback(wrap->ssl_.get(), PskServerCallback);
1351
20
  SSL_set_psk_client_callback(wrap->ssl_.get(), PskClientCallback);
1352
}
1353
1354
9
unsigned int TLSWrap::PskServerCallback(
1355
    SSL* s,
1356
    const char* identity,
1357
    unsigned char* psk,
1358
    unsigned int max_psk_len) {
1359
9
  TLSWrap* p = static_cast<TLSWrap*>(SSL_get_app_data(s));
1360
1361
9
  Environment* env = p->env();
1362
18
  HandleScope scope(env->isolate());
1363
1364
  Local<String> identity_str =
1365
18
      String::NewFromUtf8(env->isolate(), identity).FromMaybe(Local<String>());
1366
9
  if (UNLIKELY(identity_str.IsEmpty()))
1367
    return 0;
1368
1369
  // Make sure there are no utf8 replacement symbols.
1370
18
  Utf8Value identity_utf8(env->isolate(), identity_str);
1371
9
  if (strcmp(*identity_utf8, identity) != 0)
1372
    return 0;
1373
1374
  Local<Value> argv[] = {
1375
    identity_str,
1376
    Integer::NewFromUnsigned(env->isolate(), max_psk_len)
1377
9
  };
1378
1379
  Local<Value> psk_val =
1380
9
      p->MakeCallback(env->onpskexchange_symbol(), arraysize(argv), argv)
1381
9
          .FromMaybe(Local<Value>());
1382

18
  if (UNLIKELY(psk_val.IsEmpty()) || !psk_val->IsArrayBufferView())
1383
1
    return 0;
1384
1385
8
  ArrayBufferViewContents<char> psk_buf(psk_val);
1386
1387
8
  if (psk_buf.length() > max_psk_len)
1388
    return 0;
1389
1390
8
  memcpy(psk, psk_buf.data(), psk_buf.length());
1391
8
  return psk_buf.length();
1392
}
1393
1394
9
unsigned int TLSWrap::PskClientCallback(
1395
    SSL* s,
1396
    const char* hint,
1397
    char* identity,
1398
    unsigned int max_identity_len,
1399
    unsigned char* psk,
1400
    unsigned int max_psk_len) {
1401
9
  TLSWrap* p = static_cast<TLSWrap*>(SSL_get_app_data(s));
1402
1403
9
  Environment* env = p->env();
1404
18
  HandleScope scope(env->isolate());
1405
1406
  Local<Value> argv[] = {
1407
    Null(env->isolate()),
1408
    Integer::NewFromUnsigned(env->isolate(), max_psk_len),
1409
    Integer::NewFromUnsigned(env->isolate(), max_identity_len)
1410
27
  };
1411
1412
9
  if (hint != nullptr) {
1413
    Local<String> local_hint =
1414
2
        String::NewFromUtf8(env->isolate(), hint).FromMaybe(Local<String>());
1415
1
    if (UNLIKELY(local_hint.IsEmpty()))
1416
      return 0;
1417
1418
1
    argv[0] = local_hint;
1419
  }
1420
1421
  Local<Value> ret =
1422
9
      p->MakeCallback(env->onpskexchange_symbol(), arraysize(argv), argv)
1423
9
          .FromMaybe(Local<Value>());
1424

18
  if (UNLIKELY(ret.IsEmpty()) || !ret->IsObject())
1425
    return 0;
1426
1427
9
  Local<Object> obj = ret.As<Object>();
1428
1429
18
  Local<Value> psk_val = obj->Get(env->context(), env->psk_string())
1430
9
      .FromMaybe(Local<Value>());
1431

18
  if (UNLIKELY(psk_val.IsEmpty()) || !psk_val->IsArrayBufferView())
1432
    return 0;
1433
1434
9
  ArrayBufferViewContents<char> psk_buf(psk_val);
1435
9
  if (psk_buf.length() > max_psk_len)
1436
    return 0;
1437
1438
18
  Local<Value> identity_val = obj->Get(env->context(), env->identity_string())
1439
9
      .FromMaybe(Local<Value>());
1440

27
  if (UNLIKELY(identity_val.IsEmpty()) || !identity_val->IsString())
1441
    return 0;
1442
1443
18
  Utf8Value identity_buf(env->isolate(), identity_val);
1444
1445
9
  if (identity_buf.length() > max_identity_len)
1446
    return 0;
1447
1448
9
  memcpy(identity, *identity_buf, identity_buf.length());
1449
9
  memcpy(psk, psk_buf.data(), psk_buf.length());
1450
1451
9
  return psk_buf.length();
1452
}
1453
1454
#endif  // ifndef OPENSSL_NO_PSK
1455
1456
2
void TLSWrap::GetWriteQueueSize(const FunctionCallbackInfo<Value>& info) {
1457
  TLSWrap* wrap;
1458
2
  ASSIGN_OR_RETURN_UNWRAP(&wrap, info.This());
1459
1460
2
  if (!wrap->ssl_)
1461
    return info.GetReturnValue().Set(0);
1462
1463
2
  uint32_t write_queue_size = BIO_pending(wrap->enc_out_);
1464
4
  info.GetReturnValue().Set(write_queue_size);
1465
}
1466
1467
void TLSWrap::MemoryInfo(MemoryTracker* tracker) const {
1468
  tracker->TrackField("ocsp_response", ocsp_response_);
1469
  tracker->TrackField("sni_context", sni_context_);
1470
  tracker->TrackField("error", error_);
1471
  if (pending_cleartext_input_)
1472
    tracker->TrackField("pending_cleartext_input", pending_cleartext_input_);
1473
  if (enc_in_ != nullptr)
1474
    tracker->TrackField("enc_in", NodeBIO::FromBIO(enc_in_));
1475
  if (enc_out_ != nullptr)
1476
    tracker->TrackField("enc_out", NodeBIO::FromBIO(enc_out_));
1477
}
1478
1479
22
void TLSWrap::CertCbDone(const FunctionCallbackInfo<Value>& args) {
1480
22
  Environment* env = Environment::GetCurrent(args);
1481
  TLSWrap* w;
1482
24
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1483
1484

22
  CHECK(w->is_waiting_cert_cb() && w->cert_cb_running_);
1485
1486
22
  Local<Object> object = w->object();
1487
44
  Local<Value> ctx = object->Get(env->context(), env->sni_context_string())
1488
22
      .FromMaybe(Local<Value>());
1489
22
  if (UNLIKELY(ctx.IsEmpty()))
1490
    return;
1491
1492
22
  Local<FunctionTemplate> cons = env->secure_context_constructor_template();
1493
22
  if (cons->HasInstance(ctx)) {
1494
12
    SecureContext* sc = Unwrap<SecureContext>(ctx.As<Object>());
1495
12
    CHECK_NOT_NULL(sc);
1496
    // Store the SNI context for later use.
1497
12
    w->sni_context_ = BaseObjectPtr<SecureContext>(sc);
1498
1499


12
    if (UseSNIContext(w->ssl_, w->sni_context_) && !w->SetCACerts(sc)) {
1500
      // Not clear why sometimes we throw error, and sometimes we call
1501
      // onerror(). Both cause .destroy(), but onerror does a bit more.
1502
      unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
1503
      return ThrowCryptoError(env, err, "CertCbDone");
1504
    }
1505
10
  } else if (ctx->IsObject()) {
1506
    // Failure: incorrect SNI context object
1507
2
    Local<Value> err = Exception::TypeError(env->sni_context_err_string());
1508
2
    w->MakeCallback(env->onerror_string(), 1, &err);
1509
2
    return;
1510
  }
1511
1512
  CertCb cb;
1513
  void* arg;
1514
1515
20
  cb = w->cert_cb_;
1516
20
  arg = w->cert_cb_arg_;
1517
1518
20
  w->cert_cb_running_ = false;
1519
20
  w->cert_cb_ = nullptr;
1520
20
  w->cert_cb_arg_ = nullptr;
1521
1522
20
  cb(arg);
1523
}
1524
1525
245
void TLSWrap::SetALPNProtocols(const FunctionCallbackInfo<Value>& args) {
1526
  TLSWrap* w;
1527
245
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1528
245
  Environment* env = w->env();
1529

490
  if (args.Length() < 1 || !Buffer::HasInstance(args[0]))
1530
    return env->ThrowTypeError("Must give a Buffer as first argument");
1531
1532
245
  if (w->is_client()) {
1533
40
    CHECK(SetALPN(w->ssl_, args[0]));
1534
  } else {
1535

820
    CHECK(
1536
        w->object()->SetPrivate(
1537
            env->context(),
1538
            env->alpn_buffer_private_symbol(),
1539
            args[0]).FromJust());
1540
    // Server should select ALPN protocol from list of advertised by client
1541
205
    SSL_CTX_set_alpn_select_cb(SSL_get_SSL_CTX(w->ssl_.get()),
1542
                               SelectALPNCallback,
1543
                               nullptr);
1544
  }
1545
}
1546
1547
497
void TLSWrap::GetPeerCertificate(const FunctionCallbackInfo<Value>& args) {
1548
  TLSWrap* w;
1549
497
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1550
497
  Environment* env = w->env();
1551
1552

994
  bool abbreviated = args.Length() < 1 || !args[0]->IsTrue();
1553
1554
  Local<Value> ret;
1555
497
  if (GetPeerCert(
1556
          env,
1557
497
          w->ssl_,
1558
          abbreviated,
1559
994
          w->is_server()).ToLocal(&ret))
1560
994
    args.GetReturnValue().Set(ret);
1561
}
1562
1563
1
void TLSWrap::GetPeerX509Certificate(const FunctionCallbackInfo<Value>& args) {
1564
  TLSWrap* w;
1565
1
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1566
1
  Environment* env = w->env();
1567
1568
1
  X509Certificate::GetPeerCertificateFlag flag = w->is_server()
1569
1
      ? X509Certificate::GetPeerCertificateFlag::SERVER
1570
1
      : X509Certificate::GetPeerCertificateFlag::NONE;
1571
1572
  Local<Value> ret;
1573
2
  if (X509Certificate::GetPeerCert(env, w->ssl_, flag).ToLocal(&ret))
1574
2
    args.GetReturnValue().Set(ret);
1575
}
1576
1577
12
void TLSWrap::GetCertificate(const FunctionCallbackInfo<Value>& args) {
1578
  TLSWrap* w;
1579
12
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1580
12
  Environment* env = w->env();
1581
1582
  Local<Value> ret;
1583
24
  if (GetCert(env, w->ssl_).ToLocal(&ret))
1584
24
    args.GetReturnValue().Set(ret);
1585
}
1586
1587
1
void TLSWrap::GetX509Certificate(const FunctionCallbackInfo<Value>& args) {
1588
  TLSWrap* w;
1589
1
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1590
1
  Environment* env = w->env();
1591
  Local<Value> ret;
1592
2
  if (X509Certificate::GetCert(env, w->ssl_).ToLocal(&ret))
1593
2
    args.GetReturnValue().Set(ret);
1594
}
1595
1596
3
void TLSWrap::GetFinished(const FunctionCallbackInfo<Value>& args) {
1597
3
  Environment* env = Environment::GetCurrent(args);
1598
1599
  TLSWrap* w;
1600
4
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1601
1602
  // We cannot just pass nullptr to SSL_get_finished()
1603
  // because it would further be propagated to memcpy(),
1604
  // where the standard requirements as described in ISO/IEC 9899:2011
1605
  // sections 7.21.2.1, 7.21.1.2, and 7.1.4, would be violated.
1606
  // Thus, we use a dummy byte.
1607
  char dummy[1];
1608
3
  size_t len = SSL_get_finished(w->ssl_.get(), dummy, sizeof dummy);
1609
3
  if (len == 0)
1610
1
    return;
1611
1612
2
  std::unique_ptr<BackingStore> bs;
1613
  {
1614
2
    NoArrayBufferZeroFillScope no_zero_fill_scope(env->isolate_data());
1615
2
    bs = ArrayBuffer::NewBackingStore(env->isolate(), len);
1616
  }
1617
1618
2
  CHECK_EQ(bs->ByteLength(),
1619
           SSL_get_finished(w->ssl_.get(), bs->Data(), bs->ByteLength()));
1620
1621
2
  Local<ArrayBuffer> ab = ArrayBuffer::New(env->isolate(), std::move(bs));
1622
  Local<Value> buffer;
1623
4
  if (!Buffer::New(env, ab, 0, ab->ByteLength()).ToLocal(&buffer)) return;
1624
4
  args.GetReturnValue().Set(buffer);
1625
}
1626
1627
3
void TLSWrap::GetPeerFinished(const FunctionCallbackInfo<Value>& args) {
1628
3
  Environment* env = Environment::GetCurrent(args);
1629
1630
  TLSWrap* w;
1631
4
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1632
1633
  // We cannot just pass nullptr to SSL_get_peer_finished()
1634
  // because it would further be propagated to memcpy(),
1635
  // where the standard requirements as described in ISO/IEC 9899:2011
1636
  // sections 7.21.2.1, 7.21.1.2, and 7.1.4, would be violated.
1637
  // Thus, we use a dummy byte.
1638
  char dummy[1];
1639
3
  size_t len = SSL_get_peer_finished(w->ssl_.get(), dummy, sizeof dummy);
1640
3
  if (len == 0)
1641
1
    return;
1642
1643
2
  std::unique_ptr<BackingStore> bs;
1644
  {
1645
2
    NoArrayBufferZeroFillScope no_zero_fill_scope(env->isolate_data());
1646
2
    bs = ArrayBuffer::NewBackingStore(env->isolate(), len);
1647
  }
1648
1649
2
  CHECK_EQ(bs->ByteLength(),
1650
           SSL_get_peer_finished(w->ssl_.get(), bs->Data(), bs->ByteLength()));
1651
1652
2
  Local<ArrayBuffer> ab = ArrayBuffer::New(env->isolate(), std::move(bs));
1653
  Local<Value> buffer;
1654
4
  if (!Buffer::New(env, ab, 0, ab->ByteLength()).ToLocal(&buffer)) return;
1655
4
  args.GetReturnValue().Set(buffer);
1656
}
1657
1658
19
void TLSWrap::GetSession(const FunctionCallbackInfo<Value>& args) {
1659
19
  Environment* env = Environment::GetCurrent(args);
1660
1661
  TLSWrap* w;
1662
19
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1663
1664
19
  SSL_SESSION* sess = SSL_get_session(w->ssl_.get());
1665
19
  if (sess == nullptr)
1666
    return;
1667
1668
19
  int slen = i2d_SSL_SESSION(sess, nullptr);
1669
19
  if (slen <= 0)
1670
    return;  // Invalid or malformed session.
1671
1672
19
  std::unique_ptr<BackingStore> bs;
1673
  {
1674
19
    NoArrayBufferZeroFillScope no_zero_fill_scope(env->isolate_data());
1675
19
    bs = ArrayBuffer::NewBackingStore(env->isolate(), slen);
1676
  }
1677
1678
19
  unsigned char* p = static_cast<unsigned char*>(bs->Data());
1679
19
  CHECK_LT(0, i2d_SSL_SESSION(sess, &p));
1680
1681
19
  Local<ArrayBuffer> ab = ArrayBuffer::New(env->isolate(), std::move(bs));
1682
  Local<Value> buffer;
1683
38
  if (!Buffer::New(env, ab, 0, ab->ByteLength()).ToLocal(&buffer)) return;
1684
38
  args.GetReturnValue().Set(buffer);
1685
}
1686
1687
114
void TLSWrap::SetSession(const FunctionCallbackInfo<Value>& args) {
1688
114
  Environment* env = Environment::GetCurrent(args);
1689
1690
  TLSWrap* w;
1691
114
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1692
1693
114
  if (args.Length() < 1)
1694
    return THROW_ERR_MISSING_ARGS(env, "Session argument is mandatory");
1695
1696
114
  THROW_AND_RETURN_IF_NOT_BUFFER(env, args[0], "Session");
1697
114
  ArrayBufferViewContents<unsigned char> sbuf(args[0]);
1698
114
  SSLSessionPointer sess = GetTLSSession(sbuf.data(), sbuf.length());
1699
114
  if (sess == nullptr)
1700
    return;  // TODO(tniessen): figure out error handling
1701
1702
114
  if (!SetTLSSession(w->ssl_, sess))
1703
    return env->ThrowError("SSL_set_session error");
1704
}
1705
1706
522
void TLSWrap::IsSessionReused(const FunctionCallbackInfo<Value>& args) {
1707
  TLSWrap* w;
1708
522
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1709
522
  bool yes = SSL_session_reused(w->ssl_.get());
1710
1044
  args.GetReturnValue().Set(yes);
1711
}
1712
1713
964
void TLSWrap::VerifyError(const FunctionCallbackInfo<Value>& args) {
1714
964
  Environment* env = Environment::GetCurrent(args);
1715
  TLSWrap* w;
1716
1460
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1717
1718
  // XXX(bnoordhuis) The UNABLE_TO_GET_ISSUER_CERT error when there is no
1719
  // peer certificate is questionable but it's compatible with what was
1720
  // here before.
1721
  long x509_verify_error =  // NOLINT(runtime/int)
1722
964
      VerifyPeerCertificate(
1723
964
          w->ssl_,
1724
          X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT);
1725
1726
964
  if (x509_verify_error == X509_V_OK)
1727
992
    return args.GetReturnValue().SetNull();
1728
1729
468
  const char* reason = X509_verify_cert_error_string(x509_verify_error);
1730
468
  const char* code = X509ErrorCode(x509_verify_error);
1731
1732
  Local<Object> error =
1733
468
      Exception::Error(OneByteString(env->isolate(), reason))
1734
468
          ->ToObject(env->isolate()->GetCurrentContext())
1735
468
              .FromMaybe(Local<Object>());
1736
1737
468
  if (Set(env, error, env->code_string(), code))
1738
936
    args.GetReturnValue().Set(error);
1739
}
1740
1741
53
void TLSWrap::GetCipher(const FunctionCallbackInfo<Value>& args) {
1742
53
  Environment* env = Environment::GetCurrent(args);
1743
  TLSWrap* w;
1744
53
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1745
53
  args.GetReturnValue().Set(
1746
106
      GetCipherInfo(env, w->ssl_).FromMaybe(Local<Object>()));
1747
}
1748
1749
10
void TLSWrap::LoadSession(const FunctionCallbackInfo<Value>& args) {
1750
  TLSWrap* w;
1751
10
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1752
1753
  // TODO(@sam-github) check arg length and types in js, and CHECK in c++
1754

20
  if (args.Length() >= 1 && Buffer::HasInstance(args[0])) {
1755
10
    ArrayBufferViewContents<unsigned char> sbuf(args[0]);
1756
1757
10
    const unsigned char* p = sbuf.data();
1758
10
    SSL_SESSION* sess = d2i_SSL_SESSION(nullptr, &p, sbuf.length());
1759
1760
    // Setup next session and move hello to the BIO buffer
1761
10
    w->next_sess_.reset(sess);
1762
  }
1763
}
1764
1765
2
void TLSWrap::GetSharedSigalgs(const FunctionCallbackInfo<Value>& args) {
1766
2
  Environment* env = Environment::GetCurrent(args);
1767
  TLSWrap* w;
1768
2
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1769
1770
2
  SSL* ssl = w->ssl_.get();
1771
2
  int nsig = SSL_get_shared_sigalgs(ssl, 0, nullptr, nullptr, nullptr, nullptr,
1772
                                    nullptr);
1773
2
  MaybeStackBuffer<Local<Value>, 16> ret_arr(nsig);
1774
1775
5
  for (int i = 0; i < nsig; i++) {
1776
    int hash_nid;
1777
    int sign_nid;
1778
3
    std::string sig_with_md;
1779
1780
3
    SSL_get_shared_sigalgs(ssl, i, &sign_nid, &hash_nid, nullptr, nullptr,
1781
                           nullptr);
1782
1783

3
    switch (sign_nid) {
1784
      case EVP_PKEY_RSA:
1785
        sig_with_md = "RSA+";
1786
        break;
1787
1788
2
      case EVP_PKEY_RSA_PSS:
1789
2
        sig_with_md = "RSA-PSS+";
1790
2
        break;
1791
1792
      case EVP_PKEY_DSA:
1793
        sig_with_md = "DSA+";
1794
        break;
1795
1796
1
      case EVP_PKEY_EC:
1797
1
        sig_with_md = "ECDSA+";
1798
1
        break;
1799
1800
      case NID_ED25519:
1801
        sig_with_md = "Ed25519+";
1802
        break;
1803
1804
      case NID_ED448:
1805
        sig_with_md = "Ed448+";
1806
        break;
1807
#ifndef OPENSSL_NO_GOST
1808
      case NID_id_GostR3410_2001:
1809
        sig_with_md = "gost2001+";
1810
        break;
1811
1812
      case NID_id_GostR3410_2012_256:
1813
        sig_with_md = "gost2012_256+";
1814
        break;
1815
1816
      case NID_id_GostR3410_2012_512:
1817
        sig_with_md = "gost2012_512+";
1818
        break;
1819
#endif  // !OPENSSL_NO_GOST
1820
      default:
1821
        const char* sn = OBJ_nid2sn(sign_nid);
1822
1823
        if (sn != nullptr) {
1824
          sig_with_md = std::string(sn) + "+";
1825
        } else {
1826
          sig_with_md = "UNDEF+";
1827
        }
1828
        break;
1829
    }
1830
1831
3
    const char* sn_hash = OBJ_nid2sn(hash_nid);
1832
3
    if (sn_hash != nullptr) {
1833
3
      sig_with_md += std::string(sn_hash);
1834
    } else {
1835
      sig_with_md += "UNDEF";
1836
    }
1837
6
    ret_arr[i] = OneByteString(env->isolate(), sig_with_md.c_str());
1838
  }
1839
1840
4
  args.GetReturnValue().Set(
1841
                 Array::New(env->isolate(), ret_arr.out(), ret_arr.length()));
1842
}
1843
1844
3
void TLSWrap::ExportKeyingMaterial(const FunctionCallbackInfo<Value>& args) {
1845
3
  CHECK(args[0]->IsInt32());
1846
6
  CHECK(args[1]->IsString());
1847
1848
3
  Environment* env = Environment::GetCurrent(args);
1849
  TLSWrap* w;
1850
3
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1851
1852
6
  uint32_t olen = args[0].As<Uint32>()->Value();
1853
3
  Utf8Value label(env->isolate(), args[1]);
1854
1855
3
  std::unique_ptr<BackingStore> bs;
1856
  {
1857
3
    NoArrayBufferZeroFillScope no_zero_fill_scope(env->isolate_data());
1858
3
    bs = ArrayBuffer::NewBackingStore(env->isolate(), olen);
1859
  }
1860
1861
3
  ByteSource context;
1862
3
  bool use_context = !args[2]->IsUndefined();
1863
3
  if (use_context)
1864
2
    context = ByteSource::FromBuffer(args[2]);
1865
1866
6
  if (SSL_export_keying_material(
1867
3
          w->ssl_.get(),
1868
3
          static_cast<unsigned char*>(bs->Data()),
1869
          olen,
1870
3
          *label,
1871
          label.length(),
1872
          context.data<unsigned char>(),
1873
          context.size(),
1874
3
          use_context) != 1) {
1875
    return ThrowCryptoError(
1876
         env,
1877
         ERR_get_error(),
1878
         "SSL_export_keying_material");
1879
  }
1880
1881
3
  Local<ArrayBuffer> ab = ArrayBuffer::New(env->isolate(), std::move(bs));
1882
  Local<Value> buffer;
1883
6
  if (!Buffer::New(env, ab, 0, ab->ByteLength()).ToLocal(&buffer)) return;
1884
6
  args.GetReturnValue().Set(buffer);
1885
}
1886
1887
19
void TLSWrap::EndParser(const FunctionCallbackInfo<Value>& args) {
1888
  TLSWrap* w;
1889
19
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1890
19
  w->hello_parser_.End();
1891
}
1892
1893
92
void TLSWrap::Renegotiate(const FunctionCallbackInfo<Value>& args) {
1894
  TLSWrap* w;
1895
93
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1896
  ClearErrorOnReturn clear_error_on_return;
1897
92
  if (SSL_renegotiate(w->ssl_.get()) != 1)
1898
1
    return ThrowCryptoError(w->env(), ERR_get_error());
1899
}
1900
1901
18
void TLSWrap::GetTLSTicket(const FunctionCallbackInfo<Value>& args) {
1902
  TLSWrap* w;
1903
18
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1904
18
  Environment* env = w->env();
1905
1906
18
  SSL_SESSION* sess = SSL_get_session(w->ssl_.get());
1907
18
  if (sess == nullptr)
1908
    return;
1909
1910
  const unsigned char* ticket;
1911
  size_t length;
1912
18
  SSL_SESSION_get0_ticket(sess, &ticket, &length);
1913
1914
18
  if (ticket != nullptr) {
1915
18
    args.GetReturnValue().Set(
1916
36
        Buffer::Copy(env, reinterpret_cast<const char*>(ticket), length)
1917
            .FromMaybe(Local<Object>()));
1918
  }
1919
}
1920
1921
8
void TLSWrap::NewSessionDone(const FunctionCallbackInfo<Value>& args) {
1922
  TLSWrap* w;
1923
8
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1924
8
  w->awaiting_new_session_ = false;
1925
8
  w->NewSessionDoneCb();
1926
}
1927
1928
2
void TLSWrap::SetOCSPResponse(const FunctionCallbackInfo<Value>& args) {
1929
  TLSWrap* w;
1930
2
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1931
2
  Environment* env = w->env();
1932
1933
2
  if (args.Length() < 1)
1934
    return THROW_ERR_MISSING_ARGS(env, "OCSP response argument is mandatory");
1935
1936
2
  THROW_AND_RETURN_IF_NOT_BUFFER(env, args[0], "OCSP response");
1937
1938
8
  w->ocsp_response_.Reset(args.GetIsolate(), args[0].As<ArrayBufferView>());
1939
}
1940
1941
4
void TLSWrap::RequestOCSP(const FunctionCallbackInfo<Value>& args) {
1942
  TLSWrap* w;
1943
4
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1944
1945
4
  SSL_set_tlsext_status_type(w->ssl_.get(), TLSEXT_STATUSTYPE_ocsp);
1946
}
1947
1948
898
void TLSWrap::GetEphemeralKeyInfo(const FunctionCallbackInfo<Value>& args) {
1949
  TLSWrap* w;
1950
905
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1951
898
  Environment* env = Environment::GetCurrent(args);
1952
1953
898
  CHECK(w->ssl_);
1954
1955
  // tmp key is available on only client
1956
898
  if (w->is_server())
1957
14
    return args.GetReturnValue().SetNull();
1958
1959
2673
  args.GetReturnValue().Set(GetEphemeralKey(env, w->ssl_)
1960
      .FromMaybe(Local<Value>()));
1961
1962
  // TODO(@sam-github) semver-major: else return ThrowCryptoError(env,
1963
  // ERR_get_error())
1964
}
1965
1966
547
void TLSWrap::GetProtocol(const FunctionCallbackInfo<Value>& args) {
1967
547
  Environment* env = Environment::GetCurrent(args);
1968
  TLSWrap* w;
1969
547
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1970
1094
  args.GetReturnValue().Set(
1971
547
      OneByteString(env->isolate(), SSL_get_version(w->ssl_.get())));
1972
}
1973
1974
1802
void TLSWrap::GetALPNNegotiatedProto(const FunctionCallbackInfo<Value>& args) {
1975
1802
  Environment* env = Environment::GetCurrent(args);
1976
  TLSWrap* w;
1977
1802
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1978
1979
  const unsigned char* alpn_proto;
1980
  unsigned int alpn_proto_len;
1981
1982
1802
  SSL_get0_alpn_selected(w->ssl_.get(), &alpn_proto, &alpn_proto_len);
1983
1984
  Local<Value> result;
1985
1802
  if (alpn_proto_len == 0) {
1986
3478
    result = False(env->isolate());
1987
63
  } else if (alpn_proto_len == sizeof("h2") - 1 &&
1988
57
             0 == memcmp(alpn_proto, "h2", sizeof("h2") - 1)) {
1989
114
    result = env->h2_string();
1990
6
  } else if (alpn_proto_len == sizeof("http/1.1") - 1 &&
1991
2
             0 == memcmp(alpn_proto, "http/1.1", sizeof("http/1.1") - 1)) {
1992
4
    result = env->http_1_1_string();
1993
  } else {
1994
8
    result = OneByteString(env->isolate(), alpn_proto, alpn_proto_len);
1995
  }
1996
1997
3604
  args.GetReturnValue().Set(result);
1998
}
1999
2000
6374
void TLSWrap::Cycle() {
2001
  // Prevent recursion
2002
6374
  if (++cycle_depth_ > 1)
2003
14
    return;
2004
2005
12732
  for (; cycle_depth_ > 0; cycle_depth_--) {
2006
6374
    ClearIn();
2007
6374
    ClearOut();
2008
    // EncIn() doesn't exist, it happens via stream listener callbacks.
2009
6373
    EncOut();
2010
  }
2011
}
2012
2013
#ifdef SSL_set_max_send_fragment
2014
3
void TLSWrap::SetMaxSendFragment(const FunctionCallbackInfo<Value>& args) {
2015

6
  CHECK(args.Length() >= 1 && args[0]->IsNumber());
2016
3
  Environment* env = Environment::GetCurrent(args);
2017
  TLSWrap* w;
2018
3
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2019
6
  int rv = SSL_set_max_send_fragment(
2020
      w->ssl_.get(),
2021
      args[0]->Int32Value(env->context()).FromJust());
2022
6
  args.GetReturnValue().Set(rv);
2023
}
2024
#endif  // SSL_set_max_send_fragment
2025
2026
754
void TLSWrap::Initialize(
2027
    Local<Object> target,
2028
    Local<Value> unused,
2029
    Local<Context> context,
2030
    void* priv) {
2031
754
  Environment* env = Environment::GetCurrent(context);
2032
2033
754
  env->SetMethod(target, "wrap", TLSWrap::Wrap);
2034
2035
1508
  NODE_DEFINE_CONSTANT(target, HAVE_SSL_TRACE);
2036
2037
754
  Local<FunctionTemplate> t = BaseObject::MakeLazilyInitializedJSTemplate(env);
2038
  Local<String> tlsWrapString =
2039
754
      FIXED_ONE_BYTE_STRING(env->isolate(), "TLSWrap");
2040
754
  t->SetClassName(tlsWrapString);
2041
1508
  t->InstanceTemplate()->SetInternalFieldCount(StreamBase::kInternalFieldCount);
2042
2043
  Local<FunctionTemplate> get_write_queue_size =
2044
      FunctionTemplate::New(env->isolate(),
2045
                            GetWriteQueueSize,
2046
                            Local<Value>(),
2047
754
                            Signature::New(env->isolate(), t));
2048
3016
  t->PrototypeTemplate()->SetAccessorProperty(
2049
      env->write_queue_size_string(),
2050
      get_write_queue_size,
2051
      Local<FunctionTemplate>(),
2052
      static_cast<PropertyAttribute>(ReadOnly | DontDelete));
2053
2054
754
  t->Inherit(AsyncWrap::GetConstructorTemplate(env));
2055
2056
754
  env->SetProtoMethod(t, "certCbDone", CertCbDone);
2057
754
  env->SetProtoMethod(t, "destroySSL", DestroySSL);
2058
754
  env->SetProtoMethod(t, "enableCertCb", EnableCertCb);
2059
754
  env->SetProtoMethod(t, "endParser", EndParser);
2060
754
  env->SetProtoMethod(t, "enableKeylogCallback", EnableKeylogCallback);
2061
754
  env->SetProtoMethod(t, "enableSessionCallbacks", EnableSessionCallbacks);
2062
754
  env->SetProtoMethod(t, "enableTrace", EnableTrace);
2063
754
  env->SetProtoMethod(t, "getServername", GetServername);
2064
754
  env->SetProtoMethod(t, "loadSession", LoadSession);
2065
754
  env->SetProtoMethod(t, "newSessionDone", NewSessionDone);
2066
754
  env->SetProtoMethod(t, "receive", Receive);
2067
754
  env->SetProtoMethod(t, "renegotiate", Renegotiate);
2068
754
  env->SetProtoMethod(t, "requestOCSP", RequestOCSP);
2069
754
  env->SetProtoMethod(t, "setALPNProtocols", SetALPNProtocols);
2070
754
  env->SetProtoMethod(t, "setOCSPResponse", SetOCSPResponse);
2071
754
  env->SetProtoMethod(t, "setServername", SetServername);
2072
754
  env->SetProtoMethod(t, "setSession", SetSession);
2073
754
  env->SetProtoMethod(t, "setVerifyMode", SetVerifyMode);
2074
754
  env->SetProtoMethod(t, "start", Start);
2075
2076
754
  env->SetProtoMethodNoSideEffect(t, "exportKeyingMaterial",
2077
                                  ExportKeyingMaterial);
2078
754
  env->SetProtoMethodNoSideEffect(t, "isSessionReused", IsSessionReused);
2079
754
  env->SetProtoMethodNoSideEffect(t, "getALPNNegotiatedProtocol",
2080
                                  GetALPNNegotiatedProto);
2081
754
  env->SetProtoMethodNoSideEffect(t, "getCertificate", GetCertificate);
2082
754
  env->SetProtoMethodNoSideEffect(t, "getX509Certificate", GetX509Certificate);
2083
754
  env->SetProtoMethodNoSideEffect(t, "getCipher", GetCipher);
2084
754
  env->SetProtoMethodNoSideEffect(t, "getEphemeralKeyInfo",
2085
                                  GetEphemeralKeyInfo);
2086
754
  env->SetProtoMethodNoSideEffect(t, "getFinished", GetFinished);
2087
754
  env->SetProtoMethodNoSideEffect(t, "getPeerCertificate", GetPeerCertificate);
2088
754
  env->SetProtoMethodNoSideEffect(t, "getPeerX509Certificate",
2089
                                  GetPeerX509Certificate);
2090
754
  env->SetProtoMethodNoSideEffect(t, "getPeerFinished", GetPeerFinished);
2091
754
  env->SetProtoMethodNoSideEffect(t, "getProtocol", GetProtocol);
2092
754
  env->SetProtoMethodNoSideEffect(t, "getSession", GetSession);
2093
754
  env->SetProtoMethodNoSideEffect(t, "getSharedSigalgs", GetSharedSigalgs);
2094
754
  env->SetProtoMethodNoSideEffect(t, "getTLSTicket", GetTLSTicket);
2095
754
  env->SetProtoMethodNoSideEffect(t, "verifyError", VerifyError);
2096
2097
#ifdef SSL_set_max_send_fragment
2098
754
  env->SetProtoMethod(t, "setMaxSendFragment", SetMaxSendFragment);
2099
#endif  // SSL_set_max_send_fragment
2100
2101
#ifndef OPENSSL_NO_PSK
2102
754
  env->SetProtoMethod(t, "enablePskCallback", EnablePskCallback);
2103
754
  env->SetProtoMethod(t, "setPskIdentityHint", SetPskIdentityHint);
2104
#endif  // !OPENSSL_NO_PSK
2105
2106
754
  StreamBase::AddMethods(env, t);
2107
2108
754
  Local<Function> fn = t->GetFunction(env->context()).ToLocalChecked();
2109
2110
754
  env->set_tls_wrap_constructor_function(fn);
2111
2112
754
  target->Set(env->context(), tlsWrapString, fn).Check();
2113
754
}
2114
2115
5201
void TLSWrap::RegisterExternalReferences(ExternalReferenceRegistry* registry) {
2116
5201
  registry->Register(TLSWrap::Wrap);
2117
5201
  registry->Register(GetWriteQueueSize);
2118
2119
5201
  registry->Register(CertCbDone);
2120
5201
  registry->Register(DestroySSL);
2121
5201
  registry->Register(EnableCertCb);
2122
5201
  registry->Register(EndParser);
2123
5201
  registry->Register(EnableKeylogCallback);
2124
5201
  registry->Register(EnableSessionCallbacks);
2125
5201
  registry->Register(EnableTrace);
2126
5201
  registry->Register(GetServername);
2127
5201
  registry->Register(LoadSession);
2128
5201
  registry->Register(NewSessionDone);
2129
5201
  registry->Register(Receive);
2130
5201
  registry->Register(Renegotiate);
2131
5201
  registry->Register(RequestOCSP);
2132
5201
  registry->Register(SetALPNProtocols);
2133
5201
  registry->Register(SetOCSPResponse);
2134
5201
  registry->Register(SetServername);
2135
5201
  registry->Register(SetSession);
2136
5201
  registry->Register(SetVerifyMode);
2137
5201
  registry->Register(Start);
2138
5201
  registry->Register(ExportKeyingMaterial);
2139
5201
  registry->Register(IsSessionReused);
2140
5201
  registry->Register(GetALPNNegotiatedProto);
2141
5201
  registry->Register(GetCertificate);
2142
5201
  registry->Register(GetX509Certificate);
2143
5201
  registry->Register(GetCipher);
2144
5201
  registry->Register(GetEphemeralKeyInfo);
2145
5201
  registry->Register(GetFinished);
2146
5201
  registry->Register(GetPeerCertificate);
2147
5201
  registry->Register(GetPeerX509Certificate);
2148
5201
  registry->Register(GetPeerFinished);
2149
5201
  registry->Register(GetProtocol);
2150
5201
  registry->Register(GetSession);
2151
5201
  registry->Register(GetSharedSigalgs);
2152
5201
  registry->Register(GetTLSTicket);
2153
5201
  registry->Register(VerifyError);
2154
2155
#ifdef SSL_set_max_send_fragment
2156
5201
  registry->Register(SetMaxSendFragment);
2157
#endif  // SSL_set_max_send_fragment
2158
2159
#ifndef OPENSSL_NO_PSK
2160
5201
  registry->Register(EnablePskCallback);
2161
5201
  registry->Register(SetPskIdentityHint);
2162
#endif  // !OPENSSL_NO_PSK
2163
5201
}
2164
2165
}  // namespace crypto
2166
}  // namespace node
2167
2168
5269
NODE_MODULE_CONTEXT_AWARE_INTERNAL(tls_wrap, node::crypto::TLSWrap::Initialize)
2169
5201
NODE_MODULE_EXTERNAL_REFERENCE(
2170
    tls_wrap, node::crypto::TLSWrap::RegisterExternalReferences)