GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: crypto/crypto_tls.cc Lines: 1030 1120 92.0 %
Date: 2022-03-31 04:14:52 Branches: 440 672 65.5 %

Line Branch Exec Source
1
// Copyright Joyent, Inc. and other Node contributors.
2
//
3
// Permission is hereby granted, free of charge, to any person obtaining a
4
// copy of this software and associated documentation files (the
5
// "Software"), to deal in the Software without restriction, including
6
// without limitation the rights to use, copy, modify, merge, publish,
7
// distribute, sublicense, and/or sell copies of the Software, and to permit
8
// persons to whom the Software is furnished to do so, subject to the
9
// following conditions:
10
//
11
// The above copyright notice and this permission notice shall be included
12
// in all copies or substantial portions of the Software.
13
//
14
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20
// USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22
#include "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 "allocated_buffer-inl.h"
29
#include "async_wrap-inl.h"
30
#include "debug_utils-inl.h"
31
#include "memory_tracker-inl.h"
32
#include "node_buffer.h"
33
#include "node_errors.h"
34
#include "stream_base-inl.h"
35
#include "util-inl.h"
36
37
namespace node {
38
39
using v8::Array;
40
using v8::ArrayBuffer;
41
using v8::ArrayBufferView;
42
using v8::BackingStore;
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::True;
62
using v8::Uint32;
63
using v8::Value;
64
65
namespace crypto {
66
67
namespace {
68
54
SSL_SESSION* GetSessionCallback(
69
    SSL* s,
70
    const unsigned char* key,
71
    int len,
72
    int* copy) {
73
54
  TLSWrap* w = static_cast<TLSWrap*>(SSL_get_app_data(s));
74
54
  *copy = 0;
75
54
  return w->ReleaseSession();
76
}
77
78
20
void OnClientHello(
79
    void* arg,
80
    const ClientHelloParser::ClientHello& hello) {
81
20
  TLSWrap* w = static_cast<TLSWrap*>(arg);
82
20
  Environment* env = w->env();
83
20
  HandleScope handle_scope(env->isolate());
84
20
  Context::Scope context_scope(env->context());
85
86
20
  Local<Object> hello_obj = Object::New(env->isolate());
87
20
  Local<String> servername = (hello.servername() == nullptr)
88
4
      ? String::Empty(env->isolate())
89
      : OneByteString(env->isolate(),
90
                      hello.servername(),
91
20
                      hello.servername_size());
92
  Local<Object> buf =
93
20
      Buffer::Copy(
94
          env,
95
20
          reinterpret_cast<const char*>(hello.session_id()),
96
40
          hello.session_size()).FromMaybe(Local<Object>());
97
98
60
  if ((buf.IsEmpty() ||
99
40
       hello_obj->Set(env->context(), env->session_id_string(), buf)
100
20
          .IsNothing()) ||
101
40
      hello_obj->Set(env->context(), env->servername_string(), servername)
102

60
          .IsNothing() ||
103
20
      hello_obj->Set(
104
          env->context(),
105
          env->tls_ticket_string(),
106
20
          hello.has_ticket()
107
5
              ? True(env->isolate())
108

100
              : False(env->isolate())).IsNothing()) {
109
    return;
110
  }
111
112
20
  Local<Value> argv[] = { hello_obj };
113
20
  w->MakeCallback(env->onclienthello_string(), arraysize(argv), argv);
114
}
115
116
32
void KeylogCallback(const SSL* s, const char* line) {
117
32
  TLSWrap* w = static_cast<TLSWrap*>(SSL_get_app_data(s));
118
32
  Environment* env = w->env();
119
32
  HandleScope handle_scope(env->isolate());
120
32
  Context::Scope context_scope(env->context());
121
122
32
  const size_t size = strlen(line);
123
32
  Local<Value> line_bf = Buffer::Copy(env, line, 1 + size)
124
32
      .FromMaybe(Local<Value>());
125
32
  if (UNLIKELY(line_bf.IsEmpty()))
126
    return;
127
128
32
  char* data = Buffer::Data(line_bf);
129
32
  data[size] = '\n';
130
32
  w->MakeCallback(env->onkeylog_string(), 1, &line_bf);
131
}
132
133
1901
int NewSessionCallback(SSL* s, SSL_SESSION* sess) {
134
1901
  TLSWrap* w = static_cast<TLSWrap*>(SSL_get_app_data(s));
135
1901
  Environment* env = w->env();
136
3802
  HandleScope handle_scope(env->isolate());
137
1901
  Context::Scope context_scope(env->context());
138
139
1901
  if (!w->has_session_callbacks())
140
1610
    return 0;
141
142
  // Check if session is small enough to be stored
143
291
  int size = i2d_SSL_SESSION(sess, nullptr);
144
291
  if (UNLIKELY(size > SecureContext::kMaxSessionSize))
145
    return 0;
146
147
  // Serialize session
148
582
  Local<Object> session = Buffer::New(env, size).FromMaybe(Local<Object>());
149
291
  if (UNLIKELY(session.IsEmpty()))
150
    return 0;
151
152
  unsigned char* session_data =
153
291
      reinterpret_cast<unsigned char*>(Buffer::Data(session));
154
155
291
  CHECK_EQ(i2d_SSL_SESSION(sess, &session_data), size);
156
157
  unsigned int session_id_length;
158
  const unsigned char* session_id_data =
159
291
      SSL_SESSION_get_id(sess, &session_id_length);
160
161
291
  Local<Object> session_id = Buffer::Copy(
162
      env,
163
      reinterpret_cast<const char*>(session_id_data),
164
582
      session_id_length).FromMaybe(Local<Object>());
165
291
  if (UNLIKELY(session_id.IsEmpty()))
166
    return 0;
167
168
  Local<Value> argv[] = {
169
    session_id,
170
    session
171
291
  };
172
173
  // On servers, we pause the handshake until callback of 'newSession', which
174
  // calls NewSessionDoneCb(). On clients, there is no callback to wait for.
175
291
  if (w->is_server())
176
8
    w->set_awaiting_new_session(true);
177
178
291
  w->MakeCallback(env->onnewsession_string(), arraysize(argv), argv);
179
180
291
  return 0;
181
}
182
183
969
int SSLCertCallback(SSL* s, void* arg) {
184
969
  TLSWrap* w = static_cast<TLSWrap*>(SSL_get_app_data(s));
185
186

969
  if (!w->is_server() || !w->is_waiting_cert_cb())
187
944
    return 1;
188
189
25
  if (w->is_cert_cb_running())
190
    // Not an error. Suspend handshake with SSL_ERROR_WANT_X509_LOOKUP, and
191
    // handshake will continue after certcb is done.
192
    return -1;
193
194
25
  Environment* env = w->env();
195
50
  HandleScope handle_scope(env->isolate());
196
25
  Context::Scope context_scope(env->context());
197
25
  w->set_cert_cb_running();
198
199
25
  Local<Object> info = Object::New(env->isolate());
200
201
25
  const char* servername = GetServerName(s);
202
  Local<String> servername_str = (servername == nullptr)
203
8
      ? String::Empty(env->isolate())
204
25
      : OneByteString(env->isolate(), servername, strlen(servername));
205
206
25
  Local<Value> ocsp = (SSL_get_tlsext_status_type(s) == TLSEXT_STATUSTYPE_ocsp)
207
6
      ? True(env->isolate())
208
50
      : False(env->isolate());
209
210
50
  if (info->Set(env->context(), env->servername_string(), servername_str)
211
50
          .IsNothing() ||
212

100
      info->Set(env->context(), env->ocsp_request_string(), ocsp).IsNothing()) {
213
    return 1;
214
  }
215
216
25
  Local<Value> argv[] = { info };
217
25
  w->MakeCallback(env->oncertcb_string(), arraysize(argv), argv);
218
219
25
  return w->is_cert_cb_running() ? -1 : 1;
220
}
221
222
34
int SelectALPNCallback(
223
    SSL* s,
224
    const unsigned char** out,
225
    unsigned char* outlen,
226
    const unsigned char* in,
227
    unsigned int inlen,
228
    void* arg) {
229
34
  TLSWrap* w = static_cast<TLSWrap*>(SSL_get_app_data(s));
230
34
  Environment* env = w->env();
231
68
  HandleScope handle_scope(env->isolate());
232
34
  Context::Scope context_scope(env->context());
233
234
  Local<Value> alpn_buffer =
235
34
      w->object()->GetPrivate(
236
          env->context(),
237
68
          env->alpn_buffer_private_symbol()).FromMaybe(Local<Value>());
238

68
  if (UNLIKELY(alpn_buffer.IsEmpty()) || !alpn_buffer->IsArrayBufferView())
239
    return SSL_TLSEXT_ERR_NOACK;
240
241
34
  ArrayBufferViewContents<unsigned char> alpn_protos(alpn_buffer);
242
34
  int status = SSL_select_next_proto(
243
      const_cast<unsigned char**>(out),
244
      outlen,
245
      alpn_protos.data(),
246
34
      alpn_protos.length(),
247
      in,
248
      inlen);
249
250
  // According to 3.2. Protocol Selection of RFC7301, fatal
251
  // no_application_protocol alert shall be sent but OpenSSL 1.0.2 does not
252
  // support it yet. See
253
  // https://rt.openssl.org/Ticket/Display.html?id=3463&user=guest&pass=guest
254
  return status == OPENSSL_NPN_NEGOTIATED
255
34
      ? SSL_TLSEXT_ERR_OK
256
34
      : SSL_TLSEXT_ERR_NOACK;
257
}
258
259
8
int TLSExtStatusCallback(SSL* s, void* arg) {
260
8
  TLSWrap* w = static_cast<TLSWrap*>(SSL_get_app_data(s));
261
8
  Environment* env = w->env();
262
16
  HandleScope handle_scope(env->isolate());
263
264
8
  if (w->is_client()) {
265
    // Incoming response
266
    Local<Value> arg;
267
12
    if (GetSSLOCSPResponse(env, s, Null(env->isolate())).ToLocal(&arg))
268
4
      w->MakeCallback(env->onocspresponse_string(), 1, &arg);
269
270
    // No async acceptance is possible, so always return 1 to accept the
271
    // response.  The listener for 'OCSPResponse' event has no control over
272
    // return value, but it can .destroy() the connection if the response is not
273
    // acceptable.
274
4
    return 1;
275
  }
276
277
  // Outgoing response
278
  Local<ArrayBufferView> obj =
279
8
      w->ocsp_response().FromMaybe(Local<ArrayBufferView>());
280
4
  if (UNLIKELY(obj.IsEmpty()))
281
2
    return SSL_TLSEXT_ERR_NOACK;
282
283
2
  size_t len = obj->ByteLength();
284
285
  // OpenSSL takes control of the pointer after accepting it
286
2
  unsigned char* data = MallocOpenSSL<unsigned char>(len);
287
2
  obj->CopyContents(data, len);
288
289
2
  if (!SSL_set_tlsext_status_ocsp_resp(s, data, len))
290
    OPENSSL_free(data);
291
292
2
  w->ClearOcspResponse();
293
294
2
  return SSL_TLSEXT_ERR_OK;
295
}
296
297
12378
void ConfigureSecureContext(SecureContext* sc) {
298
  // OCSP stapling
299
12378
  SSL_CTX_set_tlsext_status_cb(sc->ctx_.get(), TLSExtStatusCallback);
300
12378
  SSL_CTX_set_tlsext_status_arg(sc->ctx_.get(), nullptr);
301
12378
}
302
303
3974
inline bool Set(
304
    Environment* env,
305
    Local<Object> target,
306
    Local<String> name,
307
    const char* value,
308
    bool ignore_null = true) {
309
3974
  if (value == nullptr)
310
1334
    return ignore_null;
311
2640
  return !target->Set(
312
      env->context(),
313
      name,
314
5280
      OneByteString(env->isolate(), value))
315
2640
          .IsNothing();
316
}
317
318
635
std::string GetBIOError() {
319
635
  std::string ret;
320
635
  ERR_print_errors_cb(
321
631
      [](const char* str, size_t len, void* opaque) {
322
631
        static_cast<std::string*>(opaque)->assign(str, len);
323
631
        return 0;
324
      },
325
      static_cast<void*>(&ret));
326
635
  return ret;
327
}
328
}  // namespace
329
330
12378
TLSWrap::TLSWrap(Environment* env,
331
                 Local<Object> obj,
332
                 Kind kind,
333
                 StreamBase* stream,
334
12378
                 SecureContext* sc)
335
    : AsyncWrap(env, obj, AsyncWrap::PROVIDER_TLSWRAP),
336
      StreamBase(env),
337
      env_(env),
338
      kind_(kind),
339
12378
      sc_(sc) {
340
12378
  MakeWeak();
341
12378
  CHECK(sc_);
342
12378
  ssl_ = sc_->CreateSSL();
343
12378
  CHECK(ssl_);
344
345
12378
  sc_->SetGetSessionCallback(GetSessionCallback);
346
12378
  sc_->SetNewSessionCallback(NewSessionCallback);
347
348
12378
  StreamBase::AttachToObject(GetObject());
349
12378
  stream->PushStreamListener(this);
350
351
12378
  env_->isolate()->AdjustAmountOfExternalAllocatedMemory(kExternalSize);
352
353
12378
  InitSSL();
354
12378
  Debug(this, "Created new TLSWrap");
355
12378
}
356
357
74238
TLSWrap::~TLSWrap() {
358
24746
  Destroy();
359
49492
}
360
361
4
MaybeLocal<ArrayBufferView> TLSWrap::ocsp_response() const {
362
4
  if (ocsp_response_.IsEmpty())
363
2
    return MaybeLocal<ArrayBufferView>();
364
4
  return PersistentToLocal::Default(env()->isolate(), ocsp_response_);
365
}
366
367
2
void TLSWrap::ClearOcspResponse() {
368
2
  ocsp_response_.Reset();
369
2
}
370
371
54
SSL_SESSION* TLSWrap::ReleaseSession() {
372
54
  return next_sess_.release();
373
}
374
375
21053
void TLSWrap::InvokeQueued(int status, const char* error_str) {
376
21053
  Debug(this, "Invoking queued write callbacks (%d, %s)", status, error_str);
377
21053
  if (!write_callback_scheduled_)
378
4816
    return;
379
380
16237
  if (current_write_) {
381
5442
    BaseObjectPtr<AsyncWrap> current_write = std::move(current_write_);
382
2721
    current_write_.reset();
383
2721
    WriteWrap* w = WriteWrap::FromObject(current_write);
384
2721
    w->Done(status, error_str);
385
  }
386
}
387
388
8
void TLSWrap::NewSessionDoneCb() {
389
8
  Debug(this, "New session callback done");
390
8
  Cycle();
391
8
}
392
393
12378
void TLSWrap::InitSSL() {
394
  // Initialize SSL – OpenSSL takes ownership of these.
395
12378
  enc_in_ = NodeBIO::New(env()).release();
396
12378
  enc_out_ = NodeBIO::New(env()).release();
397
398
12378
  SSL_set_bio(ssl_.get(), enc_in_, enc_out_);
399
400
  // NOTE: This could be overridden in SetVerifyMode
401
12378
  SSL_set_verify(ssl_.get(), SSL_VERIFY_NONE, VerifyCallback);
402
403
#ifdef SSL_MODE_RELEASE_BUFFERS
404
12378
  SSL_set_mode(ssl_.get(), SSL_MODE_RELEASE_BUFFERS);
405
#endif  // SSL_MODE_RELEASE_BUFFERS
406
407
  // This is default in 1.1.1, but set it anyway, Cycle() doesn't currently
408
  // re-call ClearIn() if SSL_read() returns SSL_ERROR_WANT_READ, so data can be
409
  // left sitting in the incoming enc_in_ and never get processed.
410
  // - https://wiki.openssl.org/index.php/TLS1.3#Non-application_data_records
411
12378
  SSL_set_mode(ssl_.get(), SSL_MODE_AUTO_RETRY);
412
413
#ifdef OPENSSL_IS_BORINGSSL
414
  // OpenSSL allows renegotiation by default, but BoringSSL disables it.
415
  // Configure BoringSSL to match OpenSSL's behavior.
416
  SSL_set_renegotiate_mode(ssl_.get(), ssl_renegotiate_freely);
417
#endif
418
419
12378
  SSL_set_app_data(ssl_.get(), this);
420
  // Using InfoCallback isn't how we are supposed to check handshake progress:
421
  //   https://github.com/openssl/openssl/issues/7199#issuecomment-420915993
422
  //
423
  // Note on when this gets called on various openssl versions:
424
  //   https://github.com/openssl/openssl/issues/7199#issuecomment-420670544
425
12378
  SSL_set_info_callback(ssl_.get(), SSLInfoCallback);
426
427
12378
  if (is_server())
428
940
    sc_->SetSelectSNIContextCallback(SelectSNIContextCallback);
429
430
12378
  ConfigureSecureContext(sc_.get());
431
432
12378
  SSL_set_cert_cb(ssl_.get(), SSLCertCallback, this);
433
434
12378
  if (is_server()) {
435
940
    SSL_set_accept_state(ssl_.get());
436
11438
  } else if (is_client()) {
437
    // Enough space for server response (hello, cert)
438
11438
    NodeBIO::FromBIO(enc_in_)->set_initial(kInitialClientBufferLength);
439
11438
    SSL_set_connect_state(ssl_.get());
440
  } else {
441
    // Unexpected
442
    ABORT();
443
  }
444
12378
}
445
446
12378
void TLSWrap::Wrap(const FunctionCallbackInfo<Value>& args) {
447
12378
  Environment* env = Environment::GetCurrent(args);
448
449
12378
  CHECK_EQ(args.Length(), 3);
450
12378
  CHECK(args[0]->IsObject());
451
12378
  CHECK(args[1]->IsObject());
452
12378
  CHECK(args[2]->IsBoolean());
453
454
24756
  Local<Object> sc = args[1].As<Object>();
455

12378
  Kind kind = args[2]->IsTrue() ? Kind::kServer : Kind::kClient;
456
457
24756
  StreamBase* stream = StreamBase::FromObject(args[0].As<Object>());
458
12378
  CHECK_NOT_NULL(stream);
459
460
  Local<Object> obj;
461
12378
  if (!env->tls_wrap_constructor_function()
462
12378
           ->NewInstance(env->context())
463
12378
           .ToLocal(&obj)) {
464
    return;
465
  }
466
467
12378
  TLSWrap* res = new TLSWrap(env, obj, kind, stream, Unwrap<SecureContext>(sc));
468
469
24756
  args.GetReturnValue().Set(res->object());
470
}
471
472
3
void TLSWrap::Receive(const FunctionCallbackInfo<Value>& args) {
473
  TLSWrap* wrap;
474
3
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
475
476
3
  ArrayBufferViewContents<char> buffer(args[0]);
477
3
  const char* data = buffer.data();
478
3
  size_t len = buffer.length();
479
3
  Debug(wrap, "Receiving %zu bytes injected from JS", len);
480
481
  // Copy given buffer entirely or partiall if handle becomes closed
482


6
  while (len > 0 && wrap->IsAlive() && !wrap->IsClosing()) {
483
3
    uv_buf_t buf = wrap->OnStreamAlloc(len);
484
3
    size_t copy = buf.len > len ? len : buf.len;
485
3
    memcpy(buf.base, data, copy);
486
3
    buf.len = copy;
487
3
    wrap->OnStreamRead(copy, buf);
488
489
3
    data += copy;
490
3
    len -= copy;
491
  }
492
}
493
494
1386
void TLSWrap::Start(const FunctionCallbackInfo<Value>& args) {
495
  TLSWrap* wrap;
496
1386
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
497
498
1386
  CHECK(!wrap->started_);
499
1386
  wrap->started_ = true;
500
501
  // Send ClientHello handshake
502
1386
  CHECK(wrap->is_client());
503
  // Seems odd to read when when we want to send, but SSL_read() triggers a
504
  // handshake if a session isn't established, and handshake will cause
505
  // encrypted data to become available for output.
506
1386
  wrap->ClearOut();
507
1386
  wrap->EncOut();
508
}
509
510
40353
void TLSWrap::SSLInfoCallback(const SSL* ssl_, int where, int ret) {
511
40353
  if (!(where & (SSL_CB_HANDSHAKE_START | SSL_CB_HANDSHAKE_DONE)))
512
36047
    return;
513
514
  // SSL_renegotiate_pending() should take `const SSL*`, but it does not.
515
4306
  SSL* ssl = const_cast<SSL*>(ssl_);
516
4306
  TLSWrap* c = static_cast<TLSWrap*>(SSL_get_app_data(ssl_));
517
4306
  Environment* env = c->env();
518
8612
  HandleScope handle_scope(env->isolate());
519
4306
  Context::Scope context_scope(env->context());
520
4306
  Local<Object> object = c->object();
521
522
4306
  if (where & SSL_CB_HANDSHAKE_START) {
523
    Debug(c, "SSLInfoCallback(SSL_CB_HANDSHAKE_START);");
524
    // Start is tracked to limit number and frequency of renegotiation attempts,
525
    // since excessive renegotiation may be an attack.
526
    Local<Value> callback;
527
528
5018
    if (object->Get(env->context(), env->onhandshakestart_string())
529

5018
            .ToLocal(&callback) && callback->IsFunction()) {
530
2509
      Local<Value> argv[] = { env->GetNow() };
531
5018
      c->MakeCallback(callback.As<Function>(), arraysize(argv), argv);
532
    }
533
  }
534
535
  // SSL_CB_HANDSHAKE_START and SSL_CB_HANDSHAKE_DONE are called
536
  // sending HelloRequest in OpenSSL-1.1.1.
537
  // We need to check whether this is in a renegotiation state or not.
538

4306
  if (where & SSL_CB_HANDSHAKE_DONE && !SSL_renegotiate_pending(ssl)) {
539
    Debug(c, "SSLInfoCallback(SSL_CB_HANDSHAKE_DONE);");
540
1796
    CHECK(!SSL_renegotiate_pending(ssl));
541
    Local<Value> callback;
542
543
1796
    c->established_ = true;
544
545
3592
    if (object->Get(env->context(), env->onhandshakedone_string())
546

3592
          .ToLocal(&callback) && callback->IsFunction()) {
547
3592
      c->MakeCallback(callback.As<Function>(), 0, nullptr);
548
    }
549
  }
550
}
551
552
20045
void TLSWrap::EncOut() {
553
20045
  Debug(this, "Trying to write encrypted output");
554
555
  // Ignore cycling data if ClientHello wasn't yet parsed
556
20045
  if (!hello_parser_.IsEnded()) {
557
1
    Debug(this, "Returning from EncOut(), hello_parser_ active");
558
12515
    return;
559
  }
560
561
  // Write in progress
562
20044
  if (write_size_ != 0) {
563
3621
    Debug(this, "Returning from EncOut(), write currently in progress");
564
3621
    return;
565
  }
566
567
  // Wait for `newSession` callback to be invoked
568
16423
  if (is_awaiting_new_session()) {
569
7
    Debug(this, "Returning from EncOut(), awaiting new session");
570
7
    return;
571
  }
572
573
  // Split-off queue
574

16416
  if (established_ && current_write_) {
575
5412
    Debug(this, "EncOut() write is scheduled");
576
5412
    write_callback_scheduled_ = true;
577
  }
578
579
16416
  if (ssl_ == nullptr) {
580
2
    Debug(this, "Returning from EncOut(), ssl_ == nullptr");
581
2
    return;
582
  }
583
584
  // No encrypted output ready to write to the underlying stream.
585
16414
  if (BIO_pending(enc_out_) == 0) {
586
8705
    Debug(this, "No pending encrypted output");
587

8913
    if (!pending_cleartext_input_ ||
588
208
        pending_cleartext_input_->ByteLength() == 0) {
589
8497
      if (!in_dowrite_) {
590
8435
        Debug(this, "No pending cleartext input, not inside DoWrite()");
591
8435
        InvokeQueued(0);
592
      } else {
593
62
        Debug(this, "No pending cleartext input, inside DoWrite()");
594
        // TODO(@sam-github, @addaleax) If in_dowrite_ is true, appdata was
595
        // passed to SSL_write().  If we are here, the data was not encrypted to
596
        // enc_out_ yet.  Calling Done() "works", but since the write is not
597
        // flushed, its too soon.  Just returning and letting the next EncOut()
598
        // call Done() passes the test suite, but without more careful analysis,
599
        // its not clear if it is always correct. Not calling Done() could block
600
        // data flow, so for now continue to call Done(), just do it in the next
601
        // tick.
602
62
        BaseObjectPtr<TLSWrap> strong_ref{this};
603
62
        env()->SetImmediate([this, strong_ref](Environment* env) {
604
62
          InvokeQueued(0);
605
62
        });
606
      }
607
    }
608
8705
    return;
609
  }
610
611
  char* data[kSimultaneousBufferCount];
612
  size_t size[arraysize(data)];
613
7709
  size_t count = arraysize(data);
614
7709
  write_size_ = NodeBIO::FromBIO(enc_out_)->PeekMultiple(data, size, &count);
615

7709
  CHECK(write_size_ != 0 && count != 0);
616
617
  uv_buf_t buf[arraysize(data)];
618
7709
  uv_buf_t* bufs = buf;
619
15554
  for (size_t i = 0; i < count; i++)
620
7845
    buf[i] = uv_buf_init(data[i], size[i]);
621
622
7709
  Debug(this, "Writing %zu buffers to the underlying stream", count);
623
7709
  StreamWriteResult res = underlying_stream()->Write(bufs, count);
624
7708
  if (res.err != 0) {
625
179
    InvokeQueued(res.err);
626
179
    return;
627
  }
628
629
7529
  if (!res.async) {
630
6970
    Debug(this, "Write finished synchronously");
631
13940
    HandleScope handle_scope(env()->isolate());
632
633
    // Simulate asynchronous finishing, TLS cannot handle this at the moment.
634
6970
    BaseObjectPtr<TLSWrap> strong_ref{this};
635
6970
    env()->SetImmediate([this, strong_ref](Environment* env) {
636
6970
      OnStreamAfterWrite(nullptr, 0);
637
6970
    });
638
  }
639
}
640
641
7628
void TLSWrap::OnStreamAfterWrite(WriteWrap* req_wrap, int status) {
642
7628
  Debug(this, "OnStreamAfterWrite(status = %d)", status);
643
7628
  if (current_empty_write_) {
644
100
    Debug(this, "Had empty write");
645
    BaseObjectPtr<AsyncWrap> current_empty_write =
646
100
        std::move(current_empty_write_);
647
100
    current_empty_write_.reset();
648
100
    WriteWrap* finishing = WriteWrap::FromObject(current_empty_write);
649
100
    finishing->Done(status);
650
100
    return;
651
  }
652
653
7528
  if (ssl_ == nullptr) {
654
    Debug(this, "ssl_ == nullptr, marking as cancelled");
655
    status = UV_ECANCELED;
656
  }
657
658
  // Handle error
659
7528
  if (status) {
660
3
    if (shutdown_) {
661
1
      Debug(this, "Ignoring error after shutdown");
662
1
      return;
663
    }
664
665
    // Notify about error
666
2
    InvokeQueued(status);
667
2
    return;
668
  }
669
670
  // Commit
671
7525
  NodeBIO::FromBIO(enc_out_)->Read(nullptr, write_size_);
672
673
  // Ensure that the progress will be made and `InvokeQueued` will be called.
674
7525
  ClearIn();
675
676
  // Try writing more data
677
7525
  write_size_ = 0;
678
7525
  EncOut();
679
}
680
681
8596
int TLSWrap::GetSSLError(int status) const {
682
  // ssl_ might already be destroyed for reading EOF from a close notify alert.
683
8596
  return ssl_ != nullptr ? SSL_get_error(ssl_.get(), status) : 0;
684
}
685
686
8179
void TLSWrap::ClearOut() {
687
8179
  Debug(this, "Trying to read cleartext output");
688
  // Ignore cycling data if ClientHello wasn't yet parsed
689
8179
  if (!hello_parser_.IsEnded()) {
690
1
    Debug(this, "Returning from ClearOut(), hello_parser_ active");
691
7549
    return;
692
  }
693
694
  // No reads after EOF
695
8178
  if (eof_) {
696
    Debug(this, "Returning from ClearOut(), EOF reached");
697
    return;
698
  }
699
700
8178
  if (ssl_ == nullptr) {
701
1
    Debug(this, "Returning from ClearOut(), ssl_ == nullptr");
702
1
    return;
703
  }
704
705
8177
  MarkPopErrorOnReturn mark_pop_error_on_return;
706
707
  char out[kClearOutChunkSize];
708
  int read;
709
  for (;;) {
710
11363
    read = SSL_read(ssl_.get(), out, sizeof(out));
711
11363
    Debug(this, "Read %d bytes of cleartext output", read);
712
713
11363
    if (read <= 0)
714
8175
      break;
715
716
3188
    char* current = out;
717
8428
    while (read > 0) {
718
5242
      int avail = read;
719
720
5242
      uv_buf_t buf = EmitAlloc(avail);
721
5242
      if (static_cast<int>(buf.len) < avail)
722
2054
        avail = buf.len;
723
5242
      memcpy(buf.base, current, avail);
724
5242
      EmitRead(avail, buf);
725
726
      // Caveat emptor: OnRead() calls into JS land which can result in
727
      // the SSL context object being destroyed.  We have to carefully
728
      // check that ssl_ != nullptr afterwards.
729
5241
      if (ssl_ == nullptr) {
730
1
        Debug(this, "Returning from read loop, ssl_ == nullptr");
731
1
        return;
732
      }
733
734
5240
      read -= avail;
735
5240
      current += avail;
736
    }
737
3186
  }
738
739
8175
  int flags = SSL_get_shutdown(ssl_.get());
740

8175
  if (!eof_ && flags & SSL_RECEIVED_SHUTDOWN) {
741
1196
    eof_ = true;
742
1196
    EmitRead(UV_EOF);
743
  }
744
745
  // We need to check whether an error occurred or the connection was
746
  // shutdown cleanly (SSL_ERROR_ZERO_RETURN) even when read == 0.
747
  // See node#1642 and SSL_read(3SSL) for details.
748
8175
  if (read <= 0) {
749
8175
    HandleScope handle_scope(env()->isolate());
750
    Local<Value> error;
751
8175
    int err = GetSSLError(read);
752
8175
    switch (err) {
753
1140
      case SSL_ERROR_ZERO_RETURN:
754
        // Ignore ZERO_RETURN after EOF, it is basically not an error.
755
1140
        if (eof_) return;
756
        error = env()->zero_return_string();
757
        break;
758
759
633
      case SSL_ERROR_SSL:
760
      case SSL_ERROR_SYSCALL:
761
        {
762
633
          unsigned long ssl_err = ERR_peek_error();  // NOLINT(runtime/int)
763
764
633
          Local<Context> context = env()->isolate()->GetCurrentContext();
765
633
          if (UNLIKELY(context.IsEmpty())) return;
766
633
          const std::string error_str = GetBIOError();
767
          Local<String> message = OneByteString(
768
633
              env()->isolate(), error_str.c_str(), error_str.size());
769
633
          if (UNLIKELY(message.IsEmpty())) return;
770
633
          error = Exception::Error(message);
771
633
          if (UNLIKELY(error.IsEmpty())) return;
772
          Local<Object> obj;
773
1266
          if (UNLIKELY(!error->ToObject(context).ToLocal(&obj))) return;
774
775
633
          const char* ls = ERR_lib_error_string(ssl_err);
776
633
          const char* fs = ERR_func_error_string(ssl_err);
777
633
          const char* rs = ERR_reason_error_string(ssl_err);
778
633
          if (!Set(env(), obj, env()->library_string(), ls) ||
779

1266
              !Set(env(), obj, env()->function_string(), fs) ||
780
637
              !Set(env(), obj, env()->reason_string(), rs, false)) return;
781
          // SSL has no API to recover the error name from the number, so we
782
          // transform reason strings like "this error" to "ERR_SSL_THIS_ERROR",
783
          // which ends up being close to the original error macro name.
784
629
          std::string code(rs);
785
          // TODO(RaisinTen): Pass an appropriate execution policy when it is
786
          // implemented in our supported compilers.
787
          std::transform(code.begin(), code.end(), code.begin(),
788
13638
                         [](char c) { return c == ' ' ? '_' : ToUpper(c); });
789
629
          if (!Set(env(), obj,
790
1891
                   env()->code_string(), ("ERR_SSL_" + code).c_str())) return;
791
        }
792
629
        break;
793
794
6402
      default:
795
6402
        return;
796
    }
797
798
629
    Debug(this, "Got SSL error (%d), calling onerror", err);
799
    // When TLS Alert are stored in wbio,
800
    // it should be flushed to socket before destroyed.
801
629
    if (BIO_pending(enc_out_) != 0)
802
572
      EncOut();
803
804
629
    MakeCallback(env()->onerror_string(), 1, &error);
805
  }
806
}
807
808
13880
void TLSWrap::ClearIn() {
809
13880
  Debug(this, "Trying to write cleartext input");
810
  // Ignore cycling data if ClientHello wasn't yet parsed
811
13880
  if (!hello_parser_.IsEnded()) {
812
    Debug(this, "Returning from ClearIn(), hello_parser_ active");
813
13644
    return;
814
  }
815
816
13880
  if (ssl_ == nullptr) {
817
    Debug(this, "Returning from ClearIn(), ssl_ == nullptr");
818
    return;
819
  }
820
821

14294
  if (!pending_cleartext_input_ ||
822
414
      pending_cleartext_input_->ByteLength() == 0) {
823
13466
    Debug(this, "Returning from ClearIn(), no pending data");
824
13466
    return;
825
  }
826
827
414
  std::unique_ptr<BackingStore> bs = std::move(pending_cleartext_input_);
828
414
  MarkPopErrorOnReturn mark_pop_error_on_return;
829
830
414
  NodeBIO::FromBIO(enc_out_)->set_allocate_tls_hint(bs->ByteLength());
831
414
  int written = SSL_write(ssl_.get(), bs->Data(), bs->ByteLength());
832
414
  Debug(this, "Writing %zu bytes, written = %d", bs->ByteLength(), written);
833

414
  CHECK(written == -1 || written == static_cast<int>(bs->ByteLength()));
834
835
  // All written
836
414
  if (written != -1) {
837
176
    Debug(this, "Successfully wrote all data to SSL");
838
176
    return;
839
  }
840
841
  // Error or partial write
842
238
  int err = GetSSLError(written);
843

238
  if (err == SSL_ERROR_SSL || err == SSL_ERROR_SYSCALL) {
844
2
    Debug(this, "Got SSL error (%d)", err);
845
2
    write_callback_scheduled_ = true;
846
    // TODO(@sam-github) Should forward an error object with
847
    // .code/.function/.etc, if possible.
848
2
    InvokeQueued(UV_EPROTO, GetBIOError().c_str());
849
2
    return;
850
  }
851
852
236
  Debug(this, "Pushing data back");
853
  // Push back the not-yet-written data. This can be skipped in the error
854
  // case because no further writes would succeed anyway.
855
236
  pending_cleartext_input_ = std::move(bs);
856
}
857
858
std::string TLSWrap::diagnostic_name() const {
859
  std::string name = "TLSWrap ";
860
  name += is_server() ? "server (" : "client (";
861
  name += std::to_string(static_cast<int64_t>(get_async_id())) + ")";
862
  return name;
863
}
864
865
26487
AsyncWrap* TLSWrap::GetAsyncWrap() {
866
26487
  return static_cast<AsyncWrap*>(this);
867
}
868
869
1136
bool TLSWrap::IsIPCPipe() {
870
1136
  return underlying_stream()->IsIPCPipe();
871
}
872
873
4
int TLSWrap::GetFD() {
874
4
  return underlying_stream()->GetFD();
875
}
876
877
4120
bool TLSWrap::IsAlive() {
878
4119
  return ssl_ &&
879

8239
      underlying_stream() != nullptr &&
880
8238
      underlying_stream()->IsAlive();
881
}
882
883
3
bool TLSWrap::IsClosing() {
884
3
  return underlying_stream()->IsClosing();
885
}
886
887
2466
int TLSWrap::ReadStart() {
888
2466
  Debug(this, "ReadStart()");
889

2466
  if (underlying_stream() != nullptr && !eof_)
890
2465
    return underlying_stream()->ReadStart();
891
1
  return 0;
892
}
893
894
1694
int TLSWrap::ReadStop() {
895
1694
  Debug(this, "ReadStop()");
896
1694
  return underlying_stream() != nullptr ? underlying_stream()->ReadStop() : 0;
897
}
898
899
5666
const char* TLSWrap::Error() const {
900
5666
  return error_.empty() ? nullptr : error_.c_str();
901
}
902
903
8
void TLSWrap::ClearError() {
904
8
  error_.clear();
905
8
}
906
907
// Called by StreamBase::Write() to request async write of clear text into SSL.
908
// TODO(@sam-github) Should there be a TLSWrap::DoTryWrite()?
909
2829
int TLSWrap::DoWrite(WriteWrap* w,
910
                     uv_buf_t* bufs,
911
                     size_t count,
912
                     uv_stream_t* send_handle) {
913
2829
  CHECK_NULL(send_handle);
914
2829
  Debug(this, "DoWrite()");
915
916
2829
  if (ssl_ == nullptr) {
917
4
    ClearError();
918
4
    error_ = "Write after DestroySSL";
919
4
    return UV_EPROTO;
920
  }
921
922
2825
  size_t length = 0;
923
  size_t i;
924
2825
  size_t nonempty_i = 0;
925
2825
  size_t nonempty_count = 0;
926
13063
  for (i = 0; i < count; i++) {
927
10238
    length += bufs[i].len;
928
10238
    if (bufs[i].len > 0) {
929
9935
      nonempty_i = i;
930
9935
      nonempty_count += 1;
931
    }
932
  }
933
934
  // We want to trigger a Write() on the underlying stream to drive the stream
935
  // system, but don't want to encrypt empty buffers into a TLS frame, so see
936
  // if we can find something to Write().
937
  // First, call ClearOut(). It does an SSL_read(), which might cause handshake
938
  // or other internal messages to be encrypted. If it does, write them later
939
  // with EncOut().
940
  // If there is still no encrypted output, call Write(bufs) on the underlying
941
  // stream. Since the bufs are empty, it won't actually write non-TLS data
942
  // onto the socket, we just want the side-effects. After, make sure the
943
  // WriteWrap was accepted by the stream, or that we call Done() on it.
944
2825
  if (length == 0) {
945
201
    Debug(this, "Empty write");
946
201
    ClearOut();
947
201
    if (BIO_pending(enc_out_) == 0) {
948
100
      Debug(this, "No pending encrypted output, writing to underlying stream");
949
100
      CHECK(!current_empty_write_);
950
100
      current_empty_write_.reset(w->GetAsyncWrap());
951
      StreamWriteResult res =
952
100
          underlying_stream()->Write(bufs, count, send_handle);
953
100
      if (!res.async) {
954
100
        BaseObjectPtr<TLSWrap> strong_ref{this};
955
100
        env()->SetImmediate([this, strong_ref](Environment* env) {
956
100
          OnStreamAfterWrite(WriteWrap::FromObject(current_empty_write_), 0);
957
100
        });
958
      }
959
100
      return 0;
960
    }
961
  }
962
963
  // Store the current write wrap
964
2725
  CHECK(!current_write_);
965
2725
  current_write_.reset(w->GetAsyncWrap());
966
967
  // Write encrypted data to underlying stream and call Done().
968
2725
  if (length == 0) {
969
101
    EncOut();
970
101
    return 0;
971
  }
972
973
2624
  std::unique_ptr<BackingStore> bs;
974
5248
  MarkPopErrorOnReturn mark_pop_error_on_return;
975
976
2624
  int written = 0;
977
978
  // It is common for zero length buffers to be written,
979
  // don't copy data if there there is one buffer with data
980
  // and one or more zero length buffers.
981
  // _http_outgoing.js writes a zero length buffer in
982
  // in OutgoingMessage.prototype.end.  If there was a large amount
983
  // of data supplied to end() there is no sense allocating
984
  // and copying it when it could just be used.
985
986
2624
  if (nonempty_count != 1) {
987
    {
988
1624
      NoArrayBufferZeroFillScope no_zero_fill_scope(env()->isolate_data());
989
1624
      bs = ArrayBuffer::NewBackingStore(env()->isolate(), length);
990
    }
991
1624
    size_t offset = 0;
992
10561
    for (i = 0; i < count; i++) {
993
8937
      memcpy(static_cast<char*>(bs->Data()) + offset,
994
8937
             bufs[i].base, bufs[i].len);
995
8937
      offset += bufs[i].len;
996
    }
997
998
1624
    NodeBIO::FromBIO(enc_out_)->set_allocate_tls_hint(length);
999
1624
    written = SSL_write(ssl_.get(), bs->Data(), length);
1000
  } else {
1001
    // Only one buffer: try to write directly, only store if it fails
1002
1000
    uv_buf_t* buf = &bufs[nonempty_i];
1003
1000
    NodeBIO::FromBIO(enc_out_)->set_allocate_tls_hint(buf->len);
1004
1000
    written = SSL_write(ssl_.get(), buf->base, buf->len);
1005
1006
1000
    if (written == -1) {
1007
178
      NoArrayBufferZeroFillScope no_zero_fill_scope(env()->isolate_data());
1008
178
      bs = ArrayBuffer::NewBackingStore(env()->isolate(), length);
1009
178
      memcpy(bs->Data(), buf->base, buf->len);
1010
    }
1011
  }
1012
1013

2624
  CHECK(written == -1 || written == static_cast<int>(length));
1014
2624
  Debug(this, "Writing %zu bytes, written = %d", length, written);
1015
1016
2624
  if (written == -1) {
1017
    // If we stopped writing because of an error, it's fatal, discard the data.
1018
183
    int err = GetSSLError(written);
1019

183
    if (err == SSL_ERROR_SSL || err == SSL_ERROR_SYSCALL) {
1020
      // TODO(@jasnell): What are we doing with the error?
1021
3
      Debug(this, "Got SSL error (%d), returning UV_EPROTO", err);
1022
3
      current_write_.reset();
1023
3
      return UV_EPROTO;
1024
    }
1025
1026
180
    Debug(this, "Saving data for later write");
1027
    // Otherwise, save unwritten data so it can be written later by ClearIn().
1028

180
    CHECK(!pending_cleartext_input_ ||
1029
          pending_cleartext_input_->ByteLength() == 0);
1030
180
    pending_cleartext_input_ = std::move(bs);
1031
  }
1032
1033
  // Write any encrypted/handshake output that may be ready.
1034
  // Guard against sync call of current_write_->Done(), its unsupported.
1035
2621
  in_dowrite_ = true;
1036
2621
  EncOut();
1037
2621
  in_dowrite_ = false;
1038
1039
2621
  return 0;
1040
}
1041
1042
7150
uv_buf_t TLSWrap::OnStreamAlloc(size_t suggested_size) {
1043
7150
  CHECK_NOT_NULL(ssl_);
1044
1045
7150
  size_t size = suggested_size;
1046
7150
  char* base = NodeBIO::FromBIO(enc_in_)->PeekWritable(&size);
1047
7150
  return uv_buf_init(base, size);
1048
}
1049
1050
7175
void TLSWrap::OnStreamRead(ssize_t nread, const uv_buf_t& buf) {
1051
7175
  Debug(this, "Read %zd bytes from underlying stream", nread);
1052
1053
  // Ignore everything after close_notify (rfc5246#section-7.2.1)
1054
7175
  if (eof_)
1055
610
    return;
1056
1057
6565
  if (nread < 0)  {
1058
    // Error should be emitted only after all data was read
1059
237
    ClearOut();
1060
1061
237
    if (nread == UV_EOF) {
1062
      // underlying stream already should have also called ReadStop on itself
1063
235
      eof_ = true;
1064
    }
1065
1066
237
    EmitRead(nread);
1067
237
    return;
1068
  }
1069
1070
  // DestroySSL() is the only thing that un-sets ssl_, but that also removes
1071
  // this TLSWrap as a stream listener, so we should not receive OnStreamRead()
1072
  // calls anymore.
1073
6328
  CHECK(ssl_);
1074
1075
  // Commit the amount of data actually read into the peeked/allocated buffer
1076
  // from the underlying stream.
1077
6328
  NodeBIO* enc_in = NodeBIO::FromBIO(enc_in_);
1078
6328
  enc_in->Commit(nread);
1079
1080
  // Parse ClientHello first, if we need to. It's only parsed if session event
1081
  // listeners are used on the server side.  "ended" is the initial state, so
1082
  // can mean parsing was never started, or that parsing is finished. Either
1083
  // way, ended means we can give the buffered data to SSL.
1084
6328
  if (!hello_parser_.IsEnded()) {
1085
20
    size_t avail = 0;
1086
20
    uint8_t* data = reinterpret_cast<uint8_t*>(enc_in->Peek(&avail));
1087

20
    CHECK_IMPLIES(data == nullptr, avail == 0);
1088
20
    Debug(this, "Passing %zu bytes to the hello parser", avail);
1089
20
    return hello_parser_.Parse(data, avail);
1090
  }
1091
1092
  // Cycle OpenSSL's state
1093
6308
  Cycle();
1094
}
1095
1096
1486
ShutdownWrap* TLSWrap::CreateShutdownWrap(Local<Object> req_wrap_object) {
1097
1486
  return underlying_stream()->CreateShutdownWrap(req_wrap_object);
1098
}
1099
1100
1486
int TLSWrap::DoShutdown(ShutdownWrap* req_wrap) {
1101
1486
  Debug(this, "DoShutdown()");
1102
2972
  MarkPopErrorOnReturn mark_pop_error_on_return;
1103
1104

1486
  if (ssl_ && SSL_shutdown(ssl_.get()) == 0)
1105
951
    SSL_shutdown(ssl_.get());
1106
1107
1486
  shutdown_ = true;
1108
1486
  EncOut();
1109
1486
  return underlying_stream()->DoShutdown(req_wrap);
1110
}
1111
1112
12356
void TLSWrap::SetVerifyMode(const FunctionCallbackInfo<Value>& args) {
1113
  TLSWrap* wrap;
1114
12356
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1115
1116
12356
  CHECK_EQ(args.Length(), 2);
1117
12356
  CHECK(args[0]->IsBoolean());
1118
12356
  CHECK(args[1]->IsBoolean());
1119
12356
  CHECK_NOT_NULL(wrap->ssl_);
1120
1121
  int verify_mode;
1122
12356
  if (wrap->is_server()) {
1123
918
    bool request_cert = args[0]->IsTrue();
1124
918
    if (!request_cert) {
1125
      // If no cert is requested, there will be none to reject as unauthorized.
1126
834
      verify_mode = SSL_VERIFY_NONE;
1127
    } else {
1128
84
      bool reject_unauthorized = args[1]->IsTrue();
1129
84
      verify_mode = SSL_VERIFY_PEER;
1130
84
      if (reject_unauthorized)
1131
48
        verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1132
    }
1133
  } else {
1134
    // Servers always send a cert if the cipher is not anonymous (anon is
1135
    // disabled by default), so use VERIFY_NONE and check the cert after the
1136
    // handshake has completed.
1137
11438
    verify_mode = SSL_VERIFY_NONE;
1138
  }
1139
1140
  // Always allow a connection. We'll reject in javascript.
1141
12356
  SSL_set_verify(wrap->ssl_.get(), verify_mode, VerifyCallback);
1142
}
1143
1144
220
void TLSWrap::EnableSessionCallbacks(const FunctionCallbackInfo<Value>& args) {
1145
  TLSWrap* wrap;
1146
420
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1147
220
  CHECK_NOT_NULL(wrap->ssl_);
1148
220
  wrap->enable_session_callbacks();
1149
1150
  // Clients don't use the HelloParser.
1151
220
  if (wrap->is_client())
1152
200
    return;
1153
1154
20
  NodeBIO::FromBIO(wrap->enc_in_)->set_initial(kMaxHelloLength);
1155
20
  wrap->hello_parser_.Start(OnClientHello,
1156
                            OnClientHelloParseEnd,
1157
                            wrap);
1158
}
1159
1160
8
void TLSWrap::EnableKeylogCallback(const FunctionCallbackInfo<Value>& args) {
1161
  TLSWrap* wrap;
1162
8
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1163
8
  CHECK(wrap->sc_);
1164
8
  wrap->sc_->SetKeylogCallback(KeylogCallback);
1165
}
1166
1167
// Check required capabilities were not excluded from the OpenSSL build:
1168
// - OPENSSL_NO_SSL_TRACE excludes SSL_trace()
1169
// - OPENSSL_NO_STDIO excludes BIO_new_fp()
1170
// HAVE_SSL_TRACE is available on the internal tcp_wrap binding for the tests.
1171
#if defined(OPENSSL_NO_SSL_TRACE) || defined(OPENSSL_NO_STDIO)
1172
# define HAVE_SSL_TRACE 0
1173
#else
1174
# define HAVE_SSL_TRACE 1
1175
#endif
1176
1177
4
void TLSWrap::EnableTrace(const FunctionCallbackInfo<Value>& args) {
1178
  TLSWrap* wrap;
1179
4
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1180
1181
#if HAVE_SSL_TRACE
1182
4
  if (wrap->ssl_) {
1183
4
    wrap->bio_trace_.reset(BIO_new_fp(stderr,  BIO_NOCLOSE | BIO_FP_TEXT));
1184
4
    SSL_set_msg_callback(wrap->ssl_.get(), [](int write_p, int version, int
1185
          content_type, const void* buf, size_t len, SSL* ssl, void* arg)
1186
114
        -> void {
1187
        // BIO_write(), etc., called by SSL_trace, may error. The error should
1188
        // be ignored, trace is a "best effort", and its usually because stderr
1189
        // is a non-blocking pipe, and its buffer has overflowed. Leaving errors
1190
        // on the stack that can get picked up by later SSL_ calls causes
1191
        // unwanted failures in SSL_ calls, so keep the error stack unchanged.
1192
228
        MarkPopErrorOnReturn mark_pop_error_on_return;
1193
114
        SSL_trace(write_p,  version, content_type, buf, len, ssl, arg);
1194
114
    });
1195
4
    SSL_set_msg_callback_arg(wrap->ssl_.get(), wrap->bio_trace_.get());
1196
  }
1197
#endif
1198
}
1199
1200
12315
void TLSWrap::DestroySSL(const FunctionCallbackInfo<Value>& args) {
1201
  TLSWrap* wrap;
1202
12315
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1203
12315
  wrap->Destroy();
1204
12315
  Debug(wrap, "DestroySSL() finished");
1205
}
1206
1207
24688
void TLSWrap::Destroy() {
1208
24688
  if (!ssl_)
1209
12315
    return;
1210
1211
  // If there is a write happening, mark it as finished.
1212
12373
  write_callback_scheduled_ = true;
1213
1214
  // And destroy
1215
12373
  InvokeQueued(UV_ECANCELED, "Canceled because of SSL destruction");
1216
1217
12373
  env()->isolate()->AdjustAmountOfExternalAllocatedMemory(-kExternalSize);
1218
12373
  ssl_.reset();
1219
1220
12373
  enc_in_ = nullptr;
1221
12373
  enc_out_ = nullptr;
1222
1223
12373
  if (underlying_stream() != nullptr)
1224
12331
    underlying_stream()->RemoveStreamListener(this);
1225
1226
12373
  sc_.reset();
1227
}
1228
1229
25
void TLSWrap::EnableCertCb(const FunctionCallbackInfo<Value>& args) {
1230
  TLSWrap* wrap;
1231
25
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1232
25
  wrap->WaitForCertCb(OnClientHelloParseEnd, wrap);
1233
}
1234
1235
25
void TLSWrap::WaitForCertCb(CertCb cb, void* arg) {
1236
25
  cert_cb_ = cb;
1237
25
  cert_cb_arg_ = arg;
1238
25
}
1239
1240
39
void TLSWrap::OnClientHelloParseEnd(void* arg) {
1241
39
  TLSWrap* c = static_cast<TLSWrap*>(arg);
1242
  Debug(c, "OnClientHelloParseEnd()");
1243
39
  c->Cycle();
1244
39
}
1245
1246
1418
void TLSWrap::GetServername(const FunctionCallbackInfo<Value>& args) {
1247
1418
  Environment* env = Environment::GetCurrent(args);
1248
1249
  TLSWrap* wrap;
1250
1418
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1251
1252
1418
  CHECK_NOT_NULL(wrap->ssl_);
1253
1254
1418
  const char* servername = SSL_get_servername(wrap->ssl_.get(),
1255
                                              TLSEXT_NAMETYPE_host_name);
1256
1418
  if (servername != nullptr) {
1257
460
    args.GetReturnValue().Set(OneByteString(env->isolate(), servername));
1258
  } else {
1259
2376
    args.GetReturnValue().Set(false);
1260
  }
1261
}
1262
1263
249
void TLSWrap::SetServername(const FunctionCallbackInfo<Value>& args) {
1264
249
  Environment* env = Environment::GetCurrent(args);
1265
1266
  TLSWrap* wrap;
1267
249
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1268
1269
249
  CHECK_EQ(args.Length(), 1);
1270
498
  CHECK(args[0]->IsString());
1271
249
  CHECK(!wrap->started_);
1272
249
  CHECK(wrap->is_client());
1273
1274
249
  CHECK(wrap->ssl_);
1275
1276
747
  Utf8Value servername(env->isolate(), args[0].As<String>());
1277
249
  SSL_set_tlsext_host_name(wrap->ssl_.get(), *servername);
1278
}
1279
1280
981
int TLSWrap::SelectSNIContextCallback(SSL* s, int* ad, void* arg) {
1281
981
  TLSWrap* p = static_cast<TLSWrap*>(SSL_get_app_data(s));
1282
981
  Environment* env = p->env();
1283
1962
  HandleScope handle_scope(env->isolate());
1284
981
  Context::Scope context_scope(env->context());
1285
1286
981
  const char* servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
1287
981
  if (!Set(env, p->GetOwner(), env->servername_string(), servername))
1288
    return SSL_TLSEXT_ERR_NOACK;
1289
1290
2943
  Local<Value> ctx = p->object()->Get(env->context(), env->sni_context_string())
1291
981
      .FromMaybe(Local<Value>());
1292
1293

1962
  if (UNLIKELY(ctx.IsEmpty()) || !ctx->IsObject())
1294
981
    return SSL_TLSEXT_ERR_NOACK;
1295
1296
  if (!env->secure_context_constructor_template()->HasInstance(ctx)) {
1297
    // Failure: incorrect SNI context object
1298
    Local<Value> err = Exception::TypeError(env->sni_context_err_string());
1299
    p->MakeCallback(env->onerror_string(), 1, &err);
1300
    return SSL_TLSEXT_ERR_NOACK;
1301
  }
1302
1303
  SecureContext* sc = Unwrap<SecureContext>(ctx.As<Object>());
1304
  CHECK_NOT_NULL(sc);
1305
  p->sni_context_ = BaseObjectPtr<SecureContext>(sc);
1306
1307
  ConfigureSecureContext(sc);
1308
  CHECK_EQ(SSL_set_SSL_CTX(p->ssl_.get(), sc->ctx_.get()), sc->ctx_.get());
1309
  p->SetCACerts(sc);
1310
1311
  return SSL_TLSEXT_ERR_OK;
1312
}
1313
1314
11
int TLSWrap::SetCACerts(SecureContext* sc) {
1315
11
  int err = SSL_set1_verify_cert_store(
1316
      ssl_.get(), SSL_CTX_get_cert_store(sc->ctx_.get()));
1317
11
  if (err != 1)
1318
    return err;
1319
1320
  STACK_OF(X509_NAME)* list =
1321
11
      SSL_dup_CA_list(SSL_CTX_get_client_CA_list(sc->ctx_.get()));
1322
1323
  // NOTE: `SSL_set_client_CA_list` takes the ownership of `list`
1324
11
  SSL_set_client_CA_list(ssl_.get(), list);
1325
11
  return 1;
1326
}
1327
1328
#ifndef OPENSSL_NO_PSK
1329
1330
2
void TLSWrap::SetPskIdentityHint(const FunctionCallbackInfo<Value>& args) {
1331
  TLSWrap* p;
1332
2
  ASSIGN_OR_RETURN_UNWRAP(&p, args.Holder());
1333
2
  CHECK_NOT_NULL(p->ssl_);
1334
1335
2
  Environment* env = p->env();
1336
2
  Isolate* isolate = env->isolate();
1337
1338
4
  CHECK(args[0]->IsString());
1339
6
  Utf8Value hint(isolate, args[0].As<String>());
1340
1341
2
  if (!SSL_use_psk_identity_hint(p->ssl_.get(), *hint)) {
1342
1
    Local<Value> err = node::ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED(isolate);
1343
1
    p->MakeCallback(env->onerror_string(), 1, &err);
1344
  }
1345
}
1346
1347
20
void TLSWrap::EnablePskCallback(const FunctionCallbackInfo<Value>& args) {
1348
  TLSWrap* wrap;
1349
20
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1350
20
  CHECK_NOT_NULL(wrap->ssl_);
1351
1352
20
  SSL_set_psk_server_callback(wrap->ssl_.get(), PskServerCallback);
1353
20
  SSL_set_psk_client_callback(wrap->ssl_.get(), PskClientCallback);
1354
}
1355
1356
9
unsigned int TLSWrap::PskServerCallback(
1357
    SSL* s,
1358
    const char* identity,
1359
    unsigned char* psk,
1360
    unsigned int max_psk_len) {
1361
9
  TLSWrap* p = static_cast<TLSWrap*>(SSL_get_app_data(s));
1362
1363
9
  Environment* env = p->env();
1364
18
  HandleScope scope(env->isolate());
1365
1366
  Local<String> identity_str =
1367
18
      String::NewFromUtf8(env->isolate(), identity).FromMaybe(Local<String>());
1368
9
  if (UNLIKELY(identity_str.IsEmpty()))
1369
    return 0;
1370
1371
  // Make sure there are no utf8 replacement symbols.
1372
18
  Utf8Value identity_utf8(env->isolate(), identity_str);
1373
9
  if (strcmp(*identity_utf8, identity) != 0)
1374
    return 0;
1375
1376
  Local<Value> argv[] = {
1377
    identity_str,
1378
    Integer::NewFromUnsigned(env->isolate(), max_psk_len)
1379
9
  };
1380
1381
  Local<Value> psk_val =
1382
9
      p->MakeCallback(env->onpskexchange_symbol(), arraysize(argv), argv)
1383
9
          .FromMaybe(Local<Value>());
1384

18
  if (UNLIKELY(psk_val.IsEmpty()) || !psk_val->IsArrayBufferView())
1385
1
    return 0;
1386
1387
8
  ArrayBufferViewContents<char> psk_buf(psk_val);
1388
1389
8
  if (psk_buf.length() > max_psk_len)
1390
    return 0;
1391
1392
8
  memcpy(psk, psk_buf.data(), psk_buf.length());
1393
8
  return psk_buf.length();
1394
}
1395
1396
9
unsigned int TLSWrap::PskClientCallback(
1397
    SSL* s,
1398
    const char* hint,
1399
    char* identity,
1400
    unsigned int max_identity_len,
1401
    unsigned char* psk,
1402
    unsigned int max_psk_len) {
1403
9
  TLSWrap* p = static_cast<TLSWrap*>(SSL_get_app_data(s));
1404
1405
9
  Environment* env = p->env();
1406
18
  HandleScope scope(env->isolate());
1407
1408
  Local<Value> argv[] = {
1409
    Null(env->isolate()),
1410
    Integer::NewFromUnsigned(env->isolate(), max_psk_len),
1411
    Integer::NewFromUnsigned(env->isolate(), max_identity_len)
1412
27
  };
1413
1414
9
  if (hint != nullptr) {
1415
    Local<String> local_hint =
1416
2
        String::NewFromUtf8(env->isolate(), hint).FromMaybe(Local<String>());
1417
1
    if (UNLIKELY(local_hint.IsEmpty()))
1418
      return 0;
1419
1420
1
    argv[0] = local_hint;
1421
  }
1422
1423
  Local<Value> ret =
1424
9
      p->MakeCallback(env->onpskexchange_symbol(), arraysize(argv), argv)
1425
9
          .FromMaybe(Local<Value>());
1426

18
  if (UNLIKELY(ret.IsEmpty()) || !ret->IsObject())
1427
    return 0;
1428
1429
9
  Local<Object> obj = ret.As<Object>();
1430
1431
18
  Local<Value> psk_val = obj->Get(env->context(), env->psk_string())
1432
9
      .FromMaybe(Local<Value>());
1433

18
  if (UNLIKELY(psk_val.IsEmpty()) || !psk_val->IsArrayBufferView())
1434
    return 0;
1435
1436
9
  ArrayBufferViewContents<char> psk_buf(psk_val);
1437
9
  if (psk_buf.length() > max_psk_len)
1438
    return 0;
1439
1440
18
  Local<Value> identity_val = obj->Get(env->context(), env->identity_string())
1441
9
      .FromMaybe(Local<Value>());
1442

27
  if (UNLIKELY(identity_val.IsEmpty()) || !identity_val->IsString())
1443
    return 0;
1444
1445
18
  Utf8Value identity_buf(env->isolate(), identity_val);
1446
1447
9
  if (identity_buf.length() > max_identity_len)
1448
    return 0;
1449
1450
9
  memcpy(identity, *identity_buf, identity_buf.length());
1451
9
  memcpy(psk, psk_buf.data(), psk_buf.length());
1452
1453
9
  return psk_buf.length();
1454
}
1455
1456
#endif  // ifndef OPENSSL_NO_PSK
1457
1458
2
void TLSWrap::GetWriteQueueSize(const FunctionCallbackInfo<Value>& info) {
1459
  TLSWrap* wrap;
1460
2
  ASSIGN_OR_RETURN_UNWRAP(&wrap, info.This());
1461
1462
2
  if (!wrap->ssl_)
1463
    return info.GetReturnValue().Set(0);
1464
1465
2
  uint32_t write_queue_size = BIO_pending(wrap->enc_out_);
1466
4
  info.GetReturnValue().Set(write_queue_size);
1467
}
1468
1469
void TLSWrap::MemoryInfo(MemoryTracker* tracker) const {
1470
  tracker->TrackField("ocsp_response", ocsp_response_);
1471
  tracker->TrackField("sni_context", sni_context_);
1472
  tracker->TrackField("error", error_);
1473
  if (pending_cleartext_input_)
1474
    tracker->TrackField("pending_cleartext_input", pending_cleartext_input_);
1475
  if (enc_in_ != nullptr)
1476
    tracker->TrackField("enc_in", NodeBIO::FromBIO(enc_in_));
1477
  if (enc_out_ != nullptr)
1478
    tracker->TrackField("enc_out", NodeBIO::FromBIO(enc_out_));
1479
}
1480
1481
22
void TLSWrap::CertCbDone(const FunctionCallbackInfo<Value>& args) {
1482
22
  Environment* env = Environment::GetCurrent(args);
1483
  TLSWrap* w;
1484
24
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1485
1486

22
  CHECK(w->is_waiting_cert_cb() && w->cert_cb_running_);
1487
1488
22
  Local<Object> object = w->object();
1489
44
  Local<Value> ctx = object->Get(env->context(), env->sni_context_string())
1490
22
      .FromMaybe(Local<Value>());
1491
22
  if (UNLIKELY(ctx.IsEmpty()))
1492
    return;
1493
1494
22
  Local<FunctionTemplate> cons = env->secure_context_constructor_template();
1495
22
  if (cons->HasInstance(ctx)) {
1496
12
    SecureContext* sc = Unwrap<SecureContext>(ctx.As<Object>());
1497
12
    CHECK_NOT_NULL(sc);
1498
    // Store the SNI context for later use.
1499
12
    w->sni_context_ = BaseObjectPtr<SecureContext>(sc);
1500
1501


12
    if (UseSNIContext(w->ssl_, w->sni_context_) && !w->SetCACerts(sc)) {
1502
      // Not clear why sometimes we throw error, and sometimes we call
1503
      // onerror(). Both cause .destroy(), but onerror does a bit more.
1504
      unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
1505
      return ThrowCryptoError(env, err, "CertCbDone");
1506
    }
1507
10
  } else if (ctx->IsObject()) {
1508
    // Failure: incorrect SNI context object
1509
2
    Local<Value> err = Exception::TypeError(env->sni_context_err_string());
1510
2
    w->MakeCallback(env->onerror_string(), 1, &err);
1511
2
    return;
1512
  }
1513
1514
  CertCb cb;
1515
  void* arg;
1516
1517
20
  cb = w->cert_cb_;
1518
20
  arg = w->cert_cb_arg_;
1519
1520
20
  w->cert_cb_running_ = false;
1521
20
  w->cert_cb_ = nullptr;
1522
20
  w->cert_cb_arg_ = nullptr;
1523
1524
20
  cb(arg);
1525
}
1526
1527
240
void TLSWrap::SetALPNProtocols(const FunctionCallbackInfo<Value>& args) {
1528
  TLSWrap* w;
1529
240
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1530
240
  Environment* env = w->env();
1531

480
  if (args.Length() < 1 || !Buffer::HasInstance(args[0]))
1532
    return env->ThrowTypeError("Must give a Buffer as first argument");
1533
1534
240
  if (w->is_client()) {
1535
39
    CHECK(SetALPN(w->ssl_, args[0]));
1536
  } else {
1537

804
    CHECK(
1538
        w->object()->SetPrivate(
1539
            env->context(),
1540
            env->alpn_buffer_private_symbol(),
1541
            args[0]).FromJust());
1542
    // Server should select ALPN protocol from list of advertised by client
1543
201
    SSL_CTX_set_alpn_select_cb(SSL_get_SSL_CTX(w->ssl_.get()),
1544
                               SelectALPNCallback,
1545
                               nullptr);
1546
  }
1547
}
1548
1549
496
void TLSWrap::GetPeerCertificate(const FunctionCallbackInfo<Value>& args) {
1550
  TLSWrap* w;
1551
496
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1552
496
  Environment* env = w->env();
1553
1554

992
  bool abbreviated = args.Length() < 1 || !args[0]->IsTrue();
1555
1556
  Local<Value> ret;
1557
496
  if (GetPeerCert(
1558
          env,
1559
496
          w->ssl_,
1560
          abbreviated,
1561
992
          w->is_server()).ToLocal(&ret))
1562
992
    args.GetReturnValue().Set(ret);
1563
}
1564
1565
1
void TLSWrap::GetPeerX509Certificate(const FunctionCallbackInfo<Value>& args) {
1566
  TLSWrap* w;
1567
1
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1568
1
  Environment* env = w->env();
1569
1570
1
  X509Certificate::GetPeerCertificateFlag flag = w->is_server()
1571
1
      ? X509Certificate::GetPeerCertificateFlag::SERVER
1572
1
      : X509Certificate::GetPeerCertificateFlag::NONE;
1573
1574
  Local<Value> ret;
1575
2
  if (X509Certificate::GetPeerCert(env, w->ssl_, flag).ToLocal(&ret))
1576
2
    args.GetReturnValue().Set(ret);
1577
}
1578
1579
12
void TLSWrap::GetCertificate(const FunctionCallbackInfo<Value>& args) {
1580
  TLSWrap* w;
1581
12
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1582
12
  Environment* env = w->env();
1583
1584
  Local<Value> ret;
1585
24
  if (GetCert(env, w->ssl_).ToLocal(&ret))
1586
24
    args.GetReturnValue().Set(ret);
1587
}
1588
1589
1
void TLSWrap::GetX509Certificate(const FunctionCallbackInfo<Value>& args) {
1590
  TLSWrap* w;
1591
1
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1592
1
  Environment* env = w->env();
1593
  Local<Value> ret;
1594
2
  if (X509Certificate::GetCert(env, w->ssl_).ToLocal(&ret))
1595
2
    args.GetReturnValue().Set(ret);
1596
}
1597
1598
3
void TLSWrap::GetFinished(const FunctionCallbackInfo<Value>& args) {
1599
3
  Environment* env = Environment::GetCurrent(args);
1600
1601
  TLSWrap* w;
1602
4
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1603
1604
  // We cannot just pass nullptr to SSL_get_finished()
1605
  // because it would further be propagated to memcpy(),
1606
  // where the standard requirements as described in ISO/IEC 9899:2011
1607
  // sections 7.21.2.1, 7.21.1.2, and 7.1.4, would be violated.
1608
  // Thus, we use a dummy byte.
1609
  char dummy[1];
1610
3
  size_t len = SSL_get_finished(w->ssl_.get(), dummy, sizeof dummy);
1611
3
  if (len == 0)
1612
1
    return;
1613
1614
2
  AllocatedBuffer buf = AllocatedBuffer::AllocateManaged(env, len);
1615
2
  CHECK_EQ(len, SSL_get_finished(w->ssl_.get(), buf.data(), len));
1616
6
  args.GetReturnValue().Set(buf.ToBuffer().FromMaybe(Local<Value>()));
1617
}
1618
1619
3
void TLSWrap::GetPeerFinished(const FunctionCallbackInfo<Value>& args) {
1620
3
  Environment* env = Environment::GetCurrent(args);
1621
1622
  TLSWrap* w;
1623
4
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1624
1625
  // We cannot just pass nullptr to SSL_get_peer_finished()
1626
  // because it would further be propagated to memcpy(),
1627
  // where the standard requirements as described in ISO/IEC 9899:2011
1628
  // sections 7.21.2.1, 7.21.1.2, and 7.1.4, would be violated.
1629
  // Thus, we use a dummy byte.
1630
  char dummy[1];
1631
3
  size_t len = SSL_get_peer_finished(w->ssl_.get(), dummy, sizeof dummy);
1632
3
  if (len == 0)
1633
1
    return;
1634
1635
2
  AllocatedBuffer buf = AllocatedBuffer::AllocateManaged(env, len);
1636
2
  CHECK_EQ(len, SSL_get_peer_finished(w->ssl_.get(), buf.data(), len));
1637
6
  args.GetReturnValue().Set(buf.ToBuffer().FromMaybe(Local<Value>()));
1638
}
1639
1640
19
void TLSWrap::GetSession(const FunctionCallbackInfo<Value>& args) {
1641
19
  Environment* env = Environment::GetCurrent(args);
1642
1643
  TLSWrap* w;
1644
19
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1645
1646
19
  SSL_SESSION* sess = SSL_get_session(w->ssl_.get());
1647
19
  if (sess == nullptr)
1648
    return;
1649
1650
19
  int slen = i2d_SSL_SESSION(sess, nullptr);
1651
19
  if (slen <= 0)
1652
    return;  // Invalid or malformed session.
1653
1654
19
  AllocatedBuffer sbuf = AllocatedBuffer::AllocateManaged(env, slen);
1655
19
  unsigned char* p = reinterpret_cast<unsigned char*>(sbuf.data());
1656
19
  CHECK_LT(0, i2d_SSL_SESSION(sess, &p));
1657
57
  args.GetReturnValue().Set(sbuf.ToBuffer().FromMaybe(Local<Value>()));
1658
}
1659
1660
114
void TLSWrap::SetSession(const FunctionCallbackInfo<Value>& args) {
1661
114
  Environment* env = Environment::GetCurrent(args);
1662
1663
  TLSWrap* w;
1664
114
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1665
1666
114
  if (args.Length() < 1)
1667
    return THROW_ERR_MISSING_ARGS(env, "Session argument is mandatory");
1668
1669
114
  THROW_AND_RETURN_IF_NOT_BUFFER(env, args[0], "Session");
1670
114
  ArrayBufferViewContents<unsigned char> sbuf(args[0]);
1671
114
  SSLSessionPointer sess = GetTLSSession(sbuf.data(), sbuf.length());
1672
114
  if (sess == nullptr)
1673
    return;  // TODO(tniessen): figure out error handling
1674
1675
114
  if (!SetTLSSession(w->ssl_, sess))
1676
    return env->ThrowError("SSL_set_session error");
1677
}
1678
1679
521
void TLSWrap::IsSessionReused(const FunctionCallbackInfo<Value>& args) {
1680
  TLSWrap* w;
1681
521
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1682
521
  bool yes = SSL_session_reused(w->ssl_.get());
1683
1042
  args.GetReturnValue().Set(yes);
1684
}
1685
1686
960
void TLSWrap::VerifyError(const FunctionCallbackInfo<Value>& args) {
1687
960
  Environment* env = Environment::GetCurrent(args);
1688
  TLSWrap* w;
1689
1455
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1690
1691
  // XXX(bnoordhuis) The UNABLE_TO_GET_ISSUER_CERT error when there is no
1692
  // peer certificate is questionable but it's compatible with what was
1693
  // here before.
1694
  long x509_verify_error =  // NOLINT(runtime/int)
1695
960
      VerifyPeerCertificate(
1696
960
          w->ssl_,
1697
          X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT);
1698
1699
960
  if (x509_verify_error == X509_V_OK)
1700
990
    return args.GetReturnValue().SetNull();
1701
1702
465
  const char* reason = X509_verify_cert_error_string(x509_verify_error);
1703
465
  const char* code = X509ErrorCode(x509_verify_error);
1704
1705
  Local<Object> error =
1706
465
      Exception::Error(OneByteString(env->isolate(), reason))
1707
465
          ->ToObject(env->isolate()->GetCurrentContext())
1708
465
              .FromMaybe(Local<Object>());
1709
1710
465
  if (Set(env, error, env->code_string(), code))
1711
930
    args.GetReturnValue().Set(error);
1712
}
1713
1714
53
void TLSWrap::GetCipher(const FunctionCallbackInfo<Value>& args) {
1715
53
  Environment* env = Environment::GetCurrent(args);
1716
  TLSWrap* w;
1717
53
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1718
53
  args.GetReturnValue().Set(
1719
106
      GetCipherInfo(env, w->ssl_).FromMaybe(Local<Object>()));
1720
}
1721
1722
10
void TLSWrap::LoadSession(const FunctionCallbackInfo<Value>& args) {
1723
  TLSWrap* w;
1724
10
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1725
1726
  // TODO(@sam-github) check arg length and types in js, and CHECK in c++
1727

20
  if (args.Length() >= 1 && Buffer::HasInstance(args[0])) {
1728
10
    ArrayBufferViewContents<unsigned char> sbuf(args[0]);
1729
1730
10
    const unsigned char* p = sbuf.data();
1731
10
    SSL_SESSION* sess = d2i_SSL_SESSION(nullptr, &p, sbuf.length());
1732
1733
    // Setup next session and move hello to the BIO buffer
1734
10
    w->next_sess_.reset(sess);
1735
  }
1736
}
1737
1738
2
void TLSWrap::GetSharedSigalgs(const FunctionCallbackInfo<Value>& args) {
1739
2
  Environment* env = Environment::GetCurrent(args);
1740
  TLSWrap* w;
1741
2
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1742
1743
2
  SSL* ssl = w->ssl_.get();
1744
2
  int nsig = SSL_get_shared_sigalgs(ssl, 0, nullptr, nullptr, nullptr, nullptr,
1745
                                    nullptr);
1746
2
  MaybeStackBuffer<Local<Value>, 16> ret_arr(nsig);
1747
1748
5
  for (int i = 0; i < nsig; i++) {
1749
    int hash_nid;
1750
    int sign_nid;
1751
3
    std::string sig_with_md;
1752
1753
3
    SSL_get_shared_sigalgs(ssl, i, &sign_nid, &hash_nid, nullptr, nullptr,
1754
                           nullptr);
1755
1756

3
    switch (sign_nid) {
1757
      case EVP_PKEY_RSA:
1758
        sig_with_md = "RSA+";
1759
        break;
1760
1761
2
      case EVP_PKEY_RSA_PSS:
1762
2
        sig_with_md = "RSA-PSS+";
1763
2
        break;
1764
1765
      case EVP_PKEY_DSA:
1766
        sig_with_md = "DSA+";
1767
        break;
1768
1769
1
      case EVP_PKEY_EC:
1770
1
        sig_with_md = "ECDSA+";
1771
1
        break;
1772
1773
      case NID_ED25519:
1774
        sig_with_md = "Ed25519+";
1775
        break;
1776
1777
      case NID_ED448:
1778
        sig_with_md = "Ed448+";
1779
        break;
1780
#ifndef OPENSSL_NO_GOST
1781
      case NID_id_GostR3410_2001:
1782
        sig_with_md = "gost2001+";
1783
        break;
1784
1785
      case NID_id_GostR3410_2012_256:
1786
        sig_with_md = "gost2012_256+";
1787
        break;
1788
1789
      case NID_id_GostR3410_2012_512:
1790
        sig_with_md = "gost2012_512+";
1791
        break;
1792
#endif  // !OPENSSL_NO_GOST
1793
      default:
1794
        const char* sn = OBJ_nid2sn(sign_nid);
1795
1796
        if (sn != nullptr) {
1797
          sig_with_md = std::string(sn) + "+";
1798
        } else {
1799
          sig_with_md = "UNDEF+";
1800
        }
1801
        break;
1802
    }
1803
1804
3
    const char* sn_hash = OBJ_nid2sn(hash_nid);
1805
3
    if (sn_hash != nullptr) {
1806
3
      sig_with_md += std::string(sn_hash);
1807
    } else {
1808
      sig_with_md += "UNDEF";
1809
    }
1810
6
    ret_arr[i] = OneByteString(env->isolate(), sig_with_md.c_str());
1811
  }
1812
1813
4
  args.GetReturnValue().Set(
1814
                 Array::New(env->isolate(), ret_arr.out(), ret_arr.length()));
1815
}
1816
1817
3
void TLSWrap::ExportKeyingMaterial(const FunctionCallbackInfo<Value>& args) {
1818
3
  CHECK(args[0]->IsInt32());
1819
6
  CHECK(args[1]->IsString());
1820
1821
3
  Environment* env = Environment::GetCurrent(args);
1822
  TLSWrap* w;
1823
3
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1824
1825
6
  uint32_t olen = args[0].As<Uint32>()->Value();
1826
3
  Utf8Value label(env->isolate(), args[1]);
1827
1828
3
  AllocatedBuffer out = AllocatedBuffer::AllocateManaged(env, olen);
1829
1830
3
  ByteSource context;
1831
3
  bool use_context = !args[2]->IsUndefined();
1832
3
  if (use_context)
1833
2
    context = ByteSource::FromBuffer(args[2]);
1834
1835
9
  if (SSL_export_keying_material(
1836
3
          w->ssl_.get(),
1837
3
          reinterpret_cast<unsigned char*>(out.data()),
1838
          olen,
1839
3
          *label,
1840
          label.length(),
1841
3
          reinterpret_cast<const unsigned char*>(context.get()),
1842
          context.size(),
1843
3
          use_context) != 1) {
1844
    return ThrowCryptoError(
1845
         env,
1846
         ERR_get_error(),
1847
         "SSL_export_keying_material");
1848
  }
1849
1850
9
  args.GetReturnValue().Set(out.ToBuffer().FromMaybe(Local<Value>()));
1851
}
1852
1853
19
void TLSWrap::EndParser(const FunctionCallbackInfo<Value>& args) {
1854
  TLSWrap* w;
1855
19
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1856
19
  w->hello_parser_.End();
1857
}
1858
1859
92
void TLSWrap::Renegotiate(const FunctionCallbackInfo<Value>& args) {
1860
  TLSWrap* w;
1861
93
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1862
  ClearErrorOnReturn clear_error_on_return;
1863
92
  if (SSL_renegotiate(w->ssl_.get()) != 1)
1864
1
    return ThrowCryptoError(w->env(), ERR_get_error());
1865
}
1866
1867
18
void TLSWrap::GetTLSTicket(const FunctionCallbackInfo<Value>& args) {
1868
  TLSWrap* w;
1869
18
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1870
18
  Environment* env = w->env();
1871
1872
18
  SSL_SESSION* sess = SSL_get_session(w->ssl_.get());
1873
18
  if (sess == nullptr)
1874
    return;
1875
1876
  const unsigned char* ticket;
1877
  size_t length;
1878
18
  SSL_SESSION_get0_ticket(sess, &ticket, &length);
1879
1880
18
  if (ticket != nullptr) {
1881
18
    args.GetReturnValue().Set(
1882
36
        Buffer::Copy(env, reinterpret_cast<const char*>(ticket), length)
1883
            .FromMaybe(Local<Object>()));
1884
  }
1885
}
1886
1887
8
void TLSWrap::NewSessionDone(const FunctionCallbackInfo<Value>& args) {
1888
  TLSWrap* w;
1889
8
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1890
8
  w->awaiting_new_session_ = false;
1891
8
  w->NewSessionDoneCb();
1892
}
1893
1894
2
void TLSWrap::SetOCSPResponse(const FunctionCallbackInfo<Value>& args) {
1895
  TLSWrap* w;
1896
2
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1897
2
  Environment* env = w->env();
1898
1899
2
  if (args.Length() < 1)
1900
    return THROW_ERR_MISSING_ARGS(env, "OCSP response argument is mandatory");
1901
1902
2
  THROW_AND_RETURN_IF_NOT_BUFFER(env, args[0], "OCSP response");
1903
1904
8
  w->ocsp_response_.Reset(args.GetIsolate(), args[0].As<ArrayBufferView>());
1905
}
1906
1907
4
void TLSWrap::RequestOCSP(const FunctionCallbackInfo<Value>& args) {
1908
  TLSWrap* w;
1909
4
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1910
1911
4
  SSL_set_tlsext_status_type(w->ssl_.get(), TLSEXT_STATUSTYPE_ocsp);
1912
}
1913
1914
894
void TLSWrap::GetEphemeralKeyInfo(const FunctionCallbackInfo<Value>& args) {
1915
  TLSWrap* w;
1916
901
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1917
894
  Environment* env = Environment::GetCurrent(args);
1918
1919
894
  CHECK(w->ssl_);
1920
1921
  // tmp key is available on only client
1922
894
  if (w->is_server())
1923
14
    return args.GetReturnValue().SetNull();
1924
1925
2661
  args.GetReturnValue().Set(GetEphemeralKey(env, w->ssl_)
1926
      .FromMaybe(Local<Value>()));
1927
1928
  // TODO(@sam-github) semver-major: else return ThrowCryptoError(env,
1929
  // ERR_get_error())
1930
}
1931
1932
547
void TLSWrap::GetProtocol(const FunctionCallbackInfo<Value>& args) {
1933
547
  Environment* env = Environment::GetCurrent(args);
1934
  TLSWrap* w;
1935
547
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1936
1094
  args.GetReturnValue().Set(
1937
547
      OneByteString(env->isolate(), SSL_get_version(w->ssl_.get())));
1938
}
1939
1940
1794
void TLSWrap::GetALPNNegotiatedProto(const FunctionCallbackInfo<Value>& args) {
1941
1794
  Environment* env = Environment::GetCurrent(args);
1942
  TLSWrap* w;
1943
1794
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1944
1945
  const unsigned char* alpn_proto;
1946
  unsigned int alpn_proto_len;
1947
1948
1794
  SSL_get0_alpn_selected(w->ssl_.get(), &alpn_proto, &alpn_proto_len);
1949
1950
  Local<Value> result;
1951
1794
  if (alpn_proto_len == 0) {
1952
3466
    result = False(env->isolate());
1953
61
  } else if (alpn_proto_len == sizeof("h2") - 1 &&
1954
55
             0 == memcmp(alpn_proto, "h2", sizeof("h2") - 1)) {
1955
110
    result = env->h2_string();
1956
6
  } else if (alpn_proto_len == sizeof("http/1.1") - 1 &&
1957
2
             0 == memcmp(alpn_proto, "http/1.1", sizeof("http/1.1") - 1)) {
1958
4
    result = env->http_1_1_string();
1959
  } else {
1960
8
    result = OneByteString(env->isolate(), alpn_proto, alpn_proto_len);
1961
  }
1962
1963
3588
  args.GetReturnValue().Set(result);
1964
}
1965
1966
6355
void TLSWrap::Cycle() {
1967
  // Prevent recursion
1968
6355
  if (++cycle_depth_ > 1)
1969
14
    return;
1970
1971
12694
  for (; cycle_depth_ > 0; cycle_depth_--) {
1972
6355
    ClearIn();
1973
6355
    ClearOut();
1974
    // EncIn() doesn't exist, it happens via stream listener callbacks.
1975
6354
    EncOut();
1976
  }
1977
}
1978
1979
#ifdef SSL_set_max_send_fragment
1980
3
void TLSWrap::SetMaxSendFragment(const FunctionCallbackInfo<Value>& args) {
1981

6
  CHECK(args.Length() >= 1 && args[0]->IsNumber());
1982
3
  Environment* env = Environment::GetCurrent(args);
1983
  TLSWrap* w;
1984
3
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1985
6
  int rv = SSL_set_max_send_fragment(
1986
      w->ssl_.get(),
1987
      args[0]->Int32Value(env->context()).FromJust());
1988
6
  args.GetReturnValue().Set(rv);
1989
}
1990
#endif  // SSL_set_max_send_fragment
1991
1992
541
void TLSWrap::Initialize(
1993
    Local<Object> target,
1994
    Local<Value> unused,
1995
    Local<Context> context,
1996
    void* priv) {
1997
541
  Environment* env = Environment::GetCurrent(context);
1998
1999
541
  env->SetMethod(target, "wrap", TLSWrap::Wrap);
2000
2001
1082
  NODE_DEFINE_CONSTANT(target, HAVE_SSL_TRACE);
2002
2003
541
  Local<FunctionTemplate> t = BaseObject::MakeLazilyInitializedJSTemplate(env);
2004
  Local<String> tlsWrapString =
2005
541
      FIXED_ONE_BYTE_STRING(env->isolate(), "TLSWrap");
2006
541
  t->SetClassName(tlsWrapString);
2007
1082
  t->InstanceTemplate()->SetInternalFieldCount(StreamBase::kInternalFieldCount);
2008
2009
  Local<FunctionTemplate> get_write_queue_size =
2010
      FunctionTemplate::New(env->isolate(),
2011
                            GetWriteQueueSize,
2012
                            Local<Value>(),
2013
541
                            Signature::New(env->isolate(), t));
2014
2164
  t->PrototypeTemplate()->SetAccessorProperty(
2015
      env->write_queue_size_string(),
2016
      get_write_queue_size,
2017
      Local<FunctionTemplate>(),
2018
      static_cast<PropertyAttribute>(ReadOnly | DontDelete));
2019
2020
541
  t->Inherit(AsyncWrap::GetConstructorTemplate(env));
2021
2022
541
  env->SetProtoMethod(t, "certCbDone", CertCbDone);
2023
541
  env->SetProtoMethod(t, "destroySSL", DestroySSL);
2024
541
  env->SetProtoMethod(t, "enableCertCb", EnableCertCb);
2025
541
  env->SetProtoMethod(t, "endParser", EndParser);
2026
541
  env->SetProtoMethod(t, "enableKeylogCallback", EnableKeylogCallback);
2027
541
  env->SetProtoMethod(t, "enableSessionCallbacks", EnableSessionCallbacks);
2028
541
  env->SetProtoMethod(t, "enableTrace", EnableTrace);
2029
541
  env->SetProtoMethod(t, "getServername", GetServername);
2030
541
  env->SetProtoMethod(t, "loadSession", LoadSession);
2031
541
  env->SetProtoMethod(t, "newSessionDone", NewSessionDone);
2032
541
  env->SetProtoMethod(t, "receive", Receive);
2033
541
  env->SetProtoMethod(t, "renegotiate", Renegotiate);
2034
541
  env->SetProtoMethod(t, "requestOCSP", RequestOCSP);
2035
541
  env->SetProtoMethod(t, "setALPNProtocols", SetALPNProtocols);
2036
541
  env->SetProtoMethod(t, "setOCSPResponse", SetOCSPResponse);
2037
541
  env->SetProtoMethod(t, "setServername", SetServername);
2038
541
  env->SetProtoMethod(t, "setSession", SetSession);
2039
541
  env->SetProtoMethod(t, "setVerifyMode", SetVerifyMode);
2040
541
  env->SetProtoMethod(t, "start", Start);
2041
2042
541
  env->SetProtoMethodNoSideEffect(t, "exportKeyingMaterial",
2043
                                  ExportKeyingMaterial);
2044
541
  env->SetProtoMethodNoSideEffect(t, "isSessionReused", IsSessionReused);
2045
541
  env->SetProtoMethodNoSideEffect(t, "getALPNNegotiatedProtocol",
2046
                                  GetALPNNegotiatedProto);
2047
541
  env->SetProtoMethodNoSideEffect(t, "getCertificate", GetCertificate);
2048
541
  env->SetProtoMethodNoSideEffect(t, "getX509Certificate", GetX509Certificate);
2049
541
  env->SetProtoMethodNoSideEffect(t, "getCipher", GetCipher);
2050
541
  env->SetProtoMethodNoSideEffect(t, "getEphemeralKeyInfo",
2051
                                  GetEphemeralKeyInfo);
2052
541
  env->SetProtoMethodNoSideEffect(t, "getFinished", GetFinished);
2053
541
  env->SetProtoMethodNoSideEffect(t, "getPeerCertificate", GetPeerCertificate);
2054
541
  env->SetProtoMethodNoSideEffect(t, "getPeerX509Certificate",
2055
                                  GetPeerX509Certificate);
2056
541
  env->SetProtoMethodNoSideEffect(t, "getPeerFinished", GetPeerFinished);
2057
541
  env->SetProtoMethodNoSideEffect(t, "getProtocol", GetProtocol);
2058
541
  env->SetProtoMethodNoSideEffect(t, "getSession", GetSession);
2059
541
  env->SetProtoMethodNoSideEffect(t, "getSharedSigalgs", GetSharedSigalgs);
2060
541
  env->SetProtoMethodNoSideEffect(t, "getTLSTicket", GetTLSTicket);
2061
541
  env->SetProtoMethodNoSideEffect(t, "verifyError", VerifyError);
2062
2063
#ifdef SSL_set_max_send_fragment
2064
541
  env->SetProtoMethod(t, "setMaxSendFragment", SetMaxSendFragment);
2065
#endif  // SSL_set_max_send_fragment
2066
2067
#ifndef OPENSSL_NO_PSK
2068
541
  env->SetProtoMethod(t, "enablePskCallback", EnablePskCallback);
2069
541
  env->SetProtoMethod(t, "setPskIdentityHint", SetPskIdentityHint);
2070
#endif  // !OPENSSL_NO_PSK
2071
2072
541
  StreamBase::AddMethods(env, t);
2073
2074
541
  Local<Function> fn = t->GetFunction(env->context()).ToLocalChecked();
2075
2076
541
  env->set_tls_wrap_constructor_function(fn);
2077
2078
541
  target->Set(env->context(), tlsWrapString, fn).Check();
2079
541
}
2080
2081
4973
void TLSWrap::RegisterExternalReferences(ExternalReferenceRegistry* registry) {
2082
4973
  registry->Register(TLSWrap::Wrap);
2083
4973
  registry->Register(GetWriteQueueSize);
2084
2085
4973
  registry->Register(CertCbDone);
2086
4973
  registry->Register(DestroySSL);
2087
4973
  registry->Register(EnableCertCb);
2088
4973
  registry->Register(EndParser);
2089
4973
  registry->Register(EnableKeylogCallback);
2090
4973
  registry->Register(EnableSessionCallbacks);
2091
4973
  registry->Register(EnableTrace);
2092
4973
  registry->Register(GetServername);
2093
4973
  registry->Register(LoadSession);
2094
4973
  registry->Register(NewSessionDone);
2095
4973
  registry->Register(Receive);
2096
4973
  registry->Register(Renegotiate);
2097
4973
  registry->Register(RequestOCSP);
2098
4973
  registry->Register(SetALPNProtocols);
2099
4973
  registry->Register(SetOCSPResponse);
2100
4973
  registry->Register(SetServername);
2101
4973
  registry->Register(SetSession);
2102
4973
  registry->Register(SetVerifyMode);
2103
4973
  registry->Register(Start);
2104
4973
  registry->Register(ExportKeyingMaterial);
2105
4973
  registry->Register(IsSessionReused);
2106
4973
  registry->Register(GetALPNNegotiatedProto);
2107
4973
  registry->Register(GetCertificate);
2108
4973
  registry->Register(GetX509Certificate);
2109
4973
  registry->Register(GetCipher);
2110
4973
  registry->Register(GetEphemeralKeyInfo);
2111
4973
  registry->Register(GetFinished);
2112
4973
  registry->Register(GetPeerCertificate);
2113
4973
  registry->Register(GetPeerX509Certificate);
2114
4973
  registry->Register(GetPeerFinished);
2115
4973
  registry->Register(GetProtocol);
2116
4973
  registry->Register(GetSession);
2117
4973
  registry->Register(GetSharedSigalgs);
2118
4973
  registry->Register(GetTLSTicket);
2119
4973
  registry->Register(VerifyError);
2120
2121
#ifdef SSL_set_max_send_fragment
2122
4973
  registry->Register(SetMaxSendFragment);
2123
#endif  // SSL_set_max_send_fragment
2124
2125
#ifndef OPENSSL_NO_PSK
2126
4973
  registry->Register(EnablePskCallback);
2127
4973
  registry->Register(SetPskIdentityHint);
2128
#endif  // !OPENSSL_NO_PSK
2129
4973
}
2130
2131
}  // namespace crypto
2132
}  // namespace node
2133
2134
5034
NODE_MODULE_CONTEXT_AWARE_INTERNAL(tls_wrap, node::crypto::TLSWrap::Initialize)
2135
4973
NODE_MODULE_EXTERNAL_REFERENCE(
2136
    tls_wrap, node::crypto::TLSWrap::RegisterExternalReferences)