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: 524 559 93.7 %
Date: 2019-07-28 22:34:34 Branches: 240 336 71.4 %

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


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

12025
    if (object->Get(env->context(), env->onhandshakestart_string())
246

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

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

8555
    if (object->Get(env->context(), env->onhandshakedone_string())
263

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

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

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

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

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

11061
    if (err == SSL_ERROR_ZERO_RETURN && eof_)
548
764
      return;
549
550
10297
    if (!arg.IsEmpty()) {
551
622
      Debug(this, "Got SSL error (%d), calling onerror", err);
552
      // When TLS Alert are stored in wbio,
553
      // it should be flushed to socket before destroyed.
554
622
      if (BIO_pending(enc_out_) != 0)
555
567
        EncOut();
556
557
622
      MakeCallback(env()->onerror_string(), 1, &arg);
558
10297
    }
559
10297
  }
560
}
561
562
563
15292
void TLSWrap::ClearIn() {
564
15292
  Debug(this, "Trying to write cleartext input");
565
  // Ignore cycling data if ClientHello wasn't yet parsed
566
15292
  if (!hello_parser_.IsEnded()) {
567
    Debug(this, "Returning from ClearIn(), hello_parser_ active");
568
14871
    return;
569
  }
570
571
15292
  if (ssl_ == nullptr) {
572
    Debug(this, "Returning from ClearIn(), ssl_ == nullptr");
573
    return;
574
  }
575
576
15292
  if (pending_cleartext_input_.size() == 0) {
577
14651
    Debug(this, "Returning from ClearIn(), no pending data");
578
14651
    return;
579
  }
580
581
641
  AllocatedBuffer data = std::move(pending_cleartext_input_);
582
1062
  crypto::MarkPopErrorOnReturn mark_pop_error_on_return;
583
584
641
  int written = SSL_write(ssl_.get(), data.data(), data.size());
585
1282
  Debug(this, "Writing %zu bytes, written = %d", data.size(), written);
586

641
  CHECK(written == -1 || written == static_cast<int>(data.size()));
587
588
  // All written
589
641
  if (written != -1) {
590
220
    Debug(this, "Successfully wrote all data to SSL");
591
220
    return;
592
  }
593
594
  // Error or partial write
595
842
  HandleScope handle_scope(env()->isolate());
596
421
  Context::Scope context_scope(env()->context());
597
598
  int err;
599
842
  std::string error_str;
600
421
  Local<Value> arg = GetSSLError(written, &err, &error_str);
601
421
  if (!arg.IsEmpty()) {
602
2
    Debug(this, "Got SSL error (%d)", err);
603
2
    write_callback_scheduled_ = true;
604
    // TODO(@sam-github) Should forward an error object with
605
    // .code/.function/.etc, if possible.
606
2
    InvokeQueued(UV_EPROTO, error_str.c_str());
607
  } else {
608
419
    Debug(this, "Pushing data back");
609
    // Push back the not-yet-written data. This can be skipped in the error
610
    // case because no further writes would succeed anyway.
611
419
    pending_cleartext_input_ = std::move(data);
612
421
  }
613
}
614
615
616
std::string TLSWrap::diagnostic_name() const {
617
  std::string name = "TLSWrap ";
618
  if (is_server())
619
    name += "server (";
620
  else
621
    name += "client (";
622
  name += std::to_string(static_cast<int64_t>(get_async_id())) + ")";
623
  return name;
624
}
625
626
627
25329
AsyncWrap* TLSWrap::GetAsyncWrap() {
628
25329
  return static_cast<AsyncWrap*>(this);
629
}
630
631
632
1255
bool TLSWrap::IsIPCPipe() {
633
1255
  return underlying_stream()->IsIPCPipe();
634
}
635
636
637
2
int TLSWrap::GetFD() {
638
2
  return underlying_stream()->GetFD();
639
}
640
641
642
3206
bool TLSWrap::IsAlive() {
643
6412
  return ssl_ != nullptr &&
644

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

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

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

875
  if (ssl_ && SSL_shutdown(ssl_.get()) == 0)
854
838
    SSL_shutdown(ssl_.get());
855
856
875
  shutdown_ = true;
857
875
  EncOut();
858
875
  return stream_->DoShutdown(req_wrap);
859
}
860
861
862
12231
void TLSWrap::SetVerifyMode(const FunctionCallbackInfo<Value>& args) {
863
  TLSWrap* wrap;
864
24462
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
865
866
12231
  CHECK_EQ(args.Length(), 2);
867
24462
  CHECK(args[0]->IsBoolean());
868
24462
  CHECK(args[1]->IsBoolean());
869
12231
  CHECK_NOT_NULL(wrap->ssl_);
870
871
  int verify_mode;
872
12231
  if (wrap->is_server()) {
873
1656
    bool request_cert = args[0]->IsTrue();
874
828
    if (!request_cert) {
875
      // If no cert is requested, there will be none to reject as unauthorized.
876
746
      verify_mode = SSL_VERIFY_NONE;
877
    } else {
878
164
      bool reject_unauthorized = args[1]->IsTrue();
879
82
      verify_mode = SSL_VERIFY_PEER;
880
82
      if (reject_unauthorized)
881
48
        verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
882
    }
883
  } else {
884
    // Servers always send a cert if the cipher is not anonymous (anon is
885
    // disabled by default), so use VERIFY_NONE and check the cert after the
886
    // handshake has completed.
887
11403
    verify_mode = SSL_VERIFY_NONE;
888
  }
889
890
  // Always allow a connection. We'll reject in javascript.
891
12231
  SSL_set_verify(wrap->ssl_.get(), verify_mode, crypto::VerifyCallback);
892
}
893
894
895
263
void TLSWrap::EnableSessionCallbacks(
896
    const FunctionCallbackInfo<Value>& args) {
897
  TLSWrap* wrap;
898
506
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
899
263
  CHECK_NOT_NULL(wrap->ssl_);
900
263
  wrap->enable_session_callbacks();
901
902
  // Clients don't use the HelloParser.
903
263
  if (wrap->is_client())
904
243
    return;
905
906
20
  crypto::NodeBIO::FromBIO(wrap->enc_in_)->set_initial(kMaxHelloLength);
907
  wrap->hello_parser_.Start(SSLWrap<TLSWrap>::OnClientHello,
908
                            OnClientHelloParseEnd,
909
20
                            wrap);
910
}
911
912
2
void TLSWrap::EnableKeylogCallback(
913
    const FunctionCallbackInfo<Value>& args) {
914
  TLSWrap* wrap;
915
4
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
916
2
  CHECK_NOT_NULL(wrap->sc_);
917
  SSL_CTX_set_keylog_callback(wrap->sc_->ctx_.get(),
918
2
      SSLWrap<TLSWrap>::KeylogCallback);
919
}
920
921
// Check required capabilities were not excluded from the OpenSSL build:
922
// - OPENSSL_NO_SSL_TRACE excludes SSL_trace()
923
// - OPENSSL_NO_STDIO excludes BIO_new_fp()
924
// HAVE_SSL_TRACE is available on the internal tcp_wrap binding for the tests.
925
#if defined(OPENSSL_NO_SSL_TRACE) || defined(OPENSSL_NO_STDIO)
926
# define HAVE_SSL_TRACE 0
927
#else
928
# define HAVE_SSL_TRACE 1
929
#endif
930
931
4
void TLSWrap::EnableTrace(
932
    const FunctionCallbackInfo<Value>& args) {
933
  TLSWrap* wrap;
934
8
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
935
936
#if HAVE_SSL_TRACE
937
4
  if (wrap->ssl_) {
938
4
    wrap->bio_trace_.reset(BIO_new_fp(stderr,  BIO_NOCLOSE | BIO_FP_TEXT));
939
    SSL_set_msg_callback(wrap->ssl_.get(), [](int write_p, int version, int
940
          content_type, const void* buf, size_t len, SSL* ssl, void* arg)
941
208
        -> void {
942
        // BIO_write(), etc., called by SSL_trace, may error. The error should
943
        // be ignored, trace is a "best effort", and its usually because stderr
944
        // is a non-blocking pipe, and its buffer has overflowed. Leaving errors
945
        // on the stack that can get picked up by later SSL_ calls causes
946
        // unwanted failures in SSL_ calls, so keep the error stack unchanged.
947
102
        crypto::MarkPopErrorOnReturn mark_pop_error_on_return;
948
102
        SSL_trace(write_p,  version, content_type, buf, len, ssl, arg);
949
212
    });
950
4
    SSL_set_msg_callback_arg(wrap->ssl_.get(), wrap->bio_trace_.get());
951
  }
952
#endif
953
}
954
955
12188
void TLSWrap::DestroySSL(const FunctionCallbackInfo<Value>& args) {
956
  TLSWrap* wrap;
957
24376
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
958
12188
  Debug(wrap, "DestroySSL()");
959
960
  // If there is a write happening, mark it as finished.
961
12188
  wrap->write_callback_scheduled_ = true;
962
963
  // And destroy
964
12188
  wrap->InvokeQueued(UV_ECANCELED, "Canceled because of SSL destruction");
965
966
  // Destroy the SSL structure and friends
967
12188
  wrap->SSLWrap<TLSWrap>::DestroySSL();
968
12188
  wrap->enc_in_ = nullptr;
969
12188
  wrap->enc_out_ = nullptr;
970
971
12188
  if (wrap->stream_ != nullptr)
972
12188
    wrap->stream_->RemoveStreamListener(wrap);
973
12188
  Debug(wrap, "DestroySSL() finished");
974
}
975
976
977
22
void TLSWrap::EnableCertCb(const FunctionCallbackInfo<Value>& args) {
978
  TLSWrap* wrap;
979
44
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
980
22
  wrap->WaitForCertCb(OnClientHelloParseEnd, wrap);
981
}
982
983
984
35
void TLSWrap::OnClientHelloParseEnd(void* arg) {
985
35
  TLSWrap* c = static_cast<TLSWrap*>(arg);
986
  Debug(c, "OnClientHelloParseEnd()");
987
35
  c->Cycle();
988
35
}
989
990
991
1406
void TLSWrap::GetServername(const FunctionCallbackInfo<Value>& args) {
992
1406
  Environment* env = Environment::GetCurrent(args);
993
994
  TLSWrap* wrap;
995
2812
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
996
997
1406
  CHECK_NOT_NULL(wrap->ssl_);
998
999
1406
  const char* servername = SSL_get_servername(wrap->ssl_.get(),
1000
1406
                                              TLSEXT_NAMETYPE_host_name);
1001
1406
  if (servername != nullptr) {
1002
639
    args.GetReturnValue().Set(OneByteString(env->isolate(), servername));
1003
  } else {
1004
2386
    args.GetReturnValue().Set(false);
1005
  }
1006
}
1007
1008
1009
238
void TLSWrap::SetServername(const FunctionCallbackInfo<Value>& args) {
1010
238
  Environment* env = Environment::GetCurrent(args);
1011
1012
  TLSWrap* wrap;
1013
476
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1014
1015
238
  CHECK_EQ(args.Length(), 1);
1016
714
  CHECK(args[0]->IsString());
1017
238
  CHECK(!wrap->started_);
1018
238
  CHECK(wrap->is_client());
1019
1020
238
  CHECK_NOT_NULL(wrap->ssl_);
1021
1022
476
  node::Utf8Value servername(env->isolate(), args[0].As<String>());
1023
238
  SSL_set_tlsext_host_name(wrap->ssl_.get(), *servername);
1024
}
1025
1026
1027
893
int TLSWrap::SelectSNIContextCallback(SSL* s, int* ad, void* arg) {
1028
893
  TLSWrap* p = static_cast<TLSWrap*>(SSL_get_app_data(s));
1029
893
  Environment* env = p->env();
1030
1031
893
  const char* servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
1032
1033
893
  if (servername == nullptr)
1034
685
    return SSL_TLSEXT_ERR_OK;
1035
1036
208
  HandleScope handle_scope(env->isolate());
1037
208
  Context::Scope context_scope(env->context());
1038
1039
  // Call the SNI callback and use its return value as context
1040
208
  Local<Object> object = p->object();
1041
  Local<Value> ctx;
1042
1043
  // Set the servername as early as possible
1044
208
  Local<Object> owner = p->GetOwner();
1045
416
  if (!owner->Set(env->context(),
1046
                  env->servername_string(),
1047
1248
                  OneByteString(env->isolate(), servername)).FromMaybe(false)) {
1048
    return SSL_TLSEXT_ERR_NOACK;
1049
  }
1050
1051
832
  if (!object->Get(env->context(), env->sni_context_string()).ToLocal(&ctx))
1052
    return SSL_TLSEXT_ERR_NOACK;
1053
1054
  // Not an object, probably undefined or null
1055
208
  if (!ctx->IsObject())
1056
208
    return SSL_TLSEXT_ERR_NOACK;
1057
1058
  Local<FunctionTemplate> cons = env->secure_context_constructor_template();
1059
  if (!cons->HasInstance(ctx)) {
1060
    // Failure: incorrect SNI context object
1061
    Local<Value> err = Exception::TypeError(env->sni_context_err_string());
1062
    p->MakeCallback(env->onerror_string(), 1, &err);
1063
    return SSL_TLSEXT_ERR_NOACK;
1064
  }
1065
1066
  p->sni_context_.Reset(env->isolate(), ctx);
1067
1068
  SecureContext* sc = Unwrap<SecureContext>(ctx.As<Object>());
1069
  CHECK_NOT_NULL(sc);
1070
  p->SetSNIContext(sc);
1071
208
  return SSL_TLSEXT_ERR_OK;
1072
}
1073
1074
1075
3
void TLSWrap::GetWriteQueueSize(const FunctionCallbackInfo<Value>& info) {
1076
  TLSWrap* wrap;
1077
3
  ASSIGN_OR_RETURN_UNWRAP(&wrap, info.This());
1078
1079
3
  if (wrap->ssl_ == nullptr) {
1080
    info.GetReturnValue().Set(0);
1081
    return;
1082
  }
1083
1084
3
  uint32_t write_queue_size = BIO_pending(wrap->enc_out_);
1085
6
  info.GetReturnValue().Set(write_queue_size);
1086
}
1087
1088
1089
2
void TLSWrap::MemoryInfo(MemoryTracker* tracker) const {
1090
2
  tracker->TrackField("error", error_);
1091
  tracker->TrackFieldWithSize("pending_cleartext_input",
1092
                              pending_cleartext_input_.size(),
1093
2
                              "AllocatedBuffer");
1094
2
  if (enc_in_ != nullptr)
1095
2
    tracker->TrackField("enc_in", crypto::NodeBIO::FromBIO(enc_in_));
1096
2
  if (enc_out_ != nullptr)
1097
2
    tracker->TrackField("enc_out", crypto::NodeBIO::FromBIO(enc_out_));
1098
2
}
1099
1100
1101
543
void TLSWrap::Initialize(Local<Object> target,
1102
                         Local<Value> unused,
1103
                         Local<Context> context,
1104
                         void* priv) {
1105
543
  Environment* env = Environment::GetCurrent(context);
1106
1107
543
  env->SetMethod(target, "wrap", TLSWrap::Wrap);
1108
1109
2172
  NODE_DEFINE_CONSTANT(target, HAVE_SSL_TRACE);
1110
1111
543
  Local<FunctionTemplate> t = BaseObject::MakeLazilyInitializedJSTemplate(env);
1112
  Local<String> tlsWrapString =
1113
543
      FIXED_ONE_BYTE_STRING(env->isolate(), "TLSWrap");
1114
543
  t->SetClassName(tlsWrapString);
1115
543
  t->InstanceTemplate()
1116
1086
    ->SetInternalFieldCount(StreamBase::kStreamBaseFieldCount);
1117
1118
  Local<FunctionTemplate> get_write_queue_size =
1119
      FunctionTemplate::New(env->isolate(),
1120
                            GetWriteQueueSize,
1121
                            env->as_callback_data(),
1122
1086
                            Signature::New(env->isolate(), t));
1123
1629
  t->PrototypeTemplate()->SetAccessorProperty(
1124
      env->write_queue_size_string(),
1125
      get_write_queue_size,
1126
      Local<FunctionTemplate>(),
1127
1629
      static_cast<PropertyAttribute>(ReadOnly | DontDelete));
1128
1129
1086
  t->Inherit(AsyncWrap::GetConstructorTemplate(env));
1130
543
  env->SetProtoMethod(t, "receive", Receive);
1131
543
  env->SetProtoMethod(t, "start", Start);
1132
543
  env->SetProtoMethod(t, "setVerifyMode", SetVerifyMode);
1133
543
  env->SetProtoMethod(t, "enableSessionCallbacks", EnableSessionCallbacks);
1134
543
  env->SetProtoMethod(t, "enableKeylogCallback", EnableKeylogCallback);
1135
543
  env->SetProtoMethod(t, "enableTrace", EnableTrace);
1136
543
  env->SetProtoMethod(t, "destroySSL", DestroySSL);
1137
543
  env->SetProtoMethod(t, "enableCertCb", EnableCertCb);
1138
1139
543
  StreamBase::AddMethods(env, t);
1140
543
  SSLWrap<TLSWrap>::AddMethods(env, t);
1141
1142
543
  env->SetProtoMethod(t, "getServername", GetServername);
1143
543
  env->SetProtoMethod(t, "setServername", SetServername);
1144
1145
  env->set_tls_wrap_constructor_function(
1146
1629
      t->GetFunction(env->context()).ToLocalChecked());
1147
1148
  target->Set(env->context(),
1149
              tlsWrapString,
1150
2715
              t->GetFunction(env->context()).ToLocalChecked()).Check();
1151
543
}
1152
1153
}  // namespace node
1154
1155
4827
NODE_MODULE_CONTEXT_AWARE_INTERNAL(tls_wrap, node::TLSWrap::Initialize)