GCC Code Coverage Report
Directory: ../src/ Exec Total Coverage
File: /home/node-core-coverage/node-core-coverage/workdir/node/out/../src/tls_wrap.cc Lines: 388 416 93.3 %
Date: 2017-01-02 Branches: 191 279 68.5 %

Line Branch Exec Source
1
#include "tls_wrap.h"
2
#include "async-wrap.h"
3
#include "async-wrap-inl.h"
4
#include "node_buffer.h"  // Buffer
5
#include "node_crypto.h"  // SecureContext
6
#include "node_crypto_bio.h"  // NodeBIO
7
#include "node_crypto_clienthello.h"  // ClientHelloParser
8
#include "node_crypto_clienthello-inl.h"
9
#include "node_counters.h"
10
#include "node_internals.h"
11
#include "stream_base.h"
12
#include "stream_base-inl.h"
13
#include "util.h"
14
#include "util-inl.h"
15
16
namespace node {
17
18
using crypto::SecureContext;
19
using crypto::SSLWrap;
20
using v8::Context;
21
using v8::EscapableHandleScope;
22
using v8::Exception;
23
using v8::Function;
24
using v8::FunctionCallbackInfo;
25
using v8::FunctionTemplate;
26
using v8::Local;
27
using v8::Object;
28
using v8::String;
29
using v8::Value;
30
31
646
TLSWrap::TLSWrap(Environment* env,
32
                 Kind kind,
33
                 StreamBase* stream,
34
                 SecureContext* sc)
35
    : AsyncWrap(env,
36
646
                env->tls_wrap_constructor_function()
37
1938
                    ->NewInstance(env->context()).ToLocalChecked(),
38
                AsyncWrap::PROVIDER_TLSWRAP),
39
      SSLWrap<TLSWrap>(env, sc, kind),
40
      StreamBase(env),
41
      sc_(sc),
42
      stream_(stream),
43
      enc_in_(nullptr),
44
      enc_out_(nullptr),
45
      clear_in_(nullptr),
46
      write_size_(0),
47
      started_(false),
48
      established_(false),
49
      shutdown_(false),
50
      error_(nullptr),
51
      cycle_depth_(0),
52
2584
      eof_(false) {
53
1292
  node::Wrap(object(), this);
54
646
  MakeWeak(this);
55
56
  // sc comes from an Unwrap. Make sure it was assigned.
57
646
  CHECK_NE(sc, nullptr);
58
59
  // We've our own session callbacks
60
646
  SSL_CTX_sess_set_get_cb(sc_->ctx_, SSLWrap<TLSWrap>::GetSessionCallback);
61
646
  SSL_CTX_sess_set_new_cb(sc_->ctx_, SSLWrap<TLSWrap>::NewSessionCallback);
62
63
1292
  stream_->Consume();
64
1292
  stream_->set_after_write_cb({ OnAfterWriteImpl, this });
65
1292
  stream_->set_alloc_cb({ OnAllocImpl, this });
66
1292
  stream_->set_read_cb({ OnReadImpl, this });
67
68
1292
  set_alloc_cb({ OnAllocSelf, this });
69
646
  set_read_cb({ OnReadSelf, this });
70
71
646
  InitSSL();
72
646
}
73
74
75
372
TLSWrap::~TLSWrap() {
76
62
  enc_in_ = nullptr;
77
62
  enc_out_ = nullptr;
78
62
  delete clear_in_;
79
62
  clear_in_ = nullptr;
80
81
62
  sc_ = nullptr;
82
83
#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
84
124
  sni_context_.Reset();
85
#endif  // SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
86
87
62
  ClearError();
88
124
}
89
90
91
void TLSWrap::MakePending() {
92
2183
  write_item_queue_.MoveBack(&pending_write_items_);
93
}
94
95
96
3480
bool TLSWrap::InvokeQueued(int status, const char* error_str) {
97
6960
  if (pending_write_items_.IsEmpty())
98
    return false;
99
100
  // Process old queue
101
908
  WriteItemList queue;
102
908
  pending_write_items_.MoveBack(&queue);
103
1817
  while (WriteItem* wi = queue.PopFront()) {
104
909
    wi->w_->Done(status, error_str);
105
1818
    delete wi;
106
  }
107
108
  return true;
109
}
110
111
112
2
void TLSWrap::NewSessionDoneCb() {
113
2
  Cycle();
114
2
}
115
116
117
646
void TLSWrap::InitSSL() {
118
  // Initialize SSL
119
646
  enc_in_ = NodeBIO::New();
120
646
  enc_out_ = NodeBIO::New();
121
1292
  NodeBIO::FromBIO(enc_in_)->AssignEnvironment(env());
122
1292
  NodeBIO::FromBIO(enc_out_)->AssignEnvironment(env());
123
124
646
  SSL_set_bio(ssl_, enc_in_, enc_out_);
125
126
  // NOTE: This could be overriden in SetVerifyMode
127
646
  SSL_set_verify(ssl_, SSL_VERIFY_NONE, crypto::VerifyCallback);
128
129
#ifdef SSL_MODE_RELEASE_BUFFERS
130
646
  long mode = SSL_get_mode(ssl_);  // NOLINT(runtime/int)
131
646
  SSL_set_mode(ssl_, mode | SSL_MODE_RELEASE_BUFFERS);
132
#endif  // SSL_MODE_RELEASE_BUFFERS
133
134
646
  SSL_set_app_data(ssl_, this);
135
646
  SSL_set_info_callback(ssl_, SSLInfoCallback);
136
137
#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
138
646
  if (is_server()) {
139
343
    SSL_CTX_set_tlsext_servername_callback(sc_->ctx_, SelectSNIContextCallback);
140
  }
141
#endif  // SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
142
143
646
  InitNPN(sc_);
144
145
646
  SSL_set_cert_cb(ssl_, SSLWrap<TLSWrap>::SSLCertCallback, this);
146
147
646
  if (is_server()) {
148
343
    SSL_set_accept_state(ssl_);
149
303
  } else if (is_client()) {
150
    // Enough space for server response (hello, cert)
151
909
    NodeBIO::FromBIO(enc_in_)->set_initial(kInitialClientBufferLength);
152
303
    SSL_set_connect_state(ssl_);
153
  } else {
154
    // Unexpected
155
    ABORT();
156
  }
157
158
  // Initialize ring for queud clear data
159
1292
  clear_in_ = new NodeBIO();
160
646
  clear_in_->AssignEnvironment(env());
161
646
}
162
163
164
646
void TLSWrap::Wrap(const FunctionCallbackInfo<Value>& args) {
165
646
  Environment* env = Environment::GetCurrent(args);
166
167

1938
  if (args.Length() < 1 || !args[0]->IsObject()) {
168
    return env->ThrowTypeError(
169
        "First argument should be a StreamWrap instance");
170
  }
171

1938
  if (args.Length() < 2 || !args[1]->IsObject()) {
172
    return env->ThrowTypeError(
173
        "Second argument should be a SecureContext instance");
174
  }
175

1938
  if (args.Length() < 3 || !args[2]->IsBoolean())
176
    return env->ThrowTypeError("Third argument should be boolean");
177
178
1292
  Local<External> stream_obj = args[0].As<External>();
179
1292
  Local<Object> sc = args[1].As<Object>();
180
1292
  Kind kind = args[2]->IsTrue() ? SSLWrap<TLSWrap>::kServer :
181
646
                                  SSLWrap<TLSWrap>::kClient;
182
183
646
  StreamBase* stream = static_cast<StreamBase*>(stream_obj->Value());
184
646
  CHECK_NE(stream, nullptr);
185
186
646
  TLSWrap* res = new TLSWrap(env, kind, stream, Unwrap<SecureContext>(sc));
187
188
2584
  args.GetReturnValue().Set(res->object());
189
}
190
191
192
3
void TLSWrap::Receive(const FunctionCallbackInfo<Value>& args) {
193
  TLSWrap* wrap;
194
3
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
195
196
3
  CHECK(Buffer::HasInstance(args[0]));
197
3
  char* data = Buffer::Data(args[0]);
198
3
  size_t len = Buffer::Length(args[0]);
199
200
  uv_buf_t buf;
201
202
  // Copy given buffer entirely or partiall if handle becomes closed
203


9
  while (len > 0 && wrap->IsAlive() && !wrap->IsClosing()) {
204
6
    wrap->stream_->OnAlloc(len, &buf);
205
3
    size_t copy = buf.len > len ? len : buf.len;
206
6
    memcpy(buf.base, data, copy);
207
3
    buf.len = copy;
208
6
    wrap->stream_->OnRead(buf.len, &buf);
209
210
3
    data += copy;
211
3
    len -= copy;
212
  }
213
}
214
215
216
292
void TLSWrap::Start(const FunctionCallbackInfo<Value>& args) {
217
292
  Environment* env = Environment::GetCurrent(args);
218
219
  TLSWrap* wrap;
220
292
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
221
222
292
  if (wrap->started_)
223
    return env->ThrowError("Already started.");
224
292
  wrap->started_ = true;
225
226
  // Send ClientHello handshake
227
292
  CHECK(wrap->is_client());
228
292
  wrap->ClearOut();
229
292
  wrap->EncOut();
230
}
231
232
233
12768
void TLSWrap::SSLInfoCallback(const SSL* ssl_, int where, int ret) {
234
12768
  if (!(where & (SSL_CB_HANDSHAKE_START | SSL_CB_HANDSHAKE_DONE)))
235
    return;
236
237
  // Be compatible with older versions of OpenSSL. SSL_get_app_data() wants
238
  // a non-const SSL* in OpenSSL <= 0.9.7e.
239
1238
  SSL* ssl = const_cast<SSL*>(ssl_);
240
1238
  TLSWrap* c = static_cast<TLSWrap*>(SSL_get_app_data(ssl));
241
1238
  Environment* env = c->env();
242
2476
  Local<Object> object = c->object();
243
244
1238
  if (where & SSL_CB_HANDSHAKE_START) {
245
1272
    Local<Value> callback = object->Get(env->onhandshakestart_string());
246
636
    if (callback->IsFunction()) {
247
636
      c->MakeCallback(callback.As<Function>(), 0, nullptr);
248
    }
249
  }
250
251
1238
  if (where & SSL_CB_HANDSHAKE_DONE) {
252
602
    c->established_ = true;
253
1204
    Local<Value> callback = object->Get(env->onhandshakedone_string());
254
602
    if (callback->IsFunction()) {
255
602
      c->MakeCallback(callback.As<Function>(), 0, nullptr);
256
    }
257
  }
258
}
259
260
261
5988
void TLSWrap::EncOut() {
262
  // Ignore cycling data if ClientHello wasn't yet parsed
263
5988
  if (!hello_parser_.IsEnded())
264
3682
    return;
265
266
  // Write in progress
267
5988
  if (write_size_ != 0)
268
    return;
269
270
  // Wait for `newSession` callback to be invoked
271
5320
  if (is_waiting_new_session())
272
    return;
273
274
  // Split-off queue
275

8844
  if (established_ && !write_item_queue_.IsEmpty())
276
    MakePending();
277
278
5319
  if (ssl_ == nullptr)
279
    return;
280
281
  // No data to write
282
5319
  if (BIO_pending(enc_out_) == 0) {
283
3013
    if (clear_in_->Length() == 0)
284
2827
      InvokeQueued(0);
285
    return;
286
  }
287
288
  char* data[kSimultaneousBufferCount];
289
  size_t size[arraysize(data)];
290
2306
  size_t count = arraysize(data);
291
4612
  write_size_ = NodeBIO::FromBIO(enc_out_)->PeekMultiple(data, size, &count);
292

2306
  CHECK(write_size_ != 0 && count != 0);
293
294
  Local<Object> req_wrap_obj =
295
4612
      env()->write_wrap_constructor_function()
296
11530
          ->NewInstance(env()->context()).ToLocalChecked();
297
2306
  WriteWrap* write_req = WriteWrap::New(env(),
298
                                        req_wrap_obj,
299
                                        this,
300
2306
                                        EncOutCb);
301
302
  uv_buf_t buf[arraysize(data)];
303
4989
  for (size_t i = 0; i < count; i++)
304
2683
    buf[i] = uv_buf_init(data[i], size[i]);
305
2306
  int err = stream_->DoWrite(write_req, buf, count, nullptr);
306
307
  // Ignore errors, this should be already handled in js
308
2306
  if (err) {
309
13
    write_req->Dispose();
310
13
    InvokeQueued(err);
311
  } else {
312
    NODE_COUNT_NET_BYTES_SENT(write_size_);
313
  }
314
}
315
316
317
2290
void TLSWrap::EncOutCb(WriteWrap* req_wrap, int status) {
318
4580
  TLSWrap* wrap = req_wrap->wrap()->Cast<TLSWrap>();
319
2290
  req_wrap->Dispose();
320
321
  // We should not be getting here after `DestroySSL`, because all queued writes
322
  // must be invoked with UV_ECANCELED
323
2290
  CHECK_NE(wrap->ssl_, nullptr);
324
325
  // Handle error
326
2290
  if (status) {
327
    // Ignore errors after shutdown
328
1
    if (wrap->shutdown_)
329
      return;
330
331
    // Notify about error
332
1
    wrap->InvokeQueued(status);
333
1
    return;
334
  }
335
336
  // Commit
337
4578
  NodeBIO::FromBIO(wrap->enc_out_)->Read(nullptr, wrap->write_size_);
338
339
  // Ensure that the progress will be made and `InvokeQueued` will be called.
340
2289
  wrap->ClearIn();
341
342
  // Try writing more data
343
2289
  wrap->write_size_ = 0;
344
2289
  wrap->EncOut();
345
}
346
347
348
3067
Local<Value> TLSWrap::GetSSLError(int status, int* err, const char** msg) {
349
6134
  EscapableHandleScope scope(env()->isolate());
350
351
  // ssl_ is already destroyed in reading EOF by close notify alert.
352
3067
  if (ssl_ == nullptr)
353
    return Local<Value>();
354
355
3067
  *err = SSL_get_error(ssl_, status);
356
3067
  switch (*err) {
357
    case SSL_ERROR_NONE:
358
    case SSL_ERROR_WANT_READ:
359
    case SSL_ERROR_WANT_WRITE:
360
    case SSL_ERROR_WANT_X509_LOOKUP:
361
      break;
362
    case SSL_ERROR_ZERO_RETURN:
363
780
      return scope.Escape(env()->zero_return_string());
364
      break;
365
    default:
366
      {
367
21
        CHECK(*err == SSL_ERROR_SSL || *err == SSL_ERROR_SYSCALL);
368
369
21
        BIO* bio = BIO_new(BIO_s_mem());
370
21
        ERR_print_errors(bio);
371
372
        BUF_MEM* mem;
373
21
        BIO_get_mem_ptr(bio, &mem);
374
375
        Local<String> message =
376
21
            OneByteString(env()->isolate(), mem->data, mem->length);
377
21
        Local<Value> exception = Exception::Error(message);
378
379
21
        if (msg != nullptr) {
380
3
          CHECK_EQ(*msg, nullptr);
381
3
          char* const buf = new char[mem->length + 1];
382
6
          memcpy(buf, mem->data, mem->length);
383
3
          buf[mem->length] = '\0';
384
3
          *msg = buf;
385
        }
386
21
        BIO_free_all(bio);
387
388
21
        return scope.Escape(exception);
389
      }
390
  }
391
2851
  return Local<Value>();
392
}
393
394
395
2697
void TLSWrap::ClearOut() {
396
  // Ignore cycling data if ClientHello wasn't yet parsed
397
2697
  if (!hello_parser_.IsEnded())
398
197
    return;
399
400
  // No reads after EOF
401
2696
  if (eof_)
402
    return;
403
404
2695
  if (ssl_ == nullptr)
405
    return;
406
407
  crypto::MarkPopErrorOnReturn mark_pop_error_on_return;
408
409
  char out[kClearOutChunkSize];
410
  int read;
411
  for (;;) {
412
3639
    read = SSL_read(ssl_, out, sizeof(out));
413
414
3638
    if (read <= 0)
415
      break;
416
417
    char* current = out;
418
2838
    while (read > 0) {
419
948
      int avail = read;
420
421
      uv_buf_t buf;
422
1896
      OnAlloc(avail, &buf);
423
948
      if (static_cast<int>(buf.len) < avail)
424
2
        avail = buf.len;
425
1896
      memcpy(buf.base, current, avail);
426
1894
      OnRead(avail, &buf);
427
428
946
      read -= avail;
429
946
      current += avail;
430
    }
431
  }
432
433
2692
  int flags = SSL_get_shutdown(ssl_);
434

2692
  if (!eof_ && flags & SSL_RECEIVED_SHUTDOWN) {
435
230
    eof_ = true;
436
230
    OnRead(UV_EOF, nullptr);
437
  }
438
439
  // We need to check whether an error occurred or the connection was
440
  // shutdown cleanly (SSL_ERROR_ZERO_RETURN) even when read == 0.
441
  // See node#1642 and SSL_read(3SSL) for details.
442
2692
  if (read <= 0) {
443
    int err;
444
2692
    Local<Value> arg = GetSSLError(read, &err, nullptr);
445
446
    // Ignore ZERO_RETURN after EOF, it is basically not a error
447

2692
    if (err == SSL_ERROR_ZERO_RETURN && eof_)
448
195
      return;
449
450
2497
    if (!arg.IsEmpty()) {
451
      // When TLS Alert are stored in wbio,
452
      // it should be flushed to socket before destroyed.
453
18
      if (BIO_pending(enc_out_) != 0)
454
9
        EncOut();
455
456
36
      MakeCallback(env()->onerror_string(), 1, &arg);
457
    }
458
  }
459
}
460
461
462
5394
bool TLSWrap::ClearIn() {
463
  // Ignore cycling data if ClientHello wasn't yet parsed
464
5394
  if (!hello_parser_.IsEnded())
465
    return false;
466
467
5394
  if (ssl_ == nullptr)
468
    return false;
469
470
  crypto::MarkPopErrorOnReturn mark_pop_error_on_return;
471
472
5394
  int written = 0;
473
5576
  while (clear_in_->Length() > 0) {
474
369
    size_t avail = 0;
475
369
    char* data = clear_in_->Peek(&avail);
476
369
    written = SSL_write(ssl_, data, avail);
477

369
    CHECK(written == -1 || written == static_cast<int>(avail));
478
369
    if (written == -1)
479
      break;
480
91
    clear_in_->Read(nullptr, avail);
481
  }
482
483
  // All written
484
5394
  if (clear_in_->Length() == 0) {
485
5116
    CHECK_GE(written, 0);
486
    return true;
487
  }
488
489
  // Error or partial write
490
  int err;
491
278
  const char* error_str = nullptr;
492
278
  Local<Value> arg = GetSSLError(written, &err, &error_str);
493
278
  if (!arg.IsEmpty()) {
494
3
    MakePending();
495
3
    InvokeQueued(UV_EPROTO, error_str);
496
3
    delete[] error_str;
497
3
    clear_in_->Reset();
498
  }
499
500
  return false;
501
}
502
503
504
2290
void* TLSWrap::Cast() {
505
2290
  return reinterpret_cast<void*>(this);
506
}
507
508
509
2424
AsyncWrap* TLSWrap::GetAsyncWrap() {
510
2424
  return static_cast<AsyncWrap*>(this);
511
}
512
513
514
439
bool TLSWrap::IsIPCPipe() {
515
439
  return stream_->IsIPCPipe();
516
}
517
518
519
2
int TLSWrap::GetFD() {
520
2
  return stream_->GetFD();
521
}
522
523
524
1623
bool TLSWrap::IsAlive() {
525

1623
  return ssl_ != nullptr && stream_->IsAlive();
526
}
527
528
529
3
bool TLSWrap::IsClosing() {
530
3
  return stream_->IsClosing();
531
}
532
533
534
351
int TLSWrap::ReadStart() {
535
351
  return stream_->ReadStart();
536
}
537
538
539
64
int TLSWrap::ReadStop() {
540
64
  return stream_->ReadStop();
541
}
542
543
544
1816
const char* TLSWrap::Error() const {
545
1816
  return error_;
546
}
547
548
549
void TLSWrap::ClearError() {
550

62
  delete[] error_;
551
62
  error_ = nullptr;
552
}
553
554
555
911
int TLSWrap::DoWrite(WriteWrap* w,
556
                     uv_buf_t* bufs,
557
                     size_t count,
558
                     uv_stream_t* send_handle) {
559
911
  CHECK_EQ(send_handle, nullptr);
560
911
  CHECK_NE(ssl_, nullptr);
561
562
  bool empty = true;
563
564
  // Empty writes should not go through encryption process
565
  size_t i;
566
915
  for (i = 0; i < count; i++)
567
911
    if (bufs[i].len > 0) {
568
      empty = false;
569
      break;
570
    }
571
911
  if (empty) {
572
2
    ClearOut();
573
    // However, if there is any data that should be written to the socket,
574
    // the callback should not be invoked immediately
575
2
    if (BIO_pending(enc_out_) == 0)
576
      return stream_->DoWrite(w, bufs, count, send_handle);
577
  }
578
579
  // Queue callback to execute it on next tick
580
2733
  write_item_queue_.PushBack(new WriteItem(w));
581
1822
  w->Dispatched();
582
583
  // Write queued data
584
911
  if (empty) {
585
2
    EncOut();
586
2
    return 0;
587
  }
588
589
  // Process enqueued data first
590
909
  if (!ClearIn()) {
591
    // If there're still data to process - enqueue current one
592
    for (i = 0; i < count; i++)
593
      clear_in_->Write(bufs[i].base, bufs[i].len);
594
    return 0;
595
  }
596
597
909
  if (ssl_ == nullptr) {
598
    ClearError();
599
600
    static char msg[] = "Write after DestroySSL";
601
    char* tmp = new char[sizeof(msg)];
602
    memcpy(tmp, msg, sizeof(msg));
603
    error_ = tmp;
604
    return UV_EPROTO;
605
  }
606
607
  crypto::MarkPopErrorOnReturn mark_pop_error_on_return;
608
609
909
  int written = 0;
610
5437
  for (i = 0; i < count; i++) {
611
4625
    written = SSL_write(ssl_, bufs[i].base, bufs[i].len);
612

4625
    CHECK(written == -1 || written == static_cast<int>(bufs[i].len));
613
4625
    if (written == -1)
614
      break;
615
  }
616
617
909
  if (i != count) {
618
    int err;
619
97
    Local<Value> arg = GetSSLError(written, &err, &error_);
620
97
    if (!arg.IsEmpty())
621
      return UV_EPROTO;
622
623
    // No errors, queue rest
624
291
    for (; i < count; i++)
625
97
      clear_in_->Write(bufs[i].base, bufs[i].len);
626
  }
627
628
  // Try writing data immediately
629
909
  EncOut();
630
631
909
  return 0;
632
}
633
634
635
11
void TLSWrap::OnAfterWriteImpl(WriteWrap* w, void* ctx) {
636
  // Intentionally empty
637
11
}
638
639
640
2379
void TLSWrap::OnAllocImpl(size_t suggested_size, uv_buf_t* buf, void* ctx) {
641
2379
  TLSWrap* wrap = static_cast<TLSWrap*>(ctx);
642
643
2379
  if (wrap->ssl_ == nullptr) {
644
    *buf = uv_buf_init(nullptr, 0);
645
    return;
646
  }
647
648
2379
  size_t size = 0;
649
4758
  buf->base = NodeBIO::FromBIO(wrap->enc_in_)->PeekWritable(&size);
650
2379
  buf->len = size;
651
}
652
653
654
2383
void TLSWrap::OnReadImpl(ssize_t nread,
655
                         const uv_buf_t* buf,
656
                         uv_handle_type pending,
657
                         void* ctx) {
658
2383
  TLSWrap* wrap = static_cast<TLSWrap*>(ctx);
659
2383
  wrap->DoRead(nread, buf, pending);
660
2380
}
661
662
663
790
void TLSWrap::OnAllocSelf(size_t suggested_size, uv_buf_t* buf, void* ctx) {
664
790
  buf->base = node::Malloc(suggested_size);
665
790
  buf->len = suggested_size;
666
790
}
667
668
669
1225
void TLSWrap::OnReadSelf(ssize_t nread,
670
                         const uv_buf_t* buf,
671
                         uv_handle_type pending,
672
                         void* ctx) {
673
1225
  TLSWrap* wrap = static_cast<TLSWrap*>(ctx);
674
1225
  Local<Object> buf_obj;
675
1225
  if (buf != nullptr)
676
1594
    buf_obj = Buffer::New(wrap->env(), buf->base, buf->len).ToLocalChecked();
677
1225
  wrap->EmitData(nread, buf_obj, Local<Object>());
678
1223
}
679
680
681
2383
void TLSWrap::DoRead(ssize_t nread,
682
                     const uv_buf_t* buf,
683
                     uv_handle_type pending) {
684
2383
  if (nread < 0)  {
685
    // Error should be emitted only after all data was read
686
207
    ClearOut();
687
688
    // Ignore EOF if received close_notify
689
207
    if (nread == UV_EOF) {
690
207
      if (eof_)
691
        return;
692
206
      eof_ = true;
693
    }
694
695
206
    OnRead(nread, nullptr);
696
    return;
697
  }
698
699
  // Only client connections can receive data
700
2176
  if (ssl_ == nullptr) {
701
    OnRead(UV_EPROTO, nullptr);
702
    return;
703
  }
704
705
  // Commit read data
706
4352
  NodeBIO* enc_in = NodeBIO::FromBIO(enc_in_);
707
2176
  enc_in->Commit(nread);
708
709
  // Parse ClientHello first
710
2176
  if (!hello_parser_.IsEnded()) {
711
14
    size_t avail = 0;
712
14
    uint8_t* data = reinterpret_cast<uint8_t*>(enc_in->Peek(&avail));
713

14
    CHECK(avail == 0 || data != nullptr);
714
14
    return hello_parser_.Parse(data, avail);
715
  }
716
717
  // Cycle OpenSSL's state
718
2162
  Cycle();
719
}
720
721
722
294
int TLSWrap::DoShutdown(ShutdownWrap* req_wrap) {
723
  crypto::MarkPopErrorOnReturn mark_pop_error_on_return;
724
725

294
  if (ssl_ != nullptr && SSL_shutdown(ssl_) == 0)
726
294
    SSL_shutdown(ssl_);
727
728
294
  shutdown_ = true;
729
294
  EncOut();
730
588
  return stream_->DoShutdown(req_wrap);
731
}
732
733
734
364
void TLSWrap::SetVerifyMode(const FunctionCallbackInfo<Value>& args) {
735
364
  Environment* env = Environment::GetCurrent(args);
736
737
  TLSWrap* wrap;
738
364
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
739
740


1456
  if (args.Length() < 2 || !args[0]->IsBoolean() || !args[1]->IsBoolean())
741
    return env->ThrowTypeError("Bad arguments, expected two booleans");
742
743
364
  if (wrap->ssl_ == nullptr)
744
    return env->ThrowTypeError("SetVerifyMode after destroySSL");
745
746
  int verify_mode;
747
364
  if (wrap->is_server()) {
748
61
    bool request_cert = args[0]->IsTrue();
749
61
    if (!request_cert) {
750
      // Note reject_unauthorized ignored.
751
      verify_mode = SSL_VERIFY_NONE;
752
    } else {
753
60
      bool reject_unauthorized = args[1]->IsTrue();
754
60
      verify_mode = SSL_VERIFY_PEER;
755
60
      if (reject_unauthorized)
756
35
        verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
757
    }
758
  } else {
759
    // Note request_cert and reject_unauthorized are ignored for clients.
760
    verify_mode = SSL_VERIFY_NONE;
761
  }
762
763
  // Always allow a connection. We'll reject in javascript.
764
364
  SSL_set_verify(wrap->ssl_, verify_mode, crypto::VerifyCallback);
765
}
766
767
768
14
void TLSWrap::EnableSessionCallbacks(
769
    const FunctionCallbackInfo<Value>& args) {
770
  TLSWrap* wrap;
771
14
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
772
14
  if (wrap->ssl_ == nullptr) {
773
    return wrap->env()->ThrowTypeError(
774
        "EnableSessionCallbacks after destroySSL");
775
  }
776
14
  wrap->enable_session_callbacks();
777
42
  NodeBIO::FromBIO(wrap->enc_in_)->set_initial(kMaxHelloLength);
778
14
  wrap->hello_parser_.Start(SSLWrap<TLSWrap>::OnClientHello,
779
                            OnClientHelloParseEnd,
780
                            wrap);
781
}
782
783
784
636
void TLSWrap::DestroySSL(const FunctionCallbackInfo<Value>& args) {
785
  TLSWrap* wrap;
786
636
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
787
788
  // Move all writes to pending
789
1272
  wrap->MakePending();
790
791
  // And destroy
792
636
  wrap->InvokeQueued(UV_ECANCELED, "Canceled because of SSL destruction");
793
794
  // Destroy the SSL structure and friends
795
636
  wrap->SSLWrap<TLSWrap>::DestroySSL();
796
797
636
  delete wrap->clear_in_;
798
636
  wrap->clear_in_ = nullptr;
799
}
800
801
802
21
void TLSWrap::EnableCertCb(const FunctionCallbackInfo<Value>& args) {
803
  TLSWrap* wrap;
804
21
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
805
21
  wrap->WaitForCertCb(OnClientHelloParseEnd, wrap);
806
}
807
808
809
32
void TLSWrap::OnClientHelloParseEnd(void* arg) {
810
32
  TLSWrap* c = static_cast<TLSWrap*>(arg);
811
32
  c->Cycle();
812
32
}
813
814
815
#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
816
322
void TLSWrap::GetServername(const FunctionCallbackInfo<Value>& args) {
817
322
  Environment* env = Environment::GetCurrent(args);
818
819
  TLSWrap* wrap;
820
322
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
821
822
322
  CHECK_NE(wrap->ssl_, nullptr);
823
824
  const char* servername = SSL_get_servername(wrap->ssl_,
825
322
                                              TLSEXT_NAMETYPE_host_name);
826
322
  if (servername != nullptr) {
827
222
    args.GetReturnValue().Set(OneByteString(env->isolate(), servername));
828
  } else {
829
422
    args.GetReturnValue().Set(false);
830
  }
831
}
832
833
834
108
void TLSWrap::SetServername(const FunctionCallbackInfo<Value>& args) {
835
108
  Environment* env = Environment::GetCurrent(args);
836
837
  TLSWrap* wrap;
838
108
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
839
840

432
  if (args.Length() < 1 || !args[0]->IsString())
841
    return env->ThrowTypeError("First argument should be a string");
842
843
108
  if (wrap->started_)
844
    return env->ThrowError("Already started.");
845
846
108
  if (!wrap->is_client())
847
    return;
848
849
108
  CHECK_NE(wrap->ssl_, nullptr);
850
851
#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
852
432
  node::Utf8Value servername(env->isolate(), args[0].As<String>());
853
108
  SSL_set_tlsext_host_name(wrap->ssl_, *servername);
854
#endif  // SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
855
}
856
857
858
333
int TLSWrap::SelectSNIContextCallback(SSL* s, int* ad, void* arg) {
859
333
  TLSWrap* p = static_cast<TLSWrap*>(SSL_get_app_data(s));
860
333
  Environment* env = p->env();
861
862
333
  const char* servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
863
864
333
  if (servername == nullptr)
865
    return SSL_TLSEXT_ERR_OK;
866
867
  // Call the SNI callback and use its return value as context
868
228
  Local<Object> object = p->object();
869
228
  Local<Value> ctx = object->Get(env->sni_context_string());
870
871
  // Not an object, probably undefined or null
872
114
  if (!ctx->IsObject())
873
    return SSL_TLSEXT_ERR_NOACK;
874
875
  Local<FunctionTemplate> cons = env->secure_context_constructor_template();
876
  if (!cons->HasInstance(ctx)) {
877
    // Failure: incorrect SNI context object
878
    Local<Value> err = Exception::TypeError(env->sni_context_err_string());
879
    p->MakeCallback(env->onerror_string(), 1, &err);
880
    return SSL_TLSEXT_ERR_NOACK;
881
  }
882
883
  p->sni_context_.Reset();
884
  p->sni_context_.Reset(env->isolate(), ctx);
885
886
  SecureContext* sc = Unwrap<SecureContext>(ctx.As<Object>());
887
  CHECK_NE(sc, nullptr);
888
  p->SetSNIContext(sc);
889
  return SSL_TLSEXT_ERR_OK;
890
}
891
#endif  // SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
892
893
894
148
void TLSWrap::Initialize(Local<Object> target,
895
                         Local<Value> unused,
896
                         Local<Context> context) {
897
148
  Environment* env = Environment::GetCurrent(context);
898
899
148
  env->SetMethod(target, "wrap", TLSWrap::Wrap);
900
901
647
  auto constructor = [](const FunctionCallbackInfo<Value>& args) {
902
647
    args.This()->SetAlignedPointerInInternalField(0, nullptr);
903
1294
  };
904
296
  auto t = env->NewFunctionTemplate(constructor);
905
296
  t->InstanceTemplate()->SetInternalFieldCount(1);
906
148
  t->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "TLSWrap"));
