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: 24 464 5.2 %
Date: 2019-02-01 22:03:38 Branches: 0 323 0.0 %

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
TLSWrap::TLSWrap(Environment* env,
52
                 Kind kind,
53
                 StreamBase* stream,
54
                 SecureContext* sc)
55
    : AsyncWrap(env,
56
                env->tls_wrap_constructor_function()
57
                    ->NewInstance(env->context()).ToLocalChecked(),
58
                AsyncWrap::PROVIDER_TLSWRAP),
59
      SSLWrap<TLSWrap>(env, sc, kind),
60
      StreamBase(env),
61
      sc_(sc) {
62
  MakeWeak();
63
64
  // sc comes from an Unwrap. Make sure it was assigned.
65
  CHECK_NOT_NULL(sc);
66
67
  // We've our own session callbacks
68
  SSL_CTX_sess_set_get_cb(sc_->ctx_.get(),
69
                          SSLWrap<TLSWrap>::GetSessionCallback);
70
  SSL_CTX_sess_set_new_cb(sc_->ctx_.get(),
71
                          SSLWrap<TLSWrap>::NewSessionCallback);
72
73
  stream->PushStreamListener(this);
74
75
  InitSSL();
76
}
77
78
79
TLSWrap::~TLSWrap() {
80
  sc_ = nullptr;
81
}
82
83
84
bool TLSWrap::InvokeQueued(int status, const char* error_str) {
85
  if (!write_callback_scheduled_)
86
    return false;
87
88
  if (current_write_ != nullptr) {
89
    WriteWrap* w = current_write_;
90
    current_write_ = nullptr;
91
    w->Done(status, error_str);
92
  }
93
94
  return true;
95
}
96
97
98
void TLSWrap::NewSessionDoneCb() {
99
  Cycle();
100
}
101
102
103
void TLSWrap::InitSSL() {
104
  // Initialize SSL – OpenSSL takes ownership of these.
105
  enc_in_ = crypto::NodeBIO::New(env()).release();
106
  enc_out_ = crypto::NodeBIO::New(env()).release();
107
108
  SSL_set_bio(ssl_.get(), enc_in_, enc_out_);
109
110
  // NOTE: This could be overridden in SetVerifyMode
111
  SSL_set_verify(ssl_.get(), SSL_VERIFY_NONE, crypto::VerifyCallback);
112
113
#ifdef SSL_MODE_RELEASE_BUFFERS
114
  SSL_set_mode(ssl_.get(), SSL_MODE_RELEASE_BUFFERS);
115
#endif  // SSL_MODE_RELEASE_BUFFERS
116
117
  SSL_set_app_data(ssl_.get(), this);
118
  // Using InfoCallback isn't how we are supposed to check handshake progress:
119
  //   https://github.com/openssl/openssl/issues/7199#issuecomment-420915993
120
  //
121
  // Note on when this gets called on various openssl versions:
122
  //   https://github.com/openssl/openssl/issues/7199#issuecomment-420670544
123
  SSL_set_info_callback(ssl_.get(), SSLInfoCallback);
124
125
  if (is_server()) {
126
    SSL_CTX_set_tlsext_servername_callback(sc_->ctx_.get(),
127
                                           SelectSNIContextCallback);
128
  }
129
130
  ConfigureSecureContext(sc_);
131
132
  SSL_set_cert_cb(ssl_.get(), SSLWrap<TLSWrap>::SSLCertCallback, this);
133
134
  if (is_server()) {
135
    SSL_set_accept_state(ssl_.get());
136
  } else if (is_client()) {
137
    // Enough space for server response (hello, cert)
138
    crypto::NodeBIO::FromBIO(enc_in_)->set_initial(kInitialClientBufferLength);
139
    SSL_set_connect_state(ssl_.get());
140
  } else {
141
    // Unexpected
142
    ABORT();
143
  }
144
}
145
146
147
void TLSWrap::Wrap(const FunctionCallbackInfo<Value>& args) {
148
  Environment* env = Environment::GetCurrent(args);
149
150
  CHECK_EQ(args.Length(), 3);
151
  CHECK(args[0]->IsObject());
152
  CHECK(args[1]->IsObject());
153
  CHECK(args[2]->IsBoolean());
154
155
  Local<External> stream_obj = args[0].As<External>();
156
  Local<Object> sc = args[1].As<Object>();
157
  Kind kind = args[2]->IsTrue() ? SSLWrap<TLSWrap>::kServer :
158
                                  SSLWrap<TLSWrap>::kClient;
159
160
  StreamBase* stream = static_cast<StreamBase*>(stream_obj->Value());
161
  CHECK_NOT_NULL(stream);
162
163
  TLSWrap* res = new TLSWrap(env, kind, stream, Unwrap<SecureContext>(sc));
164
165
  args.GetReturnValue().Set(res->object());
166
}
167
168
169
void TLSWrap::Receive(const FunctionCallbackInfo<Value>& args) {
170
  TLSWrap* wrap;
171
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
172
173
  CHECK(Buffer::HasInstance(args[0]));
174
  char* data = Buffer::Data(args[0]);
175
  size_t len = Buffer::Length(args[0]);
176
177
  // Copy given buffer entirely or partiall if handle becomes closed
178
  while (len > 0 && wrap->IsAlive() && !wrap->IsClosing()) {
179
    uv_buf_t buf = wrap->OnStreamAlloc(len);
180
    size_t copy = buf.len > len ? len : buf.len;
181
    memcpy(buf.base, data, copy);
182
    buf.len = copy;
183
    wrap->OnStreamRead(copy, buf);
184
185
    data += copy;
186
    len -= copy;
187
  }
188
}
189
190
191
void TLSWrap::Start(const FunctionCallbackInfo<Value>& args) {
192
  TLSWrap* wrap;
193
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
194
195
  CHECK(!wrap->started_);
196
197
  wrap->started_ = true;
198
199
  // Send ClientHello handshake
200
  CHECK(wrap->is_client());
201
  // Seems odd to read when when we want to send, but SSL_read() triggers a
202
  // handshake if a session isn't established, and handshake will cause
203
  // encrypted data to become available for output.
204
  wrap->ClearOut();
205
  wrap->EncOut();
206
}
207
208
209
void TLSWrap::SSLInfoCallback(const SSL* ssl_, int where, int ret) {
210
  if (!(where & (SSL_CB_HANDSHAKE_START | SSL_CB_HANDSHAKE_DONE)))
211
    return;
212
213
  // Be compatible with older versions of OpenSSL. SSL_get_app_data() wants
214
  // a non-const SSL* in OpenSSL <= 0.9.7e.
215
  SSL* ssl = const_cast<SSL*>(ssl_);
216
  TLSWrap* c = static_cast<TLSWrap*>(SSL_get_app_data(ssl));
217
  Environment* env = c->env();
218
  HandleScope handle_scope(env->isolate());
219
  Context::Scope context_scope(env->context());
220
  Local<Object> object = c->object();
221
222
  if (where & SSL_CB_HANDSHAKE_START) {
223
    Local<Value> callback;
224
225
    if (object->Get(env->context(), env->onhandshakestart_string())
226
          .ToLocal(&callback) && callback->IsFunction()) {
227
      Local<Value> argv[] = { env->GetNow() };
228
      c->MakeCallback(callback.As<Function>(), arraysize(argv), argv);
229
    }
230
  }
231
232
  // SSL_CB_HANDSHAKE_START and SSL_CB_HANDSHAKE_DONE are called
233
  // sending HelloRequest in OpenSSL-1.1.1.
234
  // We need to check whether this is in a renegotiation state or not.
235
  if (where & SSL_CB_HANDSHAKE_DONE && !SSL_renegotiate_pending(ssl)) {
236
    Local<Value> callback;
237
238
    c->established_ = true;
239
240
    if (object->Get(env->context(), env->onhandshakedone_string())
241
          .ToLocal(&callback) && callback->IsFunction()) {
242
      c->MakeCallback(callback.As<Function>(), 0, nullptr);
243
    }
244
  }
245
}
246
247
248
void TLSWrap::EncOut() {
249
  // Ignore cycling data if ClientHello wasn't yet parsed
250
  if (!hello_parser_.IsEnded())
251
    return;
252
253
  // Write in progress
254
  if (write_size_ != 0)
255
    return;
256
257
  // Wait for `newSession` callback to be invoked
258
  if (is_awaiting_new_session())
259
    return;
260
261
  // Split-off queue
262
  if (established_ && current_write_ != nullptr)
263
    write_callback_scheduled_ = true;
264
265
  if (ssl_ == nullptr)
266
    return;
267
268
  // No encrypted output ready to write to the underlying stream.
269
  if (BIO_pending(enc_out_) == 0) {
270
    if (pending_cleartext_input_.empty())
271
      InvokeQueued(0);
272
    return;
273
  }
274
275
  char* data[kSimultaneousBufferCount];
276
  size_t size[arraysize(data)];
277
  size_t count = arraysize(data);
278
  write_size_ = crypto::NodeBIO::FromBIO(enc_out_)->PeekMultiple(data,
279
                                                                 size,
280
                                                                 &count);
281
  CHECK(write_size_ != 0 && count != 0);
282
283
  uv_buf_t buf[arraysize(data)];
284
  uv_buf_t* bufs = buf;
285
  for (size_t i = 0; i < count; i++)
286
    buf[i] = uv_buf_init(data[i], size[i]);
287
288
  StreamWriteResult res = underlying_stream()->Write(bufs, count);
289
  if (res.err != 0) {
290
    InvokeQueued(res.err);
291
    return;
292
  }
293
294
  if (!res.async) {
295
    HandleScope handle_scope(env()->isolate());
296
297
    // Simulate asynchronous finishing, TLS cannot handle this at the moment.
298
    env()->SetImmediate([](Environment* env, void* data) {
299
      static_cast<TLSWrap*>(data)->OnStreamAfterWrite(nullptr, 0);
300
    }, this, object());
301
  }
302
}
303
304
305
void TLSWrap::OnStreamAfterWrite(WriteWrap* req_wrap, int status) {
306
  if (current_empty_write_ != nullptr) {
307
    WriteWrap* finishing = current_empty_write_;
308
    current_empty_write_ = nullptr;
309
    finishing->Done(status);
310
    return;
311
  }
312
313
  if (ssl_ == nullptr)
314
    status = UV_ECANCELED;
315
316
  // Handle error
317
  if (status) {
318
    // Ignore errors after shutdown
319
    if (shutdown_)
320
      return;
321
322
    // Notify about error
323
    InvokeQueued(status);
324
    return;
325
  }
326
327
  // Commit
328
  crypto::NodeBIO::FromBIO(enc_out_)->Read(nullptr, write_size_);
329
330
  // Ensure that the progress will be made and `InvokeQueued` will be called.
331
  ClearIn();
332
333
  // Try writing more data
334
  write_size_ = 0;
335
  EncOut();
336
}
337
338
339
Local<Value> TLSWrap::GetSSLError(int status, int* err, std::string* msg) {
340
  EscapableHandleScope scope(env()->isolate());
341
342
  // ssl_ is already destroyed in reading EOF by close notify alert.
343
  if (ssl_ == nullptr)
344
    return Local<Value>();
345
346
  *err = SSL_get_error(ssl_.get(), status);
347
  switch (*err) {
348
    case SSL_ERROR_NONE:
349
    case SSL_ERROR_WANT_READ:
350
    case SSL_ERROR_WANT_WRITE:
351
    case SSL_ERROR_WANT_X509_LOOKUP:
352
      break;
353
    case SSL_ERROR_ZERO_RETURN:
354
      return scope.Escape(env()->zero_return_string());
355
      break;
356
    default:
357
      {
358
        CHECK(*err == SSL_ERROR_SSL || *err == SSL_ERROR_SYSCALL);
359
360
        unsigned long ssl_err = ERR_peek_error();  // NOLINT(runtime/int)
361
        BIO* bio = BIO_new(BIO_s_mem());
362
        ERR_print_errors(bio);
363
364
        BUF_MEM* mem;
365
        BIO_get_mem_ptr(bio, &mem);
366
367
        Isolate* isolate = env()->isolate();
368
        Local<Context> context = isolate->GetCurrentContext();
369
370
        Local<String> message =
371
            OneByteString(isolate, mem->data, mem->length);
372
        Local<Value> exception = Exception::Error(message);
373
        Local<Object> obj = exception->ToObject(context).ToLocalChecked();
374
375
        const char* ls = ERR_lib_error_string(ssl_err);
376
        const char* fs = ERR_func_error_string(ssl_err);
377
        const char* rs = ERR_reason_error_string(ssl_err);
378
379
        if (ls != nullptr)
380
          obj->Set(context, env()->library_string(),
381
                   OneByteString(isolate, ls)).FromJust();
382
        if (fs != nullptr)
383
          obj->Set(context, env()->function_string(),
384
                   OneByteString(isolate, fs)).FromJust();
385
        if (rs != nullptr) {
386
          obj->Set(context, env()->reason_string(),
387
                   OneByteString(isolate, rs)).FromJust();
388
389
          // SSL has no API to recover the error name from the number, so we
390
          // transform reason strings like "this error" to "ERR_SSL_THIS_ERROR",
391
          // which ends up being close to the original error macro name.
392
          std::string code(rs);
393
394
          for (auto& c : code) {
395
            if (c == ' ')
396
              c = '_';
397
            else
398
              c = ::toupper(c);
399
          }
400
          obj->Set(context, env()->code_string(),
401
                   OneByteString(isolate, ("ERR_SSL_" + code).c_str()))
402
                     .FromJust();
403
        }
404
405
        if (msg != nullptr)
406
          msg->assign(mem->data, mem->data + mem->length);
407
408
        BIO_free_all(bio);
409
410
        return scope.Escape(exception);
411
      }
412
  }
413
  return Local<Value>();
414
}
415
416
417
void TLSWrap::ClearOut() {
418
  // Ignore cycling data if ClientHello wasn't yet parsed
419
  if (!hello_parser_.IsEnded())
420
    return;
421
422
  // No reads after EOF
423
  if (eof_)
424
    return;
425
426
  if (ssl_ == nullptr)
427
    return;
428
429
  crypto::MarkPopErrorOnReturn mark_pop_error_on_return;
430
431
  char out[kClearOutChunkSize];
432
  int read;
433
  for (;;) {
434
    read = SSL_read(ssl_.get(), out, sizeof(out));
435
436
    if (read <= 0)
437
      break;
438
439
    char* current = out;
440
    while (read > 0) {
441
      int avail = read;
442
443
      uv_buf_t buf = EmitAlloc(avail);
444
      if (static_cast<int>(buf.len) < avail)
445
        avail = buf.len;
446
      memcpy(buf.base, current, avail);
447
      EmitRead(avail, buf);
448
449
      // Caveat emptor: OnRead() calls into JS land which can result in
450
      // the SSL context object being destroyed.  We have to carefully
451
      // check that ssl_ != nullptr afterwards.
452
      if (ssl_ == nullptr)
453
        return;
454
455
      read -= avail;
456
      current += avail;
457
    }
458
  }
459
460
  int flags = SSL_get_shutdown(ssl_.get());
461
  if (!eof_ && flags & SSL_RECEIVED_SHUTDOWN) {
462
    eof_ = true;
463
    EmitRead(UV_EOF);
464
  }
465
466
  // We need to check whether an error occurred or the connection was
467
  // shutdown cleanly (SSL_ERROR_ZERO_RETURN) even when read == 0.
468
  // See node#1642 and SSL_read(3SSL) for details.
469
  if (read <= 0) {
470
    HandleScope handle_scope(env()->isolate());
471
    int err;
472
    Local<Value> arg = GetSSLError(read, &err, nullptr);
473
474
    // Ignore ZERO_RETURN after EOF, it is basically not a error
475
    if (err == SSL_ERROR_ZERO_RETURN && eof_)
476
      return;
477
478
    if (!arg.IsEmpty()) {
479
      // When TLS Alert are stored in wbio,
480
      // it should be flushed to socket before destroyed.
481
      if (BIO_pending(enc_out_) != 0)
482
        EncOut();
483
484
      MakeCallback(env()->onerror_string(), 1, &arg);
485
    }
486
  }
487
}
488
489
490
void TLSWrap::ClearIn() {
491
  // Ignore cycling data if ClientHello wasn't yet parsed
492
  if (!hello_parser_.IsEnded())
493
    return;
494
495
  if (ssl_ == nullptr)
496
    return;
497
498
  std::vector<uv_buf_t> buffers;
499
  buffers.swap(pending_cleartext_input_);
500
501
  crypto::MarkPopErrorOnReturn mark_pop_error_on_return;
502
503
  size_t i;
504
  int written = 0;
505
  for (i = 0; i < buffers.size(); ++i) {
506
    size_t avail = buffers[i].len;
507
    char* data = buffers[i].base;
508
    written = SSL_write(ssl_.get(), data, avail);
509
    CHECK(written == -1 || written == static_cast<int>(avail));
510
    if (written == -1)
511
      break;
512
  }
513
514
  // All written
515
  if (i == buffers.size()) {
516
    // We wrote all the buffers, so no writes failed (written < 0 on failure).
517
    CHECK_GE(written, 0);
518
    return;
519
  }
520
521
  // Error or partial write
522
  HandleScope handle_scope(env()->isolate());
523
  Context::Scope context_scope(env()->context());
524
525
  int err;
526
  std::string error_str;
527
  Local<Value> arg = GetSSLError(written, &err, &error_str);
528
  if (!arg.IsEmpty()) {
529
    write_callback_scheduled_ = true;
530
    // XXX(sam) Should forward an error object with .code/.function/.etc, if
531
    // possible.
532
    InvokeQueued(UV_EPROTO, error_str.c_str());
533
  } else {
534
    // Push back the not-yet-written pending buffers into their queue.
535
    // This can be skipped in the error case because no further writes
536
    // would succeed anyway.
537
    pending_cleartext_input_.insert(pending_cleartext_input_.end(),
538
                                    buffers.begin() + i,
539
                                    buffers.end());
540
  }
541
542
  return;
543
}
544
545
546
AsyncWrap* TLSWrap::GetAsyncWrap() {
547
  return static_cast<AsyncWrap*>(this);
548
}
549
550
551
bool TLSWrap::IsIPCPipe() {
552
  return underlying_stream()->IsIPCPipe();
553
}
554
555
556
int TLSWrap::GetFD() {
557
  return underlying_stream()->GetFD();
558
}
559
560
561
bool TLSWrap::IsAlive() {
562
  return ssl_ != nullptr &&
563
      stream_ != nullptr &&
564
      underlying_stream()->IsAlive();
565
}
566
567
568
bool TLSWrap::IsClosing() {
569
  return underlying_stream()->IsClosing();
570
}
571
572
573
574
int TLSWrap::ReadStart() {
575
  if (stream_ != nullptr)
576
    return stream_->ReadStart();
577
  return 0;
578
}
579
580
581
int TLSWrap::ReadStop() {
582
  if (stream_ != nullptr)
583
    return stream_->ReadStop();
584
  return 0;
585
}
586
587
588
const char* TLSWrap::Error() const {
589
  return error_.empty() ? nullptr : error_.c_str();
590
}
591
592
593
void TLSWrap::ClearError() {
594
  error_.clear();
595
}
596
597
598
// Called by StreamBase::Write() to request async write of clear text into SSL.
599
int TLSWrap::DoWrite(WriteWrap* w,
600
                     uv_buf_t* bufs,
601
                     size_t count,
602
                     uv_stream_t* send_handle) {
603
  CHECK_NULL(send_handle);
604
605
  if (ssl_ == nullptr) {
606
    ClearError();
607
    error_ = "Write after DestroySSL";
608
    return UV_EPROTO;
609
  }
610
611
  bool empty = true;
612
  size_t i;
613
  for (i = 0; i < count; i++) {
614
    if (bufs[i].len > 0) {
615
      empty = false;
616
      break;
617
    }
618
  }
619
620
  // We want to trigger a Write() on the underlying stream to drive the stream
621
  // system, but don't want to encrypt empty buffers into a TLS frame, so see
622
  // if we can find something to Write().
623
  // First, call ClearOut(). It does an SSL_read(), which might cause handshake
624
  // or other internal messages to be encrypted. If it does, write them later
625
  // with EncOut().
626
  // If there is still no encrypted output, call Write(bufs) on the underlying
627
  // stream. Since the bufs are empty, it won't actually write non-TLS data
628
  // onto the socket, we just want the side-effects. After, make sure the
629
  // WriteWrap was accepted by the stream, or that we call Done() on it.
630
  if (empty) {
631
    ClearOut();
632
    if (BIO_pending(enc_out_) == 0) {
633
      CHECK_NULL(current_empty_write_);
634
      current_empty_write_ = w;
635
      StreamWriteResult res =
636
          underlying_stream()->Write(bufs, count, send_handle);
637
      if (!res.async) {
638
        env()->SetImmediate([](Environment* env, void* data) {
639
          TLSWrap* self = static_cast<TLSWrap*>(data);
640
          self->OnStreamAfterWrite(self->current_empty_write_, 0);
641
        }, this, object());
642
      }
643
      return 0;
644
    }
645
  }
646
647
  // Store the current write wrap
648
  CHECK_NULL(current_write_);
649
  current_write_ = w;
650
651
  // Write encrypted data to underlying stream and call Done().
652
  if (empty) {
653
    EncOut();
654
    return 0;
655
  }
656
657
  crypto::MarkPopErrorOnReturn mark_pop_error_on_return;
658
659
  int written = 0;
660
  for (i = 0; i < count; i++) {
661
    written = SSL_write(ssl_.get(), bufs[i].base, bufs[i].len);
662
    CHECK(written == -1 || written == static_cast<int>(bufs[i].len));
663
    if (written == -1)
664
      break;
665
  }
666
667
  if (i != count) {
668
    int err;
669
    Local<Value> arg = GetSSLError(written, &err, &error_);
670
671
    // If we stopped writing because of an error, it's fatal, discard the data.
672
    if (!arg.IsEmpty()) {
673
      current_write_ = nullptr;
674
      return UV_EPROTO;
675
    }
676
677
    // Otherwise, save unwritten data so it can be written later by ClearIn().
678
    pending_cleartext_input_.insert(pending_cleartext_input_.end(),
679
                                    &bufs[i],
680
                                    &bufs[count]);
681
  }
682
683
  // Write any encrypted/handshake output that may be ready.
684
  EncOut();
685
686
  return 0;
687
}
688
689
690
uv_buf_t TLSWrap::OnStreamAlloc(size_t suggested_size) {
691
  CHECK_NOT_NULL(ssl_);
692
693
  size_t size = suggested_size;
694
  char* base = crypto::NodeBIO::FromBIO(enc_in_)->PeekWritable(&size);
695
  return uv_buf_init(base, size);
696
}
697
698
699
void TLSWrap::OnStreamRead(ssize_t nread, const uv_buf_t& buf) {
700
  if (nread < 0)  {
701
    // Error should be emitted only after all data was read
702
    ClearOut();
703
704
    // Ignore EOF if received close_notify
705
    if (nread == UV_EOF) {
706
      if (eof_)
707
        return;
708
      eof_ = true;
709
    }
710
711
    EmitRead(nread);
712
    return;
713
  }
714
715
  if (ssl_ == nullptr) {
716
    EmitRead(UV_EPROTO);
717
    return;
718
  }
719
720
  // Commit the amount of data actually read into the peeked/allocated buffer
721
  // from the underlying stream.
722
  crypto::NodeBIO* enc_in = crypto::NodeBIO::FromBIO(enc_in_);
723
  enc_in->Commit(nread);
724
725
  // Parse ClientHello first, if we need to. It's only parsed if session event
726
  // listeners are used on the server side.  "ended" is the initial state, so
727
  // can mean parsing was never started, or that parsing is finished. Either
728
  // way, ended means we can give the buffered data to SSL.
729
  if (!hello_parser_.IsEnded()) {
730
    size_t avail = 0;
731
    uint8_t* data = reinterpret_cast<uint8_t*>(enc_in->Peek(&avail));
732
    CHECK_IMPLIES(data == nullptr, avail == 0);
733
    return hello_parser_.Parse(data, avail);
734
  }
735
736
  // Cycle OpenSSL's state
737
  Cycle();
738
}
739
740
741
ShutdownWrap* TLSWrap::CreateShutdownWrap(Local<Object> req_wrap_object) {
742
  return underlying_stream()->CreateShutdownWrap(req_wrap_object);
743
}
744
745
746
int TLSWrap::DoShutdown(ShutdownWrap* req_wrap) {
747
  crypto::MarkPopErrorOnReturn mark_pop_error_on_return;
748
749
  if (ssl_ && SSL_shutdown(ssl_.get()) == 0)
750
    SSL_shutdown(ssl_.get());
751
752
  shutdown_ = true;
753
  EncOut();
754
  return stream_->DoShutdown(req_wrap);
755
}
756
757
758
void TLSWrap::SetVerifyMode(const FunctionCallbackInfo<Value>& args) {
759
  TLSWrap* wrap;
760
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
761
762
  CHECK_EQ(args.Length(), 2);
763
  CHECK(args[0]->IsBoolean());
764
  CHECK(args[1]->IsBoolean());
765
  CHECK_NOT_NULL(wrap->ssl_);
766
767
  int verify_mode;
768
  if (wrap->is_server()) {
769
    bool request_cert = args[0]->IsTrue();
770
    if (!request_cert) {
771
      // Note reject_unauthorized ignored.
772
      verify_mode = SSL_VERIFY_NONE;
773
    } else {
774
      bool reject_unauthorized = args[1]->IsTrue();
775
      verify_mode = SSL_VERIFY_PEER;
776
      if (reject_unauthorized)
777
        verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
778
    }
779
  } else {
780
    // Note request_cert and reject_unauthorized are ignored for clients.
781
    verify_mode = SSL_VERIFY_NONE;
782
  }
783
784
  // Always allow a connection. We'll reject in javascript.
785
  SSL_set_verify(wrap->ssl_.get(), verify_mode, crypto::VerifyCallback);
786
}
787
788
789
void TLSWrap::EnableSessionCallbacks(
790
    const FunctionCallbackInfo<Value>& args) {
791
  TLSWrap* wrap;
792
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
793
  CHECK_NOT_NULL(wrap->ssl_);
794
  wrap->enable_session_callbacks();
795
796
  // Clients don't use the HelloParser.
797
  if (wrap->is_client())
798
    return;
799
800
  crypto::NodeBIO::FromBIO(wrap->enc_in_)->set_initial(kMaxHelloLength);
801
  wrap->hello_parser_.Start(SSLWrap<TLSWrap>::OnClientHello,
802
                            OnClientHelloParseEnd,
803
                            wrap);
804
}
805
806
807
void TLSWrap::DestroySSL(const FunctionCallbackInfo<Value>& args) {
808
  TLSWrap* wrap;
809
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
810
811
  // If there is a write happening, mark it as finished.
812
  wrap->write_callback_scheduled_ = true;
813
814
  // And destroy
815
  wrap->InvokeQueued(UV_ECANCELED, "Canceled because of SSL destruction");
816
817
  // Destroy the SSL structure and friends
818
  wrap->SSLWrap<TLSWrap>::DestroySSL();
819
  wrap->enc_in_ = nullptr;
820
  wrap->enc_out_ = nullptr;
821
822
  if (wrap->stream_ != nullptr)
823
    wrap->stream_->RemoveStreamListener(wrap);
824
}
825
826
827
void TLSWrap::EnableCertCb(const FunctionCallbackInfo<Value>& args) {
828
  TLSWrap* wrap;
829
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
830
  wrap->WaitForCertCb(OnClientHelloParseEnd, wrap);
831
}
832
833
834
void TLSWrap::OnClientHelloParseEnd(void* arg) {
835
  TLSWrap* c = static_cast<TLSWrap*>(arg);
836
  c->Cycle();
837
}
838
839
840
void TLSWrap::GetServername(const FunctionCallbackInfo<Value>& args) {
841
  Environment* env = Environment::GetCurrent(args);
842
843
  TLSWrap* wrap;
844
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
845
846
  CHECK_NOT_NULL(wrap->ssl_);
847
848
  const char* servername = SSL_get_servername(wrap->ssl_.get(),
849
                                              TLSEXT_NAMETYPE_host_name);
850
  if (servername != nullptr) {
851
    args.GetReturnValue().Set(OneByteString(env->isolate(), servername));
852
  } else {
853
    args.GetReturnValue().Set(false);
854
  }
855
}
856
857
858
void TLSWrap::SetServername(const FunctionCallbackInfo<Value>& args) {
859
  Environment* env = Environment::GetCurrent(args);
860
861
  TLSWrap* wrap;
862
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
863
864
  CHECK_EQ(args.Length(), 1);
865
  CHECK(args[0]->IsString());
866
  CHECK(!wrap->started_);
867
  CHECK(wrap->is_client());
868
869
  CHECK_NOT_NULL(wrap->ssl_);
870
871
  node::Utf8Value servername(env->isolate(), args[0].As<String>());
872
  SSL_set_tlsext_host_name(wrap->ssl_.get(), *servername);
873
}
874
875
876
int TLSWrap::SelectSNIContextCallback(SSL* s, int* ad, void* arg) {
877
  TLSWrap* p = static_cast<TLSWrap*>(SSL_get_app_data(s));
878
  Environment* env = p->env();
879
880
  const char* servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
881
882
  if (servername == nullptr)
883
    return SSL_TLSEXT_ERR_OK;
884
885
  HandleScope handle_scope(env->isolate());
886
  Context::Scope context_scope(env->context());
887
888
  // Call the SNI callback and use its return value as context
889
  Local<Object> object = p->object();
890
  Local<Value> ctx;
891
892
  if (!object->Get(env->context(), env->sni_context_string()).ToLocal(&ctx))
893
    return SSL_TLSEXT_ERR_NOACK;
894
895
  // Not an object, probably undefined or null
896
  if (!ctx->IsObject())
897
    return SSL_TLSEXT_ERR_NOACK;
898
899
  Local<FunctionTemplate> cons = env->secure_context_constructor_template();
900
  if (!cons->HasInstance(ctx)) {
901
    // Failure: incorrect SNI context object
902
    Local<Value> err = Exception::TypeError(env->sni_context_err_string());
903
    p->MakeCallback(env->onerror_string(), 1, &err);
904
    return SSL_TLSEXT_ERR_NOACK;
905
  }
906
907
  p->sni_context_.Reset(env->isolate(), ctx);
908
909
  SecureContext* sc = Unwrap<SecureContext>(ctx.As<Object>());
910
  CHECK_NOT_NULL(sc);
911
  p->SetSNIContext(sc);
912
  return SSL_TLSEXT_ERR_OK;
913
}
914
915
916
void TLSWrap::GetWriteQueueSize(const FunctionCallbackInfo<Value>& info) {
917
  TLSWrap* wrap;
918
  ASSIGN_OR_RETURN_UNWRAP(&wrap, info.This());
919
920
  if (wrap->ssl_ == nullptr) {
921
    info.GetReturnValue().Set(0);
922
    return;
923
  }
924
925
  uint32_t write_queue_size = BIO_pending(wrap->enc_out_);
926
  info.GetReturnValue().Set(write_queue_size);
927
}
928
929
930
void TLSWrap::MemoryInfo(MemoryTracker* tracker) const {
931
  tracker->TrackField("error", error_);
932
  tracker->TrackField("pending_cleartext_input", pending_cleartext_input_);
933
  if (enc_in_ != nullptr)
934
    tracker->TrackField("enc_in", crypto::NodeBIO::FromBIO(enc_in_));
935
  if (enc_out_ != nullptr)
936
    tracker->TrackField("enc_out", crypto::NodeBIO::FromBIO(enc_out_));
937
}
938
939
940
1
void TLSWrap::Initialize(Local<Object> target,
941
                         Local<Value> unused,
942
                         Local<Context> context,
943
                         void* priv) {
944
1
  Environment* env = Environment::GetCurrent(context);
945
946
1
  env->SetMethod(target, "wrap", TLSWrap::Wrap);
947
948
1
  Local<FunctionTemplate> t = BaseObject::MakeLazilyInitializedJSTemplate(env);
949
  Local<String> tlsWrapString =
950
1
      FIXED_ONE_BYTE_STRING(env->isolate(), "TLSWrap");
951
1
  t->SetClassName(tlsWrapString);
952
953
  Local<FunctionTemplate> get_write_queue_size =
954
      FunctionTemplate::New(env->isolate(),
955
                            GetWriteQueueSize,
956
                            env->as_external(),
957
2
                            Signature::New(env->isolate(), t));
958
3
  t->PrototypeTemplate()->SetAccessorProperty(
959
      env->write_queue_size_string(),
960
      get_write_queue_size,
961
      Local<FunctionTemplate>(),
962
3
      static_cast<PropertyAttribute>(ReadOnly | DontDelete));
963
964
2
  t->Inherit(AsyncWrap::GetConstructorTemplate(env));
965
1
  env->SetProtoMethod(t, "receive", Receive);
966
1
  env->SetProtoMethod(t, "start", Start);
967
1
  env->SetProtoMethod(t, "setVerifyMode", SetVerifyMode);
968
1
  env->SetProtoMethod(t, "enableSessionCallbacks", EnableSessionCallbacks);
969
1
  env->SetProtoMethod(t, "destroySSL", DestroySSL);
970
1
  env->SetProtoMethod(t, "enableCertCb", EnableCertCb);
971
972
1
  StreamBase::AddMethods<TLSWrap>(env, t);
973
1
  SSLWrap<TLSWrap>::AddMethods(env, t);
974
975
1
  env->SetProtoMethod(t, "getServername", GetServername);
976
1
  env->SetProtoMethod(t, "setServername", SetServername);
977
978
  env->set_tls_wrap_constructor_function(
979
3
      t->GetFunction(env->context()).ToLocalChecked());
980
981
  target->Set(env->context(),
982
              tlsWrapString,
983
5
              t->GetFunction(env->context()).ToLocalChecked()).FromJust();
984
1
}
985
986
}  // namespace node
987
988
164
NODE_MODULE_CONTEXT_AWARE_INTERNAL(tls_wrap, node::TLSWrap::Initialize)