GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: crypto/crypto_tls.cc Lines: 1045 1135 92.1 %
Date: 2022-05-03 04:14:50 Branches: 443 680 65.1 %

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
1897
int NewSessionCallback(SSL* s, SSL_SESSION* sess) {
133
1897
  TLSWrap* w = static_cast<TLSWrap*>(SSL_get_app_data(s));
134
1897
  Environment* env = w->env();
135
3794
  HandleScope handle_scope(env->isolate());
136
1897
  Context::Scope context_scope(env->context());
137
138
1897
  if (!w->has_session_callbacks())
139
1606
    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
968
int SSLCertCallback(SSL* s, void* arg) {
183
968
  TLSWrap* w = static_cast<TLSWrap*>(SSL_get_app_data(s));
184
185

968
  if (!w->is_server() || !w->is_waiting_cert_cb())
186
943
    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
34
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
34
  TLSWrap* w = static_cast<TLSWrap*>(SSL_get_app_data(s));
229
34
  Environment* env = w->env();
230
68
  HandleScope handle_scope(env->isolate());
231
34
  Context::Scope context_scope(env->context());
232
233
  Local<Value> alpn_buffer =
234
34
      w->object()->GetPrivate(
235
          env->context(),
236
68
          env->alpn_buffer_private_symbol()).FromMaybe(Local<Value>());
237

68
  if (UNLIKELY(alpn_buffer.IsEmpty()) || !alpn_buffer->IsArrayBufferView())
238
    return SSL_TLSEXT_ERR_NOACK;
239
240
34
  ArrayBufferViewContents<unsigned char> alpn_protos(alpn_buffer);
241
34
  int status = SSL_select_next_proto(
242
      const_cast<unsigned char**>(out),
243
      outlen,
244
      alpn_protos.data(),
245
34
      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
34
      ? SSL_TLSEXT_ERR_OK
255
34
      : 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
12376
void ConfigureSecureContext(SecureContext* sc) {
297
  // OCSP stapling
298
12376
  SSL_CTX_set_tlsext_status_cb(sc->ctx_.get(), TLSExtStatusCallback);
299
12376
  SSL_CTX_set_tlsext_status_arg(sc->ctx_.get(), nullptr);
300
12376
}
301
302
3972
inline bool Set(
303
    Environment* env,
304
    Local<Object> target,
305
    Local<String> name,
306
    const char* value,
307
    bool ignore_null = true) {
308
3972
  if (value == nullptr)
309
1333
    return ignore_null;
310
2639
  return !target->Set(
311
      env->context(),
312
      name,
313
5278
      OneByteString(env->isolate(), value))
314
2639
          .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
12376
TLSWrap::TLSWrap(Environment* env,
330
                 Local<Object> obj,
331
                 Kind kind,
332
                 StreamBase* stream,
333
12376
                 SecureContext* sc)
334
    : AsyncWrap(env, obj, AsyncWrap::PROVIDER_TLSWRAP),
335
      StreamBase(env),
336
      env_(env),
337
      kind_(kind),
338
12376
      sc_(sc) {
339
12376
  MakeWeak();
340
12376
  CHECK(sc_);
341
12376
  ssl_ = sc_->CreateSSL();
342
12376
  CHECK(ssl_);
343
344
12376
  sc_->SetGetSessionCallback(GetSessionCallback);
345
12376
  sc_->SetNewSessionCallback(NewSessionCallback);
346
347
12376
  StreamBase::AttachToObject(GetObject());
348
12376
  stream->PushStreamListener(this);
349
350
12376
  env_->isolate()->AdjustAmountOfExternalAllocatedMemory(kExternalSize);
351
352
12376
  InitSSL();
353
12376
  Debug(this, "Created new TLSWrap");
354
12376
}
355
356
74226
TLSWrap::~TLSWrap() {
357
24742
  Destroy();
358
49484
}
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
21019
void TLSWrap::InvokeQueued(int status, const char* error_str) {
375
21019
  Debug(this, "Invoking queued write callbacks (%d, %s)", status, error_str);
376
21019
  if (!write_callback_scheduled_)
377
4817
    return;
378
379
16202
  if (current_write_) {
380
5378
    BaseObjectPtr<AsyncWrap> current_write = std::move(current_write_);
381
2689
    current_write_.reset();
382
2689
    WriteWrap* w = WriteWrap::FromObject(current_write);
383
2689
    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
12376
void TLSWrap::InitSSL() {
393
  // Initialize SSL – OpenSSL takes ownership of these.
394
12376
  enc_in_ = NodeBIO::New(env()).release();
395
12376
  enc_out_ = NodeBIO::New(env()).release();
396
397
12376
  SSL_set_bio(ssl_.get(), enc_in_, enc_out_);
398
399
  // NOTE: This could be overridden in SetVerifyMode
400
12376
  SSL_set_verify(ssl_.get(), SSL_VERIFY_NONE, VerifyCallback);
401
402
#ifdef SSL_MODE_RELEASE_BUFFERS
403
12376
  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
12376
  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
12376
  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
12376
  SSL_set_info_callback(ssl_.get(), SSLInfoCallback);
425
426
12376
  if (is_server())
427
939
    sc_->SetSelectSNIContextCallback(SelectSNIContextCallback);
428
429
12376
  ConfigureSecureContext(sc_.get());
430
431
12376
  SSL_set_cert_cb(ssl_.get(), SSLCertCallback, this);
432
433
12376
  if (is_server()) {
434
939
    SSL_set_accept_state(ssl_.get());
435
11437
  } else if (is_client()) {
436
    // Enough space for server response (hello, cert)
437
11437
    NodeBIO::FromBIO(enc_in_)->set_initial(kInitialClientBufferLength);
438
11437
    SSL_set_connect_state(ssl_.get());
439
  } else {
440
    // Unexpected
441
    ABORT();
442
  }
443
12376
}
444
445
12376
void TLSWrap::Wrap(const FunctionCallbackInfo<Value>& args) {
446
12376
  Environment* env = Environment::GetCurrent(args);
447
448
12376
  CHECK_EQ(args.Length(), 3);
449
12376
  CHECK(args[0]->IsObject());
450
12376
  CHECK(args[1]->IsObject());
451
12376
  CHECK(args[2]->IsBoolean());
452
453
24752
  Local<Object> sc = args[1].As<Object>();
454

12376
  Kind kind = args[2]->IsTrue() ? Kind::kServer : Kind::kClient;
455
456
24752
  StreamBase* stream = StreamBase::FromObject(args[0].As<Object>());
457
12376
  CHECK_NOT_NULL(stream);
458
459
  Local<Object> obj;
460
12376
  if (!env->tls_wrap_constructor_function()
461
12376
           ->NewInstance(env->context())
462
12376
           .ToLocal(&obj)) {
463
    return;
464
  }
465
466
12376
  TLSWrap* res = new TLSWrap(env, obj, kind, stream, Unwrap<SecureContext>(sc));
467
468
24752
  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
1385
void TLSWrap::Start(const FunctionCallbackInfo<Value>& args) {
494
  TLSWrap* wrap;
495
1385
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
496
497
1385
  CHECK(!wrap->started_);
498
1385
  wrap->started_ = true;
499
500
  // Send ClientHello handshake
501
1385
  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
1385
  wrap->ClearOut();
506
1385
  wrap->EncOut();
507
}
508
509
40310
void TLSWrap::SSLInfoCallback(const SSL* ssl_, int where, int ret) {
510
40310
  if (!(where & (SSL_CB_HANDSHAKE_START | SSL_CB_HANDSHAKE_DONE)))
511
36008
    return;
512
513
  // SSL_renegotiate_pending() should take `const SSL*`, but it does not.
514
4302
  SSL* ssl = const_cast<SSL*>(ssl_);
515
4302
  TLSWrap* c = static_cast<TLSWrap*>(SSL_get_app_data(ssl_));
516
4302
  Environment* env = c->env();
517
8604
  HandleScope handle_scope(env->isolate());
518
4302
  Context::Scope context_scope(env->context());
519
4302
  Local<Object> object = c->object();
520
521
4302
  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
5014
    if (object->Get(env->context(), env->onhandshakestart_string())
528

5014
            .ToLocal(&callback) && callback->IsFunction()) {
529
2507
      Local<Value> argv[] = { env->GetNow() };
530
5014
      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

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

3588
          .ToLocal(&callback) && callback->IsFunction()) {
546
3588
      c->MakeCallback(callback.As<Function>(), 0, nullptr);
547
    }
548
  }
549
}
550
551
19976
void TLSWrap::EncOut() {
552
19976
  Debug(this, "Trying to write encrypted output");
553
554
  // Ignore cycling data if ClientHello wasn't yet parsed
555
19976
  if (!hello_parser_.IsEnded()) {
556
1
    Debug(this, "Returning from EncOut(), hello_parser_ active");
557
12481
    return;
558
  }
559
560
  // Write in progress
561
19975
  if (write_size_ != 0) {
562
3620
    Debug(this, "Returning from EncOut(), write currently in progress");
563
3620
    return;
564
  }
565
566
  // Wait for `newSession` callback to be invoked
567
16355
  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

16348
  if (established_ && current_write_) {
574
5348
    Debug(this, "EncOut() write is scheduled");
575
5348
    write_callback_scheduled_ = true;
576
  }
577
578
16348
  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
16346
  if (BIO_pending(enc_out_) == 0) {
585
8673
    Debug(this, "No pending encrypted output");
586

8880
    if (!pending_cleartext_input_ ||
587
207
        pending_cleartext_input_->ByteLength() == 0) {
588
8466
      if (!in_dowrite_) {
589
8404
        Debug(this, "No pending cleartext input, not inside DoWrite()");
590
8404
        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
8673
    return;
608
  }
609
610
  char* data[kSimultaneousBufferCount];
611
  size_t size[arraysize(data)];
612
7673
  size_t count = arraysize(data);
613
7673
  write_size_ = NodeBIO::FromBIO(enc_out_)->PeekMultiple(data, size, &count);
614

7673
  CHECK(write_size_ != 0 && count != 0);
615
616
  uv_buf_t buf[arraysize(data)];
617
7673
  uv_buf_t* bufs = buf;
618
15482
  for (size_t i = 0; i < count; i++)
619
7809
    buf[i] = uv_buf_init(data[i], size[i]);
620
621
7673
  Debug(this, "Writing %zu buffers to the underlying stream", count);
622
7673
  StreamWriteResult res = underlying_stream()->Write(bufs, count);
623
7672
  if (res.err != 0) {
624
178
    InvokeQueued(res.err);
625
178
    return;
626
  }
627
628
7494
  if (!res.async) {
629
6935
    Debug(this, "Write finished synchronously");
630
13870
    HandleScope handle_scope(env()->isolate());
631
632
    // Simulate asynchronous finishing, TLS cannot handle this at the moment.
633
6935
    BaseObjectPtr<TLSWrap> strong_ref{this};
634
6935
    env()->SetImmediate([this, strong_ref](Environment* env) {
635
6935
      OnStreamAfterWrite(nullptr, 0);
636
6935
    });
637
  }
638
}
639
640
7593
void TLSWrap::OnStreamAfterWrite(WriteWrap* req_wrap, int status) {
641
7593
  Debug(this, "OnStreamAfterWrite(status = %d)", status);
642
7593
  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
7493
  if (ssl_ == nullptr) {
653
    Debug(this, "ssl_ == nullptr, marking as cancelled");
654
    status = UV_ECANCELED;
655
  }
656
657
  // Handle error
658
7493
  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
7490
  NodeBIO::FromBIO(enc_out_)->Read(nullptr, write_size_);
671
672
  // Ensure that the progress will be made and `InvokeQueued` will be called.
673
7490
  ClearIn();
674
675
  // Try writing more data
676
7490
  write_size_ = 0;
677
7490
  EncOut();
678
}
679
680
8592
int TLSWrap::GetSSLError(int status) const {
681
  // ssl_ might already be destroyed for reading EOF from a close notify alert.
682
8592
  return ssl_ != nullptr ? SSL_get_error(ssl_.get(), status) : 0;
683
}
684
685
8177
void TLSWrap::ClearOut() {
686
8177
  Debug(this, "Trying to read cleartext output");
687
  // Ignore cycling data if ClientHello wasn't yet parsed
688
8177
  if (!hello_parser_.IsEnded()) {
689
1
    Debug(this, "Returning from ClearOut(), hello_parser_ active");
690
7547
    return;
691
  }
692
693
  // No reads after EOF
694
8176
  if (eof_) {
695
    Debug(this, "Returning from ClearOut(), EOF reached");
696
    return;
697
  }
698
699
8176
  if (ssl_ == nullptr) {
700
1
    Debug(this, "Returning from ClearOut(), ssl_ == nullptr");
701
1
    return;
702
  }
703
704
8175
  MarkPopErrorOnReturn mark_pop_error_on_return;
705
706
  char out[kClearOutChunkSize];
707
  int read;
708
  for (;;) {
709
11355
    read = SSL_read(ssl_.get(), out, sizeof(out));
710
11355
    Debug(this, "Read %d bytes of cleartext output", read);
711
712
11355
    if (read <= 0)
713
8173
      break;
714
715
3182
    char* current = out;
716
8416
    while (read > 0) {
717
5236
      int avail = read;
718
719
5236
      uv_buf_t buf = EmitAlloc(avail);
720
5236
      if (static_cast<int>(buf.len) < avail)
721
2054
        avail = buf.len;
722
5236
      memcpy(buf.base, current, avail);
723
5236
      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
5235
      if (ssl_ == nullptr) {
729
1
        Debug(this, "Returning from read loop, ssl_ == nullptr");
730
1
        return;
731
      }
732
733
5234
      read -= avail;
734
5234
      current += avail;
735
    }
736
3180
  }
737
738
8173
  int flags = SSL_get_shutdown(ssl_.get());
739

8173
  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
8173
  if (read <= 0) {
748
8173
    HandleScope handle_scope(env()->isolate());
749
    Local<Value> error;
750
8173
    int err = GetSSLError(read);
751
8173
    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
6400
      default:
794
6400
        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
13845
void TLSWrap::ClearIn() {
808
13845
  Debug(this, "Trying to write cleartext input");
809
  // Ignore cycling data if ClientHello wasn't yet parsed
810
13845
  if (!hello_parser_.IsEnded()) {
811
    Debug(this, "Returning from ClearIn(), hello_parser_ active");
812
13610
    return;
813
  }
814
815
13845
  if (ssl_ == nullptr) {
816
    Debug(this, "Returning from ClearIn(), ssl_ == nullptr");
817
    return;
818
  }
819
820

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

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

237
  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
235
  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
235
  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
26435
AsyncWrap* TLSWrap::GetAsyncWrap() {
865
26435
  return static_cast<AsyncWrap*>(this);
866
}
867
868
1122
bool TLSWrap::IsIPCPipe() {
869
1122
  return underlying_stream()->IsIPCPipe();
870
}
871
872
4
int TLSWrap::GetFD() {
873
4
  return underlying_stream()->GetFD();
874
}
875
876
4111
bool TLSWrap::IsAlive() {
877
4110
  return ssl_ &&
878

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

2440
  if (underlying_stream() != nullptr && !eof_)
889
2439
    return underlying_stream()->ReadStart();
890
1
  return 0;
891
}
892
893
1669
int TLSWrap::ReadStop() {
894
1669
  Debug(this, "ReadStop()");
895
1669
  return underlying_stream() != nullptr ? underlying_stream()->ReadStop() : 0;
896
}
897
898
5626
const char* TLSWrap::Error() const {
899
5626
  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
2797
int TLSWrap::DoWrite(WriteWrap* w,
909
                     uv_buf_t* bufs,
910
                     size_t count,
911
                     uv_stream_t* send_handle) {
912
2797
  CHECK_NULL(send_handle);
913
2797
  Debug(this, "DoWrite()");
914
915
2797
  if (ssl_ == nullptr) {
916
4
    ClearError();
917
4
    error_ = "Write after DestroySSL";
918
4
    return UV_EPROTO;
919
  }
920
921
2793
  size_t length = 0;
922
  size_t i;
923
2793
  size_t nonempty_i = 0;
924
2793
  size_t nonempty_count = 0;
925
12824
  for (i = 0; i < count; i++) {
926
10031
    length += bufs[i].len;
927
10031
    if (bufs[i].len > 0) {
928
9728
      nonempty_i = i;
929
9728
      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
2793
  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
2693
  CHECK(!current_write_);
964
2693
  current_write_.reset(w->GetAsyncWrap());
965
966
  // Write encrypted data to underlying stream and call Done().
967
2693
  if (length == 0) {
968
101
    EncOut();
969
101
    return 0;
970
  }
971
972
2592
  std::unique_ptr<BackingStore> bs;
973
5184
  MarkPopErrorOnReturn mark_pop_error_on_return;
974
975
2592
  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
2592
  if (nonempty_count != 1) {
986
    {
987
1599
      NoArrayBufferZeroFillScope no_zero_fill_scope(env()->isolate_data());
988
1599
      bs = ArrayBuffer::NewBackingStore(env()->isolate(), length);
989
    }
990
1599
    size_t offset = 0;
991
10336
    for (i = 0; i < count; i++) {
992
8737
      memcpy(static_cast<char*>(bs->Data()) + offset,
993
8737
             bufs[i].base, bufs[i].len);
994
8737
      offset += bufs[i].len;
995
    }
996
997
1599
    NodeBIO::FromBIO(enc_out_)->set_allocate_tls_hint(length);
998
1599
    written = SSL_write(ssl_.get(), bs->Data(), length);
999
  } else {
1000
    // Only one buffer: try to write directly, only store if it fails
1001
993
    uv_buf_t* buf = &bufs[nonempty_i];
1002
993
    NodeBIO::FromBIO(enc_out_)->set_allocate_tls_hint(buf->len);
1003
993
    written = SSL_write(ssl_.get(), buf->base, buf->len);
1004
1005
993
    if (written == -1) {
1006
177
      NoArrayBufferZeroFillScope no_zero_fill_scope(env()->isolate_data());
1007
177
      bs = ArrayBuffer::NewBackingStore(env()->isolate(), length);
1008
177
      memcpy(bs->Data(), buf->base, buf->len);
1009
    }
1010
  }
1011
1012

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

182
    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
179
    Debug(this, "Saving data for later write");
1026
    // Otherwise, save unwritten data so it can be written later by ClearIn().
1027

179
    CHECK(!pending_cleartext_input_ ||
1028
          pending_cleartext_input_->ByteLength() == 0);
1029
179
    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
2589
  in_dowrite_ = true;
1035
2589
  EncOut();
1036
2589
  in_dowrite_ = false;
1037
1038
2589
  return 0;
1039
}
1040
1041
7148
uv_buf_t TLSWrap::OnStreamAlloc(size_t suggested_size) {
1042
7148
  CHECK_NOT_NULL(ssl_);
1043
1044
7148
  size_t size = suggested_size;
1045
7148
  char* base = NodeBIO::FromBIO(enc_in_)->PeekWritable(&size);
1046
7148
  return uv_buf_init(base, size);
1047
}
1048
1049
7172
void TLSWrap::OnStreamRead(ssize_t nread, const uv_buf_t& buf) {
1050
7172
  Debug(this, "Read %zd bytes from underlying stream", nread);
1051
1052
  // Ignore everything after close_notify (rfc5246#section-7.2.1)
1053
7172
  if (eof_)
1054
608
    return;
1055
1056
6564
  if (nread < 0)  {
1057
    // Error should be emitted only after all data was read
1058
236
    ClearOut();
1059
1060
236
    if (nread == UV_EOF) {
1061
      // underlying stream already should have also called ReadStop on itself
1062
234
      eof_ = true;
1063
    }
1064
1065
236
    EmitRead(nread);
1066
236
    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
6328
  CHECK(ssl_);
1073
1074
  // Commit the amount of data actually read into the peeked/allocated buffer
1075
  // from the underlying stream.
1076
6328
  NodeBIO* enc_in = NodeBIO::FromBIO(enc_in_);
1077
6328
  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
6328
  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
6308
  Cycle();
1093
}
1094
1095
1485
ShutdownWrap* TLSWrap::CreateShutdownWrap(Local<Object> req_wrap_object) {
1096
1485
  return underlying_stream()->CreateShutdownWrap(req_wrap_object);
1097
}
1098
1099
1485
int TLSWrap::DoShutdown(ShutdownWrap* req_wrap) {
1100
1485
  Debug(this, "DoShutdown()");
1101
2970
  MarkPopErrorOnReturn mark_pop_error_on_return;
1102
1103

1485
  if (ssl_ && SSL_shutdown(ssl_.get()) == 0)
1104
951
    SSL_shutdown(ssl_.get());
1105
1106
1485
  shutdown_ = true;
1107
1485
  EncOut();
1108
1485
  return underlying_stream()->DoShutdown(req_wrap);
1109
}
1110
1111
12354
void TLSWrap::SetVerifyMode(const FunctionCallbackInfo<Value>& args) {
1112
  TLSWrap* wrap;
1113
12354
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1114
1115
12354
  CHECK_EQ(args.Length(), 2);
1116
12354
  CHECK(args[0]->IsBoolean());
1117
12354
  CHECK(args[1]->IsBoolean());
1118
12354
  CHECK_NOT_NULL(wrap->ssl_);
1119
1120
  int verify_mode;
1121
12354
  if (wrap->is_server()) {
1122
917
    bool request_cert = args[0]->IsTrue();
1123
917
    if (!request_cert) {
1124
      // If no cert is requested, there will be none to reject as unauthorized.
1125
833
      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
11437
    verify_mode = SSL_VERIFY_NONE;
1137
  }
1138
1139
  // Always allow a connection. We'll reject in javascript.
1140
12354
  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
12313
void TLSWrap::DestroySSL(const FunctionCallbackInfo<Value>& args) {
1200
  TLSWrap* wrap;
1201
12313
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1202
12313
  wrap->Destroy();
1203
12313
  Debug(wrap, "DestroySSL() finished");
1204
}
1205
1206
24684
void TLSWrap::Destroy() {
1207
24684
  if (!ssl_)
1208
12313
    return;
1209
1210
  // If there is a write happening, mark it as finished.
1211
12371
  write_callback_scheduled_ = true;
1212
1213
  // And destroy
1214
12371
  InvokeQueued(UV_ECANCELED, "Canceled because of SSL destruction");
1215
1216
12371
  env()->isolate()->AdjustAmountOfExternalAllocatedMemory(-kExternalSize);
1217
12371
  ssl_.reset();
1218
1219
12371
  enc_in_ = nullptr;
1220
12371
  enc_out_ = nullptr;
1221
1222
12371
  if (underlying_stream() != nullptr)
1223
12329
    underlying_stream()->RemoveStreamListener(this);
1224
1225
12371
  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
1416
void TLSWrap::GetServername(const FunctionCallbackInfo<Value>& args) {
1246
1416
  Environment* env = Environment::GetCurrent(args);
1247
1248
  TLSWrap* wrap;
1249
1416
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1250
1251
1416
  CHECK_NOT_NULL(wrap->ssl_);
1252
1253
1416
  const char* servername = SSL_get_servername(wrap->ssl_.get(),
1254
                                              TLSEXT_NAMETYPE_host_name);
1255
1416
  if (servername != nullptr) {
1256
460
    args.GetReturnValue().Set(OneByteString(env->isolate(), servername));
1257
  } else {
1258
2372
    args.GetReturnValue().Set(false);
1259
  }
1260
}
1261
1262
249
void TLSWrap::SetServername(const FunctionCallbackInfo<Value>& args) {
1263
249
  Environment* env = Environment::GetCurrent(args);
1264
1265
  TLSWrap* wrap;
1266
249
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1267
1268
249
  CHECK_EQ(args.Length(), 1);
1269
498
  CHECK(args[0]->IsString());
1270
249
  CHECK(!wrap->started_);
1271
249
  CHECK(wrap->is_client());
1272
1273
249
  CHECK(wrap->ssl_);
1274
1275
747
  Utf8Value servername(env->isolate(), args[0].As<String>());
1276
249
  SSL_set_tlsext_host_name(wrap->ssl_.get(), *servername);
1277
}
1278
1279
980
int TLSWrap::SelectSNIContextCallback(SSL* s, int* ad, void* arg) {
1280
980
  TLSWrap* p = static_cast<TLSWrap*>(SSL_get_app_data(s));
1281
980
  Environment* env = p->env();
1282
1960
  HandleScope handle_scope(env->isolate());
1283
980
  Context::Scope context_scope(env->context());
1284
1285
980
  const char* servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
1286
980
  if (!Set(env, p->GetOwner(), env->servername_string(), servername))
1287
    return SSL_TLSEXT_ERR_NOACK;
1288
1289
2940
  Local<Value> ctx = p->object()->Get(env->context(), env->sni_context_string())
1290
980
      .FromMaybe(Local<Value>());
1291
1292

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

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

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

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

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

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


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

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

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

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

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

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

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