GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/crypto/crypto_tls.cc Lines: 993 1081 91.9 %
Date: 2021-04-16 04:11:37 Branches: 446 667 66.9 %

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
40
  HandleScope handle_scope(env->isolate());
83
40
  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
2
      ? String::Empty(env->isolate())
88
      : OneByteString(env->isolate(),
89
                      hello.servername(),
90
22
                      hello.servername_size());
91
  Local<Object> buf =
92
40
      Buffer::Copy(
93
          env,
94
20
          reinterpret_cast<const char*>(hello.session_id()),
95
60
          hello.session_size()).FromMaybe(Local<Object>());
96
97

80
  if ((buf.IsEmpty() ||
98
80
       hello_obj->Set(env->context(), env->session_id_string(), buf)
99
40
          .IsNothing()) ||
100
80
      hello_obj->Set(env->context(), env->servername_string(), servername)
101

60
          .IsNothing() ||
102
40
      hello_obj->Set(
103
          env->context(),
104
          env->tls_ticket_string(),
105
20
          hello.has_ticket()
106
5
              ? True(env->isolate())
107
135
              : False(env->isolate())).IsNothing()) {
108
    return;
109
  }
110
111
40
  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
64
  HandleScope handle_scope(env->isolate());
119
64
  Context::Scope context_scope(env->context());
120
121
32
  const size_t size = strlen(line);
122
64
  Local<Value> line_bf = Buffer::Copy(env, line, 1 + size)
123
64
      .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
1765
int NewSessionCallback(SSL* s, SSL_SESSION* sess) {
133
1765
  TLSWrap* w = static_cast<TLSWrap*>(SSL_get_app_data(s));
134
1765
  Environment* env = w->env();
135
3530
  HandleScope handle_scope(env->isolate());
136
1765
  Context::Scope context_scope(env->context());
137
138
1765
  if (!w->has_session_callbacks())
139
1482
    return 0;
140
141
  // Check if session is small enough to be stored
142
283
  int size = i2d_SSL_SESSION(sess, nullptr);
143
283
  if (UNLIKELY(size > SecureContext::kMaxSessionSize))
144
    return 0;
145
146
  // Serialize session
147
  // TODO(@jasnell): An AllocatedBuffer or BackingStore would be better
148
  // here to start eliminating unnecessary uses of Buffer where an ordinary
149
  // Uint8Array would do just fine.
150
566
  Local<Object> session = Buffer::New(env, size).FromMaybe(Local<Object>());
151
283
  if (UNLIKELY(session.IsEmpty()))
152
    return 0;
153
154
  unsigned char* session_data =
155
283
      reinterpret_cast<unsigned char*>(Buffer::Data(session));
156
157
283
  memset(session_data, 0, size);
158
283
  i2d_SSL_SESSION(sess, &session_data);
159
160
  unsigned int session_id_length;
161
  const unsigned char* session_id_data =
162
283
      SSL_SESSION_get_id(sess, &session_id_length);
163
164
  // TODO(@jasnell): An AllocatedBuffer or BackingStore would be better
165
  // here to start eliminating unnecessary uses of Buffer where an ordinary
166
  // Uint8Array would do just fine
167
566
  Local<Object> session_id = Buffer::Copy(
168
      env,
169
      reinterpret_cast<const char*>(session_id_data),
170
849
      session_id_length).FromMaybe(Local<Object>());
171
283
  if (UNLIKELY(session_id.IsEmpty()))
172
    return 0;
173
174
  Local<Value> argv[] = {
175
    session_id,
176
    session
177
849
  };
178
179
  // On servers, we pause the handshake until callback of 'newSession', which
180
  // calls NewSessionDoneCb(). On clients, there is no callback to wait for.
181
283
  if (w->is_server())
182
8
    w->set_awaiting_new_session(true);
183
184
283
  w->MakeCallback(env->onnewsession_string(), arraysize(argv), argv);
185
186
283
  return 0;
187
}
188
189
904
int SSLCertCallback(SSL* s, void* arg) {
190
904
  TLSWrap* w = static_cast<TLSWrap*>(SSL_get_app_data(s));
191
192

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

50
          .IsNothing() ||
218
125
      info->Set(env->context(), env->ocsp_request_string(), ocsp).IsNothing()) {
219
    return 1;
220
  }
221
222
50
  Local<Value> argv[] = { info };
223
25
  w->MakeCallback(env->oncertcb_string(), arraysize(argv), argv);
224
225
25
  return w->is_cert_cb_running() ? -1 : 1;
226
}
227
228
33
int SelectALPNCallback(
229
    SSL* s,
230
    const unsigned char** out,
231
    unsigned char* outlen,
232
    const unsigned char* in,
233
    unsigned int inlen,
234
    void* arg) {
235
33
  TLSWrap* w = static_cast<TLSWrap*>(SSL_get_app_data(s));
236
33
  Environment* env = w->env();
237
66
  HandleScope handle_scope(env->isolate());
238
33
  Context::Scope context_scope(env->context());
239
240
  Local<Value> alpn_buffer =
241
99
      w->object()->GetPrivate(
242
          env->context(),
243
132
          env->alpn_buffer_private_symbol()).FromMaybe(Local<Value>());
244

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


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

4750
            .ToLocal(&callback) && callback->IsFunction()) {
525
2375
      Local<Value> argv[] = { env->GetNow() };
526
4750
      c->MakeCallback(callback.As<Function>(), arraysize(argv), argv);
527
    }
528
  }
529
530
  // SSL_CB_HANDSHAKE_START and SSL_CB_HANDSHAKE_DONE are called
