GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: crypto/crypto_tls.cc Lines: 1045 1137 91.9 %
Date: 2022-08-12 04:19:25 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
35
int SelectALPNCallback(
222
    SSL* s,
223
    const unsigned char** out,
224
    unsigned char* outlen,
225
    const unsigned char* in,
226
    unsigned int inlen,
227
    void* arg) {
228
35
  TLSWrap* w = static_cast<TLSWrap*>(SSL_get_app_data(s));
229
35
  Environment* env = w->env();
230
70
  HandleScope handle_scope(env->isolate());
231
35
  Context::Scope context_scope(env->context());
232
233
  Local<Value> alpn_buffer =
234
35
      w->object()->GetPrivate(
235
          env->context(),
236
70
          env->alpn_buffer_private_symbol()).FromMaybe(Local<Value>());
237

70
  if (UNLIKELY(alpn_buffer.IsEmpty()) || !alpn_buffer->IsArrayBufferView())
238
    return SSL_TLSEXT_ERR_NOACK;
239
240
35
  ArrayBufferViewContents<unsigned char> alpn_protos(alpn_buffer);
241
35
  int status = SSL_select_next_proto(
242
      const_cast<unsigned char**>(out),
243
      outlen,
244
      alpn_protos.data(),
245
35
      alpn_protos.length(),
246
      in,
247
      inlen);
248
249
  // According to 3.2. Protocol Selection of RFC7301, fatal
250
  // no_application_protocol alert shall be sent but OpenSSL 1.0.2 does not
251
  // support it yet. See
252
  // https://rt.openssl.org/Ticket/Display.html?id=3463&user=guest&pass=guest
253
  return status == OPENSSL_NPN_NEGOTIATED
254
35
      ? SSL_TLSEXT_ERR_OK
255
35
      : SSL_TLSEXT_ERR_NOACK;
256
}
257
258
8
int TLSExtStatusCallback(SSL* s, void* arg) {
259
8
  TLSWrap* w = static_cast<TLSWrap*>(SSL_get_app_data(s));
260
8
  Environment* env = w->env();
261
16
  HandleScope handle_scope(env->isolate());
262
263
8
  if (w->is_client()) {
264
    // Incoming response
265
    Local<Value> arg;
266
12
    if (GetSSLOCSPResponse(env, s, Null(env->isolate())).ToLocal(&arg))
267
4
      w->MakeCallback(env->onocspresponse_string(), 1, &arg);
268
269
    // No async acceptance is possible, so always return 1 to accept the
270
    // response.  The listener for 'OCSPResponse' event has no control over
271
    // return value, but it can .destroy() the connection if the response is not
272
    // acceptable.
273
4
    return 1;
274
  }
275
276
  // Outgoing response
277
  Local<ArrayBufferView> obj =
278
8
      w->ocsp_response().FromMaybe(Local<ArrayBufferView>());
279
4
  if (UNLIKELY(obj.IsEmpty()))
280
2
    return SSL_TLSEXT_ERR_NOACK;
281
282
2
  size_t len = obj->ByteLength();
283
284
  // OpenSSL takes control of the pointer after accepting it
285
2
  unsigned char* data = MallocOpenSSL<unsigned char>(len);
286
2
  obj->CopyContents(data, len);
287
288
2
  if (!SSL_set_tlsext_status_ocsp_resp(s, data, len))
289
    OPENSSL_free(data);
290
291
2
  w->ClearOcspResponse();
292
293
2
  return SSL_TLSEXT_ERR_OK;
294
}
295
296
12392
void ConfigureSecureContext(SecureContext* sc) {
297
  // OCSP stapling
298
12392
  SSL_CTX_set_tlsext_status_cb(sc->ctx().get(), TLSExtStatusCallback);
299
12392
  SSL_CTX_set_tlsext_status_arg(sc->ctx().get(), nullptr);
300
12392
}
301
302
3985
inline bool Set(
303
    Environment* env,
304
    Local<Object> target,
305
    Local<String> name,
306
    const char* value,
307
    bool ignore_null = true) {
308
3985
  if (value == nullptr)
309
1340
    return ignore_null;
310
2645
  return !target->Set(
311
      env->context(),
312
      name,
313
5290
      OneByteString(env->isolate(), value))
314
2645
          .IsNothing();
315
}
316
317
635
std::string GetBIOError() {
318
635
  std::string ret;
319
635
  ERR_print_errors_cb(
320
631
      [](const char* str, size_t len, void* opaque) {
321
631
        static_cast<std::string*>(opaque)->assign(str, len);
322
631
        return 0;
323
      },
324
      static_cast<void*>(&ret));
325
635
  return ret;
326
}
327
}  // namespace
328
329
12392
TLSWrap::TLSWrap(Environment* env,
330
                 Local<Object> obj,
331
                 Kind kind,
332
                 StreamBase* stream,
333
12392
                 SecureContext* sc)
