GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/node-core-coverage/node-core-coverage/workdir/node/out/../src/tls_wrap.cc Lines: 371 416 89.2 %
Date: 2016-09-05 Branches: 186 281 66.2 %

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
593
TLSWrap::TLSWrap(Environment* env,
32
                 Kind kind,
33
                 StreamBase* stream,
34
                 SecureContext* sc)
35
    : AsyncWrap(env,
36
593
                env->tls_wrap_constructor_function()
37
1779
                    ->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
2372
      eof_(false) {
53
1186
  node::Wrap(object(), this);
54
593
  MakeWeak(this);
55
56
  // sc comes from an Unwrap. Make sure it was assigned.
57
593
  CHECK_NE(sc, nullptr);
58
59
  // We've our own session callbacks
60
593
  SSL_CTX_sess_set_get_cb(sc_->ctx_, SSLWrap<TLSWrap>::GetSessionCallback);
61
593
  SSL_CTX_sess_set_new_cb(sc_->ctx_, SSLWrap<TLSWrap>::NewSessionCallback);
62
63
1186
  stream_->Consume();
64
1186
  stream_->set_after_write_cb({ OnAfterWriteImpl, this });
65
1186
  stream_->set_alloc_cb({ OnAllocImpl, this });
66
1186
  stream_->set_read_cb({ OnReadImpl, this });
67
68
1186
  set_alloc_cb({ OnAllocSelf, this });
69
593
  set_read_cb({ OnReadSelf, this });
70
71
593
  InitSSL();
72
593
}
73
74
75
TLSWrap::~TLSWrap() {
76
  enc_in_ = nullptr;
77
  enc_out_ = nullptr;
78
  delete clear_in_;
79
  clear_in_ = nullptr;
80
81
  sc_ = nullptr;
82
83
#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
84
  sni_context_.Reset();
85
#endif  // SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
86
87
  ClearError();
88
}
89
90
91
void TLSWrap::MakePending() {
92
912
  write_item_queue_.MoveBack(&pending_write_items_);
93
}
94
95
96
2785
bool TLSWrap::InvokeQueued(int status, const char* error_str) {
97
5570
  if (pending_write_items_.IsEmpty())
98
    return false;
99
100
  // Process old queue
101
906
  WriteItemList queue;
102
906
  pending_write_items_.MoveBack(&queue);
103
1813
  while (WriteItem* wi = queue.PopFront()) {
104
907
    wi->w_->Done(status, error_str);
105
1814
    delete wi;
106
  }
107
108
  return true;
109
}
110
111
112
2
void TLSWrap::NewSessionDoneCb() {
113
2
  Cycle();
114
2
}
115
116
117
593
void TLSWrap::InitSSL() {
118
  // Initialize SSL
119
593
  enc_in_ = NodeBIO::New();
120
593
  enc_out_ = NodeBIO::New();
121
1186
  NodeBIO::FromBIO(enc_in_)->AssignEnvironment(env());
122
1186
  NodeBIO::FromBIO(enc_out_)->AssignEnvironment(env());
123
124
593
  SSL_set_bio(ssl_, enc_in_, enc_out_);
125
126
  // NOTE: This could be overriden in SetVerifyMode
127
593
  SSL_set_verify(ssl_, SSL_VERIFY_NONE, crypto::VerifyCallback);
128
129
#ifdef SSL_MODE_RELEASE_BUFFERS
130
593
  long mode = SSL_get_mode(ssl_);  // NOLINT(runtime/int)
131
593
  SSL_set_mode(ssl_, mode | SSL_MODE_RELEASE_BUFFERS);
132
#endif  // SSL_MODE_RELEASE_BUFFERS
133
134
593
  SSL_set_app_data(ssl_, this);
135
593
  SSL_set_info_callback(ssl_, SSLInfoCallback);
136
137
#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
138
593
  if (is_server()) {
139
316
    SSL_CTX_set_tlsext_servername_callback(sc_->ctx_, SelectSNIContextCallback);
140
  }
141
#endif  // SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
142
143
593
  InitNPN(sc_);
144
145
593
  SSL_set_cert_cb(ssl_, SSLWrap<TLSWrap>::SSLCertCallback, this);
146
147
593
  if (is_server()) {
148
316
    SSL_set_accept_state(ssl_);
149
277
  } else if (is_client()) {
150
    // Enough space for server response (hello, cert)
151
831
    NodeBIO::FromBIO(enc_in_)->set_initial(kInitialClientBufferLength);
152
277
    SSL_set_connect_state(ssl_);
153
  } else {
154
    // Unexpected
155
    ABORT();
156
  }
157
158
  // Initialize ring for queud clear data
159
1186
  clear_in_ = new NodeBIO();
160
593
  clear_in_->AssignEnvironment(env());
161
593
}
162
163
164
593
void TLSWrap::Wrap(const FunctionCallbackInfo<Value>& args) {
165
593
  Environment* env = Environment::GetCurrent(args);
166
167

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

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

1779
  if (args.Length() < 3 || !args[2]->IsBoolean())
176
    return env->ThrowTypeError("Third argument should be boolean");
177
178
1186
  Local<External> stream_obj = args[0].As<External>();
179
1186
  Local<Object> sc = args[1].As<Object>();
180
1186
  Kind kind = args[2]->IsTrue() ? SSLWrap<TLSWrap>::kServer :
181
593
                                  SSLWrap<TLSWrap>::kClient;
182
183
593
  StreamBase* stream = static_cast<StreamBase*>(stream_obj->Value());
184
593
  CHECK_NE(stream, nullptr);
185
186
593
  TLSWrap* res = new TLSWrap(env, kind, stream, Unwrap<SecureContext>(sc));
187
188
2372
  args.GetReturnValue().Set(res->object());
189
}
190
191
192
2
void TLSWrap::Receive(const FunctionCallbackInfo<Value>& args) {
193
  TLSWrap* wrap;
194
2
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
195
196
2
  CHECK(Buffer::HasInstance(args[0]));
197
2
  char* data = Buffer::Data(args[0]);
198
2
  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


6
  while (len > 0 && wrap->IsAlive() && !wrap->IsClosing()) {
204
4
    wrap->stream_->OnAlloc(len, &buf);
205
2
    size_t copy = buf.len > len ? len : buf.len;
206
4
    memcpy(buf.base, data, copy);
207
2
    buf.len = copy;
208
4
    wrap->stream_->OnRead(buf.len, &buf);
209
210
2
    data += copy;
211
2
    len -= copy;
212
  }
213
}
214
215
216
266
void TLSWrap::Start(const FunctionCallbackInfo<Value>& args) {
217
266
  Environment* env = Environment::GetCurrent(args);
218
219
  TLSWrap* wrap;
220
266
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
221
222
266
  if (wrap->started_)
223
    return env->ThrowError("Already started.");
224
266
  wrap->started_ = true;
225
226
  // Send ClientHello handshake
227
266
  CHECK(wrap->is_client());
228
266
  wrap->ClearOut();
229
266
  wrap->EncOut();
230
}
231
232
233
11642
void TLSWrap::SSLInfoCallback(const SSL* ssl_, int where, int ret) {
234
11642
  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
1136
  SSL* ssl = const_cast<SSL*>(ssl_);
240
1136
  TLSWrap* c = static_cast<TLSWrap*>(SSL_get_app_data(ssl));
241
1136
  Environment* env = c->env();
242
2272
  Local<Object> object = c->object();
243
244
1136
  if (where & SSL_CB_HANDSHAKE_START) {
245
1166
    Local<Value> callback = object->Get(env->onhandshakestart_string());
246
583
    if (callback->IsFunction()) {
247
583
      c->MakeCallback(callback.As<Function>(), 0, nullptr);
248
    }
249
  }
250
251
1136
  if (where & SSL_CB_HANDSHAKE_DONE) {
252
553
    c->established_ = true;
253
1106
    Local<Value> callback = object->Get(env->onhandshakedone_string());
254
553
    if (callback->IsFunction()) {
255
553
      c->MakeCallback(callback.As<Function>(), 0, nullptr);
256
    }
257
  }
258
}
259
260
261
5797
void TLSWrap::EncOut() {
262
  // Ignore cycling data if ClientHello wasn't yet parsed
263
5797
  if (!hello_parser_.IsEnded())
264
3592
    return;
265
266
  // Write in progress
267
5797
  if (write_size_ != 0)
268
    return;
269
270
  // Wait for `newSession` callback to be invoked
271
5156
  if (is_waiting_new_session())
272
    return;
273
274
  // Split-off queue
275

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

2205
  CHECK(write_size_ != 0 && count != 0);
293
294
  Local<Object> req_wrap_obj =
295
4410
      env()->write_wrap_constructor_function()
296
11025
          ->NewInstance(env()->context()).ToLocalChecked();
297
2205
  WriteWrap* write_req = WriteWrap::New(env(),
298
                                        req_wrap_obj,
299
                                        this,
300
2205
                                        EncOutCb);
301
302
  uv_buf_t buf[arraysize(data)];
303
4828
  for (size_t i = 0; i < count; i++)
304
2623
    buf[i] = uv_buf_init(data[i], size[i]);
305
2205
  int err = stream_->DoWrite(write_req, buf, count, nullptr);
306
307
  // Ignore errors, this should be already handled in js
308
2205
  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
2189
void TLSWrap::EncOutCb(WriteWrap* req_wrap, int status) {
318
4378
  TLSWrap* wrap = req_wrap->wrap()->Cast<TLSWrap>();
319
2189
  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
2189
  CHECK_NE(wrap->ssl_, nullptr);
324
325
  // Handle error
326
2189
  if (status) {
327
    // Ignore errors after shutdown
328
2
    if (wrap->shutdown_)
329
      return;
330
331
    // Notify about error
332
2
    wrap->InvokeQueued(status);
333
2
    return;
334
  }
335
336
  // Commit
337
4374
  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
2187
  wrap->ClearIn();
341
342
  // Try writing more data
343
2187
  wrap->write_size_ = 0;
344
2187
  wrap->EncOut();
345
}
346
347
348
2974
Local<Value> TLSWrap::GetSSLError(int status, int* err, const char** msg) {
349
5948
  EscapableHandleScope scope(env()->isolate());
350
351
  // ssl_ is already destroyed in reading EOF by close notify alert.
352
2974
  if (ssl_ == nullptr)
353
    return Local<Value>();
354
355
2974
  *err = SSL_get_error(ssl_, status);
356
2974
  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
680
      return scope.Escape(env()->zero_return_string());
364
      break;
365
    default:
366
      {
367
19
        CHECK(*err == SSL_ERROR_SSL || *err == SSL_ERROR_SYSCALL);
368
369
19
        BIO* bio = BIO_new(BIO_s_mem());
370
19
        ERR_print_errors(bio);
371
372
        BUF_MEM* mem;
373
19
        BIO_get_mem_ptr(bio, &mem);
374
375
        Local<String> message =
376
19
            OneByteString(env()->isolate(), mem->data, mem->length);
377
19
        Local<Value> exception = Exception::Error(message);
378
379
19
        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
19
        BIO_free_all(bio);
387
388
19
        return scope.Escape(exception);
389
      }
390
  }
391
2785
  return Local<Value>();
392
}
393
394
395
2609
void TLSWrap::ClearOut() {
396
  // Ignore cycling data if ClientHello wasn't yet parsed
397
2609
  if (!hello_parser_.IsEnded())
398
171
    return;
399
400
  // No reads after EOF
401
2608
  if (eof_)
402
    return;
403
404
2608
  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
3591
    read = SSL_read(ssl_, out, sizeof(out));
413
414
3590
    if (read <= 0)
415
      break;
416
417
    char* current = out;
418
2977
    while (read > 0) {
419
998
      int avail = read;
420
421
      uv_buf_t buf;
422
1996
      OnAlloc(avail, &buf);
423
998
      if (static_cast<int>(buf.len) < avail)
424
13
        avail = buf.len;
425
1996
      memcpy(buf.base, current, avail);
426
1994
      OnRead(avail, &buf);
427
428
996
      read -= avail;
429
996
      current += avail;
430
    }
431
  }
432
433
2605
  int flags = SSL_get_shutdown(ssl_);
434

2605
  if (!eof_ && flags & SSL_RECEIVED_SHUTDOWN) {
435
205
    eof_ = true;
436
205
    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
2605
  if (read <= 0) {
443
    int err;
444
2605
    Local<Value> arg = GetSSLError(read, &err, nullptr);
445
446
    // Ignore ZERO_RETURN after EOF, it is basically not a error
447

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

365
    CHECK(written == -1 || written == static_cast<int>(avail));
478
365
    if (written == -1)
479
      break;
480
91
    clear_in_->Read(nullptr, avail);
481
  }
482
483
  // All written
484
5254
  if (clear_in_->Length() == 0) {
485
4980
    CHECK_GE(written, 0);
486
    return true;
487
  }
488
489
  // Error or partial write
490
  int err;
491
274
  const char* error_str = nullptr;
492
274
  Local<Value> arg = GetSSLError(written, &err, &error_str);
493
274
  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
2189
void* TLSWrap::Cast() {
505
2189
  return reinterpret_cast<void*>(this);
506
}
507
508
509
2367
AsyncWrap* TLSWrap::GetAsyncWrap() {
510
2367
  return static_cast<AsyncWrap*>(this);
511
}
512
513
514
430
bool TLSWrap::IsIPCPipe() {
515
430
  return stream_->IsIPCPipe();
516
}
517
518
519
2
int TLSWrap::GetFD() {
520
2
  return stream_->GetFD();
521
}
522
523
524
1570
bool TLSWrap::IsAlive() {
525

1570
  return ssl_ != nullptr && stream_->IsAlive();
526
}
527
528
529
2
bool TLSWrap::IsClosing() {
530
2
  return stream_->IsClosing();
531
}
532
533
534
325
int TLSWrap::ReadStart() {
535
325
  return stream_->ReadStart();
536
}
537
538
539
64
int TLSWrap::ReadStop() {
540
64
  return stream_->ReadStop();
541
}
542
543
544
1813
const char* TLSWrap::Error() const {
545
1813
  return error_;
546
}
547
548
549
void TLSWrap::ClearError() {
550
  delete[] error_;
551
  error_ = nullptr;
552
}
553
554
555
910
int TLSWrap::DoWrite(WriteWrap* w,
556
                     uv_buf_t* bufs,
557
                     size_t count,
558
                     uv_stream_t* send_handle) {
559
910
  CHECK_EQ(send_handle, nullptr);
560
910
  CHECK_NE(ssl_, nullptr);
561
562
  bool empty = true;
563
564
  // Empty writes should not go through encryption process
565
  size_t i;
566
914
  for (i = 0; i < count; i++)
567
910
    if (bufs[i].len > 0) {
568
      empty = false;
569
      break;
570
    }
571
910
  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
2730
  write_item_queue_.PushBack(new WriteItem(w));
581
1820
  w->Dispatched();
582
583
  // Write queued data
584
910
  if (empty) {
585
2
    EncOut();
586
2
    return 0;
587
  }
588
589
  // Process enqueued data first
590
908
  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
908
  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
908
  int written = 0;
610
5422
  for (i = 0; i < count; i++) {
611
4609
    written = SSL_write(ssl_, bufs[i].base, bufs[i].len);
612

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

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

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


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

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