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 "crypto/crypto_tls.h"
23 #include "crypto/crypto_context.h"
24 #include "crypto/crypto_common.h"
25 #include "crypto/crypto_util.h"
26 #include "crypto/crypto_bio.h"
27 #include "crypto/crypto_clienthello-inl.h"
28 #include "async_wrap-inl.h"
29 #include "debug_utils-inl.h"
30 #include "memory_tracker-inl.h"
31 #include "node_buffer.h"
32 #include "node_errors.h"
33 #include "stream_base-inl.h"
34 #include "util-inl.h"
35
36 namespace node {
37
38 using v8::Array;
39 using v8::ArrayBuffer;
40 using v8::ArrayBufferView;
41 using v8::BackingStore;
42 using v8::Boolean;
43 using v8::Context;
44 using v8::DontDelete;
45 using v8::Exception;
46 using v8::False;
47 using v8::Function;
48 using v8::FunctionCallbackInfo;
49 using v8::FunctionTemplate;
50 using v8::HandleScope;
51 using v8::Integer;
52 using v8::Isolate;
53 using v8::Local;
54 using v8::MaybeLocal;
55 using v8::Null;
56 using v8::Object;
57 using v8::PropertyAttribute;
58 using v8::ReadOnly;
59 using v8::Signature;
60 using v8::String;
61 using v8::Uint32;
62 using v8::Value;
63
64 namespace crypto {
65
66 namespace {
GetSessionCallback( SSL* s, const unsigned char* key, int len, int* copy)67 SSL_SESSION* GetSessionCallback(
68 SSL* s,
69 const unsigned char* key,
70 int len,
71 int* copy) {
72 TLSWrap* w = static_cast<TLSWrap*>(SSL_get_app_data(s));
73 *copy = 0;
74 return w->ReleaseSession();
75 }
76
OnClientHello( void* arg, const ClientHelloParser::ClientHello& hello)77 void OnClientHello(
78 void* arg,
79 const ClientHelloParser::ClientHello& hello) {
80 TLSWrap* w = static_cast<TLSWrap*>(arg);
81 Environment* env = w->env();
82 HandleScope handle_scope(env->isolate());
83 Context::Scope context_scope(env->context());
84
85 Local<Object> hello_obj = Object::New(env->isolate());
86 Local<String> servername = (hello.servername() == nullptr)
87 ? String::Empty(env->isolate())
88 : OneByteString(env->isolate(),
89 hello.servername(),
90 hello.servername_size());
91 Local<Object> buf =
92 Buffer::Copy(
93 env,
94 reinterpret_cast<const char*>(hello.session_id()),
95 hello.session_size()).FromMaybe(Local<Object>());
96
97 if ((buf.IsEmpty() ||
98 hello_obj->Set(env->context(), env->session_id_string(), buf)
99 .IsNothing()) ||
100 hello_obj->Set(env->context(), env->servername_string(), servername)
101 .IsNothing() ||
102 hello_obj
103 ->Set(env->context(),
104 env->tls_ticket_string(),
105 Boolean::New(env->isolate(), hello.has_ticket()))
106 .IsNothing()) {
107 return;
108 }
109
110 Local<Value> argv[] = { hello_obj };
111 w->MakeCallback(env->onclienthello_string(), arraysize(argv), argv);
112 }
113
KeylogCallback(const SSL* s, const char* line)114 void KeylogCallback(const SSL* s, const char* line) {
115 TLSWrap* w = static_cast<TLSWrap*>(SSL_get_app_data(s));
116 Environment* env = w->env();
117 HandleScope handle_scope(env->isolate());
118 Context::Scope context_scope(env->context());
119
120 const size_t size = strlen(line);
121 Local<Value> line_bf = Buffer::Copy(env, line, 1 + size)
122 .FromMaybe(Local<Value>());
123 if (UNLIKELY(line_bf.IsEmpty()))
124 return;
125
126 char* data = Buffer::Data(line_bf);
127 data[size] = '\n';
128 w->MakeCallback(env->onkeylog_string(), 1, &line_bf);
129 }
130
NewSessionCallback(SSL* s, SSL_SESSION* sess)131 int NewSessionCallback(SSL* s, SSL_SESSION* sess) {
132 TLSWrap* w = static_cast<TLSWrap*>(SSL_get_app_data(s));
133 Environment* env = w->env();
134 HandleScope handle_scope(env->isolate());
135 Context::Scope context_scope(env->context());
136
137 if (!w->has_session_callbacks())
138 return 0;
139
140 // Check if session is small enough to be stored
141 int size = i2d_SSL_SESSION(sess, nullptr);
142 if (UNLIKELY(size > SecureContext::kMaxSessionSize))
143 return 0;
144
145 // Serialize session
146 Local<Object> session = Buffer::New(env, size).FromMaybe(Local<Object>());
147 if (UNLIKELY(session.IsEmpty()))
148 return 0;
149
150 unsigned char* session_data =
151 reinterpret_cast<unsigned char*>(Buffer::Data(session));
152
153 CHECK_EQ(i2d_SSL_SESSION(sess, &session_data), size);
154
155 unsigned int session_id_length;
156 const unsigned char* session_id_data =
157 SSL_SESSION_get_id(sess, &session_id_length);
158
159 Local<Object> session_id = Buffer::Copy(
160 env,
161 reinterpret_cast<const char*>(session_id_data),
162 session_id_length).FromMaybe(Local<Object>());
163 if (UNLIKELY(session_id.IsEmpty()))
164 return 0;
165
166 Local<Value> argv[] = {
167 session_id,
168 session
169 };
170
171 // On servers, we pause the handshake until callback of 'newSession', which
172 // calls NewSessionDoneCb(). On clients, there is no callback to wait for.
173 if (w->is_server())
174 w->set_awaiting_new_session(true);
175
176 w->MakeCallback(env->onnewsession_string(), arraysize(argv), argv);
177
178 return 0;
179 }
180
SSLCertCallback(SSL* s, void* arg)181 int SSLCertCallback(SSL* s, void* arg) {
182 TLSWrap* w = static_cast<TLSWrap*>(SSL_get_app_data(s));
183
184 if (!w->is_server() || !w->is_waiting_cert_cb())
185 return 1;
186
187 if (w->is_cert_cb_running())
188 // Not an error. Suspend handshake with SSL_ERROR_WANT_X509_LOOKUP, and
189 // handshake will continue after certcb is done.
190 return -1;
191
192 Environment* env = w->env();
193 HandleScope handle_scope(env->isolate());
194 Context::Scope context_scope(env->context());
195 w->set_cert_cb_running();
196
197 Local<Object> info = Object::New(env->isolate());
198
199 const char* servername = GetServerName(s);
200 Local<String> servername_str = (servername == nullptr)
201 ? String::Empty(env->isolate())
202 : OneByteString(env->isolate(), servername, strlen(servername));
203
204 Local<Value> ocsp = Boolean::New(
205 env->isolate(), SSL_get_tlsext_status_type(s) == TLSEXT_STATUSTYPE_ocsp);
206
207 if (info->Set(env->context(), env->servername_string(), servername_str)
208 .IsNothing() ||
209 info->Set(env->context(), env->ocsp_request_string(), ocsp).IsNothing()) {
210 return 1;
211 }
212
213 Local<Value> argv[] = { info };
214 w->MakeCallback(env->oncertcb_string(), arraysize(argv), argv);
215
216 return w->is_cert_cb_running() ? -1 : 1;
217 }
218
SelectALPNCallback( SSL* s, const unsigned char** out, unsigned char* outlen, const unsigned char* in, unsigned int inlen, void* arg)219 int SelectALPNCallback(
220 SSL* s,
221 const unsigned char** out,
222 unsigned char* outlen,
223 const unsigned char* in,
224 unsigned int inlen,
225 void* arg) {
226 TLSWrap* w = static_cast<TLSWrap*>(SSL_get_app_data(s));
227 if (w->alpn_callback_enabled_) {
228 Environment* env = w->env();
229 HandleScope handle_scope(env->isolate());
230
231 Local<Value> callback_arg =
232 Buffer::Copy(env, reinterpret_cast<const char*>(in), inlen)
233 .ToLocalChecked();
234
235 MaybeLocal<Value> maybe_callback_result =
236 w->MakeCallback(env->alpn_callback_string(), 1, &callback_arg);
237
238 if (UNLIKELY(maybe_callback_result.IsEmpty())) {
239 // Implies the callback didn't return, because some exception was thrown
240 // during processing, e.g. if callback returned an invalid ALPN value.
241 return SSL_TLSEXT_ERR_ALERT_FATAL;
242 }
243
244 Local<Value> callback_result = maybe_callback_result.ToLocalChecked();
245
246 if (callback_result->IsUndefined()) {
247 // If you set an ALPN callback, but you return undefined for an ALPN
248 // request, you're rejecting all proposed ALPN protocols, and so we send
249 // a fatal alert:
250 return SSL_TLSEXT_ERR_ALERT_FATAL;
251 }
252
253 CHECK(callback_result->IsNumber());
254 unsigned int result_int = callback_result.As<v8::Number>()->Value();
255
256 // The callback returns an offset into the given buffer, for the selected
257 // protocol that should be returned. We then set outlen & out to point
258 // to the selected input length & value directly:
259 *outlen = *(in + result_int);
260 *out = (in + result_int + 1);
261
262 return SSL_TLSEXT_ERR_OK;
263 }
264
265 const std::vector<unsigned char>& alpn_protos = w->alpn_protos_;
266
267 if (alpn_protos.empty()) return SSL_TLSEXT_ERR_NOACK;
268
269 int status = SSL_select_next_proto(const_cast<unsigned char**>(out),
270 outlen,
271 alpn_protos.data(),
272 alpn_protos.size(),
273 in,
274 inlen);
275
276 // According to 3.2. Protocol Selection of RFC7301, fatal
277 // no_application_protocol alert shall be sent but OpenSSL 1.0.2 does not
278 // support it yet. See
279 // https://rt.openssl.org/Ticket/Display.html?id=3463&user=guest&pass=guest
280 return status == OPENSSL_NPN_NEGOTIATED
281 ? SSL_TLSEXT_ERR_OK
282 : SSL_TLSEXT_ERR_NOACK;
283 }
284
TLSExtStatusCallback(SSL* s, void* arg)285 int TLSExtStatusCallback(SSL* s, void* arg) {
286 TLSWrap* w = static_cast<TLSWrap*>(SSL_get_app_data(s));
287 Environment* env = w->env();
288 HandleScope handle_scope(env->isolate());
289
290 if (w->is_client()) {
291 // Incoming response
292 Local<Value> arg;
293 if (GetSSLOCSPResponse(env, s, Null(env->isolate())).ToLocal(&arg))
294 w->MakeCallback(env->onocspresponse_string(), 1, &arg);
295
296 // No async acceptance is possible, so always return 1 to accept the
297 // response. The listener for 'OCSPResponse' event has no control over
298 // return value, but it can .destroy() the connection if the response is not
299 // acceptable.
300 return 1;
301 }
302
303 // Outgoing response
304 Local<ArrayBufferView> obj =
305 w->ocsp_response().FromMaybe(Local<ArrayBufferView>());
306 if (UNLIKELY(obj.IsEmpty()))
307 return SSL_TLSEXT_ERR_NOACK;
308
309 size_t len = obj->ByteLength();
310
311 // OpenSSL takes control of the pointer after accepting it
312 unsigned char* data = MallocOpenSSL<unsigned char>(len);
313 obj->CopyContents(data, len);
314
315 if (!SSL_set_tlsext_status_ocsp_resp(s, data, len))
316 OPENSSL_free(data);
317
318 w->ClearOcspResponse();
319
320 return SSL_TLSEXT_ERR_OK;
321 }
322
ConfigureSecureContext(SecureContext* sc)323 void ConfigureSecureContext(SecureContext* sc) {
324 // OCSP stapling
325 SSL_CTX_set_tlsext_status_cb(sc->ctx().get(), TLSExtStatusCallback);
326 SSL_CTX_set_tlsext_status_arg(sc->ctx().get(), nullptr);
327 }
328
Set( Environment* env, Local<Object> target, Local<String> name, const char* value, bool ignore_null = true)329 inline bool Set(
330 Environment* env,
331 Local<Object> target,
332 Local<String> name,
333 const char* value,
334 bool ignore_null = true) {
335 if (value == nullptr)
336 return ignore_null;
337 return !target->Set(
338 env->context(),
339 name,
340 OneByteString(env->isolate(), value))
341 .IsNothing();
342 }
343
GetBIOError()344 std::string GetBIOError() {
345 std::string ret;
346 ERR_print_errors_cb(
347 [](const char* str, size_t len, void* opaque) {
348 static_cast<std::string*>(opaque)->assign(str, len);
349 return 0;
350 },
351 static_cast<void*>(&ret));
352 return ret;
353 }
354 } // namespace
355
TLSWrap(Environment* env, Local<Object> obj, Kind kind, StreamBase* stream, SecureContext* sc, UnderlyingStreamWriteStatus under_stream_ws)356 TLSWrap::TLSWrap(Environment* env,
357 Local<Object> obj,
358 Kind kind,
359 StreamBase* stream,
360 SecureContext* sc,
361 UnderlyingStreamWriteStatus under_stream_ws)
362 : AsyncWrap(env, obj, AsyncWrap::PROVIDER_TLSWRAP),
363 StreamBase(env),
364 env_(env),
365 kind_(kind),
366 sc_(sc),
367 has_active_write_issued_by_prev_listener_(
368 under_stream_ws == UnderlyingStreamWriteStatus::kHasActive) {
369 MakeWeak();
370 CHECK(sc_);
371 ssl_ = sc_->CreateSSL();
372 CHECK(ssl_);
373
374 sc_->SetGetSessionCallback(GetSessionCallback);
375 sc_->SetNewSessionCallback(NewSessionCallback);
376
377 StreamBase::AttachToObject(GetObject());
378 stream->PushStreamListener(this);
379
380 env_->isolate()->AdjustAmountOfExternalAllocatedMemory(kExternalSize);
381
382 InitSSL();
383 Debug(this, "Created new TLSWrap");
384 }
385
~TLSWrap()386 TLSWrap::~TLSWrap() {
387 Destroy();
388 }
389
ocsp_response() const390 MaybeLocal<ArrayBufferView> TLSWrap::ocsp_response() const {
391 if (ocsp_response_.IsEmpty())
392 return MaybeLocal<ArrayBufferView>();
393 return PersistentToLocal::Default(env()->isolate(), ocsp_response_);
394 }
395
ClearOcspResponse()396 void TLSWrap::ClearOcspResponse() {
397 ocsp_response_.Reset();
398 }
399
ReleaseSession()400 SSL_SESSION* TLSWrap::ReleaseSession() {
401 return next_sess_.release();
402 }
403
InvokeQueued(int status, const char* error_str)404 void TLSWrap::InvokeQueued(int status, const char* error_str) {
405 Debug(this, "Invoking queued write callbacks (%d, %s)", status, error_str);
406 if (!write_callback_scheduled_)
407 return;
408
409 if (current_write_) {
410 BaseObjectPtr<AsyncWrap> current_write = std::move(current_write_);
411 current_write_.reset();
412 WriteWrap* w = WriteWrap::FromObject(current_write);
413 w->Done(status, error_str);
414 }
415 }
416
NewSessionDoneCb()417 void TLSWrap::NewSessionDoneCb() {
418 Debug(this, "New session callback done");
419 Cycle();
420 }
421
InitSSL()422 void TLSWrap::InitSSL() {
423 // Initialize SSL – OpenSSL takes ownership of these.
424 enc_in_ = NodeBIO::New(env()).release();
425 enc_out_ = NodeBIO::New(env()).release();
426
427 SSL_set_bio(ssl_.get(), enc_in_, enc_out_);
428
429 // NOTE: This could be overridden in SetVerifyMode
430 SSL_set_verify(ssl_.get(), SSL_VERIFY_NONE, VerifyCallback);
431
432 #ifdef SSL_MODE_RELEASE_BUFFERS
433 SSL_set_mode(ssl_.get(), SSL_MODE_RELEASE_BUFFERS);
434 #endif // SSL_MODE_RELEASE_BUFFERS
435
436 // This is default in 1.1.1, but set it anyway, Cycle() doesn't currently
437 // re-call ClearIn() if SSL_read() returns SSL_ERROR_WANT_READ, so data can be
438 // left sitting in the incoming enc_in_ and never get processed.
439 // - https://wiki.openssl.org/index.php/TLS1.3#Non-application_data_records
440 SSL_set_mode(ssl_.get(), SSL_MODE_AUTO_RETRY);
441
442 #ifdef OPENSSL_IS_BORINGSSL
443 // OpenSSL allows renegotiation by default, but BoringSSL disables it.
444 // Configure BoringSSL to match OpenSSL's behavior.
445 SSL_set_renegotiate_mode(ssl_.get(), ssl_renegotiate_freely);
446 #endif
447
448 SSL_set_app_data(ssl_.get(), this);
449 // Using InfoCallback isn't how we are supposed to check handshake progress:
450 // https://github.com/openssl/openssl/issues/7199#issuecomment-420915993
451 //
452 // Note on when this gets called on various openssl versions:
453 // https://github.com/openssl/openssl/issues/7199#issuecomment-420670544
454 SSL_set_info_callback(ssl_.get(), SSLInfoCallback);
455
456 if (is_server())
457 sc_->SetSelectSNIContextCallback(SelectSNIContextCallback);
458
459 ConfigureSecureContext(sc_.get());
460
461 SSL_set_cert_cb(ssl_.get(), SSLCertCallback, this);
462
463 if (is_server()) {
464 SSL_set_accept_state(ssl_.get());
465 } else if (is_client()) {
466 // Enough space for server response (hello, cert)
467 NodeBIO::FromBIO(enc_in_)->set_initial(kInitialClientBufferLength);
468 SSL_set_connect_state(ssl_.get());
469 } else {
470 // Unexpected
471 ABORT();
472 }
473 }
474
Wrap(const FunctionCallbackInfo<Value>& args)475 void TLSWrap::Wrap(const FunctionCallbackInfo<Value>& args) {
476 Environment* env = Environment::GetCurrent(args);
477
478 CHECK_EQ(args.Length(), 4);
479 CHECK(args[0]->IsObject());
480 CHECK(args[1]->IsObject());
481 CHECK(args[2]->IsBoolean());
482 CHECK(args[3]->IsBoolean());
483
484 Local<Object> sc = args[1].As<Object>();
485 Kind kind = args[2]->IsTrue() ? Kind::kServer : Kind::kClient;
486
487 UnderlyingStreamWriteStatus under_stream_ws =
488 args[3]->IsTrue() ? UnderlyingStreamWriteStatus::kHasActive
489 : UnderlyingStreamWriteStatus::kVacancy;
490
491 StreamBase* stream = StreamBase::FromObject(args[0].As<Object>());
492 CHECK_NOT_NULL(stream);
493
494 Local<Object> obj;
495 if (!env->tls_wrap_constructor_function()
496 ->NewInstance(env->context())
497 .ToLocal(&obj)) {
498 return;
499 }
500
501 TLSWrap* res = new TLSWrap(
502 env, obj, kind, stream, Unwrap<SecureContext>(sc), under_stream_ws);
503
504 args.GetReturnValue().Set(res->object());
505 }
506
Receive(const FunctionCallbackInfo<Value>& args)507 void TLSWrap::Receive(const FunctionCallbackInfo<Value>& args) {
508 TLSWrap* wrap;
509 ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
510
511 ArrayBufferViewContents<char> buffer(args[0]);
512 const char* data = buffer.data();
513 size_t len = buffer.length();
514 Debug(wrap, "Receiving %zu bytes injected from JS", len);
515
516 // Copy given buffer entirely or partiall if handle becomes closed
517 while (len > 0 && wrap->IsAlive() && !wrap->IsClosing()) {
518 uv_buf_t buf = wrap->OnStreamAlloc(len);
519 size_t copy = buf.len > len ? len : buf.len;
520 memcpy(buf.base, data, copy);
521 buf.len = copy;
522 wrap->OnStreamRead(copy, buf);
523
524 data += copy;
525 len -= copy;
526 }
527 }
528
Start(const FunctionCallbackInfo<Value>& args)529 void TLSWrap::Start(const FunctionCallbackInfo<Value>& args) {
530 TLSWrap* wrap;
531 ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
532
533 CHECK(!wrap->started_);
534 wrap->started_ = true;
535
536 // Send ClientHello handshake
537 CHECK(wrap->is_client());
538 // Seems odd to read when when we want to send, but SSL_read() triggers a
539 // handshake if a session isn't established, and handshake will cause
540 // encrypted data to become available for output.
541 wrap->ClearOut();
542 wrap->EncOut();
543 }
544
SSLInfoCallback(const SSL* ssl_, int where, int ret)545 void TLSWrap::SSLInfoCallback(const SSL* ssl_, int where, int ret) {
546 if (!(where & (SSL_CB_HANDSHAKE_START | SSL_CB_HANDSHAKE_DONE)))
547 return;
548
549 // SSL_renegotiate_pending() should take `const SSL*`, but it does not.
550 SSL* ssl = const_cast<SSL*>(ssl_);
551 TLSWrap* c = static_cast<TLSWrap*>(SSL_get_app_data(ssl_));
552 Environment* env = c->env();
553 HandleScope handle_scope(env->isolate());
554 Context::Scope context_scope(env->context());
555 Local<Object> object = c->object();
556
557 if (where & SSL_CB_HANDSHAKE_START) {
558 Debug(c, "SSLInfoCallback(SSL_CB_HANDSHAKE_START);");
559 // Start is tracked to limit number and frequency of renegotiation attempts,
560 // since excessive renegotiation may be an attack.
561 Local<Value> callback;
562
563 if (object->Get(env->context(), env->onhandshakestart_string())
564 .ToLocal(&callback) && callback->IsFunction()) {
565 Local<Value> argv[] = { env->GetNow() };
566 c->MakeCallback(callback.As<Function>(), arraysize(argv), argv);
567 }
568 }
569
570 // SSL_CB_HANDSHAKE_START and SSL_CB_HANDSHAKE_DONE are called
571 // sending HelloRequest in OpenSSL-1.1.1.
572 // We need to check whether this is in a renegotiation state or not.
573 if (where & SSL_CB_HANDSHAKE_DONE && !SSL_renegotiate_pending(ssl)) {
574 Debug(c, "SSLInfoCallback(SSL_CB_HANDSHAKE_DONE);");
575 CHECK(!SSL_renegotiate_pending(ssl));
576 Local<Value> callback;
577
578 c->established_ = true;
579
580 if (object->Get(env->context(), env->onhandshakedone_string())
581 .ToLocal(&callback) && callback->IsFunction()) {
582 c->MakeCallback(callback.As<Function>(), 0, nullptr);
583 }
584 }
585 }
586
EncOut()587 void TLSWrap::EncOut() {
588 Debug(this, "Trying to write encrypted output");
589
590 // Ignore cycling data if ClientHello wasn't yet parsed
591 if (!hello_parser_.IsEnded()) {
592 Debug(this, "Returning from EncOut(), hello_parser_ active");
593 return;
594 }
595
596 // Write in progress
597 if (write_size_ != 0) {
598 Debug(this, "Returning from EncOut(), write currently in progress");
599 return;
600 }
601
602 // Wait for `newSession` callback to be invoked
603 if (is_awaiting_new_session()) {
604 Debug(this, "Returning from EncOut(), awaiting new session");
605 return;
606 }
607
608 if (UNLIKELY(has_active_write_issued_by_prev_listener_)) {
609 Debug(this,
610 "Returning from EncOut(), "
611 "has_active_write_issued_by_prev_listener_ is true");
612 return;
613 }
614
615 // Split-off queue
616 if (established_ && current_write_) {
617 Debug(this, "EncOut() write is scheduled");
618 write_callback_scheduled_ = true;
619 }
620
621 if (ssl_ == nullptr) {
622 Debug(this, "Returning from EncOut(), ssl_ == nullptr");
623 return;
624 }
625
626 // No encrypted output ready to write to the underlying stream.
627 if (BIO_pending(enc_out_) == 0) {
628 Debug(this, "No pending encrypted output");
629 if (!pending_cleartext_input_ ||
630 pending_cleartext_input_->ByteLength() == 0) {
631 if (!in_dowrite_) {
632 Debug(this, "No pending cleartext input, not inside DoWrite()");
633 InvokeQueued(0);
634 } else {
635 Debug(this, "No pending cleartext input, inside DoWrite()");
636 // TODO(@sam-github, @addaleax) If in_dowrite_ is true, appdata was
637 // passed to SSL_write(). If we are here, the data was not encrypted to
638 // enc_out_ yet. Calling Done() "works", but since the write is not
639 // flushed, its too soon. Just returning and letting the next EncOut()
640 // call Done() passes the test suite, but without more careful analysis,
641 // its not clear if it is always correct. Not calling Done() could block
642 // data flow, so for now continue to call Done(), just do it in the next
643 // tick.
644 BaseObjectPtr<TLSWrap> strong_ref{this};
645 env()->SetImmediate([this, strong_ref](Environment* env) {
646 InvokeQueued(0);
647 });
648 }
649 }
650 return;
651 }
652
653 char* data[kSimultaneousBufferCount];
654 size_t size[arraysize(data)];
655 size_t count = arraysize(data);
656 write_size_ = NodeBIO::FromBIO(enc_out_)->PeekMultiple(data, size, &count);
657 CHECK(write_size_ != 0 && count != 0);
658
659 uv_buf_t buf[arraysize(data)];
660 uv_buf_t* bufs = buf;
661 for (size_t i = 0; i < count; i++)
662 buf[i] = uv_buf_init(data[i], size[i]);
663
664 Debug(this, "Writing %zu buffers to the underlying stream", count);
665 StreamWriteResult res = underlying_stream()->Write(bufs, count);
666 if (res.err != 0) {
667 InvokeQueued(res.err);
668 return;
669 }
670
671 if (!res.async) {
672 Debug(this, "Write finished synchronously");
673 HandleScope handle_scope(env()->isolate());
674
675 // Simulate asynchronous finishing, TLS cannot handle this at the moment.
676 BaseObjectPtr<TLSWrap> strong_ref{this};
677 env()->SetImmediate([this, strong_ref](Environment* env) {
678 OnStreamAfterWrite(nullptr, 0);
679 });
680 }
681 }
682
OnStreamAfterWrite(WriteWrap* req_wrap, int status)683 void TLSWrap::OnStreamAfterWrite(WriteWrap* req_wrap, int status) {
684 Debug(this, "OnStreamAfterWrite(status = %d)", status);
685
686 if (UNLIKELY(has_active_write_issued_by_prev_listener_)) {
687 Debug(this, "Notify write finish to the previous_listener_");
688 CHECK_EQ(write_size_, 0); // we must have restrained writes
689
690 previous_listener_->OnStreamAfterWrite(req_wrap, status);
691 return;
692 }
693
694 if (current_empty_write_) {
695 Debug(this, "Had empty write");
696 BaseObjectPtr<AsyncWrap> current_empty_write =
697 std::move(current_empty_write_);
698 current_empty_write_.reset();
699 WriteWrap* finishing = WriteWrap::FromObject(current_empty_write);
700 finishing->Done(status);
701 return;
702 }
703
704 if (ssl_ == nullptr) {
705 Debug(this, "ssl_ == nullptr, marking as cancelled");
706 status = UV_ECANCELED;
707 }
708
709 // Handle error
710 if (status) {
711 if (shutdown_) {
712 Debug(this, "Ignoring error after shutdown");
713 return;
714 }
715
716 // Notify about error
717 InvokeQueued(status);
718 return;
719 }
720
721 // Commit
722 NodeBIO::FromBIO(enc_out_)->Read(nullptr, write_size_);
723
724 // Ensure that the progress will be made and `InvokeQueued` will be called.
725 ClearIn();
726
727 // Try writing more data
728 write_size_ = 0;
729 EncOut();
730 }
731
ClearOut()732 void TLSWrap::ClearOut() {
733 Debug(this, "Trying to read cleartext output");
734 // Ignore cycling data if ClientHello wasn't yet parsed
735 if (!hello_parser_.IsEnded()) {
736 Debug(this, "Returning from ClearOut(), hello_parser_ active");
737 return;
738 }
739
740 // No reads after EOF
741 if (eof_) {
742 Debug(this, "Returning from ClearOut(), EOF reached");
743 return;
744 }
745
746 if (ssl_ == nullptr) {
747 Debug(this, "Returning from ClearOut(), ssl_ == nullptr");
748 return;
749 }
750
751 MarkPopErrorOnReturn mark_pop_error_on_return;
752
753 char out[kClearOutChunkSize];
754 int read;
755 for (;;) {
756 read = SSL_read(ssl_.get(), out, sizeof(out));
757 Debug(this, "Read %d bytes of cleartext output", read);
758
759 if (read <= 0)
760 break;
761
762 char* current = out;
763 while (read > 0) {
764 int avail = read;
765
766 uv_buf_t buf = EmitAlloc(avail);
767 if (static_cast<int>(buf.len) < avail)
768 avail = buf.len;
769 memcpy(buf.base, current, avail);
770 EmitRead(avail, buf);
771
772 // Caveat emptor: OnRead() calls into JS land which can result in
773 // the SSL context object being destroyed. We have to carefully
774 // check that ssl_ != nullptr afterwards.
775 if (ssl_ == nullptr) {
776 Debug(this, "Returning from read loop, ssl_ == nullptr");
777 return;
778 }
779
780 read -= avail;
781 current += avail;
782 }
783 }
784
785 // We need to check whether an error occurred or the connection was
786 // shutdown cleanly (SSL_ERROR_ZERO_RETURN) even when read == 0.
787 // See node#1642 and SSL_read(3SSL) for details. SSL_get_error must be
788 // called immediately after SSL_read, without calling into JS, which may
789 // change OpenSSL's error queue, modify ssl_, or even destroy ssl_
790 // altogether.
791 if (read <= 0) {
792 HandleScope handle_scope(env()->isolate());
793 Local<Value> error;
794 int err = SSL_get_error(ssl_.get(), read);
795 switch (err) {
796 case SSL_ERROR_ZERO_RETURN:
797 if (!eof_) {
798 eof_ = true;
799 EmitRead(UV_EOF);
800 }
801 return;
802
803 case SSL_ERROR_SSL:
804 case SSL_ERROR_SYSCALL:
805 {
806 unsigned long ssl_err = ERR_peek_error(); // NOLINT(runtime/int)
807
808 Local<Context> context = env()->isolate()->GetCurrentContext();
809 if (UNLIKELY(context.IsEmpty())) return;
810 const std::string error_str = GetBIOError();
811 Local<String> message = OneByteString(
812 env()->isolate(), error_str.c_str(), error_str.size());
813 if (UNLIKELY(message.IsEmpty())) return;
814 error = Exception::Error(message);
815 if (UNLIKELY(error.IsEmpty())) return;
816 Local<Object> obj;
817 if (UNLIKELY(!error->ToObject(context).ToLocal(&obj))) return;
818
819 const char* ls = ERR_lib_error_string(ssl_err);
820 const char* fs = ERR_func_error_string(ssl_err);
821 const char* rs = ERR_reason_error_string(ssl_err);
822 if (!Set(env(), obj, env()->library_string(), ls) ||
823 !Set(env(), obj, env()->function_string(), fs) ||
824 !Set(env(), obj, env()->reason_string(), rs, false)) return;
825 // SSL has no API to recover the error name from the number, so we
826 // transform reason strings like "this error" to "ERR_SSL_THIS_ERROR",
827 // which ends up being close to the original error macro name.
828 std::string code(rs);
829 // TODO(RaisinTen): Pass an appropriate execution policy when it is
830 // implemented in our supported compilers.
831 std::transform(code.begin(), code.end(), code.begin(),
832 [](char c) { return c == ' ' ? '_' : ToUpper(c); });
833 if (!Set(env(), obj,
834 env()->code_string(), ("ERR_SSL_" + code).c_str())) return;
835 }
836 break;
837
838 default:
839 return;
840 }
841
842 Debug(this, "Got SSL error (%d), calling onerror", err);
843 // When TLS Alert are stored in wbio,
844 // it should be flushed to socket before destroyed.
845 if (BIO_pending(enc_out_) != 0)
846 EncOut();
847
848 MakeCallback(env()->onerror_string(), 1, &error);
849 }
850 }
851
ClearIn()852 void TLSWrap::ClearIn() {
853 Debug(this, "Trying to write cleartext input");
854 // Ignore cycling data if ClientHello wasn't yet parsed
855 if (!hello_parser_.IsEnded()) {
856 Debug(this, "Returning from ClearIn(), hello_parser_ active");
857 return;
858 }
859
860 if (ssl_ == nullptr) {
861 Debug(this, "Returning from ClearIn(), ssl_ == nullptr");
862 return;
863 }
864
865 if (!pending_cleartext_input_ ||
866 pending_cleartext_input_->ByteLength() == 0) {
867 Debug(this, "Returning from ClearIn(), no pending data");
868 return;
869 }
870
871 std::unique_ptr<BackingStore> bs = std::move(pending_cleartext_input_);
872 MarkPopErrorOnReturn mark_pop_error_on_return;
873
874 NodeBIO::FromBIO(enc_out_)->set_allocate_tls_hint(bs->ByteLength());
875 int written = SSL_write(ssl_.get(), bs->Data(), bs->ByteLength());
876 Debug(this, "Writing %zu bytes, written = %d", bs->ByteLength(), written);
877 CHECK(written == -1 || written == static_cast<int>(bs->ByteLength()));
878
879 // All written
880 if (written != -1) {
881 Debug(this, "Successfully wrote all data to SSL");
882 return;
883 }
884
885 // Error or partial write
886 int err = SSL_get_error(ssl_.get(), written);
887 if (err == SSL_ERROR_SSL || err == SSL_ERROR_SYSCALL) {
888 Debug(this, "Got SSL error (%d)", err);
889 write_callback_scheduled_ = true;
890 // TODO(@sam-github) Should forward an error object with
891 // .code/.function/.etc, if possible.
892 InvokeQueued(UV_EPROTO, GetBIOError().c_str());
893 return;
894 }
895
896 Debug(this, "Pushing data back");
897 // Push back the not-yet-written data. This can be skipped in the error
898 // case because no further writes would succeed anyway.
899 pending_cleartext_input_ = std::move(bs);
900 }
901
diagnostic_name() const902 std::string TLSWrap::diagnostic_name() const {
903 std::string name = "TLSWrap ";
904 name += is_server() ? "server (" : "client (";
905 name += std::to_string(static_cast<int64_t>(get_async_id())) + ")";
906 return name;
907 }
908
GetAsyncWrap()909 AsyncWrap* TLSWrap::GetAsyncWrap() {
910 return static_cast<AsyncWrap*>(this);
911 }
912
IsIPCPipe()913 bool TLSWrap::IsIPCPipe() {
914 return underlying_stream()->IsIPCPipe();
915 }
916
GetFD()917 int TLSWrap::GetFD() {
918 return underlying_stream()->GetFD();
919 }
920
IsAlive()921 bool TLSWrap::IsAlive() {
922 return ssl_ &&
923 underlying_stream() != nullptr &&
924 underlying_stream()->IsAlive();
925 }
926
IsClosing()927 bool TLSWrap::IsClosing() {
928 return underlying_stream()->IsClosing();
929 }
930
ReadStart()931 int TLSWrap::ReadStart() {
932 Debug(this, "ReadStart()");
933 if (underlying_stream() != nullptr && !eof_)
934 return underlying_stream()->ReadStart();
935 return 0;
936 }
937
ReadStop()938 int TLSWrap::ReadStop() {
939 Debug(this, "ReadStop()");
940 return underlying_stream() != nullptr ? underlying_stream()->ReadStop() : 0;
941 }
942
Error() const943 const char* TLSWrap::Error() const {
944 return error_.empty() ? nullptr : error_.c_str();
945 }
946
ClearError()947 void TLSWrap::ClearError() {
948 error_.clear();
949 }
950
951 // Called by StreamBase::Write() to request async write of clear text into SSL.
952 // TODO(@sam-github) Should there be a TLSWrap::DoTryWrite()?
DoWrite(WriteWrap* w, uv_buf_t* bufs, size_t count, uv_stream_t* send_handle)953 int TLSWrap::DoWrite(WriteWrap* w,
954 uv_buf_t* bufs,
955 size_t count,
956 uv_stream_t* send_handle) {
957 CHECK_NULL(send_handle);
958 Debug(this, "DoWrite()");
959
960 if (ssl_ == nullptr) {
961 ClearError();
962 error_ = "Write after DestroySSL";
963 return UV_EPROTO;
964 }
965
966 size_t length = 0;
967 size_t i;
968 size_t nonempty_i = 0;
969 size_t nonempty_count = 0;
970 for (i = 0; i < count; i++) {
971 length += bufs[i].len;
972 if (bufs[i].len > 0) {
973 nonempty_i = i;
974 nonempty_count += 1;
975 }
976 }
977
978 // We want to trigger a Write() on the underlying stream to drive the stream
979 // system, but don't want to encrypt empty buffers into a TLS frame, so see
980 // if we can find something to Write().
981 // First, call ClearOut(). It does an SSL_read(), which might cause handshake
982 // or other internal messages to be encrypted. If it does, write them later
983 // with EncOut().
984 // If there is still no encrypted output, call Write(bufs) on the underlying
985 // stream. Since the bufs are empty, it won't actually write non-TLS data
986 // onto the socket, we just want the side-effects. After, make sure the
987 // WriteWrap was accepted by the stream, or that we call Done() on it.
988 if (length == 0) {
989 Debug(this, "Empty write");
990 ClearOut();
991 if (BIO_pending(enc_out_) == 0) {
992 Debug(this, "No pending encrypted output, writing to underlying stream");
993 CHECK(!current_empty_write_);
994 current_empty_write_.reset(w->GetAsyncWrap());
995 StreamWriteResult res =
996 underlying_stream()->Write(bufs, count, send_handle);
997 if (!res.async) {
998 BaseObjectPtr<TLSWrap> strong_ref{this};
999 env()->SetImmediate([this, strong_ref](Environment* env) {
1000 OnStreamAfterWrite(WriteWrap::FromObject(current_empty_write_), 0);
1001 });
1002 }
1003 return 0;
1004 }
1005 }
1006
1007 // Store the current write wrap
1008 CHECK(!current_write_);
1009 current_write_.reset(w->GetAsyncWrap());
1010
1011 // Write encrypted data to underlying stream and call Done().
1012 if (length == 0) {
1013 EncOut();
1014 return 0;
1015 }
1016
1017 std::unique_ptr<BackingStore> bs;
1018 MarkPopErrorOnReturn mark_pop_error_on_return;
1019
1020 int written = 0;
1021
1022 // It is common for zero length buffers to be written,
1023 // don't copy data if there there is one buffer with data
1024 // and one or more zero length buffers.
1025 // _http_outgoing.js writes a zero length buffer in
1026 // in OutgoingMessage.prototype.end. If there was a large amount
1027 // of data supplied to end() there is no sense allocating
1028 // and copying it when it could just be used.
1029
1030 if (nonempty_count != 1) {
1031 {
1032 NoArrayBufferZeroFillScope no_zero_fill_scope(env()->isolate_data());
1033 bs = ArrayBuffer::NewBackingStore(env()->isolate(), length);
1034 }
1035 size_t offset = 0;
1036 for (i = 0; i < count; i++) {
1037 memcpy(static_cast<char*>(bs->Data()) + offset,
1038 bufs[i].base, bufs[i].len);
1039 offset += bufs[i].len;
1040 }
1041
1042 NodeBIO::FromBIO(enc_out_)->set_allocate_tls_hint(length);
1043 written = SSL_write(ssl_.get(), bs->Data(), length);
1044 } else {
1045 // Only one buffer: try to write directly, only store if it fails
1046 uv_buf_t* buf = &bufs[nonempty_i];
1047 NodeBIO::FromBIO(enc_out_)->set_allocate_tls_hint(buf->len);
1048 written = SSL_write(ssl_.get(), buf->base, buf->len);
1049
1050 if (written == -1) {
1051 NoArrayBufferZeroFillScope no_zero_fill_scope(env()->isolate_data());
1052 bs = ArrayBuffer::NewBackingStore(env()->isolate(), length);
1053 memcpy(bs->Data(), buf->base, buf->len);
1054 }
1055 }
1056
1057 CHECK(written == -1 || written == static_cast<int>(length));
1058 Debug(this, "Writing %zu bytes, written = %d", length, written);
1059
1060 if (written == -1) {
1061 // If we stopped writing because of an error, it's fatal, discard the data.
1062 int err = SSL_get_error(ssl_.get(), written);
1063 if (err == SSL_ERROR_SSL || err == SSL_ERROR_SYSCALL) {
1064 // TODO(@jasnell): What are we doing with the error?
1065 Debug(this, "Got SSL error (%d), returning UV_EPROTO", err);
1066 current_write_.reset();
1067 return UV_EPROTO;
1068 }
1069
1070 Debug(this, "Saving data for later write");
1071 // Otherwise, save unwritten data so it can be written later by ClearIn().
1072 CHECK(!pending_cleartext_input_ ||
1073 pending_cleartext_input_->ByteLength() == 0);
1074 pending_cleartext_input_ = std::move(bs);
1075 }
1076
1077 // Write any encrypted/handshake output that may be ready.
1078 // Guard against sync call of current_write_->Done(), its unsupported.
1079 in_dowrite_ = true;
1080 EncOut();
1081 in_dowrite_ = false;
1082
1083 return 0;
1084 }
1085
OnStreamAlloc(size_t suggested_size)1086 uv_buf_t TLSWrap::OnStreamAlloc(size_t suggested_size) {
1087 CHECK_NOT_NULL(ssl_);
1088
1089 size_t size = suggested_size;
1090 char* base = NodeBIO::FromBIO(enc_in_)->PeekWritable(&size);
1091 return uv_buf_init(base, size);
1092 }
1093
OnStreamRead(ssize_t nread, const uv_buf_t& buf)1094 void TLSWrap::OnStreamRead(ssize_t nread, const uv_buf_t& buf) {
1095 Debug(this, "Read %zd bytes from underlying stream", nread);
1096
1097 // Ignore everything after close_notify (rfc5246#section-7.2.1)
1098 if (eof_)
1099 return;
1100
1101 if (nread < 0) {
1102 // Error should be emitted only after all data was read
1103 ClearOut();
1104
1105 if (nread == UV_EOF) {
1106 // underlying stream already should have also called ReadStop on itself
1107 eof_ = true;
1108 }
1109
1110 EmitRead(nread);
1111 return;
1112 }
1113
1114 // DestroySSL() is the only thing that un-sets ssl_, but that also removes
1115 // this TLSWrap as a stream listener, so we should not receive OnStreamRead()
1116 // calls anymore.
1117 CHECK(ssl_);
1118
1119 // Commit the amount of data actually read into the peeked/allocated buffer
1120 // from the underlying stream.
1121 NodeBIO* enc_in = NodeBIO::FromBIO(enc_in_);
1122 enc_in->Commit(nread);
1123
1124 // Parse ClientHello first, if we need to. It's only parsed if session event
1125 // listeners are used on the server side. "ended" is the initial state, so
1126 // can mean parsing was never started, or that parsing is finished. Either
1127 // way, ended means we can give the buffered data to SSL.
1128 if (!hello_parser_.IsEnded()) {
1129 size_t avail = 0;
1130 uint8_t* data = reinterpret_cast<uint8_t*>(enc_in->Peek(&avail));
1131 CHECK_IMPLIES(data == nullptr, avail == 0);
1132 Debug(this, "Passing %zu bytes to the hello parser", avail);
1133 return hello_parser_.Parse(data, avail);
1134 }
1135
1136 // Cycle OpenSSL's state
1137 Cycle();
1138 }
1139
CreateShutdownWrap(Local<Object> req_wrap_object)1140 ShutdownWrap* TLSWrap::CreateShutdownWrap(Local<Object> req_wrap_object) {
1141 return underlying_stream()->CreateShutdownWrap(req_wrap_object);
1142 }
1143
DoShutdown(ShutdownWrap* req_wrap)1144 int TLSWrap::DoShutdown(ShutdownWrap* req_wrap) {
1145 Debug(this, "DoShutdown()");
1146 MarkPopErrorOnReturn mark_pop_error_on_return;
1147
1148 if (ssl_ && SSL_shutdown(ssl_.get()) == 0)
1149 SSL_shutdown(ssl_.get());
1150
1151 shutdown_ = true;
1152 EncOut();
1153 return underlying_stream()->DoShutdown(req_wrap);
1154 }
1155
SetVerifyMode(const FunctionCallbackInfo<Value>& args)1156 void TLSWrap::SetVerifyMode(const FunctionCallbackInfo<Value>& args) {
1157 TLSWrap* wrap;
1158 ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1159
1160 CHECK_EQ(args.Length(), 2);
1161 CHECK(args[0]->IsBoolean());
1162 CHECK(args[1]->IsBoolean());
1163 CHECK_NOT_NULL(wrap->ssl_);
1164
1165 int verify_mode;
1166 if (wrap->is_server()) {
1167 bool request_cert = args[0]->IsTrue();
1168 if (!request_cert) {
1169 // If no cert is requested, there will be none to reject as unauthorized.
1170 verify_mode = SSL_VERIFY_NONE;
1171 } else {
1172 bool reject_unauthorized = args[1]->IsTrue();
1173 verify_mode = SSL_VERIFY_PEER;
1174 if (reject_unauthorized)
1175 verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1176 }
1177 } else {
1178 // Servers always send a cert if the cipher is not anonymous (anon is
1179 // disabled by default), so use VERIFY_NONE and check the cert after the
1180 // handshake has completed.
1181 verify_mode = SSL_VERIFY_NONE;
1182 }
1183
1184 // Always allow a connection. We'll reject in javascript.
1185 SSL_set_verify(wrap->ssl_.get(), verify_mode, VerifyCallback);
1186 }
1187
EnableSessionCallbacks(const FunctionCallbackInfo<Value>& args)1188 void TLSWrap::EnableSessionCallbacks(const FunctionCallbackInfo<Value>& args) {
1189 TLSWrap* wrap;
1190 ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1191 CHECK_NOT_NULL(wrap->ssl_);
1192 wrap->enable_session_callbacks();
1193
1194 // Clients don't use the HelloParser.
1195 if (wrap->is_client())
1196 return;
1197
1198 NodeBIO::FromBIO(wrap->enc_in_)->set_initial(kMaxHelloLength);
1199 wrap->hello_parser_.Start(OnClientHello,
1200 OnClientHelloParseEnd,
1201 wrap);
1202 }
1203
EnableKeylogCallback(const FunctionCallbackInfo<Value>& args)1204 void TLSWrap::EnableKeylogCallback(const FunctionCallbackInfo<Value>& args) {
1205 TLSWrap* wrap;
1206 ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1207 CHECK(wrap->sc_);
1208 wrap->sc_->SetKeylogCallback(KeylogCallback);
1209 }
1210
1211 // Check required capabilities were not excluded from the OpenSSL build:
1212 // - OPENSSL_NO_SSL_TRACE excludes SSL_trace()
1213 // - OPENSSL_NO_STDIO excludes BIO_new_fp()
1214 // HAVE_SSL_TRACE is available on the internal tcp_wrap binding for the tests.
1215 #if defined(OPENSSL_NO_SSL_TRACE) || defined(OPENSSL_NO_STDIO)
1216 # define HAVE_SSL_TRACE 0
1217 #else
1218 # define HAVE_SSL_TRACE 1
1219 #endif
1220
EnableTrace(const FunctionCallbackInfo<Value>& args)1221 void TLSWrap::EnableTrace(const FunctionCallbackInfo<Value>& args) {
1222 TLSWrap* wrap;
1223 ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1224
1225 #if HAVE_SSL_TRACE
1226 if (wrap->ssl_) {
1227 wrap->bio_trace_.reset(BIO_new_fp(stderr, BIO_NOCLOSE | BIO_FP_TEXT));
1228 SSL_set_msg_callback(wrap->ssl_.get(), [](int write_p, int version, int
1229 content_type, const void* buf, size_t len, SSL* ssl, void* arg)
1230 -> void {
1231 // BIO_write(), etc., called by SSL_trace, may error. The error should
1232 // be ignored, trace is a "best effort", and its usually because stderr
1233 // is a non-blocking pipe, and its buffer has overflowed. Leaving errors
1234 // on the stack that can get picked up by later SSL_ calls causes
1235 // unwanted failures in SSL_ calls, so keep the error stack unchanged.
1236 MarkPopErrorOnReturn mark_pop_error_on_return;
1237 SSL_trace(write_p, version, content_type, buf, len, ssl, arg);
1238 });
1239 SSL_set_msg_callback_arg(wrap->ssl_.get(), wrap->bio_trace_.get());
1240 }
1241 #endif
1242 }
1243
DestroySSL(const FunctionCallbackInfo<Value>& args)1244 void TLSWrap::DestroySSL(const FunctionCallbackInfo<Value>& args) {
1245 TLSWrap* wrap;
1246 ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1247 wrap->Destroy();
1248 Debug(wrap, "DestroySSL() finished");
1249 }
1250
Destroy()1251 void TLSWrap::Destroy() {
1252 if (!ssl_)
1253 return;
1254
1255 // If there is a write happening, mark it as finished.
1256 write_callback_scheduled_ = true;
1257
1258 // And destroy
1259 InvokeQueued(UV_ECANCELED, "Canceled because of SSL destruction");
1260
1261 env()->isolate()->AdjustAmountOfExternalAllocatedMemory(-kExternalSize);
1262 ssl_.reset();
1263
1264 enc_in_ = nullptr;
1265 enc_out_ = nullptr;
1266
1267 if (underlying_stream() != nullptr)
1268 underlying_stream()->RemoveStreamListener(this);
1269
1270 sc_.reset();
1271 }
1272
EnableCertCb(const FunctionCallbackInfo<Value>& args)1273 void TLSWrap::EnableCertCb(const FunctionCallbackInfo<Value>& args) {
1274 TLSWrap* wrap;
1275 ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1276 wrap->WaitForCertCb(OnClientHelloParseEnd, wrap);
1277 }
1278
WaitForCertCb(CertCb cb, void* arg)1279 void TLSWrap::WaitForCertCb(CertCb cb, void* arg) {
1280 cert_cb_ = cb;
1281 cert_cb_arg_ = arg;
1282 }
1283
OnClientHelloParseEnd(void* arg)1284 void TLSWrap::OnClientHelloParseEnd(void* arg) {
1285 TLSWrap* c = static_cast<TLSWrap*>(arg);
1286 Debug(c, "OnClientHelloParseEnd()");
1287 c->Cycle();
1288 }
1289
EnableALPNCb(const FunctionCallbackInfo<Value>& args)1290 void TLSWrap::EnableALPNCb(const FunctionCallbackInfo<Value>& args) {
1291 TLSWrap* wrap;
1292 ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1293 wrap->alpn_callback_enabled_ = true;
1294
1295 SSL* ssl = wrap->ssl_.get();
1296 SSL_CTX* ssl_ctx = SSL_get_SSL_CTX(ssl);
1297 SSL_CTX_set_alpn_select_cb(ssl_ctx, SelectALPNCallback, nullptr);
1298 }
1299
GetServername(const FunctionCallbackInfo<Value>& args)1300 void TLSWrap::GetServername(const FunctionCallbackInfo<Value>& args) {
1301 Environment* env = Environment::GetCurrent(args);
1302
1303 TLSWrap* wrap;
1304 ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1305
1306 CHECK_NOT_NULL(wrap->ssl_);
1307
1308 const char* servername = GetServerName(wrap->ssl_.get());
1309 if (servername != nullptr) {
1310 args.GetReturnValue().Set(OneByteString(env->isolate(), servername));
1311 } else {
1312 args.GetReturnValue().Set(false);
1313 }
1314 }
1315
SetServername(const FunctionCallbackInfo<Value>& args)1316 void TLSWrap::SetServername(const FunctionCallbackInfo<Value>& args) {
1317 Environment* env = Environment::GetCurrent(args);
1318
1319 TLSWrap* wrap;
1320 ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1321
1322 CHECK_EQ(args.Length(), 1);
1323 CHECK(args[0]->IsString());
1324 CHECK(!wrap->started_);
1325 CHECK(wrap->is_client());
1326
1327 CHECK(wrap->ssl_);
1328
1329 Utf8Value servername(env->isolate(), args[0].As<String>());
1330 SSL_set_tlsext_host_name(wrap->ssl_.get(), *servername);
1331 }
1332
SelectSNIContextCallback(SSL* s, int* ad, void* arg)1333 int TLSWrap::SelectSNIContextCallback(SSL* s, int* ad, void* arg) {
1334 TLSWrap* p = static_cast<TLSWrap*>(SSL_get_app_data(s));
1335 Environment* env = p->env();
1336 HandleScope handle_scope(env->isolate());
1337 Context::Scope context_scope(env->context());
1338
1339 const char* servername = GetServerName(s);
1340 if (!Set(env, p->GetOwner(), env->servername_string(), servername))
1341 return SSL_TLSEXT_ERR_NOACK;
1342
1343 Local<Value> ctx = p->object()->Get(env->context(), env->sni_context_string())
1344 .FromMaybe(Local<Value>());
1345
1346 if (UNLIKELY(ctx.IsEmpty()) || !ctx->IsObject())
1347 return SSL_TLSEXT_ERR_NOACK;
1348
1349 if (!env->secure_context_constructor_template()->HasInstance(ctx)) {
1350 // Failure: incorrect SNI context object
1351 Local<Value> err = Exception::TypeError(env->sni_context_err_string());
1352 p->MakeCallback(env->onerror_string(), 1, &err);
1353 return SSL_TLSEXT_ERR_NOACK;
1354 }
1355
1356 SecureContext* sc = Unwrap<SecureContext>(ctx.As<Object>());
1357 CHECK_NOT_NULL(sc);
1358 p->sni_context_ = BaseObjectPtr<SecureContext>(sc);
1359
1360 ConfigureSecureContext(sc);
1361 CHECK_EQ(SSL_set_SSL_CTX(p->ssl_.get(), sc->ctx().get()), sc->ctx().get());
1362 p->SetCACerts(sc);
1363
1364 return SSL_TLSEXT_ERR_OK;
1365 }
1366
SetCACerts(SecureContext* sc)1367 int TLSWrap::SetCACerts(SecureContext* sc) {
1368 int err = SSL_set1_verify_cert_store(ssl_.get(),
1369 SSL_CTX_get_cert_store(sc->ctx().get()));
1370 if (err != 1)
1371 return err;
1372
1373 STACK_OF(X509_NAME)* list =
1374 SSL_dup_CA_list(SSL_CTX_get_client_CA_list(sc->ctx().get()));
1375
1376 // NOTE: `SSL_set_client_CA_list` takes the ownership of `list`
1377 SSL_set_client_CA_list(ssl_.get(), list);
1378 return 1;
1379 }
1380
1381 #ifndef OPENSSL_NO_PSK
1382
SetPskIdentityHint(const FunctionCallbackInfo<Value>& args)1383 void TLSWrap::SetPskIdentityHint(const FunctionCallbackInfo<Value>& args) {
1384 TLSWrap* p;
1385 ASSIGN_OR_RETURN_UNWRAP(&p, args.Holder());
1386 CHECK_NOT_NULL(p->ssl_);
1387
1388 Environment* env = p->env();
1389 Isolate* isolate = env->isolate();
1390
1391 CHECK(args[0]->IsString());
1392 Utf8Value hint(isolate, args[0].As<String>());
1393
1394 if (!SSL_use_psk_identity_hint(p->ssl_.get(), *hint)) {
1395 Local<Value> err = node::ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED(isolate);
1396 p->MakeCallback(env->onerror_string(), 1, &err);
1397 }
1398 }
1399
EnablePskCallback(const FunctionCallbackInfo<Value>& args)1400 void TLSWrap::EnablePskCallback(const FunctionCallbackInfo<Value>& args) {
1401 TLSWrap* wrap;
1402 ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1403 CHECK_NOT_NULL(wrap->ssl_);
1404
1405 SSL_set_psk_server_callback(wrap->ssl_.get(), PskServerCallback);
1406 SSL_set_psk_client_callback(wrap->ssl_.get(), PskClientCallback);
1407 }
1408
PskServerCallback( SSL* s, const char* identity, unsigned char* psk, unsigned int max_psk_len)1409 unsigned int TLSWrap::PskServerCallback(
1410 SSL* s,
1411 const char* identity,
1412 unsigned char* psk,
1413 unsigned int max_psk_len) {
1414 TLSWrap* p = static_cast<TLSWrap*>(SSL_get_app_data(s));
1415
1416 Environment* env = p->env();
1417 HandleScope scope(env->isolate());
1418
1419 Local<String> identity_str =
1420 String::NewFromUtf8(env->isolate(), identity).FromMaybe(Local<String>());
1421 if (UNLIKELY(identity_str.IsEmpty()))
1422 return 0;
1423
1424 // Make sure there are no utf8 replacement symbols.
1425 Utf8Value identity_utf8(env->isolate(), identity_str);
1426 if (identity_utf8 != identity) return 0;
1427
1428 Local<Value> argv[] = {
1429 identity_str,
1430 Integer::NewFromUnsigned(env->isolate(), max_psk_len)
1431 };
1432
1433 Local<Value> psk_val =
1434 p->MakeCallback(env->onpskexchange_symbol(), arraysize(argv), argv)
1435 .FromMaybe(Local<Value>());
1436 if (UNLIKELY(psk_val.IsEmpty()) || !psk_val->IsArrayBufferView())
1437 return 0;
1438
1439 ArrayBufferViewContents<char> psk_buf(psk_val);
1440
1441 if (psk_buf.length() > max_psk_len)
1442 return 0;
1443
1444 memcpy(psk, psk_buf.data(), psk_buf.length());
1445 return psk_buf.length();
1446 }
1447
PskClientCallback( SSL* s, const char* hint, char* identity, unsigned int max_identity_len, unsigned char* psk, unsigned int max_psk_len)1448 unsigned int TLSWrap::PskClientCallback(
1449 SSL* s,
1450 const char* hint,
1451 char* identity,
1452 unsigned int max_identity_len,
1453 unsigned char* psk,
1454 unsigned int max_psk_len) {
1455 TLSWrap* p = static_cast<TLSWrap*>(SSL_get_app_data(s));
1456
1457 Environment* env = p->env();
1458 HandleScope scope(env->isolate());
1459
1460 Local<Value> argv[] = {
1461 Null(env->isolate()),
1462 Integer::NewFromUnsigned(env->isolate(), max_psk_len),
1463 Integer::NewFromUnsigned(env->isolate(), max_identity_len)
1464 };
1465
1466 if (hint != nullptr) {
1467 Local<String> local_hint =
1468 String::NewFromUtf8(env->isolate(), hint).FromMaybe(Local<String>());
1469 if (UNLIKELY(local_hint.IsEmpty()))
1470 return 0;
1471
1472 argv[0] = local_hint;
1473 }
1474
1475 Local<Value> ret =
1476 p->MakeCallback(env->onpskexchange_symbol(), arraysize(argv), argv)
1477 .FromMaybe(Local<Value>());
1478 if (UNLIKELY(ret.IsEmpty()) || !ret->IsObject())
1479 return 0;
1480
1481 Local<Object> obj = ret.As<Object>();
1482
1483 Local<Value> psk_val = obj->Get(env->context(), env->psk_string())
1484 .FromMaybe(Local<Value>());
1485 if (UNLIKELY(psk_val.IsEmpty()) || !psk_val->IsArrayBufferView())
1486 return 0;
1487
1488 ArrayBufferViewContents<char> psk_buf(psk_val);
1489 if (psk_buf.length() > max_psk_len)
1490 return 0;
1491
1492 Local<Value> identity_val = obj->Get(env->context(), env->identity_string())
1493 .FromMaybe(Local<Value>());
1494 if (UNLIKELY(identity_val.IsEmpty()) || !identity_val->IsString())
1495 return 0;
1496
1497 Utf8Value identity_buf(env->isolate(), identity_val);
1498
1499 if (identity_buf.length() > max_identity_len)
1500 return 0;
1501
1502 memcpy(identity, *identity_buf, identity_buf.length());
1503 memcpy(psk, psk_buf.data(), psk_buf.length());
1504
1505 return psk_buf.length();
1506 }
1507
1508 #endif // ifndef OPENSSL_NO_PSK
1509
GetWriteQueueSize(const FunctionCallbackInfo<Value>& info)1510 void TLSWrap::GetWriteQueueSize(const FunctionCallbackInfo<Value>& info) {
1511 TLSWrap* wrap;
1512 ASSIGN_OR_RETURN_UNWRAP(&wrap, info.This());
1513
1514 if (!wrap->ssl_)
1515 return info.GetReturnValue().Set(0);
1516
1517 uint32_t write_queue_size = BIO_pending(wrap->enc_out_);
1518 info.GetReturnValue().Set(write_queue_size);
1519 }
1520
MemoryInfo(MemoryTracker* tracker) const1521 void TLSWrap::MemoryInfo(MemoryTracker* tracker) const {
1522 tracker->TrackField("ocsp_response", ocsp_response_);
1523 tracker->TrackField("sni_context", sni_context_);
1524 tracker->TrackField("error", error_);
1525 if (pending_cleartext_input_)
1526 tracker->TrackField("pending_cleartext_input", pending_cleartext_input_);
1527 if (enc_in_ != nullptr)
1528 tracker->TrackField("enc_in", NodeBIO::FromBIO(enc_in_));
1529 if (enc_out_ != nullptr)
1530 tracker->TrackField("enc_out", NodeBIO::FromBIO(enc_out_));
1531 }
1532
CertCbDone(const FunctionCallbackInfo<Value>& args)1533 void TLSWrap::CertCbDone(const FunctionCallbackInfo<Value>& args) {
1534 Environment* env = Environment::GetCurrent(args);
1535 TLSWrap* w;
1536 ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1537
1538 CHECK(w->is_waiting_cert_cb() && w->cert_cb_running_);
1539
1540 Local<Object> object = w->object();
1541 Local<Value> ctx = object->Get(env->context(), env->sni_context_string())
1542 .FromMaybe(Local<Value>());
1543 if (UNLIKELY(ctx.IsEmpty()))
1544 return;
1545
1546 Local<FunctionTemplate> cons = env->secure_context_constructor_template();
1547 if (cons->HasInstance(ctx)) {
1548 SecureContext* sc = Unwrap<SecureContext>(ctx.As<Object>());
1549 CHECK_NOT_NULL(sc);
1550 // Store the SNI context for later use.
1551 w->sni_context_ = BaseObjectPtr<SecureContext>(sc);
1552
1553 if (UseSNIContext(w->ssl_, w->sni_context_) && !w->SetCACerts(sc)) {
1554 // Not clear why sometimes we throw error, and sometimes we call
1555 // onerror(). Both cause .destroy(), but onerror does a bit more.
1556 unsigned long err = ERR_get_error(); // NOLINT(runtime/int)
1557 return ThrowCryptoError(env, err, "CertCbDone");
1558 }
1559 } else if (ctx->IsObject()) {
1560 // Failure: incorrect SNI context object
1561 Local<Value> err = Exception::TypeError(env->sni_context_err_string());
1562 w->MakeCallback(env->onerror_string(), 1, &err);
1563 return;
1564 }
1565
1566 CertCb cb;
1567 void* arg;
1568
1569 cb = w->cert_cb_;
1570 arg = w->cert_cb_arg_;
1571
1572 w->cert_cb_running_ = false;
1573 w->cert_cb_ = nullptr;
1574 w->cert_cb_arg_ = nullptr;
1575
1576 cb(arg);
1577 }
1578
SetALPNProtocols(const FunctionCallbackInfo<Value>& args)1579 void TLSWrap::SetALPNProtocols(const FunctionCallbackInfo<Value>& args) {
1580 TLSWrap* w;
1581 ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1582 Environment* env = w->env();
1583 if (args.Length() < 1 || !Buffer::HasInstance(args[0]))
1584 return env->ThrowTypeError("Must give a Buffer as first argument");
1585
1586 ArrayBufferViewContents<uint8_t> protos(args[0].As<ArrayBufferView>());
1587 SSL* ssl = w->ssl_.get();
1588 if (w->is_client()) {
1589 CHECK_EQ(0, SSL_set_alpn_protos(ssl, protos.data(), protos.length()));
1590 } else {
1591 w->alpn_protos_ = std::vector<unsigned char>(
1592 protos.data(), protos.data() + protos.length());
1593 SSL_CTX* ssl_ctx = SSL_get_SSL_CTX(ssl);
1594 SSL_CTX_set_alpn_select_cb(ssl_ctx, SelectALPNCallback, nullptr);
1595 }
1596 }
1597
GetPeerCertificate(const FunctionCallbackInfo<Value>& args)1598 void TLSWrap::GetPeerCertificate(const FunctionCallbackInfo<Value>& args) {
1599 TLSWrap* w;
1600 ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1601 Environment* env = w->env();
1602
1603 bool abbreviated = args.Length() < 1 || !args[0]->IsTrue();
1604
1605 Local<Value> ret;
1606 if (GetPeerCert(
1607 env,
1608 w->ssl_,
1609 abbreviated,
1610 w->is_server()).ToLocal(&ret))
1611 args.GetReturnValue().Set(ret);
1612 }
1613
GetPeerX509Certificate(const FunctionCallbackInfo<Value>& args)1614 void TLSWrap::GetPeerX509Certificate(const FunctionCallbackInfo<Value>& args) {
1615 TLSWrap* w;
1616 ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1617 Environment* env = w->env();
1618
1619 X509Certificate::GetPeerCertificateFlag flag = w->is_server()
1620 ? X509Certificate::GetPeerCertificateFlag::SERVER
1621 : X509Certificate::GetPeerCertificateFlag::NONE;
1622
1623 Local<Value> ret;
1624 if (X509Certificate::GetPeerCert(env, w->ssl_, flag).ToLocal(&ret))
1625 args.GetReturnValue().Set(ret);
1626 }
1627
GetCertificate(const FunctionCallbackInfo<Value>& args)1628 void TLSWrap::GetCertificate(const FunctionCallbackInfo<Value>& args) {
1629 TLSWrap* w;
1630 ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1631 Environment* env = w->env();
1632
1633 Local<Value> ret;
1634 if (GetCert(env, w->ssl_).ToLocal(&ret))
1635 args.GetReturnValue().Set(ret);
1636 }
1637
GetX509Certificate(const FunctionCallbackInfo<Value>& args)1638 void TLSWrap::GetX509Certificate(const FunctionCallbackInfo<Value>& args) {
1639 TLSWrap* w;
1640 ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1641 Environment* env = w->env();
1642 Local<Value> ret;
1643 if (X509Certificate::GetCert(env, w->ssl_).ToLocal(&ret))
1644 args.GetReturnValue().Set(ret);
1645 }
1646
GetFinished(const FunctionCallbackInfo<Value>& args)1647 void TLSWrap::GetFinished(const FunctionCallbackInfo<Value>& args) {
1648 Environment* env = Environment::GetCurrent(args);
1649
1650 TLSWrap* w;
1651 ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1652
1653 // We cannot just pass nullptr to SSL_get_finished()
1654 // because it would further be propagated to memcpy(),
1655 // where the standard requirements as described in ISO/IEC 9899:2011
1656 // sections 7.21.2.1, 7.21.1.2, and 7.1.4, would be violated.
1657 // Thus, we use a dummy byte.
1658 char dummy[1];
1659 size_t len = SSL_get_finished(w->ssl_.get(), dummy, sizeof dummy);
1660 if (len == 0)
1661 return;
1662
1663 std::unique_ptr<BackingStore> bs;
1664 {
1665 NoArrayBufferZeroFillScope no_zero_fill_scope(env->isolate_data());
1666 bs = ArrayBuffer::NewBackingStore(env->isolate(), len);
1667 }
1668
1669 CHECK_EQ(bs->ByteLength(),
1670 SSL_get_finished(w->ssl_.get(), bs->Data(), bs->ByteLength()));
1671
1672 Local<ArrayBuffer> ab = ArrayBuffer::New(env->isolate(), std::move(bs));
1673 Local<Value> buffer;
1674 if (!Buffer::New(env, ab, 0, ab->ByteLength()).ToLocal(&buffer)) return;
1675 args.GetReturnValue().Set(buffer);
1676 }
1677
GetPeerFinished(const FunctionCallbackInfo<Value>& args)1678 void TLSWrap::GetPeerFinished(const FunctionCallbackInfo<Value>& args) {
1679 Environment* env = Environment::GetCurrent(args);
1680
1681 TLSWrap* w;
1682 ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1683
1684 // We cannot just pass nullptr to SSL_get_peer_finished()
1685 // because it would further be propagated to memcpy(),
1686 // where the standard requirements as described in ISO/IEC 9899:2011
1687 // sections 7.21.2.1, 7.21.1.2, and 7.1.4, would be violated.
1688 // Thus, we use a dummy byte.
1689 char dummy[1];
1690 size_t len = SSL_get_peer_finished(w->ssl_.get(), dummy, sizeof dummy);
1691 if (len == 0)
1692 return;
1693
1694 std::unique_ptr<BackingStore> bs;
1695 {
1696 NoArrayBufferZeroFillScope no_zero_fill_scope(env->isolate_data());
1697 bs = ArrayBuffer::NewBackingStore(env->isolate(), len);
1698 }
1699
1700 CHECK_EQ(bs->ByteLength(),
1701 SSL_get_peer_finished(w->ssl_.get(), bs->Data(), bs->ByteLength()));
1702
1703 Local<ArrayBuffer> ab = ArrayBuffer::New(env->isolate(), std::move(bs));
1704 Local<Value> buffer;
1705 if (!Buffer::New(env, ab, 0, ab->ByteLength()).ToLocal(&buffer)) return;
1706 args.GetReturnValue().Set(buffer);
1707 }
1708
GetSession(const FunctionCallbackInfo<Value>& args)1709 void TLSWrap::GetSession(const FunctionCallbackInfo<Value>& args) {
1710 Environment* env = Environment::GetCurrent(args);
1711
1712 TLSWrap* w;
1713 ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1714
1715 SSL_SESSION* sess = SSL_get_session(w->ssl_.get());
1716 if (sess == nullptr)
1717 return;
1718
1719 int slen = i2d_SSL_SESSION(sess, nullptr);
1720 if (slen <= 0)
1721 return; // Invalid or malformed session.
1722
1723 std::unique_ptr<BackingStore> bs;
1724 {
1725 NoArrayBufferZeroFillScope no_zero_fill_scope(env->isolate_data());
1726 bs = ArrayBuffer::NewBackingStore(env->isolate(), slen);
1727 }
1728
1729 unsigned char* p = static_cast<unsigned char*>(bs->Data());
1730 CHECK_LT(0, i2d_SSL_SESSION(sess, &p));
1731
1732 Local<ArrayBuffer> ab = ArrayBuffer::New(env->isolate(), std::move(bs));
1733 Local<Value> buffer;
1734 if (!Buffer::New(env, ab, 0, ab->ByteLength()).ToLocal(&buffer)) return;
1735 args.GetReturnValue().Set(buffer);
1736 }
1737
SetSession(const FunctionCallbackInfo<Value>& args)1738 void TLSWrap::SetSession(const FunctionCallbackInfo<Value>& args) {
1739 Environment* env = Environment::GetCurrent(args);
1740
1741 TLSWrap* w;
1742 ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1743
1744 if (args.Length() < 1)
1745 return THROW_ERR_MISSING_ARGS(env, "Session argument is mandatory");
1746
1747 THROW_AND_RETURN_IF_NOT_BUFFER(env, args[0], "Session");
1748 ArrayBufferViewContents<unsigned char> sbuf(args[0]);
1749 SSLSessionPointer sess = GetTLSSession(sbuf.data(), sbuf.length());
1750 if (sess == nullptr)
1751 return; // TODO(tniessen): figure out error handling
1752
1753 if (!SetTLSSession(w->ssl_, sess))
1754 return env->ThrowError("SSL_set_session error");
1755 }
1756
IsSessionReused(const FunctionCallbackInfo<Value>& args)1757 void TLSWrap::IsSessionReused(const FunctionCallbackInfo<Value>& args) {
1758 TLSWrap* w;
1759 ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1760 bool yes = SSL_session_reused(w->ssl_.get());
1761 args.GetReturnValue().Set(yes);
1762 }
1763
VerifyError(const FunctionCallbackInfo<Value>& args)1764 void TLSWrap::VerifyError(const FunctionCallbackInfo<Value>& args) {
1765 Environment* env = Environment::GetCurrent(args);
1766 TLSWrap* w;
1767 ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1768
1769 // XXX(bnoordhuis) The UNABLE_TO_GET_ISSUER_CERT error when there is no
1770 // peer certificate is questionable but it's compatible with what was
1771 // here before.
1772 long x509_verify_error = // NOLINT(runtime/int)
1773 VerifyPeerCertificate(
1774 w->ssl_,
1775 X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT);
1776
1777 if (x509_verify_error == X509_V_OK)
1778 return args.GetReturnValue().SetNull();
1779
1780 const char* reason = X509_verify_cert_error_string(x509_verify_error);
1781 const char* code = X509ErrorCode(x509_verify_error);
1782
1783 Local<Object> error =
1784 Exception::Error(OneByteString(env->isolate(), reason))
1785 ->ToObject(env->isolate()->GetCurrentContext())
1786 .FromMaybe(Local<Object>());
1787
1788 if (Set(env, error, env->code_string(), code))
1789 args.GetReturnValue().Set(error);
1790 }
1791
GetCipher(const FunctionCallbackInfo<Value>& args)1792 void TLSWrap::GetCipher(const FunctionCallbackInfo<Value>& args) {
1793 Environment* env = Environment::GetCurrent(args);
1794 TLSWrap* w;
1795 ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1796 args.GetReturnValue().Set(
1797 GetCipherInfo(env, w->ssl_).FromMaybe(Local<Object>()));
1798 }
1799
LoadSession(const FunctionCallbackInfo<Value>& args)1800 void TLSWrap::LoadSession(const FunctionCallbackInfo<Value>& args) {
1801 TLSWrap* w;
1802 ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1803
1804 // TODO(@sam-github) check arg length and types in js, and CHECK in c++
1805 if (args.Length() >= 1 && Buffer::HasInstance(args[0])) {
1806 ArrayBufferViewContents<unsigned char> sbuf(args[0]);
1807
1808 const unsigned char* p = sbuf.data();
1809 SSL_SESSION* sess = d2i_SSL_SESSION(nullptr, &p, sbuf.length());
1810
1811 // Setup next session and move hello to the BIO buffer
1812 w->next_sess_.reset(sess);
1813 }
1814 }
1815
GetSharedSigalgs(const FunctionCallbackInfo<Value>& args)1816 void TLSWrap::GetSharedSigalgs(const FunctionCallbackInfo<Value>& args) {
1817 Environment* env = Environment::GetCurrent(args);
1818 TLSWrap* w;
1819 ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1820
1821 SSL* ssl = w->ssl_.get();
1822 int nsig = SSL_get_shared_sigalgs(ssl, 0, nullptr, nullptr, nullptr, nullptr,
1823 nullptr);
1824 MaybeStackBuffer<Local<Value>, 16> ret_arr(nsig);
1825
1826 for (int i = 0; i < nsig; i++) {
1827 int hash_nid;
1828 int sign_nid;
1829 std::string sig_with_md;
1830
1831 SSL_get_shared_sigalgs(ssl, i, &sign_nid, &hash_nid, nullptr, nullptr,
1832 nullptr);
1833
1834 switch (sign_nid) {
1835 case EVP_PKEY_RSA:
1836 sig_with_md = "RSA+";
1837 break;
1838
1839 case EVP_PKEY_RSA_PSS:
1840 sig_with_md = "RSA-PSS+";
1841 break;
1842
1843 case EVP_PKEY_DSA:
1844 sig_with_md = "DSA+";
1845 break;
1846
1847 case EVP_PKEY_EC:
1848 sig_with_md = "ECDSA+";
1849 break;
1850
1851 case NID_ED25519:
1852 sig_with_md = "Ed25519+";
1853 break;
1854
1855 case NID_ED448:
1856 sig_with_md = "Ed448+";
1857 break;
1858 #ifndef OPENSSL_NO_GOST
1859 case NID_id_GostR3410_2001:
1860 sig_with_md = "gost2001+";
1861 break;
1862
1863 case NID_id_GostR3410_2012_256:
1864 sig_with_md = "gost2012_256+";
1865 break;
1866
1867 case NID_id_GostR3410_2012_512:
1868 sig_with_md = "gost2012_512+";
1869 break;
1870 #endif // !OPENSSL_NO_GOST
1871 default:
1872 const char* sn = OBJ_nid2sn(sign_nid);
1873
1874 if (sn != nullptr) {
1875 sig_with_md = std::string(sn) + "+";
1876 } else {
1877 sig_with_md = "UNDEF+";
1878 }
1879 break;
1880 }
1881
1882 const char* sn_hash = OBJ_nid2sn(hash_nid);
1883 if (sn_hash != nullptr) {
1884 sig_with_md += std::string(sn_hash);
1885 } else {
1886 sig_with_md += "UNDEF";
1887 }
1888 ret_arr[i] = OneByteString(env->isolate(), sig_with_md.c_str());
1889 }
1890
1891 args.GetReturnValue().Set(
1892 Array::New(env->isolate(), ret_arr.out(), ret_arr.length()));
1893 }
1894
ExportKeyingMaterial(const FunctionCallbackInfo<Value>& args)1895 void TLSWrap::ExportKeyingMaterial(const FunctionCallbackInfo<Value>& args) {
1896 CHECK(args[0]->IsInt32());
1897 CHECK(args[1]->IsString());
1898
1899 Environment* env = Environment::GetCurrent(args);
1900 TLSWrap* w;
1901 ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1902
1903 uint32_t olen = args[0].As<Uint32>()->Value();
1904 Utf8Value label(env->isolate(), args[1]);
1905
1906 std::unique_ptr<BackingStore> bs;
1907 {
1908 NoArrayBufferZeroFillScope no_zero_fill_scope(env->isolate_data());
1909 bs = ArrayBuffer::NewBackingStore(env->isolate(), olen);
1910 }
1911
1912 ByteSource context;
1913 bool use_context = !args[2]->IsUndefined();
1914 if (use_context)
1915 context = ByteSource::FromBuffer(args[2]);
1916
1917 if (SSL_export_keying_material(
1918 w->ssl_.get(),
1919 static_cast<unsigned char*>(bs->Data()),
1920 olen,
1921 *label,
1922 label.length(),
1923 context.data<unsigned char>(),
1924 context.size(),
1925 use_context) != 1) {
1926 return ThrowCryptoError(
1927 env,
1928 ERR_get_error(),
1929 "SSL_export_keying_material");
1930 }
1931
1932 Local<ArrayBuffer> ab = ArrayBuffer::New(env->isolate(), std::move(bs));
1933 Local<Value> buffer;
1934 if (!Buffer::New(env, ab, 0, ab->ByteLength()).ToLocal(&buffer)) return;
1935 args.GetReturnValue().Set(buffer);
1936 }
1937
EndParser(const FunctionCallbackInfo<Value>& args)1938 void TLSWrap::EndParser(const FunctionCallbackInfo<Value>& args) {
1939 TLSWrap* w;
1940 ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1941 w->hello_parser_.End();
1942 }
1943
Renegotiate(const FunctionCallbackInfo<Value>& args)1944 void TLSWrap::Renegotiate(const FunctionCallbackInfo<Value>& args) {
1945 TLSWrap* w;
1946 ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1947 ClearErrorOnReturn clear_error_on_return;
1948 if (SSL_renegotiate(w->ssl_.get()) != 1)
1949 return ThrowCryptoError(w->env(), ERR_get_error());
1950 }
1951
GetTLSTicket(const FunctionCallbackInfo<Value>& args)1952 void TLSWrap::GetTLSTicket(const FunctionCallbackInfo<Value>& args) {
1953 TLSWrap* w;
1954 ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1955 Environment* env = w->env();
1956
1957 SSL_SESSION* sess = SSL_get_session(w->ssl_.get());
1958 if (sess == nullptr)
1959 return;
1960
1961 const unsigned char* ticket;
1962 size_t length;
1963 SSL_SESSION_get0_ticket(sess, &ticket, &length);
1964
1965 if (ticket != nullptr) {
1966 args.GetReturnValue().Set(
1967 Buffer::Copy(env, reinterpret_cast<const char*>(ticket), length)
1968 .FromMaybe(Local<Object>()));
1969 }
1970 }
1971
NewSessionDone(const FunctionCallbackInfo<Value>& args)1972 void TLSWrap::NewSessionDone(const FunctionCallbackInfo<Value>& args) {
1973 TLSWrap* w;
1974 ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1975 w->awaiting_new_session_ = false;
1976 w->NewSessionDoneCb();
1977 }
1978
SetOCSPResponse(const FunctionCallbackInfo<Value>& args)1979 void TLSWrap::SetOCSPResponse(const FunctionCallbackInfo<Value>& args) {
1980 TLSWrap* w;
1981 ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1982 Environment* env = w->env();
1983
1984 if (args.Length() < 1)
1985 return THROW_ERR_MISSING_ARGS(env, "OCSP response argument is mandatory");
1986
1987 THROW_AND_RETURN_IF_NOT_BUFFER(env, args[0], "OCSP response");
1988
1989 w->ocsp_response_.Reset(args.GetIsolate(), args[0].As<ArrayBufferView>());
1990 }
1991
RequestOCSP(const FunctionCallbackInfo<Value>& args)1992 void TLSWrap::RequestOCSP(const FunctionCallbackInfo<Value>& args) {
1993 TLSWrap* w;
1994 ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1995
1996 SSL_set_tlsext_status_type(w->ssl_.get(), TLSEXT_STATUSTYPE_ocsp);
1997 }
1998
GetEphemeralKeyInfo(const FunctionCallbackInfo<Value>& args)1999 void TLSWrap::GetEphemeralKeyInfo(const FunctionCallbackInfo<Value>& args) {
2000 TLSWrap* w;
2001 ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2002 Environment* env = Environment::GetCurrent(args);
2003
2004 CHECK(w->ssl_);
2005
2006 // tmp key is available on only client
2007 if (w->is_server())
2008 return args.GetReturnValue().SetNull();
2009
2010 args.GetReturnValue().Set(GetEphemeralKey(env, w->ssl_)
2011 .FromMaybe(Local<Value>()));
2012
2013 // TODO(@sam-github) semver-major: else return ThrowCryptoError(env,
2014 // ERR_get_error())
2015 }
2016
GetProtocol(const FunctionCallbackInfo<Value>& args)2017 void TLSWrap::GetProtocol(const FunctionCallbackInfo<Value>& args) {
2018 Environment* env = Environment::GetCurrent(args);
2019 TLSWrap* w;
2020 ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2021 args.GetReturnValue().Set(
2022 OneByteString(env->isolate(), SSL_get_version(w->ssl_.get())));
2023 }
2024
GetALPNNegotiatedProto(const FunctionCallbackInfo<Value>& args)2025 void TLSWrap::GetALPNNegotiatedProto(const FunctionCallbackInfo<Value>& args) {
2026 Environment* env = Environment::GetCurrent(args);
2027 TLSWrap* w;
2028 ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2029
2030 const unsigned char* alpn_proto;
2031 unsigned int alpn_proto_len;
2032
2033 SSL_get0_alpn_selected(w->ssl_.get(), &alpn_proto, &alpn_proto_len);
2034
2035 Local<Value> result;
2036 if (alpn_proto_len == 0) {
2037 result = False(env->isolate());
2038 } else if (alpn_proto_len == sizeof("h2") - 1 &&
2039 0 == memcmp(alpn_proto, "h2", sizeof("h2") - 1)) {
2040 result = env->h2_string();
2041 } else if (alpn_proto_len == sizeof("http/1.1") - 1 &&
2042 0 == memcmp(alpn_proto, "http/1.1", sizeof("http/1.1") - 1)) {
2043 result = env->http_1_1_string();
2044 } else {
2045 result = OneByteString(env->isolate(), alpn_proto, alpn_proto_len);
2046 }
2047
2048 args.GetReturnValue().Set(result);
2049 }
2050
WritesIssuedByPrevListenerDone( const FunctionCallbackInfo<Value>& args)2051 void TLSWrap::WritesIssuedByPrevListenerDone(
2052 const FunctionCallbackInfo<Value>& args) {
2053 TLSWrap* w;
2054 ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2055
2056 Debug(w, "WritesIssuedByPrevListenerDone is called");
2057 w->has_active_write_issued_by_prev_listener_ = false;
2058 w->EncOut(); // resume all of our restrained writes
2059 }
2060
Cycle()2061 void TLSWrap::Cycle() {
2062 // Prevent recursion
2063 if (++cycle_depth_ > 1)
2064 return;
2065
2066 for (; cycle_depth_ > 0; cycle_depth_--) {
2067 ClearIn();
2068 ClearOut();
2069 // EncIn() doesn't exist, it happens via stream listener callbacks.
2070 EncOut();
2071 }
2072 }
2073
2074 #ifdef SSL_set_max_send_fragment
SetMaxSendFragment(const FunctionCallbackInfo<Value>& args)2075 void TLSWrap::SetMaxSendFragment(const FunctionCallbackInfo<Value>& args) {
2076 CHECK(args.Length() >= 1 && args[0]->IsNumber());
2077 Environment* env = Environment::GetCurrent(args);
2078 TLSWrap* w;
2079 ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
2080 int rv = SSL_set_max_send_fragment(
2081 w->ssl_.get(),
2082 args[0]->Int32Value(env->context()).FromJust());
2083 args.GetReturnValue().Set(rv);
2084 }
2085 #endif // SSL_set_max_send_fragment
2086
Initialize( Local<Object> target, Local<Value> unused, Local<Context> context, void* priv)2087 void TLSWrap::Initialize(
2088 Local<Object> target,
2089 Local<Value> unused,
2090 Local<Context> context,
2091 void* priv) {
2092 Environment* env = Environment::GetCurrent(context);
2093 Isolate* isolate = env->isolate();
2094
2095 SetMethod(context, target, "wrap", TLSWrap::Wrap);
2096
2097 NODE_DEFINE_CONSTANT(target, HAVE_SSL_TRACE);
2098
2099 Local<FunctionTemplate> t = BaseObject::MakeLazilyInitializedJSTemplate(env);
2100 Local<String> tlsWrapString =
2101 FIXED_ONE_BYTE_STRING(env->isolate(), "TLSWrap");
2102 t->SetClassName(tlsWrapString);
2103 t->InstanceTemplate()->SetInternalFieldCount(StreamBase::kInternalFieldCount);
2104
2105 Local<FunctionTemplate> get_write_queue_size =
2106 FunctionTemplate::New(env->isolate(),
2107 GetWriteQueueSize,
2108 Local<Value>(),
2109 Signature::New(env->isolate(), t));
2110 t->PrototypeTemplate()->SetAccessorProperty(
2111 env->write_queue_size_string(),
2112 get_write_queue_size,
2113 Local<FunctionTemplate>(),
2114 static_cast<PropertyAttribute>(ReadOnly | DontDelete));
2115
2116 t->Inherit(AsyncWrap::GetConstructorTemplate(env));
2117
2118 SetProtoMethod(isolate, t, "certCbDone", CertCbDone);
2119 SetProtoMethod(isolate, t, "destroySSL", DestroySSL);
2120 SetProtoMethod(isolate, t, "enableCertCb", EnableCertCb);
2121 SetProtoMethod(isolate, t, "enableALPNCb", EnableALPNCb);
2122 SetProtoMethod(isolate, t, "endParser", EndParser);
2123 SetProtoMethod(isolate, t, "enableKeylogCallback", EnableKeylogCallback);
2124 SetProtoMethod(isolate, t, "enableSessionCallbacks", EnableSessionCallbacks);
2125 SetProtoMethod(isolate, t, "enableTrace", EnableTrace);
2126 SetProtoMethod(isolate, t, "getServername", GetServername);
2127 SetProtoMethod(isolate, t, "loadSession", LoadSession);
2128 SetProtoMethod(isolate, t, "newSessionDone", NewSessionDone);
2129 SetProtoMethod(isolate, t, "receive", Receive);
2130 SetProtoMethod(isolate, t, "renegotiate", Renegotiate);
2131 SetProtoMethod(isolate, t, "requestOCSP", RequestOCSP);
2132 SetProtoMethod(isolate, t, "setALPNProtocols", SetALPNProtocols);
2133 SetProtoMethod(isolate, t, "setOCSPResponse", SetOCSPResponse);
2134 SetProtoMethod(isolate, t, "setServername", SetServername);
2135 SetProtoMethod(isolate, t, "setSession", SetSession);
2136 SetProtoMethod(isolate, t, "setVerifyMode", SetVerifyMode);
2137 SetProtoMethod(isolate, t, "start", Start);
2138 SetProtoMethod(isolate,
2139 t,
2140 "writesIssuedByPrevListenerDone",
2141 WritesIssuedByPrevListenerDone);
2142
2143 SetProtoMethodNoSideEffect(
2144 isolate, t, "exportKeyingMaterial", ExportKeyingMaterial);
2145 SetProtoMethodNoSideEffect(isolate, t, "isSessionReused", IsSessionReused);
2146 SetProtoMethodNoSideEffect(
2147 isolate, t, "getALPNNegotiatedProtocol", GetALPNNegotiatedProto);
2148 SetProtoMethodNoSideEffect(isolate, t, "getCertificate", GetCertificate);
2149 SetProtoMethodNoSideEffect(
2150 isolate, t, "getX509Certificate", GetX509Certificate);
2151 SetProtoMethodNoSideEffect(isolate, t, "getCipher", GetCipher);
2152 SetProtoMethodNoSideEffect(
2153 isolate, t, "getEphemeralKeyInfo", GetEphemeralKeyInfo);
2154 SetProtoMethodNoSideEffect(isolate, t, "getFinished", GetFinished);
2155 SetProtoMethodNoSideEffect(
2156 isolate, t, "getPeerCertificate", GetPeerCertificate);
2157 SetProtoMethodNoSideEffect(
2158 isolate, t, "getPeerX509Certificate", GetPeerX509Certificate);
2159 SetProtoMethodNoSideEffect(isolate, t, "getPeerFinished", GetPeerFinished);
2160 SetProtoMethodNoSideEffect(isolate, t, "getProtocol", GetProtocol);
2161 SetProtoMethodNoSideEffect(isolate, t, "getSession", GetSession);
2162 SetProtoMethodNoSideEffect(isolate, t, "getSharedSigalgs", GetSharedSigalgs);
2163 SetProtoMethodNoSideEffect(isolate, t, "getTLSTicket", GetTLSTicket);
2164 SetProtoMethodNoSideEffect(isolate, t, "verifyError", VerifyError);
2165
2166 #ifdef SSL_set_max_send_fragment
2167 SetProtoMethod(isolate, t, "setMaxSendFragment", SetMaxSendFragment);
2168 #endif // SSL_set_max_send_fragment
2169
2170 #ifndef OPENSSL_NO_PSK
2171 SetProtoMethod(isolate, t, "enablePskCallback", EnablePskCallback);
2172 SetProtoMethod(isolate, t, "setPskIdentityHint", SetPskIdentityHint);
2173 #endif // !OPENSSL_NO_PSK
2174
2175 StreamBase::AddMethods(env, t);
2176
2177 Local<Function> fn = t->GetFunction(env->context()).ToLocalChecked();
2178
2179 env->set_tls_wrap_constructor_function(fn);
2180
2181 target->Set(env->context(), tlsWrapString, fn).Check();
2182 }
2183
RegisterExternalReferences(ExternalReferenceRegistry* registry)2184 void TLSWrap::RegisterExternalReferences(ExternalReferenceRegistry* registry) {
2185 registry->Register(TLSWrap::Wrap);
2186 registry->Register(GetWriteQueueSize);
2187
2188 registry->Register(CertCbDone);
2189 registry->Register(DestroySSL);
2190 registry->Register(EnableCertCb);
2191 registry->Register(EnableALPNCb);
2192 registry->Register(EndParser);
2193 registry->Register(EnableKeylogCallback);
2194 registry->Register(EnableSessionCallbacks);
2195 registry->Register(EnableTrace);
2196 registry->Register(GetServername);
2197 registry->Register(LoadSession);
2198 registry->Register(NewSessionDone);
2199 registry->Register(Receive);
2200 registry->Register(Renegotiate);
2201 registry->Register(RequestOCSP);
2202 registry->Register(SetALPNProtocols);
2203 registry->Register(SetOCSPResponse);
2204 registry->Register(SetServername);
2205 registry->Register(SetSession);
2206 registry->Register(SetVerifyMode);
2207 registry->Register(Start);
2208 registry->Register(ExportKeyingMaterial);
2209 registry->Register(IsSessionReused);
2210 registry->Register(GetALPNNegotiatedProto);
2211 registry->Register(GetCertificate);
2212 registry->Register(GetX509Certificate);
2213 registry->Register(GetCipher);
2214 registry->Register(GetEphemeralKeyInfo);
2215 registry->Register(GetFinished);
2216 registry->Register(GetPeerCertificate);
2217 registry->Register(GetPeerX509Certificate);
2218 registry->Register(GetPeerFinished);
2219 registry->Register(GetProtocol);
2220 registry->Register(GetSession);
2221 registry->Register(GetSharedSigalgs);
2222 registry->Register(GetTLSTicket);
2223 registry->Register(VerifyError);
2224 registry->Register(WritesIssuedByPrevListenerDone);
2225
2226 #ifdef SSL_set_max_send_fragment
2227 registry->Register(SetMaxSendFragment);
2228 #endif // SSL_set_max_send_fragment
2229
2230 #ifndef OPENSSL_NO_PSK
2231 registry->Register(EnablePskCallback);
2232 registry->Register(SetPskIdentityHint);
2233 #endif // !OPENSSL_NO_PSK
2234 }
2235
2236 } // namespace crypto
2237 } // namespace node
2238
2239 NODE_BINDING_CONTEXT_AWARE_INTERNAL(tls_wrap, node::crypto::TLSWrap::Initialize)
2240 NODE_BINDING_EXTERNAL_REFERENCE(
2241 tls_wrap, node::crypto::TLSWrap::RegisterExternalReferences)
2242