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