GCC Code Coverage Report
Directory: ../src/ Exec Total Coverage
File: /home/node-core-coverage/node-core-coverage/workdir/node/src/tls_wrap.cc Lines: 382 419 91.2 %
Date: 2016-07-18 Branches: 188 281 66.9 %

Line 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::Boolean;
21
using v8::Context;
22
using v8::EscapableHandleScope;
23
using v8::Exception;
24
using v8::Function;
25
using v8::FunctionCallbackInfo;
26
using v8::FunctionTemplate;
27
using v8::Local;
28
using v8::Object;
29
using v8::String;
30
using v8::Value;
31
32
593
TLSWrap::TLSWrap(Environment* env,
33
                 Kind kind,
34
                 StreamBase* stream,
35
                 SecureContext* sc)
36
    : AsyncWrap(env,
37
593
                env->tls_wrap_constructor_function()
38
1779
                    ->NewInstance(env->context()).ToLocalChecked(),
39
                AsyncWrap::PROVIDER_TLSWRAP),
40
      SSLWrap<TLSWrap>(env, sc, kind),
41
      StreamBase(env),
42
      sc_(sc),
43
      stream_(stream),
44
      enc_in_(nullptr),
45
      enc_out_(nullptr),
46
      clear_in_(nullptr),
47
      write_size_(0),
48
      started_(false),
49
      established_(false),
50
      shutdown_(false),
51
      error_(nullptr),
52
      cycle_depth_(0),
