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-inl.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 "node_errors.h"
32 #include "stream_base-inl.h"
33 #include "util-inl.h"
34
35 namespace node {
36
37 using crypto::SecureContext;
38 using crypto::SSLWrap;
39 using v8::Context;
40 using v8::DontDelete;
41 using v8::EscapableHandleScope;
42 using v8::Exception;
43 using v8::Function;
44 using v8::FunctionCallbackInfo;
45 using v8::FunctionTemplate;
46 using v8::Integer;
47 using v8::Isolate;
48 using v8::Local;
49 using v8::MaybeLocal;
50 using v8::Object;
51 using v8::ReadOnly;
52 using v8::Signature;
53 using v8::String;
54 using v8::Value;
55
TLSWrap(Environment * env,Local<Object> obj,Kind kind,StreamBase * stream,SecureContext * sc)56 TLSWrap::TLSWrap(Environment* env,
57 Local<Object> obj,
58 Kind kind,
59 StreamBase* stream,
60 SecureContext* sc)
61 : AsyncWrap(env, obj, AsyncWrap::PROVIDER_TLSWRAP),
62 SSLWrap<TLSWrap>(env, sc, kind),
63 StreamBase(env),
64 sc_(sc) {
65 MakeWeak();
66 StreamBase::AttachToObject(GetObject());
67
68 // sc comes from an Unwrap. Make sure it was assigned.
69 CHECK_NOT_NULL(sc);
70
71 // We've our own session callbacks
72 SSL_CTX_sess_set_get_cb(sc_->ctx_.get(),
73 SSLWrap<TLSWrap>::GetSessionCallback);
74 SSL_CTX_sess_set_new_cb(sc_->ctx_.get(),
75 SSLWrap<TLSWrap>::NewSessionCallback);
76
77 stream->PushStreamListener(this);
78
79 InitSSL();
80 Debug(this, "Created new TLSWrap");
81 }
82
83
~TLSWrap()84 TLSWrap::~TLSWrap() {
85 Debug(this, "~TLSWrap()");
86 sc_ = nullptr;
87 }
88
89
InvokeQueued(int status,const char * error_str)90 bool TLSWrap::InvokeQueued(int status, const char* error_str) {
91 Debug(this, "InvokeQueued(%d, %s)", status, error_str);
92 if (!write_callback_scheduled_)
93 return false;
94
95 if (current_write_ != nullptr) {
96 WriteWrap* w = current_write_;
97 current_write_ = nullptr;
98 w->Done(status, error_str);
99 }
100
101 return true;
102 }
103
104
NewSessionDoneCb()105 void TLSWrap::NewSessionDoneCb() {
106 Debug(this, "NewSessionDoneCb()");
107 Cycle();
108 }
109
110
InitSSL()111 void TLSWrap::InitSSL() {
112 // Initialize SSL – OpenSSL takes ownership of these.
113 enc_in_ = crypto::NodeBIO::New(env()).release();
114 enc_out_ = crypto::NodeBIO::New(env()).release();
115
116 SSL_set_bio(ssl_.get(), enc_in_, enc_out_);
117
118 // NOTE: This could be overridden in SetVerifyMode
119 SSL_set_verify(ssl_.get(), SSL_VERIFY_NONE, crypto::VerifyCallback);
120
121 #ifdef SSL_MODE_RELEASE_BUFFERS
122 SSL_set_mode(ssl_.get(), SSL_MODE_RELEASE_BUFFERS);
123 #endif // SSL_MODE_RELEASE_BUFFERS
124
125 // This is default in 1.1.1, but set it anyway, Cycle() doesn't currently
126 // re-call ClearIn() if SSL_read() returns SSL_ERROR_WANT_READ, so data can be
127 // left sitting in the incoming enc_in_ and never get processed.
128 // - https://wiki.openssl.org/index.php/TLS1.3#Non-application_data_records
129 SSL_set_mode(ssl_.get(), SSL_MODE_AUTO_RETRY);
130
131 #ifdef OPENSSL_IS_BORINGSSL
132 // OpenSSL allows renegotiation by default, but BoringSSL disables it.
133 // Configure BoringSSL to match OpenSSL's behavior.
134 SSL_set_renegotiate_mode(ssl_.get(), ssl_renegotiate_freely);
135 #endif
136
137 SSL_set_app_data(ssl_.get(), this);
138 // Using InfoCallback isn't how we are supposed to check handshake progress:
139 // https://github.com/openssl/openssl/issues/7199#issuecomment-420915993
140 //
141 // Note on when this gets called on various openssl versions:
142 // https://github.com/openssl/openssl/issues/7199#issuecomment-420670544
143 SSL_set_info_callback(ssl_.get(), SSLInfoCallback);
144
145 if (is_server()) {
146 SSL_CTX_set_tlsext_servername_callback(sc_->ctx_.get(),
147 SelectSNIContextCallback);
148 }
149
150 ConfigureSecureContext(sc_);
151
152 SSL_set_cert_cb(ssl_.get(), SSLWrap<TLSWrap>::SSLCertCallback, this);
153
154 if (is_server()) {
155 SSL_set_accept_state(ssl_.get());
156 } else if (is_client()) {
157 // Enough space for server response (hello, cert)
158 crypto::NodeBIO::FromBIO(enc_in_)->set_initial(kInitialClientBufferLength);
159 SSL_set_connect_state(ssl_.get());
160 } else {
161 // Unexpected
162 ABORT();
163 }
164 }
165
166
Wrap(const FunctionCallbackInfo<Value> & args)167 void TLSWrap::Wrap(const FunctionCallbackInfo<Value>& args) {
168 Environment* env = Environment::GetCurrent(args);
169
170 CHECK_EQ(args.Length(), 3);
171 CHECK(args[0]->IsObject());
172 CHECK(args[1]->IsObject());
173 CHECK(args[2]->IsBoolean());
174
175 Local<Object> sc = args[1].As<Object>();
176 Kind kind = args[2]->IsTrue() ? SSLWrap<TLSWrap>::kServer :
177 SSLWrap<TLSWrap>::kClient;
178
179 StreamBase* stream = StreamBase::FromObject(args[0].As<Object>());
180 CHECK_NOT_NULL(stream);
181
182 Local<Object> obj;
183 if (!env->tls_wrap_constructor_function()
184 ->NewInstance(env->context())
185 .ToLocal(&obj)) {
186 return;
187 }
188
189 TLSWrap* res = new TLSWrap(env, obj, kind, stream, Unwrap<SecureContext>(sc));
190
191 args.GetReturnValue().Set(res->object());
192 }
193
194
Receive(const FunctionCallbackInfo<Value> & args)195 void TLSWrap::Receive(const FunctionCallbackInfo<Value>& args) {
196 TLSWrap* wrap;
197 ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
198
199 ArrayBufferViewContents<char> buffer(args[0]);
200 const char* data = buffer.data();
201 size_t len = buffer.length();
202 Debug(wrap, "Receiving %zu bytes injected from JS", len);
203
204 // Copy given buffer entirely or partiall if handle becomes closed
205 while (len > 0 && wrap->IsAlive() && !wrap->IsClosing()) {
206 uv_buf_t buf = wrap->OnStreamAlloc(len);
207 size_t copy = buf.len > len ? len : buf.len;
208 memcpy(buf.base, data, copy);
209 buf.len = copy;
210 wrap->OnStreamRead(copy, buf);
211
212 data += copy;
213 len -= copy;
214 }
215 }
216
217
Start(const FunctionCallbackInfo<Value> & args)218 void TLSWrap::Start(const FunctionCallbackInfo<Value>& args) {
219 TLSWrap* wrap;
220 ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
221
222 CHECK(!wrap->started_);
223
224 wrap->started_ = true;
225
226 // Send ClientHello handshake
227 CHECK(wrap->is_client());
228 // Seems odd to read when when we want to send, but SSL_read() triggers a
229 // handshake if a session isn't established, and handshake will cause
230 // encrypted data to become available for output.
231 wrap->ClearOut();
232 wrap->EncOut();
233 }
234
235
SSLInfoCallback(const SSL * ssl_,int where,int ret)236 void TLSWrap::SSLInfoCallback(const SSL* ssl_, int where, int ret) {
237 if (!(where & (SSL_CB_HANDSHAKE_START | SSL_CB_HANDSHAKE_DONE)))
238 return;
239
240 // SSL_renegotiate_pending() should take `const SSL*`, but it does not.
241 SSL* ssl = const_cast<SSL*>(ssl_);
242 TLSWrap* c = static_cast<TLSWrap*>(SSL_get_app_data(ssl_));
243 Environment* env = c->env();
244 HandleScope handle_scope(env->isolate());
245 Context::Scope context_scope(env->context());
246 Local<Object> object = c->object();
247
248 if (where & SSL_CB_HANDSHAKE_START) {
249 Debug(c, "SSLInfoCallback(SSL_CB_HANDSHAKE_START);");
250 // Start is tracked to limit number and frequency of renegotiation attempts,
251 // since excessive renegotiation may be an attack.
252 Local<Value> callback;
253
254 if (object->Get(env->context(), env->onhandshakestart_string())
255 .ToLocal(&callback) && callback->IsFunction()) {
256 Local<Value> argv[] = { env->GetNow() };
257 c->MakeCallback(callback.As<Function>(), arraysize(argv), argv);
258 }
259 }
260
261 // SSL_CB_HANDSHAKE_START and SSL_CB_HANDSHAKE_DONE are called
262 // sending HelloRequest in OpenSSL-1.1.1.
263 // We need to check whether this is in a renegotiation state or not.
264 if (where & SSL_CB_HANDSHAKE_DONE && !SSL_renegotiate_pending(ssl)) {
265 Debug(c, "SSLInfoCallback(SSL_CB_HANDSHAKE_DONE);");
266 CHECK(!SSL_renegotiate_pending(ssl));
267 Local<Value> callback;
268
269 c->established_ = true;
270
271 if (object->Get(env->context(), env->onhandshakedone_string())
272 .ToLocal(&callback) && callback->IsFunction()) {
273 c->MakeCallback(callback.As<Function>(), 0, nullptr);
274 }
275 }
276 }
277
278
EncOut()279 void TLSWrap::EncOut() {
280 Debug(this, "Trying to write encrypted output");
281
282 // Ignore cycling data if ClientHello wasn't yet parsed
283 if (!hello_parser_.IsEnded()) {
284 Debug(this, "Returning from EncOut(), hello_parser_ active");
285 return;
286 }
287
288 // Write in progress
289 if (write_size_ != 0) {
290 Debug(this, "Returning from EncOut(), write currently in progress");
291 return;
292 }
293
294 // Wait for `newSession` callback to be invoked
295 if (is_awaiting_new_session()) {
296 Debug(this, "Returning from EncOut(), awaiting new session");
297 return;
298 }
299
300 // Split-off queue
301 if (established_ && current_write_ != nullptr) {
302 Debug(this, "EncOut() setting write_callback_scheduled_");
303 write_callback_scheduled_ = true;
304 }
305
306 if (ssl_ == nullptr) {
307 Debug(this, "Returning from EncOut(), ssl_ == nullptr");
308 return;
309 }
310
311 // No encrypted output ready to write to the underlying stream.
312 if (BIO_pending(enc_out_) == 0) {
313 Debug(this, "No pending encrypted output");
314 if (pending_cleartext_input_.size() == 0) {
315 if (!in_dowrite_) {
316 Debug(this, "No pending cleartext input, not inside DoWrite()");
317 InvokeQueued(0);
318 } else {
319 Debug(this, "No pending cleartext input, inside DoWrite()");
320 // TODO(@sam-github, @addaleax) If in_dowrite_ is true, appdata was
321 // passed to SSL_write(). If we are here, the data was not encrypted to
322 // enc_out_ yet. Calling Done() "works", but since the write is not
323 // flushed, its too soon. Just returning and letting the next EncOut()
324 // call Done() passes the test suite, but without more careful analysis,
325 // its not clear if it is always correct. Not calling Done() could block
326 // data flow, so for now continue to call Done(), just do it in the next
327 // tick.
328 BaseObjectPtr<TLSWrap> strong_ref{this};
329 env()->SetImmediate([this, strong_ref](Environment* env) {
330 InvokeQueued(0);
331 });
332 }
333 }
334 return;
335 }
336
337 char* data[kSimultaneousBufferCount];
338 size_t size[arraysize(data)];
339 size_t count = arraysize(data);
340 write_size_ = crypto::NodeBIO::FromBIO(enc_out_)->PeekMultiple(data,
341 size,
342 &count);
343 CHECK(write_size_ != 0 && count != 0);
344
345 uv_buf_t buf[arraysize(data)];
346 uv_buf_t* bufs = buf;
347 for (size_t i = 0; i < count; i++)
348 buf[i] = uv_buf_init(data[i], size[i]);
349
350 Debug(this, "Writing %zu buffers to the underlying stream", count);
351 StreamWriteResult res = underlying_stream()->Write(bufs, count);
352 if (res.err != 0) {
353 InvokeQueued(res.err);
354 return;
355 }
356
357 if (!res.async) {
358 Debug(this, "Write finished synchronously");
359 HandleScope handle_scope(env()->isolate());
360
361 // Simulate asynchronous finishing, TLS cannot handle this at the moment.
362 BaseObjectPtr<TLSWrap> strong_ref{this};
363 env()->SetImmediate([this, strong_ref](Environment* env) {
364 OnStreamAfterWrite(nullptr, 0);
365 });
366 }
367 }
368
369
OnStreamAfterWrite(WriteWrap * req_wrap,int status)370 void TLSWrap::OnStreamAfterWrite(WriteWrap* req_wrap, int status) {
371 Debug(this, "OnStreamAfterWrite(status = %d)", status);
372 if (current_empty_write_ != nullptr) {
373 Debug(this, "Had empty write");
374 WriteWrap* finishing = current_empty_write_;
375 current_empty_write_ = nullptr;
376 finishing->Done(status);
377 return;
378 }
379
380 if (ssl_ == nullptr) {
381 Debug(this, "ssl_ == nullptr, marking as cancelled");
382 status = UV_ECANCELED;
383 }
384
385 // Handle error
386 if (status) {
387 if (shutdown_) {
388 Debug(this, "Ignoring error after shutdown");
389 return;
390 }
391
392 // Notify about error
393 InvokeQueued(status);
394 return;
395 }
396
397 // Commit
398 crypto::NodeBIO::FromBIO(enc_out_)->Read(nullptr, write_size_);
399
400 // Ensure that the progress will be made and `InvokeQueued` will be called.
401 ClearIn();
402
403 // Try writing more data
404 write_size_ = 0;
405 EncOut();
406 }
407
408
GetSSLError(int status,int * err,std::string * msg)409 Local<Value> TLSWrap::GetSSLError(int status, int* err, std::string* msg) {
410 EscapableHandleScope scope(env()->isolate());
411
412 // ssl_ is already destroyed in reading EOF by close notify alert.
413 if (ssl_ == nullptr)
414 return Local<Value>();
415
416 *err = SSL_get_error(ssl_.get(), status);
417 switch (*err) {
418 case SSL_ERROR_NONE:
419 case SSL_ERROR_WANT_READ:
420 case SSL_ERROR_WANT_WRITE:
421 case SSL_ERROR_WANT_X509_LOOKUP:
422 return Local<Value>();
423
424 case SSL_ERROR_ZERO_RETURN:
425 return scope.Escape(env()->zero_return_string());
426
427 case SSL_ERROR_SSL:
428 case SSL_ERROR_SYSCALL:
429 {
430 unsigned long ssl_err = ERR_peek_error(); // NOLINT(runtime/int)
431 BIO* bio = BIO_new(BIO_s_mem());
432 ERR_print_errors(bio);
433
434 BUF_MEM* mem;
435 BIO_get_mem_ptr(bio, &mem);
436
437 Isolate* isolate = env()->isolate();
438 Local<Context> context = isolate->GetCurrentContext();
439
440 Local<String> message =
441 OneByteString(isolate, mem->data, mem->length);
442 Local<Value> exception = Exception::Error(message);
443 Local<Object> obj = exception->ToObject(context).ToLocalChecked();
444
445 const char* ls = ERR_lib_error_string(ssl_err);
446 const char* fs = ERR_func_error_string(ssl_err);
447 const char* rs = ERR_reason_error_string(ssl_err);
448
449 if (ls != nullptr)
450 obj->Set(context, env()->library_string(),
451 OneByteString(isolate, ls)).Check();
452 if (fs != nullptr)
453 obj->Set(context, env()->function_string(),
454 OneByteString(isolate, fs)).Check();
455 if (rs != nullptr) {
456 obj->Set(context, env()->reason_string(),
457 OneByteString(isolate, rs)).Check();
458
459 // SSL has no API to recover the error name from the number, so we
460 // transform reason strings like "this error" to "ERR_SSL_THIS_ERROR",
461 // which ends up being close to the original error macro name.
462 std::string code(rs);
463
464 for (auto& c : code) {
465 if (c == ' ')
466 c = '_';
467 else
468 c = ToUpper(c);
469 }
470 obj->Set(context, env()->code_string(),
471 OneByteString(isolate, ("ERR_SSL_" + code).c_str()))
472 .Check();
473 }
474
475 if (msg != nullptr)
476 msg->assign(mem->data, mem->data + mem->length);
477
478 BIO_free_all(bio);
479
480 return scope.Escape(exception);
481 }
482
483 default:
484 UNREACHABLE();
485 }
486 UNREACHABLE();
487 }
488
489
ClearOut()490 void TLSWrap::ClearOut() {
491 Debug(this, "Trying to read cleartext output");
492 // Ignore cycling data if ClientHello wasn't yet parsed
493 if (!hello_parser_.IsEnded()) {
494 Debug(this, "Returning from ClearOut(), hello_parser_ active");
495 return;
496 }
497
498 // No reads after EOF
499 if (eof_) {
500 Debug(this, "Returning from ClearOut(), EOF reached");
501 return;
502 }
503
504 if (ssl_ == nullptr) {
505 Debug(this, "Returning from ClearOut(), ssl_ == nullptr");
506 return;
507 }
508
509 crypto::MarkPopErrorOnReturn mark_pop_error_on_return;
510
511 char out[kClearOutChunkSize];
512 int read;
513 for (;;) {
514 read = SSL_read(ssl_.get(), out, sizeof(out));
515 Debug(this, "Read %d bytes of cleartext output", read);
516
517 if (read <= 0)
518 break;
519
520 char* current = out;
521 while (read > 0) {
522 int avail = read;
523
524 uv_buf_t buf = EmitAlloc(avail);
525 if (static_cast<int>(buf.len) < avail)
526 avail = buf.len;
527 memcpy(buf.base, current, avail);
528 EmitRead(avail, buf);
529
530 // Caveat emptor: OnRead() calls into JS land which can result in
531 // the SSL context object being destroyed. We have to carefully
532 // check that ssl_ != nullptr afterwards.
533 if (ssl_ == nullptr) {
534 Debug(this, "Returning from read loop, ssl_ == nullptr");
535 return;
536 }
537
538 read -= avail;
539 current += avail;
540 }
541 }
542
543 int flags = SSL_get_shutdown(ssl_.get());
544 if (!eof_ && flags & SSL_RECEIVED_SHUTDOWN) {
545 eof_ = true;
546 EmitRead(UV_EOF);
547 }
548
549 // We need to check whether an error occurred or the connection was
550 // shutdown cleanly (SSL_ERROR_ZERO_RETURN) even when read == 0.
551 // See node#1642 and SSL_read(3SSL) for details.
552 if (read <= 0) {
553 HandleScope handle_scope(env()->isolate());
554 int err;
555 Local<Value> arg = GetSSLError(read, &err, nullptr);
556
557 // Ignore ZERO_RETURN after EOF, it is basically not a error
558 if (err == SSL_ERROR_ZERO_RETURN && eof_)
559 return;
560
561 if (!arg.IsEmpty()) {
562 Debug(this, "Got SSL error (%d), calling onerror", err);
563 // When TLS Alert are stored in wbio,
564 // it should be flushed to socket before destroyed.
565 if (BIO_pending(enc_out_) != 0)
566 EncOut();
567
568 MakeCallback(env()->onerror_string(), 1, &arg);
569 }
570 }
571 }
572
573
ClearIn()574 void TLSWrap::ClearIn() {
575 Debug(this, "Trying to write cleartext input");
576 // Ignore cycling data if ClientHello wasn't yet parsed
577 if (!hello_parser_.IsEnded()) {
578 Debug(this, "Returning from ClearIn(), hello_parser_ active");
579 return;
580 }
581
582 if (ssl_ == nullptr) {
583 Debug(this, "Returning from ClearIn(), ssl_ == nullptr");
584 return;
585 }
586
587 if (pending_cleartext_input_.size() == 0) {
588 Debug(this, "Returning from ClearIn(), no pending data");
589 return;
590 }
591
592 AllocatedBuffer data = std::move(pending_cleartext_input_);
593 crypto::MarkPopErrorOnReturn mark_pop_error_on_return;
594
595 crypto::NodeBIO::FromBIO(enc_out_)->set_allocate_tls_hint(data.size());
596 int written = SSL_write(ssl_.get(), data.data(), data.size());
597 Debug(this, "Writing %zu bytes, written = %d", data.size(), written);
598 CHECK(written == -1 || written == static_cast<int>(data.size()));
599
600 // All written
601 if (written != -1) {
602 Debug(this, "Successfully wrote all data to SSL");
603 return;
604 }
605
606 // Error or partial write
607 HandleScope handle_scope(env()->isolate());
608 Context::Scope context_scope(env()->context());
609
610 int err;
611 std::string error_str;
612 Local<Value> arg = GetSSLError(written, &err, &error_str);
613 if (!arg.IsEmpty()) {
614 Debug(this, "Got SSL error (%d)", err);
615 write_callback_scheduled_ = true;
616 // TODO(@sam-github) Should forward an error object with
617 // .code/.function/.etc, if possible.
618 InvokeQueued(UV_EPROTO, error_str.c_str());
619 } else {
620 Debug(this, "Pushing data back");
621 // Push back the not-yet-written data. This can be skipped in the error
622 // case because no further writes would succeed anyway.
623 pending_cleartext_input_ = std::move(data);
624 }
625 }
626
627
diagnostic_name() const628 std::string TLSWrap::diagnostic_name() const {
629 std::string name = "TLSWrap ";
630 if (is_server())
631 name += "server (";
632 else
633 name += "client (";
634 name += std::to_string(static_cast<int64_t>(get_async_id())) + ")";
635 return name;
636 }
637
638
GetAsyncWrap()639 AsyncWrap* TLSWrap::GetAsyncWrap() {
640 return static_cast<AsyncWrap*>(this);
641 }
642
643
IsIPCPipe()644 bool TLSWrap::IsIPCPipe() {
645 return underlying_stream()->IsIPCPipe();
646 }
647
648
GetFD()649 int TLSWrap::GetFD() {
650 return underlying_stream()->GetFD();
651 }
652
653
IsAlive()654 bool TLSWrap::IsAlive() {
655 return ssl_ != nullptr &&
656 stream_ != nullptr &&
657 underlying_stream()->IsAlive();
658 }
659
660
IsClosing()661 bool TLSWrap::IsClosing() {
662 return underlying_stream()->IsClosing();
663 }
664
665
666
ReadStart()667 int TLSWrap::ReadStart() {
668 Debug(this, "ReadStart()");
669 if (stream_ != nullptr)
670 return stream_->ReadStart();
671 return 0;
672 }
673
674
ReadStop()675 int TLSWrap::ReadStop() {
676 Debug(this, "ReadStop()");
677 if (stream_ != nullptr)
678 return stream_->ReadStop();
679 return 0;
680 }
681
682
Error() const683 const char* TLSWrap::Error() const {
684 return error_.empty() ? nullptr : error_.c_str();
685 }
686
687
ClearError()688 void TLSWrap::ClearError() {
689 error_.clear();
690 }
691
692
693 // Called by StreamBase::Write() to request async write of clear text into SSL.
694 // TODO(@sam-github) Should there be a TLSWrap::DoTryWrite()?
DoWrite(WriteWrap * w,uv_buf_t * bufs,size_t count,uv_stream_t * send_handle)695 int TLSWrap::DoWrite(WriteWrap* w,
696 uv_buf_t* bufs,
697 size_t count,
698 uv_stream_t* send_handle) {
699 CHECK_NULL(send_handle);
700 Debug(this, "DoWrite()");
701
702 if (ssl_ == nullptr) {
703 ClearError();
704 error_ = "Write after DestroySSL";
705 return UV_EPROTO;
706 }
707
708 size_t length = 0;
709 size_t i;
710 size_t nonempty_i = 0;
711 size_t nonempty_count = 0;
712 for (i = 0; i < count; i++) {
713 length += bufs[i].len;
714 if (bufs[i].len > 0) {
715 nonempty_i = i;
716 nonempty_count += 1;
717 }
718 }
719
720 // We want to trigger a Write() on the underlying stream to drive the stream
721 // system, but don't want to encrypt empty buffers into a TLS frame, so see
722 // if we can find something to Write().
723 // First, call ClearOut(). It does an SSL_read(), which might cause handshake
724 // or other internal messages to be encrypted. If it does, write them later
725 // with EncOut().
726 // If there is still no encrypted output, call Write(bufs) on the underlying
727 // stream. Since the bufs are empty, it won't actually write non-TLS data
728 // onto the socket, we just want the side-effects. After, make sure the
729 // WriteWrap was accepted by the stream, or that we call Done() on it.
730 if (length == 0) {
731 Debug(this, "Empty write");
732 ClearOut();
733 if (BIO_pending(enc_out_) == 0) {
734 Debug(this, "No pending encrypted output, writing to underlying stream");
735 CHECK_NULL(current_empty_write_);
736 current_empty_write_ = w;
737 StreamWriteResult res =
738 underlying_stream()->Write(bufs, count, send_handle);
739 if (!res.async) {
740 BaseObjectPtr<TLSWrap> strong_ref{this};
741 env()->SetImmediate([this, strong_ref](Environment* env) {
742 OnStreamAfterWrite(current_empty_write_, 0);
743 });
744 }
745 return 0;
746 }
747 }
748
749 // Store the current write wrap
750 CHECK_NULL(current_write_);
751 current_write_ = w;
752
753 // Write encrypted data to underlying stream and call Done().
754 if (length == 0) {
755 EncOut();
756 return 0;
757 }
758
759 AllocatedBuffer data;
760 crypto::MarkPopErrorOnReturn mark_pop_error_on_return;
761
762 int written = 0;
763
764 // It is common for zero length buffers to be written,
765 // don't copy data if there there is one buffer with data
766 // and one or more zero length buffers.
767 // _http_outgoing.js writes a zero length buffer in
768 // in OutgoingMessage.prototype.end. If there was a large amount
769 // of data supplied to end() there is no sense allocating
770 // and copying it when it could just be used.
771
772 if (nonempty_count != 1) {
773 data = env()->AllocateManaged(length);
774 size_t offset = 0;
775 for (i = 0; i < count; i++) {
776 memcpy(data.data() + offset, bufs[i].base, bufs[i].len);
777 offset += bufs[i].len;
778 }
779
780 crypto::NodeBIO::FromBIO(enc_out_)->set_allocate_tls_hint(length);
781 written = SSL_write(ssl_.get(), data.data(), length);
782 } else {
783 // Only one buffer: try to write directly, only store if it fails
784 uv_buf_t* buf = &bufs[nonempty_i];
785 crypto::NodeBIO::FromBIO(enc_out_)->set_allocate_tls_hint(buf->len);
786 written = SSL_write(ssl_.get(), buf->base, buf->len);
787
788 if (written == -1) {
789 data = env()->AllocateManaged(length);
790 memcpy(data.data(), buf->base, buf->len);
791 }
792 }
793
794 CHECK(written == -1 || written == static_cast<int>(length));
795 Debug(this, "Writing %zu bytes, written = %d", length, written);
796
797 if (written == -1) {
798 int err;
799 Local<Value> arg = GetSSLError(written, &err, &error_);
800
801 // If we stopped writing because of an error, it's fatal, discard the data.
802 if (!arg.IsEmpty()) {
803 Debug(this, "Got SSL error (%d), returning UV_EPROTO", err);
804 current_write_ = nullptr;
805 return UV_EPROTO;
806 }
807
808 Debug(this, "Saving data for later write");
809 // Otherwise, save unwritten data so it can be written later by ClearIn().
810 CHECK_EQ(pending_cleartext_input_.size(), 0);
811 pending_cleartext_input_ = std::move(data);
812 }
813
814 // Write any encrypted/handshake output that may be ready.
815 // Guard against sync call of current_write_->Done(), its unsupported.
816 in_dowrite_ = true;
817 EncOut();
818 in_dowrite_ = false;
819
820 return 0;
821 }
822
823
OnStreamAlloc(size_t suggested_size)824 uv_buf_t TLSWrap::OnStreamAlloc(size_t suggested_size) {
825 CHECK_NOT_NULL(ssl_);
826
827 size_t size = suggested_size;
828 char* base = crypto::NodeBIO::FromBIO(enc_in_)->PeekWritable(&size);
829 return uv_buf_init(base, size);
830 }
831
832
OnStreamRead(ssize_t nread,const uv_buf_t & buf)833 void TLSWrap::OnStreamRead(ssize_t nread, const uv_buf_t& buf) {
834 Debug(this, "Read %zd bytes from underlying stream", nread);
835 if (nread < 0) {
836 // Error should be emitted only after all data was read
837 ClearOut();
838
839 // Ignore EOF if received close_notify
840 if (nread == UV_EOF) {
841 if (eof_)
842 return;
843 eof_ = true;
844 }
845
846 EmitRead(nread);
847 return;
848 }
849
850 // DestroySSL() is the only thing that un-sets ssl_, but that also removes
851 // this TLSWrap as a stream listener, so we should not receive OnStreamRead()
852 // calls anymore.
853 CHECK(ssl_);
854
855 // Commit the amount of data actually read into the peeked/allocated buffer
856 // from the underlying stream.
857 crypto::NodeBIO* enc_in = crypto::NodeBIO::FromBIO(enc_in_);
858 enc_in->Commit(nread);
859
860 // Parse ClientHello first, if we need to. It's only parsed if session event
861 // listeners are used on the server side. "ended" is the initial state, so
862 // can mean parsing was never started, or that parsing is finished. Either
863 // way, ended means we can give the buffered data to SSL.
864 if (!hello_parser_.IsEnded()) {
865 size_t avail = 0;
866 uint8_t* data = reinterpret_cast<uint8_t*>(enc_in->Peek(&avail));
867 CHECK_IMPLIES(data == nullptr, avail == 0);
868 Debug(this, "Passing %zu bytes to the hello parser", avail);
869 return hello_parser_.Parse(data, avail);
870 }
871
872 // Cycle OpenSSL's state
873 Cycle();
874 }
875
876
CreateShutdownWrap(Local<Object> req_wrap_object)877 ShutdownWrap* TLSWrap::CreateShutdownWrap(Local<Object> req_wrap_object) {
878 return underlying_stream()->CreateShutdownWrap(req_wrap_object);
879 }
880
881
DoShutdown(ShutdownWrap * req_wrap)882 int TLSWrap::DoShutdown(ShutdownWrap* req_wrap) {
883 Debug(this, "DoShutdown()");
884 crypto::MarkPopErrorOnReturn mark_pop_error_on_return;
885
886 if (ssl_ && SSL_shutdown(ssl_.get()) == 0)
887 SSL_shutdown(ssl_.get());
888
889 shutdown_ = true;
890 EncOut();
891 return stream_->DoShutdown(req_wrap);
892 }
893
894
SetVerifyMode(const FunctionCallbackInfo<Value> & args)895 void TLSWrap::SetVerifyMode(const FunctionCallbackInfo<Value>& args) {
896 TLSWrap* wrap;
897 ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
898
899 CHECK_EQ(args.Length(), 2);
900 CHECK(args[0]->IsBoolean());
901 CHECK(args[1]->IsBoolean());
902 CHECK_NOT_NULL(wrap->ssl_);
903
904 int verify_mode;
905 if (wrap->is_server()) {
906 bool request_cert = args[0]->IsTrue();
907 if (!request_cert) {
908 // If no cert is requested, there will be none to reject as unauthorized.
909 verify_mode = SSL_VERIFY_NONE;
910 } else {
911 bool reject_unauthorized = args[1]->IsTrue();
912 verify_mode = SSL_VERIFY_PEER;
913 if (reject_unauthorized)
914 verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
915 }
916 } else {
917 // Servers always send a cert if the cipher is not anonymous (anon is
918 // disabled by default), so use VERIFY_NONE and check the cert after the
919 // handshake has completed.
920 verify_mode = SSL_VERIFY_NONE;
921 }
922
923 // Always allow a connection. We'll reject in javascript.
924 SSL_set_verify(wrap->ssl_.get(), verify_mode, crypto::VerifyCallback);
925 }
926
927
EnableSessionCallbacks(const FunctionCallbackInfo<Value> & args)928 void TLSWrap::EnableSessionCallbacks(
929 const FunctionCallbackInfo<Value>& args) {
930 TLSWrap* wrap;
931 ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
932 CHECK_NOT_NULL(wrap->ssl_);
933 wrap->enable_session_callbacks();
934
935 // Clients don't use the HelloParser.
936 if (wrap->is_client())
937 return;
938
939 crypto::NodeBIO::FromBIO(wrap->enc_in_)->set_initial(kMaxHelloLength);
940 wrap->hello_parser_.Start(SSLWrap<TLSWrap>::OnClientHello,
941 OnClientHelloParseEnd,
942 wrap);
943 }
944
EnableKeylogCallback(const FunctionCallbackInfo<Value> & args)945 void TLSWrap::EnableKeylogCallback(
946 const FunctionCallbackInfo<Value>& args) {
947 TLSWrap* wrap;
948 ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
949 CHECK_NOT_NULL(wrap->sc_);
950 SSL_CTX_set_keylog_callback(wrap->sc_->ctx_.get(),
951 SSLWrap<TLSWrap>::KeylogCallback);
952 }
953
954 // Check required capabilities were not excluded from the OpenSSL build:
955 // - OPENSSL_NO_SSL_TRACE excludes SSL_trace()
956 // - OPENSSL_NO_STDIO excludes BIO_new_fp()
957 // HAVE_SSL_TRACE is available on the internal tcp_wrap binding for the tests.
958 #if defined(OPENSSL_NO_SSL_TRACE) || defined(OPENSSL_NO_STDIO)
959 # define HAVE_SSL_TRACE 0
960 #else
961 # define HAVE_SSL_TRACE 1
962 #endif
963
EnableTrace(const FunctionCallbackInfo<Value> & args)964 void TLSWrap::EnableTrace(
965 const FunctionCallbackInfo<Value>& args) {
966 TLSWrap* wrap;
967 ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
968
969 #if HAVE_SSL_TRACE
970 if (wrap->ssl_) {
971 wrap->bio_trace_.reset(BIO_new_fp(stderr, BIO_NOCLOSE | BIO_FP_TEXT));
972 SSL_set_msg_callback(wrap->ssl_.get(), [](int write_p, int version, int
973 content_type, const void* buf, size_t len, SSL* ssl, void* arg)
974 -> void {
975 // BIO_write(), etc., called by SSL_trace, may error. The error should
976 // be ignored, trace is a "best effort", and its usually because stderr
977 // is a non-blocking pipe, and its buffer has overflowed. Leaving errors
978 // on the stack that can get picked up by later SSL_ calls causes
979 // unwanted failures in SSL_ calls, so keep the error stack unchanged.
980 crypto::MarkPopErrorOnReturn mark_pop_error_on_return;
981 SSL_trace(write_p, version, content_type, buf, len, ssl, arg);
982 });
983 SSL_set_msg_callback_arg(wrap->ssl_.get(), wrap->bio_trace_.get());
984 }
985 #endif
986 }
987
DestroySSL(const FunctionCallbackInfo<Value> & args)988 void TLSWrap::DestroySSL(const FunctionCallbackInfo<Value>& args) {
989 TLSWrap* wrap;
990 ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
991 Debug(wrap, "DestroySSL()");
992
993 // If there is a write happening, mark it as finished.
994 wrap->write_callback_scheduled_ = true;
995
996 // And destroy
997 wrap->InvokeQueued(UV_ECANCELED, "Canceled because of SSL destruction");
998
999 // Destroy the SSL structure and friends
1000 wrap->SSLWrap<TLSWrap>::DestroySSL();
1001 wrap->enc_in_ = nullptr;
1002 wrap->enc_out_ = nullptr;
1003
1004 if (wrap->stream_ != nullptr)
1005 wrap->stream_->RemoveStreamListener(wrap);
1006 Debug(wrap, "DestroySSL() finished");
1007 }
1008
1009
EnableCertCb(const FunctionCallbackInfo<Value> & args)1010 void TLSWrap::EnableCertCb(const FunctionCallbackInfo<Value>& args) {
1011 TLSWrap* wrap;
1012 ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1013 wrap->WaitForCertCb(OnClientHelloParseEnd, wrap);
1014 }
1015
1016
OnClientHelloParseEnd(void * arg)1017 void TLSWrap::OnClientHelloParseEnd(void* arg) {
1018 TLSWrap* c = static_cast<TLSWrap*>(arg);
1019 Debug(c, "OnClientHelloParseEnd()");
1020 c->Cycle();
1021 }
1022
1023
GetServername(const FunctionCallbackInfo<Value> & args)1024 void TLSWrap::GetServername(const FunctionCallbackInfo<Value>& args) {
1025 Environment* env = Environment::GetCurrent(args);
1026
1027 TLSWrap* wrap;
1028 ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1029
1030 CHECK_NOT_NULL(wrap->ssl_);
1031
1032 const char* servername = SSL_get_servername(wrap->ssl_.get(),
1033 TLSEXT_NAMETYPE_host_name);
1034 if (servername != nullptr) {
1035 args.GetReturnValue().Set(OneByteString(env->isolate(), servername));
1036 } else {
1037 args.GetReturnValue().Set(false);
1038 }
1039 }
1040
1041
SetServername(const FunctionCallbackInfo<Value> & args)1042 void TLSWrap::SetServername(const FunctionCallbackInfo<Value>& args) {
1043 Environment* env = Environment::GetCurrent(args);
1044
1045 TLSWrap* wrap;
1046 ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1047
1048 CHECK_EQ(args.Length(), 1);
1049 CHECK(args[0]->IsString());
1050 CHECK(!wrap->started_);
1051 CHECK(wrap->is_client());
1052
1053 CHECK_NOT_NULL(wrap->ssl_);
1054
1055 node::Utf8Value servername(env->isolate(), args[0].As<String>());
1056 SSL_set_tlsext_host_name(wrap->ssl_.get(), *servername);
1057 }
1058
1059
SelectSNIContextCallback(SSL * s,int * ad,void * arg)1060 int TLSWrap::SelectSNIContextCallback(SSL* s, int* ad, void* arg) {
1061 TLSWrap* p = static_cast<TLSWrap*>(SSL_get_app_data(s));
1062 Environment* env = p->env();
1063
1064 const char* servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
1065
1066 if (servername == nullptr)
1067 return SSL_TLSEXT_ERR_OK;
1068
1069 HandleScope handle_scope(env->isolate());
1070 Context::Scope context_scope(env->context());
1071
1072 // Call the SNI callback and use its return value as context
1073 Local<Object> object = p->object();
1074 Local<Value> ctx;
1075
1076 // Set the servername as early as possible
1077 Local<Object> owner = p->GetOwner();
1078 if (!owner->Set(env->context(),
1079 env->servername_string(),
1080 OneByteString(env->isolate(), servername)).FromMaybe(false)) {
1081 return SSL_TLSEXT_ERR_NOACK;
1082 }
1083
1084 if (!object->Get(env->context(), env->sni_context_string()).ToLocal(&ctx))
1085 return SSL_TLSEXT_ERR_NOACK;
1086
1087 // Not an object, probably undefined or null
1088 if (!ctx->IsObject())
1089 return SSL_TLSEXT_ERR_NOACK;
1090
1091 Local<FunctionTemplate> cons = env->secure_context_constructor_template();
1092 if (!cons->HasInstance(ctx)) {
1093 // Failure: incorrect SNI context object
1094 Local<Value> err = Exception::TypeError(env->sni_context_err_string());
1095 p->MakeCallback(env->onerror_string(), 1, &err);
1096 return SSL_TLSEXT_ERR_NOACK;
1097 }
1098
1099 SecureContext* sc = Unwrap<SecureContext>(ctx.As<Object>());
1100 CHECK_NOT_NULL(sc);
1101 p->sni_context_ = BaseObjectPtr<SecureContext>(sc);
1102
1103 p->ConfigureSecureContext(sc);
1104 CHECK_EQ(SSL_set_SSL_CTX(p->ssl_.get(), sc->ctx_.get()), sc->ctx_.get());
1105 p->SetCACerts(sc);
1106
1107 return SSL_TLSEXT_ERR_OK;
1108 }
1109
1110 #ifndef OPENSSL_NO_PSK
1111
SetPskIdentityHint(const FunctionCallbackInfo<Value> & args)1112 void TLSWrap::SetPskIdentityHint(const FunctionCallbackInfo<Value>& args) {
1113 TLSWrap* p;
1114 ASSIGN_OR_RETURN_UNWRAP(&p, args.Holder());
1115 CHECK_NOT_NULL(p->ssl_);
1116
1117 Environment* env = p->env();
1118 Isolate* isolate = env->isolate();
1119
1120 CHECK(args[0]->IsString());
1121 node::Utf8Value hint(isolate, args[0].As<String>());
1122
1123 if (!SSL_use_psk_identity_hint(p->ssl_.get(), *hint)) {
1124 Local<Value> err = node::ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED(isolate);
1125 p->MakeCallback(env->onerror_string(), 1, &err);
1126 }
1127 }
1128
EnablePskCallback(const FunctionCallbackInfo<Value> & args)1129 void TLSWrap::EnablePskCallback(const FunctionCallbackInfo<Value>& args) {
1130 TLSWrap* wrap;
1131 ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1132 CHECK_NOT_NULL(wrap->ssl_);
1133
1134 SSL_set_psk_server_callback(wrap->ssl_.get(), PskServerCallback);
1135 SSL_set_psk_client_callback(wrap->ssl_.get(), PskClientCallback);
1136 }
1137
PskServerCallback(SSL * s,const char * identity,unsigned char * psk,unsigned int max_psk_len)1138 unsigned int TLSWrap::PskServerCallback(SSL* s,
1139 const char* identity,
1140 unsigned char* psk,
1141 unsigned int max_psk_len) {
1142 TLSWrap* p = static_cast<TLSWrap*>(SSL_get_app_data(s));
1143
1144 Environment* env = p->env();
1145 Isolate* isolate = env->isolate();
1146 HandleScope scope(isolate);
1147
1148 MaybeLocal<String> maybe_identity_str =
1149 v8::String::NewFromUtf8(isolate, identity, v8::NewStringType::kNormal);
1150
1151 v8::Local<v8::String> identity_str;
1152 if (!maybe_identity_str.ToLocal(&identity_str)) return 0;
1153
1154 // Make sure there are no utf8 replacement symbols.
1155 v8::String::Utf8Value identity_utf8(isolate, identity_str);
1156 if (strcmp(*identity_utf8, identity) != 0) return 0;
1157
1158 Local<Value> argv[] = {identity_str,
1159 Integer::NewFromUnsigned(isolate, max_psk_len)};
1160
1161 MaybeLocal<Value> maybe_psk_val =
1162 p->MakeCallback(env->onpskexchange_symbol(), arraysize(argv), argv);
1163 Local<Value> psk_val;
1164 if (!maybe_psk_val.ToLocal(&psk_val) || !psk_val->IsArrayBufferView())
1165 return 0;
1166
1167 char* psk_buf = Buffer::Data(psk_val);
1168 size_t psk_buflen = Buffer::Length(psk_val);
1169
1170 if (psk_buflen > max_psk_len) return 0;
1171
1172 memcpy(psk, psk_buf, psk_buflen);
1173 return psk_buflen;
1174 }
1175
PskClientCallback(SSL * s,const char * hint,char * identity,unsigned int max_identity_len,unsigned char * psk,unsigned int max_psk_len)1176 unsigned int TLSWrap::PskClientCallback(SSL* s,
1177 const char* hint,
1178 char* identity,
1179 unsigned int max_identity_len,
1180 unsigned char* psk,
1181 unsigned int max_psk_len) {
1182 TLSWrap* p = static_cast<TLSWrap*>(SSL_get_app_data(s));
1183
1184 Environment* env = p->env();
1185 Isolate* isolate = env->isolate();
1186 HandleScope scope(isolate);
1187
1188 Local<Value> argv[] = {Null(isolate),
1189 Integer::NewFromUnsigned(isolate, max_psk_len),
1190 Integer::NewFromUnsigned(isolate, max_identity_len)};
1191 if (hint != nullptr) {
1192 MaybeLocal<String> maybe_hint = String::NewFromUtf8(isolate, hint);
1193
1194 Local<String> local_hint;
1195 if (!maybe_hint.ToLocal(&local_hint)) return 0;
1196
1197 argv[0] = local_hint;
1198 }
1199 MaybeLocal<Value> maybe_ret =
1200 p->MakeCallback(env->onpskexchange_symbol(), arraysize(argv), argv);
1201 Local<Value> ret;
1202 if (!maybe_ret.ToLocal(&ret) || !ret->IsObject()) return 0;
1203 Local<Object> obj = ret.As<Object>();
1204
1205 MaybeLocal<Value> maybe_psk_val = obj->Get(env->context(), env->psk_string());
1206
1207 Local<Value> psk_val;
1208 if (!maybe_psk_val.ToLocal(&psk_val) || !psk_val->IsArrayBufferView())
1209 return 0;
1210
1211 char* psk_buf = Buffer::Data(psk_val);
1212 size_t psk_buflen = Buffer::Length(psk_val);
1213
1214 if (psk_buflen > max_psk_len) return 0;
1215
1216 MaybeLocal<Value> maybe_identity_val =
1217 obj->Get(env->context(), env->identity_string());
1218 Local<Value> identity_val;
1219 if (!maybe_identity_val.ToLocal(&identity_val) || !identity_val->IsString())
1220 return 0;
1221 Local<String> identity_str = identity_val.As<String>();
1222
1223 String::Utf8Value identity_buf(isolate, identity_str);
1224 size_t identity_len = identity_buf.length();
1225
1226 if (identity_len > max_identity_len) return 0;
1227
1228 memcpy(identity, *identity_buf, identity_len);
1229 memcpy(psk, psk_buf, psk_buflen);
1230
1231 return psk_buflen;
1232 }
1233
1234 #endif
1235
GetWriteQueueSize(const FunctionCallbackInfo<Value> & info)1236 void TLSWrap::GetWriteQueueSize(const FunctionCallbackInfo<Value>& info) {
1237 TLSWrap* wrap;
1238 ASSIGN_OR_RETURN_UNWRAP(&wrap, info.This());
1239
1240 if (wrap->ssl_ == nullptr) {
1241 info.GetReturnValue().Set(0);
1242 return;
1243 }
1244
1245 uint32_t write_queue_size = BIO_pending(wrap->enc_out_);
1246 info.GetReturnValue().Set(write_queue_size);
1247 }
1248
1249
MemoryInfo(MemoryTracker * tracker) const1250 void TLSWrap::MemoryInfo(MemoryTracker* tracker) const {
1251 SSLWrap<TLSWrap>::MemoryInfo(tracker);
1252 tracker->TrackField("error", error_);
1253 tracker->TrackFieldWithSize("pending_cleartext_input",
1254 pending_cleartext_input_.size(),
1255 "AllocatedBuffer");
1256 if (enc_in_ != nullptr)
1257 tracker->TrackField("enc_in", crypto::NodeBIO::FromBIO(enc_in_));
1258 if (enc_out_ != nullptr)
1259 tracker->TrackField("enc_out", crypto::NodeBIO::FromBIO(enc_out_));
1260 }
1261
1262
Initialize(Local<Object> target,Local<Value> unused,Local<Context> context,void * priv)1263 void TLSWrap::Initialize(Local<Object> target,
1264 Local<Value> unused,
1265 Local<Context> context,
1266 void* priv) {
1267 Environment* env = Environment::GetCurrent(context);
1268
1269 env->SetMethod(target, "wrap", TLSWrap::Wrap);
1270
1271 NODE_DEFINE_CONSTANT(target, HAVE_SSL_TRACE);
1272
1273 Local<FunctionTemplate> t = BaseObject::MakeLazilyInitializedJSTemplate(env);
1274 Local<String> tlsWrapString =
1275 FIXED_ONE_BYTE_STRING(env->isolate(), "TLSWrap");
1276 t->SetClassName(tlsWrapString);
1277 t->InstanceTemplate()->SetInternalFieldCount(StreamBase::kInternalFieldCount);
1278
1279 Local<FunctionTemplate> get_write_queue_size =
1280 FunctionTemplate::New(env->isolate(),
1281 GetWriteQueueSize,
1282 env->as_callback_data(),
1283 Signature::New(env->isolate(), t));
1284 t->PrototypeTemplate()->SetAccessorProperty(
1285 env->write_queue_size_string(),
1286 get_write_queue_size,
1287 Local<FunctionTemplate>(),
1288 static_cast<PropertyAttribute>(ReadOnly | DontDelete));
1289
1290 t->Inherit(AsyncWrap::GetConstructorTemplate(env));
1291 env->SetProtoMethod(t, "receive", Receive);
1292 env->SetProtoMethod(t, "start", Start);
1293 env->SetProtoMethod(t, "setVerifyMode", SetVerifyMode);
1294 env->SetProtoMethod(t, "enableSessionCallbacks", EnableSessionCallbacks);
1295 env->SetProtoMethod(t, "enableKeylogCallback", EnableKeylogCallback);
1296 env->SetProtoMethod(t, "enableTrace", EnableTrace);
1297 env->SetProtoMethod(t, "destroySSL", DestroySSL);
1298 env->SetProtoMethod(t, "enableCertCb", EnableCertCb);
1299
1300 #ifndef OPENSSL_NO_PSK
1301 env->SetProtoMethod(t, "setPskIdentityHint", SetPskIdentityHint);
1302 env->SetProtoMethod(t, "enablePskCallback", EnablePskCallback);
1303 #endif
1304
1305 StreamBase::AddMethods(env, t);
1306 SSLWrap<TLSWrap>::AddMethods(env, t);
1307
1308 env->SetProtoMethod(t, "getServername", GetServername);
1309 env->SetProtoMethod(t, "setServername", SetServername);
1310
1311 Local<Function> fn = t->GetFunction(env->context()).ToLocalChecked();
1312
1313 env->set_tls_wrap_constructor_function(fn);
1314
1315 target->Set(env->context(), tlsWrapString, fn).Check();
1316 }
1317
1318 } // namespace node
1319
1320 NODE_MODULE_CONTEXT_AWARE_INTERNAL(tls_wrap, node::TLSWrap::Initialize)
1321