GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: crypto/crypto_tls.cc Lines: 1039 1128 92.1 %
Date: 2022-12-31 04:22:30 Branches: 435 666 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
1988
int NewSessionCallback(SSL* s, SSL_SESSION* sess) {
133
1988
  TLSWrap* w = static_cast<TLSWrap*>(SSL_get_app_data(s));
134
1988
  Environment* env = w->env();
135
3976
  HandleScope handle_scope(env->isolate());
136
1988
  Context::Scope context_scope(env->context());
137
138
1988
  if (!w->has_session_callbacks())
139
1687
    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
977
int SSLCertCallback(SSL* s, void* arg) {
183
977
  TLSWrap* w = static_cast<TLSWrap*>(SSL_get_app_data(s));
184
185

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

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


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

5068
            .ToLocal(&callback) && callback->IsFunction()) {
520
2534
      Local<Value> argv[] = { env->GetNow() };
521
5068
      c->MakeCallback(callback.As<Function>(), arraysize(argv), argv);
522
    }
523
  }
524
525
  // SSL_CB_HANDSHAKE_START and SSL_CB_HANDSHAKE_DONE are called
526
  // sending HelloRequest in OpenSSL-1.1.1.
527
  // We need to check whether this is in a renegotiation state or not.
528

4349
  if (where & SSL_CB_HANDSHAKE_DONE && !SSL_renegotiate_pending(ssl)) {
529
    Debug(c, "SSLInfoCallback(SSL_CB_HANDSHAKE_DONE);");
530
1814
    CHECK(!SSL_renegotiate_pending(ssl));
531
    Local<Value> callback;
532
533
1814
    c->established_ = true;
534
535
3628
    if (object->Get(env->context(), env->onhandshakedone_string())
536

3628
          .ToLocal(&callback) && callback->IsFunction()) {
537
3628
      c->MakeCallback(callback.As<Function>(), 0, nullptr);
538
    }
539
  }