531
  // sending HelloRequest in OpenSSL-1.1.1.
532
  // We need to check whether this is in a renegotiation state or not.
533

4046
  if (where & SSL_CB_HANDSHAKE_DONE && !SSL_renegotiate_pending(ssl)) {
534
    Debug(c, "SSLInfoCallback(SSL_CB_HANDSHAKE_DONE);");
535
1670
    CHECK(!SSL_renegotiate_pending(ssl));
536
    Local<Value> callback;
537
538
1670
    c->established_ = true;
539
540
6680
    if (object->Get(env->context(), env->onhandshakedone_string())
541

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

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

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

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

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

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

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

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

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

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

20
    CHECK_IMPLIES(data == nullptr, avail == 0);
1116
20
    Debug(this, "Passing %zu bytes to the hello parser", avail);
1117
20
    return hello_parser_.Parse(data, avail);
1118
  }
1119
1120
  // Cycle OpenSSL's state
1121
6065
  Cycle();
1122
}
1123
1124
1403
ShutdownWrap* TLSWrap::CreateShutdownWrap(Local<Object> req_wrap_object) {
1125
1403
  return underlying_stream()->CreateShutdownWrap(req_wrap_object);
1126
}
1127
1128
1403
int TLSWrap::DoShutdown(ShutdownWrap* req_wrap) {
1129
1403
  Debug(this, "DoShutdown()");
1130
2806
  MarkPopErrorOnReturn mark_pop_error_on_return;
1131
1132

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

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

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

18
  if (UNLIKELY(ret.IsEmpty()) || !ret->IsObject())
1455
    return 0;
1456
1457
9
  Local<Object> obj = ret.As<Object>();
1458
1459
36
  Local<Value> psk_val = obj->Get(env->context(), env->psk_string())
1460
18
      .FromMaybe(Local<Value>());
1461

18
  if (UNLIKELY(psk_val.IsEmpty()) || !psk_val->IsArrayBufferView())
1462
    return 0;
1463
1464
9
  ArrayBufferViewContents<char> psk_buf(psk_val);
1465
9
  if (psk_buf.length() > max_psk_len)
1466
    return 0;
1467
1468
36
  Local<Value> identity_val = obj->Get(env->context(), env->identity_string())
1469
18
      .FromMaybe(Local<Value>());
1470

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

22
  CHECK(w->is_waiting_cert_cb() && w->cert_cb_running_);
1516
1517
22
  Local<Object> object = w->object();
1518
88
  Local<Value> ctx = object->Get(env->context(), env->sni_context_string())
1519
44
      .FromMaybe(Local<Value>());
1520
22
  if (UNLIKELY(ctx.IsEmpty()))
1521
    return;
1522
1523
22
  Local<FunctionTemplate> cons = env->secure_context_constructor_template();
1524
22
  if (cons->HasInstance(ctx)) {
1525
12
    SecureContext* sc = Unwrap<SecureContext>(ctx.As<Object>());
1526
12
    CHECK_NOT_NULL(sc);
1527
    // Store the SNI context for later use.
1528
12
    w->sni_context_ = BaseObjectPtr<SecureContext>(sc);
1529
1530


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

442
  if (args.Length() < 1 || !Buffer::HasInstance(args[0]))
1561
    return env->ThrowTypeError("Must give a Buffer as first argument");
1562
1563
221
  if (w->is_client()) {
1564
38
    CHECK(SetALPN(w->ssl_, args[0]));
1565
  } else {
1566
549
    CHECK(
1567
        w->object()->SetPrivate(
1568
            env->context(),
1569
            env->alpn_buffer_private_symbol(),
1570
            args[0]).FromJust());
1571
    // Server should select ALPN protocol from list of advertised by client
1572
183
    SSL_CTX_set_alpn_select_cb(SSL_get_SSL_CTX(w->ssl_.get()),
1573
                               SelectALPNCallback,
1574
183
                               nullptr);
1575
  }
1576
}
1577
1578
444
void TLSWrap::GetPeerCertificate(const FunctionCallbackInfo<Value>& args) {
1579
  TLSWrap* w;
1580
444
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1581
444
  Environment* env = w->env();
1582
1583

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

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

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

112
  } else if (alpn_proto_len == sizeof("h2") - 1 &&
1983
53
             0 == memcmp(alpn_proto, "h2", sizeof("h2") - 1)) {
1984
106
    result = env->h2_string();
1985

8
  } else if (alpn_proto_len == sizeof("http/1.1") - 1 &&
1986
2
             0 == memcmp(alpn_proto, "http/1.1", sizeof("http/1.1") - 1)) {
1987
4
    result = env->http_1_1_string();
1988
  } else {
1989
8
    result = OneByteString(env->isolate(), alpn_proto, alpn_proto_len);
1990
  }
1991
1992
3336
  args.GetReturnValue().Set(result);
1993
}
1994
1995
6112
void TLSWrap::Cycle() {
1996
  // Prevent recursion
1997
6112
  if (++cycle_depth_ > 1)
1998
14
    return;
1999
2000
18318
  for (; cycle_depth_ > 0; cycle_depth_--) {
2001
6112
    ClearIn();
2002
6112
    ClearOut();
2003
    // EncIn() doesn't exist, it happens via stream listener callbacks.
2004
6111
    EncOut();
2005
  }
2006
}
2007
2008
#ifdef SSL_set_max_send_fragment
2009
3
void TLSWrap::SetMaxSendFragment(const FunctionCallbackInfo<Value>& args) {
2010

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

19072
NODE_MODULE_CONTEXT_AWARE_INTERNAL(tls_wrap, node::crypto::TLSWrap::Initialize)