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: 448 476 94.1 %
Date: 2019-02-23 22:23:05 Branches: 231 320 72.2 %

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 "node_buffer.h"  // Buffer
25
#include "node_crypto.h"  // SecureContext
26
#include "node_crypto_bio.h"  // NodeBIO
27
// ClientHelloParser
28
#include "node_crypto_clienthello-inl.h"
29
#include "stream_base-inl.h"
30
#include "util-inl.h"
31
32
namespace node {
33
34
using crypto::SecureContext;
35
using crypto::SSLWrap;
36
using v8::Context;
37
using v8::DontDelete;
38
using v8::EscapableHandleScope;
39
using v8::Exception;
40
using v8::Function;
41
using v8::FunctionCallbackInfo;
42
using v8::FunctionTemplate;
43
using v8::Isolate;
44
using v8::Local;
45
using v8::Object;
46
using v8::ReadOnly;
47
using v8::Signature;
48
using v8::String;
49
using v8::Value;
50
51
11708
TLSWrap::TLSWrap(Environment* env,
52
                 Local<Object> obj,
53
                 Kind kind,
54
                 StreamBase* stream,
55
                 SecureContext* sc)
56
    : AsyncWrap(env, obj, AsyncWrap::PROVIDER_TLSWRAP),
57
      SSLWrap<TLSWrap>(env, sc, kind),
58
      StreamBase(env),
59
11708
      sc_(sc) {
60
11708
  MakeWeak();
61
62
  // sc comes from an Unwrap. Make sure it was assigned.
63
11708
  CHECK_NOT_NULL(sc);
64
65
  // We've our own session callbacks
66
  SSL_CTX_sess_set_get_cb(sc_->ctx_.get(),
67
11708
                          SSLWrap<TLSWrap>::GetSessionCallback);
68
  SSL_CTX_sess_set_new_cb(sc_->ctx_.get(),
69
11708
                          SSLWrap<TLSWrap>::NewSessionCallback);
70
71
11708
  stream->PushStreamListener(this);
72
73
11708
  InitSSL();
74
11708
}
75
76
77
34707
TLSWrap::~TLSWrap() {
78
11569
  sc_ = nullptr;
79
23138
}
80
81
82
19499
bool TLSWrap::InvokeQueued(int status, const char* error_str) {
83
19499
  if (!write_callback_scheduled_)
84
4491
    return false;
85
86
15008
  if (current_write_ != nullptr) {
87
1293
    WriteWrap* w = current_write_;
88
1293
    current_write_ = nullptr;
89
1293
    w->Done(status, error_str);
90
  }
91
92
15007
  return true;
93
}
94
95
96
8
void TLSWrap::NewSessionDoneCb() {
97
8
  Cycle();
98
8
}
99
100
101
11708
void TLSWrap::InitSSL() {
102
  // Initialize SSL – OpenSSL takes ownership of these.
103
11708
  enc_in_ = crypto::NodeBIO::New(env()).release();
104
11708
  enc_out_ = crypto::NodeBIO::New(env()).release();
105
106
11708
  SSL_set_bio(ssl_.get(), enc_in_, enc_out_);
107
108
  // NOTE: This could be overridden in SetVerifyMode
109
11708
  SSL_set_verify(ssl_.get(), SSL_VERIFY_NONE, crypto::VerifyCallback);
110
111
#ifdef SSL_MODE_RELEASE_BUFFERS
112
11708
  SSL_set_mode(ssl_.get(), SSL_MODE_RELEASE_BUFFERS);
113
#endif  // SSL_MODE_RELEASE_BUFFERS
114
115
11708
  SSL_set_app_data(ssl_.get(), this);
116
  // Using InfoCallback isn't how we are supposed to check handshake progress:
117
  //   https://github.com/openssl/openssl/issues/7199#issuecomment-420915993
118
  //
119
  // Note on when this gets called on various openssl versions:
120
  //   https://github.com/openssl/openssl/issues/7199#issuecomment-420670544
121
11708
  SSL_set_info_callback(ssl_.get(), SSLInfoCallback);
122
123
11708
  if (is_server()) {
124
611
    SSL_CTX_set_tlsext_servername_callback(sc_->ctx_.get(),
125
611
                                           SelectSNIContextCallback);
126
  }
127
128
11708
  ConfigureSecureContext(sc_);
129
130
11708
  SSL_set_cert_cb(ssl_.get(), SSLWrap<TLSWrap>::SSLCertCallback, this);
131
132
11708
  if (is_server()) {
133
611
    SSL_set_accept_state(ssl_.get());
134
11097
  } else if (is_client()) {
135
    // Enough space for server response (hello, cert)
136
11097
    crypto::NodeBIO::FromBIO(enc_in_)->set_initial(kInitialClientBufferLength);
137
11097
    SSL_set_connect_state(ssl_.get());
138
  } else {
139
    // Unexpected
140
    ABORT();
141
  }
142
11708
}
143
144
145
11708
void TLSWrap::Wrap(const FunctionCallbackInfo<Value>& args) {
146
11708
  Environment* env = Environment::GetCurrent(args);
147
148
11708
  CHECK_EQ(args.Length(), 3);
149
23416
  CHECK(args[0]->IsObject());
150
23416
  CHECK(args[1]->IsObject());
151
23416
  CHECK(args[2]->IsBoolean());
152
153
23416
  Local<External> stream_obj = args[0].As<External>();
154
23416
  Local<Object> sc = args[1].As<Object>();
155
35124
  Kind kind = args[2]->IsTrue() ? SSLWrap<TLSWrap>::kServer :
156
11708
                                  SSLWrap<TLSWrap>::kClient;
157
158
11708
  StreamBase* stream = static_cast<StreamBase*>(stream_obj->Value());
159
11708
  CHECK_NOT_NULL(stream);
160
161
  Local<Object> obj;
162
23416
  if (!env->tls_wrap_constructor_function()
163
35124
           ->NewInstance(env->context())
164
35124
           .ToLocal(&obj)) {
165
11708
    return;
166
  }
167
168
11708
  TLSWrap* res = new TLSWrap(env, obj, kind, stream, Unwrap<SecureContext>(sc));
169
170
35124
  args.GetReturnValue().Set(res->object());
171
}
172
173
174
3
void TLSWrap::Receive(const FunctionCallbackInfo<Value>& args) {
175
  TLSWrap* wrap;
176
6
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
177
178
3
  CHECK(Buffer::HasInstance(args[0]));
179
3
  char* data = Buffer::Data(args[0]);
180
3
  size_t len = Buffer::Length(args[0]);
181
182
  // Copy given buffer entirely or partiall if handle becomes closed
183


9
  while (len > 0 && wrap->IsAlive() && !wrap->IsClosing()) {
184
3
    uv_buf_t buf = wrap->OnStreamAlloc(len);
185
3
    size_t copy = buf.len > len ? len : buf.len;
186
3
    memcpy(buf.base, data, copy);
187
3
    buf.len = copy;
188
3
    wrap->OnStreamRead(copy, buf);
189
190
3
    data += copy;
191
3
    len -= copy;
192
  }
193
}
194
195
196
1066
void TLSWrap::Start(const FunctionCallbackInfo<Value>& args) {
197
  TLSWrap* wrap;
198
2132
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
199
200
1066
  CHECK(!wrap->started_);
201
202
1066
  wrap->started_ = true;
203
204
  // Send ClientHello handshake
205
1066
  CHECK(wrap->is_client());
206
  // Seems odd to read when when we want to send, but SSL_read() triggers a
207
  // handshake if a session isn't established, and handshake will cause
208
  // encrypted data to become available for output.
209
1066
  wrap->ClearOut();
210
1066
  wrap->EncOut();
211
}
212
213
214
27884
void TLSWrap::SSLInfoCallback(const SSL* ssl_, int where, int ret) {
215
27884
  if (!(where & (SSL_CB_HANDSHAKE_START | SSL_CB_HANDSHAKE_DONE)))
216
52650
    return;
217
218
  // SSL_renegotiate_pending() should take `const SSL*`, but it does not.
219
3118
  SSL* ssl = const_cast<SSL*>(ssl_);
220
3118
  TLSWrap* c = static_cast<TLSWrap*>(SSL_get_app_data(ssl_));
221
3118
  Environment* env = c->env();
222
3118
  HandleScope handle_scope(env->isolate());
223
3118
  Context::Scope context_scope(env->context());
224
3118
  Local<Object> object = c->object();
225
226
3118
  if (where & SSL_CB_HANDSHAKE_START) {
227
    Local<Value> callback;
228
229

9315
    if (object->Get(env->context(), env->onhandshakestart_string())
230

11178
          .ToLocal(&callback) && callback->IsFunction()) {
231
1863
      Local<Value> argv[] = { env->GetNow() };
232
3726
      c->MakeCallback(callback.As<Function>(), arraysize(argv), argv);
233
    }
234
  }
235
236
  // SSL_CB_HANDSHAKE_START and SSL_CB_HANDSHAKE_DONE are called
237
  // sending HelloRequest in OpenSSL-1.1.1.
238
  // We need to check whether this is in a renegotiation state or not.
239

3118
  if (where & SSL_CB_HANDSHAKE_DONE && !SSL_renegotiate_pending(ssl)) {
240
    Local<Value> callback;
241
242
1254
    c->established_ = true;
243
244

6270
    if (object->Get(env->context(), env->onhandshakedone_string())
245

7524
          .ToLocal(&callback) && callback->IsFunction()) {
246
1254
      c->MakeCallback(callback.As<Function>(), 0, nullptr);
247
    }
248
3118
  }
249
}
250
251
252
15769
void TLSWrap::EncOut() {
253
  // Ignore cycling data if ClientHello wasn't yet parsed
254
15769
  if (!hello_parser_.IsEnded())
255
10498
    return;
256
257
  // Write in progress
258
15769
  if (write_size_ != 0)
259
2355
    return;
260
261
  // Wait for `newSession` callback to be invoked
262
13414
  if (is_awaiting_new_session())
263
7
    return;
264
265
  // Split-off queue
266

13407
  if (established_ && current_write_ != nullptr)
267
3155
    write_callback_scheduled_ = true;
268
269
13407
  if (ssl_ == nullptr)
270
1
    return;
271
272
  // No encrypted output ready to write to the underlying stream.
273
13406
  if (BIO_pending(enc_out_) == 0) {
274
8097
    if (pending_cleartext_input_.empty())
275
7804
      InvokeQueued(0);
276
8096
    return;
277
  }
278
279
  char* data[kSimultaneousBufferCount];
280
  size_t size[arraysize(data)];
281
5309
  size_t count = arraysize(data);
282
  write_size_ = crypto::NodeBIO::FromBIO(enc_out_)->PeekMultiple(data,
283
                                                                 size,
284
5309
                                                                 &count);
285

5309
  CHECK(write_size_ != 0 && count != 0);
286
287
  uv_buf_t buf[arraysize(data)];
288
5309
  uv_buf_t* bufs = buf;
289
16614
  for (size_t i = 0; i < count; i++)
290
11305
    buf[i] = uv_buf_init(data[i], size[i]);
291
292
5309
  StreamWriteResult res = underlying_stream()->Write(bufs, count);
293
5308
  if (res.err != 0) {
294
39
    InvokeQueued(res.err);
295
39
    return;
296
  }
297
298
5269
  if (!res.async) {
299
4687
    HandleScope handle_scope(env()->isolate());
300
301
    // Simulate asynchronous finishing, TLS cannot handle this at the moment.
302
14057
    env()->SetImmediate([](Environment* env, void* data) {
303
4685
      static_cast<TLSWrap*>(data)->OnStreamAfterWrite(nullptr, 0);
304
18743
    }, this, object());
305
  }
306
}
307
308
309
5356
void TLSWrap::OnStreamAfterWrite(WriteWrap* req_wrap, int status) {
310
5356
  if (current_empty_write_ != nullptr) {
311
90
    WriteWrap* finishing = current_empty_write_;
312
90
    current_empty_write_ = nullptr;
313
90
    finishing->Done(status);
314
90
    return;
315
  }
316
317
5266
  if (ssl_ == nullptr)
318
1
    status = UV_ECANCELED;
319
320
  // Handle error
321
5266
  if (status) {
322
    // Ignore errors after shutdown
323
6
    if (shutdown_)
324
2
      return;
325
326
    // Notify about error
327
4
    InvokeQueued(status);
328
4
    return;
329
  }
330
331
  // Commit
332
5260
  crypto::NodeBIO::FromBIO(enc_out_)->Read(nullptr, write_size_);
333
334
  // Ensure that the progress will be made and `InvokeQueued` will be called.
335
5260
  ClearIn();
336
337
  // Try writing more data
338
5260
  write_size_ = 0;
339
5260
  EncOut();
340
}
341
342
343
9234
Local<Value> TLSWrap::GetSSLError(int status, int* err, std::string* msg) {
344
9234
  EscapableHandleScope scope(env()->isolate());
345
346
  // ssl_ is already destroyed in reading EOF by close notify alert.
347
9234
  if (ssl_ == nullptr)
348
    return Local<Value>();
349
350
9234
  *err = SSL_get_error(ssl_.get(), status);
351

9234
  switch (*err) {
352
    case SSL_ERROR_NONE:
353
    case SSL_ERROR_WANT_READ:
354
    case SSL_ERROR_WANT_WRITE:
355
    case SSL_ERROR_WANT_X509_LOOKUP:
356
8206
      return Local<Value>();
357
358
    case SSL_ERROR_ZERO_RETURN:
359
942
      return scope.Escape(env()->zero_return_string());
360
361
    case SSL_ERROR_SSL:
362
    case SSL_ERROR_SYSCALL:
363
      {
364
557
        unsigned long ssl_err = ERR_peek_error();  // NOLINT(runtime/int)
365
557
        BIO* bio = BIO_new(BIO_s_mem());
366
557
        ERR_print_errors(bio);
367
368
        BUF_MEM* mem;
369
557
        BIO_get_mem_ptr(bio, &mem);
370
371
557
        Isolate* isolate = env()->isolate();
372
557
        Local<Context> context = isolate->GetCurrentContext();
373
374
        Local<String> message =
375
557
            OneByteString(isolate, mem->data, mem->length);
376
557
        Local<Value> exception = Exception::Error(message);
377
1114
        Local<Object> obj = exception->ToObject(context).ToLocalChecked();
378
379
557
        const char* ls = ERR_lib_error_string(ssl_err);
380
557
        const char* fs = ERR_func_error_string(ssl_err);
381
557
        const char* rs = ERR_reason_error_string(ssl_err);
382
383
557
        if (ls != nullptr)
384
          obj->Set(context, env()->library_string(),
385
2212
                   OneByteString(isolate, ls)).FromJust();
386
557
        if (fs != nullptr)
387
          obj->Set(context, env()->function_string(),
388
2212
                   OneByteString(isolate, fs)).FromJust();
389
557
        if (rs != nullptr) {
390
          obj->Set(context, env()->reason_string(),
391
2212
                   OneByteString(isolate, rs)).FromJust();
392
393
          // SSL has no API to recover the error name from the number, so we
394
          // transform reason strings like "this error" to "ERR_SSL_THIS_ERROR",
395
          // which ends up being close to the original error macro name.
396
553
          std::string code(rs);
397
398
11728
          for (auto& c : code) {
399
11175
            if (c == ' ')
400
1112
              c = '_';
401
            else
402
10063
              c = ::toupper(c);
403
          }
404
          obj->Set(context, env()->code_string(),
405
2212
                   OneByteString(isolate, ("ERR_SSL_" + code).c_str()))
406
1659
                     .FromJust();
407
        }
408
409
557
        if (msg != nullptr)
410
3
          msg->assign(mem->data, mem->data + mem->length);
411
412
557
        BIO_free_all(bio);
413
414
        return scope.Escape(exception);
415
      }
416
417
    default:
418
      UNREACHABLE();
419
  }
420
  UNREACHABLE();
421
}
422
423
424
8665
void TLSWrap::ClearOut() {
425
  // Ignore cycling data if ClientHello wasn't yet parsed
426
8665
  if (!hello_parser_.IsEnded())
427
489
    return;
428
429
  // No reads after EOF
430
8664
  if (eof_)
431
15
    return;
432
433
8649
  if (ssl_ == nullptr)
434
    return;
435
436
8649
  crypto::MarkPopErrorOnReturn mark_pop_error_on_return;
437
438
  char out[kClearOutChunkSize];
439
  int read;
440
  for (;;) {
441
33246
    read = SSL_read(ssl_.get(), out, sizeof(out));
442
443
33246
    if (read <= 0)
444
8647
      break;
445
446
24599
    char* current = out;
447
73797
    while (read > 0) {
448
24601
      int avail = read;
449
450
24601
      uv_buf_t buf = EmitAlloc(avail);
451
24601
      if (static_cast<int>(buf.len) < avail)
452
2
        avail = buf.len;
453
24601
      memcpy(buf.base, current, avail);
454
24601
      EmitRead(avail, buf);
455
456
      // Caveat emptor: OnRead() calls into JS land which can result in
457
      // the SSL context object being destroyed.  We have to carefully
458
      // check that ssl_ != nullptr afterwards.
459
24600
      if (ssl_ == nullptr)
460
1
        return;
461
462
24599
      read -= avail;
463
24599
      current += avail;
464
    }
465
24597
  }
466
467
8647
  int flags = SSL_get_shutdown(ssl_.get());
468

8647
  if (!eof_ && flags & SSL_RECEIVED_SHUTDOWN) {
469
514
    eof_ = true;
470
514
    EmitRead(UV_EOF);
471
  }
472
473
  // We need to check whether an error occurred or the connection was
474
  // shutdown cleanly (SSL_ERROR_ZERO_RETURN) even when read == 0.
475
  // See node#1642 and SSL_read(3SSL) for details.
476
8646
  if (read <= 0) {
477
8646
    HandleScope handle_scope(env()->isolate());
478
    int err;
479
8646
    Local<Value> arg = GetSSLError(read, &err, nullptr);
480
481
    // Ignore ZERO_RETURN after EOF, it is basically not a error
482

8646
    if (err == SSL_ERROR_ZERO_RETURN && eof_)
483
471
      return;
484
485
8175
    if (!arg.IsEmpty()) {
486
      // When TLS Alert are stored in wbio,
487
      // it should be flushed to socket before destroyed.
488
554
      if (BIO_pending(enc_out_) != 0)
489
531
        EncOut();
490
491
554
      MakeCallback(env()->onerror_string(), 1, &arg);
492
8175
    }
493
8175
  }
494
}
495
496
497
12283
void TLSWrap::ClearIn() {
498
  // Ignore cycling data if ClientHello wasn't yet parsed
499
12283
  if (!hello_parser_.IsEnded())
500
    return;
501
502
12283
  if (ssl_ == nullptr)
503
    return;
504
505
12283
  std::vector<uv_buf_t> buffers;
506
12283
  buffers.swap(pending_cleartext_input_);
507
508
24566
  crypto::MarkPopErrorOnReturn mark_pop_error_on_return;
509
510
  size_t i;
511
12283
  int written = 0;
512
12439
  for (i = 0; i < buffers.size(); ++i) {
513
591
    size_t avail = buffers[i].len;
514
591
    char* data = buffers[i].base;
515
591
    written = SSL_write(ssl_.get(), data, avail);
516

591
    CHECK(written == -1 || written == static_cast<int>(avail));
517
591
    if (written == -1)
518
435
      break;
519
  }
520
521
  // All written
522
12283
  if (i == buffers.size()) {
523
    // We wrote all the buffers, so no writes failed (written < 0 on failure).
524
11848
    CHECK_GE(written, 0);
525
11848
    return;
526
  }
527
528
  // Error or partial write
529
870
  HandleScope handle_scope(env()->isolate());
530
435
  Context::Scope context_scope(env()->context());
531
532
  int err;
533
870
  std::string error_str;
534
435
  Local<Value> arg = GetSSLError(written, &err, &error_str);
535
435
  if (!arg.IsEmpty()) {
536
2
    write_callback_scheduled_ = true;
537
    // XXX(sam) Should forward an error object with .code/.function/.etc, if
538
    // possible.
539
2
    InvokeQueued(UV_EPROTO, error_str.c_str());
540
  } else {
541
    // Push back the not-yet-written pending buffers into their queue.
542
    // This can be skipped in the error case because no further writes
543
    // would succeed anyway.
544
433
    pending_cleartext_input_.insert(pending_cleartext_input_.end(),
545
                                    buffers.begin() + i,
546
866
                                    buffers.end());
547
  }
548
549
12718
  return;
550
}
551
552
553
24679
AsyncWrap* TLSWrap::GetAsyncWrap() {
554
24679
  return static_cast<AsyncWrap*>(this);
555
}
556
557
558
1031
bool TLSWrap::IsIPCPipe() {
559
1031
  return underlying_stream()->IsIPCPipe();
560
}
561
562
563
int TLSWrap::GetFD() {
564
  return underlying_stream()->GetFD();
565
}
566
567
568
2450
bool TLSWrap::IsAlive() {
569
4900
  return ssl_ != nullptr &&
570

4899
      stream_ != nullptr &&
571
4899
      underlying_stream()->IsAlive();
572
}
573
574
575
3
bool TLSWrap::IsClosing() {
576
3
  return underlying_stream()->IsClosing();
577
}
578
579
580
581
752
int TLSWrap::ReadStart() {
582
752
  if (stream_ != nullptr)
583
752
    return stream_->ReadStart();
584
  return 0;
585
}
586
587
588
382
int TLSWrap::ReadStop() {
589
382
  if (stream_ != nullptr)
590
377
    return stream_->ReadStop();
591
5
  return 0;
592
}
593
594
595
2796
const char* TLSWrap::Error() const {
596
2796
  return error_.empty() ? nullptr : error_.c_str();
597
}
598
599
600
void TLSWrap::ClearError() {
601
  error_.clear();
602
}
603
604
605
// Called by StreamBase::Write() to request async write of clear text into SSL.
606
1386
int TLSWrap::DoWrite(WriteWrap* w,
607
                     uv_buf_t* bufs,
608
                     size_t count,
609
                     uv_stream_t* send_handle) {
610
1386
  CHECK_NULL(send_handle);
611
612
1386
  if (ssl_ == nullptr) {
613
    ClearError();
614
    error_ = "Write after DestroySSL";
615
    return UV_EPROTO;
616
  }
617
618
1386
  bool empty = true;
619
  size_t i;
620
1613
  for (i = 0; i < count; i++) {
621
1431
    if (bufs[i].len > 0) {
622
1204
      empty = false;
623
1204
      break;
624
    }
625
  }
626
627
  // We want to trigger a Write() on the underlying stream to drive the stream
628
  // system, but don't want to encrypt empty buffers into a TLS frame, so see
629
  // if we can find something to Write().
630
  // First, call ClearOut(). It does an SSL_read(), which might cause handshake
631
  // or other internal messages to be encrypted. If it does, write them later
632
  // with EncOut().
633
  // If there is still no encrypted output, call Write(bufs) on the underlying
634
  // stream. Since the bufs are empty, it won't actually write non-TLS data
635
  // onto the socket, we just want the side-effects. After, make sure the
636
  // WriteWrap was accepted by the stream, or that we call Done() on it.
637
1386
  if (empty) {
638
182
    ClearOut();
639
182
    if (BIO_pending(enc_out_) == 0) {
640
90
      CHECK_NULL(current_empty_write_);
641
90
      current_empty_write_ = w;
642
      StreamWriteResult res =
643
90
          underlying_stream()->Write(bufs, count, send_handle);
644
90
      if (!res.async) {
645
270
        env()->SetImmediate([](Environment* env, void* data) {
646
90
          TLSWrap* self = static_cast<TLSWrap*>(data);
647
90
          self->OnStreamAfterWrite(self->current_empty_write_, 0);
648
360
        }, this, object());
649
      }
650
90
      return 0;
651
    }
652
  }
653
654
  // Store the current write wrap
655
1296
  CHECK_NULL(current_write_);
656
1296
  current_write_ = w;
657
658
  // Write encrypted data to underlying stream and call Done().
659
1296
  if (empty) {
660
92
    EncOut();
661
92
    return 0;
662
  }
663
664
1204
  crypto::MarkPopErrorOnReturn mark_pop_error_on_return;
665
666
1204
  int written = 0;
667
20096
  for (i = 0; i < count; i++) {
668
19045
    written = SSL_write(ssl_.get(), bufs[i].base, bufs[i].len);
669

19045
    CHECK(written == -1 || written == static_cast<int>(bufs[i].len));
670
19045
    if (written == -1)
671
153
      break;
672
  }
673
674
1204
  if (i != count) {
675
    int err;
676
153
    Local<Value> arg = GetSSLError(written, &err, &error_);
677
678
    // If we stopped writing because of an error, it's fatal, discard the data.
679
153
    if (!arg.IsEmpty()) {
680
1
      current_write_ = nullptr;
681
1
      return UV_EPROTO;
682
    }
683
684
    // Otherwise, save unwritten data so it can be written later by ClearIn().
685
152
    pending_cleartext_input_.insert(pending_cleartext_input_.end(),
686
                                    &bufs[i],
687
304
                                    &bufs[count]);
688
  }
689
690
  // Write any encrypted/handshake output that may be ready.
691
1203
  EncOut();
692
693
1203
  return 0;
694
}
695
696
697
7378
uv_buf_t TLSWrap::OnStreamAlloc(size_t suggested_size) {
698
7378
  CHECK_NOT_NULL(ssl_);
699
700
7378
  size_t size = suggested_size;
701
7378
  char* base = crypto::NodeBIO::FromBIO(enc_in_)->PeekWritable(&size);
702
7378
  return uv_buf_init(base, size);
703
}
704
705
706
7394
void TLSWrap::OnStreamRead(ssize_t nread, const uv_buf_t& buf) {
707
7394
  if (nread < 0)  {
708
    // Error should be emitted only after all data was read
709
394
    ClearOut();
710
711
    // Ignore EOF if received close_notify
712
394
    if (nread == UV_EOF) {
713
393
      if (eof_)
714
15
        return;
715
378
      eof_ = true;
716
    }
717
718
379
    EmitRead(nread);
719
379
    return;
720
  }
721
722
7000
  if (ssl_ == nullptr) {
723
    EmitRead(UV_EPROTO);
724
    return;
725
  }
726
727
  // Commit the amount of data actually read into the peeked/allocated buffer
728
  // from the underlying stream.
729
7000
  crypto::NodeBIO* enc_in = crypto::NodeBIO::FromBIO(enc_in_);
730
7000
  enc_in->Commit(nread);
731
732
  // Parse ClientHello first, if we need to. It's only parsed if session event
733
  // listeners are used on the server side.  "ended" is the initial state, so
734
  // can mean parsing was never started, or that parsing is finished. Either
735
  // way, ended means we can give the buffered data to SSL.
736
7000
  if (!hello_parser_.IsEnded()) {
737
20
    size_t avail = 0;
738
20
    uint8_t* data = reinterpret_cast<uint8_t*>(enc_in->Peek(&avail));
739

20
    CHECK_IMPLIES(data == nullptr, avail == 0);
740
20
    return hello_parser_.Parse(data, avail);
741
  }
742
743
  // Cycle OpenSSL's state
744
6980
  Cycle();
745
}
746
747
748
596
ShutdownWrap* TLSWrap::CreateShutdownWrap(Local<Object> req_wrap_object) {
749
596
  return underlying_stream()->CreateShutdownWrap(req_wrap_object);
750
}
751
752
753
596
int TLSWrap::DoShutdown(ShutdownWrap* req_wrap) {
754
596
  crypto::MarkPopErrorOnReturn mark_pop_error_on_return;
755
756

596
  if (ssl_ && SSL_shutdown(ssl_.get()) == 0)
757
580
    SSL_shutdown(ssl_.get());
758
759
596
  shutdown_ = true;
760
596
  EncOut();
761
596
  return stream_->DoShutdown(req_wrap);
762
}
763
764
765
11688
void TLSWrap::SetVerifyMode(const FunctionCallbackInfo<Value>& args) {
766
  TLSWrap* wrap;
767
23376
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
768
769
11688
  CHECK_EQ(args.Length(), 2);
770
23376
  CHECK(args[0]->IsBoolean());
771
23376
  CHECK(args[1]->IsBoolean());
772
11688
  CHECK_NOT_NULL(wrap->ssl_);
773
774
  int verify_mode;
775
11688
  if (wrap->is_server()) {
776
1182
    bool request_cert = args[0]->IsTrue();
777
591
    if (!request_cert) {
778
      // If no cert is requested, there will be none to reject as unauthorized.
779
512
      verify_mode = SSL_VERIFY_NONE;
780
    } else {
781
158
      bool reject_unauthorized = args[1]->IsTrue();
782
79
      verify_mode = SSL_VERIFY_PEER;
783
79
      if (reject_unauthorized)
784
47
        verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
785
    }
786
  } else {
787
    // Servers always send a cert if the cipher is not anonymous (anon is
788
    // disabled by default), so use VERIFY_NONE and check the cert after the
789
    // handshake has completed.
790
11097
    verify_mode = SSL_VERIFY_NONE;
791
  }
792
793
  // Always allow a connection. We'll reject in javascript.
794
11688
  SSL_set_verify(wrap->ssl_.get(), verify_mode, crypto::VerifyCallback);
795
}
796
797
798
183
void TLSWrap::EnableSessionCallbacks(
799
    const FunctionCallbackInfo<Value>& args) {
800
  TLSWrap* wrap;
801
346
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
802
183
  CHECK_NOT_NULL(wrap->ssl_);
803
183
  wrap->enable_session_callbacks();
804
805
  // Clients don't use the HelloParser.
806
183
  if (wrap->is_client())
807
163
    return;
808
809
20
  crypto::NodeBIO::FromBIO(wrap->enc_in_)->set_initial(kMaxHelloLength);
810
  wrap->hello_parser_.Start(SSLWrap<TLSWrap>::OnClientHello,
811
                            OnClientHelloParseEnd,
812
20
                            wrap);
813
}
814
815
816
11650
void TLSWrap::DestroySSL(const FunctionCallbackInfo<Value>& args) {
817
  TLSWrap* wrap;
818
23300
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
819
820
  // If there is a write happening, mark it as finished.
821
11650
  wrap->write_callback_scheduled_ = true;
822
823
  // And destroy
824
11650
  wrap->InvokeQueued(UV_ECANCELED, "Canceled because of SSL destruction");
825
826
  // Destroy the SSL structure and friends
827
11650
  wrap->SSLWrap<TLSWrap>::DestroySSL();
828
11650
  wrap->enc_in_ = nullptr;
829
11650
  wrap->enc_out_ = nullptr;
830
831
11650
  if (wrap->stream_ != nullptr)
832
11650
    wrap->stream_->RemoveStreamListener(wrap);
833
}
834
835
836
20
void TLSWrap::EnableCertCb(const FunctionCallbackInfo<Value>& args) {
837
  TLSWrap* wrap;
838
40
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
839
20
  wrap->WaitForCertCb(OnClientHelloParseEnd, wrap);
840
}
841
842
843
35
void TLSWrap::OnClientHelloParseEnd(void* arg) {
844
35
  TLSWrap* c = static_cast<TLSWrap*>(arg);
845
35
  c->Cycle();
846
35
}
847
848
849
1254
void TLSWrap::GetServername(const FunctionCallbackInfo<Value>& args) {
850
1254
  Environment* env = Environment::GetCurrent(args);
851
852
  TLSWrap* wrap;
853
2508
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
854
855
1254
  CHECK_NOT_NULL(wrap->ssl_);
856
857
1254
  const char* servername = SSL_get_servername(wrap->ssl_.get(),
858
1254
                                              TLSEXT_NAMETYPE_host_name);
859
1254
  if (servername != nullptr) {
860
1254
    args.GetReturnValue().Set(OneByteString(env->isolate(), servername));
861
  } else {
862
1672
    args.GetReturnValue().Set(false);
863
  }
864
}
865
866
867
173
void TLSWrap::SetServername(const FunctionCallbackInfo<Value>& args) {
868
173
  Environment* env = Environment::GetCurrent(args);
869
870
  TLSWrap* wrap;
871
346
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
872
873
173
  CHECK_EQ(args.Length(), 1);
874
519
  CHECK(args[0]->IsString());
875
173
  CHECK(!wrap->started_);
876
173
  CHECK(wrap->is_client());
877
878
173
  CHECK_NOT_NULL(wrap->ssl_);
879
880
346
  node::Utf8Value servername(env->isolate(), args[0].As<String>());
881
173
  SSL_set_tlsext_host_name(wrap->ssl_.get(), *servername);
882
}
883
884
885
683
int TLSWrap::SelectSNIContextCallback(SSL* s, int* ad, void* arg) {
886
683
  TLSWrap* p = static_cast<TLSWrap*>(SSL_get_app_data(s));
887
683
  Environment* env = p->env();
888
889
683
  const char* servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
890
891
683
  if (servername == nullptr)
892
439
    return SSL_TLSEXT_ERR_OK;
893
894
244
  HandleScope handle_scope(env->isolate());
895
244
  Context::Scope context_scope(env->context());
896
897
  // Call the SNI callback and use its return value as context
898
244
  Local<Object> object = p->object();
899
  Local<Value> ctx;
900
901
976
  if (!object->Get(env->context(), env->sni_context_string()).ToLocal(&ctx))
902
    return SSL_TLSEXT_ERR_NOACK;
903
904
  // Not an object, probably undefined or null
905
244
  if (!ctx->IsObject())
906
244
    return SSL_TLSEXT_ERR_NOACK;
907
908
  Local<FunctionTemplate> cons = env->secure_context_constructor_template();
909
  if (!cons->HasInstance(ctx)) {
910
    // Failure: incorrect SNI context object
911
    Local<Value> err = Exception::TypeError(env->sni_context_err_string());
912
    p->MakeCallback(env->onerror_string(), 1, &err);
913
    return SSL_TLSEXT_ERR_NOACK;
914
  }
915
916
  p->sni_context_.Reset(env->isolate(), ctx);
917
918
  SecureContext* sc = Unwrap<SecureContext>(ctx.As<Object>());
919
  CHECK_NOT_NULL(sc);
920
  p->SetSNIContext(sc);
921
244
  return SSL_TLSEXT_ERR_OK;
922
}
923
924
925
3
void TLSWrap::GetWriteQueueSize(const FunctionCallbackInfo<Value>& info) {
926
  TLSWrap* wrap;
927
3
  ASSIGN_OR_RETURN_UNWRAP(&wrap, info.This());
928
929
3
  if (wrap->ssl_ == nullptr) {
930
    info.GetReturnValue().Set(0);
931
    return;
932
  }
933
934
3
  uint32_t write_queue_size = BIO_pending(wrap->enc_out_);
935
6
  info.GetReturnValue().Set(write_queue_size);
936
}
937
938
939
2
void TLSWrap::MemoryInfo(MemoryTracker* tracker) const {
940
2
  tracker->TrackField("error", error_);
941
2
  tracker->TrackField("pending_cleartext_input", pending_cleartext_input_);
942
2
  if (enc_in_ != nullptr)
943
2
    tracker->TrackField("enc_in", crypto::NodeBIO::FromBIO(enc_in_));
944
2
  if (enc_out_ != nullptr)
945
2
    tracker->TrackField("enc_out", crypto::NodeBIO::FromBIO(enc_out_));
946
2
}
947
948
949
452
void TLSWrap::Initialize(Local<Object> target,
950
                         Local<Value> unused,
951
                         Local<Context> context,
952
                         void* priv) {
953
452
  Environment* env = Environment::GetCurrent(context);
954
955
452
  env->SetMethod(target, "wrap", TLSWrap::Wrap);
956
957
452
  Local<FunctionTemplate> t = BaseObject::MakeLazilyInitializedJSTemplate(env);
958
  Local<String> tlsWrapString =
959
452
      FIXED_ONE_BYTE_STRING(env->isolate(), "TLSWrap");
960
452
  t->SetClassName(tlsWrapString);
961
962
  Local<FunctionTemplate> get_write_queue_size =
963
      FunctionTemplate::New(env->isolate(),
964
                            GetWriteQueueSize,
965
                            env->as_external(),
966
904
                            Signature::New(env->isolate(), t));
967
1356
  t->PrototypeTemplate()->SetAccessorProperty(
968
      env->write_queue_size_string(),
969
      get_write_queue_size,
970
      Local<FunctionTemplate>(),
971
1356
      static_cast<PropertyAttribute>(ReadOnly | DontDelete));
972
973
904
  t->Inherit(AsyncWrap::GetConstructorTemplate(env));
974
452
  env->SetProtoMethod(t, "receive", Receive);
975
452
  env->SetProtoMethod(t, "start", Start);
976
452
  env->SetProtoMethod(t, "setVerifyMode", SetVerifyMode);
977
452
  env->SetProtoMethod(t, "enableSessionCallbacks", EnableSessionCallbacks);
978
452
  env->SetProtoMethod(t, "destroySSL", DestroySSL);
979
452
  env->SetProtoMethod(t, "enableCertCb", EnableCertCb);
980
981
452
  StreamBase::AddMethods<TLSWrap>(env, t);
982
452
  SSLWrap<TLSWrap>::AddMethods(env, t);
983
984
452
  env->SetProtoMethod(t, "getServername", GetServername);
985
452
  env->SetProtoMethod(t, "setServername", SetServername);
986
987
  env->set_tls_wrap_constructor_function(
988
1356
      t->GetFunction(env->context()).ToLocalChecked());
989
990
  target->Set(env->context(),
991
              tlsWrapString,
992
2260
              t->GetFunction(env->context()).ToLocalChecked()).FromJust();
993
452
}
994
995
}  // namespace node
996
997
4288
NODE_MODULE_CONTEXT_AWARE_INTERNAL(tls_wrap, node::TLSWrap::Initialize)