GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: crypto/crypto_tls.cc Lines: 989 1082 91.4 %
Date: 2021-10-05 04:12:38 Branches: 433 655 66.1 %

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::ArrayBufferView;
41
using v8::Context;
42
using v8::DontDelete;
43
using v8::EscapableHandleScope;
44
using v8::Exception;
45
using v8::False;
46
using v8::Function;
47
using v8::FunctionCallbackInfo;
48
using v8::FunctionTemplate;
49
using v8::HandleScope;
50
using v8::Integer;
51
using v8::Isolate;
52
using v8::Local;
53
using v8::MaybeLocal;
54
using v8::Null;
55
using v8::Object;
56
using v8::PropertyAttribute;
57
using v8::ReadOnly;
58
using v8::Signature;
59
using v8::String;
60
using v8::True;
61
using v8::Uint32;
62
using v8::Value;
63
64
namespace crypto {
65
66
namespace {
67
99
SSL_SESSION* GetSessionCallback(
68
    SSL* s,
69
    const unsigned char* key,
70
    int len,
71
    int* copy) {
72
99
  TLSWrap* w = static_cast<TLSWrap*>(SSL_get_app_data(s));
73
99
  *copy = 0;
74
99
  return w->ReleaseSession();
75
}
76
77
20
void OnClientHello(
78
    void* arg,
79
    const ClientHelloParser::ClientHello& hello) {
80
20
  TLSWrap* w = static_cast<TLSWrap*>(arg);
81
20
  Environment* env = w->env();
82
20
  HandleScope handle_scope(env->isolate());
83
20
  Context::Scope context_scope(env->context());
84
85
20
  Local<Object> hello_obj = Object::New(env->isolate());
86
20
  Local<String> servername = (hello.servername() == nullptr)
87
4
      ? String::Empty(env->isolate())
88
      : OneByteString(env->isolate(),
89
                      hello.servername(),
90
20
                      hello.servername_size());
91
  Local<Object> buf =
92
20
      Buffer::Copy(
93
          env,
94
20
          reinterpret_cast<const char*>(hello.session_id()),
95
40
          hello.session_size()).FromMaybe(Local<Object>());
96
97
60
  if ((buf.IsEmpty() ||
98
40
       hello_obj->Set(env->context(), env->session_id_string(), buf)
99
20
          .IsNothing()) ||
100
40
      hello_obj->Set(env->context(), env->servername_string(), servername)
101

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

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

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

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

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

12246
  Kind kind = args[2]->IsTrue() ? Kind::kServer : Kind::kClient;
444
445
24492
  StreamBase* stream = StreamBase::FromObject(args[0].As<Object>());
446
12246
  CHECK_NOT_NULL(stream);
447
448
  Local<Object> obj;
449
12246
  if (!env->tls_wrap_constructor_function()
450
12246
           ->NewInstance(env->context())
451
12246
           .ToLocal(&obj)) {
452
    return;
453
  }
454
455
12246
  TLSWrap* res = new TLSWrap(env, obj, kind, stream, Unwrap<SecureContext>(sc));
456
457
24492
  args.GetReturnValue().Set(res->object());
458
}
459
460
3
void TLSWrap::Receive(const FunctionCallbackInfo<Value>& args) {
461
  TLSWrap* wrap;
462
3
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
463
464
3
  ArrayBufferViewContents<char> buffer(args[0]);
465
3
  const char* data = buffer.data();
466
3
  size_t len = buffer.length();
467
3
  Debug(wrap, "Receiving %zu bytes injected from JS", len);
468
469
  // Copy given buffer entirely or partiall if handle becomes closed
470


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

4754
            .ToLocal(&callback) && callback->IsFunction()) {
518
2377
      Local<Value> argv[] = { env->GetNow() };
519
4754
      c->MakeCallback(callback.As<Function>(), arraysize(argv), argv);
520
    }
521
  }
522
523
  // SSL_CB_HANDSHAKE_START and SSL_CB_HANDSHAKE_DONE are called
524
  // sending HelloRequest in OpenSSL-1.1.1.
525
  // We need to check whether this is in a renegotiation state or not.
526

4048
  if (where & SSL_CB_HANDSHAKE_DONE && !SSL_renegotiate_pending(ssl)) {
527
    Debug(c, "SSLInfoCallback(SSL_CB_HANDSHAKE_DONE);");
528
1670
    CHECK(!SSL_renegotiate_pending(ssl));
529
    Local<Value> callback;
530
531
1670
    c->established_ = true;
532
533
3340
    if (object->Get(env->context(), env->onhandshakedone_string())
534

3340
          .ToLocal(&callback) && callback->IsFunction()) {
535
3340
      c->MakeCallback(callback.As<Function>(), 0, nullptr);
536
    }
537
  }
538
}
539
540
19038
void TLSWrap::EncOut() {
541
19038
  Debug(this, "Trying to write encrypted output");
542
543
  // Ignore cycling data if ClientHello wasn't yet parsed
544
19038
  if (!hello_parser_.IsEnded()) {
545
1
    Debug(this, "Returning from EncOut(), hello_parser_ active");
546
11936
    return;
547
  }
548
549
  // Write in progress
550
19037
  if (write_size_ != 0) {
551
3544
    Debug(this, "Returning from EncOut(), write currently in progress");
552
3544
    return;
553
  }
554
555
  // Wait for `newSession` callback to be invoked
556
15493
  if (is_awaiting_new_session()) {
557
7
    Debug(this, "Returning from EncOut(), awaiting new session");
558
7
    return;
559
  }
560
561
  // Split-off queue
562

15486
  if (established_ && current_write_) {
563
5050
    Debug(this, "EncOut() write is scheduled");
564
5050
    write_callback_scheduled_ = true;
565
  }
566
567
15486
  if (ssl_ == nullptr) {
568
2
    Debug(this, "Returning from EncOut(), ssl_ == nullptr");
569
2
    return;
570
  }
571
572
  // No encrypted output ready to write to the underlying stream.
573
15484
  if (BIO_pending(enc_out_) == 0) {
574
8255
    Debug(this, "No pending encrypted output");
575
8255
    if (pending_cleartext_input_.size() == 0) {
576
8059
      if (!in_dowrite_) {
577
7998
        Debug(this, "No pending cleartext input, not inside DoWrite()");
578
7998
        InvokeQueued(0);
579
      } else {
580
61
        Debug(this, "No pending cleartext input, inside DoWrite()");
581
        // TODO(@sam-github, @addaleax) If in_dowrite_ is true, appdata was
582
        // passed to SSL_write().  If we are here, the data was not encrypted to
583
        // enc_out_ yet.  Calling Done() "works", but since the write is not
584
        // flushed, its too soon.  Just returning and letting the next EncOut()
585
        // call Done() passes the test suite, but without more careful analysis,
586
        // its not clear if it is always correct. Not calling Done() could block
587
        // data flow, so for now continue to call Done(), just do it in the next
588
        // tick.
589
61
        BaseObjectPtr<TLSWrap> strong_ref{this};
590
61
        env()->SetImmediate([this, strong_ref](Environment* env) {
591
61
          InvokeQueued(0);
592
61
        });
593
      }
594
    }
595
8255
    return;
596
  }
597
598
  char* data[kSimultaneousBufferCount];
599
  size_t size[arraysize(data)];
600
7229
  size_t count = arraysize(data);
601
7229
  write_size_ = NodeBIO::FromBIO(enc_out_)->PeekMultiple(data, size, &count);
602

7229
  CHECK(write_size_ != 0 && count != 0);
603
604
  uv_buf_t buf[arraysize(data)];
605
7229
  uv_buf_t* bufs = buf;
606
14594
  for (size_t i = 0; i < count; i++)
607
7365
    buf[i] = uv_buf_init(data[i], size[i]);
608
609
7229
  Debug(this, "Writing %zu buffers to the underlying stream", count);
610
7229
  StreamWriteResult res = underlying_stream()->Write(bufs, count);
611
7228
  if (res.err != 0) {
612
127
    InvokeQueued(res.err);
613
127
    return;
614
  }
615
616
7101
  if (!res.async) {
617
6542
    Debug(this, "Write finished synchronously");
618
13084
    HandleScope handle_scope(env()->isolate());
619
620
    // Simulate asynchronous finishing, TLS cannot handle this at the moment.
621
6542
    BaseObjectPtr<TLSWrap> strong_ref{this};
622
6542
    env()->SetImmediate([this, strong_ref](Environment* env) {
623
6542
      OnStreamAfterWrite(nullptr, 0);
624
6542
    });
625
  }
626
}
627
628
7200
void TLSWrap::OnStreamAfterWrite(WriteWrap* req_wrap, int status) {
629
7200
  Debug(this, "OnStreamAfterWrite(status = %d)", status);
630
7200
  if (current_empty_write_) {
631
100
    Debug(this, "Had empty write");
632
    BaseObjectPtr<AsyncWrap> current_empty_write =
633
100
        std::move(current_empty_write_);
634
100
    current_empty_write_.reset();
635
100
    WriteWrap* finishing = WriteWrap::FromObject(current_empty_write);
636
100
    finishing->Done(status);
637
100
    return;
638
  }
639
640
7100
  if (ssl_ == nullptr) {
641
    Debug(this, "ssl_ == nullptr, marking as cancelled");
642
    status = UV_ECANCELED;
643
  }
644
645
  // Handle error
646
7100
  if (status) {
647
3
    if (shutdown_) {
648
1
      Debug(this, "Ignoring error after shutdown");
649
1
      return;
650
    }
651
652
    // Notify about error
653
2
    InvokeQueued(status);
654
2
    return;
655
  }
656
657
  // Commit
658
7097
  NodeBIO::FromBIO(enc_out_)->Read(nullptr, write_size_);
659
660
  // Ensure that the progress will be made and `InvokeQueued` will be called.
661
7097
  ClearIn();
662
663
  // Try writing more data
664
7097
  write_size_ = 0;
665
7097
  EncOut();
666
}
667
668
8180
MaybeLocal<Value> TLSWrap::GetSSLError(int status, int* err, std::string* msg) {
669
8180
  EscapableHandleScope scope(env()->isolate());
670
671
  // ssl_ is already destroyed in reading EOF by close notify alert.
672
8180
  if (ssl_ == nullptr)
673
    return MaybeLocal<Value>();
674
675
8180
  *err = SSL_get_error(ssl_.get(), status);
676

8180
  switch (*err) {
677
6407
    case SSL_ERROR_NONE:
678
    case SSL_ERROR_WANT_READ:
679
    case SSL_ERROR_WANT_WRITE:
680
    case SSL_ERROR_WANT_X509_LOOKUP:
681
6407
      return MaybeLocal<Value>();
682
683
1135
    case SSL_ERROR_ZERO_RETURN:
684
2270
      return scope.Escape(env()->zero_return_string());
685
686
638
    case SSL_ERROR_SSL:
687
    case SSL_ERROR_SYSCALL:
688
      {
689
638
        unsigned long ssl_err = ERR_peek_error();  // NOLINT(runtime/int)
690
638
        BIO* bio = BIO_new(BIO_s_mem());
691
638
        ERR_print_errors(bio);
692
693
        BUF_MEM* mem;
694
638
        BIO_get_mem_ptr(bio, &mem);
695
696
638
        Isolate* isolate = env()->isolate();
697
638
        Local<Context> context = isolate->GetCurrentContext();
698
699
638
        Local<String> message = OneByteString(isolate, mem->data, mem->length);
700
638
        Local<Value> exception = Exception::Error(message);
701
        Local<Object> obj =
702
1276
            exception->ToObject(context).FromMaybe(Local<Object>());
703
638
        if (UNLIKELY(obj.IsEmpty()))
704
          return MaybeLocal<Value>();
705
706
638
        const char* ls = ERR_lib_error_string(ssl_err);
707
638
        const char* fs = ERR_func_error_string(ssl_err);
708
638
        const char* rs = ERR_reason_error_string(ssl_err);
709
710

1276
        if (!Set(env(), obj, env()->library_string(), ls) ||
711
638
            !Set(env(), obj, env()->function_string(), fs)) {
712
          return MaybeLocal<Value>();
713
        }
714
715
638
        if (rs != nullptr) {
716
634
          if (!Set(env(), obj, env()->reason_string(), rs))
717
            return MaybeLocal<Value>();
718
719
          // SSL has no API to recover the error name from the number, so we
720
          // transform reason strings like "this error" to "ERR_SSL_THIS_ERROR",
721
          // which ends up being close to the original error macro name.
722
634
          std::string code(rs);
723
724
13725
          for (auto& c : code)
725
13091
            c = (c == ' ') ? '_' : ToUpper(c);
726
727
634
          if (!Set(env(), obj,
728
                   env()->code_string(),
729
1268
                   ("ERR_SSL_" + code).c_str())) {
730
            return MaybeLocal<Value>();
731
          }
732
        }
733
734
638
        if (msg != nullptr)
735
5
          msg->assign(mem->data, mem->data + mem->length);
736
737
638
        BIO_free_all(bio);
738
739
638
        return scope.Escape(exception);
740
      }
741
742
    default:
743
      UNREACHABLE();
744
  }
745
  UNREACHABLE();
746
}
747
748
7790
void TLSWrap::ClearOut() {
749
7790
  Debug(this, "Trying to read cleartext output");
750
  // Ignore cycling data if ClientHello wasn't yet parsed
751
7790
  if (!hello_parser_.IsEnded()) {
752
1
    Debug(this, "Returning from ClearOut(), hello_parser_ active");
753
1141
    return;
754
  }
755
756
  // No reads after EOF
757
7789
  if (eof_) {
758
3
    Debug(this, "Returning from ClearOut(), EOF reached");
759
3
    return;
760
  }
761
762
7786
  if (ssl_ == nullptr) {
763
1
    Debug(this, "Returning from ClearOut(), ssl_ == nullptr");
764
1
    return;
765
  }
766
767
7785
  MarkPopErrorOnReturn mark_pop_error_on_return;
768
769
  char out[kClearOutChunkSize];
770
  int read;
771
  for (;;) {
772
10892
    read = SSL_read(ssl_.get(), out, sizeof(out));
773
10892
    Debug(this, "Read %d bytes of cleartext output", read);
774
775
10892
    if (read <= 0)
776
7783
      break;
777
778
3109
    char* current = out;
779
8270
    while (read > 0) {
780
5163
      int avail = read;
781
782
5163
      uv_buf_t buf = EmitAlloc(avail);
783
5163
      if (static_cast<int>(buf.len) < avail)
784
2054
        avail = buf.len;
785
5163
      memcpy(buf.base, current, avail);
786
5163
      EmitRead(avail, buf);
787
788
      // Caveat emptor: OnRead() calls into JS land which can result in
789
      // the SSL context object being destroyed.  We have to carefully
790
      // check that ssl_ != nullptr afterwards.
791
5162
      if (ssl_ == nullptr) {
792
1
        Debug(this, "Returning from read loop, ssl_ == nullptr");
793
1
        return;
794
      }
795
796
5161
      read -= avail;
797
5161
      current += avail;
798
    }
799
3107
  }
800
801
7783
  int flags = SSL_get_shutdown(ssl_.get());
802

7783
  if (!eof_ && flags & SSL_RECEIVED_SHUTDOWN) {
803
1192
    eof_ = true;
804
1192
    EmitRead(UV_EOF);
805
  }
806
807
  // We need to check whether an error occurred or the connection was
808
  // shutdown cleanly (SSL_ERROR_ZERO_RETURN) even when read == 0.
809
  // See node#1642 and SSL_read(3SSL) for details.
810
7783
  if (read <= 0) {
811
7783
    HandleScope handle_scope(env()->isolate());
812
    int err;
813
814
7783
    Local<Value> arg = GetSSLError(read, &err, nullptr)
815
7783
        .FromMaybe(Local<Value>());
816
817
    // Ignore ZERO_RETURN after EOF, it is basically not a error
818

7783
    if (err == SSL_ERROR_ZERO_RETURN && eof_)
819
1135
      return;
820
821
6648
    if (LIKELY(!arg.IsEmpty())) {
822
633
      Debug(this, "Got SSL error (%d), calling onerror", err);
823
      // When TLS Alert are stored in wbio,
824
      // it should be flushed to socket before destroyed.
825
633
      if (BIO_pending(enc_out_) != 0)
826
573
        EncOut();
827
828
633
      MakeCallback(env()->onerror_string(), 1, &arg);
829
    }
830
  }
831
}
832
833
13190
void TLSWrap::ClearIn() {
834
13190
  Debug(this, "Trying to write cleartext input");
835
  // Ignore cycling data if ClientHello wasn't yet parsed
836
13190
  if (!hello_parser_.IsEnded()) {
837
    Debug(this, "Returning from ClearIn(), hello_parser_ active");
838
12966
    return;
839
  }
840
841
13190
  if (ssl_ == nullptr) {
842
    Debug(this, "Returning from ClearIn(), ssl_ == nullptr");
843
    return;
844
  }
845
846
13190
  if (pending_cleartext_input_.size() == 0) {
847
12800
    Debug(this, "Returning from ClearIn(), no pending data");
848
12800
    return;
849
  }
850
851
390
  AllocatedBuffer data = std::move(pending_cleartext_input_);
852
390
  MarkPopErrorOnReturn mark_pop_error_on_return;
853
854
390
  NodeBIO::FromBIO(enc_out_)->set_allocate_tls_hint(data.size());
855
390
  int written = SSL_write(ssl_.get(), data.data(), data.size());
856
390
  Debug(this, "Writing %zu bytes, written = %d", data.size(), written);
857

390
  CHECK(written == -1 || written == static_cast<int>(data.size()));
858
859
  // All written
860
390
  if (written != -1) {
861
164
    Debug(this, "Successfully wrote all data to SSL");
862
164
    return;
863
  }
864
865
  // Error or partial write
866
226
  HandleScope handle_scope(env()->isolate());
867
226
  Context::Scope context_scope(env()->context());
868
869
  int err;
870
226
  std::string error_str;
871
226
  MaybeLocal<Value> arg = GetSSLError(written, &err, &error_str);
872
226
  if (!arg.IsEmpty()) {
873
2
    Debug(this, "Got SSL error (%d)", err);
874
2
    write_callback_scheduled_ = true;
875
    // TODO(@sam-github) Should forward an error object with
876
    // .code/.function/.etc, if possible.
877
2
    return InvokeQueued(UV_EPROTO, error_str.c_str());
878
  }
879
880
224
  Debug(this, "Pushing data back");
881
  // Push back the not-yet-written data. This can be skipped in the error
882
  // case because no further writes would succeed anyway.
883
224
  pending_cleartext_input_ = std::move(data);
884
}
885
886
std::string TLSWrap::diagnostic_name() const {
887
  std::string name = "TLSWrap ";
888
  name += is_server() ? "server (" : "client (";
889
  name += std::to_string(static_cast<int64_t>(get_async_id())) + ")";
890
  return name;
891
}
892
893
27030
AsyncWrap* TLSWrap::GetAsyncWrap() {
894
27030
  return static_cast<AsyncWrap*>(this);
895
}
896
897
1032
bool TLSWrap::IsIPCPipe() {
898
1032
  return underlying_stream()->IsIPCPipe();
899
}
900
901
4
int TLSWrap::GetFD() {
902
4
  return underlying_stream()->GetFD();
903
}
904
905
5235
bool TLSWrap::IsAlive() {
906
5234
  return ssl_ &&
907

10469
      underlying_stream() != nullptr &&
908
10468
      underlying_stream()->IsAlive();
909
}
910
911
3
bool TLSWrap::IsClosing() {
912
3
  return underlying_stream()->IsClosing();
913
}
914
915
2285
int TLSWrap::ReadStart() {
916
2285
  Debug(this, "ReadStart()");
917
2285
  if (underlying_stream() != nullptr)
918
2285
    return underlying_stream()->ReadStart();
919
  return 0;
920
}
921
922
2936
int TLSWrap::ReadStop() {
923
2936
  Debug(this, "ReadStop()");
924
2936
  return underlying_stream() != nullptr ? underlying_stream()->ReadStop() : 0;
925
}
926
927
5335
const char* TLSWrap::Error() const {
928
5335
  return error_.empty() ? nullptr : error_.c_str();
929
}
930
931
11
void TLSWrap::ClearError() {
932
11
  error_.clear();
933
11
}
934
935
// Called by StreamBase::Write() to request async write of clear text into SSL.
936
// TODO(@sam-github) Should there be a TLSWrap::DoTryWrite()?
937
2648
int TLSWrap::DoWrite(WriteWrap* w,
938
                     uv_buf_t* bufs,
939
                     size_t count,
940
                     uv_stream_t* send_handle) {
941
2648
  CHECK_NULL(send_handle);
942
2648
  Debug(this, "DoWrite()");
943
944
2648
  if (ssl_ == nullptr) {
945
4
    ClearError();
946
4
    error_ = "Write after DestroySSL";
947
4
    return UV_EPROTO;
948
  }
949
950
2644
  size_t length = 0;
951
  size_t i;
952
2644
  size_t nonempty_i = 0;
953
2644
  size_t nonempty_count = 0;
954
11879
  for (i = 0; i < count; i++) {
955
9235
    length += bufs[i].len;
956
9235
    if (bufs[i].len > 0) {
957
8932
      nonempty_i = i;
958
8932
      nonempty_count += 1;
959
    }
960
  }
961
962
  // We want to trigger a Write() on the underlying stream to drive the stream
963
  // system, but don't want to encrypt empty buffers into a TLS frame, so see
964
  // if we can find something to Write().
965
  // First, call ClearOut(). It does an SSL_read(), which might cause handshake
966
  // or other internal messages to be encrypted. If it does, write them later
967
  // with EncOut().
968
  // If there is still no encrypted output, call Write(bufs) on the underlying
969
  // stream. Since the bufs are empty, it won't actually write non-TLS data
970
  // onto the socket, we just want the side-effects. After, make sure the
971
  // WriteWrap was accepted by the stream, or that we call Done() on it.
972
2644
  if (length == 0) {
973
201
    Debug(this, "Empty write");
974
201
    ClearOut();
975
201
    if (BIO_pending(enc_out_) == 0) {
976
100
      Debug(this, "No pending encrypted output, writing to underlying stream");
977
100
      CHECK(!current_empty_write_);
978
100
      current_empty_write_.reset(w->GetAsyncWrap());
979
      StreamWriteResult res =
980
100
          underlying_stream()->Write(bufs, count, send_handle);
981
100
      if (!res.async) {
982
100
        BaseObjectPtr<TLSWrap> strong_ref{this};
983
100
        env()->SetImmediate([this, strong_ref](Environment* env) {
984
100
          OnStreamAfterWrite(WriteWrap::FromObject(current_empty_write_), 0);
985
100
        });
986
      }
987
100
      return 0;
988
    }
989
  }
990
991
  // Store the current write wrap
992
2544
  CHECK(!current_write_);
993
2544
  current_write_.reset(w->GetAsyncWrap());
994
995
  // Write encrypted data to underlying stream and call Done().
996
2544
  if (length == 0) {
997
101
    EncOut();
998
101
    return 0;
999
  }
1000
1001
2443
  AllocatedBuffer data;
1002
4886
  MarkPopErrorOnReturn mark_pop_error_on_return;
1003
1004
2443
  int written = 0;
1005
1006
  // It is common for zero length buffers to be written,
1007
  // don't copy data if there there is one buffer with data
1008
  // and one or more zero length buffers.
1009
  // _http_outgoing.js writes a zero length buffer in
1010
  // in OutgoingMessage.prototype.end.  If there was a large amount
1011
  // of data supplied to end() there is no sense allocating
1012
  // and copying it when it could just be used.
1013
1014
2443
  if (nonempty_count != 1) {
1015
1495
    data = AllocatedBuffer::AllocateManaged(env(), length);
1016
1495
    size_t offset = 0;
1017
9481
    for (i = 0; i < count; i++) {
1018
7986
      memcpy(data.data() + offset, bufs[i].base, bufs[i].len);
1019
7986
      offset += bufs[i].len;
1020
    }
1021
1022
1495
    NodeBIO::FromBIO(enc_out_)->set_allocate_tls_hint(length);
1023
1495
    written = SSL_write(ssl_.get(), data.data(), length);
1024
  } else {
1025
    // Only one buffer: try to write directly, only store if it fails
1026
948
    uv_buf_t* buf = &bufs[nonempty_i];
1027
948
    NodeBIO::FromBIO(enc_out_)->set_allocate_tls_hint(buf->len);
1028
948
    written = SSL_write(ssl_.get(), buf->base, buf->len);
1029
1030
948
    if (written == -1) {
1031
166
      data = AllocatedBuffer::AllocateManaged(env(), length);
1032
166
      memcpy(data.data(), buf->base, buf->len);
1033
    }
1034
  }
1035
1036

2443
  CHECK(written == -1 || written == static_cast<int>(length));
1037
2443
  Debug(this, "Writing %zu bytes, written = %d", length, written);
1038
1039
2443
  if (written == -1) {
1040
    int err;
1041
171
    MaybeLocal<Value> arg = GetSSLError(written, &err, &error_);
1042
1043
    // If we stopped writing because of an error, it's fatal, discard the data.
1044
171
    if (!arg.IsEmpty()) {
1045
      // TODO(@jasnell): What are we doing with the error?
1046
3
      Debug(this, "Got SSL error (%d), returning UV_EPROTO", err);
1047
3
      current_write_.reset();
1048
3
      return UV_EPROTO;
1049
    }
1050
1051
168
    Debug(this, "Saving data for later write");
1052
    // Otherwise, save unwritten data so it can be written later by ClearIn().
1053
168
    CHECK_EQ(pending_cleartext_input_.size(), 0);
1054
168
    pending_cleartext_input_ = std::move(data);
1055
  }
1056
1057
  // Write any encrypted/handshake output that may be ready.
1058
  // Guard against sync call of current_write_->Done(), its unsupported.
1059
2440
  in_dowrite_ = true;
1060
2440
  EncOut();
1061
2440
  in_dowrite_ = false;
1062
1063
2440
  return 0;
1064
}
1065
1066
6234
uv_buf_t TLSWrap::OnStreamAlloc(size_t suggested_size) {
1067
6234
  CHECK_NOT_NULL(ssl_);
1068
1069
6234
  size_t size = suggested_size;
1070
6234
  char* base = NodeBIO::FromBIO(enc_in_)->PeekWritable(&size);
1071
6234
  return uv_buf_init(base, size);
1072
}
1073
1074
6242
void TLSWrap::OnStreamRead(ssize_t nread, const uv_buf_t& buf) {
1075
6242
  Debug(this, "Read %zd bytes from underlying stream", nread);
1076
6242
  if (nread < 0)  {
1077
    // Error should be emitted only after all data was read
1078
176
    ClearOut();
1079
1080
    // Ignore EOF if received close_notify
1081
176
    if (nread == UV_EOF) {
1082
170
      if (eof_)
1083
3
        return;
1084
167
      eof_ = true;
1085
    }
1086
1087
173
    EmitRead(nread);
1088
173
    return;
1089
  }
1090
1091
  // DestroySSL() is the only thing that un-sets ssl_, but that also removes
1092
  // this TLSWrap as a stream listener, so we should not receive OnStreamRead()
1093
  // calls anymore.
1094
6066
  CHECK(ssl_);
1095
1096
  // Commit the amount of data actually read into the peeked/allocated buffer
1097
  // from the underlying stream.
1098
6066
  NodeBIO* enc_in = NodeBIO::FromBIO(enc_in_);
1099
6066
  enc_in->Commit(nread);
1100
1101
  // Parse ClientHello first, if we need to. It's only parsed if session event
1102
  // listeners are used on the server side.  "ended" is the initial state, so
1103
  // can mean parsing was never started, or that parsing is finished. Either
1104
  // way, ended means we can give the buffered data to SSL.
1105
6066
  if (!hello_parser_.IsEnded()) {
1106
20
    size_t avail = 0;
1107
20
    uint8_t* data = reinterpret_cast<uint8_t*>(enc_in->Peek(&avail));
1108

20
    CHECK_IMPLIES(data == nullptr, avail == 0);
1109
20
    Debug(this, "Passing %zu bytes to the hello parser", avail);
1110
20
    return hello_parser_.Parse(data, avail);
1111
  }
1112
1113
  // Cycle OpenSSL's state
1114
6046
  Cycle();
1115
}
1116
1117
1415
ShutdownWrap* TLSWrap::CreateShutdownWrap(Local<Object> req_wrap_object) {
1118
1415
  return underlying_stream()->CreateShutdownWrap(req_wrap_object);
1119
}
1120
1121
1415
int TLSWrap::DoShutdown(ShutdownWrap* req_wrap) {
1122
1415
  Debug(this, "DoShutdown()");
1123
2830
  MarkPopErrorOnReturn mark_pop_error_on_return;
1124
1125

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

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

18
  if (UNLIKELY(psk_val.IsEmpty()) || !psk_val->IsArrayBufferView())
1406
1
    return 0;
1407
1408
8
  ArrayBufferViewContents<char> psk_buf(psk_val);
1409
1410
8
  if (psk_buf.length() > max_psk_len)
1411
    return 0;
1412
1413
8
  memcpy(psk, psk_buf.data(), psk_buf.length());
1414
8
  return psk_buf.length();
1415
}
1416
1417
9
unsigned int TLSWrap::PskClientCallback(
1418
    SSL* s,
1419
    const char* hint,
1420
    char* identity,
1421
    unsigned int max_identity_len,
1422
    unsigned char* psk,
1423
    unsigned int max_psk_len) {
1424
9
  TLSWrap* p = static_cast<TLSWrap*>(SSL_get_app_data(s));
1425
1426
9
  Environment* env = p->env();
1427
18
  HandleScope scope(env->isolate());
1428
1429
  Local<Value> argv[] = {
1430
    Null(env->isolate()),
1431
    Integer::NewFromUnsigned(env->isolate(), max_psk_len),
1432
    Integer::NewFromUnsigned(env->isolate(), max_identity_len)
1433
27
  };
1434
1435
9
  if (hint != nullptr) {
1436
    Local<String> local_hint =
1437
2
        String::NewFromUtf8(env->isolate(), hint).FromMaybe(Local<String>());
1438
1
    if (UNLIKELY(local_hint.IsEmpty()))
1439
      return 0;
1440
1441
1
    argv[0] = local_hint;
1442
  }
1443
1444
  Local<Value> ret =
1445
9
      p->MakeCallback(env->onpskexchange_symbol(), arraysize(argv), argv)
1446
9
          .FromMaybe(Local<Value>());
1447

18
  if (UNLIKELY(ret.IsEmpty()) || !ret->IsObject())
1448
    return 0;
1449
1450
9
  Local<Object> obj = ret.As<Object>();
1451
1452
18
  Local<Value> psk_val = obj->Get(env->context(), env->psk_string())
1453
9
      .FromMaybe(Local<Value>());
1454

18
  if (UNLIKELY(psk_val.IsEmpty()) || !psk_val->IsArrayBufferView())
1455
    return 0;
1456
1457
9
  ArrayBufferViewContents<char> psk_buf(psk_val);
1458
9
  if (psk_buf.length() > max_psk_len)
1459
    return 0;
1460
1461
18
  Local<Value> identity_val = obj->Get(env->context(), env->identity_string())
1462
9
      .FromMaybe(Local<Value>());
1463

27
  if (UNLIKELY(identity_val.IsEmpty()) || !identity_val->IsString())
1464
    return 0;
1465
1466
18
  Utf8Value identity_buf(env->isolate(), identity_val);
1467
1468
9
  if (identity_buf.length() > max_identity_len)
1469
    return 0;
1470
1471
9
  memcpy(identity, *identity_buf, identity_buf.length());
1472
9
  memcpy(psk, psk_buf.data(), psk_buf.length());
1473
1474
9
  return psk_buf.length();
1475
}
1476
1477
#endif
1478
1479
2
void TLSWrap::GetWriteQueueSize(const FunctionCallbackInfo<Value>& info) {
1480
  TLSWrap* wrap;
1481
2
  ASSIGN_OR_RETURN_UNWRAP(&wrap, info.This());
1482
1483
2
  if (!wrap->ssl_)
1484
    return info.GetReturnValue().Set(0);
1485
1486
2
  uint32_t write_queue_size = BIO_pending(wrap->enc_out_);
1487
4
  info.GetReturnValue().Set(write_queue_size);
1488
}
1489
1490
void TLSWrap::MemoryInfo(MemoryTracker* tracker) const {
1491
  tracker->TrackField("ocsp_response", ocsp_response_);
1492
  tracker->TrackField("sni_context", sni_context_);
1493
  tracker->TrackField("error", error_);
1494
  tracker->TrackFieldWithSize("pending_cleartext_input",
1495
                              pending_cleartext_input_.size(),
1496
                              "AllocatedBuffer");
1497
  if (enc_in_ != nullptr)
1498
    tracker->TrackField("enc_in", NodeBIO::FromBIO(enc_in_));
1499
  if (enc_out_ != nullptr)
1500
    tracker->TrackField("enc_out", NodeBIO::FromBIO(enc_out_));
1501
}
1502
1503
22
void TLSWrap::CertCbDone(const FunctionCallbackInfo<Value>& args) {
1504
22
  Environment* env = Environment::GetCurrent(args);
1505
  TLSWrap* w;
1506
24
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1507
1508

22
  CHECK(w->is_waiting_cert_cb() && w->cert_cb_running_);
1509
1510
22
  Local<Object> object = w->object();
1511
44
  Local<Value> ctx = object->Get(env->context(), env->sni_context_string())
1512
22
      .FromMaybe(Local<Value>());
1513
22
  if (UNLIKELY(ctx.IsEmpty()))
1514
    return;
1515
1516
22
  Local<FunctionTemplate> cons = env->secure_context_constructor_template();
1517
22
  if (cons->HasInstance(ctx)) {
1518
12
    SecureContext* sc = Unwrap<SecureContext>(ctx.As<Object>());
1519
12
    CHECK_NOT_NULL(sc);
1520
    // Store the SNI context for later use.
1521
12
    w->sni_context_ = BaseObjectPtr<SecureContext>(sc);
1522
1523


12
    if (UseSNIContext(w->ssl_, w->sni_context_) && !w->SetCACerts(sc)) {
1524
      // Not clear why sometimes we throw error, and sometimes we call
1525
      // onerror(). Both cause .destroy(), but onerror does a bit more.
1526
      unsigned long err = ERR_get_error();  // NOLINT(runtime/int)
1527
      return ThrowCryptoError(env, err, "CertCbDone");
1528
    }
1529
10
  } else if (ctx->IsObject()) {
1530
    // Failure: incorrect SNI context object
1531
2
    Local<Value> err = Exception::TypeError(env->sni_context_err_string());
1532
2
    w->MakeCallback(env->onerror_string(), 1, &err);
1533
2
    return;
1534
  }
1535
1536
  CertCb cb;
1537
  void* arg;
1538
1539
20
  cb = w->cert_cb_;
1540
20
  arg = w->cert_cb_arg_;
1541
1542
20
  w->cert_cb_running_ = false;
1543
20
  w->cert_cb_ = nullptr;
1544
20
  w->cert_cb_arg_ = nullptr;
1545
1546
20
  cb(arg);
1547
}
1548
1549
228
void TLSWrap::SetALPNProtocols(const FunctionCallbackInfo<Value>& args) {
1550
  TLSWrap* w;
1551
228
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1552
228
  Environment* env = w->env();
1553

456
  if (args.Length() < 1 || !Buffer::HasInstance(args[0]))
1554
    return env->ThrowTypeError("Must give a Buffer as first argument");
1555
1556
228
  if (w->is_client()) {
1557
39
    CHECK(SetALPN(w->ssl_, args[0]));
1558
  } else {
1559

756
    CHECK(
1560
        w->object()->SetPrivate(
1561
            env->context(),
1562
            env->alpn_buffer_private_symbol(),
1563
            args[0]).FromJust());
1564
    // Server should select ALPN protocol from list of advertised by client
1565
189
    SSL_CTX_set_alpn_select_cb(SSL_get_SSL_CTX(w->ssl_.get()),
1566
                               SelectALPNCallback,
1567
                               nullptr);
1568
  }
1569
}
1570
1571
444
void TLSWrap::GetPeerCertificate(const FunctionCallbackInfo<Value>& args) {
1572
  TLSWrap* w;
1573
444
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1574
444
  Environment* env = w->env();
1575
1576

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

20
  if (args.Length() >= 1 && Buffer::HasInstance(args[0])) {
1750
10
    ArrayBufferViewContents<unsigned char> sbuf(args[0]);
1751
1752
10
    const unsigned char* p = sbuf.data();
1753
10
    SSL_SESSION* sess = d2i_SSL_SESSION(nullptr, &p, sbuf.length());
1754
1755
    // Setup next session and move hello to the BIO buffer
1756
10
    w->next_sess_.reset(sess);
1757
  }
1758
}
1759
1760
2
void TLSWrap::GetSharedSigalgs(const FunctionCallbackInfo<Value>& args) {
1761
2
  Environment* env = Environment::GetCurrent(args);
1762
  TLSWrap* w;
1763
2
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1764
1765
2
  SSL* ssl = w->ssl_.get();
1766
2
  int nsig = SSL_get_shared_sigalgs(ssl, 0, nullptr, nullptr, nullptr, nullptr,
1767
                                    nullptr);
1768
2
  MaybeStackBuffer<Local<Value>, 16> ret_arr(nsig);
1769
1770
5
  for (int i = 0; i < nsig; i++) {
1771
    int hash_nid;
1772
    int sign_nid;
1773
3
    std::string sig_with_md;
1774
1775
3
    SSL_get_shared_sigalgs(ssl, i, &sign_nid, &hash_nid, nullptr, nullptr,
1776
                           nullptr);
1777
1778

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

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