GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage/nodes/benchmark/out/../src/tls_wrap.cc Lines: 447 474 94.3 %
Date: 2019-01-07 12:15:22 Branches: 228 317 71.9 %

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


9
  while (len > 0 && wrap->IsAlive() && !wrap->IsClosing()) {
176
3
    uv_buf_t buf = wrap->OnStreamAlloc(len);
177
3
    size_t copy = buf.len > len ? len : buf.len;
178
3
    memcpy(buf.base, data, copy);
179
3
    buf.len = copy;
180
3
    wrap->OnStreamRead(copy, buf);
181
182
3
    data += copy;
183
3
    len -= copy;
184
  }
185
}
186
187
188
988
void TLSWrap::Start(const FunctionCallbackInfo<Value>& args) {
189
  TLSWrap* wrap;
190
1976
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
191
192
988
  CHECK(!wrap->started_);
193
194
988
  wrap->started_ = true;
195
196
  // Send ClientHello handshake
197
988
  CHECK(wrap->is_client());
198
988
  wrap->ClearOut();
199
988
  wrap->EncOut();
200
}
201
202
203
21850
void TLSWrap::SSLInfoCallback(const SSL* ssl_, int where, int ret) {
204
21850
  if (!(where & (SSL_CB_HANDSHAKE_START | SSL_CB_HANDSHAKE_DONE)))
205
41229
    return;
206
207
  // Be compatible with older versions of OpenSSL. SSL_get_app_data() wants
208
  // a non-const SSL* in OpenSSL <= 0.9.7e.
209
2471
  SSL* ssl = const_cast<SSL*>(ssl_);
210
2471
  TLSWrap* c = static_cast<TLSWrap*>(SSL_get_app_data(ssl));
211
2471
  Environment* env = c->env();
212
2471
  HandleScope handle_scope(env->isolate());
213
2471
  Context::Scope context_scope(env->context());
214
2471
  Local<Object> object = c->object();
215
216
2471
  if (where & SSL_CB_HANDSHAKE_START) {
217
    Local<Value> callback;
218
219

7625
    if (object->Get(env->context(), env->onhandshakestart_string())
220

9150
          .ToLocal(&callback) && callback->IsFunction()) {
221
1525
      Local<Value> argv[] = { env->GetNow() };
222
3050
      c->MakeCallback(callback.As<Function>(), arraysize(argv), argv);
223
    }
224
  }
225
226
2471
  if (where & SSL_CB_HANDSHAKE_DONE) {
227
    Local<Value> callback;
228
229
946
    c->established_ = true;
230
231

4730
    if (object->Get(env->context(), env->onhandshakedone_string())
232

5676
          .ToLocal(&callback) && callback->IsFunction()) {
233
946
      c->MakeCallback(callback.As<Function>(), 0, nullptr);
234
    }
235
2471
  }
236
}
237
238
239
11833
void TLSWrap::EncOut() {
240
  // Ignore cycling data if ClientHello wasn't yet parsed
241
11833
  if (!hello_parser_.IsEnded())
242
7733
    return;
243
244
  // Write in progress
245
11833
  if (write_size_ != 0)
246
2229
    return;
247
248
  // Wait for `newSession` callback to be invoked
249
9604
  if (is_waiting_new_session())
250
7
    return;
251
252
  // Split-off queue
253

9597
  if (established_ && current_write_ != nullptr)
254
2440
    write_callback_scheduled_ = true;
255
256
9597
  if (ssl_ == nullptr)
257
1
    return;
258
259
  // No data to write
260
9596
  if (BIO_pending(enc_out_) == 0) {
261
5473
    if (pending_cleartext_input_.empty())
262
5206
      InvokeQueued(0);
263
5472
    return;
264
  }
265
266
  char* data[kSimultaneousBufferCount];
267
  size_t size[arraysize(data)];
268
4123
  size_t count = arraysize(data);
269
  write_size_ = crypto::NodeBIO::FromBIO(enc_out_)->PeekMultiple(data,
270
                                                                 size,
271
4123
                                                                 &count);
272

4123
  CHECK(write_size_ != 0 && count != 0);
273
274
  uv_buf_t buf[arraysize(data)];
275
4123
  uv_buf_t* bufs = buf;
276
10748
  for (size_t i = 0; i < count; i++)
277
6625
    buf[i] = uv_buf_init(data[i], size[i]);
278
279
4123
  StreamWriteResult res = underlying_stream()->Write(bufs, count);
280
4122
  if (res.err != 0) {
281
24
    InvokeQueued(res.err);
282
24
    return;
283
  }
284
285
4098
  if (!res.async) {
286
3541
    HandleScope handle_scope(env()->isolate());
287
288
    // Simulate asynchronous finishing, TLS cannot handle this at the moment.
289
10619
    env()->SetImmediate([](Environment* env, void* data) {
290
3539
      static_cast<TLSWrap*>(data)->OnStreamAfterWrite(nullptr, 0);
291
14159
    }, this, object());
292
  }
293
}
294
295
296
4098
void TLSWrap::OnStreamAfterWrite(WriteWrap* req_wrap, int status) {
297
4098
  if (current_empty_write_ != nullptr) {
298
2
    WriteWrap* finishing = current_empty_write_;
299
2
    current_empty_write_ = nullptr;
300
2
    finishing->Done(status);
301
2
    return;
302
  }
303
304
4096
  if (ssl_ == nullptr)
305
1
    status = UV_ECANCELED;
306
307
  // Handle error
308
4096
  if (status) {
309
    // Ignore errors after shutdown
310
10
    if (shutdown_)
311
6
      return;
312
313
    // Notify about error
314
4
    InvokeQueued(status);
315
4
    return;
316
  }
317
318
  // Commit
319
4086
  crypto::NodeBIO::FromBIO(enc_out_)->Read(nullptr, write_size_);
320
321
  // Ensure that the progress will be made and `InvokeQueued` will be called.
322
4086
  ClearIn();
323
324
  // Try writing more data
325
4086
  write_size_ = 0;
326
4086
  EncOut();
327
}
328
329
330
6430
Local<Value> TLSWrap::GetSSLError(int status, int* err, std::string* msg) {
331
6430
  EscapableHandleScope scope(env()->isolate());
332
333
  // ssl_ is already destroyed in reading EOF by close notify alert.
334
6430
  if (ssl_ == nullptr)
335
    return Local<Value>();
336
337
6430
  *err = SSL_get_error(ssl_.get(), status);
338
6430
  switch (*err) {
339
    case SSL_ERROR_NONE:
340
    case SSL_ERROR_WANT_READ:
341
    case SSL_ERROR_WANT_WRITE:
342
    case SSL_ERROR_WANT_X509_LOOKUP:
343
5486
      break;
344
    case SSL_ERROR_ZERO_RETURN:
345
774
      return scope.Escape(env()->zero_return_string());
346
      break;
347
    default:
348
      {
349

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

5896
  if (!eof_ && flags & SSL_RECEIVED_SHUTDOWN) {
453
430
    eof_ = true;
454
430
    EmitRead(UV_EOF);
455
  }
456
457
  // We need to check whether an error occurred or the connection was
458
  // shutdown cleanly (SSL_ERROR_ZERO_RETURN) even when read == 0.
459
  // See node#1642 and SSL_read(3SSL) for details.
460
5895
  if (read <= 0) {
461
5895
    HandleScope handle_scope(env()->isolate());
462
    int err;
463
5895
    Local<Value> arg = GetSSLError(read, &err, nullptr);
464
465
    // Ignore ZERO_RETURN after EOF, it is basically not a error
466

5895
    if (err == SSL_ERROR_ZERO_RETURN && eof_)
467
387
      return;
468
469
5508
    if (!arg.IsEmpty()) {
470
      // When TLS Alert are stored in wbio,
471
      // it should be flushed to socket before destroyed.
472
554
      if (BIO_pending(enc_out_) != 0)
473
531
        EncOut();
474
475
554
      MakeCallback(env()->onerror_string(), 1, &arg);
476
5508
    }
477
5508
  }
478
}
479
480
481
8685
bool TLSWrap::ClearIn() {
482
  // Ignore cycling data if ClientHello wasn't yet parsed
483
8685
  if (!hello_parser_.IsEnded())
484
    return false;
485
486
8685
  if (ssl_ == nullptr)
487
    return false;
488
489
8685
  std::vector<uv_buf_t> buffers;
490
8685
  buffers.swap(pending_cleartext_input_);
491
492
17370
  crypto::MarkPopErrorOnReturn mark_pop_error_on_return;
493
494
  size_t i;
495
8685
  int written = 0;
496
8826
  for (i = 0; i < buffers.size(); ++i) {
497
536
    size_t avail = buffers[i].len;
498
536
    char* data = buffers[i].base;
499
536
    written = SSL_write(ssl_.get(), data, avail);
500

536
    CHECK(written == -1 || written == static_cast<int>(avail));
501
536
    if (written == -1)
502
395
      break;
503
  }
504
505
  // All written
506
8685
  if (i == buffers.size()) {
507
8290
    CHECK_GE(written, 0);
508
8290
    return true;
509
  }
510
511
  // Error or partial write
512
790
  HandleScope handle_scope(env()->isolate());
513
395
  Context::Scope context_scope(env()->context());
514
515
  int err;
516
790
  std::string error_str;
517
395
  Local<Value> arg = GetSSLError(written, &err, &error_str);
518
395
  if (!arg.IsEmpty()) {
519
2
    write_callback_scheduled_ = true;
520
2
    InvokeQueued(UV_EPROTO, error_str.c_str());
521
  } else {
522
    // Push back the not-yet-written pending buffers into their queue.
523
    // This can be skipped in the error case because no further writes
524
    // would succeed anyway.
525
393
    pending_cleartext_input_.insert(pending_cleartext_input_.end(),
526
                                    buffers.begin() + i,
527
786
                                    buffers.end());
528
  }
529
530
9080
  return false;
531
}
532
533
534
5895
AsyncWrap* TLSWrap::GetAsyncWrap() {
535
5895
  return static_cast<AsyncWrap*>(this);
536
}
537
538
539
644
bool TLSWrap::IsIPCPipe() {
540
644
  return underlying_stream()->IsIPCPipe();
541
}
542
543
544
int TLSWrap::GetFD() {
545
  return underlying_stream()->GetFD();
546
}
547
548
549
1935
bool TLSWrap::IsAlive() {
550
3870
  return ssl_ != nullptr &&
551

3869
      stream_ != nullptr &&
552
3869
      underlying_stream()->IsAlive();
553
}
554
555
556
3
bool TLSWrap::IsClosing() {
557
3
  return underlying_stream()->IsClosing();
558
}
559
560
561
562
649
int TLSWrap::ReadStart() {
563
649
  if (stream_ != nullptr)
564
649
    return stream_->ReadStart();
565
  return 0;
566
}
567
568
569
318
int TLSWrap::ReadStop() {
570
318
  if (stream_ != nullptr)
571
313
    return stream_->ReadStop();
572
5
  return 0;
573
}
574
575
576
2190
const char* TLSWrap::Error() const {
577
2190
  return error_.empty() ? nullptr : error_.c_str();
578
}
579
580
581
void TLSWrap::ClearError() {
582
  error_.clear();
583
}
584
585
586
1127
int TLSWrap::DoWrite(WriteWrap* w,
587
                     uv_buf_t* bufs,
588
                     size_t count,
589
                     uv_stream_t* send_handle) {
590
1127
  CHECK_NULL(send_handle);
591
592
1127
  if (ssl_ == nullptr) {
593
    ClearError();
594
    error_ = "Write after DestroySSL";
595
    return UV_EPROTO;
596
  }
597
598
1127
  bool empty = true;
599
600
  // Empty writes should not go through encryption process
601
  size_t i;
602
1133
  for (i = 0; i < count; i++)
603
1127
    if (bufs[i].len > 0) {
604
1121
      empty = false;
605
1121
      break;
606
    }
607
1127
  if (empty) {
608
6
    ClearOut();
609
    // However, if there is any data that should be written to the socket,
610
    // the callback should not be invoked immediately
611
6
    if (BIO_pending(enc_out_) == 0) {
612
2
      CHECK_NULL(current_empty_write_);
613
2
      current_empty_write_ = w;
614
      StreamWriteResult res =
615
2
          underlying_stream()->Write(bufs, count, send_handle);
616
2
      if (!res.async) {
617
6
        env()->SetImmediate([](Environment* env, void* data) {
618
2
          TLSWrap* self = static_cast<TLSWrap*>(data);
619
2
          self->OnStreamAfterWrite(self->current_empty_write_, 0);
620
8
        }, this, object());
621
      }
622
2
      return 0;
623
    }
624
  }
625
626
  // Store the current write wrap
627
1125
  CHECK_NULL(current_write_);
628
1125
  current_write_ = w;
629
630
  // Write queued data
631
1125
  if (empty) {
632
4
    EncOut();
633
4
    return 0;
634
  }
635
636
1121
  crypto::MarkPopErrorOnReturn mark_pop_error_on_return;
637
638
1121
  int written = 0;
639
3350
  for (i = 0; i < count; i++) {
640
2369
    written = SSL_write(ssl_.get(), bufs[i].base, bufs[i].len);
641

2369
    CHECK(written == -1 || written == static_cast<int>(bufs[i].len));
642
2369
    if (written == -1)
643
140
      break;
644
  }
645
646
1121
  if (i != count) {
647
    int err;
648
140
    Local<Value> arg = GetSSLError(written, &err, &error_);
649
140
    if (!arg.IsEmpty()) {
650
1
      current_write_ = nullptr;
651
1
      return UV_EPROTO;
652
    }
653
654
139
    pending_cleartext_input_.insert(pending_cleartext_input_.end(),
655
                                    &bufs[i],
656
278
                                    &bufs[count]);
657
  }
658
659
  // Try writing data immediately
660
1120
  EncOut();
661
662
1120
  return 0;
663
}
664
665
666
4883
uv_buf_t TLSWrap::OnStreamAlloc(size_t suggested_size) {
667
4883
  CHECK_NOT_NULL(ssl_);
668
669
4883
  size_t size = suggested_size;
670
4883
  char* base = crypto::NodeBIO::FromBIO(enc_in_)->PeekWritable(&size);
671
4883
  return uv_buf_init(base, size);
672
}
673
674
675
4895
void TLSWrap::OnStreamRead(ssize_t nread, const uv_buf_t& buf) {
676
4895
  if (nread < 0)  {
677
    // Error should be emitted only after all data was read
678
319
    ClearOut();
679
680
    // Ignore EOF if received close_notify
681
319
    if (nread == UV_EOF) {
682
318
      if (eof_)
683
13
        return;
684
305
      eof_ = true;
685
    }
686
687
306
    EmitRead(nread);
688
306
    return;
689
  }
690
691
  // Only client connections can receive data
692
4576
  if (ssl_ == nullptr) {
693
    EmitRead(UV_EPROTO);
694
    return;
695
  }
696
697
  // Commit read data
698
4576
  crypto::NodeBIO* enc_in = crypto::NodeBIO::FromBIO(enc_in_);
699
4576
  enc_in->Commit(nread);
700
701
  // Parse ClientHello first
702
4576
  if (!hello_parser_.IsEnded()) {
703
20
    size_t avail = 0;
704
20
    uint8_t* data = reinterpret_cast<uint8_t*>(enc_in->Peek(&avail));
705

20
    CHECK_IMPLIES(data == nullptr, avail == 0);
706
20
    return hello_parser_.Parse(data, avail);
707
  }
708
709
  // Cycle OpenSSL's state
710
4556
  Cycle();
711
}
712
713
714
507
ShutdownWrap* TLSWrap::CreateShutdownWrap(Local<Object> req_wrap_object) {
715
507
  return underlying_stream()->CreateShutdownWrap(req_wrap_object);
716
}
717
718
719
507
int TLSWrap::DoShutdown(ShutdownWrap* req_wrap) {
720
507
  crypto::MarkPopErrorOnReturn mark_pop_error_on_return;
721
722

507
  if (ssl_ && SSL_shutdown(ssl_.get()) == 0)
723
493
    SSL_shutdown(ssl_.get());
724
725
507
  shutdown_ = true;
726
507
  EncOut();
727
507
  return stream_->DoShutdown(req_wrap);
728
}
729
730
731
11525
void TLSWrap::SetVerifyMode(const FunctionCallbackInfo<Value>& args) {
732
  TLSWrap* wrap;
733
23050
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
734
735
11525
  CHECK_EQ(args.Length(), 2);
736
23050
  CHECK(args[0]->IsBoolean());
737
23050
  CHECK(args[1]->IsBoolean());
738
11525
  CHECK_NOT_NULL(wrap->ssl_);
739
740
  int verify_mode;
741
11525
  if (wrap->is_server()) {
742
1018
    bool request_cert = args[0]->IsTrue();
743
509
    if (!request_cert) {
744
      // Note reject_unauthorized ignored.
745
431
      verify_mode = SSL_VERIFY_NONE;
746
    } else {
747
156
      bool reject_unauthorized = args[1]->IsTrue();
748
78
      verify_mode = SSL_VERIFY_PEER;
749
78
      if (reject_unauthorized)
750
47
        verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
751
    }
752
  } else {
753
    // Note request_cert and reject_unauthorized are ignored for clients.
754
11016
    verify_mode = SSL_VERIFY_NONE;
755
  }
756
757
  // Always allow a connection. We'll reject in javascript.
758
11525
  SSL_set_verify(wrap->ssl_.get(), verify_mode, crypto::VerifyCallback);
759
}
760
761
762
20
void TLSWrap::EnableSessionCallbacks(
763
    const FunctionCallbackInfo<Value>& args) {
764
  TLSWrap* wrap;
765
40
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
766
20
  CHECK_NOT_NULL(wrap->ssl_);
767
20
  wrap->enable_session_callbacks();
768
20
  crypto::NodeBIO::FromBIO(wrap->enc_in_)->set_initial(kMaxHelloLength);
769
  wrap->hello_parser_.Start(SSLWrap<TLSWrap>::OnClientHello,
770
                            OnClientHelloParseEnd,
771
20
                            wrap);
772
}
773
774
775
11496
void TLSWrap::DestroySSL(const FunctionCallbackInfo<Value>& args) {
776
  TLSWrap* wrap;
777
22992
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
778
779
  // If there is a write happening, mark it as finished.
780
11496
  wrap->write_callback_scheduled_ = true;
781
782
  // And destroy
783
11496
  wrap->InvokeQueued(UV_ECANCELED, "Canceled because of SSL destruction");
784
785
  // Destroy the SSL structure and friends
786
11496
  wrap->SSLWrap<TLSWrap>::DestroySSL();
787
11496
  wrap->enc_in_ = nullptr;
788
11496
  wrap->enc_out_ = nullptr;
789
790
11496
  if (wrap->stream_ != nullptr)
791
11496
    wrap->stream_->RemoveStreamListener(wrap);
792
}
793
794
795
20
void TLSWrap::EnableCertCb(const FunctionCallbackInfo<Value>& args) {
796
  TLSWrap* wrap;
797
40
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
798
20
  wrap->WaitForCertCb(OnClientHelloParseEnd, wrap);
799
}
800
801
802
35
void TLSWrap::OnClientHelloParseEnd(void* arg) {
803
35
  TLSWrap* c = static_cast<TLSWrap*>(arg);
804
35
  c->Cycle();
805
35
}
806
807
808
946
void TLSWrap::GetServername(const FunctionCallbackInfo<Value>& args) {
809
946
  Environment* env = Environment::GetCurrent(args);
810
811
  TLSWrap* wrap;
812
1892
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
813
814
946
  CHECK_NOT_NULL(wrap->ssl_);
815
816
946
  const char* servername = SSL_get_servername(wrap->ssl_.get(),
817
946
                                              TLSEXT_NAMETYPE_host_name);
818
946
  if (servername != nullptr) {
819
942
    args.GetReturnValue().Set(OneByteString(env->isolate(), servername));
820
  } else {
821
1264
    args.GetReturnValue().Set(false);
822
  }
823
}
824
825
826
162
void TLSWrap::SetServername(const FunctionCallbackInfo<Value>& args) {
827
162
  Environment* env = Environment::GetCurrent(args);
828
829
  TLSWrap* wrap;
830
324
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
831
832
162
  CHECK_EQ(args.Length(), 1);
833
486
  CHECK(args[0]->IsString());
834
162
  CHECK(!wrap->started_);
835
162
  CHECK(wrap->is_client());
836
837
162
  CHECK_NOT_NULL(wrap->ssl_);
838
839
324
  node::Utf8Value servername(env->isolate(), args[0].As<String>());
840
162
  SSL_set_tlsext_host_name(wrap->ssl_.get(), *servername);
841
}
842
843
844
513
int TLSWrap::SelectSNIContextCallback(SSL* s, int* ad, void* arg) {
845
513
  TLSWrap* p = static_cast<TLSWrap*>(SSL_get_app_data(s));
846
513
  Environment* env = p->env();
847
848
513
  const char* servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
849
850
513
  if (servername == nullptr)
851
344
    return SSL_TLSEXT_ERR_OK;
852
853
169
  HandleScope handle_scope(env->isolate());
854
169
  Context::Scope context_scope(env->context());
855
856
  // Call the SNI callback and use its return value as context
857
169
  Local<Object> object = p->object();
858
  Local<Value> ctx;
859
860
676
  if (!object->Get(env->context(), env->sni_context_string()).ToLocal(&ctx))
861
    return SSL_TLSEXT_ERR_NOACK;
862
863
  // Not an object, probably undefined or null
864
169
  if (!ctx->IsObject())
865
169
    return SSL_TLSEXT_ERR_NOACK;
866
867
  Local<FunctionTemplate> cons = env->secure_context_constructor_template();
868
  if (!cons->HasInstance(ctx)) {
869
    // Failure: incorrect SNI context object
870
    Local<Value> err = Exception::TypeError(env->sni_context_err_string());
871
    p->MakeCallback(env->onerror_string(), 1, &err);
872
    return SSL_TLSEXT_ERR_NOACK;
873
  }
874
875
  p->sni_context_.Reset(env->isolate(), ctx);
876
877
  SecureContext* sc = Unwrap<SecureContext>(ctx.As<Object>());
878
  CHECK_NOT_NULL(sc);
879
  p->SetSNIContext(sc);
880
169
  return SSL_TLSEXT_ERR_OK;
881
}
882
883
884
3
void TLSWrap::GetWriteQueueSize(const FunctionCallbackInfo<Value>& info) {
885
  TLSWrap* wrap;
886
3
  ASSIGN_OR_RETURN_UNWRAP(&wrap, info.This());
887
888
3
  if (wrap->ssl_ == nullptr) {
889
    info.GetReturnValue().Set(0);
890
    return;
891
  }
892
893
3
  uint32_t write_queue_size = BIO_pending(wrap->enc_out_);
894
6
  info.GetReturnValue().Set(write_queue_size);
895
}
896
897
898
2
void TLSWrap::MemoryInfo(MemoryTracker* tracker) const {
899
2
  tracker->TrackField("error", error_);
900
2
  tracker->TrackField("pending_cleartext_input", pending_cleartext_input_);
901
2
  if (enc_in_ != nullptr)
902
2
    tracker->TrackField("enc_in", crypto::NodeBIO::FromBIO(enc_in_));
903
2
  if (enc_out_ != nullptr)
904
2
    tracker->TrackField("enc_out", crypto::NodeBIO::FromBIO(enc_out_));
905
2
}
906
907
908
420
void TLSWrap::Initialize(Local<Object> target,
909
                         Local<Value> unused,
910
                         Local<Context> context,
911
                         void* priv) {
912
420
  Environment* env = Environment::GetCurrent(context);
913
914
420
  env->SetMethod(target, "wrap", TLSWrap::Wrap);
915
916
420
  Local<FunctionTemplate> t = BaseObject::MakeLazilyInitializedJSTemplate(env);
917
  Local<String> tlsWrapString =
918
420
      FIXED_ONE_BYTE_STRING(env->isolate(), "TLSWrap");
919
420
  t->SetClassName(tlsWrapString);
920
921
  Local<FunctionTemplate> get_write_queue_size =
922
      FunctionTemplate::New(env->isolate(),
923
                            GetWriteQueueSize,
924
                            env->as_external(),
925
840
                            Signature::New(env->isolate(), t));
926
1260
  t->PrototypeTemplate()->SetAccessorProperty(
927
      env->write_queue_size_string(),
928
      get_write_queue_size,
929
      Local<FunctionTemplate>(),
930
1260
      static_cast<PropertyAttribute>(ReadOnly | DontDelete));
931
932
840
  t->Inherit(AsyncWrap::GetConstructorTemplate(env));
933
420
  env->SetProtoMethod(t, "receive", Receive);
934
420
  env->SetProtoMethod(t, "start", Start);
935
420
  env->SetProtoMethod(t, "setVerifyMode", SetVerifyMode);
936
420
  env->SetProtoMethod(t, "enableSessionCallbacks", EnableSessionCallbacks);
937
420
  env->SetProtoMethod(t, "destroySSL", DestroySSL);
938
420
  env->SetProtoMethod(t, "enableCertCb", EnableCertCb);
939
940
420
  StreamBase::AddMethods<TLSWrap>(env, t);
941
420
  SSLWrap<TLSWrap>::AddMethods(env, t);
942
943
420
  env->SetProtoMethod(t, "getServername", GetServername);
944
420
  env->SetProtoMethod(t, "setServername", SetServername);
945
946
  env->set_tls_wrap_constructor_function(
947
1260
      t->GetFunction(env->context()).ToLocalChecked());
948
949
  target->Set(env->context(),
950
              tlsWrapString,
951
2100
              t->GetFunction(env->context()).ToLocalChecked()).FromJust();
952
420
}
953
954
}  // namespace node
955
956
3596
NODE_MODULE_CONTEXT_AWARE_INTERNAL(tls_wrap, node::TLSWrap::Initialize)