907
908
148
  env->SetProtoMethod(t, "receive", Receive);
909
148
  env->SetProtoMethod(t, "start", Start);
910
148
  env->SetProtoMethod(t, "setVerifyMode", SetVerifyMode);
911
148
  env->SetProtoMethod(t, "enableSessionCallbacks", EnableSessionCallbacks);
912
148
  env->SetProtoMethod(t, "destroySSL", DestroySSL);
913
148
  env->SetProtoMethod(t, "enableCertCb", EnableCertCb);
914
915
148
  StreamBase::AddMethods<TLSWrap>(env, t, StreamBase::kFlagHasWritev);
916
148
  SSLWrap<TLSWrap>::AddMethods(env, t);
917
918
#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
919
148
  env->SetProtoMethod(t, "getServername", GetServername);
920
148
  env->SetProtoMethod(t, "setServername", SetServername);
921
#endif  // SSL_CRT_SET_TLSEXT_SERVERNAME_CB
922
923
148
  env->set_tls_wrap_constructor_template(t);
924
148
  env->set_tls_wrap_constructor_function(t->GetFunction());
925
926
740
  target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "TLSWrap"),
927
148
              t->GetFunction());
928
148
}
929
930
}  // namespace node
931
932
1757
NODE_MODULE_CONTEXT_AWARE_BUILTIN(tls_wrap, node::TLSWrap::Initialize)