540
}
541
542
19811
void TLSWrap::EncOut() {
543
19811
  Debug(this, "Trying to write encrypted output");
544
545
  // Ignore cycling data if ClientHello wasn't yet parsed
546
19811
  if (!hello_parser_.IsEnded()) {
547
1
    Debug(this, "Returning from EncOut(), hello_parser_ active");
548
12439
    return;
549
  }
550
551
  // Write in progress
552
19810
  if (write_size_ != 0) {
553
3601
    Debug(this, "Returning from EncOut(), write currently in progress");
554
3601
    return;
555
  }
556
557
  // Wait for `newSession` callback to be invoked
558
16209
  if (is_awaiting_new_session()) {
559
7
    Debug(this, "Returning from EncOut(), awaiting new session");
560
7
    return;
561
  }
562
563
  // Split-off queue
564

16202
  if (established_ && current_write_) {
565
5155
    Debug(this, "EncOut() write is scheduled");
566
5155
    write_callback_scheduled_ = true;
567
  }
568
569
16202
  if (ssl_ == nullptr) {
570
2
    Debug(this, "Returning from EncOut(), ssl_ == nullptr");
571
2
    return;
572
  }
573
574
  // No encrypted output ready to write to the underlying stream.
575
16200
  if (BIO_pending(enc_out_) == 0) {
576
8652
    Debug(this, "No pending encrypted output");
577

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

7548
  CHECK(write_size_ != 0 && count != 0);
606
607
  uv_buf_t buf[arraysize(data)];
608
7548
  uv_buf_t* bufs = buf;
609
15229
  for (size_t i = 0; i < count; i++)
610
7681
    buf[i] = uv_buf_init(data[i], size[i]);
611
612
7548
  Debug(this, "Writing %zu buffers to the underlying stream", count);
613
7548
  StreamWriteResult res = underlying_stream()->Write(bufs, count);
614
7547
  if (res.err != 0) {
615
176
    InvokeQueued(res.err);
616
176
    return;
617
  }
618
619
7371
  if (!res.async) {
620
6813
    Debug(this, "Write finished synchronously");
621
13626
    HandleScope handle_scope(env()->isolate());
622
623
    // Simulate asynchronous finishing, TLS cannot handle this at the moment.
624
6813
    BaseObjectPtr<TLSWrap> strong_ref{this};
625
6813
    env()->SetImmediate([this, strong_ref](Environment* env) {
626
6813
      OnStreamAfterWrite(nullptr, 0);
627
6813
    });
628
  }
629
}
630
631
7470
void TLSWrap::OnStreamAfterWrite(WriteWrap* req_wrap, int status) {
632
7470
  Debug(this, "OnStreamAfterWrite(status = %d)", status);
633
7470
  if (current_empty_write_) {
634
100
    Debug(this, "Had empty write");
635
    BaseObjectPtr<AsyncWrap> current_empty_write =
636
100
        std::move(current_empty_write_);
637
100
    current_empty_write_.reset();
638
100
    WriteWrap* finishing = WriteWrap::FromObject(current_empty_write);
639
100
    finishing->Done(status);
640
100
    return;
641
  }
642
643
7370
  if (ssl_ == nullptr) {
644
    Debug(this, "ssl_ == nullptr, marking as cancelled");
645
    status = UV_ECANCELED;
646
  }
647
648
  // Handle error
649
7370
  if (status) {
650
3
    if (shutdown_) {
651
1
      Debug(this, "Ignoring error after shutdown");
652
1
      return;
653
    }
654
655
    // Notify about error
656
2
    InvokeQueued(status);
657
2
    return;
658
  }
659
660
  // Commit
661
7367
  NodeBIO::FromBIO(enc_out_)->Read(nullptr, write_size_);
662
663
  // Ensure that the progress will be made and `InvokeQueued` will be called.
664
7367
  ClearIn();
665
666
  // Try writing more data
667
7367
  write_size_ = 0;
668
7367
  EncOut();
669
}
670
671
8358
void TLSWrap::ClearOut() {
672
8358
  Debug(this, "Trying to read cleartext output");
673
  // Ignore cycling data if ClientHello wasn't yet parsed
674
8358
  if (!hello_parser_.IsEnded()) {
675
1
    Debug(this, "Returning from ClearOut(), hello_parser_ active");
676
7724
    return;
677
  }
678
679
  // No reads after EOF
680
8357
  if (eof_) {
681
    Debug(this, "Returning from ClearOut(), EOF reached");
682
    return;
683
  }
684
685
8357
  if (ssl_ == nullptr) {
686
1
    Debug(this, "Returning from ClearOut(), ssl_ == nullptr");
687
1
    return;
688
  }
689
690
8356
  MarkPopErrorOnReturn mark_pop_error_on_return;
691
692
  char out[kClearOutChunkSize];
693
  int read;
694
  for (;;) {
695
11590
    read = SSL_read(ssl_.get(), out, sizeof(out));
696
11590
    Debug(this, "Read %d bytes of cleartext output", read);
697
698
11590
    if (read <= 0)
699
8354
      break;
700
701
3236
    char* current = out;
702
8524
    while (read > 0) {
703
5290
      int avail = read;
704
705
5290
      uv_buf_t buf = EmitAlloc(avail);
706
5290
      if (static_cast<int>(buf.len) < avail)
707
2054
        avail = buf.len;
708
5290
      memcpy(buf.base, current, avail);
709
5290
      EmitRead(avail, buf);
710
711
      // Caveat emptor: OnRead() calls into JS land which can result in
712
      // the SSL context object being destroyed.  We have to carefully
713
      // check that ssl_ != nullptr afterwards.
714
5289
      if (ssl_ == nullptr) {
715
1
        Debug(this, "Returning from read loop, ssl_ == nullptr");
716
1
        return;
717
      }
718
719
5288
      read -= avail;
720
5288
      current += avail;
721
    }
722
3234
  }
723
724
  // We need to check whether an error occurred or the connection was
725
  // shutdown cleanly (SSL_ERROR_ZERO_RETURN) even when read == 0.
726
  // See node#1642 and SSL_read(3SSL) for details. SSL_get_error must be
727
  // called immediately after SSL_read, without calling into JS, which may
728
  // change OpenSSL's error queue, modify ssl_, or even destroy ssl_
729
  // altogether.
730
8354
  if (read <= 0) {
731
8354
    HandleScope handle_scope(env()->isolate());
732
    Local<Value> error;
733
8354
    int err = SSL_get_error(ssl_.get(), read);
734
8354
    switch (err) {
735
1126
      case SSL_ERROR_ZERO_RETURN:
736
1126
        if (!eof_) {
737
1126
          eof_ = true;
738
1126
          EmitRead(UV_EOF);
739
        }
740
1126
        return;
741
742
640
      case SSL_ERROR_SSL:
743
      case SSL_ERROR_SYSCALL:
744
        {
745
640
          unsigned long ssl_err = ERR_peek_error();  // NOLINT(runtime/int)
746
747
640
          Local<Context> context = env()->isolate()->GetCurrentContext();
748
640
          if (UNLIKELY(context.IsEmpty())) return;
749
640
          const std::string error_str = GetBIOError();
750
          Local<String> message = OneByteString(
751
640
              env()->isolate(), error_str.c_str(), error_str.size());
752
640
          if (UNLIKELY(message.IsEmpty())) return;
753
640
          error = Exception::Error(message);
754
640
          if (UNLIKELY(error.IsEmpty())) return;
755
          Local<Object> obj;
756
1280
          if (UNLIKELY(!error->ToObject(context).ToLocal(&obj))) return;
757
758
640
          const char* ls = ERR_lib_error_string(ssl_err);
759
640
          const char* fs = ERR_func_error_string(ssl_err);
760
640
          const char* rs = ERR_reason_error_string(ssl_err);
761
640
          if (!Set(env(), obj, env()->library_string(), ls) ||
762

1280
              !Set(env(), obj, env()->function_string(), fs) ||
763
647
              !Set(env(), obj, env()->reason_string(), rs, false)) return;
764
          // SSL has no API to recover the error name from the number, so we
765
          // transform reason strings like "this error" to "ERR_SSL_THIS_ERROR",
766
          // which ends up being close to the original error macro name.
767
633
          std::string code(rs);
768
          // TODO(RaisinTen): Pass an appropriate execution policy when it is
769
          // implemented in our supported compilers.
770
          std::transform(code.begin(), code.end(), code.begin(),
771
13734
                         [](char c) { return c == ' ' ? '_' : ToUpper(c); });
772
633
          if (!Set(env(), obj,
773
1906
                   env()->code_string(), ("ERR_SSL_" + code).c_str())) return;
774
        }
775
633
        break;
776
777
6588
      default:
778
6588
        return;
779
    }
780
781
633
    Debug(this, "Got SSL error (%d), calling onerror", err);
782
    // When TLS Alert are stored in wbio,
783
    // it should be flushed to socket before destroyed.
784
633
    if (BIO_pending(enc_out_) != 0)
785
576
      EncOut();
786
787
633
    MakeCallback(env()->onerror_string(), 1, &error);
788
  }
789
}
790
791
13799
void TLSWrap::ClearIn() {
792
13799
  Debug(this, "Trying to write cleartext input");
793
  // Ignore cycling data if ClientHello wasn't yet parsed
794
13799
  if (!hello_parser_.IsEnded()) {
795
    Debug(this, "Returning from ClearIn(), hello_parser_ active");
796
13578
    return;
797
  }
798
799
13799
  if (ssl_ == nullptr) {
800
    Debug(this, "Returning from ClearIn(), ssl_ == nullptr");
801
    return;
802
  }
803
804

14203
  if (!pending_cleartext_input_ ||
805
404
      pending_cleartext_input_->ByteLength() == 0) {
806
13395
    Debug(this, "Returning from ClearIn(), no pending data");
807
13395
    return;
808
  }
809
810
404
  std::unique_ptr<BackingStore> bs = std::move(pending_cleartext_input_);
811
404
  MarkPopErrorOnReturn mark_pop_error_on_return;
812
813
404
  NodeBIO::FromBIO(enc_out_)->set_allocate_tls_hint(bs->ByteLength());
814
404
  int written = SSL_write(ssl_.get(), bs->Data(), bs->ByteLength());
815
404
  Debug(this, "Writing %zu bytes, written = %d", bs->ByteLength(), written);
816

404
  CHECK(written == -1 || written == static_cast<int>(bs->ByteLength()));
817
818
  // All written
819
404
  if (written != -1) {
820
181
    Debug(this, "Successfully wrote all data to SSL");
821
181
    return;
822
  }
823
824
  // Error or partial write
825
223
  int err = SSL_get_error(ssl_.get(), written);
826

223
  if (err == SSL_ERROR_SSL || err == SSL_ERROR_SYSCALL) {
827
2
    Debug(this, "Got SSL error (%d)", err);
828
2
    write_callback_scheduled_ = true;
829
    // TODO(@sam-github) Should forward an error object with
830
    // .code/.function/.etc, if possible.
831
2
    InvokeQueued(UV_EPROTO, GetBIOError().c_str());
832
2
    return;
833
  }
834
835
221
  Debug(this, "Pushing data back");
836
  // Push back the not-yet-written data. This can be skipped in the error
837
  // case because no further writes would succeed anyway.
838
221
  pending_cleartext_input_ = std::move(bs);
839
}
840
841
std::string TLSWrap::diagnostic_name() const {
842
  std::string name = "TLSWrap ";
843
  name += is_server() ? "server (" : "client (";
844
  name += std::to_string(static_cast<int64_t>(get_async_id())) + ")";
845
  return name;
846
}
847
848
26233
AsyncWrap* TLSWrap::GetAsyncWrap() {
849
26233
  return static_cast<AsyncWrap*>(this);
850
}
851
852
1154
bool TLSWrap::IsIPCPipe() {
853
1154
  return underlying_stream()->IsIPCPipe();
854
}
855
856
3
int TLSWrap::GetFD() {
857
3
  return underlying_stream()->GetFD();
858
}
859
860
4032
bool TLSWrap::IsAlive() {
861
4031
  return ssl_ &&
862

8063
      underlying_stream() != nullptr &&
863
8062
      underlying_stream()->IsAlive();
864
}
865
866
3
bool TLSWrap::IsClosing() {
867
3
  return underlying_stream()->IsClosing();
868
}
869
870
2451
int TLSWrap::ReadStart() {
871
2451
  Debug(this, "ReadStart()");
872

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

2495
  CHECK(written == -1 || written == static_cast<int>(length));
997
2495
  Debug(this, "Writing %zu bytes, written = %d", length, written);
998
999
2495
  if (written == -1) {
1000
    // If we stopped writing because of an error, it's fatal, discard the data.
1001
187
    int err = SSL_get_error(ssl_.get(), written);
1002

187
    if (err == SSL_ERROR_SSL || err == SSL_ERROR_SYSCALL) {
1003
      // TODO(@jasnell): What are we doing with the error?
1004
2
      Debug(this, "Got SSL error (%d), returning UV_EPROTO", err);
1005
2
      current_write_.reset();
1006
2
      return UV_EPROTO;
1007
    }
1008
1009
185
    Debug(this, "Saving data for later write");
1010
    // Otherwise, save unwritten data so it can be written later by ClearIn().
1011

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

20
    CHECK_IMPLIES(data == nullptr, avail == 0);
1071
20
    Debug(this, "Passing %zu bytes to the hello parser", avail);
1072
20
    return hello_parser_.Parse(data, avail);
1073
  }
1074
1075
  // Cycle OpenSSL's state
1076
6385
  Cycle();
1077
}
1078
1079
1445
ShutdownWrap* TLSWrap::CreateShutdownWrap(Local<Object> req_wrap_object) {
1080
1445
  return underlying_stream()->CreateShutdownWrap(req_wrap_object);
1081
}
1082
1083
1445
int TLSWrap::DoShutdown(ShutdownWrap* req_wrap) {
1084
1445
  Debug(this, "DoShutdown()");
1085
2890
  MarkPopErrorOnReturn mark_pop_error_on_return;
1086
1087

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

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

18
  if (UNLIKELY(psk_val.IsEmpty()) || !psk_val->IsArrayBufferView())
1367
1
    return 0;
1368
1369
8
  ArrayBufferViewContents<char> psk_buf(psk_val);
1370
1371
8
  if (psk_buf.length() > max_psk_len)
1372
    return 0;
1373
1374
8
  memcpy(psk, psk_buf.data(), psk_buf.length());
1375
8
  return psk_buf.length();
1376
}
1377
1378
10
unsigned int TLSWrap::PskClientCallback(
1379
    SSL* s,
1380
    const char* hint,
1381
    char* identity,
1382
    unsigned int max_identity_len,
1383
    unsigned char* psk,
1384
    unsigned int max_psk_len) {
1385
10
  TLSWrap* p = static_cast<TLSWrap*>(SSL_get_app_data(s));
1386
1387
10
  Environment* env = p->env();
1388
20
  HandleScope scope(env->isolate());
1389
1390
  Local<Value> argv[] = {
1391
    Null(env->isolate()),
1392
    Integer::NewFromUnsigned(env->isolate(), max_psk_len),
1393
    Integer::NewFromUnsigned(env->isolate(), max_identity_len)
1394
30
  };
1395
1396
10
  if (hint != nullptr) {
1397
    Local<String> local_hint =
1398
        String::NewFromUtf8(env->isolate(), hint).FromMaybe(Local<String>());
1399
    if (UNLIKELY(local_hint.IsEmpty()))
1400
      return 0;
1401
1402
    argv[0] = local_hint;
1403
  }
1404
1405
  Local<Value> ret =
1406
10
      p->MakeCallback(env->onpskexchange_symbol(), arraysize(argv), argv)
1407
10
          .FromMaybe(Local<Value>());
1408

20
  if (UNLIKELY(ret.IsEmpty()) || !ret->IsObject())
1409
1
    return 0;
1410
1411
9
  Local<Object> obj = ret.As<Object>();
1412
1413
18
  Local<Value> psk_val = obj->Get(env->context(), env->psk_string())
1414
9
      .FromMaybe(Local<Value>());
1415

18
  if (UNLIKELY(psk_val.IsEmpty()) || !psk_val->IsArrayBufferView())
1416
    return 0;
1417
1418
9
  ArrayBufferViewContents<char> psk_buf(psk_val);
1419
9
  if (psk_buf.length() > max_psk_len)
1420
    return 0;
1421
1422
18
  Local<Value> identity_val = obj->Get(env->context(), env->identity_string())
1423
9
      .FromMaybe(Local<Value>());
1424

27
  if (UNLIKELY(identity_val.IsEmpty()) || !identity_val->IsString())
1425
    return 0;
1426
1427
18
  Utf8Value identity_buf(env->isolate(), identity_val);
1428
1429
9
  if (identity_buf.length() > max_identity_len)
1430
    return 0;
1431
1432
9
  memcpy(identity, *identity_buf, identity_buf.length());
1433
9
  memcpy(psk, psk_buf.data(), psk_buf.length());
1434
1435
9
  return psk_buf.length();
1436
}
1437
1438
#endif  // ifndef OPENSSL_NO_PSK
1439
1440
2
void TLSWrap::GetWriteQueueSize(const FunctionCallbackInfo<Value>& info) {
1441
  TLSWrap* wrap;
1442
2
  ASSIGN_OR_RETURN_UNWRAP(&wrap, info.This());
1443
1444
2
  if (!wrap->ssl_)
1445
    return info.GetReturnValue().Set(0);
1446
1447
2
  uint32_t write_queue_size = BIO_pending(wrap->enc_out_);
1448
4
  info.GetReturnValue().Set(write_queue_size);
1449
}
1450
1451
void TLSWrap::MemoryInfo(MemoryTracker* tracker) const {
1452
  tracker->TrackField("ocsp_response", ocsp_response_);
1453
  tracker->TrackField("sni_context", sni_context_);
1454
  tracker->TrackField("error", error_);
1455
  if (pending_cleartext_input_)
1456
    tracker->TrackField("pending_cleartext_input", pending_cleartext_input_);
1457
  if (enc_in_ != nullptr)
1458
    tracker->TrackField("enc_in", NodeBIO::FromBIO(enc_in_));
1459
  if (enc_out_ != nullptr)
1460
    tracker->TrackField("enc_out", NodeBIO::FromBIO(enc_out_));
1461
}
1462
1463
22
void TLSWrap::CertCbDone(const FunctionCallbackInfo<Value>& args) {
1464
22
  Environment* env = Environment::GetCurrent(args);
1465
  TLSWrap* w;
1466
24
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1467
1468

22
  CHECK(w->is_waiting_cert_cb() && w->cert_cb_running_);
1469
1470
22
  Local<Object> object = w->object();
1471
44
  Local<Value> ctx = object->Get(env->context(), env->sni_context_string())
1472
22
      .FromMaybe(Local<Value>());
1473
22
  if (UNLIKELY(ctx.IsEmpty()))
1474
    return;
1475
1476
22
  Local<FunctionTemplate> cons = env->secure_context_constructor_template();
1477
22
  if (cons->HasInstance(ctx)) {
1478
12
    SecureContext* sc = Unwrap<SecureContext>(ctx.As<Object>());
1479
12
    CHECK_NOT_NULL(sc);
1480
    // Store the SNI context for later use.
1481
12
    w->sni_context_ = BaseObjectPtr<SecureContext>(sc);
1482
1483


12
    if (UseSNIContext(w->ssl_, w->sni_context_) && !w->SetCACerts(sc)) {
1484
      // Not clear why sometimes we throw error, and sometimes we call
1485
      // onerror(). Both cause .destroy(), but onerror does a bit more.
1486
      unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
1487
      return ThrowCryptoError(env, err, "CertCbDone");
1488
    }
1489
10
  } else if (ctx->IsObject()) {
1490
    // Failure: incorrect SNI context object
1491
2
    Local<Value> err = Exception::TypeError(env->sni_context_err_string());
1492
2
    w->MakeCallback(env->onerror_string(), 1, &err);
1493
2
    return;
1494
  }
1495
1496
  CertCb cb;
1497
  void* arg;
1498
1499
20
  cb = w->cert_cb_;
1500
20
  arg = w->cert_cb_arg_;
1501
1502
20
  w->cert_cb_running_ = false;
1503
20
  w->cert_cb_ = nullptr;
1504
20
  w->cert_cb_arg_ = nullptr;
1505
1506
20
  cb(arg);
1507
}
1508
1509
253
void TLSWrap::SetALPNProtocols(const FunctionCallbackInfo<Value>& args) {
1510
  TLSWrap* w;
1511
253
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1512
253
  Environment* env = w->env();
1513

506
  if (args.Length() < 1 || !Buffer::HasInstance(args[0]))
1514
    return env->ThrowTypeError("Must give a Buffer as first argument");
1515
1516
506
  ArrayBufferViewContents<uint8_t> protos(args[0].As<ArrayBufferView>());
1517
253
  SSL* ssl = w->ssl_.get();
1518
253
  if (w->is_client()) {
1519
41
    CHECK_EQ(0, SSL_set_alpn_protos(ssl, protos.data(), protos.length()));
1520
  } else {
1521
636
    w->alpn_protos_ = std::vector<unsigned char>(
1522
424
        protos.data(), protos.data() + protos.length());
1523
212
    SSL_CTX_set_alpn_select_cb(SSL_get_SSL_CTX(ssl), SelectALPNCallback, w);
1524
  }
1525
}
1526
1527
498
void TLSWrap::GetPeerCertificate(const FunctionCallbackInfo<Value>& args) {
1528
  TLSWrap* w;
1529
498
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1530
498
  Environment* env = w->env();
1531
1532

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

20
  if (args.Length() >= 1 && Buffer::HasInstance(args[0])) {
1735
10
    ArrayBufferViewContents<unsigned char> sbuf(args[0]);
1736
1737
10
    const unsigned char* p = sbuf.data();
1738
10
    SSL_SESSION* sess = d2i_SSL_SESSION(nullptr, &p, sbuf.length());
1739
1740
    // Setup next session and move hello to the BIO buffer
1741
10
    w->next_sess_.reset(sess);
1742
  }
1743
}
1744
1745
2
void TLSWrap::GetSharedSigalgs(const FunctionCallbackInfo<Value>& args) {
1746
2
  Environment* env = Environment::GetCurrent(args);
1747
  TLSWrap* w;
1748
2
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1749
1750
2
  SSL* ssl = w->ssl_.get();
1751
2
  int nsig = SSL_get_shared_sigalgs(ssl, 0, nullptr, nullptr, nullptr, nullptr,
1752
                                    nullptr);
1753
2
  MaybeStackBuffer<Local<Value>, 16> ret_arr(nsig);
1754
1755
5
  for (int i = 0; i < nsig; i++) {
1756
    int hash_nid;
1757
    int sign_nid;
1758
3
    std::string sig_with_md;
1759
1760
3
    SSL_get_shared_sigalgs(ssl, i, &sign_nid, &hash_nid, nullptr, nullptr,
1761
                           nullptr);
1762
1763

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

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