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


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

4656
          .ToLocal(&callback) && callback->IsFunction()) {
259
2328
      Local<Value> argv[] = { env->GetNow() };
260
4656
      c->MakeCallback(callback.As<Function>(), arraysize(argv), argv);
261
    }
262
  }
263
264
  // SSL_CB_HANDSHAKE_START and SSL_CB_HANDSHAKE_DONE are called
265
  // sending HelloRequest in OpenSSL-1.1.1.
266
  // We need to check whether this is in a renegotiation state or not.
267

3954
  if (where & SSL_CB_HANDSHAKE_DONE && !SSL_renegotiate_pending(ssl)) {
268
    Debug(c, "SSLInfoCallback(SSL_CB_HANDSHAKE_DONE);");
269
1625
    CHECK(!SSL_renegotiate_pending(ssl));
270
    Local<Value> callback;
271
272
1625
    c->established_ = true;
273
274
6500
    if (object->Get(env->context(), env->onhandshakedone_string())
275

3250
          .ToLocal(&callback) && callback->IsFunction()) {
276
1625
      c->MakeCallback(callback.As<Function>(), 0, nullptr);
277
    }
278
  }
279
}
280
281
282
18575
void TLSWrap::EncOut() {
283
18575
  Debug(this, "Trying to write encrypted output");
284
285
  // Ignore cycling data if ClientHello wasn't yet parsed
286
18575
  if (!hello_parser_.IsEnded()) {
287
1
    Debug(this, "Returning from EncOut(), hello_parser_ active");
288
11660
    return;
289
  }
290
291
  // Write in progress
292
18574
  if (write_size_ != 0) {
293
3478
    Debug(this, "Returning from EncOut(), write currently in progress");
294
3478
    return;
295
  }
296
297
  // Wait for `newSession` callback to be invoked
298
15096
  if (is_awaiting_new_session()) {
299
7
    Debug(this, "Returning from EncOut(), awaiting new session");
300
7
    return;
301
  }
302
303
  // Split-off queue
304

15089
  if (established_ && current_write_ != nullptr) {
305
4841
    Debug(this, "EncOut() setting write_callback_scheduled_");
306
4841
    write_callback_scheduled_ = true;
307
  }
308
309
15089
  if (ssl_ == nullptr) {
310
1
    Debug(this, "Returning from EncOut(), ssl_ == nullptr");
311
1
    return;
312
  }
313
314
  // No encrypted output ready to write to the underlying stream.
315
15088
  if (BIO_pending(enc_out_) == 0) {
316
8097
    Debug(this, "No pending encrypted output");
317
8097
    if (pending_cleartext_input_.size() == 0) {
318
7910
      if (!in_dowrite_) {
319
7854
        Debug(this, "No pending cleartext input, not inside DoWrite()");
320
7854
        InvokeQueued(0);
321
      } else {
322
56
        Debug(this, "No pending cleartext input, inside DoWrite()");
323
        // TODO(@sam-github, @addaleax) If in_dowrite_ is true, appdata was
324
        // passed to SSL_write().  If we are here, the data was not encrypted to
325
        // enc_out_ yet.  Calling Done() "works", but since the write is not
326
        // flushed, its too soon.  Just returning and letting the next EncOut()
327
        // call Done() passes the test suite, but without more careful analysis,
328
        // its not clear if it is always correct. Not calling Done() could block
329
        // data flow, so for now continue to call Done(), just do it in the next
330
        // tick.
331
112
        BaseObjectPtr<TLSWrap> strong_ref{this};
332
336
        env()->SetImmediate([this, strong_ref](Environment* env) {
333
56
          InvokeQueued(0);
334
112
        });
335
      }
336
    }
337
8097
    return;
338
  }
339
340
  char* data[kSimultaneousBufferCount];
341
  size_t size[arraysize(data)];
342
6991
  size_t count = arraysize(data);
343
6991
  write_size_ = crypto::NodeBIO::FromBIO(enc_out_)->PeekMultiple(data,
344
                                                                 size,
345
                                                                 &count);
346

6991
  CHECK(write_size_ != 0 && count != 0);
347
348
  uv_buf_t buf[arraysize(data)];
349
6991
  uv_buf_t* bufs = buf;
350
14102
  for (size_t i = 0; i < count; i++)
351
7111
    buf[i] = uv_buf_init(data[i], size[i]);
352
353
6991
  Debug(this, "Writing %zu buffers to the underlying stream", count);
354
6991
  StreamWriteResult res = underlying_stream()->Write(bufs, count);
355
6990
  if (res.err != 0) {
356
75
    InvokeQueued(res.err);
357
75
    return;
358
  }
359
360
6915
  if (!res.async) {
361
6356
    Debug(this, "Write finished synchronously");
362
12712
    HandleScope handle_scope(env()->isolate());
363
364
    // Simulate asynchronous finishing, TLS cannot handle this at the moment.
365
12712
    BaseObjectPtr<TLSWrap> strong_ref{this};
366
44492
    env()->SetImmediate([this, strong_ref](Environment* env) {
367
12712
      OnStreamAfterWrite(nullptr, 0);
368
12712
    });
369
  }
370
}
371
372
373
7010
void TLSWrap::OnStreamAfterWrite(WriteWrap* req_wrap, int status) {
374
7010
  Debug(this, "OnStreamAfterWrite(status = %d)", status);
375
7010
  if (current_empty_write_ != nullptr) {
376
96
    Debug(this, "Had empty write");
377
96
    WriteWrap* finishing = current_empty_write_;
378
96
    current_empty_write_ = nullptr;
379
96
    finishing->Done(status);
380
96
    return;
381
  }
382
383
6914
  if (ssl_ == nullptr) {
384
    Debug(this, "ssl_ == nullptr, marking as cancelled");
385
    status = UV_ECANCELED;
386
  }
387
388
  // Handle error
389
6914
  if (status) {
390
3
    if (shutdown_) {
391
1
      Debug(this, "Ignoring error after shutdown");
392
1
      return;
393
    }
394
395
    // Notify about error
396
2
    InvokeQueued(status);
397
2
    return;
398
  }
399
400
  // Commit
401
6911
  crypto::NodeBIO::FromBIO(enc_out_)->Read(nullptr, write_size_);
402
403
  // Ensure that the progress will be made and `InvokeQueued` will be called.
404
6911
  ClearIn();
405
406
  // Try writing more data
407
6911
  write_size_ = 0;
408
6911
  EncOut();
409
}
410
411
412
7990
Local<Value> TLSWrap::GetSSLError(int status, int* err, std::string* msg) {
413
7990
  EscapableHandleScope scope(env()->isolate());
414
415
  // ssl_ is already destroyed in reading EOF by close notify alert.
416
7990
  if (ssl_ == nullptr)
417
    return Local<Value>();
418
419
7990
  *err = SSL_get_error(ssl_.get(), status);
420

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

7613
  if (!eof_ && flags & SSL_RECEIVED_SHUTDOWN) {
548
1191
    eof_ = true;
549
1191
    EmitRead(UV_EOF);
550
  }
551
552
  // We need to check whether an error occurred or the connection was
553
  // shutdown cleanly (SSL_ERROR_ZERO_RETURN) even when read == 0.
554
  // See node#1642 and SSL_read(3SSL) for details.
555
7613
  if (read <= 0) {
556
14092
    HandleScope handle_scope(env()->isolate());
557
    int err;
558
7613
    Local<Value> arg = GetSSLError(read, &err, nullptr);
559
560
    // Ignore ZERO_RETURN after EOF, it is basically not a error
561

7613
    if (err == SSL_ERROR_ZERO_RETURN && eof_)
562
1134
      return;
563
564
6479
    if (!arg.IsEmpty()) {
565
633
      Debug(this, "Got SSL error (%d), calling onerror", err);
566
      // When TLS Alert are stored in wbio,
567
      // it should be flushed to socket before destroyed.
568
633
      if (BIO_pending(enc_out_) != 0)
569
573
        EncOut();
570
571
633
      MakeCallback(env()->onerror_string(), 1, &arg);
572
    }
573
  }
574
}
575
576
577
12898
void TLSWrap::ClearIn() {
578
12898
  Debug(this, "Trying to write cleartext input");
579
  // Ignore cycling data if ClientHello wasn't yet parsed
580
12898
  if (!hello_parser_.IsEnded()) {
581
    Debug(this, "Returning from ClearIn(), hello_parser_ active");
582
12690
    return;
583
  }
584
585
12898
  if (ssl_ == nullptr) {
586
    Debug(this, "Returning from ClearIn(), ssl_ == nullptr");
587
    return;
588
  }
589
590
12898
  if (pending_cleartext_input_.size() == 0) {
591
12526
    Debug(this, "Returning from ClearIn(), no pending data");
592
12526
    return;
593
  }
594
595
580
  AllocatedBuffer data = std::move(pending_cleartext_input_);
596
580
  crypto::MarkPopErrorOnReturn mark_pop_error_on_return;
597
598
372
  crypto::NodeBIO::FromBIO(enc_out_)->set_allocate_tls_hint(data.size());
599
372
  int written = SSL_write(ssl_.get(), data.data(), data.size());
600
744
  Debug(this, "Writing %zu bytes, written = %d", data.size(), written);
601

372
  CHECK(written == -1 || written == static_cast<int>(data.size()));
602
603
  // All written
604
372
  if (written != -1) {
605
164
    Debug(this, "Successfully wrote all data to SSL");
606
164
    return;
607
  }
608
609
  // Error or partial write
610
416
  HandleScope handle_scope(env()->isolate());
611
208
  Context::Scope context_scope(env()->context());
612
613
  int err;
614
416
  std::string error_str;
615
208
  Local<Value> arg = GetSSLError(written, &err, &error_str);
616
208
  if (!arg.IsEmpty()) {
617
2
    Debug(this, "Got SSL error (%d)", err);
618
2
    write_callback_scheduled_ = true;
619
    // TODO(@sam-github) Should forward an error object with
620
    // .code/.function/.etc, if possible.
621
2
    InvokeQueued(UV_EPROTO, error_str.c_str());
622
  } else {
623
206
    Debug(this, "Pushing data back");
624
    // Push back the not-yet-written data. This can be skipped in the error
625
    // case because no further writes would succeed anyway.
626
206
    pending_cleartext_input_ = std::move(data);
627
  }
628
}
629
630
631
std::string TLSWrap::diagnostic_name() const {
632
  std::string name = "TLSWrap ";
633
  if (is_server())
634
    name += "server (";
635
  else
636
    name += "client (";
637
  name += std::to_string(static_cast<int64_t>(get_async_id())) + ")";
638
  return name;
639
}
640
641
642
24707
AsyncWrap* TLSWrap::GetAsyncWrap() {
643
24707
  return static_cast<AsyncWrap*>(this);
644
}
645
646
647
1134
bool TLSWrap::IsIPCPipe() {
648
1134
  return underlying_stream()->IsIPCPipe();
649
}
650
651
652
3
int TLSWrap::GetFD() {
653
3
  return underlying_stream()->GetFD();
654
}
655
656
657
5151
bool TLSWrap::IsAlive() {
658
10302
  return ssl_ != nullptr &&
659

10301
      stream_ != nullptr &&
660
10301
      underlying_stream()->IsAlive();
661
}
662
663
664
3
bool TLSWrap::IsClosing() {
665
3
  return underlying_stream()->IsClosing();
666
}
667
668
669
670
2130
int TLSWrap::ReadStart() {
671
2130
  Debug(this, "ReadStart()");
672
2130
  if (stream_ != nullptr)
673
2130
    return stream_->ReadStart();
674
  return 0;
675
}
676
677
678
2746
int TLSWrap::ReadStop() {
679
2746
  Debug(this, "ReadStop()");
680
2746
  if (stream_ != nullptr)
681
2739
    return stream_->ReadStop();
682
7
  return 0;
683
}
684
685
686
5212
const char* TLSWrap::Error() const {
687
5212
  return error_.empty() ? nullptr : error_.c_str();
688
}
689
690
691
7
void TLSWrap::ClearError() {
692
7
  error_.clear();
693
7
}
694
695
696
// Called by StreamBase::Write() to request async write of clear text into SSL.
697
// TODO(@sam-github) Should there be a TLSWrap::DoTryWrite()?
698
2538
int TLSWrap::DoWrite(WriteWrap* w,
699
                     uv_buf_t* bufs,
700
                     size_t count,
701
                     uv_stream_t* send_handle) {
702
2538
  CHECK_NULL(send_handle);
703
2538
  Debug(this, "DoWrite()");
704
705
2538
  if (ssl_ == nullptr) {
706
3
    ClearError();
707
3
    error_ = "Write after DestroySSL";
708
3
    return UV_EPROTO;
709
  }
710
711
2535
  size_t length = 0;
712
  size_t i;
713
2535
  size_t nonempty_i = 0;
714
2535
  size_t nonempty_count = 0;
715
10756
  for (i = 0; i < count; i++) {
716
8221
    length += bufs[i].len;
717
8221
    if (bufs[i].len > 0) {
718
7919
      nonempty_i = i;
719
7919
      nonempty_count += 1;
720
    }
721
  }
722
723
  // We want to trigger a Write() on the underlying stream to drive the stream
724
  // system, but don't want to encrypt empty buffers into a TLS frame, so see
725
  // if we can find something to Write().
726
  // First, call ClearOut(). It does an SSL_read(), which might cause handshake
727
  // or other internal messages to be encrypted. If it does, write them later
728
  // with EncOut().
729
  // If there is still no encrypted output, call Write(bufs) on the underlying
730
  // stream. Since the bufs are empty, it won't actually write non-TLS data
731
  // onto the socket, we just want the side-effects. After, make sure the
732
  // WriteWrap was accepted by the stream, or that we call Done() on it.
733
2535
  if (length == 0) {
734
201
    Debug(this, "Empty write");
735
201
    ClearOut();
736
201
    if (BIO_pending(enc_out_) == 0) {
737
96
      Debug(this, "No pending encrypted output, writing to underlying stream");
738
96
      CHECK_NULL(current_empty_write_);
739
96
      current_empty_write_ = w;
740
      StreamWriteResult res =
741
96
          underlying_stream()->Write(bufs, count, send_handle);
742
96
      if (!res.async) {
743
192
        BaseObjectPtr<TLSWrap> strong_ref{this};
744
768
        env()->SetImmediate([this, strong_ref](Environment* env) {
745
288
          OnStreamAfterWrite(current_empty_write_, 0);
746
192
        });
747
      }
748
96
      return 0;
749
    }
750
  }
751
752
  // Store the current write wrap
753
2439
  CHECK_NULL(current_write_);
754
2439
  current_write_ = w;
755
756
  // Write encrypted data to underlying stream and call Done().
757
2439
  if (length == 0) {
758
105
    EncOut();
759
105
    return 0;
760
  }
761
762
4668
  AllocatedBuffer data;
763
4668
  crypto::MarkPopErrorOnReturn mark_pop_error_on_return;
764
765
2334
  int written = 0;
766
767
  // It is common for zero length buffers to be written,
768
  // don't copy data if there there is one buffer with data
769
  // and one or more zero length buffers.
770
  // _http_outgoing.js writes a zero length buffer in
771
  // in OutgoingMessage.prototype.end.  If there was a large amount
772
  // of data supplied to end() there is no sense allocating
773
  // and copying it when it could just be used.
774
775
2334
  if (nonempty_count != 1) {
776
1354
    data = AllocatedBuffer::AllocateManaged(env(), length);
777
1354
    size_t offset = 0;
778
8296
    for (i = 0; i < count; i++) {
779
6942
      memcpy(data.data() + offset, bufs[i].base, bufs[i].len);
780
6942
      offset += bufs[i].len;
781
    }
782
783
1354
    crypto::NodeBIO::FromBIO(enc_out_)->set_allocate_tls_hint(length);
784
1354
    written = SSL_write(ssl_.get(), data.data(), length);
785
  } else {
786
    // Only one buffer: try to write directly, only store if it fails
787
980
    uv_buf_t* buf = &bufs[nonempty_i];
788
980
    crypto::NodeBIO::FromBIO(enc_out_)->set_allocate_tls_hint(buf->len);
789
980
    written = SSL_write(ssl_.get(), buf->base, buf->len);
790
791
980
    if (written == -1) {
792
166
      data = AllocatedBuffer::AllocateManaged(env(), length);
793
166
      memcpy(data.data(), buf->base, buf->len);
794
    }
795
  }
796
797

2334
  CHECK(written == -1 || written == static_cast<int>(length));
798
2334
  Debug(this, "Writing %zu bytes, written = %d", length, written);
799
800
2334
  if (written == -1) {
801
    int err;
802
169
    Local<Value> arg = GetSSLError(written, &err, &error_);
803
804
    // If we stopped writing because of an error, it's fatal, discard the data.
805
169
    if (!arg.IsEmpty()) {
806
2
      Debug(this, "Got SSL error (%d), returning UV_EPROTO", err);
807
2
      current_write_ = nullptr;
808
2
      return UV_EPROTO;
809
    }
810
811
167
    Debug(this, "Saving data for later write");
812
    // Otherwise, save unwritten data so it can be written later by ClearIn().
813
167
    CHECK_EQ(pending_cleartext_input_.size(), 0);
814
167
    pending_cleartext_input_ = std::move(data);
815
  }
816
817
  // Write any encrypted/handshake output that may be ready.
818
  // Guard against sync call of current_write_->Done(), its unsupported.
819
2332
  in_dowrite_ = true;
820
2332
  EncOut();
821
2332
  in_dowrite_ = false;
822
823
2332
  return 0;
824
}
825
826
827
6088
uv_buf_t TLSWrap::OnStreamAlloc(size_t suggested_size) {
828
6088
  CHECK_NOT_NULL(ssl_);
829
830
6088
  size_t size = suggested_size;
831
6088
  char* base = crypto::NodeBIO::FromBIO(enc_in_)->PeekWritable(&size);
832
6088
  return uv_buf_init(base, size);
833
}
834
835
836
6094
void TLSWrap::OnStreamRead(ssize_t nread, const uv_buf_t& buf) {
837
6094
  Debug(this, "Read %zd bytes from underlying stream", nread);
838
6094
  if (nread < 0)  {
839
    // Error should be emitted only after all data was read
840
131
    ClearOut();
841
842
    // Ignore EOF if received close_notify
843
131
    if (nread == UV_EOF) {
844
130
      if (eof_)
845
3
        return;
846
127
      eof_ = true;
847
    }
848
849
128
    EmitRead(nread);
850
128
    return;
851
  }
852
853
  // DestroySSL() is the only thing that un-sets ssl_, but that also removes
854
  // this TLSWrap as a stream listener, so we should not receive OnStreamRead()
855
  // calls anymore.
856
5963
  CHECK(ssl_);
857
858
  // Commit the amount of data actually read into the peeked/allocated buffer
859
  // from the underlying stream.
860
5963
  crypto::NodeBIO* enc_in = crypto::NodeBIO::FromBIO(enc_in_);
861
5963
  enc_in->Commit(nread);
862
863
  // Parse ClientHello first, if we need to. It's only parsed if session event
864
  // listeners are used on the server side.  "ended" is the initial state, so
865
  // can mean parsing was never started, or that parsing is finished. Either
866
  // way, ended means we can give the buffered data to SSL.
867
5963
  if (!hello_parser_.IsEnded()) {
868
20
    size_t avail = 0;
869
20
    uint8_t* data = reinterpret_cast<uint8_t*>(enc_in->Peek(&avail));
870

20
    CHECK_IMPLIES(data == nullptr, avail == 0);
871
20
    Debug(this, "Passing %zu bytes to the hello parser", avail);
872
20
    return hello_parser_.Parse(data, avail);
873
  }
874
875
  // Cycle OpenSSL's state
876
5943
  Cycle();
877
}
878
879
880
1368
ShutdownWrap* TLSWrap::CreateShutdownWrap(Local<Object> req_wrap_object) {
881
1368
  return underlying_stream()->CreateShutdownWrap(req_wrap_object);
882
}
883
884
885
1368
int TLSWrap::DoShutdown(ShutdownWrap* req_wrap) {
886
1368
  Debug(this, "DoShutdown()");
887
2736
  crypto::MarkPopErrorOnReturn mark_pop_error_on_return;
888
889

1368
  if (ssl_ && SSL_shutdown(ssl_.get()) == 0)
890
838
    SSL_shutdown(ssl_.get());
891
892
1368
  shutdown_ = true;
893
1368
  EncOut();
894
2736
  return stream_->DoShutdown(req_wrap);
895
}
896
897
898
12160
void TLSWrap::SetVerifyMode(const FunctionCallbackInfo<Value>& args) {
899
  TLSWrap* wrap;
900
12160
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
901
902
12160
  CHECK_EQ(args.Length(), 2);
903
24320
  CHECK(args[0]->IsBoolean());
904
24320
  CHECK(args[1]->IsBoolean());
905
12160
  CHECK_NOT_NULL(wrap->ssl_);
906
907
  int verify_mode;
908
12160
  if (wrap->is_server()) {
909
1644
    bool request_cert = args[0]->IsTrue();
910
822
    if (!request_cert) {
911
      // If no cert is requested, there will be none to reject as unauthorized.
912
741
      verify_mode = SSL_VERIFY_NONE;
913
    } else {
914
162
      bool reject_unauthorized = args[1]->IsTrue();
915
81
      verify_mode = SSL_VERIFY_PEER;
916
81
      if (reject_unauthorized)
917
48
        verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
918
    }
919
  } else {
920
    // Servers always send a cert if the cipher is not anonymous (anon is
921
    // disabled by default), so use VERIFY_NONE and check the cert after the
922
    // handshake has completed.
923
11338
    verify_mode = SSL_VERIFY_NONE;
924
  }
925
926
  // Always allow a connection. We'll reject in javascript.
927
12160
  SSL_set_verify(wrap->ssl_.get(), verify_mode, crypto::VerifyCallback);
928
}
929
930
931
208
void TLSWrap::EnableSessionCallbacks(
932
    const FunctionCallbackInfo<Value>& args) {
933
  TLSWrap* wrap;
934
396
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
935
208
  CHECK_NOT_NULL(wrap->ssl_);
936
208
  wrap->enable_session_callbacks();
937
938
  // Clients don't use the HelloParser.
939
208
  if (wrap->is_client())
940
188
    return;
941
942
20
  crypto::NodeBIO::FromBIO(wrap->enc_in_)->set_initial(kMaxHelloLength);
943
20
  wrap->hello_parser_.Start(SSLWrap<TLSWrap>::OnClientHello,
944
                            OnClientHelloParseEnd,
945
20
                            wrap);
946
}
947
948
8
void TLSWrap::EnableKeylogCallback(
949
    const FunctionCallbackInfo<Value>& args) {
950
  TLSWrap* wrap;
951
8
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
952
8
  CHECK_NOT_NULL(wrap->sc_);
953
8
  SSL_CTX_set_keylog_callback(wrap->sc_->ctx_.get(),
954
8
      SSLWrap<TLSWrap>::KeylogCallback);
955
}
956
957
// Check required capabilities were not excluded from the OpenSSL build:
958
// - OPENSSL_NO_SSL_TRACE excludes SSL_trace()
959
// - OPENSSL_NO_STDIO excludes BIO_new_fp()
960
// HAVE_SSL_TRACE is available on the internal tcp_wrap binding for the tests.
961
#if defined(OPENSSL_NO_SSL_TRACE) || defined(OPENSSL_NO_STDIO)
962
# define HAVE_SSL_TRACE 0
963
#else
964
# define HAVE_SSL_TRACE 1
965
#endif
966
967
4
void TLSWrap::EnableTrace(
968
    const FunctionCallbackInfo<Value>& args) {
969
  TLSWrap* wrap;
970
4
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
971
972
#if HAVE_SSL_TRACE
973
4
  if (wrap->ssl_) {
974
4
    wrap->bio_trace_.reset(BIO_new_fp(stderr,  BIO_NOCLOSE | BIO_FP_TEXT));
975
8
    SSL_set_msg_callback(wrap->ssl_.get(), [](int write_p, int version, int
976
          content_type, const void* buf, size_t len, SSL* ssl, void* arg)
977
232
        -> void {
978
        // BIO_write(), etc., called by SSL_trace, may error. The error should
979
        // be ignored, trace is a "best effort", and its usually because stderr
980
        // is a non-blocking pipe, and its buffer has overflowed. Leaving errors
981
        // on the stack that can get picked up by later SSL_ calls causes
982
        // unwanted failures in SSL_ calls, so keep the error stack unchanged.
983
228
        crypto::MarkPopErrorOnReturn mark_pop_error_on_return;
984
114
        SSL_trace(write_p,  version, content_type, buf, len, ssl, arg);
985
236
    });
986
4
    SSL_set_msg_callback_arg(wrap->ssl_.get(), wrap->bio_trace_.get());
987
  }
988
#endif
989
}
990
991
12117
void TLSWrap::DestroySSL(const FunctionCallbackInfo<Value>& args) {
992
  TLSWrap* wrap;
993
12117
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
994
12117
  Debug(wrap, "DestroySSL()");
995
996
  // If there is a write happening, mark it as finished.
997
12117
  wrap->write_callback_scheduled_ = true;
998
999
  // And destroy
1000
12117
  wrap->InvokeQueued(UV_ECANCELED, "Canceled because of SSL destruction");
1001
1002
  // Destroy the SSL structure and friends
1003
12117
  wrap->SSLWrap<TLSWrap>::DestroySSL();
1004
12117
  wrap->enc_in_ = nullptr;
1005
12117
  wrap->enc_out_ = nullptr;
1006
1007
12117
  if (wrap->stream_ != nullptr)
1008
12117
    wrap->stream_->RemoveStreamListener(wrap);
1009
12117
  Debug(wrap, "DestroySSL() finished");
1010
}
1011
1012
1013
22
void TLSWrap::EnableCertCb(const FunctionCallbackInfo<Value>& args) {
1014
  TLSWrap* wrap;
1015
22
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1016
22
  wrap->WaitForCertCb(OnClientHelloParseEnd, wrap);
1017
}
1018
1019
1020
36
void TLSWrap::OnClientHelloParseEnd(void* arg) {
1021
36
  TLSWrap* c = static_cast<TLSWrap*>(arg);
1022
  Debug(c, "OnClientHelloParseEnd()");
1023
36
  c->Cycle();
1024
36
}
1025
1026
1027
1310
void TLSWrap::GetServername(const FunctionCallbackInfo<Value>& args) {
1028
1310
  Environment* env = Environment::GetCurrent(args);
1029
1030
  TLSWrap* wrap;
1031
1310
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1032
1033
1310
  CHECK_NOT_NULL(wrap->ssl_);
1034
1035
1310
  const char* servername = SSL_get_servername(wrap->ssl_.get(),
1036
1310
                                              TLSEXT_NAMETYPE_host_name);
1037
1310
  if (servername != nullptr) {
1038
513
    args.GetReturnValue().Set(OneByteString(env->isolate(), servername));
1039
  } else {
1040
2278
    args.GetReturnValue().Set(false);
1041
  }
1042
}
1043
1044
1045
184
void TLSWrap::SetServername(const FunctionCallbackInfo<Value>& args) {
1046
184
  Environment* env = Environment::GetCurrent(args);
1047
1048
  TLSWrap* wrap;
1049
184
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1050
1051
184
  CHECK_EQ(args.Length(), 1);
1052
552
  CHECK(args[0]->IsString());
1053
184
  CHECK(!wrap->started_);
1054
184
  CHECK(wrap->is_client());
1055
1056
184
  CHECK_NOT_NULL(wrap->ssl_);
1057
1058
552
  node::Utf8Value servername(env->isolate(), args[0].As<String>());
1059
184
  SSL_set_tlsext_host_name(wrap->ssl_.get(), *servername);
1060
}
1061
1062
1063
886
int TLSWrap::SelectSNIContextCallback(SSL* s, int* ad, void* arg) {
1064
886
  TLSWrap* p = static_cast<TLSWrap*>(SSL_get_app_data(s));
1065
886
  Environment* env = p->env();
1066
1067
886
  const char* servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
1068
1069
886
  if (servername == nullptr)
1070
668
    return SSL_TLSEXT_ERR_OK;
1071
1072
436
  HandleScope handle_scope(env->isolate());
1073
218
  Context::Scope context_scope(env->context());
1074
1075
  // Call the SNI callback and use its return value as context
1076
218
  Local<Object> object = p->object();
1077
  Local<Value> ctx;
1078
1079
  // Set the servername as early as possible
1080
218
  Local<Object> owner = p->GetOwner();
1081
654
  if (!owner->Set(env->context(),
1082
                  env->servername_string(),
1083
1308
                  OneByteString(env->isolate(), servername)).FromMaybe(false)) {
1084
    return SSL_TLSEXT_ERR_NOACK;
1085
  }
1086
1087
872
  if (!object->Get(env->context(), env->sni_context_string()).ToLocal(&ctx))
1088
    return SSL_TLSEXT_ERR_NOACK;
1089
1090
  // Not an object, probably undefined or null
1091
218
  if (!ctx->IsObject())
1092
218
    return SSL_TLSEXT_ERR_NOACK;
1093
1094
  Local<FunctionTemplate> cons = env->secure_context_constructor_template();
1095
  if (!cons->HasInstance(ctx)) {
1096
    // Failure: incorrect SNI context object
1097
    Local<Value> err = Exception::TypeError(env->sni_context_err_string());
1098
    p->MakeCallback(env->onerror_string(), 1, &err);
1099
    return SSL_TLSEXT_ERR_NOACK;
1100
  }
1101
1102
  SecureContext* sc = Unwrap<SecureContext>(ctx.As<Object>());
1103
  CHECK_NOT_NULL(sc);
1104
  p->sni_context_ = BaseObjectPtr<SecureContext>(sc);
1105
1106
  p->ConfigureSecureContext(sc);
1107
  CHECK_EQ(SSL_set_SSL_CTX(p->ssl_.get(), sc->ctx_.get()), sc->ctx_.get());
1108
  p->SetCACerts(sc);
1109
1110
  return SSL_TLSEXT_ERR_OK;
1111
}
1112
1113
#ifndef OPENSSL_NO_PSK
1114
1115
2
void TLSWrap::SetPskIdentityHint(const FunctionCallbackInfo<Value>& args) {
1116
  TLSWrap* p;
1117
2
  ASSIGN_OR_RETURN_UNWRAP(&p, args.Holder());
1118
2
  CHECK_NOT_NULL(p->ssl_);
1119
1120
2
  Environment* env = p->env();
1121
2
  Isolate* isolate = env->isolate();
1122
1123
6
  CHECK(args[0]->IsString());
1124
6
  node::Utf8Value hint(isolate, args[0].As<String>());
1125
1126
2
  if (!SSL_use_psk_identity_hint(p->ssl_.get(), *hint)) {
1127
1
    Local<Value> err = node::ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED(isolate);
1128
1
    p->MakeCallback(env->onerror_string(), 1, &err);
1129
  }
1130
}
1131
1132
20
void TLSWrap::EnablePskCallback(const FunctionCallbackInfo<Value>& args) {
1133
  TLSWrap* wrap;
1134
20
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1135
20
  CHECK_NOT_NULL(wrap->ssl_);
1136
1137
20
  SSL_set_psk_server_callback(wrap->ssl_.get(), PskServerCallback);
1138
20
  SSL_set_psk_client_callback(wrap->ssl_.get(), PskClientCallback);
1139
}
1140
1141
9
unsigned int TLSWrap::PskServerCallback(SSL* s,
1142
                                        const char* identity,
1143
                                        unsigned char* psk,
1144
                                        unsigned int max_psk_len) {
1145
9
  TLSWrap* p = static_cast<TLSWrap*>(SSL_get_app_data(s));
1146
1147
9
  Environment* env = p->env();
1148
9
  Isolate* isolate = env->isolate();
1149
18
  HandleScope scope(isolate);
1150
1151
  MaybeLocal<String> maybe_identity_str =
1152
9
      String::NewFromUtf8(isolate, identity);
1153
1154
  v8::Local<v8::String> identity_str;
1155
9
  if (!maybe_identity_str.ToLocal(&identity_str)) return 0;
1156
1157
  // Make sure there are no utf8 replacement symbols.
1158
18
  v8::String::Utf8Value identity_utf8(isolate, identity_str);
1159
9
  if (strcmp(*identity_utf8, identity) != 0) return 0;
1160
1161
  Local<Value> argv[] = {identity_str,
1162
27
                         Integer::NewFromUnsigned(isolate, max_psk_len)};
1163
1164
  MaybeLocal<Value> maybe_psk_val =
1165
9
      p->MakeCallback(env->onpskexchange_symbol(), arraysize(argv), argv);
1166
  Local<Value> psk_val;
1167

18
  if (!maybe_psk_val.ToLocal(&psk_val) || !psk_val->IsArrayBufferView())
1168
1
    return 0;
1169
1170
8
  char* psk_buf = Buffer::Data(psk_val);
1171
8
  size_t psk_buflen = Buffer::Length(psk_val);
1172
1173
8
  if (psk_buflen > max_psk_len) return 0;
1174
1175
8
  memcpy(psk, psk_buf, psk_buflen);
1176
8
  return psk_buflen;
1177
}
1178
1179
9
unsigned int TLSWrap::PskClientCallback(SSL* s,
1180
                                        const char* hint,
1181
                                        char* identity,
1182
                                        unsigned int max_identity_len,
1183
                                        unsigned char* psk,
1184
                                        unsigned int max_psk_len) {
1185
9
  TLSWrap* p = static_cast<TLSWrap*>(SSL_get_app_data(s));
1186
1187
9
  Environment* env = p->env();
1188
9
  Isolate* isolate = env->isolate();
1189
18
  HandleScope scope(isolate);
1190
1191
  Local<Value> argv[] = {Null(isolate),
1192
                         Integer::NewFromUnsigned(isolate, max_psk_len),
1193
36
                         Integer::NewFromUnsigned(isolate, max_identity_len)};
1194
9
  if (hint != nullptr) {
1195
1
    MaybeLocal<String> maybe_hint = String::NewFromUtf8(isolate, hint);
1196
1197
    Local<String> local_hint;
1198
1
    if (!maybe_hint.ToLocal(&local_hint)) return 0;
1199
1200
1
    argv[0] = local_hint;
1201
  }
1202
  MaybeLocal<Value> maybe_ret =
1203
9
      p->MakeCallback(env->onpskexchange_symbol(), arraysize(argv), argv);
1204
  Local<Value> ret;
1205

18
  if (!maybe_ret.ToLocal(&ret) || !ret->IsObject()) return 0;
1206
9
  Local<Object> obj = ret.As<Object>();
1207
1208
27
  MaybeLocal<Value> maybe_psk_val = obj->Get(env->context(), env->psk_string());
1209
1210
  Local<Value> psk_val;
1211

18
  if (!maybe_psk_val.ToLocal(&psk_val) || !psk_val->IsArrayBufferView())
1212
    return 0;
1213
1214
9
  char* psk_buf = Buffer::Data(psk_val);
1215
9
  size_t psk_buflen = Buffer::Length(psk_val);
1216
1217
9
  if (psk_buflen > max_psk_len) return 0;
1218
1219
  MaybeLocal<Value> maybe_identity_val =
1220
27
      obj->Get(env->context(), env->identity_string());
1221
  Local<Value> identity_val;
1222

27
  if (!maybe_identity_val.ToLocal(&identity_val) || !identity_val->IsString())
1223
    return 0;
1224
9
  Local<String> identity_str = identity_val.As<String>();
1225
1226
18
  String::Utf8Value identity_buf(isolate, identity_str);
1227
9
  size_t identity_len = identity_buf.length();
1228
1229
9
  if (identity_len > max_identity_len) return 0;
1230
1231
9
  memcpy(identity, *identity_buf, identity_len);
1232
9
  memcpy(psk, psk_buf, psk_buflen);
1233
1234
9
  return psk_buflen;
1235
}
1236
1237
#endif
1238
1239
2
void TLSWrap::GetWriteQueueSize(const FunctionCallbackInfo<Value>& info) {
1240
  TLSWrap* wrap;
1241
2
  ASSIGN_OR_RETURN_UNWRAP(&wrap, info.This());
1242
1243
2
  if (wrap->ssl_ == nullptr) {
1244
    info.GetReturnValue().Set(0);
1245
    return;
1246
  }
1247
1248
2
  uint32_t write_queue_size = BIO_pending(wrap->enc_out_);
1249
4
  info.GetReturnValue().Set(write_queue_size);
1250
}
1251
1252
1253
void TLSWrap::MemoryInfo(MemoryTracker* tracker) const {
1254
  SSLWrap<TLSWrap>::MemoryInfo(tracker);
1255
  tracker->TrackField("error", error_);
1256
  tracker->TrackFieldWithSize("pending_cleartext_input",
1257
                              pending_cleartext_input_.size(),
1258
                              "AllocatedBuffer");
1259
  if (enc_in_ != nullptr)
1260
    tracker->TrackField("enc_in", crypto::NodeBIO::FromBIO(enc_in_));
1261
  if (enc_out_ != nullptr)
1262
    tracker->TrackField("enc_out", crypto::NodeBIO::FromBIO(enc_out_));
1263
}
1264
1265
1266
506
void TLSWrap::Initialize(Local<Object> target,
1267
                         Local<Value> unused,
1268
                         Local<Context> context,
1269
                         void* priv) {
1270
506
  Environment* env = Environment::GetCurrent(context);
1271
1272
506
  env->SetMethod(target, "wrap", TLSWrap::Wrap);
1273
1274
2024
  NODE_DEFINE_CONSTANT(target, HAVE_SSL_TRACE);
1275
1276
506
  Local<FunctionTemplate> t = BaseObject::MakeLazilyInitializedJSTemplate(env);
1277
  Local<String> tlsWrapString =
1278
506
      FIXED_ONE_BYTE_STRING(env->isolate(), "TLSWrap");
1279
506
  t->SetClassName(tlsWrapString);
1280
1012
  t->InstanceTemplate()->SetInternalFieldCount(StreamBase::kInternalFieldCount);
1281
1282
  Local<FunctionTemplate> get_write_queue_size =
1283
      FunctionTemplate::New(env->isolate(),
1284
                            GetWriteQueueSize,
1285
                            Local<Value>(),
1286
1012
                            Signature::New(env->isolate(), t));
1287
2024
  t->PrototypeTemplate()->SetAccessorProperty(
1288
      env->write_queue_size_string(),
1289
      get_write_queue_size,
1290
      Local<FunctionTemplate>(),
1291
506
      static_cast<PropertyAttribute>(ReadOnly | DontDelete));
1292
1293
1012
  t->Inherit(AsyncWrap::GetConstructorTemplate(env));
1294
506
  env->SetProtoMethod(t, "receive", Receive);
1295
506
  env->SetProtoMethod(t, "start", Start);
1296
506
  env->SetProtoMethod(t, "setVerifyMode", SetVerifyMode);
1297
506
  env->SetProtoMethod(t, "enableSessionCallbacks", EnableSessionCallbacks);
1298
506
  env->SetProtoMethod(t, "enableKeylogCallback", EnableKeylogCallback);
1299
506
  env->SetProtoMethod(t, "enableTrace", EnableTrace);
1300
506
  env->SetProtoMethod(t, "destroySSL", DestroySSL);
1301
506
  env->SetProtoMethod(t, "enableCertCb", EnableCertCb);
1302
1303
#ifndef OPENSSL_NO_PSK
1304
506
  env->SetProtoMethod(t, "setPskIdentityHint", SetPskIdentityHint);
1305
506
  env->SetProtoMethod(t, "enablePskCallback", EnablePskCallback);
1306
#endif
1307
1308
506
  StreamBase::AddMethods(env, t);
1309
506
  SSLWrap<TLSWrap>::AddMethods(env, t);
1310
1311
506
  env->SetProtoMethod(t, "getServername", GetServername);
1312
506
  env->SetProtoMethod(t, "setServername", SetServername);
1313
1314
1518
  Local<Function> fn = t->GetFunction(env->context()).ToLocalChecked();
1315
1316
506
  env->set_tls_wrap_constructor_function(fn);
1317
1318
1518
  target->Set(env->context(), tlsWrapString, fn).Check();
1319
506
}
1320
1321
}  // namespace node
1322
1323

17887
NODE_MODULE_CONTEXT_AWARE_INTERNAL(tls_wrap, node::TLSWrap::Initialize)