GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: crypto/crypto_tls.cc Lines: 1045 1137 91.9 %
Date: 2022-08-28 04:20:35 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
94
SSL_SESSION* GetSessionCallback(
68
    SSL* s,
69
    const unsigned char* key,
70
    int len,
71
    int* copy) {
72
94
  TLSWrap* w = static_cast<TLSWrap*>(SSL_get_app_data(s));
73
94
  *copy = 0;
74
94
  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
1962
int NewSessionCallback(SSL* s, SSL_SESSION* sess) {
133
1962
  TLSWrap* w = static_cast<TLSWrap*>(SSL_get_app_data(s));
134
1962
  Environment* env = w->env();
135
3924
  HandleScope handle_scope(env->isolate());
136
1962
  Context::Scope context_scope(env->context());
137
138
1962
  if (!w->has_session_callbacks())
139
1661
    return 0;
140
141
  // Check if session is small enough to be stored
142
301
  int size = i2d_SSL_SESSION(sess, nullptr);
143
301
  if (UNLIKELY(size > SecureContext::kMaxSessionSize))
144
    return 0;
145
146
  // Serialize session
147
602
  Local<Object> session = Buffer::New(env, size).FromMaybe(Local<Object>());
148
301
  if (UNLIKELY(session.IsEmpty()))
149
    return 0;
150
151
  unsigned char* session_data =
152
301
      reinterpret_cast<unsigned char*>(Buffer::Data(session));
153
154
301
  CHECK_EQ(i2d_SSL_SESSION(sess, &session_data), size);
155
156
  unsigned int session_id_length;
157
  const unsigned char* session_id_data =
158
301
      SSL_SESSION_get_id(sess, &session_id_length);
159
160
301
  Local<Object> session_id = Buffer::Copy(
161
      env,
162
      reinterpret_cast<const char*>(session_id_data),
163
602
      session_id_length).FromMaybe(Local<Object>());
164
301
  if (UNLIKELY(session_id.IsEmpty()))
165
    return 0;
166
167
  Local<Value> argv[] = {
168
    session_id,
169
    session
170
301
  };
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
301
  if (w->is_server())
175
8
    w->set_awaiting_new_session(true);
176
177
301
  w->MakeCallback(env->onnewsession_string(), arraysize(argv), argv);
178
179
301
  return 0;
180
}
181
182
975
int SSLCertCallback(SSL* s, void* arg) {
183
975
  TLSWrap* w = static_cast<TLSWrap*>(SSL_get_app_data(s));
184
185

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

74
  if (UNLIKELY(alpn_buffer.IsEmpty()) || !alpn_buffer->IsArrayBufferView())
238
    return SSL_TLSEXT_ERR_NOACK;
239
240
37
  ArrayBufferViewContents<unsigned char> alpn_protos(alpn_buffer);
241
37
  int status = SSL_select_next_proto(
242
      const_cast<unsigned char**>(out),
243
      outlen,
244
      alpn_protos.data(),
245
37
      alpn_protos.length(),
246
      in,
247
      inlen);
248
249
  // Previous versions of Node.js returned SSL_TLSEXT_ERR_NOACK if no protocol
250
  // match was found. This would neither cause a fatal alert nor would it result
251
  // in a useful ALPN response as part of the Server Hello message.
252
  // We now return SSL_TLSEXT_ERR_ALERT_FATAL in that case as per Section 3.2
253
  // of RFC 7301, which causes a fatal no_application_protocol alert.
254
37
  return status == OPENSSL_NPN_NEGOTIATED ? SSL_TLSEXT_ERR_OK
255
37
                                          : SSL_TLSEXT_ERR_ALERT_FATAL;
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
12399
void ConfigureSecureContext(SecureContext* sc) {
297
  // OCSP stapling
298
12399
  SSL_CTX_set_tlsext_status_cb(sc->ctx().get(), TLSExtStatusCallback);
299
12399
  SSL_CTX_set_tlsext_status_arg(sc->ctx().get(), nullptr);
300
12399
}
301
302
4014
inline bool Set(
303
    Environment* env,
304
    Local<Object> target,
305
    Local<String> name,
306
    const char* value,
307
    bool ignore_null = true) {
308
4014
  if (value == nullptr)
309
1354
    return ignore_null;
310
2660
  return !target->Set(
311
      env->context(),
312
      name,
313
5320
      OneByteString(env->isolate(), value))
314
2660
          .IsNothing();
315
}
316
317
642
std::string GetBIOError() {
318
642
  std::string ret;
319
642
  ERR_print_errors_cb(
320
638
      [](const char* str, size_t len, void* opaque) {
321
638
        static_cast<std::string*>(opaque)->assign(str, len);
322
638
        return 0;
323
      },
324
      static_cast<void*>(&ret));
325
642
  return ret;
326
}
327
}  // namespace
328
329
12399
TLSWrap::TLSWrap(Environment* env,
330
                 Local<Object> obj,
331
                 Kind kind,
332
                 StreamBase* stream,
333
12399
                 SecureContext* sc)
334
    : AsyncWrap(env, obj, AsyncWrap::PROVIDER_TLSWRAP),
335
      StreamBase(env),
336
      env_(env),
337
      kind_(kind),
338
12399
      sc_(sc) {
339
12399
  MakeWeak();
340
12399
  CHECK(sc_);
341
12399
  ssl_ = sc_->CreateSSL();
342
12399
  CHECK(ssl_);
343
344
12399
  sc_->SetGetSessionCallback(GetSessionCallback);
345
12399
  sc_->SetNewSessionCallback(NewSessionCallback);
346
347
12399
  StreamBase::AttachToObject(GetObject());
348
12399
  stream->PushStreamListener(this);
349
350
12399
  env_->isolate()->AdjustAmountOfExternalAllocatedMemory(kExternalSize);
351
352
12399
  InitSSL();
353
12399
  Debug(this, "Created new TLSWrap");
354
12399
}
355
356
74364
TLSWrap::~TLSWrap() {
357
24788
  Destroy();
358
49576
}
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
94
SSL_SESSION* TLSWrap::ReleaseSession() {
371
94
  return next_sess_.release();
372
}
373
374
21143
void TLSWrap::InvokeQueued(int status, const char* error_str) {
375
21143
  Debug(this, "Invoking queued write callbacks (%d, %s)", status, error_str);
376
21143
  if (!write_callback_scheduled_)
377
4841
    return;
378
379
16302
  if (current_write_) {
380
5452
    BaseObjectPtr<AsyncWrap> current_write = std::move(current_write_);
381
2726
    current_write_.reset();
382
2726
    WriteWrap* w = WriteWrap::FromObject(current_write);
383
2726
    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
12399
void TLSWrap::InitSSL() {
393
  // Initialize SSL – OpenSSL takes ownership of these.
394
12399
  enc_in_ = NodeBIO::New(env()).release();
395
12399
  enc_out_ = NodeBIO::New(env()).release();
396
397
12399
  SSL_set_bio(ssl_.get(), enc_in_, enc_out_);
398
399
  // NOTE: This could be overridden in SetVerifyMode
400
12399
  SSL_set_verify(ssl_.get(), SSL_VERIFY_NONE, VerifyCallback);
401
402
#ifdef SSL_MODE_RELEASE_BUFFERS
403
12399
  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
12399
  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
12399
  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
12399
  SSL_set_info_callback(ssl_.get(), SSLInfoCallback);
425
426
12399
  if (is_server())
427
951
    sc_->SetSelectSNIContextCallback(SelectSNIContextCallback);
428
429
12399
  ConfigureSecureContext(sc_.get());
430
431
12399
  SSL_set_cert_cb(ssl_.get(), SSLCertCallback, this);
432
433
12399
  if (is_server()) {
434
951
    SSL_set_accept_state(ssl_.get());
435
11448
  } else if (is_client()) {
436
    // Enough space for server response (hello, cert)
437
11448
    NodeBIO::FromBIO(enc_in_)->set_initial(kInitialClientBufferLength);
438
11448
    SSL_set_connect_state(ssl_.get());
439
  } else {
440
    // Unexpected
441
    ABORT();
442
  }
443
12399
}
444
445
12399
void TLSWrap::Wrap(const FunctionCallbackInfo<Value>& args) {
446
12399
  Environment* env = Environment::GetCurrent(args);
447
448
12399
  CHECK_EQ(args.Length(), 3);
449
12399
  CHECK(args[0]->IsObject());
450
12399
  CHECK(args[1]->IsObject());
451
12399
  CHECK(args[2]->IsBoolean());
452
453
24798
  Local<Object> sc = args[1].As<Object>();
454

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

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

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

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

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

8968
    if (!pending_cleartext_input_ ||
587
201
        pending_cleartext_input_->ByteLength() == 0) {
588
8566
      if (!in_dowrite_) {
589
8501
        Debug(this, "No pending cleartext input, not inside DoWrite()");
590
8501
        InvokeQueued(0);
591
      } else {
592
65
        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
65
        BaseObjectPtr<TLSWrap> strong_ref{this};
602
65
        env()->SetImmediate([this, strong_ref](Environment* env) {
603
65
          InvokeQueued(0);
604
65
        });
605
      }
606
    }
607
8767
    return;
608
  }
609
610
  char* data[kSimultaneousBufferCount];
611
  size_t size[arraysize(data)];
612
7671
  size_t count = arraysize(data);
613
7671
  write_size_ = NodeBIO::FromBIO(enc_out_)->PeekMultiple(data, size, &count);
614

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

8299
  if (!eof_ && flags & SSL_RECEIVED_SHUTDOWN) {
740
1149
    eof_ = true;
741
1149
    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
8299
  if (read <= 0) {
748
8299
    HandleScope handle_scope(env()->isolate());
749
    Local<Value> error;
750
8299
    int err = GetSSLError(read);
751
8299
    switch (err) {
752
1090
      case SSL_ERROR_ZERO_RETURN:
753
        // Ignore ZERO_RETURN after EOF, it is basically not an error.
754
1090
        if (eof_) return;
755
        error = env()->zero_return_string();
756
        break;
757
758
640
      case SSL_ERROR_SSL:
759
      case SSL_ERROR_SYSCALL:
760
        {
761
640
          unsigned long ssl_err = ERR_peek_error();  // NOLINT(runtime/int)
762
763
640
          Local<Context> context = env()->isolate()->GetCurrentContext();
764
640
          if (UNLIKELY(context.IsEmpty())) return;
765
640
          const std::string error_str = GetBIOError();
766
          Local<String> message = OneByteString(
767
640
              env()->isolate(), error_str.c_str(), error_str.size());
768
640
          if (UNLIKELY(message.IsEmpty())) return;
769
640
          error = Exception::Error(message);
770
640
          if (UNLIKELY(error.IsEmpty())) return;
771
          Local<Object> obj;
772
1280
          if (UNLIKELY(!error->ToObject(context).ToLocal(&obj))) return;
773
774
640
          const char* ls = ERR_lib_error_string(ssl_err);
775
640
          const char* fs = ERR_func_error_string(ssl_err);
776
640
          const char* rs = ERR_reason_error_string(ssl_err);
777
640
          if (!Set(env(), obj, env()->library_string(), ls) ||
778

1280
              !Set(env(), obj, env()->function_string(), fs) ||
779
647
              !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
633
          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
13734
                         [](char c) { return c == ' ' ? '_' : ToUpper(c); });
788
633
          if (!Set(env(), obj,
789
1906
                   env()->code_string(), ("ERR_SSL_" + code).c_str())) return;
790
        }
791
633
        break;
792
793
6569
      default:
794
6569
        return;
795
    }
796
797
633
    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
633
    if (BIO_pending(enc_out_) != 0)
801
576
      EncOut();
802
803
633
    MakeCallback(env()->onerror_string(), 1, &error);
804
  }
805
}
806
807
13897
void TLSWrap::ClearIn() {
808
13897
  Debug(this, "Trying to write cleartext input");
809
  // Ignore cycling data if ClientHello wasn't yet parsed
810
13897
  if (!hello_parser_.IsEnded()) {
811
    Debug(this, "Returning from ClearIn(), hello_parser_ active");
812
13678
    return;
813
  }
814
815
13897
  if (ssl_ == nullptr) {
816
    Debug(this, "Returning from ClearIn(), ssl_ == nullptr");
817
    return;
818
  }
819
820

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

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

221
  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
219
  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
219
  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
26460
AsyncWrap* TLSWrap::GetAsyncWrap() {
865
26460
  return static_cast<AsyncWrap*>(this);
866
}
867
868
1144
bool TLSWrap::IsIPCPipe() {
869
1144
  return underlying_stream()->IsIPCPipe();
870
}
871
872
4
int TLSWrap::GetFD() {
873
4
  return underlying_stream()->GetFD();
874
}
875
876
4091
bool TLSWrap::IsAlive() {
877
4090
  return ssl_ &&
878

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

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

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

1440
  if (ssl_ && SSL_shutdown(ssl_.get()) == 0)
1104
909
    SSL_shutdown(ssl_.get());
1105
1106
1440
  shutdown_ = true;
1107
1440
  EncOut();
1108
1440
  return underlying_stream()->DoShutdown(req_wrap);
1109
}
1110
1111
12377
void TLSWrap::SetVerifyMode(const FunctionCallbackInfo<Value>& args) {
1112
  TLSWrap* wrap;
1113
12377
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1114
1115
12377
  CHECK_EQ(args.Length(), 2);
1116
12377
  CHECK(args[0]->IsBoolean());
1117
12377
  CHECK(args[1]->IsBoolean());
1118
12377
  CHECK_NOT_NULL(wrap->ssl_);
1119
1120
  int verify_mode;
1121
12377
  if (wrap->is_server()) {
1122
929
    bool request_cert = args[0]->IsTrue();
1123
929
    if (!request_cert) {
1124
      // If no cert is requested, there will be none to reject as unauthorized.
1125
845
      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
11448
    verify_mode = SSL_VERIFY_NONE;
1137
  }
1138
1139
  // Always allow a connection. We'll reject in javascript.
1140
12377
  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
12336
void TLSWrap::DestroySSL(const FunctionCallbackInfo<Value>& args) {
1200
  TLSWrap* wrap;
1201
12336
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1202
12336
  wrap->Destroy();
1203
12336
  Debug(wrap, "DestroySSL() finished");
1204
}
1205
1206
24730
void TLSWrap::Destroy() {
1207
24730
  if (!ssl_)
1208
12336
    return;
1209
1210
  // If there is a write happening, mark it as finished.
1211
12394
  write_callback_scheduled_ = true;
1212
1213
  // And destroy
1214
12394
  InvokeQueued(UV_ECANCELED, "Canceled because of SSL destruction");
1215
1216
12394
  env()->isolate()->AdjustAmountOfExternalAllocatedMemory(-kExternalSize);
1217
12394
  ssl_.reset();
1218
1219
12394
  enc_in_ = nullptr;
1220
12394
  enc_out_ = nullptr;
1221
1222
12394
  if (underlying_stream() != nullptr)
1223
12353
    underlying_stream()->RemoveStreamListener(this);
1224
1225
12394
  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
1431
void TLSWrap::GetServername(const FunctionCallbackInfo<Value>& args) {
1246
1431
  Environment* env = Environment::GetCurrent(args);
1247
1248
  TLSWrap* wrap;
1249
1431
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1250
1251
1431
  CHECK_NOT_NULL(wrap->ssl_);
1252
1253
1431
  const char* servername = GetServerName(wrap->ssl_.get());
1254
1431
  if (servername != nullptr) {
1255
462
    args.GetReturnValue().Set(OneByteString(env->isolate(), servername));
1256
  } else {
1257
2400
    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
992
int TLSWrap::SelectSNIContextCallback(SSL* s, int* ad, void* arg) {
1279
992
  TLSWrap* p = static_cast<TLSWrap*>(SSL_get_app_data(s));
1280
992
  Environment* env = p->env();
1281
1984
  HandleScope handle_scope(env->isolate());
1282
992
  Context::Scope context_scope(env->context());
1283
1284
992
  const char* servername = GetServerName(s);
1285
992
  if (!Set(env, p->GetOwner(), env->servername_string(), servername))
1286
    return SSL_TLSEXT_ERR_NOACK;
1287
1288
2976
  Local<Value> ctx = p->object()->Get(env->context(), env->sni_context_string())
1289
992
      .FromMaybe(Local<Value>());
1290
1291

1984
  if (UNLIKELY(ctx.IsEmpty()) || !ctx->IsObject())
1292
992
    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
10
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
10
  TLSWrap* p = static_cast<TLSWrap*>(SSL_get_app_data(s));
1402
1403
10
  Environment* env = p->env();
1404
20
  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
30
  };
1411
1412
10
  if (hint != nullptr) {
1413
    Local<String> local_hint =
1414
        String::NewFromUtf8(env->isolate(), hint).FromMaybe(Local<String>());
1415
    if (UNLIKELY(local_hint.IsEmpty()))
1416
      return 0;
1417
1418
    argv[0] = local_hint;
1419
  }
1420
1421
  Local<Value> ret =
1422
10
      p->MakeCallback(env->onpskexchange_symbol(), arraysize(argv), argv)
1423
10
          .FromMaybe(Local<Value>());
1424

20
  if (UNLIKELY(ret.IsEmpty()) || !ret->IsObject())
1425
1
    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
251
void TLSWrap::SetALPNProtocols(const FunctionCallbackInfo<Value>& args) {
1526
  TLSWrap* w;
1527
251
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1528
251
  Environment* env = w->env();
1529

502
  if (args.Length() < 1 || !Buffer::HasInstance(args[0]))
1530
    return env->ThrowTypeError("Must give a Buffer as first argument");
1531
1532
251
  if (w->is_client()) {
1533
82
    ArrayBufferViewContents<char> protos(args[0].As<ArrayBufferView>());
1534
41
    CHECK(SetALPN(w->ssl_, {protos.data(), protos.length()}));
1535
  } else {
1536

840
    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
210
    SSL_CTX_set_alpn_select_cb(SSL_get_SSL_CTX(w->ssl_.get()),
1543
                               SelectALPNCallback,
1544
                               nullptr);
1545
  }
1546
}
1547
1548
498
void TLSWrap::GetPeerCertificate(const FunctionCallbackInfo<Value>& args) {
1549
  TLSWrap* w;
1550
498
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1551
498
  Environment* env = w->env();
1552
1553

996
  bool abbreviated = args.Length() < 1 || !args[0]->IsTrue();
1554
1555
  Local<Value> ret;
1556
498
  if (GetPeerCert(
1557
          env,
1558
498
          w->ssl_,
1559
          abbreviated,
1560
996
          w->is_server()).ToLocal(&ret))
1561
996
    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
108
void TLSWrap::SetSession(const FunctionCallbackInfo<Value>& args) {
1689
108
  Environment* env = Environment::GetCurrent(args);
1690
1691
  TLSWrap* w;
1692
108
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1693
1694
108
  if (args.Length() < 1)
1695
    return THROW_ERR_MISSING_ARGS(env, "Session argument is mandatory");
1696
1697
108
  THROW_AND_RETURN_IF_NOT_BUFFER(env, args[0], "Session");
1698
108
  ArrayBufferViewContents<unsigned char> sbuf(args[0]);
1699
108
  SSLSessionPointer sess = GetTLSSession(sbuf.data(), sbuf.length());
1700
108
  if (sess == nullptr)
1701
    return;  // TODO(tniessen): figure out error handling
1702
1703
108
  if (!SetTLSSession(w->ssl_, sess))
1704
    return env->ThrowError("SSL_set_session error");
1705
}
1706
1707
524
void TLSWrap::IsSessionReused(const FunctionCallbackInfo<Value>& args) {
1708
  TLSWrap* w;
1709
524
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1710
524
  bool yes = SSL_session_reused(w->ssl_.get());
1711
1048
  args.GetReturnValue().Set(yes);
1712
}
1713
1714
967
void TLSWrap::VerifyError(const FunctionCallbackInfo<Value>& args) {
1715
967
  Environment* env = Environment::GetCurrent(args);
1716
  TLSWrap* w;
1717
1465
  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
967
      VerifyPeerCertificate(
1724
967
          w->ssl_,
1725
          X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT);
1726
1727
967
  if (x509_verify_error == X509_V_OK)
1728
996
    return args.GetReturnValue().SetNull();
1729
1730
469
  const char* reason = X509_verify_cert_error_string(x509_verify_error);
1731
469
  const char* code = X509ErrorCode(x509_verify_error);
1732
1733
  Local<Object> error =
1734
469
      Exception::Error(OneByteString(env->isolate(), reason))
1735
469
          ->ToObject(env->isolate()->GetCurrentContext())
1736
469
              .FromMaybe(Local<Object>());
1737
1738
469
  if (Set(env, error, env->code_string(), code))
1739
938
    args.GetReturnValue().Set(error);
1740
}
1741
1742
57
void TLSWrap::GetCipher(const FunctionCallbackInfo<Value>& args) {
1743
57
  Environment* env = Environment::GetCurrent(args);
1744
  TLSWrap* w;
1745
57
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1746
57
  args.GetReturnValue().Set(
1747
114
      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
901
void TLSWrap::GetEphemeralKeyInfo(const FunctionCallbackInfo<Value>& args) {
1950
  TLSWrap* w;
1951
908
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1952
901
  Environment* env = Environment::GetCurrent(args);
1953
1954
901
  CHECK(w->ssl_);
1955
1956
  // tmp key is available on only client
1957
901
  if (w->is_server())
1958
14
    return args.GetReturnValue().SetNull();
1959
1960
2682
  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
1808
void TLSWrap::GetALPNNegotiatedProto(const FunctionCallbackInfo<Value>& args) {
1976
1808
  Environment* env = Environment::GetCurrent(args);
1977
  TLSWrap* w;
1978
1808
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1979
1980
  const unsigned char* alpn_proto;
1981
  unsigned int alpn_proto_len;
1982
1983
1808
  SSL_get0_alpn_selected(w->ssl_.get(), &alpn_proto, &alpn_proto_len);
1984
1985
  Local<Value> result;
1986
1808
  if (alpn_proto_len == 0) {
1987
3486
    result = False(env->isolate());
1988
65
  } else if (alpn_proto_len == sizeof("h2") - 1 &&
1989
57
             0 == memcmp(alpn_proto, "h2", sizeof("h2") - 1)) {
1990
114
    result = env->h2_string();
1991
8
  } 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
12
    result = OneByteString(env->isolate(), alpn_proto, alpn_proto_len);
1996
  }
1997
1998
3616
  args.GetReturnValue().Set(result);
1999
}
2000
2001
6410
void TLSWrap::Cycle() {
2002
  // Prevent recursion
2003
6410
  if (++cycle_depth_ > 1)
2004
14
    return;
2005
2006
12804
  for (; cycle_depth_ > 0; cycle_depth_--) {
2007
6410
    ClearIn();
2008
6410
    ClearOut();
2009
    // EncIn() doesn't exist, it happens via stream listener callbacks.
2010
6409
    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
583
void TLSWrap::Initialize(
2028
    Local<Object> target,
2029
    Local<Value> unused,
2030
    Local<Context> context,
2031
    void* priv) {
2032
583
  Environment* env = Environment::GetCurrent(context);
2033
583
  Isolate* isolate = env->isolate();
2034
2035
583
  SetMethod(context, target, "wrap", TLSWrap::Wrap);
2036
2037
1166
  NODE_DEFINE_CONSTANT(target, HAVE_SSL_TRACE);
2038
2039
583
  Local<FunctionTemplate> t = BaseObject::MakeLazilyInitializedJSTemplate(env);
2040
  Local<String> tlsWrapString =
2041
583
      FIXED_ONE_BYTE_STRING(env->isolate(), "TLSWrap");
2042
583
  t->SetClassName(tlsWrapString);
2043
1166
  t->InstanceTemplate()->SetInternalFieldCount(StreamBase::kInternalFieldCount);
2044
2045
  Local<FunctionTemplate> get_write_queue_size =
2046
      FunctionTemplate::New(env->isolate(),
2047
                            GetWriteQueueSize,
2048
                            Local<Value>(),
2049
583
                            Signature::New(env->isolate(), t));
2050
2332
  t->PrototypeTemplate()->SetAccessorProperty(
2051
      env->write_queue_size_string(),
2052
      get_write_queue_size,
2053
      Local<FunctionTemplate>(),
2054
      static_cast<PropertyAttribute>(ReadOnly | DontDelete));
2055
2056
583
  t->Inherit(AsyncWrap::GetConstructorTemplate(env));
2057
2058
583
  SetProtoMethod(isolate, t, "certCbDone", CertCbDone);
2059
583
  SetProtoMethod(isolate, t, "destroySSL", DestroySSL);
2060
583
  SetProtoMethod(isolate, t, "enableCertCb", EnableCertCb);
2061
583
  SetProtoMethod(isolate, t, "endParser", EndParser);
2062
583
  SetProtoMethod(isolate, t, "enableKeylogCallback", EnableKeylogCallback);
2063
583
  SetProtoMethod(isolate, t, "enableSessionCallbacks", EnableSessionCallbacks);
2064
583
  SetProtoMethod(isolate, t, "enableTrace", EnableTrace);
2065
583
  SetProtoMethod(isolate, t, "getServername", GetServername);
2066
583
  SetProtoMethod(isolate, t, "loadSession", LoadSession);
2067
583
  SetProtoMethod(isolate, t, "newSessionDone", NewSessionDone);
2068
583
  SetProtoMethod(isolate, t, "receive", Receive);
2069
583
  SetProtoMethod(isolate, t, "renegotiate", Renegotiate);
2070
583
  SetProtoMethod(isolate, t, "requestOCSP", RequestOCSP);
2071
583
  SetProtoMethod(isolate, t, "setALPNProtocols", SetALPNProtocols);
2072
583
  SetProtoMethod(isolate, t, "setOCSPResponse", SetOCSPResponse);
2073
583
  SetProtoMethod(isolate, t, "setServername", SetServername);
2074
583
  SetProtoMethod(isolate, t, "setSession", SetSession);
2075
583
  SetProtoMethod(isolate, t, "setVerifyMode", SetVerifyMode);
2076
583
  SetProtoMethod(isolate, t, "start", Start);
2077
2078
583
  SetProtoMethodNoSideEffect(
2079
      isolate, t, "exportKeyingMaterial", ExportKeyingMaterial);
2080
583
  SetProtoMethodNoSideEffect(isolate, t, "isSessionReused", IsSessionReused);
2081
583
  SetProtoMethodNoSideEffect(
2082
      isolate, t, "getALPNNegotiatedProtocol", GetALPNNegotiatedProto);
2083
583
  SetProtoMethodNoSideEffect(isolate, t, "getCertificate", GetCertificate);
2084
583
  SetProtoMethodNoSideEffect(
2085
      isolate, t, "getX509Certificate", GetX509Certificate);
2086
583
  SetProtoMethodNoSideEffect(isolate, t, "getCipher", GetCipher);
2087
583
  SetProtoMethodNoSideEffect(
2088
      isolate, t, "getEphemeralKeyInfo", GetEphemeralKeyInfo);
2089
583
  SetProtoMethodNoSideEffect(isolate, t, "getFinished", GetFinished);
2090
583
  SetProtoMethodNoSideEffect(
2091
      isolate, t, "getPeerCertificate", GetPeerCertificate);
2092
583
  SetProtoMethodNoSideEffect(
2093
      isolate, t, "getPeerX509Certificate", GetPeerX509Certificate);
2094
583
  SetProtoMethodNoSideEffect(isolate, t, "getPeerFinished", GetPeerFinished);
2095
583
  SetProtoMethodNoSideEffect(isolate, t, "getProtocol", GetProtocol);
2096
583
  SetProtoMethodNoSideEffect(isolate, t, "getSession", GetSession);
2097
583
  SetProtoMethodNoSideEffect(isolate, t, "getSharedSigalgs", GetSharedSigalgs);
2098
583
  SetProtoMethodNoSideEffect(isolate, t, "getTLSTicket", GetTLSTicket);
2099
583
  SetProtoMethodNoSideEffect(isolate, t, "verifyError", VerifyError);
2100
2101
#ifdef SSL_set_max_send_fragment
2102
583
  SetProtoMethod(isolate, t, "setMaxSendFragment", SetMaxSendFragment);
2103
#endif  // SSL_set_max_send_fragment
2104
2105
#ifndef OPENSSL_NO_PSK
2106
583
  SetProtoMethod(isolate, t, "enablePskCallback", EnablePskCallback);
2107
583
  SetProtoMethod(isolate, t, "setPskIdentityHint", SetPskIdentityHint);
2108
#endif  // !OPENSSL_NO_PSK
2109
2110
583
  StreamBase::AddMethods(env, t);
2111
2112
583
  Local<Function> fn = t->GetFunction(env->context()).ToLocalChecked();
2113
2114
583
  env->set_tls_wrap_constructor_function(fn);
2115
2116
583
  target->Set(env->context(), tlsWrapString, fn).Check();
2117
583
}
2118
2119
5378
void TLSWrap::RegisterExternalReferences(ExternalReferenceRegistry* registry) {
2120
5378
  registry->Register(TLSWrap::Wrap);
2121
5378
  registry->Register(GetWriteQueueSize);
2122
2123
5378
  registry->Register(CertCbDone);
2124
5378
  registry->Register(DestroySSL);
2125
5378
  registry->Register(EnableCertCb);
2126
5378
  registry->Register(EndParser);
2127
5378
  registry->Register(EnableKeylogCallback);
2128
5378
  registry->Register(EnableSessionCallbacks);
2129
5378
  registry->Register(EnableTrace);
2130
5378
  registry->Register(GetServername);
2131
5378
  registry->Register(LoadSession);
2132
5378
  registry->Register(NewSessionDone);
2133
5378
  registry->Register(Receive);
2134
5378
  registry->Register(Renegotiate);
2135
5378
  registry->Register(RequestOCSP);
2136
5378
  registry->Register(SetALPNProtocols);
2137
5378
  registry->Register(SetOCSPResponse);
2138
5378
  registry->Register(SetServername);
2139
5378
  registry->Register(SetSession);
2140
5378
  registry->Register(SetVerifyMode);
2141
5378
  registry->Register(Start);
2142
5378
  registry->Register(ExportKeyingMaterial);
2143
5378
  registry->Register(IsSessionReused);
2144
5378
  registry->Register(GetALPNNegotiatedProto);
2145
5378
  registry->Register(GetCertificate);
2146
5378
  registry->Register(GetX509Certificate);
2147
5378
  registry->Register(GetCipher);
2148
5378
  registry->Register(GetEphemeralKeyInfo);
2149
5378
  registry->Register(GetFinished);
2150
5378
  registry->Register(GetPeerCertificate);
2151
5378
  registry->Register(GetPeerX509Certificate);
2152
5378
  registry->Register(GetPeerFinished);
2153
5378
  registry->Register(GetProtocol);
2154
5378
  registry->Register(GetSession);
2155
5378
  registry->Register(GetSharedSigalgs);
2156
5378
  registry->Register(GetTLSTicket);
2157
5378
  registry->Register(VerifyError);
2158
2159
#ifdef SSL_set_max_send_fragment
2160
5378
  registry->Register(SetMaxSendFragment);
2161
#endif  // SSL_set_max_send_fragment
2162
2163
#ifndef OPENSSL_NO_PSK
2164
5378
  registry->Register(EnablePskCallback);
2165
5378
  registry->Register(SetPskIdentityHint);
2166
#endif  // !OPENSSL_NO_PSK
2167
5378
}
2168
2169
}  // namespace crypto
2170
}  // namespace node
2171
2172
5450
NODE_MODULE_CONTEXT_AWARE_INTERNAL(tls_wrap, node::crypto::TLSWrap::Initialize)
2173
5378
NODE_MODULE_EXTERNAL_REFERENCE(
2174
    tls_wrap, node::crypto::TLSWrap::RegisterExternalReferences)