53
2372
      eof_(false) {
54
1186
  node::Wrap(object(), this);
55
593
  MakeWeak(this);
56
57
  // sc comes from an Unwrap. Make sure it was assigned.
58
593
  CHECK_NE(sc, nullptr);
59
60
  // We've our own session callbacks
61
593
  SSL_CTX_sess_set_get_cb(sc_->ctx_, SSLWrap<TLSWrap>::GetSessionCallback);
62
593
  SSL_CTX_sess_set_new_cb(sc_->ctx_, SSLWrap<TLSWrap>::NewSessionCallback);
63
64
1186
  stream_->Consume();
65
1186
  stream_->set_after_write_cb({ OnAfterWriteImpl, this });
66
1186
  stream_->set_alloc_cb({ OnAllocImpl, this });
67
1186
  stream_->set_read_cb({ OnReadImpl, this });
68
69
1186
  set_alloc_cb({ OnAllocSelf, this });
70
593
  set_read_cb({ OnReadSelf, this });
71
72
593
  InitSSL();
73
593
}
74
75
76
1248
TLSWrap::~TLSWrap() {
77
208
  enc_in_ = nullptr;
78
208
  enc_out_ = nullptr;
79
208
  delete clear_in_;
80
208
  clear_in_ = nullptr;
81
82
208
  sc_ = nullptr;
83
84
#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
85
416
  sni_context_.Reset();
86
#endif  // SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
87
88
208
  ClearError();
89
416
}
90
91
92
void TLSWrap::MakePending() {
93
847
  write_item_queue_.MoveBack(&pending_write_items_);
94
}
95
96
97
2723
bool TLSWrap::InvokeQueued(int status, const char* error_str) {
98
5446
  if (pending_write_items_.IsEmpty())
99
    return false;
100
101
  // Process old queue
102
842
  WriteItemList queue;
103
842
  pending_write_items_.MoveBack(&queue);
104
1685
  while (WriteItem* wi = queue.PopFront()) {
105
843
    wi->w_->Done(status, error_str);
106
1686
    delete wi;
107
  }
108
109
  return true;
110
}
111
112
113
2
void TLSWrap::NewSessionDoneCb() {
114
2
  Cycle();
115
2
}
116
117
118
593
void TLSWrap::InitSSL() {
119
  // Initialize SSL
120
593
  enc_in_ = NodeBIO::New();
121
593
  enc_out_ = NodeBIO::New();
122
1186
  NodeBIO::FromBIO(enc_in_)->AssignEnvironment(env());
123
1186
  NodeBIO::FromBIO(enc_out_)->AssignEnvironment(env());
124
125
593
  SSL_set_bio(ssl_, enc_in_, enc_out_);
126
127
  // NOTE: This could be overriden in SetVerifyMode
128
593
  SSL_set_verify(ssl_, SSL_VERIFY_NONE, crypto::VerifyCallback);
129
130
#ifdef SSL_MODE_RELEASE_BUFFERS
131
593
  long mode = SSL_get_mode(ssl_);  // NOLINT(runtime/int)
132
593
  SSL_set_mode(ssl_, mode | SSL_MODE_RELEASE_BUFFERS);
133
#endif  // SSL_MODE_RELEASE_BUFFERS
134
135
593
  SSL_set_app_data(ssl_, this);
136
593
  SSL_set_info_callback(ssl_, SSLInfoCallback);
137
138
#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
139
593
  if (is_server()) {
140
316
    SSL_CTX_set_tlsext_servername_callback(sc_->ctx_, SelectSNIContextCallback);
141
  }
142
#endif  // SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
143
144
593
  InitNPN(sc_);
145
146
593
  SSL_set_cert_cb(ssl_, SSLWrap<TLSWrap>::SSLCertCallback, this);
147
148
593
  if (is_server()) {
149
316
    SSL_set_accept_state(ssl_);
150
277
  } else if (is_client()) {
151
    // Enough space for server response (hello, cert)
152
831
    NodeBIO::FromBIO(enc_in_)->set_initial(kInitialClientBufferLength);
153
277
    SSL_set_connect_state(ssl_);
154
  } else {
155
    // Unexpected
156
    ABORT();
157
  }
158
159
  // Initialize ring for queud clear data
160
1186
  clear_in_ = new NodeBIO();
161
593
  clear_in_->AssignEnvironment(env());
162
593
}
163
164
165
593
void TLSWrap::Wrap(const FunctionCallbackInfo<Value>& args) {
166
593
  Environment* env = Environment::GetCurrent(args);
167
168
1779
  if (args.Length() < 1 || !args[0]->IsObject()) {
169
    return env->ThrowTypeError(
170
        "First argument should be a StreamWrap instance");
171
  }
172
1779
  if (args.Length() < 2 || !args[1]->IsObject()) {
173
    return env->ThrowTypeError(
174
        "Second argument should be a SecureContext instance");
175
  }
176
1779
  if (args.Length() < 3 || !args[2]->IsBoolean())
177
    return env->ThrowTypeError("Third argument should be boolean");
178
179
1186
  Local<External> stream_obj = args[0].As<External>();
180
1186
  Local<Object> sc = args[1].As<Object>();
181
1186
  Kind kind = args[2]->IsTrue() ? SSLWrap<TLSWrap>::kServer :
182
593
                                  SSLWrap<TLSWrap>::kClient;
183
184
593
  StreamBase* stream = static_cast<StreamBase*>(stream_obj->Value());
185
593
  CHECK_NE(stream, nullptr);
186
187
593
  TLSWrap* res = new TLSWrap(env, kind, stream, Unwrap<SecureContext>(sc));
188
189
2372
  args.GetReturnValue().Set(res->object());
190
}
191
192
193
2
void TLSWrap::Receive(const FunctionCallbackInfo<Value>& args) {
194
  TLSWrap* wrap;
195
2
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
196
197
2
  CHECK(Buffer::HasInstance(args[0]));
198
2
  char* data = Buffer::Data(args[0]);
199
2
  size_t len = Buffer::Length(args[0]);
200
201
  uv_buf_t buf;
202
203
  // Copy given buffer entirely or partiall if handle becomes closed
204
6
  while (len > 0 && wrap->IsAlive() && !wrap->IsClosing()) {
205
4
    wrap->stream_->OnAlloc(len, &buf);
206
2
    size_t copy = buf.len > len ? len : buf.len;
207
4
    memcpy(buf.base, data, copy);
208
2
    buf.len = copy;
209
4
    wrap->stream_->OnRead(buf.len, &buf);
210
211
2
    data += copy;
212
2
    len -= copy;
213
  }
214
}
215
216
217
266
void TLSWrap::Start(const FunctionCallbackInfo<Value>& args) {
218
266
  Environment* env = Environment::GetCurrent(args);
219
220
  TLSWrap* wrap;
221
266
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
222
223
266
  if (wrap->started_)
224
    return env->ThrowError("Already started.");
225
266
  wrap->started_ = true;
226
227
  // Send ClientHello handshake
228
266
  CHECK(wrap->is_client());
229
266
  wrap->ClearOut();
230
266
  wrap->EncOut();
231
}
232
233
234
11627
void TLSWrap::SSLInfoCallback(const SSL* ssl_, int where, int ret) {
235
11627
  if (!(where & (SSL_CB_HANDSHAKE_START | SSL_CB_HANDSHAKE_DONE)))
236
    return;
237
238
  // Be compatible with older versions of OpenSSL. SSL_get_app_data() wants
239
  // a non-const SSL* in OpenSSL <= 0.9.7e.
240
1134
  SSL* ssl = const_cast<SSL*>(ssl_);
241
1134
  TLSWrap* c = static_cast<TLSWrap*>(SSL_get_app_data(ssl));
242
1134
  Environment* env = c->env();
243
2268
  Local<Object> object = c->object();
244
245
1134
  if (where & SSL_CB_HANDSHAKE_START) {
246
1166
    Local<Value> callback = object->Get(env->onhandshakestart_string());
247
583
    if (callback->IsFunction()) {
248
583
      c->MakeCallback(callback.As<Function>(), 0, nullptr);
249
    }
250
  }
251
252
1134
  if (where & SSL_CB_HANDSHAKE_DONE) {
253
551
    c->established_ = true;
254
1102
    Local<Value> callback = object->Get(env->onhandshakedone_string());
255
551
    if (callback->IsFunction()) {
256
551
      c->MakeCallback(callback.As<Function>(), 0, nullptr);
257
    }
258
  }
259
}
260
261
262
5667
void TLSWrap::EncOut() {
263
  // Ignore cycling data if ClientHello wasn't yet parsed
264
5667
  if (!hello_parser_.IsEnded())
265
3528
    return;
266
267
  // Write in progress
268
5667
  if (write_size_ != 0)
269
    return;
270
271
  // Wait for `newSession` callback to be invoked
272
5027
  if (is_waiting_new_session())
273
    return;
274
275
  // Split-off queue
276
8414
  if (established_ && !write_item_queue_.IsEmpty())
277
    MakePending();
278
279
5026
  if (ssl_ == nullptr)
280
    return;
281
282
  // No data to write
283
5026
  if (BIO_pending(enc_out_) == 0) {
284
2887
    if (clear_in_->Length() == 0)
285
2705
      InvokeQueued(0);
286
    return;
287
  }
288
289
  char* data[kSimultaneousBufferCount];
290
  size_t size[arraysize(data)];
291
2139
  size_t count = arraysize(data);
292
4278
  write_size_ = NodeBIO::FromBIO(enc_out_)->PeekMultiple(data, size, &count);
293
2139
  CHECK(write_size_ != 0 && count != 0);
294
295
  Local<Object> req_wrap_obj =
296
4278
      env()->write_wrap_constructor_function()
297
10695
          ->NewInstance(env()->context()).ToLocalChecked();
298
2139
  WriteWrap* write_req = WriteWrap::New(env(),
299
                                        req_wrap_obj,
300
                                        this,
301
2139
                                        EncOutCb);
302
303
  uv_buf_t buf[arraysize(data)];
304
4696
  for (size_t i = 0; i < count; i++)
305
2557
    buf[i] = uv_buf_init(data[i], size[i]);
306
2139
  int err = stream_->DoWrite(write_req, buf, count, nullptr);
307
308
  // Ignore errors, this should be already handled in js
309
2139
  if (err) {
310
13
    write_req->Dispose();
311
13
    InvokeQueued(err);
312
  } else {
313
    NODE_COUNT_NET_BYTES_SENT(write_size_);
314
  }
315
}
316
317
318
2123
void TLSWrap::EncOutCb(WriteWrap* req_wrap, int status) {
319
4246
  TLSWrap* wrap = req_wrap->wrap()->Cast<TLSWrap>();
320
2123
  req_wrap->Dispose();
321
322
  // We should not be getting here after `DestroySSL`, because all queued writes
323
  // must be invoked with UV_ECANCELED
324
2123
  CHECK_NE(wrap->ssl_, nullptr);
325
326
  // Handle error
327
2123
  if (status) {
328
    // Ignore errors after shutdown
329
2
    if (wrap->shutdown_)
330
      return;
331
332
    // Notify about error
333
2
    wrap->InvokeQueued(status);
334
2
    return;
335
  }
336
337
  // Commit
338
4242
  NodeBIO::FromBIO(wrap->enc_out_)->Read(nullptr, wrap->write_size_);
339
340
  // Ensure that the progress will be made and `InvokeQueued` will be called.
341
2121
  wrap->ClearIn();
342
343
  // Try writing more data
344
2121
  wrap->write_size_ = 0;
345
2121
  wrap->EncOut();
346
}
347
348
349
2973
Local<Value> TLSWrap::GetSSLError(int status, int* err, const char** msg) {
350
5946
  EscapableHandleScope scope(env()->isolate());
351
352
  // ssl_ is already destroyed in reading EOF by close notify alert.
353
2973
  if (ssl_ == nullptr)
354
    return Local<Value>();
355
356
2973
  *err = SSL_get_error(ssl_, status);
357
2973
  switch (*err) {
358
    case SSL_ERROR_NONE:
359
    case SSL_ERROR_WANT_READ:
360
    case SSL_ERROR_WANT_WRITE:
361
    case SSL_ERROR_WANT_X509_LOOKUP:
362
      break;
363
    case SSL_ERROR_ZERO_RETURN:
364
688
      return scope.Escape(env()->zero_return_string());
365
      break;
366
    default:
367
      {
368
19
        CHECK(*err == SSL_ERROR_SSL || *err == SSL_ERROR_SYSCALL);
369
370
19
        BIO* bio = BIO_new(BIO_s_mem());
371
19
        ERR_print_errors(bio);
372
373
        BUF_MEM* mem;
374
19
        BIO_get_mem_ptr(bio, &mem);
375
376
        Local<String> message =
377
19
            OneByteString(env()->isolate(), mem->data, mem->length);
378
19
        Local<Value> exception = Exception::Error(message);
379
380
19
        if (msg != nullptr) {
381
3
          CHECK_EQ(*msg, nullptr);
382
3
          char* const buf = new char[mem->length + 1];
383
6
          memcpy(buf, mem->data, mem->length);
384
3
          buf[mem->length] = '\0';
385
3
          *msg = buf;
386
        }
387
19
        BIO_free_all(bio);
388
389
19
        return scope.Escape(exception);
390
      }
391
  }
392
2782
  return Local<Value>();
393
}
394
395
396
2609
void TLSWrap::ClearOut() {
397
  // Ignore cycling data if ClientHello wasn't yet parsed
398
2609
  if (!hello_parser_.IsEnded())
399
173
    return;
400
401
  // No reads after EOF
402
2608
  if (eof_)
403
    return;
404
405
2608
  if (ssl_ == nullptr)
406
    return;
407
408
  crypto::MarkPopErrorOnReturn mark_pop_error_on_return;
409
410
  char out[kClearOutChunkSize];
411
  int read;
412
  for (;;) {
413
3591
    read = SSL_read(ssl_, out, sizeof(out));
414
415
3590
    if (read <= 0)
416
      break;
417
418
    char* current = out;
419
2977
    while (read > 0) {
420
998
      int avail = read;
421
422
      uv_buf_t buf;
423
1996
      OnAlloc(avail, &buf);
424
998
      if (static_cast<int>(buf.len) < avail)
425
13
        avail = buf.len;
426
1996
      memcpy(buf.base, current, avail);
427
1994
      OnRead(avail, &buf);
428
429
996
      read -= avail;
430
996
      current += avail;
431
    }
432
  }
433
434
2605
  int flags = SSL_get_shutdown(ssl_);
435
2605
  if (!eof_ && flags & SSL_RECEIVED_SHUTDOWN) {
436
205
    eof_ = true;
437
205
    OnRead(UV_EOF, nullptr);
438
  }
439
440
  // We need to check whether an error occurred or the connection was
441
  // shutdown cleanly (SSL_ERROR_ZERO_RETURN) even when read == 0.
442
  // See node#1642 and SSL_read(3SSL) for details.
443
2605
  if (read <= 0) {
444
    int err;
445
2605
    Local<Value> arg = GetSSLError(read, &err, nullptr);
446
447
    // Ignore ZERO_RETURN after EOF, it is basically not a error
448
2605
    if (err == SSL_ERROR_ZERO_RETURN && eof_)
449
172
      return;
450
451
2433
    if (!arg.IsEmpty()) {
452
      // When TLS Alert are stored in wbio,
453
      // it should be flushed to socket before destroyed.
454
16
      if (BIO_pending(enc_out_) != 0)
455
9
        EncOut();
456
457
32
      MakeCallback(env()->onerror_string(), 1, &arg);
458
    }
459
  }
460
}
461
462
463
5124
bool TLSWrap::ClearIn() {
464
  // Ignore cycling data if ClientHello wasn't yet parsed
465
5124
  if (!hello_parser_.IsEnded())
466
    return false;
467
468
5124
  if (ssl_ == nullptr)
469
    return false;
470
471
  crypto::MarkPopErrorOnReturn mark_pop_error_on_return;
472
473
5124
  int written = 0;
474
5304
  while (clear_in_->Length() > 0) {
475
363
    size_t avail = 0;
476
363
    char* data = clear_in_->Peek(&avail);
477
363
    written = SSL_write(ssl_, data, avail);
478
363
    CHECK(written == -1 || written == static_cast<int>(avail));
479
363
    if (written == -1)
480
      break;
481
90
    clear_in_->Read(nullptr, avail);
482
  }
483
484
  // All written
485
5124
  if (clear_in_->Length() == 0) {
486
4851
    CHECK_GE(written, 0);
487
    return true;
488
  }
489
490
  // Error or partial write
491
  int err;
492
273
  const char* error_str = nullptr;
493
273
  Local<Value> arg = GetSSLError(written, &err, &error_str);
494
273
  if (!arg.IsEmpty()) {
495
3
    MakePending();
496
3
    InvokeQueued(UV_EPROTO, error_str);
497
3
    delete[] error_str;
498
3
    clear_in_->Reset();
499
  }
500
501
  return false;
502
}
503
504
505
2123
void* TLSWrap::Cast() {
506
2123
  return reinterpret_cast<void*>(this);
507
}
508
509
510
2303
AsyncWrap* TLSWrap::GetAsyncWrap() {
511
2303
  return static_cast<AsyncWrap*>(this);
512
}
513
514
515
430
bool TLSWrap::IsIPCPipe() {
516
430
  return stream_->IsIPCPipe();
517
}
518
519
520
2
int TLSWrap::GetFD() {
521
2
  return stream_->GetFD();
522
}
523
524
525
1506
bool TLSWrap::IsAlive() {
526
1506
  return ssl_ != nullptr && stream_->IsAlive();
527
}
528
529
530
2
bool TLSWrap::IsClosing() {
531
2
  return stream_->IsClosing();
532
}
533
534
535
325
int TLSWrap::ReadStart() {
536
325
  return stream_->ReadStart();
537
}
538
539
540
64
int TLSWrap::ReadStop() {
541
64
  return stream_->ReadStop();
542
}
543
544
545
1685
const char* TLSWrap::Error() const {
546
1685
  return error_;
547
}
548
549
550
void TLSWrap::ClearError() {
551
208
  delete[] error_;
552
208
  error_ = nullptr;
553
}
554
555
556
846
int TLSWrap::DoWrite(WriteWrap* w,
557
                     uv_buf_t* bufs,
558
                     size_t count,
559
                     uv_stream_t* send_handle) {
560
846
  CHECK_EQ(send_handle, nullptr);
561
846
  CHECK_NE(ssl_, nullptr);
562
563
  bool empty = true;
564
565
  // Empty writes should not go through encryption process
566
  size_t i;
567
850
  for (i = 0; i < count; i++)
568
846
    if (bufs[i].len > 0) {
569
      empty = false;
570
      break;
571
    }
572
846
  if (empty) {
573
2
    ClearOut();
574
    // However, if there is any data that should be written to the socket,
575
    // the callback should not be invoked immediately
576
2
    if (BIO_pending(enc_out_) == 0)
577
      return stream_->DoWrite(w, bufs, count, send_handle);
578
  }
579
580
  // Queue callback to execute it on next tick
581
2538
  write_item_queue_.PushBack(new WriteItem(w));
582
1692
  w->Dispatched();
583
584
  // Write queued data
585
846
  if (empty) {
586
2
    EncOut();
587
2
    return 0;
588
  }
589
590
  // Process enqueued data first
591
844
  if (!ClearIn()) {
592
    // If there're still data to process - enqueue current one
593
    for (i = 0; i < count; i++)
594
      clear_in_->Write(bufs[i].base, bufs[i].len);
595
    return 0;
596
  }
597
598
844
  if (ssl_ == nullptr) {
599
    ClearError();
600
601
    static char msg[] = "Write after DestroySSL";
602
    char* tmp = new char[sizeof(msg)];
603
    memcpy(tmp, msg, sizeof(msg));
604
    error_ = tmp;
605
    return UV_EPROTO;
606
  }
607
608
  crypto::MarkPopErrorOnReturn mark_pop_error_on_return;
609
610
844
  int written = 0;
611
4846
  for (i = 0; i < count; i++) {
612
4097
    written = SSL_write(ssl_, bufs[i].base, bufs[i].len);
613
4097
    CHECK(written == -1 || written == static_cast<int>(bufs[i].len));
614
4097
    if (written == -1)
615
      break;
616
  }
617
618
844
  if (i != count) {
619
    int err;
620
95
    Local<Value> arg = GetSSLError(written, &err, &error_);
621
95
    if (!arg.IsEmpty())
622
      return UV_EPROTO;
623
624
    // No errors, queue rest
625
285
    for (; i < count; i++)
626
95
      clear_in_->Write(bufs[i].base, bufs[i].len);
627
  }
628
629
  // Try writing data immediately
630
844
  EncOut();
631
632
844
  return 0;
633
}
634
635
636
11
void TLSWrap::OnAfterWriteImpl(WriteWrap* w, void* ctx) {
637
  // Intentionally empty
638
11
}
639
640
641
2318
void TLSWrap::OnAllocImpl(size_t suggested_size, uv_buf_t* buf, void* ctx) {
642
2318
  TLSWrap* wrap = static_cast<TLSWrap*>(ctx);
643
644
2318
  if (wrap->ssl_ == nullptr) {
645
    *buf = uv_buf_init(nullptr, 0);
646
    return;
647
  }
648
649
2318
  size_t size = 0;
650
4636
  buf->base = NodeBIO::FromBIO(wrap->enc_in_)->PeekWritable(&size);
651
2318
  buf->len = size;
652
}
653
654
655
2321
void TLSWrap::OnReadImpl(ssize_t nread,
656
                         const uv_buf_t* buf,
657
                         uv_handle_type pending,
658
                         void* ctx) {
659
2321
  TLSWrap* wrap = static_cast<TLSWrap*>(ctx);
660
2321
  wrap->DoRead(nread, buf, pending);
661
2318
}
662
663
664
808
void TLSWrap::OnAllocSelf(size_t suggested_size, uv_buf_t* buf, void* ctx) {
665
808
  buf->base = static_cast<char*>(malloc(suggested_size));
666
808
  CHECK_NE(buf->base, nullptr);
667
808
  buf->len = suggested_size;
668
808
}
669
670
671
1195
void TLSWrap::OnReadSelf(ssize_t nread,
672
                         const uv_buf_t* buf,
673
                         uv_handle_type pending,
674
                         void* ctx) {
675
1195
  TLSWrap* wrap = static_cast<TLSWrap*>(ctx);
676
1195
  Local<Object> buf_obj;
677
1195
  if (buf != nullptr)
678
1630
    buf_obj = Buffer::New(wrap->env(), buf->base, buf->len).ToLocalChecked();
679
1195
  wrap->EmitData(nread, buf_obj, Local<Object>());
680
1193
}
681
682
683
2321
void TLSWrap::DoRead(ssize_t nread,
684
                     const uv_buf_t* buf,
685
                     uv_handle_type pending) {
686
2321
  if (nread < 0)  {
687
    // Error should be emitted only after all data was read
688
182
    ClearOut();
689
690
    // Ignore EOF if received close_notify
691
182
    if (nread == UV_EOF) {
692
182
      if (eof_)
693
        return;
694
182
      eof_ = true;
695
    }
696
697
182
    OnRead(nread, nullptr);
698
    return;
699
  }
700
701
  // Only client connections can receive data
702
2139
  if (ssl_ == nullptr) {
703
    OnRead(UV_EPROTO, nullptr);
704
    return;
705
  }
706
707
  // Commit read data
708
4278
  NodeBIO* enc_in = NodeBIO::FromBIO(enc_in_);
709
2139
  enc_in->Commit(nread);
710
711
  // Parse ClientHello first
712
2139
  if (!hello_parser_.IsEnded()) {
713
14
    size_t avail = 0;
714
14
    uint8_t* data = reinterpret_cast<uint8_t*>(enc_in->Peek(&avail));
715
14
    CHECK(avail == 0 || data != nullptr);
716
14
    return hello_parser_.Parse(data, avail);
717
  }
718
719
  // Cycle OpenSSL's state
720
2125
  Cycle();
721
}
722
723
724
269
int TLSWrap::DoShutdown(ShutdownWrap* req_wrap) {
725
  crypto::MarkPopErrorOnReturn mark_pop_error_on_return;
726
727
269
  if (ssl_ != nullptr && SSL_shutdown(ssl_) == 0)
728
269
    SSL_shutdown(ssl_);
729
730
269
  shutdown_ = true;
731
269
  EncOut();
732
538
  return stream_->DoShutdown(req_wrap);
733
}
734
735
736
317
void TLSWrap::SetVerifyMode(const FunctionCallbackInfo<Value>& args) {
737
317
  Environment* env = Environment::GetCurrent(args);
738
739
  TLSWrap* wrap;
740
317
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
741
742
1268
  if (args.Length() < 2 || !args[0]->IsBoolean() || !args[1]->IsBoolean())
743
    return env->ThrowTypeError("Bad arguments, expected two booleans");
744
745
317
  if (wrap->ssl_ == nullptr)
746
    return env->ThrowTypeError("SetVerifyMode after destroySSL");
747
748
  int verify_mode;
749
317
  if (wrap->is_server()) {
750
40
    bool request_cert = args[0]->IsTrue();
751
40
    if (!request_cert) {
752
      // Note reject_unauthorized ignored.
753
      verify_mode = SSL_VERIFY_NONE;
754
    } else {
755
39
      bool reject_unauthorized = args[1]->IsTrue();
756
39
      verify_mode = SSL_VERIFY_PEER;
757
39
      if (reject_unauthorized)
758
14
        verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
759
    }
760
  } else {
761
    // Note request_cert and reject_unauthorized are ignored for clients.
762
    verify_mode = SSL_VERIFY_NONE;
763
  }
764
765
  // Always allow a connection. We'll reject in javascript.
766
317
  SSL_set_verify(wrap->ssl_, verify_mode, crypto::VerifyCallback);
767
}
768
769
770
14
void TLSWrap::EnableSessionCallbacks(
771
    const FunctionCallbackInfo<Value>& args) {
772
  TLSWrap* wrap;
773
14
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
774
14
  if (wrap->ssl_ == nullptr) {
775
    return wrap->env()->ThrowTypeError(
776
        "EnableSessionCallbacks after destroySSL");
777
  }
778
14
  wrap->enable_session_callbacks();
779
42
  NodeBIO::FromBIO(wrap->enc_in_)->set_initial(kMaxHelloLength);
780
14
  wrap->hello_parser_.Start(SSLWrap<TLSWrap>::OnClientHello,
781
                            OnClientHelloParseEnd,
782
                            wrap);
783
}
784
785
786
void TLSWrap::DestroySSL(const FunctionCallbackInfo<Value>& args) {
787
  TLSWrap* wrap;
788
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
789
790
  // Move all writes to pending
791
  wrap->MakePending();
792
793
  // And destroy
794
  wrap->InvokeQueued(UV_ECANCELED, "Canceled because of SSL destruction");
795
796
  // Destroy the SSL structure and friends
797
  wrap->SSLWrap<TLSWrap>::DestroySSL();
798
799
  delete wrap->clear_in_;
800
  wrap->clear_in_ = nullptr;
801
}
802
803
804
21
void TLSWrap::EnableCertCb(const FunctionCallbackInfo<Value>& args) {
805
  TLSWrap* wrap;
806
21
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
807
21
  wrap->WaitForCertCb(OnClientHelloParseEnd, wrap);
808
}
809
810
811
32
void TLSWrap::OnClientHelloParseEnd(void* arg) {
812
32
  TLSWrap* c = static_cast<TLSWrap*>(arg);
813
32
  c->Cycle();
814
32
}
815
816
817
#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
818
296
void TLSWrap::GetServername(const FunctionCallbackInfo<Value>& args) {
819
296
  Environment* env = Environment::GetCurrent(args);
820
821
  TLSWrap* wrap;
822
296
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
823
824
296
  CHECK_NE(wrap->ssl_, nullptr);
825
826
  const char* servername = SSL_get_servername(wrap->ssl_,
827
296
                                              TLSEXT_NAMETYPE_host_name);
828
296
  if (servername != nullptr) {
829
214
    args.GetReturnValue().Set(OneByteString(env->isolate(), servername));
830
  } else {
831
378
    args.GetReturnValue().Set(false);
832
  }
833
}
834
835
836
105
void TLSWrap::SetServername(const FunctionCallbackInfo<Value>& args) {
837
105
  Environment* env = Environment::GetCurrent(args);
838
839
  TLSWrap* wrap;
840
105
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
841
842
420
  if (args.Length() < 1 || !args[0]->IsString())
843
    return env->ThrowTypeError("First argument should be a string");
844
845
105
  if (wrap->started_)
846
    return env->ThrowError("Already started.");
847
848
105
  if (!wrap->is_client())
849
    return;
850
851
105
  CHECK_NE(wrap->ssl_, nullptr);
852
853
#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
854
420
  node::Utf8Value servername(env->isolate(), args[0].As<String>());
855
105
  SSL_set_tlsext_host_name(wrap->ssl_, *servername);
856
#endif  // SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
857
}
858
859
860
308
int TLSWrap::SelectSNIContextCallback(SSL* s, int* ad, void* arg) {
861
308
  TLSWrap* p = static_cast<TLSWrap*>(SSL_get_app_data(s));
862
308
  Environment* env = p->env();
863
864
308
  const char* servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
865
866
308
  if (servername == nullptr)
867
    return SSL_TLSEXT_ERR_OK;
868
869
  // Call the SNI callback and use its return value as context
870
222
  Local<Object> object = p->object();
871
222
  Local<Value> ctx = object->Get(env->sni_context_string());
872
873
  // Not an object, probably undefined or null
874
111
  if (!ctx->IsObject())
875
    return SSL_TLSEXT_ERR_NOACK;
876
877
  Local<FunctionTemplate> cons = env->secure_context_constructor_template();
878
  if (!cons->HasInstance(ctx)) {
879
    // Failure: incorrect SNI context object
880
    Local<Value> err = Exception::TypeError(env->sni_context_err_string());
881
    p->MakeCallback(env->onerror_string(), 1, &err);
882
    return SSL_TLSEXT_ERR_NOACK;
883
  }
884
885
  p->sni_context_.Reset();
886
  p->sni_context_.Reset(env->isolate(), ctx);
887
888
  SecureContext* sc = Unwrap<SecureContext>(ctx.As<Object>());
889
  CHECK_NE(sc, nullptr);
890
  p->SetSNIContext(sc);
891
  return SSL_TLSEXT_ERR_OK;
892
}
893
#endif  // SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
894
895
896
139
void TLSWrap::Initialize(Local<Object> target,
897
                         Local<Value> unused,
898
                         Local<Context> context) {
899
139
  Environment* env = Environment::GetCurrent(context);
900
901
139
  env->SetMethod(target, "wrap", TLSWrap::Wrap);
902
903
594
  auto constructor = [](const FunctionCallbackInfo<Value>& args) {
904
594
    args.This()->SetAlignedPointerInInternalField(0, nullptr);
905
1188
  };
906
278
  auto t = env->NewFunctionTemplate(constructor);
907
278
  t->InstanceTemplate()->SetInternalFieldCount(1);
908
139
  t->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "TLSWrap"));
