Node.js  v8.x
Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine
tls_wrap.cc
Go to the documentation of this file.
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.h"
24 #include "async-wrap-inl.h"
25 #include "node_buffer.h" // Buffer
26 #include "node_crypto.h" // SecureContext
27 #include "node_crypto_bio.h" // NodeBIO
28 #include "node_crypto_clienthello.h" // ClientHelloParser
30 #include "node_counters.h"
31 #include "node_internals.h"
32 #include "stream_base.h"
33 #include "stream_base-inl.h"
34 #include "util.h"
35 #include "util-inl.h"
36 
37 namespace node {
38 
39 using crypto::SecureContext;
40 using crypto::SSLWrap;
41 using v8::Context;
42 using v8::EscapableHandleScope;
43 using v8::Exception;
44 using v8::Function;
45 using v8::FunctionCallbackInfo;
46 using v8::FunctionTemplate;
47 using v8::Local;
48 using v8::Object;
49 using v8::String;
50 using v8::Value;
51 
52 TLSWrap::TLSWrap(Environment* env,
53  Kind kind,
54  StreamBase* stream,
55  SecureContext* sc)
56  : AsyncWrap(env,
57  env->tls_wrap_constructor_function()
58  ->NewInstance(env->context()).ToLocalChecked(),
59  AsyncWrap::PROVIDER_TLSWRAP),
60  SSLWrap<TLSWrap>(env, sc, kind),
61  StreamBase(env),
62  sc_(sc),
63  stream_(stream),
64  enc_in_(nullptr),
65  enc_out_(nullptr),
66  clear_in_(nullptr),
67  write_size_(0),
68  started_(false),
69  established_(false),
70  shutdown_(false),
71  error_(nullptr),
72  cycle_depth_(0),
73  eof_(false) {
74  node::Wrap(object(), this);
75  MakeWeak(this);
76 
77  // sc comes from an Unwrap. Make sure it was assigned.
78  CHECK_NE(sc, nullptr);
79 
80  // We've our own session callbacks
81  SSL_CTX_sess_set_get_cb(sc_->ctx_, SSLWrap<TLSWrap>::GetSessionCallback);
82  SSL_CTX_sess_set_new_cb(sc_->ctx_, SSLWrap<TLSWrap>::NewSessionCallback);
83 
84  stream_->Consume();
85  stream_->set_after_write_cb({ OnAfterWriteImpl, this });
86  stream_->set_alloc_cb({ OnAllocImpl, this });
87  stream_->set_read_cb({ OnReadImpl, this });
88  stream_->set_destruct_cb({ OnDestructImpl, this });
89 
90  set_alloc_cb({ OnAllocSelf, this });
91  set_read_cb({ OnReadSelf, this });
92 
93  InitSSL();
94 }
95 
96 
97 TLSWrap::~TLSWrap() {
98  enc_in_ = nullptr;
99  enc_out_ = nullptr;
100  delete clear_in_;
101  clear_in_ = nullptr;
102 
103  sc_ = nullptr;
104 
105 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
106  sni_context_.Reset();
107 #endif // SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
108 
109  ClearError();
110 }
111 
112 
113 void TLSWrap::MakePending() {
114  write_item_queue_.MoveBack(&pending_write_items_);
115 }
116 
117 
118 bool TLSWrap::InvokeQueued(int status, const char* error_str) {
119  if (pending_write_items_.IsEmpty())
120  return false;
121 
122  // Process old queue
123  WriteItemList queue;
124  pending_write_items_.MoveBack(&queue);
125  while (WriteItem* wi = queue.PopFront()) {
126  wi->w_->Done(status, error_str);
127  delete wi;
128  }
129 
130  return true;
131 }
132 
133 
134 void TLSWrap::NewSessionDoneCb() {
135  Cycle();
136 }
137 
138 
139 void TLSWrap::InitSSL() {
140  // Initialize SSL
141  enc_in_ = crypto::NodeBIO::New();
142  enc_out_ = crypto::NodeBIO::New();
143  crypto::NodeBIO::FromBIO(enc_in_)->AssignEnvironment(env());
144  crypto::NodeBIO::FromBIO(enc_out_)->AssignEnvironment(env());
145 
146  SSL_set_bio(ssl_, enc_in_, enc_out_);
147 
148  // NOTE: This could be overridden in SetVerifyMode
149  SSL_set_verify(ssl_, SSL_VERIFY_NONE, crypto::VerifyCallback);
150 
151 #ifdef SSL_MODE_RELEASE_BUFFERS
152  long mode = SSL_get_mode(ssl_); // NOLINT(runtime/int)
153  SSL_set_mode(ssl_, mode | SSL_MODE_RELEASE_BUFFERS);
154 #endif // SSL_MODE_RELEASE_BUFFERS
155 
156  SSL_set_app_data(ssl_, this);
157  SSL_set_info_callback(ssl_, SSLInfoCallback);
158 
159 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
160  if (is_server()) {
161  SSL_CTX_set_tlsext_servername_callback(sc_->ctx_, SelectSNIContextCallback);
162  }
163 #endif // SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
164 
165  InitNPN(sc_);
166 
167  SSL_set_cert_cb(ssl_, SSLWrap<TLSWrap>::SSLCertCallback, this);
168 
169  if (is_server()) {
170  SSL_set_accept_state(ssl_);
171  } else if (is_client()) {
172  // Enough space for server response (hello, cert)
173  crypto::NodeBIO::FromBIO(enc_in_)->set_initial(kInitialClientBufferLength);
174  SSL_set_connect_state(ssl_);
175  } else {
176  // Unexpected
177  ABORT();
178  }
179 
180  // Initialize ring for queud clear data
181  clear_in_ = new crypto::NodeBIO();
182  clear_in_->AssignEnvironment(env());
183 }
184 
185 
186 void TLSWrap::Wrap(const FunctionCallbackInfo<Value>& args) {
187  Environment* env = Environment::GetCurrent(args);
188 
189  if (args.Length() < 1 || !args[0]->IsObject()) {
190  return env->ThrowTypeError(
191  "First argument should be a StreamWrap instance");
192  }
193  if (args.Length() < 2 || !args[1]->IsObject()) {
194  return env->ThrowTypeError(
195  "Second argument should be a SecureContext instance");
196  }
197  if (args.Length() < 3 || !args[2]->IsBoolean())
198  return env->ThrowTypeError("Third argument should be boolean");
199 
200  Local<External> stream_obj = args[0].As<External>();
201  Local<Object> sc = args[1].As<Object>();
202  Kind kind = args[2]->IsTrue() ? SSLWrap<TLSWrap>::kServer :
203  SSLWrap<TLSWrap>::kClient;
204 
205  StreamBase* stream = static_cast<StreamBase*>(stream_obj->Value());
206  CHECK_NE(stream, nullptr);
207 
208  TLSWrap* res = new TLSWrap(env, kind, stream, Unwrap<SecureContext>(sc));
209 
210  args.GetReturnValue().Set(res->object());
211 }
212 
213 
214 void TLSWrap::Receive(const FunctionCallbackInfo<Value>& args) {
215  TLSWrap* wrap;
216  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
217 
218  CHECK(Buffer::HasInstance(args[0]));
219  char* data = Buffer::Data(args[0]);
220  size_t len = Buffer::Length(args[0]);
221 
222  uv_buf_t buf;
223 
224  // Copy given buffer entirely or partiall if handle becomes closed
225  while (len > 0 && wrap->IsAlive() && !wrap->IsClosing()) {
226  wrap->stream_->OnAlloc(len, &buf);
227  size_t copy = buf.len > len ? len : buf.len;
228  memcpy(buf.base, data, copy);
229  buf.len = copy;
230  wrap->stream_->OnRead(buf.len, &buf);
231 
232  data += copy;
233  len -= copy;
234  }
235 }
236 
237 
238 void TLSWrap::Start(const FunctionCallbackInfo<Value>& args) {
239  Environment* env = Environment::GetCurrent(args);
240 
241  TLSWrap* wrap;
242  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
243 
244  if (wrap->started_)
245  return env->ThrowError("Already started.");
246  wrap->started_ = true;
247 
248  // Send ClientHello handshake
249  CHECK(wrap->is_client());
250  wrap->ClearOut();
251  wrap->EncOut();
252 }
253 
254 
255 void TLSWrap::SSLInfoCallback(const SSL* ssl_, int where, int ret) {
256  if (!(where & (SSL_CB_HANDSHAKE_START | SSL_CB_HANDSHAKE_DONE)))
257  return;
258 
259  // Be compatible with older versions of OpenSSL. SSL_get_app_data() wants
260  // a non-const SSL* in OpenSSL <= 0.9.7e.
261  SSL* ssl = const_cast<SSL*>(ssl_);
262  TLSWrap* c = static_cast<TLSWrap*>(SSL_get_app_data(ssl));
263  Environment* env = c->env();
264  Local<Object> object = c->object();
265 
266  if (where & SSL_CB_HANDSHAKE_START) {
267  Local<Value> callback = object->Get(env->onhandshakestart_string());
268  if (callback->IsFunction()) {
269  c->MakeCallback(callback.As<Function>(), 0, nullptr);
270  }
271  }
272 
273  if (where & SSL_CB_HANDSHAKE_DONE) {
274  c->established_ = true;
275  Local<Value> callback = object->Get(env->onhandshakedone_string());
276  if (callback->IsFunction()) {
277  c->MakeCallback(callback.As<Function>(), 0, nullptr);
278  }
279  }
280 }
281 
282 
283 void TLSWrap::EncOut() {
284  // Ignore cycling data if ClientHello wasn't yet parsed
285  if (!hello_parser_.IsEnded())
286  return;
287 
288  // Write in progress
289  if (write_size_ != 0)
290  return;
291 
292  // Wait for `newSession` callback to be invoked
293  if (is_waiting_new_session())
294  return;
295 
296  // Split-off queue
297  if (established_ && !write_item_queue_.IsEmpty())
298  MakePending();
299 
300  if (ssl_ == nullptr)
301  return;
302 
303  // No data to write
304  if (BIO_pending(enc_out_) == 0) {
305  if (clear_in_->Length() == 0)
306  InvokeQueued(0);
307  return;
308  }
309 
310  char* data[kSimultaneousBufferCount];
311  size_t size[arraysize(data)];
312  size_t count = arraysize(data);
313  write_size_ = crypto::NodeBIO::FromBIO(enc_out_)->PeekMultiple(data,
314  size,
315  &count);
316  CHECK(write_size_ != 0 && count != 0);
317 
318  Local<Object> req_wrap_obj =
319  env()->write_wrap_constructor_function()
320  ->NewInstance(env()->context()).ToLocalChecked();
321  WriteWrap* write_req = WriteWrap::New(env(),
322  req_wrap_obj,
323  this,
324  EncOutCb);
325 
326  uv_buf_t buf[arraysize(data)];
327  for (size_t i = 0; i < count; i++)
328  buf[i] = uv_buf_init(data[i], size[i]);
329  int err = stream_->DoWrite(write_req, buf, count, nullptr);
330 
331  // Ignore errors, this should be already handled in js
332  if (err) {
333  write_req->Dispose();
334  InvokeQueued(err);
335  } else {
336  NODE_COUNT_NET_BYTES_SENT(write_size_);
337  }
338 }
339 
340 
341 void TLSWrap::EncOutCb(WriteWrap* req_wrap, int status) {
342  TLSWrap* wrap = req_wrap->wrap()->Cast<TLSWrap>();
343  req_wrap->Dispose();
344 
345  // We should not be getting here after `DestroySSL`, because all queued writes
346  // must be invoked with UV_ECANCELED
347  CHECK_NE(wrap->ssl_, nullptr);
348 
349  // Handle error
350  if (status) {
351  // Ignore errors after shutdown
352  if (wrap->shutdown_)
353  return;
354 
355  // Notify about error
356  wrap->InvokeQueued(status);
357  return;
358  }
359 
360  // Commit
361  crypto::NodeBIO::FromBIO(wrap->enc_out_)->Read(nullptr, wrap->write_size_);
362 
363  // Ensure that the progress will be made and `InvokeQueued` will be called.
364  wrap->ClearIn();
365 
366  // Try writing more data
367  wrap->write_size_ = 0;
368  wrap->EncOut();
369 }
370 
371 
372 Local<Value> TLSWrap::GetSSLError(int status, int* err, const char** msg) {
373  EscapableHandleScope scope(env()->isolate());
374 
375  // ssl_ is already destroyed in reading EOF by close notify alert.
376  if (ssl_ == nullptr)
377  return Local<Value>();
378 
379  *err = SSL_get_error(ssl_, status);
380  switch (*err) {
381  case SSL_ERROR_NONE:
382  case SSL_ERROR_WANT_READ:
383  case SSL_ERROR_WANT_WRITE:
384  case SSL_ERROR_WANT_X509_LOOKUP:
385  break;
386  case SSL_ERROR_ZERO_RETURN:
387  return scope.Escape(env()->zero_return_string());
388  break;
389  default:
390  {
391  CHECK(*err == SSL_ERROR_SSL || *err == SSL_ERROR_SYSCALL);
392 
393  BIO* bio = BIO_new(BIO_s_mem());
394  ERR_print_errors(bio);
395 
396  BUF_MEM* mem;
397  BIO_get_mem_ptr(bio, &mem);
398 
399  Local<String> message =
400  OneByteString(env()->isolate(), mem->data, mem->length);
401  Local<Value> exception = Exception::Error(message);
402 
403  if (msg != nullptr) {
404  CHECK_EQ(*msg, nullptr);
405  char* const buf = new char[mem->length + 1];
406  memcpy(buf, mem->data, mem->length);
407  buf[mem->length] = '\0';
408  *msg = buf;
409  }
410  BIO_free_all(bio);
411 
412  return scope.Escape(exception);
413  }
414  }
415  return Local<Value>();
416 }
417 
418 
419 void TLSWrap::ClearOut() {
420  // Ignore cycling data if ClientHello wasn't yet parsed
421  if (!hello_parser_.IsEnded())
422  return;
423 
424  // No reads after EOF
425  if (eof_)
426  return;
427 
428  if (ssl_ == nullptr)
429  return;
430 
431  crypto::MarkPopErrorOnReturn mark_pop_error_on_return;
432 
433  char out[kClearOutChunkSize];
434  int read;
435  for (;;) {
436  read = SSL_read(ssl_, out, sizeof(out));
437 
438  if (read <= 0)
439  break;
440 
441  char* current = out;
442  while (read > 0) {
443  int avail = read;
444 
445  uv_buf_t buf;
446  OnAlloc(avail, &buf);
447  if (static_cast<int>(buf.len) < avail)
448  avail = buf.len;
449  memcpy(buf.base, current, avail);
450  OnRead(avail, &buf);
451 
452  // Caveat emptor: OnRead() calls into JS land which can result in
453  // the SSL context object being destroyed. We have to carefully
454  // check that ssl_ != nullptr afterwards.
455  if (ssl_ == nullptr)
456  return;
457 
458  read -= avail;
459  current += avail;
460  }
461  }
462 
463  int flags = SSL_get_shutdown(ssl_);
464  if (!eof_ && flags & SSL_RECEIVED_SHUTDOWN) {
465  eof_ = true;
466  OnRead(UV_EOF, nullptr);
467  }
468 
469  // We need to check whether an error occurred or the connection was
470  // shutdown cleanly (SSL_ERROR_ZERO_RETURN) even when read == 0.
471  // See node#1642 and SSL_read(3SSL) for details.
472  if (read <= 0) {
473  int err;
474  Local<Value> arg = GetSSLError(read, &err, nullptr);
475 
476  // Ignore ZERO_RETURN after EOF, it is basically not a error
477  if (err == SSL_ERROR_ZERO_RETURN && eof_)
478  return;
479 
480  if (!arg.IsEmpty()) {
481  // When TLS Alert are stored in wbio,
482  // it should be flushed to socket before destroyed.
483  if (BIO_pending(enc_out_) != 0)
484  EncOut();
485 
486  MakeCallback(env()->onerror_string(), 1, &arg);
487  }
488  }
489 }
490 
491 
492 bool TLSWrap::ClearIn() {
493  // Ignore cycling data if ClientHello wasn't yet parsed
494  if (!hello_parser_.IsEnded())
495  return false;
496 
497  if (ssl_ == nullptr)
498  return false;
499 
500  crypto::MarkPopErrorOnReturn mark_pop_error_on_return;
501 
502  int written = 0;
503  while (clear_in_->Length() > 0) {
504  size_t avail = 0;
505  char* data = clear_in_->Peek(&avail);
506  written = SSL_write(ssl_, data, avail);
507  CHECK(written == -1 || written == static_cast<int>(avail));
508  if (written == -1)
509  break;
510  clear_in_->Read(nullptr, avail);
511  }
512 
513  // All written
514  if (clear_in_->Length() == 0) {
515  CHECK_GE(written, 0);
516  return true;
517  }
518 
519  // Error or partial write
520  int err;
521  const char* error_str = nullptr;
522  Local<Value> arg = GetSSLError(written, &err, &error_str);
523  if (!arg.IsEmpty()) {
524  MakePending();
525  InvokeQueued(UV_EPROTO, error_str);
526  delete[] error_str;
527  clear_in_->Reset();
528  }
529 
530  return false;
531 }
532 
533 
534 void* TLSWrap::Cast() {
535  return reinterpret_cast<void*>(this);
536 }
537 
538 
539 AsyncWrap* TLSWrap::GetAsyncWrap() {
540  return static_cast<AsyncWrap*>(this);
541 }
542 
543 
544 bool TLSWrap::IsIPCPipe() {
545  return stream_->IsIPCPipe();
546 }
547 
548 
549 int TLSWrap::GetFD() {
550  return stream_->GetFD();
551 }
552 
553 
554 bool TLSWrap::IsAlive() {
555  return ssl_ != nullptr && stream_ != nullptr && stream_->IsAlive();
556 }
557 
558 
559 bool TLSWrap::IsClosing() {
560  return stream_->IsClosing();
561 }
562 
563 
564 int TLSWrap::ReadStart() {
565  return stream_->ReadStart();
566 }
567 
568 
569 int TLSWrap::ReadStop() {
570  return stream_->ReadStop();
571 }
572 
573 
574 const char* TLSWrap::Error() const {
575  return error_;
576 }
577 
578 
579 void TLSWrap::ClearError() {
580  delete[] error_;
581  error_ = nullptr;
582 }
583 
584 
585 int TLSWrap::DoWrite(WriteWrap* w,
586  uv_buf_t* bufs,
587  size_t count,
588  uv_stream_t* send_handle) {
589  CHECK_EQ(send_handle, nullptr);
590  CHECK_NE(ssl_, nullptr);
591 
592  bool empty = true;
593 
594  // Empty writes should not go through encryption process
595  size_t i;
596  for (i = 0; i < count; i++)
597  if (bufs[i].len > 0) {
598  empty = false;
599  break;
600  }
601  if (empty) {
602  ClearOut();
603  // However, if there is any data that should be written to the socket,
604  // the callback should not be invoked immediately
605  if (BIO_pending(enc_out_) == 0)
606  return stream_->DoWrite(w, bufs, count, send_handle);
607  }
608 
609  // Queue callback to execute it on next tick
610  write_item_queue_.PushBack(new WriteItem(w));
611  w->Dispatched();
612 
613  // Write queued data
614  if (empty) {
615  EncOut();
616  return 0;
617  }
618 
619  // Process enqueued data first
620  if (!ClearIn()) {
621  // If there're still data to process - enqueue current one
622  for (i = 0; i < count; i++)
623  clear_in_->Write(bufs[i].base, bufs[i].len);
624  return 0;
625  }
626 
627  if (ssl_ == nullptr) {
628  ClearError();
629 
630  static char msg[] = "Write after DestroySSL";
631  char* tmp = new char[sizeof(msg)];
632  memcpy(tmp, msg, sizeof(msg));
633  error_ = tmp;
634  return UV_EPROTO;
635  }
636 
637  crypto::MarkPopErrorOnReturn mark_pop_error_on_return;
638 
639  int written = 0;
640  for (i = 0; i < count; i++) {
641  written = SSL_write(ssl_, bufs[i].base, bufs[i].len);
642  CHECK(written == -1 || written == static_cast<int>(bufs[i].len));
643  if (written == -1)
644  break;
645  }
646 
647  if (i != count) {
648  int err;
649  Local<Value> arg = GetSSLError(written, &err, &error_);
650  if (!arg.IsEmpty())
651  return UV_EPROTO;
652 
653  // No errors, queue rest
654  for (; i < count; i++)
655  clear_in_->Write(bufs[i].base, bufs[i].len);
656  }
657 
658  // Try writing data immediately
659  EncOut();
660 
661  return 0;
662 }
663 
664 
665 void TLSWrap::OnAfterWriteImpl(WriteWrap* w, void* ctx) {
666  // Intentionally empty
667 }
668 
669 
670 void TLSWrap::OnAllocImpl(size_t suggested_size, uv_buf_t* buf, void* ctx) {
671  TLSWrap* wrap = static_cast<TLSWrap*>(ctx);
672 
673  if (wrap->ssl_ == nullptr) {
674  *buf = uv_buf_init(nullptr, 0);
675  return;
676  }
677 
678  size_t size = 0;
679  buf->base = crypto::NodeBIO::FromBIO(wrap->enc_in_)->PeekWritable(&size);
680  buf->len = size;
681 }
682 
683 
684 void TLSWrap::OnReadImpl(ssize_t nread,
685  const uv_buf_t* buf,
686  uv_handle_type pending,
687  void* ctx) {
688  TLSWrap* wrap = static_cast<TLSWrap*>(ctx);
689  wrap->DoRead(nread, buf, pending);
690 }
691 
692 
693 void TLSWrap::OnDestructImpl(void* ctx) {
694  TLSWrap* wrap = static_cast<TLSWrap*>(ctx);
695  wrap->clear_stream();
696 }
697 
698 
699 void TLSWrap::OnAllocSelf(size_t suggested_size, uv_buf_t* buf, void* ctx) {
700  buf->base = node::Malloc(suggested_size);
701  buf->len = suggested_size;
702 }
703 
704 
705 void TLSWrap::OnReadSelf(ssize_t nread,
706  const uv_buf_t* buf,
707  uv_handle_type pending,
708  void* ctx) {
709  TLSWrap* wrap = static_cast<TLSWrap*>(ctx);
710  Local<Object> buf_obj;
711  if (buf != nullptr)
712  buf_obj = Buffer::New(wrap->env(), buf->base, buf->len).ToLocalChecked();
713  wrap->EmitData(nread, buf_obj, Local<Object>());
714 }
715 
716 
717 void TLSWrap::DoRead(ssize_t nread,
718  const uv_buf_t* buf,
719  uv_handle_type pending) {
720  if (nread < 0) {
721  // Error should be emitted only after all data was read
722  ClearOut();
723 
724  // Ignore EOF if received close_notify
725  if (nread == UV_EOF) {
726  if (eof_)
727  return;
728  eof_ = true;
729  }
730 
731  OnRead(nread, nullptr);
732  return;
733  }
734 
735  // Only client connections can receive data
736  if (ssl_ == nullptr) {
737  OnRead(UV_EPROTO, nullptr);
738  return;
739  }
740 
741  // Commit read data
742  crypto::NodeBIO* enc_in = crypto::NodeBIO::FromBIO(enc_in_);
743  enc_in->Commit(nread);
744 
745  // Parse ClientHello first
746  if (!hello_parser_.IsEnded()) {
747  size_t avail = 0;
748  uint8_t* data = reinterpret_cast<uint8_t*>(enc_in->Peek(&avail));
749  CHECK(avail == 0 || data != nullptr);
750  return hello_parser_.Parse(data, avail);
751  }
752 
753  // Cycle OpenSSL's state
754  Cycle();
755 }
756 
757 
758 int TLSWrap::DoShutdown(ShutdownWrap* req_wrap) {
759  crypto::MarkPopErrorOnReturn mark_pop_error_on_return;
760 
761  if (ssl_ != nullptr && SSL_shutdown(ssl_) == 0)
762  SSL_shutdown(ssl_);
763 
764  shutdown_ = true;
765  EncOut();
766  return stream_->DoShutdown(req_wrap);
767 }
768 
769 
770 void TLSWrap::SetVerifyMode(const FunctionCallbackInfo<Value>& args) {
771  Environment* env = Environment::GetCurrent(args);
772 
773  TLSWrap* wrap;
774  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
775 
776  if (args.Length() < 2 || !args[0]->IsBoolean() || !args[1]->IsBoolean())
777  return env->ThrowTypeError("Bad arguments, expected two booleans");
778 
779  if (wrap->ssl_ == nullptr)
780  return env->ThrowTypeError("SetVerifyMode after destroySSL");
781 
782  int verify_mode;
783  if (wrap->is_server()) {
784  bool request_cert = args[0]->IsTrue();
785  if (!request_cert) {
786  // Note reject_unauthorized ignored.
787  verify_mode = SSL_VERIFY_NONE;
788  } else {
789  bool reject_unauthorized = args[1]->IsTrue();
790  verify_mode = SSL_VERIFY_PEER;
791  if (reject_unauthorized)
792  verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
793  }
794  } else {
795  // Note request_cert and reject_unauthorized are ignored for clients.
796  verify_mode = SSL_VERIFY_NONE;
797  }
798 
799  // Always allow a connection. We'll reject in javascript.
800  SSL_set_verify(wrap->ssl_, verify_mode, crypto::VerifyCallback);
801 }
802 
803 
804 void TLSWrap::EnableSessionCallbacks(
805  const FunctionCallbackInfo<Value>& args) {
806  TLSWrap* wrap;
807  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
808  if (wrap->ssl_ == nullptr) {
809  return wrap->env()->ThrowTypeError(
810  "EnableSessionCallbacks after destroySSL");
811  }
812  wrap->enable_session_callbacks();
813  crypto::NodeBIO::FromBIO(wrap->enc_in_)->set_initial(kMaxHelloLength);
814  wrap->hello_parser_.Start(SSLWrap<TLSWrap>::OnClientHello,
815  OnClientHelloParseEnd,
816  wrap);
817 }
818 
819 
820 void TLSWrap::DestroySSL(const FunctionCallbackInfo<Value>& args) {
821  TLSWrap* wrap;
822  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
823 
824  // Move all writes to pending
825  wrap->MakePending();
826 
827  // And destroy
828  wrap->InvokeQueued(UV_ECANCELED, "Canceled because of SSL destruction");
829 
830  // Destroy the SSL structure and friends
831  wrap->SSLWrap<TLSWrap>::DestroySSL();
832 
833  delete wrap->clear_in_;
834  wrap->clear_in_ = nullptr;
835 }
836 
837 
838 void TLSWrap::EnableCertCb(const FunctionCallbackInfo<Value>& args) {
839  TLSWrap* wrap;
840  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
841  wrap->WaitForCertCb(OnClientHelloParseEnd, wrap);
842 }
843 
844 
845 void TLSWrap::OnClientHelloParseEnd(void* arg) {
846  TLSWrap* c = static_cast<TLSWrap*>(arg);
847  c->Cycle();
848 }
849 
850 
851 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
852 void TLSWrap::GetServername(const FunctionCallbackInfo<Value>& args) {
853  Environment* env = Environment::GetCurrent(args);
854 
855  TLSWrap* wrap;
856  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
857 
858  CHECK_NE(wrap->ssl_, nullptr);
859 
860  const char* servername = SSL_get_servername(wrap->ssl_,
861  TLSEXT_NAMETYPE_host_name);
862  if (servername != nullptr) {
863  args.GetReturnValue().Set(OneByteString(env->isolate(), servername));
864  } else {
865  args.GetReturnValue().Set(false);
866  }
867 }
868 
869 
870 void TLSWrap::SetServername(const FunctionCallbackInfo<Value>& args) {
871  Environment* env = Environment::GetCurrent(args);
872 
873  TLSWrap* wrap;
874  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
875 
876  if (args.Length() < 1 || !args[0]->IsString())
877  return env->ThrowTypeError("First argument should be a string");
878 
879  if (wrap->started_)
880  return env->ThrowError("Already started.");
881 
882  if (!wrap->is_client())
883  return;
884 
885  CHECK_NE(wrap->ssl_, nullptr);
886 
887 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
888  node::Utf8Value servername(env->isolate(), args[0].As<String>());
889  SSL_set_tlsext_host_name(wrap->ssl_, *servername);
890 #endif // SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
891 }
892 
893 
894 int TLSWrap::SelectSNIContextCallback(SSL* s, int* ad, void* arg) {
895  TLSWrap* p = static_cast<TLSWrap*>(SSL_get_app_data(s));
896  Environment* env = p->env();
897 
898  const char* servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
899 
900  if (servername == nullptr)
901  return SSL_TLSEXT_ERR_OK;
902 
903  // Call the SNI callback and use its return value as context
904  Local<Object> object = p->object();
905  Local<Value> ctx = object->Get(env->sni_context_string());
906 
907  // Not an object, probably undefined or null
908  if (!ctx->IsObject())
909  return SSL_TLSEXT_ERR_NOACK;
910 
911  Local<FunctionTemplate> cons = env->secure_context_constructor_template();
912  if (!cons->HasInstance(ctx)) {
913  // Failure: incorrect SNI context object
914  Local<Value> err = Exception::TypeError(env->sni_context_err_string());
915  p->MakeCallback(env->onerror_string(), 1, &err);
916  return SSL_TLSEXT_ERR_NOACK;
917  }
918 
919  p->sni_context_.Reset();
920  p->sni_context_.Reset(env->isolate(), ctx);
921 
922  SecureContext* sc = Unwrap<SecureContext>(ctx.As<Object>());
923  CHECK_NE(sc, nullptr);
924  p->SetSNIContext(sc);
925  return SSL_TLSEXT_ERR_OK;
926 }
927 #endif // SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
928 
929 
930 void TLSWrap::Initialize(Local<Object> target,
931  Local<Value> unused,
932  Local<Context> context) {
933  Environment* env = Environment::GetCurrent(context);
934 
935  env->SetMethod(target, "wrap", TLSWrap::Wrap);
936 
937  auto constructor = [](const FunctionCallbackInfo<Value>& args) {
938  CHECK(args.IsConstructCall());
939  args.This()->SetAlignedPointerInInternalField(0, nullptr);
940  };
941 
942  Local<String> tlsWrapString =
943  FIXED_ONE_BYTE_STRING(env->isolate(), "TLSWrap");
944 
945  auto t = env->NewFunctionTemplate(constructor);
946  t->InstanceTemplate()->SetInternalFieldCount(1);
947  t->SetClassName(tlsWrapString);
948 
949  AsyncWrap::AddWrapMethods(env, t, AsyncWrap::kFlagHasReset);
950  env->SetProtoMethod(t, "receive", Receive);
951  env->SetProtoMethod(t, "start", Start);
952  env->SetProtoMethod(t, "setVerifyMode", SetVerifyMode);
953  env->SetProtoMethod(t, "enableSessionCallbacks", EnableSessionCallbacks);
954  env->SetProtoMethod(t, "destroySSL", DestroySSL);
955  env->SetProtoMethod(t, "enableCertCb", EnableCertCb);
956 
957  StreamBase::AddMethods<TLSWrap>(env, t, StreamBase::kFlagHasWritev);
958  SSLWrap<TLSWrap>::AddMethods(env, t);
959 
960 #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB
961  env->SetProtoMethod(t, "getServername", GetServername);
962  env->SetProtoMethod(t, "setServername", SetServername);
963 #endif // SSL_CRT_SET_TLSEXT_SERVERNAME_CB
964 
965  env->set_tls_wrap_constructor_function(t->GetFunction());
966 
967  target->Set(tlsWrapString, t->GetFunction());
968 }
969 
970 } // namespace node
971 
bool HasInstance(Local< Value > val)
Definition: node_buffer.cc:201
unsigned char * buf
Definition: cares_wrap.cc:483
void NODE_COUNT_NET_BYTES_SENT(int bytes)
NODE_MODULE_CONTEXT_AWARE_BUILTIN(inspector, node::inspector::Agent::InitInspector)
int len
Definition: cares_wrap.cc:485
QueryWrap * wrap
Definition: cares_wrap.cc:478
int status
Definition: cares_wrap.cc:479
union node::cares_wrap::@8::CaresAsyncData::@0 data
size_t Length(Local< Value > val)
Definition: node_buffer.cc:227
void Initialize(Local< Object > target, Local< Value > unused, Local< Context > context, void *priv)
Definition: node_http2.cc:1172
char * Data(Local< Value > val)
Definition: node_buffer.cc:211
dtrace p
Definition: v8ustack.d:615
dtrace s
Definition: v8ustack.d:615
dtrace t
Definition: v8ustack.d:582
int VerifyCallback(int preverify_ok, X509_STORE_CTX *ctx)
MaybeLocal< Object > New(Isolate *isolate, Local< String > string, enum encoding enc)
Definition: node_buffer.cc:241
MaybeLocal< Value > MakeCallback(Isolate *isolate, Local< Object > recv, Local< Function > callback, int argc, Local< Value > *argv, async_id asyncId, async_id triggerAsyncId)
Definition: async-wrap.cc:802
this ctx
Definition: v8ustack.d:369
int Start(Isolate *isolate, IsolateData *isolate_data, int argc, const char *const *argv, int exec_argc, const char *const *exec_argv)
Definition: node.cc:4536