GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: crypto/crypto_tls.cc Lines: 1042 1133 92.0 %
Date: 2022-11-10 04:21:28 Branches: 439 672 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
1980
int NewSessionCallback(SSL* s, SSL_SESSION* sess) {
133
1980
  TLSWrap* w = static_cast<TLSWrap*>(SSL_get_app_data(s));
134
1980
  Environment* env = w->env();
135
3960
  HandleScope handle_scope(env->isolate());
136
1980
  Context::Scope context_scope(env->context());
137
138
1980
  if (!w->has_session_callbacks())
139
1679
    return 0;
140
141
  // Check if session is small enough to be stored
142
301
  int size = i2d_SSL_SESSION(sess, nullptr);
143
301
  if (UNLIKELY(size > SecureContext::kMaxSessionSize))
144
    return 0;
145
146
  // Serialize session
147
602
  Local<Object> session = Buffer::New(env, size).FromMaybe(Local<Object>());
148
301
  if (UNLIKELY(session.IsEmpty()))
149
    return 0;
150
151
  unsigned char* session_data =
152
301
      reinterpret_cast<unsigned char*>(Buffer::Data(session));
153
154
301
  CHECK_EQ(i2d_SSL_SESSION(sess, &session_data), size);
155
156
  unsigned int session_id_length;
157
  const unsigned char* session_id_data =
158
301
      SSL_SESSION_get_id(sess, &session_id_length);
159
160
301
  Local<Object> session_id = Buffer::Copy(
161
      env,
162
      reinterpret_cast<const char*>(session_id_data),
163
602
      session_id_length).FromMaybe(Local<Object>());
164
301
  if (UNLIKELY(session_id.IsEmpty()))
165
    return 0;
166
167
  Local<Value> argv[] = {
168
    session_id,
169
    session
170
301
  };
171
172
  // On servers, we pause the handshake until callback of 'newSession', which
173
  // calls NewSessionDoneCb(). On clients, there is no callback to wait for.
174
301
  if (w->is_server())
175
8
    w->set_awaiting_new_session(true);
176
177
301
  w->MakeCallback(env->onnewsession_string(), arraysize(argv), argv);
178
179
301
  return 0;
180
}
181
182
975
int SSLCertCallback(SSL* s, void* arg) {
183
975
  TLSWrap* w = static_cast<TLSWrap*>(SSL_get_app_data(s));
184
185

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

100
      info->Set(env->context(), env->ocsp_request_string(), ocsp).IsNothing()) {
212
    return 1;
213
  }
214
215
25
  Local<Value> argv[] = { info };
216
25
  w->MakeCallback(env->oncertcb_string(), arraysize(argv), argv);
217
218
25
  return w->is_cert_cb_running() ? -1 : 1;
