GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/tls_wrap.cc Lines: 511 546 93.6 %
Date: 2019-05-05 22:32:45 Branches: 236 330 71.5 %

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 "debug_utils.h"
25
#include "node_buffer.h"  // Buffer
26
#include "node_crypto.h"  // SecureContext
27
#include "node_crypto_bio.h"  // NodeBIO
28
// ClientHelloParser
29
#include "node_crypto_clienthello-inl.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
12217
TLSWrap::TLSWrap(Environment* env,
53
                 Local<Object> obj,
54
                 Kind kind,
55
                 StreamBase* stream,
56
                 SecureContext* sc)
57
    : AsyncWrap(env, obj, AsyncWrap::PROVIDER_TLSWRAP),
58
      SSLWrap<TLSWrap>(env, sc, kind),
59
      StreamBase(env),
60
12217
      sc_(sc) {
61
12217
  MakeWeak();
62
12217
  StreamBase::AttachToObject(GetObject());
63
64
  // sc comes from an Unwrap. Make sure it was assigned.
65
12217
  CHECK_NOT_NULL(sc);
66
67
  // We've our own session callbacks
68
  SSL_CTX_sess_set_get_cb(sc_->ctx_.get(),
69
12217
                          SSLWrap<TLSWrap>::GetSessionCallback);
70
  SSL_CTX_sess_set_new_cb(sc_->ctx_.get(),
71
12217
                          SSLWrap<TLSWrap>::NewSessionCallback);
72
73
12217
  stream->PushStreamListener(this);
74
75
12217
  InitSSL();
76
12217
  Debug(this, "Created new TLSWrap");
77
12217
}
78
79
80
36255
TLSWrap::~TLSWrap() {
81
12085
  Debug(this, "~TLSWrap()");
82
12085
  sc_ = nullptr;
83
24170
}
84
85
86
21373
bool TLSWrap::InvokeQueued(int status, const char* error_str) {
87
21373
  Debug(this, "InvokeQueued(%d, %s)", status, error_str);
88
21373
  if (!write_callback_scheduled_)
89
5532
    return false;
90
91
15841
  if (current_write_ != nullptr) {
92
1405
    WriteWrap* w = current_write_;
93
1405
    current_write_ = nullptr;
94
1405
    w->Done(status, error_str);
95
  }
96
97
15840
  return true;
98
}
99
100
101
8
void TLSWrap::NewSessionDoneCb() {
102
8
  Debug(this, "NewSessionDoneCb()");
103
8
  Cycle();
104
8
}
105
106
107
12217
void TLSWrap::InitSSL() {
108
  // Initialize SSL – OpenSSL takes ownership of these.
109
12217
  enc_in_ = crypto::NodeBIO::New(env()).release();
110
12217
  enc_out_ = crypto::NodeBIO::New(env()).release();
111
112
12217
  SSL_set_bio(ssl_.get(), enc_in_, enc_out_);
113
114
  // NOTE: This could be overridden in SetVerifyMode
115
12217
  SSL_set_verify(ssl_.get(), SSL_VERIFY_NONE, crypto::VerifyCallback);
116
117
#ifdef SSL_MODE_RELEASE_BUFFERS
118
12217
  SSL_set_mode(ssl_.get(), SSL_MODE_RELEASE_BUFFERS);
119
#endif  // SSL_MODE_RELEASE_BUFFERS
120
121
  // This is default in 1.1.1, but set it anyway, Cycle() doesn't currently
122
  // re-call ClearIn() if SSL_read() returns SSL_ERROR_WANT_READ, so data can be
123
  // left sitting in the incoming enc_in_ and never get processed.
124
  // - https://wiki.openssl.org/index.php/TLS1.3#Non-application_data_records
125
12217
  SSL_set_mode(ssl_.get(), SSL_MODE_AUTO_RETRY);
126
127
12217
  SSL_set_app_data(ssl_.get(), this);
128
  // Using InfoCallback isn't how we are supposed to check handshake progress:
129
  //   https://github.com/openssl/openssl/issues/7199#issuecomment-420915993
130
  //
131
  // Note on when this gets called on various openssl versions:
132
  //   https://github.com/openssl/openssl/issues/7199#issuecomment-420670544
133
12217
  SSL_set_info_callback(ssl_.get(), SSLInfoCallback);
134
135
12217
  if (is_server()) {
136
858
    SSL_CTX_set_tlsext_servername_callback(sc_->ctx_.get(),
137
858
                                           SelectSNIContextCallback);
138
  }
139
140
12217
  ConfigureSecureContext(sc_);
141
142
12217
  SSL_set_cert_cb(ssl_.get(), SSLWrap<TLSWrap>::SSLCertCallback, this);
143
144
12217
  if (is_server()) {
145
858
    SSL_set_accept_state(ssl_.get());
146
11359
  } else if (is_client()) {
147
    // Enough space for server response (hello, cert)
148
11359
    crypto::NodeBIO::FromBIO(enc_in_)->set_initial(kInitialClientBufferLength);
149
11359
    SSL_set_connect_state(ssl_.get());
150
  } else {
151
    // Unexpected
152
    ABORT();
153
  }
154
12217
}
155
156
157
12217
void TLSWrap::Wrap(const FunctionCallbackInfo<Value>& args) {
158
12217
  Environment* env = Environment::GetCurrent(args);
159
160
12217
  CHECK_EQ(args.Length(), 3);
161
24434
  CHECK(args[0]->IsObject());
162
24434
  CHECK(args[1]->IsObject());
163
24434
  CHECK(args[2]->IsBoolean());
164
165
24434
  Local<Object> sc = args[1].As<Object>();
166
36651
  Kind kind = args[2]->IsTrue() ? SSLWrap<TLSWrap>::kServer :
167
12217
                                  SSLWrap<TLSWrap>::kClient;
168
169
24434
  StreamBase* stream = StreamBase::FromObject(args[0].As<Object>());
170
12217
  CHECK_NOT_NULL(stream);
171
172
  Local<Object> obj;
173
24434
  if (!env->tls_wrap_constructor_function()
174
36651
           ->NewInstance(env->context())
175
36651
           .ToLocal(&obj)) {
176
12217
    return;
177
  }
178
179
12217
  TLSWrap* res = new TLSWrap(env, obj, kind, stream, Unwrap<SecureContext>(sc));
180
181
36651
  args.GetReturnValue().Set(res->object());
182
}
183
184
185
3
void TLSWrap::Receive(const FunctionCallbackInfo<Value>& args) {
186
  TLSWrap* wrap;
187
6
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
188
189
3
  CHECK(Buffer::HasInstance(args[0]));
190
3
  char* data = Buffer::Data(args[0]);
191
3
  size_t len = Buffer::Length(args[0]);
192
3
  Debug(wrap, "Receiving %zu bytes injected from JS", len);
193
194
  // Copy given buffer entirely or partiall if handle becomes closed
195


9
  while (len > 0 && wrap->IsAlive() && !wrap->IsClosing()) {
196
3
    uv_buf_t buf = wrap->OnStreamAlloc(len);
197
3
    size_t copy = buf.len > len ? len : buf.len;
198
3
    memcpy(buf.base, data, copy);
199
3
    buf.len = copy;
200
3
    wrap->OnStreamRead(copy, buf);
201
202
3
    data += copy;
203
3
    len -= copy;
204
  }
205
}
206
207
208
1327
void TLSWrap::Start(const FunctionCallbackInfo<Value>& args) {
209
  TLSWrap* wrap;
210
2654
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
211
212
1327
  CHECK(!wrap->started_);
213
214
1327
  wrap->started_ = true;
215
216
  // Send ClientHello handshake
217
1327
  CHECK(wrap->is_client());
218
  // Seems odd to read when when we want to send, but SSL_read() triggers a
219
  // handshake if a session isn't established, and handshake will cause
220
  // encrypted data to become available for output.
221
1327
  wrap->ClearOut();
222
1327
  wrap->EncOut();
223
}
224
225
226
36795
void TLSWrap::SSLInfoCallback(const SSL* ssl_, int where, int ret) {
227
36795
  if (!(where & (SSL_CB_HANDSHAKE_START | SSL_CB_HANDSHAKE_DONE)))
228
69536
    return;
229
230
  // SSL_renegotiate_pending() should take `const SSL*`, but it does not.
231
4054
  SSL* ssl = const_cast<SSL*>(ssl_);
232
4054
  TLSWrap* c = static_cast<TLSWrap*>(SSL_get_app_data(ssl_));
233
4054
  Environment* env = c->env();
234
4054
  HandleScope handle_scope(env->isolate());
235
4054
  Context::Scope context_scope(env->context());
236
4054
  Local<Object> object = c->object();
237
238
4054
  if (where & SSL_CB_HANDSHAKE_START) {
239
    Debug(c, "SSLInfoCallback(SSL_CB_HANDSHAKE_START);");
240
    // Start is tracked to limit number and frequency of renegotiation attempts,
241
    // since excessive renegotiation may be an attack.
242
    Local<Value> callback;
243
244

11855
    if (object->Get(env->context(), env->onhandshakestart_string())
245

14226
          .ToLocal(&callback) && callback->IsFunction()) {
246
2371
      Local<Value> argv[] = { env->GetNow() };
247
4742
      c->MakeCallback(callback.As<Function>(), arraysize(argv), argv);
248
    }
249
  }
250
251
  // SSL_CB_HANDSHAKE_START and SSL_CB_HANDSHAKE_DONE are called
252
  // sending HelloRequest in OpenSSL-1.1.1.
253
  // We need to check whether this is in a renegotiation state or not.
254

4054
  if (where & SSL_CB_HANDSHAKE_DONE && !SSL_renegotiate_pending(ssl)) {
255
    Debug(c, "SSLInfoCallback(SSL_CB_HANDSHAKE_DONE);");
256
1682
    CHECK(!SSL_renegotiate_pending(ssl));
257
    Local<Value> callback;
258
259
1682
    c->established_ = true;
260
261

8410
    if (object->Get(env->context(), env->onhandshakedone_string())
262

10092
          .ToLocal(&callback) && callback->IsFunction()) {
263
1682
      c->MakeCallback(callback.As<Function>(), 0, nullptr);
264
    }
265
4054
  }
266
}
267
268
269
18247
void TLSWrap::EncOut() {
270
18247
  Debug(this, "Trying to write encrypted output");
271
272
  // Ignore cycling data if ClientHello wasn't yet parsed
273
18247
  if (!hello_parser_.IsEnded()) {
274
    Debug(this, "Returning from EncOut(), hello_parser_ active");
275
12019
    return;
276
  }
277
278
  // Write in progress
279
18247
  if (write_size_ != 0) {
280
2609
    Debug(this, "Returning from EncOut(), write currently in progress");
281
2609
    return;
282
  }
283
284
  // Wait for `newSession` callback to be invoked
285
15638
  if (is_awaiting_new_session()) {
286
7
    Debug(this, "Returning from EncOut(), awaiting new session");
287
7
    return;
288
  }
289
290
  // Split-off queue
291

15631
  if (established_ && current_write_ != nullptr) {
292
3417
    Debug(this, "EncOut() setting write_callback_scheduled_");
293
3417
    write_callback_scheduled_ = true;
294
  }
295
296
15631
  if (ssl_ == nullptr) {
297
1
    Debug(this, "Returning from EncOut(), ssl_ == nullptr");
298
1
    return;
299
  }
300
301
  // No encrypted output ready to write to the underlying stream.
302
15630
  if (BIO_pending(enc_out_) == 0) {
303
9309
    Debug(this, "No pending encrypted output");
304
9309
    if (pending_cleartext_input_.empty()) {
305
9118
      if (!in_dowrite_) {
306
9065
        Debug(this, "No pending cleartext input, not inside DoWrite()");
307
9065
        InvokeQueued(0);
308
      } else {
309
53
        Debug(this, "No pending cleartext input, inside DoWrite()");
310
        // TODO(@sam-github, @addaleax) If in_dowrite_ is true, appdata was
311
        // passed to SSL_write().  If we are here, the data was not encrypted to
312
        // enc_out_ yet.  Calling Done() "works", but since the write is not
313
        // flushed, its too soon.  Just returning and letting the next EncOut()
314
        // call Done() passes the test suite, but without more careful analysis,
315
        // its not clear if it is always correct. Not calling Done() could block
316
        // data flow, so for now continue to call Done(), just do it in the next
317
        // tick.
318
159
        env()->SetImmediate([](Environment* env, void* data) {
319
53
            static_cast<TLSWrap*>(data)->InvokeQueued(0);
320
212
        }, this, object());
321
      }
322
    }
323
9308
    return;
324
  }
325
326
  char* data[kSimultaneousBufferCount];
327
  size_t size[arraysize(data)];
328
6321
  size_t count = arraysize(data);
329
  write_size_ = crypto::NodeBIO::FromBIO(enc_out_)->PeekMultiple(data,
330
                                                                 size,
331
6321
                                                                 &count);
332

6321
  CHECK(write_size_ != 0 && count != 0);
333
334
  uv_buf_t buf[arraysize(data)];
335
6321
  uv_buf_t* bufs = buf;
336
18984
  for (size_t i = 0; i < count; i++)
337
12663
    buf[i] = uv_buf_init(data[i], size[i]);
338
339
6321
  Debug(this, "Writing %zu buffers to the underlying stream", count);
340
6321
  StreamWriteResult res = underlying_stream()->Write(bufs, count);
341
6320
  if (res.err != 0) {
342
94
    InvokeQueued(res.err);
343
94
    return;
344
  }
345
346
6226
  if (!res.async) {
347
5632
    Debug(this, "Write finished synchronously");
348
5632
    HandleScope handle_scope(env()->isolate());
349
350
    // Simulate asynchronous finishing, TLS cannot handle this at the moment.
351
16892
    env()->SetImmediate([](Environment* env, void* data) {
352
5630
      static_cast<TLSWrap*>(data)->OnStreamAfterWrite(nullptr, 0);
353
22523
    }, this, object());
354
  }
355
}
356
357
358
6314
void TLSWrap::OnStreamAfterWrite(WriteWrap* req_wrap, int status) {
359
6314
  Debug(this, "OnStreamAfterWrite(status = %d)", status);
360
6314
  if (current_empty_write_ != nullptr) {
361
91
    Debug(this, "Had empty write");
362
91
    WriteWrap* finishing = current_empty_write_;
363
91
    current_empty_write_ = nullptr;
364
91
    finishing->Done(status);
365
91
    return;
366
  }
367
368
6223
  if (ssl_ == nullptr) {
369
1
    Debug(this, "ssl_ == nullptr, marking as cancelled");
370
1
    status = UV_ECANCELED;
371
  }
372
373
  // Handle error
374
6223
  if (status) {
375
7
    if (shutdown_) {
376
2
      Debug(this, "Ignoring error after shutdown");
377
2
      return;
378
    }
379
380
    // Notify about error
381
5
    InvokeQueued(status);
382
5
    return;
383
  }
384
385
  // Commit
386
6216
  crypto::NodeBIO::FromBIO(enc_out_)->Read(nullptr, write_size_);
387
388
  // Ensure that the progress will be made and `InvokeQueued` will be called.
389
6216
  ClearIn();
390
391
  // Try writing more data
392
6216
  write_size_ = 0;
393
6216
  EncOut();
394
}
395
396
397
10361
Local<Value> TLSWrap::GetSSLError(int status, int* err, std::string* msg) {
398
10361
  EscapableHandleScope scope(env()->isolate());
399
400
  // ssl_ is already destroyed in reading EOF by close notify alert.
401
10361
  if (ssl_ == nullptr)
402
    return Local<Value>();
403
404
10361
  *err = SSL_get_error(ssl_.get(), status);
405

10361
  switch (*err) {
406
    case SSL_ERROR_NONE:
407
    case SSL_ERROR_WANT_READ:
408
    case SSL_ERROR_WANT_WRITE:
409
    case SSL_ERROR_WANT_X509_LOOKUP:
410
9018
      return Local<Value>();
411
412
    case SSL_ERROR_ZERO_RETURN:
413
1436
      return scope.Escape(env()->zero_return_string());
414
415
    case SSL_ERROR_SSL:
416
    case SSL_ERROR_SYSCALL:
417
      {
418
625
        unsigned long ssl_err = ERR_peek_error();  // NOLINT(runtime/int)
419
625
        BIO* bio = BIO_new(BIO_s_mem());
420
625
        ERR_print_errors(bio);
421
422
        BUF_MEM* mem;
423
625
        BIO_get_mem_ptr(bio, &mem);
424
425
625
        Isolate* isolate = env()->isolate();
426
625
        Local<Context> context = isolate->GetCurrentContext();
427
428
        Local<String> message =
429
625
            OneByteString(isolate, mem->data, mem->length);
430
625
        Local<Value> exception = Exception::Error(message);
431
1250
        Local<Object> obj = exception->ToObject(context).ToLocalChecked();
432
433
625
        const char* ls = ERR_lib_error_string(ssl_err);
434
625
        const char* fs = ERR_func_error_string(ssl_err);
435
625
        const char* rs = ERR_reason_error_string(ssl_err);
436
437
625
        if (ls != nullptr)
438
          obj->Set(context, env()->library_string(),
439
2484
                   OneByteString(isolate, ls)).Check();
440
625
        if (fs != nullptr)
441
          obj->Set(context, env()->function_string(),
442
2484
                   OneByteString(isolate, fs)).Check();
443
625
        if (rs != nullptr) {
444
          obj->Set(context, env()->reason_string(),
445
2484
                   OneByteString(isolate, rs)).Check();
446
447
          // SSL has no API to recover the error name from the number, so we
448
          // transform reason strings like "this error" to "ERR_SSL_THIS_ERROR",
449
          // which ends up being close to the original error macro name.
450
621
          std::string code(rs);
451
452
13354
          for (auto& c : code) {
453
12733
            if (c == ' ')
454
1249
              c = '_';
455
            else
456
11484
              c = ToUpper(c);
457
          }
458
          obj->Set(context, env()->code_string(),
459
2484
                   OneByteString(isolate, ("ERR_SSL_" + code).c_str()))
460
1863
                     .Check();
461
        }
462
463
625
        if (msg != nullptr)
464
3
          msg->assign(mem->data, mem->data + mem->length);
465
466
625
        BIO_free_all(bio);
467
468
        return scope.Escape(exception);
469
      }
470
471
    default:
472
      UNREACHABLE();
473
  }
474
  UNREACHABLE();
475
}
476
477
478
9999
void TLSWrap::ClearOut() {
479
9999
  Debug(this, "Trying to read cleartext output");
480
  // Ignore cycling data if ClientHello wasn't yet parsed
481
9999
  if (!hello_parser_.IsEnded()) {
482
1
    Debug(this, "Returning from ClearOut(), hello_parser_ active");
483
737
    return;
484
  }
485
486
  // No reads after EOF
487
9998
  if (eof_) {
488
16
    Debug(this, "Returning from ClearOut(), EOF reached");
489
16
    return;
490
  }
491
492
9982
  if (ssl_ == nullptr) {
493
    Debug(this, "Returning from ClearOut(), ssl_ == nullptr");
494
    return;
495
  }
496
497
9982
  crypto::MarkPopErrorOnReturn mark_pop_error_on_return;
498
499
  char out[kClearOutChunkSize];
500
  int read;
501
  for (;;) {
502
34705
    read = SSL_read(ssl_.get(), out, sizeof(out));
503
34705
    Debug(this, "Read %d bytes of cleartext output", read);
504
505
34705
    if (read <= 0)
506
9980
      break;
507
508
24725
    char* current = out;
509
74175
    while (read > 0) {
510
24727
      int avail = read;
511
512
24727
      uv_buf_t buf = EmitAlloc(avail);
513
24727
      if (static_cast<int>(buf.len) < avail)
514
2
        avail = buf.len;
515
24727
      memcpy(buf.base, current, avail);
516
24727
      EmitRead(avail, buf);
517
518
      // Caveat emptor: OnRead() calls into JS land which can result in
519
      // the SSL context object being destroyed.  We have to carefully
520
      // check that ssl_ != nullptr afterwards.
521
24726
      if (ssl_ == nullptr) {
522
1
        Debug(this, "Returning from read loop, ssl_ == nullptr");
523
1
        return;
524
      }
525
526
24725
      read -= avail;
527
24725
      current += avail;
528
    }
529
24723
  }
530
531
9980
  int flags = SSL_get_shutdown(ssl_.get());
532

9980
  if (!eof_ && flags & SSL_RECEIVED_SHUTDOWN) {
533
772
    eof_ = true;
534
772
    EmitRead(UV_EOF);
535
  }
536
537
  // We need to check whether an error occurred or the connection was
538
  // shutdown cleanly (SSL_ERROR_ZERO_RETURN) even when read == 0.
539
  // See node#1642 and SSL_read(3SSL) for details.
540
9980
  if (read <= 0) {
541
9980
    HandleScope handle_scope(env()->isolate());
542
    int err;
543
9980
    Local<Value> arg = GetSSLError(read, &err, nullptr);
544
545
    // Ignore ZERO_RETURN after EOF, it is basically not a error
546

9980
    if (err == SSL_ERROR_ZERO_RETURN && eof_)
547
718
      return;
548
549
9262
    if (!arg.IsEmpty()) {
550
622
      Debug(this, "Got SSL error (%d), calling onerror", err);
551
      // When TLS Alert are stored in wbio,
552
      // it should be flushed to socket before destroyed.
553
622
      if (BIO_pending(enc_out_) != 0)
554
567
        EncOut();
555
556
622
      MakeCallback(env()->onerror_string(), 1, &arg);
557
9262
    }
558
9262
  }
559
}
560
561
562
14116
void TLSWrap::ClearIn() {
563
14116
  Debug(this, "Trying to write cleartext input");
564
  // Ignore cycling data if ClientHello wasn't yet parsed
565
14116
  if (!hello_parser_.IsEnded()) {
566
    Debug(this, "Returning from ClearIn(), hello_parser_ active");
567
    return;
568
  }
569
570
14116
  if (ssl_ == nullptr) {
571
    Debug(this, "Returning from ClearIn(), ssl_ == nullptr");
572
    return;
573
  }
574
575
14116
  std::vector<uv_buf_t> buffers;
576
14116
  buffers.swap(pending_cleartext_input_);
577
578
28232
  crypto::MarkPopErrorOnReturn mark_pop_error_on_return;
579
580
  size_t i;
581
14116
  int written = 0;
582
14292
  for (i = 0; i < buffers.size(); ++i) {
583
386
    size_t avail = buffers[i].len;
584
386
    char* data = buffers[i].base;
585
386
    written = SSL_write(ssl_.get(), data, avail);
586
386
    Debug(this, "Writing %zu bytes, written = %d", avail, written);
587

386
    CHECK(written == -1 || written == static_cast<int>(avail));
588
386
    if (written == -1)
589
210
      break;
590
  }
591
592
  // All written
593
14116
  if (i == buffers.size()) {
594
13906
    Debug(this, "Successfully wrote all data to SSL");
595
    // We wrote all the buffers, so no writes failed (written < 0 on failure).
596
13906
    CHECK_GE(written, 0);
597
13906
    return;
598
  }
599
600
  // Error or partial write
601
420
  HandleScope handle_scope(env()->isolate());
602
210
  Context::Scope context_scope(env()->context());
603
604
  int err;
605
420
  std::string error_str;
606
210
  Local<Value> arg = GetSSLError(written, &err, &error_str);
607
210
  if (!arg.IsEmpty()) {
608
2
    Debug(this, "Got SSL error (%d)", err);
609
2
    write_callback_scheduled_ = true;
610
    // TODO(@sam-github) Should forward an error object with
611
    // .code/.function/.etc, if possible.
612
2
    InvokeQueued(UV_EPROTO, error_str.c_str());
613
  } else {
614
416
    Debug(this, "Pushing back %zu buffers", buffers.size() - i);
615
    // Push back the not-yet-written pending buffers into their queue.
616
    // This can be skipped in the error case because no further writes
617
    // would succeed anyway.
618
208
    pending_cleartext_input_.insert(pending_cleartext_input_.end(),
619
                                    buffers.begin() + i,
620
416
                                    buffers.end());
621
  }
622
623
14326
  return;
624
}
625
626
627
std::string TLSWrap::diagnostic_name() const {
628
  std::string name = "TLSWrap ";
629
  if (is_server())
630
    name += "server (";
631
  else
632
    name += "client (";
633
  name += std::to_string(static_cast<int64_t>(get_async_id())) + ")";
634
  return name;
635
}
636
637
638
41058
AsyncWrap* TLSWrap::GetAsyncWrap() {
639
41058
  return static_cast<AsyncWrap*>(this);
640
}
641
642
643
1275
bool TLSWrap::IsIPCPipe() {
644
1275
  return underlying_stream()->IsIPCPipe();
645
}
646
647
648
2
int TLSWrap::GetFD() {
649
2
  return underlying_stream()->GetFD();
650
}
651
652
653
3067
bool TLSWrap::IsAlive() {
654
6134
  return ssl_ != nullptr &&
655

6133
      stream_ != nullptr &&
656
6133
      underlying_stream()->IsAlive();
657
}
658
659
660
3
bool TLSWrap::IsClosing() {
661
3
  return underlying_stream()->IsClosing();
662
}
663
664
665
666
1010
int TLSWrap::ReadStart() {
667
1010
  Debug(this, "ReadStart()");
668
1010
  if (stream_ != nullptr)
669
1010
    return stream_->ReadStart();
670
  return 0;
671
}
672
673
674
368
int TLSWrap::ReadStop() {
675
368
  Debug(this, "ReadStop()");
676
368
  if (stream_ != nullptr)
677
362
    return stream_->ReadStop();
678
6
  return 0;
679
}
680
681
682
3266
const char* TLSWrap::Error() const {
683
3266
  return error_.empty() ? nullptr : error_.c_str();
684
}
685
686
687
void TLSWrap::ClearError() {
688
  error_.clear();
689
}
690
691
692
// Called by StreamBase::Write() to request async write of clear text into SSL.
693
// TODO(@sam-github) Should there be a TLSWrap::DoTryWrite()?
694
1498
int TLSWrap::DoWrite(WriteWrap* w,
695
                     uv_buf_t* bufs,
696
                     size_t count,
697
                     uv_stream_t* send_handle) {
698
1498
  CHECK_NULL(send_handle);
699
1498
  Debug(this, "DoWrite()");
700
701
1498
  if (ssl_ == nullptr) {
702
    ClearError();
703
    error_ = "Write after DestroySSL";
704
    return UV_EPROTO;
705
  }
706
707
1498
  bool empty = true;
708
  size_t i;
709
1726
  for (i = 0; i < count; i++) {
710
1543
    if (bufs[i].len > 0) {
711
1315
      empty = false;
712
1315
      break;
713
    }
714
  }
715
716
  // We want to trigger a Write() on the underlying stream to drive the stream
717
  // system, but don't want to encrypt empty buffers into a TLS frame, so see
718
  // if we can find something to Write().
719
  // First, call ClearOut(). It does an SSL_read(), which might cause handshake
720
  // or other internal messages to be encrypted. If it does, write them later
721
  // with EncOut().
722
  // If there is still no encrypted output, call Write(bufs) on the underlying
723
  // stream. Since the bufs are empty, it won't actually write non-TLS data
724
  // onto the socket, we just want the side-effects. After, make sure the
725
  // WriteWrap was accepted by the stream, or that we call Done() on it.
726
1498
  if (empty) {
727
183
    Debug(this, "Empty write");
728
183
    ClearOut();
729
183
    if (BIO_pending(enc_out_) == 0) {
730
91
      Debug(this, "No pending encrypted output, writing to underlying stream");
731
91
      CHECK_NULL(current_empty_write_);
732
91
      current_empty_write_ = w;
733
      StreamWriteResult res =
734
91
          underlying_stream()->Write(bufs, count, send_handle);
735
91
      if (!res.async) {
736
273
        env()->SetImmediate([](Environment* env, void* data) {
737
91
          TLSWrap* self = static_cast<TLSWrap*>(data);
738
91
          self->OnStreamAfterWrite(self->current_empty_write_, 0);
739
364
        }, this, object());
740
      }
741
91
      return 0;
742
    }
743
  }
744
745
  // Store the current write wrap
746
1407
  CHECK_NULL(current_write_);
747
1407
  current_write_ = w;
748
749
  // Write encrypted data to underlying stream and call Done().
750
1407
  if (empty) {
751
92
    EncOut();
752
92
    return 0;
753
  }
754
755
1315
  crypto::MarkPopErrorOnReturn mark_pop_error_on_return;
756
757
1315
  int written = 0;
758
20281
  for (i = 0; i < count; i++) {
759
19137
    written = SSL_write(ssl_.get(), bufs[i].base, bufs[i].len);
760

19137
    CHECK(written == -1 || written == static_cast<int>(bufs[i].len));
761
19137
    Debug(this, "Writing %zu bytes, written = %d", bufs[i].len, written);
762
19137
    if (written == -1)
763
171
      break;
764
  }
765
766
1315
  if (i != count) {
767
    int err;
768
171
    Local<Value> arg = GetSSLError(written, &err, &error_);
769
770
    // If we stopped writing because of an error, it's fatal, discard the data.
771
171
    if (!arg.IsEmpty()) {
772
1
      Debug(this, "Got SSL error (%d), returning UV_EPROTO", err);
773
1
      current_write_ = nullptr;
774
1
      return UV_EPROTO;
775
    }
776
777
340
    Debug(this, "Saving %zu buffers for later write", count - i);
778
    // Otherwise, save unwritten data so it can be written later by ClearIn().
779
170
    pending_cleartext_input_.insert(pending_cleartext_input_.end(),
780
                                    &bufs[i],
781
340
                                    &bufs[count]);
782
  }
783
784
  // Write any encrypted/handshake output that may be ready.
785
  // Guard against sync call of current_write_->Done(), its unsupported.
786
1314
  in_dowrite_ = true;
787
1314
  EncOut();
788
1314
  in_dowrite_ = false;
789
790
1314
  return 0;
791
}
792
793
794
8445
uv_buf_t TLSWrap::OnStreamAlloc(size_t suggested_size) {
795
8445
  CHECK_NOT_NULL(ssl_);
796
797
8445
  size_t size = suggested_size;
798
8445
  char* base = crypto::NodeBIO::FromBIO(enc_in_)->PeekWritable(&size);
799
8445
  return uv_buf_init(base, size);
800
}
801
802
803
8466
void TLSWrap::OnStreamRead(ssize_t nread, const uv_buf_t& buf) {
804
8466
  Debug(this, "Read %zd bytes from underlying stream", nread);
805
8466
  if (nread < 0)  {
806
    // Error should be emitted only after all data was read
807
589
    ClearOut();
808
809
    // Ignore EOF if received close_notify
810
589
    if (nread == UV_EOF) {
811
588
      if (eof_)
812
16
        return;
813
572
      eof_ = true;
814
    }
815
816
573
    EmitRead(nread);
817
573
    return;
818
  }
819
820
  // DestroySSL() is the only thing that un-sets ssl_, but that also removes
821
  // this TLSWrap as a stream listener, so we should not receive OnStreamRead()
822
  // calls anymore.
823
7877
  CHECK(ssl_);
824
825
  // Commit the amount of data actually read into the peeked/allocated buffer
826
  // from the underlying stream.
827
7877
  crypto::NodeBIO* enc_in = crypto::NodeBIO::FromBIO(enc_in_);
828
7877
  enc_in->Commit(nread);
829
830
  // Parse ClientHello first, if we need to. It's only parsed if session event
831
  // listeners are used on the server side.  "ended" is the initial state, so
832
  // can mean parsing was never started, or that parsing is finished. Either
833
  // way, ended means we can give the buffered data to SSL.
834
7877
  if (!hello_parser_.IsEnded()) {
835
20
    size_t avail = 0;
836
20
    uint8_t* data = reinterpret_cast<uint8_t*>(enc_in->Peek(&avail));
837

20
    CHECK_IMPLIES(data == nullptr, avail == 0);
838
20
    Debug(this, "Passing %zu bytes to the hello parser", avail);
839
20
    return hello_parser_.Parse(data, avail);
840
  }
841
842
  // Cycle OpenSSL's state
843
7857
  Cycle();
844
}
845
846
847
832
ShutdownWrap* TLSWrap::CreateShutdownWrap(Local<Object> req_wrap_object) {
848
832
  return underlying_stream()->CreateShutdownWrap(req_wrap_object);
849
}
850
851
852
832
int TLSWrap::DoShutdown(ShutdownWrap* req_wrap) {
853
832
  Debug(this, "DoShutdown()");
854
832
  crypto::MarkPopErrorOnReturn mark_pop_error_on_return;
855
856

832
  if (ssl_ && SSL_shutdown(ssl_.get()) == 0)
857
796
    SSL_shutdown(ssl_.get());
858
859
832
  shutdown_ = true;
860
832
  EncOut();
861
832
  return stream_->DoShutdown(req_wrap);
862
}
863
864
865
12197
void TLSWrap::SetVerifyMode(const FunctionCallbackInfo<Value>& args) {
866
  TLSWrap* wrap;
867
24394
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
868
869
12197
  CHECK_EQ(args.Length(), 2);
870
24394
  CHECK(args[0]->IsBoolean());
871
24394
  CHECK(args[1]->IsBoolean());
872
12197
  CHECK_NOT_NULL(wrap->ssl_);
873
874
  int verify_mode;
875
12197
  if (wrap->is_server()) {
876
1676
    bool request_cert = args[0]->IsTrue();
877
838
    if (!request_cert) {
878
      // If no cert is requested, there will be none to reject as unauthorized.
879
758
      verify_mode = SSL_VERIFY_NONE;
880
    } else {
881
160
      bool reject_unauthorized = args[1]->IsTrue();
882
80
      verify_mode = SSL_VERIFY_PEER;
883
80
      if (reject_unauthorized)
884
48
        verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
885
    }
886
  } else {
887
    // Servers always send a cert if the cipher is not anonymous (anon is
888
    // disabled by default), so use VERIFY_NONE and check the cert after the
889
    // handshake has completed.
890
11359
    verify_mode = SSL_VERIFY_NONE;
891
  }
892
893
  // Always allow a connection. We'll reject in javascript.
894
12197
  SSL_set_verify(wrap->ssl_.get(), verify_mode, crypto::VerifyCallback);
895
}
896
897
898
209
void TLSWrap::EnableSessionCallbacks(
899
    const FunctionCallbackInfo<Value>& args) {
900
  TLSWrap* wrap;
901
398
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
902
209
  CHECK_NOT_NULL(wrap->ssl_);
903
209
  wrap->enable_session_callbacks();
904
905
  // Clients don't use the HelloParser.
906
209
  if (wrap->is_client())
907
189
    return;
908
909
20
  crypto::NodeBIO::FromBIO(wrap->enc_in_)->set_initial(kMaxHelloLength);
910
  wrap->hello_parser_.Start(SSLWrap<TLSWrap>::OnClientHello,
911
                            OnClientHelloParseEnd,
912
20
                            wrap);
913
}
914
915
// Check required capabilities were not excluded from the OpenSSL build:
916
// - OPENSSL_NO_SSL_TRACE excludes SSL_trace()
917
// - OPENSSL_NO_STDIO excludes BIO_new_fp()
918
// HAVE_SSL_TRACE is available on the internal tcp_wrap binding for the tests.
919
#if defined(OPENSSL_NO_SSL_TRACE) || defined(OPENSSL_NO_STDIO)
920
# define HAVE_SSL_TRACE 0
921
#else
922
# define HAVE_SSL_TRACE 1
923
#endif
924
925
4
void TLSWrap::EnableTrace(
926
    const FunctionCallbackInfo<Value>& args) {
927
  TLSWrap* wrap;
928
8
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
929
930
#if HAVE_SSL_TRACE
931
4
  if (wrap->ssl_) {
932
4
    BIO* b = BIO_new_fp(stderr,  BIO_NOCLOSE | BIO_FP_TEXT);
933
4
    SSL_set_msg_callback(wrap->ssl_.get(), SSL_trace);
934
4
    SSL_set_msg_callback_arg(wrap->ssl_.get(), b);
935
  }
936
#endif
937
}
938
939
12154
void TLSWrap::DestroySSL(const FunctionCallbackInfo<Value>& args) {
940
  TLSWrap* wrap;
941
24308
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
942
12154
  Debug(wrap, "DestroySSL()");
943
944
  // If there is a write happening, mark it as finished.
945
12154
  wrap->write_callback_scheduled_ = true;
946
947
  // And destroy
948
12154
  wrap->InvokeQueued(UV_ECANCELED, "Canceled because of SSL destruction");
949
950
  // Destroy the SSL structure and friends
951
12154
  wrap->SSLWrap<TLSWrap>::DestroySSL();
952
12154
  wrap->enc_in_ = nullptr;
953
12154
  wrap->enc_out_ = nullptr;
954
955
12154
  if (wrap->stream_ != nullptr)
956
12154
    wrap->stream_->RemoveStreamListener(wrap);
957
12154
  Debug(wrap, "DestroySSL() finished");
958
}
959
960
961
20
void TLSWrap::EnableCertCb(const FunctionCallbackInfo<Value>& args) {
962
  TLSWrap* wrap;
963
40
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
964
20
  wrap->WaitForCertCb(OnClientHelloParseEnd, wrap);
965
}
966
967
968
35
void TLSWrap::OnClientHelloParseEnd(void* arg) {
969
35
  TLSWrap* c = static_cast<TLSWrap*>(arg);
970
  Debug(c, "OnClientHelloParseEnd()");
971
35
  c->Cycle();
972
35
}
973
974
975
1680
void TLSWrap::GetServername(const FunctionCallbackInfo<Value>& args) {
976
1680
  Environment* env = Environment::GetCurrent(args);
977
978
  TLSWrap* wrap;
979
3360
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
980
981
1680
  CHECK_NOT_NULL(wrap->ssl_);
982
983
1680
  const char* servername = SSL_get_servername(wrap->ssl_.get(),
984
1680
                                              TLSEXT_NAMETYPE_host_name);
985
1680
  if (servername != nullptr) {
986
1188
    args.GetReturnValue().Set(OneByteString(env->isolate(), servername));
987
  } else {
988
2568
    args.GetReturnValue().Set(false);
989
  }
990
}
991
992
993
189
void TLSWrap::SetServername(const FunctionCallbackInfo<Value>& args) {
994
189
  Environment* env = Environment::GetCurrent(args);
995
996
  TLSWrap* wrap;
997
378
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
998
999
189
  CHECK_EQ(args.Length(), 1);
1000
567
  CHECK(args[0]->IsString());
1001
189
  CHECK(!wrap->started_);
1002
189
  CHECK(wrap->is_client());
1003
1004
189
  CHECK_NOT_NULL(wrap->ssl_);
1005
1006
378
  node::Utf8Value servername(env->isolate(), args[0].As<String>());
1007
189
  SSL_set_tlsext_host_name(wrap->ssl_.get(), *servername);
1008
}
1009
1010
1011
903
int TLSWrap::SelectSNIContextCallback(SSL* s, int* ad, void* arg) {
1012
903
  TLSWrap* p = static_cast<TLSWrap*>(SSL_get_app_data(s));
1013
903
  Environment* env = p->env();
1014
1015
903
  const char* servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
1016
1017
903
  if (servername == nullptr)
1018
692
    return SSL_TLSEXT_ERR_OK;
1019
1020
211
  HandleScope handle_scope(env->isolate());
1021
211
  Context::Scope context_scope(env->context());
1022
1023
  // Call the SNI callback and use its return value as context
1024
211
  Local<Object> object = p->object();
1025
  Local<Value> ctx;
1026
1027
844
  if (!object->Get(env->context(), env->sni_context_string()).ToLocal(&ctx))
1028
    return SSL_TLSEXT_ERR_NOACK;
1029
1030
  // Not an object, probably undefined or null
1031
211
  if (!ctx->IsObject())
1032
211
    return SSL_TLSEXT_ERR_NOACK;
1033
1034
  Local<FunctionTemplate> cons = env->secure_context_constructor_template();
1035
  if (!cons->HasInstance(ctx)) {
1036
    // Failure: incorrect SNI context object
1037
    Local<Value> err = Exception::TypeError(env->sni_context_err_string());
1038
    p->MakeCallback(env->onerror_string(), 1, &err);
1039
    return SSL_TLSEXT_ERR_NOACK;
1040
  }
1041
1042
  p->sni_context_.Reset(env->isolate(), ctx);
1043
1044
  SecureContext* sc = Unwrap<SecureContext>(ctx.As<Object>());
1045
  CHECK_NOT_NULL(sc);
1046
  p->SetSNIContext(sc);
1047
211
  return SSL_TLSEXT_ERR_OK;
1048
}
1049
1050
1051
3
void TLSWrap::GetWriteQueueSize(const FunctionCallbackInfo<Value>& info) {
1052
  TLSWrap* wrap;
1053
3
  ASSIGN_OR_RETURN_UNWRAP(&wrap, info.This());
1054
1055
3
  if (wrap->ssl_ == nullptr) {
1056
    info.GetReturnValue().Set(0);
1057
    return;
1058
  }
1059
1060
3
  uint32_t write_queue_size = BIO_pending(wrap->enc_out_);
1061
6
  info.GetReturnValue().Set(write_queue_size);
1062
}
1063
1064
1065
2
void TLSWrap::MemoryInfo(MemoryTracker* tracker) const {
1066
2
  tracker->TrackField("error", error_);
1067
2
  tracker->TrackField("pending_cleartext_input", pending_cleartext_input_);
1068
2
  if (enc_in_ != nullptr)
1069
2
    tracker->TrackField("enc_in", crypto::NodeBIO::FromBIO(enc_in_));
1070
2
  if (enc_out_ != nullptr)
1071
2
    tracker->TrackField("enc_out", crypto::NodeBIO::FromBIO(enc_out_));
1072
2
}
1073
1074
1075
478
void TLSWrap::Initialize(Local<Object> target,
1076
                         Local<Value> unused,
1077
                         Local<Context> context,
1078
                         void* priv) {
1079
478
  Environment* env = Environment::GetCurrent(context);
1080
1081
478
  env->SetMethod(target, "wrap", TLSWrap::Wrap);
1082
1083
1912
  NODE_DEFINE_CONSTANT(target, HAVE_SSL_TRACE);
1084
1085
478
  Local<FunctionTemplate> t = BaseObject::MakeLazilyInitializedJSTemplate(env);
1086
  Local<String> tlsWrapString =
1087
478
      FIXED_ONE_BYTE_STRING(env->isolate(), "TLSWrap");
1088
478
  t->SetClassName(tlsWrapString);
1089
478
  t->InstanceTemplate()
1090
956
    ->SetInternalFieldCount(StreamBase::kStreamBaseFieldCount);
1091
1092
  Local<FunctionTemplate> get_write_queue_size =
1093
      FunctionTemplate::New(env->isolate(),
1094
                            GetWriteQueueSize,
1095
                            env->as_callback_data(),
1096
956
                            Signature::New(env->isolate(), t));
1097
1434
  t->PrototypeTemplate()->SetAccessorProperty(
1098
      env->write_queue_size_string(),
1099
      get_write_queue_size,
1100
      Local<FunctionTemplate>(),
1101
1434
      static_cast<PropertyAttribute>(ReadOnly | DontDelete));
1102
1103
956
  t->Inherit(AsyncWrap::GetConstructorTemplate(env));
1104
478
  env->SetProtoMethod(t, "receive", Receive);
1105
478
  env->SetProtoMethod(t, "start", Start);
1106
478
  env->SetProtoMethod(t, "setVerifyMode", SetVerifyMode);
1107
478
  env->SetProtoMethod(t, "enableSessionCallbacks", EnableSessionCallbacks);
1108
478
  env->SetProtoMethod(t, "enableTrace", EnableTrace);
1109
478
  env->SetProtoMethod(t, "destroySSL", DestroySSL);
1110
478
  env->SetProtoMethod(t, "enableCertCb", EnableCertCb);
1111
1112
478
  StreamBase::AddMethods(env, t);
1113
478
  SSLWrap<TLSWrap>::AddMethods(env, t);
1114
1115
478
  env->SetProtoMethod(t, "getServername", GetServername);
1116
478
  env->SetProtoMethod(t, "setServername", SetServername);
1117
1118
  env->set_tls_wrap_constructor_function(
1119
1434
      t->GetFunction(env->context()).ToLocalChecked());
1120
1121
  target->Set(env->context(),
1122
              tlsWrapString,
1123
2390
              t->GetFunction(env->context()).ToLocalChecked()).Check();
1124
478
}
1125
1126
}  // namespace node
1127
1128
4524
NODE_MODULE_CONTEXT_AWARE_INTERNAL(tls_wrap, node::TLSWrap::Initialize)