GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/tls_wrap.cc Lines: 585 634 92.3 %
Date: 2020-02-19 22:14:06 Branches: 259 372 69.6 %

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 "tls_wrap.h"
23
#include "async_wrap-inl.h"
24
#include "debug_utils-inl.h"
25
#include "memory_tracker-inl.h"
26
#include "node_buffer.h"  // Buffer
27
#include "node_crypto.h"  // SecureContext
28
#include "node_crypto_bio.h"  // NodeBIO
29
// ClientHelloParser
30
#include "node_crypto_clienthello-inl.h"
31
#include "node_errors.h"
32
#include "stream_base-inl.h"
33
#include "util-inl.h"
34
35
namespace node {
36
37
using crypto::SecureContext;
38
using crypto::SSLWrap;
39
using v8::Context;
40
using v8::DontDelete;
41
using v8::EscapableHandleScope;
42
using v8::Exception;
43
using v8::Function;
44
using v8::FunctionCallbackInfo;
45
using v8::FunctionTemplate;
46
using v8::Integer;
47
using v8::Isolate;
48
using v8::Local;
49
using v8::Maybe;
50
using v8::MaybeLocal;
51
using v8::Object;
52
using v8::ReadOnly;
53
using v8::Signature;
54
using v8::String;
55
using v8::Value;
56
57
12166
TLSWrap::TLSWrap(Environment* env,
58
                 Local<Object> obj,
59
                 Kind kind,
60
                 StreamBase* stream,
61
12166
                 SecureContext* sc)
62
    : AsyncWrap(env, obj, AsyncWrap::PROVIDER_TLSWRAP),
63
      SSLWrap<TLSWrap>(env, sc, kind),
64
      StreamBase(env),
65
12166
      sc_(sc) {
66
12166
  MakeWeak();
67
12166
  StreamBase::AttachToObject(GetObject());
68
69
  // sc comes from an Unwrap. Make sure it was assigned.
70
12166
  CHECK_NOT_NULL(sc);
71
72
  // We've our own session callbacks
73
12166
  SSL_CTX_sess_set_get_cb(sc_->ctx_.get(),
74
12166
                          SSLWrap<TLSWrap>::GetSessionCallback);
75
12166
  SSL_CTX_sess_set_new_cb(sc_->ctx_.get(),
76
12166
                          SSLWrap<TLSWrap>::NewSessionCallback);
77
78
12166
  stream->PushStreamListener(this);
79
80
12166
  InitSSL();
81
12166
  Debug(this, "Created new TLSWrap");
82
12166
}
83
84
85
36417
TLSWrap::~TLSWrap() {
86
12139
  Debug(this, "~TLSWrap()");
87
12139
  sc_ = nullptr;
88
24278
}
89
90
91
20399
bool TLSWrap::InvokeQueued(int status, const char* error_str) {
92
20399
  Debug(this, "InvokeQueued(%d, %s)", status, error_str);
93
20399
  if (!write_callback_scheduled_)
94
4049
    return false;
95
96
16350
  if (current_write_ != nullptr) {
97
2516
    WriteWrap* w = current_write_;
98
2516
    current_write_ = nullptr;
99
2516
    w->Done(status, error_str);
100
  }
101
102
16350
  return true;
103
}
104
105
106
8
void TLSWrap::NewSessionDoneCb() {
107
8
  Debug(this, "NewSessionDoneCb()");
108
8
  Cycle();
109
8
}
110
111
112
12166
void TLSWrap::InitSSL() {
113
  // Initialize SSL – OpenSSL takes ownership of these.
114
12166
  enc_in_ = crypto::NodeBIO::New(env()).release();
115
12166
  enc_out_ = crypto::NodeBIO::New(env()).release();
116
117
12166
  SSL_set_bio(ssl_.get(), enc_in_, enc_out_);
118
119
  // NOTE: This could be overridden in SetVerifyMode
120
12166
  SSL_set_verify(ssl_.get(), SSL_VERIFY_NONE, crypto::VerifyCallback);
121
122
#ifdef SSL_MODE_RELEASE_BUFFERS
123
12166
  SSL_set_mode(ssl_.get(), SSL_MODE_RELEASE_BUFFERS);
124
#endif  // SSL_MODE_RELEASE_BUFFERS
125
126
  // This is default in 1.1.1, but set it anyway, Cycle() doesn't currently
127
  // re-call ClearIn() if SSL_read() returns SSL_ERROR_WANT_READ, so data can be
128
  // left sitting in the incoming enc_in_ and never get processed.
129
  // - https://wiki.openssl.org/index.php/TLS1.3#Non-application_data_records
130
12166
  SSL_set_mode(ssl_.get(), SSL_MODE_AUTO_RETRY);
131
132
12166
  SSL_set_app_data(ssl_.get(), this);
133
  // Using InfoCallback isn't how we are supposed to check handshake progress:
134
  //   https://github.com/openssl/openssl/issues/7199#issuecomment-420915993
135
  //
136
  // Note on when this gets called on various openssl versions:
137
  //   https://github.com/openssl/openssl/issues/7199#issuecomment-420670544
138
12166
  SSL_set_info_callback(ssl_.get(), SSLInfoCallback);
139
140
12166
  if (is_server()) {
141
832
    SSL_CTX_set_tlsext_servername_callback(sc_->ctx_.get(),
142
832
                                           SelectSNIContextCallback);
143
  }
144
145
12166
  ConfigureSecureContext(sc_);
146
147
12166
  SSL_set_cert_cb(ssl_.get(), SSLWrap<TLSWrap>::SSLCertCallback, this);
148
149
12166
  if (is_server()) {
150
832
    SSL_set_accept_state(ssl_.get());
151
11334
  } else if (is_client()) {
152
    // Enough space for server response (hello, cert)
153
11334
    crypto::NodeBIO::FromBIO(enc_in_)->set_initial(kInitialClientBufferLength);
154
11334
    SSL_set_connect_state(ssl_.get());
155
  } else {
156
    // Unexpected
157
    ABORT();
158
  }
159
12166
}
160
161
162
12166
void TLSWrap::Wrap(const FunctionCallbackInfo<Value>& args) {
163
12166
  Environment* env = Environment::GetCurrent(args);
164
165
12166
  CHECK_EQ(args.Length(), 3);
166
24332
  CHECK(args[0]->IsObject());
167
24332
  CHECK(args[1]->IsObject());
168
24332
  CHECK(args[2]->IsBoolean());
169
170
24332
  Local<Object> sc = args[1].As<Object>();
171
36498
  Kind kind = args[2]->IsTrue() ? SSLWrap<TLSWrap>::kServer :
172
12166
                                  SSLWrap<TLSWrap>::kClient;
173
174
24332
  StreamBase* stream = StreamBase::FromObject(args[0].As<Object>());
175
12166
  CHECK_NOT_NULL(stream);
176
177
  Local<Object> obj;
178
36498
  if (!env->tls_wrap_constructor_function()
179
36498
           ->NewInstance(env->context())
180
12166
           .ToLocal(&obj)) {
181
    return;
182
  }
183
184
12166
  TLSWrap* res = new TLSWrap(env, obj, kind, stream, Unwrap<SecureContext>(sc));
185
186
36498
  args.GetReturnValue().Set(res->object());
187
}
188
189
190
3
void TLSWrap::Receive(const FunctionCallbackInfo<Value>& args) {
191
  TLSWrap* wrap;
192
3
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
193
194
3
  ArrayBufferViewContents<char> buffer(args[0]);
195
3
  const char* data = buffer.data();
196
3
  size_t len = buffer.length();
197
3
  Debug(wrap, "Receiving %zu bytes injected from JS", len);
198
199
  // Copy given buffer entirely or partiall if handle becomes closed
200


9
  while (len > 0 && wrap->IsAlive() && !wrap->IsClosing()) {
201
3
    uv_buf_t buf = wrap->OnStreamAlloc(len);
202
3
    size_t copy = buf.len > len ? len : buf.len;
203
3
    memcpy(buf.base, data, copy);
204
3
    buf.len = copy;
205
3
    wrap->OnStreamRead(copy, buf);
206
207
3
    data += copy;
208
3
    len -= copy;
209
  }
210
}
211
212
213
1296
void TLSWrap::Start(const FunctionCallbackInfo<Value>& args) {
214
  TLSWrap* wrap;
215
1296
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
216
217
1296
  CHECK(!wrap->started_);
218
219
1296
  wrap->started_ = true;
220
221
  // Send ClientHello handshake
222
1296
  CHECK(wrap->is_client());
223
  // Seems odd to read when when we want to send, but SSL_read() triggers a
224
  // handshake if a session isn't established, and handshake will cause
225
  // encrypted data to become available for output.
226
1296
  wrap->ClearOut();
227
1296
  wrap->EncOut();
228
}
229
230
231
35522
void TLSWrap::SSLInfoCallback(const SSL* ssl_, int where, int ret) {
232
35522
  if (!(where & (SSL_CB_HANDSHAKE_START | SSL_CB_HANDSHAKE_DONE)))
233
31597
    return;
234
235
  // SSL_renegotiate_pending() should take `const SSL*`, but it does not.
236
3925
  SSL* ssl = const_cast<SSL*>(ssl_);
237
3925
  TLSWrap* c = static_cast<TLSWrap*>(SSL_get_app_data(ssl_));
238
3925
  Environment* env = c->env();
239
7850
  HandleScope handle_scope(env->isolate());
240
3925
  Context::Scope context_scope(env->context());
241
3925
  Local<Object> object = c->object();
242
243
3925
  if (where & SSL_CB_HANDSHAKE_START) {
244
    Debug(c, "SSLInfoCallback(SSL_CB_HANDSHAKE_START);");
245
    // Start is tracked to limit number and frequency of renegotiation attempts,
246
    // since excessive renegotiation may be an attack.
247
    Local<Value> callback;
248
249
9252
    if (object->Get(env->context(), env->onhandshakestart_string())
250

4626
          .ToLocal(&callback) && callback->IsFunction()) {
251
2313
      Local<Value> argv[] = { env->GetNow() };
252
4626
      c->MakeCallback(callback.As<Function>(), arraysize(argv), argv);
253
    }
254
  }
255
256
  // SSL_CB_HANDSHAKE_START and SSL_CB_HANDSHAKE_DONE are called
257
  // sending HelloRequest in OpenSSL-1.1.1.
258
  // We need to check whether this is in a renegotiation state or not.
259

3925
  if (where & SSL_CB_HANDSHAKE_DONE && !SSL_renegotiate_pending(ssl)) {
260
    Debug(c, "SSLInfoCallback(SSL_CB_HANDSHAKE_DONE);");
261
1611
    CHECK(!SSL_renegotiate_pending(ssl));
262
    Local<Value> callback;
263
264
1611
    c->established_ = true;
265
266
6444
    if (object->Get(env->context(), env->onhandshakedone_string())
267

3222
          .ToLocal(&callback) && callback->IsFunction()) {
268
1611
      c->MakeCallback(callback.As<Function>(), 0, nullptr);
269
    }
270
  }
271
}
272
273
274
18250
void TLSWrap::EncOut() {
275
18250
  Debug(this, "Trying to write encrypted output");
276
277
  // Ignore cycling data if ClientHello wasn't yet parsed
278
18250
  if (!hello_parser_.IsEnded()) {
279
    Debug(this, "Returning from EncOut(), hello_parser_ active");
280
11538
    return;
281
  }
282
283
  // Write in progress
284
18250
  if (write_size_ != 0) {
285
3049
    Debug(this, "Returning from EncOut(), write currently in progress");
286
3049
    return;
287
  }
288
289
  // Wait for `newSession` callback to be invoked
290
15201
  if (is_awaiting_new_session()) {
291
7
    Debug(this, "Returning from EncOut(), awaiting new session");
292
7
    return;
293
  }
294
295
  // Split-off queue
296

15194
  if (established_ && current_write_ != nullptr) {
297
5234
    Debug(this, "EncOut() setting write_callback_scheduled_");
298
5234
    write_callback_scheduled_ = true;
299
  }
300
301
15194
  if (ssl_ == nullptr) {
302
1
    Debug(this, "Returning from EncOut(), ssl_ == nullptr");
303
1
    return;
304
  }
305
306
  // No encrypted output ready to write to the underlying stream.
307
15193
  if (BIO_pending(enc_out_) == 0) {
308
8355
    Debug(this, "No pending encrypted output");
309
8355
    if (pending_cleartext_input_.size() == 0) {
310
8168
      if (!in_dowrite_) {
311
8113
        Debug(this, "No pending cleartext input, not inside DoWrite()");
312
8113
        InvokeQueued(0);
313
      } else {
314
55
        Debug(this, "No pending cleartext input, inside DoWrite()");
315
        // TODO(@sam-github, @addaleax) If in_dowrite_ is true, appdata was
316
        // passed to SSL_write().  If we are here, the data was not encrypted to
317
        // enc_out_ yet.  Calling Done() "works", but since the write is not
318
        // flushed, its too soon.  Just returning and letting the next EncOut()
319
        // call Done() passes the test suite, but without more careful analysis,
320
        // its not clear if it is always correct. Not calling Done() could block
321
        // data flow, so for now continue to call Done(), just do it in the next
322
        // tick.
323
110
        BaseObjectPtr<TLSWrap> strong_ref{this};
324
330
        env()->SetImmediate([this, strong_ref](Environment* env) {
325
55
          InvokeQueued(0);
326
110
        });
327
      }
328
    }
329
8355
    return;
330
  }
331
332
  char* data[kSimultaneousBufferCount];
333
  size_t size[arraysize(data)];
334
6838
  size_t count = arraysize(data);
335
6838
  write_size_ = crypto::NodeBIO::FromBIO(enc_out_)->PeekMultiple(data,
336
                                                                 size,
337
                                                                 &count);
338

6838
  CHECK(write_size_ != 0 && count != 0);
339
340
  uv_buf_t buf[arraysize(data)];
341
6838
  uv_buf_t* bufs = buf;
342
16865
  for (size_t i = 0; i < count; i++)
343
10027
    buf[i] = uv_buf_init(data[i], size[i]);
344
345
6838
  Debug(this, "Writing %zu buffers to the underlying stream", count);
346
6838
  StreamWriteResult res = underlying_stream()->Write(bufs, count);
347
6837
  if (res.err != 0) {
348
126
    InvokeQueued(res.err);
349
126
    return;
350
  }
351
352
6711
  if (!res.async) {
353
6146
    Debug(this, "Write finished synchronously");
354
12292
    HandleScope handle_scope(env()->isolate());
355
356
    // Simulate asynchronous finishing, TLS cannot handle this at the moment.
357
12292
    BaseObjectPtr<TLSWrap> strong_ref{this};
358
43022
    env()->SetImmediate([this, strong_ref](Environment* env) {
359
12292
      OnStreamAfterWrite(nullptr, 0);
360
12292
    });
361
  }
362
}
363
364
365
6801
void TLSWrap::OnStreamAfterWrite(WriteWrap* req_wrap, int status) {
366
6801
  Debug(this, "OnStreamAfterWrite(status = %d)", status);
367
6801
  if (current_empty_write_ != nullptr) {
368
91
    Debug(this, "Had empty write");
369
91
    WriteWrap* finishing = current_empty_write_;
370
91
    current_empty_write_ = nullptr;
371
91
    finishing->Done(status);
372
91
    return;
373
  }
374
375
6710
  if (ssl_ == nullptr) {
376
    Debug(this, "ssl_ == nullptr, marking as cancelled");
377
    status = UV_ECANCELED;
378
  }
379
380
  // Handle error
381
6710
  if (status) {
382
2
    if (shutdown_) {
383
      Debug(this, "Ignoring error after shutdown");
384
      return;
385
    }
386
387
    // Notify about error
388
2
    InvokeQueued(status);
389
2
    return;
390
  }
391
392
  // Commit
393
6708
  crypto::NodeBIO::FromBIO(enc_out_)->Read(nullptr, write_size_);
394
395
  // Ensure that the progress will be made and `InvokeQueued` will be called.
396
6708
  ClearIn();
397
398
  // Try writing more data
399
6708
  write_size_ = 0;
400
6708
  EncOut();
401
}
402
403
404
8719
Local<Value> TLSWrap::GetSSLError(int status, int* err, std::string* msg) {
405
8719
  EscapableHandleScope scope(env()->isolate());
406
407
  // ssl_ is already destroyed in reading EOF by close notify alert.
408
8719
  if (ssl_ == nullptr)
409
    return Local<Value>();
410
411
8719
  *err = SSL_get_error(ssl_.get(), status);
412

8719
  switch (*err) {
413
    case SSL_ERROR_NONE:
414
    case SSL_ERROR_WANT_READ:
415
    case SSL_ERROR_WANT_WRITE:
416
    case SSL_ERROR_WANT_X509_LOOKUP:
417
7368
      return Local<Value>();
418
419
    case SSL_ERROR_ZERO_RETURN:
420
1434
      return scope.Escape(env()->zero_return_string());
421
422
    case SSL_ERROR_SSL:
423
    case SSL_ERROR_SYSCALL:
424
      {
425
634
        unsigned long ssl_err = ERR_peek_error();  // NOLINT(runtime/int)
426
634
        BIO* bio = BIO_new(BIO_s_mem());
427
634
        ERR_print_errors(bio);
428
429
        BUF_MEM* mem;
430
634
        BIO_get_mem_ptr(bio, &mem);
431
432
634
        Isolate* isolate = env()->isolate();
433
634
        Local<Context> context = isolate->GetCurrentContext();
434
435
        Local<String> message =
436
634
            OneByteString(isolate, mem->data, mem->length);
437
634
        Local<Value> exception = Exception::Error(message);
438
1268
        Local<Object> obj = exception->ToObject(context).ToLocalChecked();
439
440
634
        const char* ls = ERR_lib_error_string(ssl_err);
441
634
        const char* fs = ERR_func_error_string(ssl_err);
442
634
        const char* rs = ERR_reason_error_string(ssl_err);
443
444
634
        if (ls != nullptr)
445
1260
          obj->Set(context, env()->library_string(),
446
2520
                   OneByteString(isolate, ls)).Check();
447
634
        if (fs != nullptr)
448
1260
          obj->Set(context, env()->function_string(),
449
2520
                   OneByteString(isolate, fs)).Check();
450
634
        if (rs != nullptr) {
451
1260
          obj->Set(context, env()->reason_string(),
452
2520
                   OneByteString(isolate, rs)).Check();
453
454
          // SSL has no API to recover the error name from the number, so we
455
          // transform reason strings like "this error" to "ERR_SSL_THIS_ERROR",
456
          // which ends up being close to the original error macro name.
457
1260
          std::string code(rs);
458
459
13612
          for (auto& c : code) {
460
12982
            if (c == ' ')
461
1275
              c = '_';
462
            else
463
11707
              c = ToUpper(c);
464
          }
465
1260
          obj->Set(context, env()->code_string(),
466
2520
                   OneByteString(isolate, ("ERR_SSL_" + code).c_str()))
467
                     .Check();
468
        }
469
470
634
        if (msg != nullptr)
471
4
          msg->assign(mem->data, mem->data + mem->length);
472
473
634
        BIO_free_all(bio);
474
475
        return scope.Escape(exception);
476
      }
477
478
    default:
479
      UNREACHABLE();
480
  }
481
  UNREACHABLE();
482
}
483
484
485
8361
void TLSWrap::ClearOut() {
486
8361
  Debug(this, "Trying to read cleartext output");
487
  // Ignore cycling data if ClientHello wasn't yet parsed
488
8361
  if (!hello_parser_.IsEnded()) {
489
1
    Debug(this, "Returning from ClearOut(), hello_parser_ active");
490
737
    return;
491
  }
492
493
  // No reads after EOF
494
8360
  if (eof_) {
495
17
    Debug(this, "Returning from ClearOut(), EOF reached");
496
17
    return;
497
  }
498
499
8343
  if (ssl_ == nullptr) {
500
    Debug(this, "Returning from ClearOut(), ssl_ == nullptr");
501
    return;
502
  }
503
504
15967
  crypto::MarkPopErrorOnReturn mark_pop_error_on_return;
505
506
  char out[kClearOutChunkSize];
507
  int read;
508
  for (;;) {
509
13387
    read = SSL_read(ssl_.get(), out, sizeof(out));
510
13387
    Debug(this, "Read %d bytes of cleartext output", read);
511
512
13387
    if (read <= 0)
513
8341
      break;
514
515
5046
    char* current = out;
516
15138
    while (read > 0) {
517
5048
      int avail = read;
518
519
5048
      uv_buf_t buf = EmitAlloc(avail);
520
5048
      if (static_cast<int>(buf.len) < avail)
521
2
        avail = buf.len;
522
5048
      memcpy(buf.base, current, avail);
523
5048
      EmitRead(avail, buf);
524
525
      // Caveat emptor: OnRead() calls into JS land which can result in
526
      // the SSL context object being destroyed.  We have to carefully
527
      // check that ssl_ != nullptr afterwards.
528
5047
      if (ssl_ == nullptr) {
529
1
        Debug(this, "Returning from read loop, ssl_ == nullptr");
530
1
        return;
531
      }
532
533
5046
      read -= avail;
534
5046
      current += avail;
535
    }
536
5044
  }
537
538
8341
  int flags = SSL_get_shutdown(ssl_.get());
539

8341
  if (!eof_ && flags & SSL_RECEIVED_SHUTDOWN) {
540
772
    eof_ = true;
541
772
    EmitRead(UV_EOF);
542
  }
543
544
  // We need to check whether an error occurred or the connection was
545
  // shutdown cleanly (SSL_ERROR_ZERO_RETURN) even when read == 0.
546
  // See node#1642 and SSL_read(3SSL) for details.
547
8341
  if (read <= 0) {
548
15965
    HandleScope handle_scope(env()->isolate());
549
    int err;
550
8341
    Local<Value> arg = GetSSLError(read, &err, nullptr);
551
552
    // Ignore ZERO_RETURN after EOF, it is basically not a error
553

8341
    if (err == SSL_ERROR_ZERO_RETURN && eof_)
554
717
      return;
555
556
7624
    if (!arg.IsEmpty()) {
557
630
      Debug(this, "Got SSL error (%d), calling onerror", err);
558
      // When TLS Alert are stored in wbio,
559
      // it should be flushed to socket before destroyed.
560
630
      if (BIO_pending(enc_out_) != 0)
561
571
        EncOut();
562
563
630
      MakeCallback(env()->onerror_string(), 1, &arg);
564
    }
565
  }
566
}
567
568
569
13043
void TLSWrap::ClearIn() {
570
13043
  Debug(this, "Trying to write cleartext input");
571
  // Ignore cycling data if ClientHello wasn't yet parsed
572
13043
  if (!hello_parser_.IsEnded()) {
573
    Debug(this, "Returning from ClearIn(), hello_parser_ active");
574
12837
    return;
575
  }
576
577
13043
  if (ssl_ == nullptr) {
578
    Debug(this, "Returning from ClearIn(), ssl_ == nullptr");
579
    return;
580
  }
581
582
13043
  if (pending_cleartext_input_.size() == 0) {
583
12670
    Debug(this, "Returning from ClearIn(), no pending data");
584
12670
    return;
585
  }
586
587
579
  AllocatedBuffer data = std::move(pending_cleartext_input_);
588
579
  crypto::MarkPopErrorOnReturn mark_pop_error_on_return;
589
590
373
  int written = SSL_write(ssl_.get(), data.data(), data.size());
591
746
  Debug(this, "Writing %zu bytes, written = %d", data.size(), written);
592

373
  CHECK(written == -1 || written == static_cast<int>(data.size()));
593
594
  // All written
595
373
  if (written != -1) {
596
167
    Debug(this, "Successfully wrote all data to SSL");
597
167
    return;
598
  }
599
600
  // Error or partial write
601
412
  HandleScope handle_scope(env()->isolate());
602
206
  Context::Scope context_scope(env()->context());
603
604
  int err;
605
412
  std::string error_str;
606
206
  Local<Value> arg = GetSSLError(written, &err, &error_str);
607
206
  if (!arg.IsEmpty()) {
608
2
    Debug(this, "Got SSL error (%d)", err);
609
2
    write_callback_scheduled_ = true;
610
    // TODO(@sam-github) Should forward an error object with
611
    // .code/.function/.etc, if possible.
612
2
    InvokeQueued(UV_EPROTO, error_str.c_str());
613
  } else {
614
204
    Debug(this, "Pushing data back");
615
    // Push back the not-yet-written data. This can be skipped in the error
616
    // case because no further writes would succeed anyway.
617
204
    pending_cleartext_input_ = std::move(data);
618
  }
619
}
620
621
622
std::string TLSWrap::diagnostic_name() const {
623
  std::string name = "TLSWrap ";
624
  if (is_server())
625
    name += "server (";
626
  else
627
    name += "client (";
628
  name += std::to_string(static_cast<int64_t>(get_async_id())) + ")";
629
  return name;
630
}
631
632
633
24195
AsyncWrap* TLSWrap::GetAsyncWrap() {
634
24195
  return static_cast<AsyncWrap*>(this);
635
}
636
637
638
1164
bool TLSWrap::IsIPCPipe() {
639
1164
  return underlying_stream()->IsIPCPipe();
640
}
641
642
643
2
int TLSWrap::GetFD() {
644
2
  return underlying_stream()->GetFD();
645
}
646
647
648
3281
bool TLSWrap::IsAlive() {
649
6562
  return ssl_ != nullptr &&
650

6561
      stream_ != nullptr &&
651
6561
      underlying_stream()->IsAlive();
652
}
653
654
655
3
bool TLSWrap::IsClosing() {
656
3
  return underlying_stream()->IsClosing();
657
}
658
659
660
661
2176
int TLSWrap::ReadStart() {
662
2176
  Debug(this, "ReadStart()");
663
2176
  if (stream_ != nullptr)
664
2176
    return stream_->ReadStart();
665
  return 0;
666
}
667
668
669
1478
int TLSWrap::ReadStop() {
670
1478
  Debug(this, "ReadStop()");
671
1478
  if (stream_ != nullptr)
672
1469
    return stream_->ReadStop();
673
9
  return 0;
674
}
675
676
677
4763
const char* TLSWrap::Error() const {
678
4763
  return error_.empty() ? nullptr : error_.c_str();
679
}
680
681
682
5
void TLSWrap::ClearError() {
683
5
  error_.clear();
684
5
}
685
686
687
// Called by StreamBase::Write() to request async write of clear text into SSL.
688
// TODO(@sam-github) Should there be a TLSWrap::DoTryWrite()?
689
2612
int TLSWrap::DoWrite(WriteWrap* w,
690
                     uv_buf_t* bufs,
691
                     size_t count,
692
                     uv_stream_t* send_handle) {
693
2612
  CHECK_NULL(send_handle);
694
2612
  Debug(this, "DoWrite()");
695
696
2612
  if (ssl_ == nullptr) {
697
2
    ClearError();
698
2
    error_ = "Write after DestroySSL";
699
2
    return UV_EPROTO;
700
  }
701
702
2610
  size_t length = 0;
703
  size_t i;
704
10884
  for (i = 0; i < count; i++)
705
8274
    length += bufs[i].len;
706
707
  // We want to trigger a Write() on the underlying stream to drive the stream
708
  // system, but don't want to encrypt empty buffers into a TLS frame, so see
709
  // if we can find something to Write().
710
  // First, call ClearOut(). It does an SSL_read(), which might cause handshake
711
  // or other internal messages to be encrypted. If it does, write them later
712
  // with EncOut().
713
  // If there is still no encrypted output, call Write(bufs) on the underlying
714
  // stream. Since the bufs are empty, it won't actually write non-TLS data
715
  // onto the socket, we just want the side-effects. After, make sure the
716
  // WriteWrap was accepted by the stream, or that we call Done() on it.
717
2610
  if (length == 0) {
718
183
    Debug(this, "Empty write");
719
183
    ClearOut();
720
183
    if (BIO_pending(enc_out_) == 0) {
721
91
      Debug(this, "No pending encrypted output, writing to underlying stream");
722
91
      CHECK_NULL(current_empty_write_);
723
91
      current_empty_write_ = w;
724
      StreamWriteResult res =
725
91
          underlying_stream()->Write(bufs, count, send_handle);
726
91
      if (!res.async) {
727
182
        BaseObjectPtr<TLSWrap> strong_ref{this};
728
728
        env()->SetImmediate([this, strong_ref](Environment* env) {
729
273
          OnStreamAfterWrite(current_empty_write_, 0);
730
182
        });
731
      }
732
91
      return 0;
733
    }
734
  }
735
736
  // Store the current write wrap
737
2519
  CHECK_NULL(current_write_);
738
2519
  current_write_ = w;
739
740
  // Write encrypted data to underlying stream and call Done().
741
2519
  if (length == 0) {
742
92
    EncOut();
743
92
    return 0;
744
  }
745
746
4854
  AllocatedBuffer data;
747
4854
  crypto::MarkPopErrorOnReturn mark_pop_error_on_return;
748
749
2427
  int written = 0;
750
2427
  if (count != 1) {
751
1402
    data = env()->AllocateManaged(length);
752
1402
    size_t offset = 0;
753
8423
    for (i = 0; i < count; i++) {
754
7021
      memcpy(data.data() + offset, bufs[i].base, bufs[i].len);
755
7021
      offset += bufs[i].len;
756
    }
757
1402
    written = SSL_write(ssl_.get(), data.data(), length);
758
  } else {
759
    // Only one buffer: try to write directly, only store if it fails
760
1025
    written = SSL_write(ssl_.get(), bufs[0].base, bufs[0].len);
761
1025
    if (written == -1) {
762
169
      data = env()->AllocateManaged(length);
763
169
      memcpy(data.data(), bufs[0].base, bufs[0].len);
764
    }
765
  }
766
767

2427
  CHECK(written == -1 || written == static_cast<int>(length));
768
2427
  Debug(this, "Writing %zu bytes, written = %d", length, written);
769
770
2427
  if (written == -1) {
771
    int err;
772
172
    Local<Value> arg = GetSSLError(written, &err, &error_);
773
774
    // If we stopped writing because of an error, it's fatal, discard the data.
775
172
    if (!arg.IsEmpty()) {
776
2
      Debug(this, "Got SSL error (%d), returning UV_EPROTO", err);
777
2
      current_write_ = nullptr;
778
2
      return UV_EPROTO;
779
    }
780
781
170
    Debug(this, "Saving data for later write");
782
    // Otherwise, save unwritten data so it can be written later by ClearIn().
783
170
    CHECK_EQ(pending_cleartext_input_.size(), 0);
784
170
    pending_cleartext_input_ = std::move(data);
785
  }
786
787
  // Write any encrypted/handshake output that may be ready.
788
  // Guard against sync call of current_write_->Done(), its unsupported.
789
2425
  in_dowrite_ = true;
790
2425
  EncOut();
791
2425
  in_dowrite_ = false;
792
793
2425
  return 0;
794
}
795
796
797
6841
uv_buf_t TLSWrap::OnStreamAlloc(size_t suggested_size) {
798
6841
  CHECK_NOT_NULL(ssl_);
799
800
6841
  size_t size = suggested_size;
801
6841
  char* base = crypto::NodeBIO::FromBIO(enc_in_)->PeekWritable(&size);
802
6841
  return uv_buf_init(base, size);
803
}
804
805
806
6859
void TLSWrap::OnStreamRead(ssize_t nread, const uv_buf_t& buf) {
807
6859
  Debug(this, "Read %zd bytes from underlying stream", nread);
808
6859
  if (nread < 0)  {
809
    // Error should be emitted only after all data was read
810
547
    ClearOut();
811
812
    // Ignore EOF if received close_notify
813
547
    if (nread == UV_EOF) {
814
546
      if (eof_)
815
17
        return;
816
529
      eof_ = true;
817
    }
818
819
530
    EmitRead(nread);
820
530
    return;
821
  }
822
823
  // DestroySSL() is the only thing that un-sets ssl_, but that also removes
824
  // this TLSWrap as a stream listener, so we should not receive OnStreamRead()
825
  // calls anymore.
826
6312
  CHECK(ssl_);
827
828
  // Commit the amount of data actually read into the peeked/allocated buffer
829
  // from the underlying stream.
830
6312
  crypto::NodeBIO* enc_in = crypto::NodeBIO::FromBIO(enc_in_);
831
6312
  enc_in->Commit(nread);
832
833
  // Parse ClientHello first, if we need to. It's only parsed if session event
834
  // listeners are used on the server side.  "ended" is the initial state, so
835
  // can mean parsing was never started, or that parsing is finished. Either
836
  // way, ended means we can give the buffered data to SSL.
837
6312
  if (!hello_parser_.IsEnded()) {
838
20
    size_t avail = 0;
839
20
    uint8_t* data = reinterpret_cast<uint8_t*>(enc_in->Peek(&avail));
840

20
    CHECK_IMPLIES(data == nullptr, avail == 0);
841
20
    Debug(this, "Passing %zu bytes to the hello parser", avail);
842
20
    return hello_parser_.Parse(data, avail);
843
  }
844
845
  // Cycle OpenSSL's state
846
6292
  Cycle();
847
}
848
849
850
824
ShutdownWrap* TLSWrap::CreateShutdownWrap(Local<Object> req_wrap_object) {
851
824
  return underlying_stream()->CreateShutdownWrap(req_wrap_object);
852
}
853
854
855
824
int TLSWrap::DoShutdown(ShutdownWrap* req_wrap) {
856
824
  Debug(this, "DoShutdown()");
857
1648
  crypto::MarkPopErrorOnReturn mark_pop_error_on_return;
858
859

824
  if (ssl_ && SSL_shutdown(ssl_.get()) == 0)
860
780
    SSL_shutdown(ssl_.get());
861
862
824
  shutdown_ = true;
863
824
  EncOut();
864
1648
  return stream_->DoShutdown(req_wrap);
865
}
866
867
868
12146
void TLSWrap::SetVerifyMode(const FunctionCallbackInfo<Value>& args) {
869
  TLSWrap* wrap;
870
12146
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
871
872
12146
  CHECK_EQ(args.Length(), 2);
873
24292
  CHECK(args[0]->IsBoolean());
874
24292
  CHECK(args[1]->IsBoolean());
875
12146
  CHECK_NOT_NULL(wrap->ssl_);
876
877
  int verify_mode;
878
12146
  if (wrap->is_server()) {
879
1624
    bool request_cert = args[0]->IsTrue();
880
812
    if (!request_cert) {
881
      // If no cert is requested, there will be none to reject as unauthorized.
882
731
      verify_mode = SSL_VERIFY_NONE;
883
    } else {
884
162
      bool reject_unauthorized = args[1]->IsTrue();
885
81
      verify_mode = SSL_VERIFY_PEER;
886
81
      if (reject_unauthorized)
887
48
        verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
888
    }
889
  } else {
890
    // Servers always send a cert if the cipher is not anonymous (anon is
891
    // disabled by default), so use VERIFY_NONE and check the cert after the
892
    // handshake has completed.
893
11334
    verify_mode = SSL_VERIFY_NONE;
894
  }
895
896
  // Always allow a connection. We'll reject in javascript.
897
12146
  SSL_set_verify(wrap->ssl_.get(), verify_mode, crypto::VerifyCallback);
898
}
899
900
901
210
void TLSWrap::EnableSessionCallbacks(
902
    const FunctionCallbackInfo<Value>& args) {
903
  TLSWrap* wrap;
904
400
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
905
210
  CHECK_NOT_NULL(wrap->ssl_);
906
210
  wrap->enable_session_callbacks();
907
908
  // Clients don't use the HelloParser.
909
210
  if (wrap->is_client())
910
190
    return;
911
912
20
  crypto::NodeBIO::FromBIO(wrap->enc_in_)->set_initial(kMaxHelloLength);
913
20
  wrap->hello_parser_.Start(SSLWrap<TLSWrap>::OnClientHello,
914
                            OnClientHelloParseEnd,
915
20
                            wrap);
916
}
917
918
8
void TLSWrap::EnableKeylogCallback(
919
    const FunctionCallbackInfo<Value>& args) {
920
  TLSWrap* wrap;
921
8
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
922
8
  CHECK_NOT_NULL(wrap->sc_);
923
8
  SSL_CTX_set_keylog_callback(wrap->sc_->ctx_.get(),
924
8
      SSLWrap<TLSWrap>::KeylogCallback);
925
}
926
927
// Check required capabilities were not excluded from the OpenSSL build:
928
// - OPENSSL_NO_SSL_TRACE excludes SSL_trace()
929
// - OPENSSL_NO_STDIO excludes BIO_new_fp()
930
// HAVE_SSL_TRACE is available on the internal tcp_wrap binding for the tests.
931
#if defined(OPENSSL_NO_SSL_TRACE) || defined(OPENSSL_NO_STDIO)
932
# define HAVE_SSL_TRACE 0
933
#else
934
# define HAVE_SSL_TRACE 1
935
#endif
936
937
4
void TLSWrap::EnableTrace(
938
    const FunctionCallbackInfo<Value>& args) {
939
  TLSWrap* wrap;
940
4
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
941
942
#if HAVE_SSL_TRACE
943
4
  if (wrap->ssl_) {
944
4
    wrap->bio_trace_.reset(BIO_new_fp(stderr,  BIO_NOCLOSE | BIO_FP_TEXT));
945
8
    SSL_set_msg_callback(wrap->ssl_.get(), [](int write_p, int version, int
946
          content_type, const void* buf, size_t len, SSL* ssl, void* arg)
947
208
        -> void {
948
        // BIO_write(), etc., called by SSL_trace, may error. The error should
949
        // be ignored, trace is a "best effort", and its usually because stderr
950
        // is a non-blocking pipe, and its buffer has overflowed. Leaving errors
951
        // on the stack that can get picked up by later SSL_ calls causes
952
        // unwanted failures in SSL_ calls, so keep the error stack unchanged.
953
204
        crypto::MarkPopErrorOnReturn mark_pop_error_on_return;
954
102
        SSL_trace(write_p,  version, content_type, buf, len, ssl, arg);
955
212
    });
956
4
    SSL_set_msg_callback_arg(wrap->ssl_.get(), wrap->bio_trace_.get());
957
  }
958
#endif
959
}
960
961
12101
void TLSWrap::DestroySSL(const FunctionCallbackInfo<Value>& args) {
962
  TLSWrap* wrap;
963
12101
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
964
12101
  Debug(wrap, "DestroySSL()");
965
966
  // If there is a write happening, mark it as finished.
967
12101
  wrap->write_callback_scheduled_ = true;
968
969
  // And destroy
970
12101
  wrap->InvokeQueued(UV_ECANCELED, "Canceled because of SSL destruction");
971
972
  // Destroy the SSL structure and friends
973
12101
  wrap->SSLWrap<TLSWrap>::DestroySSL();
974
12101
  wrap->enc_in_ = nullptr;
975
12101
  wrap->enc_out_ = nullptr;
976
977
12101
  if (wrap->stream_ != nullptr)
978
12101
    wrap->stream_->RemoveStreamListener(wrap);
979
12101
  Debug(wrap, "DestroySSL() finished");
980
}
981
982
983
22
void TLSWrap::EnableCertCb(const FunctionCallbackInfo<Value>& args) {
984
  TLSWrap* wrap;
985
22
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
986
22
  wrap->WaitForCertCb(OnClientHelloParseEnd, wrap);
987
}
988
989
990
35
void TLSWrap::OnClientHelloParseEnd(void* arg) {
991
35
  TLSWrap* c = static_cast<TLSWrap*>(arg);
992
  Debug(c, "OnClientHelloParseEnd()");
993
35
  c->Cycle();
994
35
}
995
996
997
1306
void TLSWrap::GetServername(const FunctionCallbackInfo<Value>& args) {
998
1306
  Environment* env = Environment::GetCurrent(args);
999
1000
  TLSWrap* wrap;
1001
1306
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1002
1003
1306
  CHECK_NOT_NULL(wrap->ssl_);
1004
1005
1306
  const char* servername = SSL_get_servername(wrap->ssl_.get(),
1006
1306
                                              TLSEXT_NAMETYPE_host_name);
1007
1306
  if (servername != nullptr) {
1008
522
    args.GetReturnValue().Set(OneByteString(env->isolate(), servername));
1009
  } else {
1010
2264
    args.GetReturnValue().Set(false);
1011
  }
1012
}
1013
1014
1015
187
void TLSWrap::SetServername(const FunctionCallbackInfo<Value>& args) {
1016
187
  Environment* env = Environment::GetCurrent(args);
1017
1018
  TLSWrap* wrap;
1019
187
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1020
1021
187
  CHECK_EQ(args.Length(), 1);
1022
561
  CHECK(args[0]->IsString());
1023
187
  CHECK(!wrap->started_);
1024
187
  CHECK(wrap->is_client());
1025
1026
187
  CHECK_NOT_NULL(wrap->ssl_);
1027
1028
561
  node::Utf8Value servername(env->isolate(), args[0].As<String>());
1029
187
  SSL_set_tlsext_host_name(wrap->ssl_.get(), *servername);
1030
}
1031
1032
1033
875
int TLSWrap::SelectSNIContextCallback(SSL* s, int* ad, void* arg) {
1034
875
  TLSWrap* p = static_cast<TLSWrap*>(SSL_get_app_data(s));
1035
875
  Environment* env = p->env();
1036
1037
875
  const char* servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
1038
1039
875
  if (servername == nullptr)
1040
667
    return SSL_TLSEXT_ERR_OK;
1041
1042
416
  HandleScope handle_scope(env->isolate());
1043
208
  Context::Scope context_scope(env->context());
1044
1045
  // Call the SNI callback and use its return value as context
1046
208
  Local<Object> object = p->object();
1047
  Local<Value> ctx;
1048
1049
  // Set the servername as early as possible
1050
208
  Local<Object> owner = p->GetOwner();
1051
624
  if (!owner->Set(env->context(),
1052
                  env->servername_string(),
1053
1248
                  OneByteString(env->isolate(), servername)).FromMaybe(false)) {
1054
    return SSL_TLSEXT_ERR_NOACK;
1055
  }
1056
1057
832
  if (!object->Get(env->context(), env->sni_context_string()).ToLocal(&ctx))
1058
    return SSL_TLSEXT_ERR_NOACK;
1059
1060
  // Not an object, probably undefined or null
1061
208
  if (!ctx->IsObject())
1062
208
    return SSL_TLSEXT_ERR_NOACK;
1063
1064
  Local<FunctionTemplate> cons = env->secure_context_constructor_template();
1065
  if (!cons->HasInstance(ctx)) {
1066
    // Failure: incorrect SNI context object
1067
    Local<Value> err = Exception::TypeError(env->sni_context_err_string());
1068
    p->MakeCallback(env->onerror_string(), 1, &err);
1069
    return SSL_TLSEXT_ERR_NOACK;
1070
  }
1071
1072
  SecureContext* sc = Unwrap<SecureContext>(ctx.As<Object>());
1073
  CHECK_NOT_NULL(sc);
1074
  p->sni_context_ = BaseObjectPtr<SecureContext>(sc);
1075
1076
  p->ConfigureSecureContext(sc);
1077
  CHECK_EQ(SSL_set_SSL_CTX(p->ssl_.get(), sc->ctx_.get()), sc->ctx_.get());
1078
  p->SetCACerts(sc);
1079
1080
  return SSL_TLSEXT_ERR_OK;
1081
}
1082
1083
#ifndef OPENSSL_NO_PSK
1084
1085
2
void TLSWrap::SetPskIdentityHint(const FunctionCallbackInfo<Value>& args) {
1086
  TLSWrap* p;
1087
2
  ASSIGN_OR_RETURN_UNWRAP(&p, args.Holder());
1088
2
  CHECK_NOT_NULL(p->ssl_);
1089
1090
2
  Environment* env = p->env();
1091
2
  Isolate* isolate = env->isolate();
1092
1093
6
  CHECK(args[0]->IsString());
1094
6
  node::Utf8Value hint(isolate, args[0].As<String>());
1095
1096
2
  if (!SSL_use_psk_identity_hint(p->ssl_.get(), *hint)) {
1097
1
    Local<Value> err = node::ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED(isolate);
1098
1
    p->MakeCallback(env->onerror_string(), 1, &err);
1099
  }
1100
}
1101
1102
20
void TLSWrap::EnablePskCallback(const FunctionCallbackInfo<Value>& args) {
1103
  TLSWrap* wrap;
1104
20
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1105
20
  CHECK_NOT_NULL(wrap->ssl_);
1106
1107
20
  SSL_set_psk_server_callback(wrap->ssl_.get(), PskServerCallback);
1108
20
  SSL_set_psk_client_callback(wrap->ssl_.get(), PskClientCallback);
1109
}
1110
1111
9
unsigned int TLSWrap::PskServerCallback(SSL* s,
1112
                                        const char* identity,
1113
                                        unsigned char* psk,
1114
                                        unsigned int max_psk_len) {
1115
9
  TLSWrap* p = static_cast<TLSWrap*>(SSL_get_app_data(s));
1116
1117
9
  Environment* env = p->env();
1118
9
  Isolate* isolate = env->isolate();
1119
18
  HandleScope scope(isolate);
1120
1121
  MaybeLocal<String> maybe_identity_str =
1122
9
      v8::String::NewFromUtf8(isolate, identity, v8::NewStringType::kNormal);
1123
1124
  v8::Local<v8::String> identity_str;
1125
9
  if (!maybe_identity_str.ToLocal(&identity_str)) return 0;
1126
1127
  // Make sure there are no utf8 replacement symbols.
1128
18
  v8::String::Utf8Value identity_utf8(isolate, identity_str);
1129
9
  if (strcmp(*identity_utf8, identity) != 0) return 0;
1130
1131
  Local<Value> argv[] = {identity_str,
1132
27
                         Integer::NewFromUnsigned(isolate, max_psk_len)};
1133
1134
  MaybeLocal<Value> maybe_psk_val =
1135
9
      p->MakeCallback(env->onpskexchange_symbol(), arraysize(argv), argv);
1136
  Local<Value> psk_val;
1137

18
  if (!maybe_psk_val.ToLocal(&psk_val) || !psk_val->IsArrayBufferView())
1138
1
    return 0;
1139
1140
8
  char* psk_buf = Buffer::Data(psk_val);
1141
8
  size_t psk_buflen = Buffer::Length(psk_val);
1142
1143
8
  if (psk_buflen > max_psk_len) return 0;
1144
1145
8
  memcpy(psk, psk_buf, psk_buflen);
1146
8
  return psk_buflen;
1147
}
1148
1149
9
unsigned int TLSWrap::PskClientCallback(SSL* s,
1150
                                        const char* hint,
1151
                                        char* identity,
1152
                                        unsigned int max_identity_len,
1153
                                        unsigned char* psk,
1154
                                        unsigned int max_psk_len) {
1155
9
  TLSWrap* p = static_cast<TLSWrap*>(SSL_get_app_data(s));
1156
1157
9
  Environment* env = p->env();
1158
9
  Isolate* isolate = env->isolate();
1159
18
  HandleScope scope(isolate);
1160
1161
  Local<Value> argv[] = {Null(isolate),
1162
                         Integer::NewFromUnsigned(isolate, max_psk_len),
1163
36
                         Integer::NewFromUnsigned(isolate, max_identity_len)};
1164
9
  if (hint != nullptr) {
1165
1
    MaybeLocal<String> maybe_hint = String::NewFromUtf8(isolate, hint);
1166
1167
    Local<String> local_hint;
1168
1
    if (!maybe_hint.ToLocal(&local_hint)) return 0;
1169
1170
1
    argv[0] = local_hint;
1171
  }
1172
  MaybeLocal<Value> maybe_ret =
1173
9
      p->MakeCallback(env->onpskexchange_symbol(), arraysize(argv), argv);
1174
  Local<Value> ret;
1175

18
  if (!maybe_ret.ToLocal(&ret) || !ret->IsObject()) return 0;
1176
9
  Local<Object> obj = ret.As<Object>();
1177
1178
27
  MaybeLocal<Value> maybe_psk_val = obj->Get(env->context(), env->psk_string());
1179
1180
  Local<Value> psk_val;
1181

18
  if (!maybe_psk_val.ToLocal(&psk_val) || !psk_val->IsArrayBufferView())
1182
    return 0;
1183
1184
9
  char* psk_buf = Buffer::Data(psk_val);
1185
9
  size_t psk_buflen = Buffer::Length(psk_val);
1186
1187
9
  if (psk_buflen > max_psk_len) return 0;
1188
1189
  MaybeLocal<Value> maybe_identity_val =
1190
27
      obj->Get(env->context(), env->identity_string());
1191
  Local<Value> identity_val;
1192

27
  if (!maybe_identity_val.ToLocal(&identity_val) || !identity_val->IsString())
1193
    return 0;
1194
9
  Local<String> identity_str = identity_val.As<String>();
1195
1196
18
  String::Utf8Value identity_buf(isolate, identity_str);
1197
9
  size_t identity_len = identity_buf.length();
1198
1199
9
  if (identity_len > max_identity_len) return 0;
1200
1201
9
  memcpy(identity, *identity_buf, identity_len);
1202
9
  memcpy(psk, psk_buf, psk_buflen);
1203
1204
9
  return psk_buflen;
1205
}
1206
1207
#endif
1208
1209
3
void TLSWrap::GetWriteQueueSize(const FunctionCallbackInfo<Value>& info) {
1210
  TLSWrap* wrap;
1211
3
  ASSIGN_OR_RETURN_UNWRAP(&wrap, info.This());
1212
1213
3
  if (wrap->ssl_ == nullptr) {
1214
    info.GetReturnValue().Set(0);
1215
    return;
1216
  }
1217
1218
3
  uint32_t write_queue_size = BIO_pending(wrap->enc_out_);
1219
6
  info.GetReturnValue().Set(write_queue_size);
1220
}
1221
1222
1223
void TLSWrap::MemoryInfo(MemoryTracker* tracker) const {
1224
  SSLWrap<TLSWrap>::MemoryInfo(tracker);
1225
  tracker->TrackField("error", error_);
1226
  tracker->TrackFieldWithSize("pending_cleartext_input",
1227
                              pending_cleartext_input_.size(),
1228
                              "AllocatedBuffer");
1229
  if (enc_in_ != nullptr)
1230
    tracker->TrackField("enc_in", crypto::NodeBIO::FromBIO(enc_in_));
1231
  if (enc_out_ != nullptr)
1232
    tracker->TrackField("enc_out", crypto::NodeBIO::FromBIO(enc_out_));
1233
}
1234
1235
1236
476
void TLSWrap::Initialize(Local<Object> target,
1237
                         Local<Value> unused,
1238
                         Local<Context> context,
1239
                         void* priv) {
1240
476
  Environment* env = Environment::GetCurrent(context);
1241
1242
476
  env->SetMethod(target, "wrap", TLSWrap::Wrap);
1243
1244
1904
  NODE_DEFINE_CONSTANT(target, HAVE_SSL_TRACE);
1245
1246
476
  Local<FunctionTemplate> t = BaseObject::MakeLazilyInitializedJSTemplate(env);
1247
  Local<String> tlsWrapString =
1248
476
      FIXED_ONE_BYTE_STRING(env->isolate(), "TLSWrap");
1249
476
  t->SetClassName(tlsWrapString);
1250
952
  t->InstanceTemplate()
1251
476
    ->SetInternalFieldCount(StreamBase::kStreamBaseFieldCount);
1252
1253
  Local<FunctionTemplate> get_write_queue_size =
1254
      FunctionTemplate::New(env->isolate(),
1255
                            GetWriteQueueSize,
1256
                            env->as_callback_data(),
1257
952
                            Signature::New(env->isolate(), t));
1258
1904
  t->PrototypeTemplate()->SetAccessorProperty(
1259
      env->write_queue_size_string(),
1260
      get_write_queue_size,
1261
      Local<FunctionTemplate>(),
1262
476
      static_cast<PropertyAttribute>(ReadOnly | DontDelete));
1263
1264
952
  t->Inherit(AsyncWrap::GetConstructorTemplate(env));
1265
476
  env->SetProtoMethod(t, "receive", Receive);
1266
476
  env->SetProtoMethod(t, "start", Start);
1267
476
  env->SetProtoMethod(t, "setVerifyMode", SetVerifyMode);
1268
476
  env->SetProtoMethod(t, "enableSessionCallbacks", EnableSessionCallbacks);
1269
476
  env->SetProtoMethod(t, "enableKeylogCallback", EnableKeylogCallback);
1270
476
  env->SetProtoMethod(t, "enableTrace", EnableTrace);
1271
476
  env->SetProtoMethod(t, "destroySSL", DestroySSL);
1272
476
  env->SetProtoMethod(t, "enableCertCb", EnableCertCb);
1273
1274
#ifndef OPENSSL_NO_PSK
1275
476
  env->SetProtoMethod(t, "setPskIdentityHint", SetPskIdentityHint);
1276
476
  env->SetProtoMethod(t, "enablePskCallback", EnablePskCallback);
1277
#endif
1278
1279
476
  StreamBase::AddMethods(env, t);
1280
476
  SSLWrap<TLSWrap>::AddMethods(env, t);
1281
1282
476
  env->SetProtoMethod(t, "getServername", GetServername);
1283
476
  env->SetProtoMethod(t, "setServername", SetServername);
1284
1285
1428
  Local<Function> fn = t->GetFunction(env->context()).ToLocalChecked();
1286
1287
476
  env->set_tls_wrap_constructor_function(fn);
1288
1289
1428
  target->Set(env->context(), tlsWrapString, fn).Check();
1290
476
}
1291
1292
}  // namespace node
1293
1294
4185
NODE_MODULE_CONTEXT_AWARE_INTERNAL(tls_wrap, node::TLSWrap::Initialize)