219
}
220
221
37
int SelectALPNCallback(
222
    SSL* s,
223
    const unsigned char** out,
224
    unsigned char* outlen,
225
    const unsigned char* in,
226
    unsigned int inlen,
227
    void* arg) {
228
37
  TLSWrap* w = static_cast<TLSWrap*>(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
12399
void ConfigureSecureContext(SecureContext* sc) {
288
  // OCSP stapling
289
12399
  SSL_CTX_set_tlsext_status_cb(sc->ctx().get(), TLSExtStatusCallback);
290
12399
  SSL_CTX_set_tlsext_status_arg(sc->ctx().get(), nullptr);
291
12399
}
292
293
4014
inline bool Set(
294
    Environment* env,
295
    Local<Object> target,
296
    Local<String> name,
297
    const char* value,
298
    bool ignore_null = true) {
299
4014
  if (value == nullptr)
300
1354
    return ignore_null;
301
2660
  return !target->Set(
302
      env->context(),
303
      name,
304
5320
      OneByteString(env->isolate(), value))
305
2660
          .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
12399
TLSWrap::TLSWrap(Environment* env,
321
                 Local<Object> obj,
322
                 Kind kind,
323
                 StreamBase* stream,
324
12399
                 SecureContext* sc)
325
    : AsyncWrap(env, obj, AsyncWrap::PROVIDER_TLSWRAP),
326
      StreamBase(env),
327
      env_(env),
328
      kind_(kind),
329
12399
      sc_(sc) {
330
12399
  MakeWeak();
331
12399
  CHECK(sc_);
332
12399
  ssl_ = sc_->CreateSSL();
333
12399
  CHECK(ssl_);
334
335
12399
  sc_->SetGetSessionCallback(GetSessionCallback);
336
12399
  sc_->SetNewSessionCallback(NewSessionCallback);
337
338
12399
  StreamBase::AttachToObject(GetObject());
339
12399
  stream->PushStreamListener(this);
340
341
12399
  env_->isolate()->AdjustAmountOfExternalAllocatedMemory(kExternalSize);
342
343
12399
  InitSSL();
344
12399
  Debug(this, "Created new TLSWrap");
345
12399
}
346
347
74364
TLSWrap::~TLSWrap() {
348
24788
  Destroy();
349
49576
}
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
21031
void TLSWrap::InvokeQueued(int status, const char* error_str) {
366
21031
  Debug(this, "Invoking queued write callbacks (%d, %s)", status, error_str);
367
21031
  if (!write_callback_scheduled_)
368
4831
    return;
369
370
16200
  if (current_write_) {
371
5214
    BaseObjectPtr<AsyncWrap> current_write = std::move(current_write_);
372
2607
    current_write_.reset();
373
2607
    WriteWrap* w = WriteWrap::FromObject(current_write);
374
2607
    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
12399
void TLSWrap::InitSSL() {
384
  // Initialize SSL – OpenSSL takes ownership of these.
385
12399
  enc_in_ = NodeBIO::New(env()).release();
386
12399
  enc_out_ = NodeBIO::New(env()).release();
387
388
12399
  SSL_set_bio(ssl_.get(), enc_in_, enc_out_);
389
390
  // NOTE: This could be overridden in SetVerifyMode
391
12399
  SSL_set_verify(ssl_.get(), SSL_VERIFY_NONE, VerifyCallback);
392
393
#ifdef SSL_MODE_RELEASE_BUFFERS
394
12399
  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
12399
  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
12399
  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
12399
  SSL_set_info_callback(ssl_.get(), SSLInfoCallback);
416
417
12399
  if (is_server())
418
951
    sc_->SetSelectSNIContextCallback(SelectSNIContextCallback);
419
420
12399
  ConfigureSecureContext(sc_.get());
421
422
12399
  SSL_set_cert_cb(ssl_.get(), SSLCertCallback, this);
423
424
12399
  if (is_server()) {
425
951
    SSL_set_accept_state(ssl_.get());
426
11448
  } else if (is_client()) {
427
    // Enough space for server response (hello, cert)
428
11448
    NodeBIO::FromBIO(enc_in_)->set_initial(kInitialClientBufferLength);
429
11448
    SSL_set_connect_state(ssl_.get());
430
  } else {
431
    // Unexpected
432
    ABORT();
433
  }
434
12399
}
435
436
12399
void TLSWrap::Wrap(const FunctionCallbackInfo<Value>& args) {
437
12399
  Environment* env = Environment::GetCurrent(args);
438
439
12399
  CHECK_EQ(args.Length(), 3);
440
12399
  CHECK(args[0]->IsObject());
441
12399
  CHECK(args[1]->IsObject());
442
12399
  CHECK(args[2]->IsBoolean());
443
444
24798
  Local<Object> sc = args[1].As<Object>();
445

12399
  Kind kind = args[2]->IsTrue() ? Kind::kServer : Kind::kClient;
446
447
24798
  StreamBase* stream = StreamBase::FromObject(args[0].As<Object>());
448
12399
  CHECK_NOT_NULL(stream);
449
450
  Local<Object> obj;
451
12399
  if (!env->tls_wrap_constructor_function()
452
12399
           ->NewInstance(env->context())
453
12399
           .ToLocal(&obj)) {
454
    return;
455
  }
456
457
12399
  TLSWrap* res = new TLSWrap(env, obj, kind, stream, Unwrap<SecureContext>(sc));
458
459
24798
  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
1396
void TLSWrap::Start(const FunctionCallbackInfo<Value>& args) {
485
  TLSWrap* wrap;
486
1396
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
487
488
1396
  CHECK(!wrap->started_);
489
1396
  wrap->started_ = true;
490
491
  // Send ClientHello handshake
492
1396
  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
1396
  wrap->ClearOut();
497
1396
  wrap->EncOut();
498
}
499
500
40682
void TLSWrap::SSLInfoCallback(const SSL* ssl_, int where, int ret) {
501
40682
  if (!(where & (SSL_CB_HANDSHAKE_START | SSL_CB_HANDSHAKE_DONE)))
502
36341
    return;
503
504
  // SSL_renegotiate_pending() should take `const SSL*`, but it does not.
505
4341
  SSL* ssl = const_cast<SSL*>(ssl_);
506
4341
  TLSWrap* c = static_cast<TLSWrap*>(SSL_get_app_data(ssl_));
507
4341
  Environment* env = c->env();
508
8682
  HandleScope handle_scope(env->isolate());
509
4341
  Context::Scope context_scope(env->context());
510
4341
  Local<Object> object = c->object();
511
512
4341
  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
5060
    if (object->Get(env->context(), env->onhandshakestart_string())
519

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

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

3620
          .ToLocal(&callback) && callback->IsFunction()) {
537
3620
      c->MakeCallback(callback.As<Function>(), 0, nullptr);
538
    }
539
  }
540
}
541
542
19809
void TLSWrap::EncOut() {
543
19809
  Debug(this, "Trying to write encrypted output");
544
545
  // Ignore cycling data if ClientHello wasn't yet parsed
546
19809
  if (!hello_parser_.IsEnded()) {
547
1
    Debug(this, "Returning from EncOut(), hello_parser_ active");
548
12436
    return;
549
  }
550
551
  // Write in progress
552
19808
  if (write_size_ != 0) {
553
3592
    Debug(this, "Returning from EncOut(), write currently in progress");
554
3592
    return;
555
  }
556
557
  // Wait for `newSession` callback to be invoked
558
16216
  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

16209
  if (established_ && current_write_) {
565
5183
    Debug(this, "EncOut() write is scheduled");
566
5183
    write_callback_scheduled_ = true;
567
  }
568
569
16209
  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
16207
  if (BIO_pending(enc_out_) == 0) {
576
8658
    Debug(this, "No pending encrypted output");
577

8859
    if (!pending_cleartext_input_ ||
578
201
        pending_cleartext_input_->ByteLength() == 0) {
579
8457
      if (!in_dowrite_) {
580
8392
        Debug(this, "No pending cleartext input, not inside DoWrite()");
581
8392
        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
8658
    return;
599
  }
600
601
  char* data[kSimultaneousBufferCount];
602
  size_t size[arraysize(data)];
603
7549
  size_t count = arraysize(data);
604
7549
  write_size_ = NodeBIO::FromBIO(enc_out_)->PeekMultiple(data, size, &count);
605

7549
  CHECK(write_size_ != 0 && count != 0);
606
607
  uv_buf_t buf[arraysize(data)];
608
7549
  uv_buf_t* bufs = buf;
609
15231
  for (size_t i = 0; i < count; i++)
610
7682
    buf[i] = uv_buf_init(data[i], size[i]);
611
612
7549
  Debug(this, "Writing %zu buffers to the underlying stream", count);
613
7549
  StreamWriteResult res = underlying_stream()->Write(bufs, count);
614
7548
  if (res.err != 0) {
615
176
    InvokeQueued(res.err);
616
176
    return;
617
  }
618
619
7372
  if (!res.async) {
620
6814
    Debug(this, "Write finished synchronously");
621
13628
    HandleScope handle_scope(env()->isolate());
622
623
    // Simulate asynchronous finishing, TLS cannot handle this at the moment.
624
6814
    BaseObjectPtr<TLSWrap> strong_ref{this};
625
6814
    env()->SetImmediate([this, strong_ref](Environment* env) {
626
6814
      OnStreamAfterWrite(nullptr, 0);
627
6814
    });
628
  }
629
}
630
631
7471
void TLSWrap::OnStreamAfterWrite(WriteWrap* req_wrap, int status) {
632
7471
  Debug(this, "OnStreamAfterWrite(status = %d)", status);
633
7471
  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
7371
  if (ssl_ == nullptr) {
644
    Debug(this, "ssl_ == nullptr, marking as cancelled");
645
    status = UV_ECANCELED;
646
  }
647
648
  // Handle error
649
7371
  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
7368
  NodeBIO::FromBIO(enc_out_)->Read(nullptr, write_size_);
662
663
  // Ensure that the progress will be made and `InvokeQueued` will be called.
664
7368
  ClearIn();
665
666
  // Try writing more data
667
7368
  write_size_ = 0;
668
7368
  EncOut();
669
}
670
671
8733
int TLSWrap::GetSSLError(int status) const {
672
  // ssl_ might already be destroyed for reading EOF from a close notify alert.
673
8733
  return ssl_ != nullptr ? SSL_get_error(ssl_.get(), status) : 0;
674
}
675
676
8331
void TLSWrap::ClearOut() {
677
8331
  Debug(this, "Trying to read cleartext output");
678
  // Ignore cycling data if ClientHello wasn't yet parsed
679
8331
  if (!hello_parser_.IsEnded()) {
680
1
    Debug(this, "Returning from ClearOut(), hello_parser_ active");
681
7697
    return;
682
  }
683
684
  // No reads after EOF
685
8330
  if (eof_) {
686
    Debug(this, "Returning from ClearOut(), EOF reached");
687
    return;
688
  }
689
690
8330
  if (ssl_ == nullptr) {
691
1
    Debug(this, "Returning from ClearOut(), ssl_ == nullptr");
692
1
    return;
693
  }
694
695
8329
  MarkPopErrorOnReturn mark_pop_error_on_return;
696
697
  char out[kClearOutChunkSize];
698
  int read;
699
  for (;;) {
700
11558
    read = SSL_read(ssl_.get(), out, sizeof(out));
701
11558
    Debug(this, "Read %d bytes of cleartext output", read);
702
703
11558
    if (read <= 0)
704
8327
      break;
705
706
3231
    char* current = out;
707
8514
    while (read > 0) {
708
5285
      int avail = read;
709
710
5285
      uv_buf_t buf = EmitAlloc(avail);
711
5285
      if (static_cast<int>(buf.len) < avail)
712
2054
        avail = buf.len;
713
5285
      memcpy(buf.base, current, avail);
714
5285
      EmitRead(avail, buf);
715
716
      // Caveat emptor: OnRead() calls into JS land which can result in
717
      // the SSL context object being destroyed.  We have to carefully
718
      // check that ssl_ != nullptr afterwards.
719
5284
      if (ssl_ == nullptr) {
720
1
        Debug(this, "Returning from read loop, ssl_ == nullptr");
721
1
        return;
722
      }
723
724
5283
      read -= avail;
725
5283
      current += avail;
726
    }
727
3229
  }
728
729
8327
  int flags = SSL_get_shutdown(ssl_.get());
730

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

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

14194
  if (!pending_cleartext_input_ ||
812
400
      pending_cleartext_input_->ByteLength() == 0) {
813
13394
    Debug(this, "Returning from ClearIn(), no pending data");
814
13394
    return;
815
  }
816
817
400
  std::unique_ptr<BackingStore> bs = std::move(pending_cleartext_input_);
818
400
  MarkPopErrorOnReturn mark_pop_error_on_return;
819
820
400
  NodeBIO::FromBIO(enc_out_)->set_allocate_tls_hint(bs->ByteLength());
821
400
  int written = SSL_write(ssl_.get(), bs->Data(), bs->ByteLength());
822
400
  Debug(this, "Writing %zu bytes, written = %d", bs->ByteLength(), written);
823

400
  CHECK(written == -1 || written == static_cast<int>(bs->ByteLength()));
824
825
  // All written
826
400
  if (written != -1) {
827
179
    Debug(this, "Successfully wrote all data to SSL");
828
179
    return;
829
  }
830
831
  // Error or partial write
832
221
  int err = GetSSLError(written);
833

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

8033
      underlying_stream() != nullptr &&
870
8032
      underlying_stream()->IsAlive();
871
}
872
873
3
bool TLSWrap::IsClosing() {
874
3
  return underlying_stream()->IsClosing();
875
}
876
877
2467
int TLSWrap::ReadStart() {
878
2467
  Debug(this, "ReadStart()");
879

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

2509
  CHECK(written == -1 || written == static_cast<int>(length));
1004
2509
  Debug(this, "Writing %zu bytes, written = %d", length, written);
1005
1006
2509
  if (written == -1) {
1007
    // If we stopped writing because of an error, it's fatal, discard the data.
1008
185
    int err = GetSSLError(written);
1009

185
    if (err == SSL_ERROR_SSL || err == SSL_ERROR_SYSCALL) {
1010
      // TODO(@jasnell): What are we doing with the error?
1011
2
      Debug(this, "Got SSL error (%d), returning UV_EPROTO", err);
1012
2
      current_write_.reset();
1013
2
      return UV_EPROTO;
1014
    }
1015
1016
183
    Debug(this, "Saving data for later write");
1017
    // Otherwise, save unwritten data so it can be written later by ClearIn().
1018

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

20
    CHECK_IMPLIES(data == nullptr, avail == 0);
1078
20
    Debug(this, "Passing %zu bytes to the hello parser", avail);
1079
20
    return hello_parser_.Parse(data, avail);
1080
  }
1081
1082
  // Cycle OpenSSL's state
1083
6379
  Cycle();
1084
}
1085
1086
1436
ShutdownWrap* TLSWrap::CreateShutdownWrap(Local<Object> req_wrap_object) {
1087
1436
  return underlying_stream()->CreateShutdownWrap(req_wrap_object);
1088
}
1089
1090
1436
int TLSWrap::DoShutdown(ShutdownWrap* req_wrap) {
1091
1436
  Debug(this, "DoShutdown()");
1092
2872
  MarkPopErrorOnReturn mark_pop_error_on_return;
1093
1094

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

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

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

20
  if (UNLIKELY(ret.IsEmpty()) || !ret->IsObject())
1416
1
    return 0;
1417
1418
9
  Local<Object> obj = ret.As<Object>();
1419
1420
18
  Local<Value> psk_val = obj->Get(env->context(), env->psk_string())
1421
9
      .FromMaybe(Local<Value>());
1422

18
  if (UNLIKELY(psk_val.IsEmpty()) || !psk_val->IsArrayBufferView())
1423
    return 0;
1424
1425
9
  ArrayBufferViewContents<char> psk_buf(psk_val);
1426
9
  if (psk_buf.length() > max_psk_len)
1427
    return 0;
1428
1429
18
  Local<Value> identity_val = obj->Get(env->context(), env->identity_string())
1430
9
      .FromMaybe(Local<Value>());
1431

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

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


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

502
  if (args.Length() < 1 || !Buffer::HasInstance(args[0]))
1521
    return env->ThrowTypeError("Must give a Buffer as first argument");
1522
1523
502
  ArrayBufferViewContents<uint8_t> protos(args[0].As<ArrayBufferView>());
1524
251
  SSL* ssl = w->ssl_.get();
1525
251
  if (w->is_client()) {
1526
41
    CHECK_EQ(0, SSL_set_alpn_protos(ssl, protos.data(), protos.length()));
1527
  } else {
1528
630
    w->alpn_protos_ = std::vector<unsigned char>(
1529
420
        protos.data(), protos.data() + protos.length());
1530
210
    SSL_CTX_set_alpn_select_cb(SSL_get_SSL_CTX(ssl), SelectALPNCallback, w);
1531
  }
1532
}
1533
1534
498
void TLSWrap::GetPeerCertificate(const FunctionCallbackInfo<Value>& args) {
1535
  TLSWrap* w;
1536
498
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1537
498
  Environment* env = w->env();
1538
1539

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

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

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

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