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


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

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

3967
  if (where & SSL_CB_HANDSHAKE_DONE && !SSL_renegotiate_pending(ssl)) {
262
    Debug(c, "SSLInfoCallback(SSL_CB_HANDSHAKE_DONE);");
263
1632
    CHECK(!SSL_renegotiate_pending(ssl));
264
    Local<Value> callback;
265
266
1632
    c->established_ = true;
267
268
6528
    if (object->Get(env->context(), env->onhandshakedone_string())
269

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

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

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

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

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

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

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

10279
      stream_ != nullptr &&
654
10279
      underlying_stream()->IsAlive();
655
}
656
657
658
3
bool TLSWrap::IsClosing() {
659
3
  return underlying_stream()->IsClosing();
660
}
661
662
663
664
2184
int TLSWrap::ReadStart() {
665
2184
  Debug(this, "ReadStart()");
666
2184
  if (stream_ != nullptr)
667
2184
    return stream_->ReadStart();
668
  return 0;
669
}
670
671
672
2793
int TLSWrap::ReadStop() {
673
2793
  Debug(this, "ReadStop()");
674
2793
  if (stream_ != nullptr)
675
2784
    return stream_->ReadStop();
676
9
  return 0;
677
}
678
679
680
5279
const char* TLSWrap::Error() const {
681
5279
  return error_.empty() ? nullptr : error_.c_str();
682
}
683
684
685
7
void TLSWrap::ClearError() {
686
7
  error_.clear();
687
7
}
688
689
690
// Called by StreamBase::Write() to request async write of clear text into SSL.
691
// TODO(@sam-github) Should there be a TLSWrap::DoTryWrite()?
692
2599
int TLSWrap::DoWrite(WriteWrap* w,
693
                     uv_buf_t* bufs,
694
                     size_t count,
695
                     uv_stream_t* send_handle) {
696
2599
  CHECK_NULL(send_handle);
697
2599
  Debug(this, "DoWrite()");
698
699
2599
  if (ssl_ == nullptr) {
700
3
    ClearError();
701
3
    error_ = "Write after DestroySSL";
702
3
    return UV_EPROTO;
703
  }
704
705
2596
  size_t length = 0;
706
  size_t i;
707
2596
  size_t nonempty_i = 0;
708
2596
  size_t nonempty_count = 0;
709
10873
  for (i = 0; i < count; i++) {
710
8277
    length += bufs[i].len;
711
8277
    if (bufs[i].len > 0) {
712
7975
      nonempty_i = i;
713
7975
      nonempty_count += 1;
714
    }
715
  }
716
717
  // We want to trigger a Write() on the underlying stream to drive the stream
718
  // system, but don't want to encrypt empty buffers into a TLS frame, so see
719
  // if we can find something to Write().
720
  // First, call ClearOut(). It does an SSL_read(), which might cause handshake
721
  // or other internal messages to be encrypted. If it does, write them later
722
  // with EncOut().
723
  // If there is still no encrypted output, call Write(bufs) on the underlying
724
  // stream. Since the bufs are empty, it won't actually write non-TLS data
725
  // onto the socket, we just want the side-effects. After, make sure the
726
  // WriteWrap was accepted by the stream, or that we call Done() on it.
727
2596
  if (length == 0) {
728
201
    Debug(this, "Empty write");
729
201
    ClearOut();
730
201
    if (BIO_pending(enc_out_) == 0) {
731
97
      Debug(this, "No pending encrypted output, writing to underlying stream");
732
97
      CHECK_NULL(current_empty_write_);
733
97
      current_empty_write_ = w;
734
      StreamWriteResult res =
735
97
          underlying_stream()->Write(bufs, count, send_handle);
736
97
      if (!res.async) {
737
194
        BaseObjectPtr<TLSWrap> strong_ref{this};
738
776
        env()->SetImmediate([this, strong_ref](Environment* env) {
739
291
          OnStreamAfterWrite(current_empty_write_, 0);
740
194
        });
741
      }
742
97
      return 0;
743
    }
744
  }
745
746
  // Store the current write wrap
747
2499
  CHECK_NULL(current_write_);
748
2499
  current_write_ = w;
749
750
  // Write encrypted data to underlying stream and call Done().
751
2499
  if (length == 0) {
752
104
    EncOut();
753
104
    return 0;
754
  }
755
756
4790
  AllocatedBuffer data;
757
4790
  crypto::MarkPopErrorOnReturn mark_pop_error_on_return;
758
759
2395
  int written = 0;
760
761
  // It is common for zero length buffers to be written,
762
  // don't copy data if there there is one buffer with data
763
  // and one or more zero length buffers.
764
  // _http_outgoing.js writes a zero length buffer in
765
  // in OutgoingMessage.prototype.end.  If there was a large amount
766
  // of data supplied to end() there is no sense allocating
767
  // and copying it when it could just be used.
768
769
2395
  if (nonempty_count != 1) {
770
1349
    data = AllocatedBuffer::AllocateManaged(env(), length);
771
1349
    size_t offset = 0;
772
8281
    for (i = 0; i < count; i++) {
773
6932
      memcpy(data.data() + offset, bufs[i].base, bufs[i].len);
774
6932
      offset += bufs[i].len;
775
    }
776
777
1349
    crypto::NodeBIO::FromBIO(enc_out_)->set_allocate_tls_hint(length);
778
1349
    written = SSL_write(ssl_.get(), data.data(), length);
779
  } else {
780
    // Only one buffer: try to write directly, only store if it fails
781
1046
    uv_buf_t* buf = &bufs[nonempty_i];
782
1046
    crypto::NodeBIO::FromBIO(enc_out_)->set_allocate_tls_hint(buf->len);
783
1046
    written = SSL_write(ssl_.get(), buf->base, buf->len);
784
785
1046
    if (written == -1) {
786
174
      data = AllocatedBuffer::AllocateManaged(env(), length);
787
174
      memcpy(data.data(), buf->base, buf->len);
788
    }
789
  }
790
791

2395
  CHECK(written == -1 || written == static_cast<int>(length));
792
2395
  Debug(this, "Writing %zu bytes, written = %d", length, written);
793
794
2395
  if (written == -1) {
795
    int err;
796
177
    Local<Value> arg = GetSSLError(written, &err, &error_);
797
798
    // If we stopped writing because of an error, it's fatal, discard the data.
799
177
    if (!arg.IsEmpty()) {
800
2
      Debug(this, "Got SSL error (%d), returning UV_EPROTO", err);
801
2
      current_write_ = nullptr;
802
2
      return UV_EPROTO;
803
    }
804
805
175
    Debug(this, "Saving data for later write");
806
    // Otherwise, save unwritten data so it can be written later by ClearIn().
807
175
    CHECK_EQ(pending_cleartext_input_.size(), 0);
808
175
    pending_cleartext_input_ = std::move(data);
809
  }
810
811
  // Write any encrypted/handshake output that may be ready.
812
  // Guard against sync call of current_write_->Done(), its unsupported.
813
2393
  in_dowrite_ = true;
814
2393
  EncOut();
815
2393
  in_dowrite_ = false;
816
817
2393
  return 0;
818
}
819
820
821
6051
uv_buf_t TLSWrap::OnStreamAlloc(size_t suggested_size) {
822
6051
  CHECK_NOT_NULL(ssl_);
823
824
6051
  size_t size = suggested_size;
825
6051
  char* base = crypto::NodeBIO::FromBIO(enc_in_)->PeekWritable(&size);
826
6051
  return uv_buf_init(base, size);
827
}
828
829
830
6057
void TLSWrap::OnStreamRead(ssize_t nread, const uv_buf_t& buf) {
831
6057
  Debug(this, "Read %zd bytes from underlying stream", nread);
832
6057
  if (nread < 0)  {
833
    // Error should be emitted only after all data was read
834
130
    ClearOut();
835
836
    // Ignore EOF if received close_notify
837
130
    if (nread == UV_EOF) {
838
129
      if (eof_)
839
3
        return;
840
126
      eof_ = true;
841
    }
842
843
127
    EmitRead(nread);
844
127
    return;
845
  }
846
847
  // DestroySSL() is the only thing that un-sets ssl_, but that also removes
848
  // this TLSWrap as a stream listener, so we should not receive OnStreamRead()
849
  // calls anymore.
850
5927
  CHECK(ssl_);
851
852
  // Commit the amount of data actually read into the peeked/allocated buffer
853
  // from the underlying stream.
854
5927
  crypto::NodeBIO* enc_in = crypto::NodeBIO::FromBIO(enc_in_);
855
5927
  enc_in->Commit(nread);
856
857
  // Parse ClientHello first, if we need to. It's only parsed if session event
858
  // listeners are used on the server side.  "ended" is the initial state, so
859
  // can mean parsing was never started, or that parsing is finished. Either
860
  // way, ended means we can give the buffered data to SSL.
861
5927
  if (!hello_parser_.IsEnded()) {
862
20
    size_t avail = 0;
863
20
    uint8_t* data = reinterpret_cast<uint8_t*>(enc_in->Peek(&avail));
864

20
    CHECK_IMPLIES(data == nullptr, avail == 0);
865
20
    Debug(this, "Passing %zu bytes to the hello parser", avail);
866
20
    return hello_parser_.Parse(data, avail);
867
  }
868
869
  // Cycle OpenSSL's state
870
5907
  Cycle();
871
}
872
873
874
1367
ShutdownWrap* TLSWrap::CreateShutdownWrap(Local<Object> req_wrap_object) {
875
1367
  return underlying_stream()->CreateShutdownWrap(req_wrap_object);
876
}
877
878
879
1367
int TLSWrap::DoShutdown(ShutdownWrap* req_wrap) {
880
1367
  Debug(this, "DoShutdown()");
881
2734
  crypto::MarkPopErrorOnReturn mark_pop_error_on_return;
882
883

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

18
  if (!maybe_psk_val.ToLocal(&psk_val) || !psk_val->IsArrayBufferView())
1162
1
    return 0;
1163
1164
8
  char* psk_buf = Buffer::Data(psk_val);
1165
8
  size_t psk_buflen = Buffer::Length(psk_val);
1166
1167
8
  if (psk_buflen > max_psk_len) return 0;
1168
1169
8
  memcpy(psk, psk_buf, psk_buflen);
1170
8
  return psk_buflen;
1171
}
1172
1173
9
unsigned int TLSWrap::PskClientCallback(SSL* s,
1174
                                        const char* hint,
1175
                                        char* identity,
1176
                                        unsigned int max_identity_len,
1177
                                        unsigned char* psk,
1178
                                        unsigned int max_psk_len) {
1179
9
  TLSWrap* p = static_cast<TLSWrap*>(SSL_get_app_data(s));
1180
1181
9
  Environment* env = p->env();
1182
9
  Isolate* isolate = env->isolate();
1183
18
  HandleScope scope(isolate);
1184
1185
  Local<Value> argv[] = {Null(isolate),
1186
                         Integer::NewFromUnsigned(isolate, max_psk_len),
1187
36
                         Integer::NewFromUnsigned(isolate, max_identity_len)};
1188
9
  if (hint != nullptr) {
1189
1
    MaybeLocal<String> maybe_hint = String::NewFromUtf8(isolate, hint);
1190
1191
    Local<String> local_hint;
1192
1
    if (!maybe_hint.ToLocal(&local_hint)) return 0;
1193
1194
1
    argv[0] = local_hint;
1195
  }
1196
  MaybeLocal<Value> maybe_ret =
1197
9
      p->MakeCallback(env->onpskexchange_symbol(), arraysize(argv), argv);
1198
  Local<Value> ret;
1199

18
  if (!maybe_ret.ToLocal(&ret) || !ret->IsObject()) return 0;
1200
9
  Local<Object> obj = ret.As<Object>();
1201
1202
27
  MaybeLocal<Value> maybe_psk_val = obj->Get(env->context(), env->psk_string());
1203
1204
  Local<Value> psk_val;
1205

18
  if (!maybe_psk_val.ToLocal(&psk_val) || !psk_val->IsArrayBufferView())
1206
    return 0;
1207
1208
9
  char* psk_buf = Buffer::Data(psk_val);
1209
9
  size_t psk_buflen = Buffer::Length(psk_val);
1210
1211
9
  if (psk_buflen > max_psk_len) return 0;
1212
1213
  MaybeLocal<Value> maybe_identity_val =
1214
27
      obj->Get(env->context(), env->identity_string());
1215
  Local<Value> identity_val;
1216

27
  if (!maybe_identity_val.ToLocal(&identity_val) || !identity_val->IsString())
1217
    return 0;
1218
9
  Local<String> identity_str = identity_val.As<String>();
1219
1220
18
  String::Utf8Value identity_buf(isolate, identity_str);
1221
9
  size_t identity_len = identity_buf.length();
1222
1223
9
  if (identity_len > max_identity_len) return 0;
1224
1225
9
  memcpy(identity, *identity_buf, identity_len);
1226
9
  memcpy(psk, psk_buf, psk_buflen);
1227
1228
9
  return psk_buflen;
1229
}
1230
1231
#endif
1232
1233
2
void TLSWrap::GetWriteQueueSize(const FunctionCallbackInfo<Value>& info) {
1234
  TLSWrap* wrap;
1235
2
  ASSIGN_OR_RETURN_UNWRAP(&wrap, info.This());
1236
1237
2
  if (wrap->ssl_ == nullptr) {
1238
    info.GetReturnValue().Set(0);
1239
    return;
1240
  }
1241
1242
2
  uint32_t write_queue_size = BIO_pending(wrap->enc_out_);
1243
4
  info.GetReturnValue().Set(write_queue_size);
1244
}
1245
1246
1247
void TLSWrap::MemoryInfo(MemoryTracker* tracker) const {
1248
  SSLWrap<TLSWrap>::MemoryInfo(tracker);
1249
  tracker->TrackField("error", error_);
1250
  tracker->TrackFieldWithSize("pending_cleartext_input",
1251
                              pending_cleartext_input_.size(),
1252
                              "AllocatedBuffer");
1253
  if (enc_in_ != nullptr)
1254
    tracker->TrackField("enc_in", crypto::NodeBIO::FromBIO(enc_in_));
1255
  if (enc_out_ != nullptr)
1256
    tracker->TrackField("enc_out", crypto::NodeBIO::FromBIO(enc_out_));
1257
}
1258
1259
1260
499
void TLSWrap::Initialize(Local<Object> target,
1261
                         Local<Value> unused,
1262
                         Local<Context> context,
1263
                         void* priv) {
1264
499
  Environment* env = Environment::GetCurrent(context);
1265
1266
499
  env->SetMethod(target, "wrap", TLSWrap::Wrap);
1267
1268
1996
  NODE_DEFINE_CONSTANT(target, HAVE_SSL_TRACE);
1269
1270
499
  Local<FunctionTemplate> t = BaseObject::MakeLazilyInitializedJSTemplate(env);
1271
  Local<String> tlsWrapString =
1272
499
      FIXED_ONE_BYTE_STRING(env->isolate(), "TLSWrap");
1273
499
  t->SetClassName(tlsWrapString);
1274
998
  t->InstanceTemplate()->SetInternalFieldCount(StreamBase::kInternalFieldCount);
1275
1276
  Local<FunctionTemplate> get_write_queue_size =
1277
      FunctionTemplate::New(env->isolate(),
1278
                            GetWriteQueueSize,
1279
                            Local<Value>(),
1280
998
                            Signature::New(env->isolate(), t));
1281
1996
  t->PrototypeTemplate()->SetAccessorProperty(
1282
      env->write_queue_size_string(),
1283
      get_write_queue_size,
1284
      Local<FunctionTemplate>(),
1285
499
      static_cast<PropertyAttribute>(ReadOnly | DontDelete));
1286
1287
998
  t->Inherit(AsyncWrap::GetConstructorTemplate(env));
1288
499
  env->SetProtoMethod(t, "receive", Receive);
1289
499
  env->SetProtoMethod(t, "start", Start);
1290
499
  env->SetProtoMethod(t, "setVerifyMode", SetVerifyMode);
1291
499
  env->SetProtoMethod(t, "enableSessionCallbacks", EnableSessionCallbacks);
1292
499
  env->SetProtoMethod(t, "enableKeylogCallback", EnableKeylogCallback);
1293
499
  env->SetProtoMethod(t, "enableTrace", EnableTrace);
1294
499
  env->SetProtoMethod(t, "destroySSL", DestroySSL);
1295
499
  env->SetProtoMethod(t, "enableCertCb", EnableCertCb);
1296
1297
#ifndef OPENSSL_NO_PSK
1298
499
  env->SetProtoMethod(t, "setPskIdentityHint", SetPskIdentityHint);
1299
499
  env->SetProtoMethod(t, "enablePskCallback", EnablePskCallback);
1300
#endif
1301
1302
499
  StreamBase::AddMethods(env, t);
1303
499
  SSLWrap<TLSWrap>::AddMethods(env, t);
1304
1305
499
  env->SetProtoMethod(t, "getServername", GetServername);
1306
499
  env->SetProtoMethod(t, "setServername", SetServername);
1307
1308
1497
  Local<Function> fn = t->GetFunction(env->context()).ToLocalChecked();
1309
1310
499
  env->set_tls_wrap_constructor_function(fn);
1311
1312
1497
  target->Set(env->context(), tlsWrapString, fn).Check();
1313
499
}
1314
1315
}  // namespace node
1316
1317
4398
NODE_MODULE_CONTEXT_AWARE_INTERNAL(tls_wrap, node::TLSWrap::Initialize)