909
910
139
  env->SetProtoMethod(t, "receive", Receive);
911
139
  env->SetProtoMethod(t, "start", Start);
912
139
  env->SetProtoMethod(t, "setVerifyMode", SetVerifyMode);
913
139
  env->SetProtoMethod(t, "enableSessionCallbacks", EnableSessionCallbacks);
914
139
  env->SetProtoMethod(t, "destroySSL", DestroySSL);
915
139
  env->SetProtoMethod(t, "enableCertCb", EnableCertCb);
916
917
139
  StreamBase::AddMethods<TLSWrap>(env, t, StreamBase::kFlagHasWritev);
918
139
  SSLWrap<TLSWrap>::AddMethods(env, t);
919
920
#ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
921
139
  env->SetProtoMethod(t, "getServername", GetServername);
922
139
  env->SetProtoMethod(t, "setServername", SetServername);
923
#endif  // SSL_CRT_SET_TLSEXT_SERVERNAME_CB
924
925
139
  env->set_tls_wrap_constructor_template(t);
926
139
  env->set_tls_wrap_constructor_function(t->GetFunction());
927
928
695
  target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "TLSWrap"),
929
139
              t->GetFunction());
930
139
}
931
932
}  // namespace node
933
934
1565
NODE_MODULE_CONTEXT_AWARE_BUILTIN(tls_wrap, node::TLSWrap::Initialize)