334
    : AsyncWrap(env, obj, AsyncWrap::PROVIDER_TLSWRAP),
335
      StreamBase(env),
336
      env_(env),
337
      kind_(kind),
338
12392
      sc_(sc) {
339
12392
  MakeWeak();
340
12392
  CHECK(sc_);
341
12392
  ssl_ = sc_->CreateSSL();
342
12392
  CHECK(ssl_);
343
344
12392
  sc_->SetGetSessionCallback(GetSessionCallback);
345
12392
  sc_->SetNewSessionCallback(NewSessionCallback);
346
347
12392
  StreamBase::AttachToObject(GetObject());
348
12392
  stream->PushStreamListener(this);
349
350
12392
  env_->isolate()->AdjustAmountOfExternalAllocatedMemory(kExternalSize);
351
352
12392
  InitSSL();
353
12392
  Debug(this, "Created new TLSWrap");
354
12392
}
355
356
74322
TLSWrap::~TLSWrap() {
357
24774
  Destroy();
358
49548
}
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
21095
void TLSWrap::InvokeQueued(int status, const char* error_str) {
375
21095
  Debug(this, "Invoking queued write callbacks (%d, %s)", status, error_str);
376
21095
  if (!write_callback_scheduled_)
377
4832
    return;
378
379
16263
  if (current_write_) {
380
5394
    BaseObjectPtr<AsyncWrap> current_write = std::move(current_write_);
381
2697
    current_write_.reset();
382
2697
    WriteWrap* w = WriteWrap::FromObject(current_write);
383
2697
    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
12392
void TLSWrap::InitSSL() {
393
  // Initialize SSL – OpenSSL takes ownership of these.
394
12392
  enc_in_ = NodeBIO::New(env()).release();
395
12392
  enc_out_ = NodeBIO::New(env()).release();
396
397
12392
  SSL_set_bio(ssl_.get(), enc_in_, enc_out_);
398
399
  // NOTE: This could be overridden in SetVerifyMode
400
12392
  SSL_set_verify(ssl_.get(), SSL_VERIFY_NONE, VerifyCallback);
401
402
#ifdef SSL_MODE_RELEASE_BUFFERS
403
12392
  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
12392
  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
12392
  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
12392
  SSL_set_info_callback(ssl_.get(), SSLInfoCallback);
425
426
12392
  if (is_server())
427
947
    sc_->SetSelectSNIContextCallback(SelectSNIContextCallback);
428
429
12392
  ConfigureSecureContext(sc_.get());
430
431
12392
  SSL_set_cert_cb(ssl_.get(), SSLCertCallback, this);
432
433
12392
  if (is_server()) {
434
947
    SSL_set_accept_state(ssl_.get());
435
11445
  } else if (is_client()) {
436
    // Enough space for server response (hello, cert)
437
11445
    NodeBIO::FromBIO(enc_in_)->set_initial(kInitialClientBufferLength);
438
11445
    SSL_set_connect_state(ssl_.get());
439
  } else {
440
    // Unexpected
441
    ABORT();
442
  }
443
12392
}
444
445
12392
void TLSWrap::Wrap(const FunctionCallbackInfo<Value>& args) {
446
12392
  Environment* env = Environment::GetCurrent(args);
447
448
12392
  CHECK_EQ(args.Length(), 3);
449
12392
  CHECK(args[0]->IsObject());
450
12392
  CHECK(args[1]->IsObject());
451
12392
  CHECK(args[2]->IsBoolean());
452
453
24784
  Local<Object> sc = args[1].As<Object>();
454

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

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

4334
  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
19952
void TLSWrap::EncOut() {
552
19952
  Debug(this, "Trying to write encrypted output");
553
554
  // Ignore cycling data if ClientHello wasn't yet parsed
555
19952
  if (!hello_parser_.IsEnded()) {
556
1
    Debug(this, "Returning from EncOut(), hello_parser_ active");
557
12498
    return;
558
  }
559
560
  // Write in progress
561
19951
  if (write_size_ != 0) {
562
3583
    Debug(this, "Returning from EncOut(), write currently in progress");
563
3583
    return;
564
  }
565
566
  // Wait for `newSession` callback to be invoked
567
16368
  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

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

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

7633
  CHECK(write_size_ != 0 && count != 0);
615
616
  uv_buf_t buf[arraysize(data)];
617
7633
  uv_buf_t* bufs = buf;
618
15402
  for (size_t i = 0; i < count; i++)
619
7769
    buf[i] = uv_buf_init(data[i], size[i]);
620
621
7633
  Debug(this, "Writing %zu buffers to the underlying stream", count);
622
7633
  StreamWriteResult res = underlying_stream()->Write(bufs, count);
623
7632
  if (res.err != 0) {
624
179
    InvokeQueued(res.err);
625
179
    return;
626
  }
627
628
7453
  if (!res.async) {
629
6895
    Debug(this, "Write finished synchronously");
630
13790
    HandleScope handle_scope(env()->isolate());
631
632
    // Simulate asynchronous finishing, TLS cannot handle this at the moment.
633
6895
    BaseObjectPtr<TLSWrap> strong_ref{this};
634
6895
    env()->SetImmediate([this, strong_ref](Environment* env) {
635
6895
      OnStreamAfterWrite(nullptr, 0);
636
6895
    });
637
  }
638
}
639
640
7552
void TLSWrap::OnStreamAfterWrite(WriteWrap* req_wrap, int status) {
641
7552
  Debug(this, "OnStreamAfterWrite(status = %d)", status);
642
7552
  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
7452
  if (ssl_ == nullptr) {
653
    Debug(this, "ssl_ == nullptr, marking as cancelled");
654
    status = UV_ECANCELED;
655
  }
656
657
  // Handle error
658
7452
  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
7449
  NodeBIO::FromBIO(enc_out_)->Read(nullptr, write_size_);
671
672
  // Ensure that the progress will be made and `InvokeQueued` will be called.
673
7449
  ClearIn();
674
675
  // Try writing more data
676
7449
  write_size_ = 0;
677
7449
  EncOut();
678
}
679
680
8694
int TLSWrap::GetSSLError(int status) const {
681
  // ssl_ might already be destroyed for reading EOF from a close notify alert.
682
8694
  return ssl_ != nullptr ? SSL_get_error(ssl_.get(), status) : 0;
683
}
684
685
8291
void TLSWrap::ClearOut() {
686
8291
  Debug(this, "Trying to read cleartext output");
687
  // Ignore cycling data if ClientHello wasn't yet parsed
688
8291
  if (!hello_parser_.IsEnded()) {
689
1
    Debug(this, "Returning from ClearOut(), hello_parser_ active");
690
7661
    return;
691
  }
692
693
  // No reads after EOF
694
8290
  if (eof_) {
695
    Debug(this, "Returning from ClearOut(), EOF reached");
696
    return;
697
  }
698
699
8290
  if (ssl_ == nullptr) {
700
1
    Debug(this, "Returning from ClearOut(), ssl_ == nullptr");
701
1
    return;
702
  }
703
704
8289
  MarkPopErrorOnReturn mark_pop_error_on_return;
705
706
  char out[kClearOutChunkSize];
707
  int read;
708
  for (;;) {
709
11483
    read = SSL_read(ssl_.get(), out, sizeof(out));
710
11483
    Debug(this, "Read %d bytes of cleartext output", read);
711
712
11483
    if (read <= 0)
713
8287
      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
8287
  int flags = SSL_get_shutdown(ssl_.get());
739

8287
  if (!eof_ && flags & SSL_RECEIVED_SHUTDOWN) {
740
1146
    eof_ = true;
741
1146
    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
8287
  if (read <= 0) {
748
8287
    HandleScope handle_scope(env()->isolate());
749
    Local<Value> error;
750
8287
    int err = GetSSLError(read);
751
8287
    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
633
      case SSL_ERROR_SSL:
759
      case SSL_ERROR_SYSCALL:
760
        {
761
633
          unsigned long ssl_err = ERR_peek_error();  // NOLINT(runtime/int)
762
763
633
          Local<Context> context = env()->isolate()->GetCurrentContext();
764
633
          if (UNLIKELY(context.IsEmpty())) return;
765
633
          const std::string error_str = GetBIOError();
766
          Local<String> message = OneByteString(
767
633
              env()->isolate(), error_str.c_str(), error_str.size());
768
633
          if (UNLIKELY(message.IsEmpty())) return;
769
633
          error = Exception::Error(message);
770
633
          if (UNLIKELY(error.IsEmpty())) return;
771
          Local<Object> obj;
772
1266
          if (UNLIKELY(!error->ToObject(context).ToLocal(&obj))) return;
773
774
633
          const char* ls = ERR_lib_error_string(ssl_err);
775
633
          const char* fs = ERR_func_error_string(ssl_err);
776
633
          const char* rs = ERR_reason_error_string(ssl_err);
777
633
          if (!Set(env(), obj, env()->library_string(), ls) ||
778

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

14252
  if (!pending_cleartext_input_ ||
821
400
      pending_cleartext_input_->ByteLength() == 0) {
822
13452
    Debug(this, "Returning from ClearIn(), no pending data");
823
13452
    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
26412
AsyncWrap* TLSWrap::GetAsyncWrap() {
865
26412
  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
4086
bool TLSWrap::IsAlive() {
877
4085
  return ssl_ &&
878

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

2445
  if (underlying_stream() != nullptr && !eof_)
889
2444
    return underlying_stream()->ReadStart();
890
1
  return 0;
891
}
892
893
1666
int TLSWrap::ReadStop() {
894
1666
  Debug(this, "ReadStop()");
895
1666
  return underlying_stream() != nullptr ? underlying_stream()->ReadStop() : 0;
896
}
897
898
5598
const char* TLSWrap::Error() const {
899
5598
  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
2805
int TLSWrap::DoWrite(WriteWrap* w,
909
                     uv_buf_t* bufs,
910
                     size_t count,
911
                     uv_stream_t* send_handle) {
912
2805
  CHECK_NULL(send_handle);
913
2805
  Debug(this, "DoWrite()");
914
915
2805
  if (ssl_ == nullptr) {
916
4
    ClearError();
917
4
    error_ = "Write after DestroySSL";
918
4
    return UV_EPROTO;
919
  }
920
921
2801
  size_t length = 0;
922
  size_t i;
923
2801
  size_t nonempty_i = 0;
924
2801
  size_t nonempty_count = 0;
925
12804
  for (i = 0; i < count; i++) {
926
10003
    length += bufs[i].len;
927
10003
    if (bufs[i].len > 0) {
928
9701
      nonempty_i = i;
929
9701
      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
2801
  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
2701
  CHECK(!current_write_);
964
2701
  current_write_.reset(w->GetAsyncWrap());
965
966
  // Write encrypted data to underlying stream and call Done().
967
2701
  if (length == 0) {
968
101
    EncOut();
969
101
    return 0;
970
  }
971
972
2600
  std::unique_ptr<BackingStore> bs;
973
5200
  MarkPopErrorOnReturn mark_pop_error_on_return;
974
975
2600
  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
2600
  if (nonempty_count != 1) {
986
    {
987
1596
      NoArrayBufferZeroFillScope no_zero_fill_scope(env()->isolate_data());
988
1596
      bs = ArrayBuffer::NewBackingStore(env()->isolate(), length);
989
    }
990
1596
    size_t offset = 0;
991
10295
    for (i = 0; i < count; i++) {
992
8699
      memcpy(static_cast<char*>(bs->Data()) + offset,
993
8699
             bufs[i].base, bufs[i].len);
994
8699
      offset += bufs[i].len;
995
    }
996
997
1596
    NodeBIO::FromBIO(enc_out_)->set_allocate_tls_hint(length);
998
1596
    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

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

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

1976
  if (UNLIKELY(ctx.IsEmpty()) || !ctx->IsObject())
1292
988
    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
246
void TLSWrap::SetALPNProtocols(const FunctionCallbackInfo<Value>& args) {
1526
  TLSWrap* w;
1527
246
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1528
246
  Environment* env = w->env();
1529

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

824
    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
206
    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
3490
    result = False(env->isolate());
1988
63
  } 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
6
  } else if (alpn_proto_len == sizeof("http/1.1") - 1 &&
1992
2
             0 == memcmp(alpn_proto, "http/1.1", sizeof("http/1.1") - 1)) {
1993
4
    result = env->http_1_1_string();
1994
  } else {
1995
8
    result = OneByteString(env->isolate(), alpn_proto, alpn_proto_len);
1996
  }
1997
1998
3616
  args.GetReturnValue().Set(result);
1999
}
2000
2001
6403
void TLSWrap::Cycle() {
2002
  // Prevent recursion
2003
6403
  if (++cycle_depth_ > 1)
2004
14
    return;
2005
2006
12790
  for (; cycle_depth_ > 0; cycle_depth_--) {
2007
6403
    ClearIn();
2008
6403
    ClearOut();
2009
    // EncIn() doesn't exist, it happens via stream listener callbacks.
2010
6402
    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
581
void TLSWrap::Initialize(
2028
    Local<Object> target,
2029
    Local<Value> unused,
2030
    Local<Context> context,
2031
    void* priv) {
2032
581
  Environment* env = Environment::GetCurrent(context);
2033
581
  Isolate* isolate = env->isolate();
2034
2035
581
  SetMethod(context, target, "wrap", TLSWrap::Wrap);
2036
2037
1162
  NODE_DEFINE_CONSTANT(target, HAVE_SSL_TRACE);
2038
2039
581
  Local<FunctionTemplate> t = BaseObject::MakeLazilyInitializedJSTemplate(env);
2040
  Local<String> tlsWrapString =
2041
581
      FIXED_ONE_BYTE_STRING(env->isolate(), "TLSWrap");
2042
581
  t->SetClassName(tlsWrapString);
2043
1162
  t->InstanceTemplate()->SetInternalFieldCount(StreamBase::kInternalFieldCount);
2044
2045
  Local<FunctionTemplate> get_write_queue_size =
2046
      FunctionTemplate::New(env->isolate(),
2047
                            GetWriteQueueSize,
2048
                            Local<Value>(),
2049
581
                            Signature::New(env->isolate(), t));
2050
2324
  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
581
  t->Inherit(AsyncWrap::GetConstructorTemplate(env));
2057
2058
581
  SetProtoMethod(isolate, t, "certCbDone", CertCbDone);
2059
581
  SetProtoMethod(isolate, t, "destroySSL", DestroySSL);
2060
581
  SetProtoMethod(isolate, t, "enableCertCb", EnableCertCb);
2061
581
  SetProtoMethod(isolate, t, "endParser", EndParser);
2062
581
  SetProtoMethod(isolate, t, "enableKeylogCallback", EnableKeylogCallback);
2063
581
  SetProtoMethod(isolate, t, "enableSessionCallbacks", EnableSessionCallbacks);
2064
581
  SetProtoMethod(isolate, t, "enableTrace", EnableTrace);
2065
581
  SetProtoMethod(isolate, t, "getServername", GetServername);
2066
581
  SetProtoMethod(isolate, t, "loadSession", LoadSession);
2067
581
  SetProtoMethod(isolate, t, "newSessionDone", NewSessionDone);
2068
581
  SetProtoMethod(isolate, t, "receive", Receive);
2069
581
  SetProtoMethod(isolate, t, "renegotiate", Renegotiate);
2070
581
  SetProtoMethod(isolate, t, "requestOCSP", RequestOCSP);
2071
581
  SetProtoMethod(isolate, t, "setALPNProtocols", SetALPNProtocols);
2072
581
  SetProtoMethod(isolate, t, "setOCSPResponse", SetOCSPResponse);
2073
581
  SetProtoMethod(isolate, t, "setServername", SetServername);
2074
581
  SetProtoMethod(isolate, t, "setSession", SetSession);
2075
581
  SetProtoMethod(isolate, t, "setVerifyMode", SetVerifyMode);
2076
581
  SetProtoMethod(isolate, t, "start", Start);
2077
2078
581
  SetProtoMethodNoSideEffect(
2079
      isolate, t, "exportKeyingMaterial", ExportKeyingMaterial);
2080
581
  SetProtoMethodNoSideEffect(isolate, t, "isSessionReused", IsSessionReused);
2081
581
  SetProtoMethodNoSideEffect(
2082
      isolate, t, "getALPNNegotiatedProtocol", GetALPNNegotiatedProto);
2083
581
  SetProtoMethodNoSideEffect(isolate, t, "getCertificate", GetCertificate);
2084
581
  SetProtoMethodNoSideEffect(
2085
      isolate, t, "getX509Certificate", GetX509Certificate);
2086
581
  SetProtoMethodNoSideEffect(isolate, t, "getCipher", GetCipher);
2087
581
  SetProtoMethodNoSideEffect(
2088
      isolate, t, "getEphemeralKeyInfo", GetEphemeralKeyInfo);
2089
581
  SetProtoMethodNoSideEffect(isolate, t, "getFinished", GetFinished);
2090
581
  SetProtoMethodNoSideEffect(
2091
      isolate, t, "getPeerCertificate", GetPeerCertificate);
2092
581
  SetProtoMethodNoSideEffect(
2093
      isolate, t, "getPeerX509Certificate", GetPeerX509Certificate);
2094
581
  SetProtoMethodNoSideEffect(isolate, t, "getPeerFinished", GetPeerFinished);
2095
581
  SetProtoMethodNoSideEffect(isolate, t, "getProtocol", GetProtocol);
2096
581
  SetProtoMethodNoSideEffect(isolate, t, "getSession", GetSession);
2097
581
  SetProtoMethodNoSideEffect(isolate, t, "getSharedSigalgs", GetSharedSigalgs);
2098
581
  SetProtoMethodNoSideEffect(isolate, t, "getTLSTicket", GetTLSTicket);
2099
581
  SetProtoMethodNoSideEffect(isolate, t, "verifyError", VerifyError);
2100
2101
#ifdef SSL_set_max_send_fragment
2102
581
  SetProtoMethod(isolate, t, "setMaxSendFragment", SetMaxSendFragment);
2103
#endif  // SSL_set_max_send_fragment
2104
2105
#ifndef OPENSSL_NO_PSK
2106
581
  SetProtoMethod(isolate, t, "enablePskCallback", EnablePskCallback);
2107
581
  SetProtoMethod(isolate, t, "setPskIdentityHint", SetPskIdentityHint);
2108
#endif  // !OPENSSL_NO_PSK
2109
2110
581
  StreamBase::AddMethods(env, t);
2111
2112
581
  Local<Function> fn = t->GetFunction(env->context()).ToLocalChecked();
2113
2114
581
  env->set_tls_wrap_constructor_function(fn);
2115
2116
581
  target->Set(env->context(), tlsWrapString, fn).Check();
2117
581
}
2118
2119
5337
void TLSWrap::RegisterExternalReferences(ExternalReferenceRegistry* registry) {
2120
5337
  registry->Register(TLSWrap::Wrap);
2121
5337
  registry->Register(GetWriteQueueSize);
2122
2123
5337
  registry->Register(CertCbDone);
2124
5337
  registry->Register(DestroySSL);
2125
5337
  registry->Register(EnableCertCb);
2126
5337
  registry->Register(EndParser);
2127
5337
  registry->Register(EnableKeylogCallback);
2128
5337
  registry->Register(EnableSessionCallbacks);
2129
5337
  registry->Register(EnableTrace);
2130
5337
  registry->Register(GetServername);
2131
5337
  registry->Register(LoadSession);
2132
5337
  registry->Register(NewSessionDone);
2133
5337
  registry->Register(Receive);
2134
5337
  registry->Register(Renegotiate);
2135
5337
  registry->Register(RequestOCSP);
2136
5337
  registry->Register(SetALPNProtocols);
2137
5337
  registry->Register(SetOCSPResponse);
2138
5337
  registry->Register(SetServername);
2139
5337
  registry->Register(SetSession);
2140
5337
  registry->Register(SetVerifyMode);
2141
5337
  registry->Register(Start);
2142
5337
  registry->Register(ExportKeyingMaterial);
2143
5337
  registry->Register(IsSessionReused);
2144
5337
  registry->Register(GetALPNNegotiatedProto);
2145
5337
  registry->Register(GetCertificate);
2146
5337
  registry->Register(GetX509Certificate);
2147
5337
  registry->Register(GetCipher);
2148
5337
  registry->Register(GetEphemeralKeyInfo);
2149
5337
  registry->Register(GetFinished);
2150
5337
  registry->Register(GetPeerCertificate);
2151
5337
  registry->Register(GetPeerX509Certificate);
2152
5337
  registry->Register(GetPeerFinished);
2153
5337
  registry->Register(GetProtocol);
2154
5337
  registry->Register(GetSession);
2155
5337
  registry->Register(GetSharedSigalgs);
2156
5337
  registry->Register(GetTLSTicket);
2157
5337
  registry->Register(VerifyError);
2158
2159
#ifdef SSL_set_max_send_fragment
2160
5337
  registry->Register(SetMaxSendFragment);
2161
#endif  // SSL_set_max_send_fragment
2162
2163
#ifndef OPENSSL_NO_PSK
2164
5337
  registry->Register(EnablePskCallback);
2165
5337
  registry->Register(SetPskIdentityHint);
2166
#endif  // !OPENSSL_NO_PSK
2167
5337
}
2168
2169
}  // namespace crypto
2170
}  // namespace node
2171
2172
5409
NODE_MODULE_CONTEXT_AWARE_INTERNAL(tls_wrap, node::crypto::TLSWrap::Initialize)
2173
5337
NODE_MODULE_EXTERNAL_REFERENCE(
2174
    tls_wrap, node::crypto::TLSWrap::RegisterExternalReferences)