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: 526 558 94.3 %
Date: 2019-09-16 22:31:04 Branches: 241 336 71.7 %

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


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

11915
    if (object->Get(env->context(), env->onhandshakestart_string())
246

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

4073
  if (where & SSL_CB_HANDSHAKE_DONE && !SSL_renegotiate_pending(ssl)) {
256
    Debug(c, "SSLInfoCallback(SSL_CB_HANDSHAKE_DONE);");
257
1689
    CHECK(!SSL_renegotiate_pending(ssl));
258
    Local<Value> callback;
259
260
1689
    c->established_ = true;
261
262

8445
    if (object->Get(env->context(), env->onhandshakedone_string())
263

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

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

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

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

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

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

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

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

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

20
    CHECK_IMPLIES(data == nullptr, avail == 0);
834
20
    Debug(this, "Passing %zu bytes to the hello parser", avail);
835
20
    return hello_parser_.Parse(data, avail);
836
  }
837
838
  // Cycle OpenSSL's state
839
8042
  Cycle();
840
}
841
842
843
865
ShutdownWrap* TLSWrap::CreateShutdownWrap(Local<Object> req_wrap_object) {
844
865
  return underlying_stream()->CreateShutdownWrap(req_wrap_object);
845
}
846
847
848
865
int TLSWrap::DoShutdown(ShutdownWrap* req_wrap) {
849
865
  Debug(this, "DoShutdown()");
850
865
  crypto::MarkPopErrorOnReturn mark_pop_error_on_return;
851
852

865
  if (ssl_ && SSL_shutdown(ssl_.get()) == 0)
853
827
    SSL_shutdown(ssl_.get());
854
855
865
  shutdown_ = true;
856
865
  EncOut();
857
865
  return stream_->DoShutdown(req_wrap);
858
}
859
860
861
12215
void TLSWrap::SetVerifyMode(const FunctionCallbackInfo<Value>& args) {
862
  TLSWrap* wrap;
863
24430
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
864
865
12215
  CHECK_EQ(args.Length(), 2);
866
24430
  CHECK(args[0]->IsBoolean());
867
24430
  CHECK(args[1]->IsBoolean());
868
12215
  CHECK_NOT_NULL(wrap->ssl_);
869
870
  int verify_mode;
871
12215
  if (wrap->is_server()) {
872
1636
    bool request_cert = args[0]->IsTrue();
873
818
    if (!request_cert) {
874
      // If no cert is requested, there will be none to reject as unauthorized.
875
736
      verify_mode = SSL_VERIFY_NONE;
876
    } else {
877
164
      bool reject_unauthorized = args[1]->IsTrue();
878
82
      verify_mode = SSL_VERIFY_PEER;
879
82
      if (reject_unauthorized)
880
48
        verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
881
    }
882
  } else {
883
    // Servers always send a cert if the cipher is not anonymous (anon is
884
    // disabled by default), so use VERIFY_NONE and check the cert after the
885
    // handshake has completed.
886
11397
    verify_mode = SSL_VERIFY_NONE;
887
  }
888
889
  // Always allow a connection. We'll reject in javascript.
890
12215
  SSL_set_verify(wrap->ssl_.get(), verify_mode, crypto::VerifyCallback);
891
}
892
893
894
261
void TLSWrap::EnableSessionCallbacks(
895
    const FunctionCallbackInfo<Value>& args) {
896
  TLSWrap* wrap;
897
502
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
898
261
  CHECK_NOT_NULL(wrap->ssl_);
899
261
  wrap->enable_session_callbacks();
900
901
  // Clients don't use the HelloParser.
902
261
  if (wrap->is_client())
903
241
    return;
904
905
20
  crypto::NodeBIO::FromBIO(wrap->enc_in_)->set_initial(kMaxHelloLength);
906
  wrap->hello_parser_.Start(SSLWrap<TLSWrap>::OnClientHello,
907
                            OnClientHelloParseEnd,
908
20
                            wrap);
909
}
910
911
2
void TLSWrap::EnableKeylogCallback(
912
    const FunctionCallbackInfo<Value>& args) {
913
  TLSWrap* wrap;
914
4
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
915
2
  CHECK_NOT_NULL(wrap->sc_);
916
  SSL_CTX_set_keylog_callback(wrap->sc_->ctx_.get(),
917
2
      SSLWrap<TLSWrap>::KeylogCallback);
918
}
919
920
// Check required capabilities were not excluded from the OpenSSL build:
921
// - OPENSSL_NO_SSL_TRACE excludes SSL_trace()
922
// - OPENSSL_NO_STDIO excludes BIO_new_fp()
923
// HAVE_SSL_TRACE is available on the internal tcp_wrap binding for the tests.
924
#if defined(OPENSSL_NO_SSL_TRACE) || defined(OPENSSL_NO_STDIO)
925
# define HAVE_SSL_TRACE 0
926
#else
927
# define HAVE_SSL_TRACE 1
928
#endif
929
930
4
void TLSWrap::EnableTrace(
931
    const FunctionCallbackInfo<Value>& args) {
932
  TLSWrap* wrap;
933
8
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
934
935
#if HAVE_SSL_TRACE
936
4
  if (wrap->ssl_) {
937
4
    wrap->bio_trace_.reset(BIO_new_fp(stderr,  BIO_NOCLOSE | BIO_FP_TEXT));
938
    SSL_set_msg_callback(wrap->ssl_.get(), [](int write_p, int version, int
939
          content_type, const void* buf, size_t len, SSL* ssl, void* arg)
940
208
        -> void {
941
        // BIO_write(), etc., called by SSL_trace, may error. The error should
942
        // be ignored, trace is a "best effort", and its usually because stderr
943
        // is a non-blocking pipe, and its buffer has overflowed. Leaving errors
944
        // on the stack that can get picked up by later SSL_ calls causes
945
        // unwanted failures in SSL_ calls, so keep the error stack unchanged.
946
102
        crypto::MarkPopErrorOnReturn mark_pop_error_on_return;
947
102
        SSL_trace(write_p,  version, content_type, buf, len, ssl, arg);
948
212
    });
949
4
    SSL_set_msg_callback_arg(wrap->ssl_.get(), wrap->bio_trace_.get());
950
  }
951
#endif
952
}
953
954
12166
void TLSWrap::DestroySSL(const FunctionCallbackInfo<Value>& args) {
955
  TLSWrap* wrap;
956
24332
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
957
12166
  Debug(wrap, "DestroySSL()");
958
959
  // If there is a write happening, mark it as finished.
960
12166
  wrap->write_callback_scheduled_ = true;
961
962
  // And destroy
963
12166
  wrap->InvokeQueued(UV_ECANCELED, "Canceled because of SSL destruction");
964
965
  // Destroy the SSL structure and friends
966
12166
  wrap->SSLWrap<TLSWrap>::DestroySSL();
967
12166
  wrap->enc_in_ = nullptr;
968
12166
  wrap->enc_out_ = nullptr;
969
970
12166
  if (wrap->stream_ != nullptr)
971
12166
    wrap->stream_->RemoveStreamListener(wrap);
972
12166
  Debug(wrap, "DestroySSL() finished");
973
}
974
975
976
22
void TLSWrap::EnableCertCb(const FunctionCallbackInfo<Value>& args) {
977
  TLSWrap* wrap;
978
44
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
979
22
  wrap->WaitForCertCb(OnClientHelloParseEnd, wrap);
980
}
981
982
983
35
void TLSWrap::OnClientHelloParseEnd(void* arg) {
984
35
  TLSWrap* c = static_cast<TLSWrap*>(arg);
985
  Debug(c, "OnClientHelloParseEnd()");
986
35
  c->Cycle();
987
35
}
988
989
990
1383
void TLSWrap::GetServername(const FunctionCallbackInfo<Value>& args) {
991
1383
  Environment* env = Environment::GetCurrent(args);
992
993
  TLSWrap* wrap;
994
2766
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
995
996
1383
  CHECK_NOT_NULL(wrap->ssl_);
997
998
1383
  const char* servername = SSL_get_servername(wrap->ssl_.get(),
999
1383
                                              TLSEXT_NAMETYPE_host_name);
1000
1383
  if (servername != nullptr) {
1001
642
    args.GetReturnValue().Set(OneByteString(env->isolate(), servername));
1002
  } else {
1003
2338
    args.GetReturnValue().Set(false);
1004
  }
1005
}
1006
1007
1008
237
void TLSWrap::SetServername(const FunctionCallbackInfo<Value>& args) {
1009
237
  Environment* env = Environment::GetCurrent(args);
1010
1011
  TLSWrap* wrap;
1012
474
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1013
1014
237
  CHECK_EQ(args.Length(), 1);
1015
711
  CHECK(args[0]->IsString());
1016
237
  CHECK(!wrap->started_);
1017
237
  CHECK(wrap->is_client());
1018
1019
237
  CHECK_NOT_NULL(wrap->ssl_);
1020
1021
474
  node::Utf8Value servername(env->isolate(), args[0].As<String>());
1022
237
  SSL_set_tlsext_host_name(wrap->ssl_.get(), *servername);
1023
}
1024
1025
1026
883
int TLSWrap::SelectSNIContextCallback(SSL* s, int* ad, void* arg) {
1027
883
  TLSWrap* p = static_cast<TLSWrap*>(SSL_get_app_data(s));
1028
883
  Environment* env = p->env();
1029
1030
883
  const char* servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
1031
1032
883
  if (servername == nullptr)
1033
674
    return SSL_TLSEXT_ERR_OK;
1034
1035
209
  HandleScope handle_scope(env->isolate());
1036
209
  Context::Scope context_scope(env->context());
1037
1038
  // Call the SNI callback and use its return value as context
1039
209
  Local<Object> object = p->object();
1040
  Local<Value> ctx;
1041
1042
  // Set the servername as early as possible
1043
209
  Local<Object> owner = p->GetOwner();
1044
418
  if (!owner->Set(env->context(),
1045
                  env->servername_string(),
1046
1254
                  OneByteString(env->isolate(), servername)).FromMaybe(false)) {
1047
    return SSL_TLSEXT_ERR_NOACK;
1048
  }
1049
1050
836
  if (!object->Get(env->context(), env->sni_context_string()).ToLocal(&ctx))
1051
    return SSL_TLSEXT_ERR_NOACK;
1052
1053
  // Not an object, probably undefined or null
1054
209
  if (!ctx->IsObject())
1055
209
    return SSL_TLSEXT_ERR_NOACK;
1056
1057
  Local<FunctionTemplate> cons = env->secure_context_constructor_template();
1058
  if (!cons->HasInstance(ctx)) {
1059
    // Failure: incorrect SNI context object
1060
    Local<Value> err = Exception::TypeError(env->sni_context_err_string());
1061
    p->MakeCallback(env->onerror_string(), 1, &err);
1062
    return SSL_TLSEXT_ERR_NOACK;
1063
  }
1064
1065
  p->sni_context_.Reset(env->isolate(), ctx);
1066
1067
  SecureContext* sc = Unwrap<SecureContext>(ctx.As<Object>());
1068
  CHECK_NOT_NULL(sc);
1069
  p->SetSNIContext(sc);
1070
209
  return SSL_TLSEXT_ERR_OK;
1071
}
1072
1073
1074
3
void TLSWrap::GetWriteQueueSize(const FunctionCallbackInfo<Value>& info) {
1075
  TLSWrap* wrap;
1076
3
  ASSIGN_OR_RETURN_UNWRAP(&wrap, info.This());
1077
1078
3
  if (wrap->ssl_ == nullptr) {
1079
    info.GetReturnValue().Set(0);
1080
    return;
1081
  }
1082
1083
3
  uint32_t write_queue_size = BIO_pending(wrap->enc_out_);
1084
6
  info.GetReturnValue().Set(write_queue_size);
1085
}
1086
1087
1088
2
void TLSWrap::MemoryInfo(MemoryTracker* tracker) const {
1089
2
  tracker->TrackField("error", error_);
1090
  tracker->TrackFieldWithSize("pending_cleartext_input",
1091
                              pending_cleartext_input_.size(),
1092
2
                              "AllocatedBuffer");
1093
2
  if (enc_in_ != nullptr)
1094
2
    tracker->TrackField("enc_in", crypto::NodeBIO::FromBIO(enc_in_));
1095
2
  if (enc_out_ != nullptr)
1096
2
    tracker->TrackField("enc_out", crypto::NodeBIO::FromBIO(enc_out_));
1097
2
}
1098
1099
1100
551
void TLSWrap::Initialize(Local<Object> target,
1101
                         Local<Value> unused,
1102
                         Local<Context> context,
1103
                         void* priv) {
1104
551
  Environment* env = Environment::GetCurrent(context);
1105
1106
551
  env->SetMethod(target, "wrap", TLSWrap::Wrap);
1107
1108
2204
  NODE_DEFINE_CONSTANT(target, HAVE_SSL_TRACE);
1109
1110
551
  Local<FunctionTemplate> t = BaseObject::MakeLazilyInitializedJSTemplate(env);
1111
  Local<String> tlsWrapString =
1112
551
      FIXED_ONE_BYTE_STRING(env->isolate(), "TLSWrap");
1113
551
  t->SetClassName(tlsWrapString);
1114
551
  t->InstanceTemplate()
1115
1102
    ->SetInternalFieldCount(StreamBase::kStreamBaseFieldCount);
1116
1117
  Local<FunctionTemplate> get_write_queue_size =
1118
      FunctionTemplate::New(env->isolate(),
1119
                            GetWriteQueueSize,
1120
                            env->as_callback_data(),
1121
1102
                            Signature::New(env->isolate(), t));
1122
1653
  t->PrototypeTemplate()->SetAccessorProperty(
1123
      env->write_queue_size_string(),
1124
      get_write_queue_size,
1125
      Local<FunctionTemplate>(),
1126
1653
      static_cast<PropertyAttribute>(ReadOnly | DontDelete));
1127
1128
1102
  t->Inherit(AsyncWrap::GetConstructorTemplate(env));
1129
551
  env->SetProtoMethod(t, "receive", Receive);
1130
551
  env->SetProtoMethod(t, "start", Start);
1131
551
  env->SetProtoMethod(t, "setVerifyMode", SetVerifyMode);
1132
551
  env->SetProtoMethod(t, "enableSessionCallbacks", EnableSessionCallbacks);
1133
551
  env->SetProtoMethod(t, "enableKeylogCallback", EnableKeylogCallback);
1134
551
  env->SetProtoMethod(t, "enableTrace", EnableTrace);
1135
551
  env->SetProtoMethod(t, "destroySSL", DestroySSL);
1136
551
  env->SetProtoMethod(t, "enableCertCb", EnableCertCb);
1137
1138
551
  StreamBase::AddMethods(env, t);
1139
551
  SSLWrap<TLSWrap>::AddMethods(env, t);
1140
1141
551
  env->SetProtoMethod(t, "getServername", GetServername);
1142
551
  env->SetProtoMethod(t, "setServername", SetServername);
1143
1144
  env->set_tls_wrap_constructor_function(
1145
1653
      t->GetFunction(env->context()).ToLocalChecked());
1146
1147
  target->Set(env->context(),
1148
              tlsWrapString,
1149
2755
              t->GetFunction(env->context()).ToLocalChecked()).Check();
1150
551
}
1151
1152
}  // namespace node
1153
1154
4952
NODE_MODULE_CONTEXT_AWARE_INTERNAL(tls_wrap, node::TLSWrap::Initialize)