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: 976 1066 91.6 %
Date: 2020-12-12 04:11:07 Branches: 437 655 66.7 %

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
98
SSL_SESSION* GetSessionCallback(
68
    SSL* s,
69
    const unsigned char* key,
70
    int len,
71
    int* copy) {
72
98
  TLSWrap* w = static_cast<TLSWrap*>(SSL_get_app_data(s));
73
98
  *copy = 0;
74
98
  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
1761
int NewSessionCallback(SSL* s, SSL_SESSION* sess) {
133
1761
  TLSWrap* w = static_cast<TLSWrap*>(SSL_get_app_data(s));
134
1761
  Environment* env = w->env();
135
3522
  HandleScope handle_scope(env->isolate());
136
1761
  Context::Scope context_scope(env->context());
137
138
1761
  if (!w->has_session_callbacks())
139
1472
    return 0;
140
141
  // Check if session is small enough to be stored
142
289
  int size = i2d_SSL_SESSION(sess, nullptr);
143
289
  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
578
  Local<Object> session = Buffer::New(env, size).FromMaybe(Local<Object>());
151
289
  if (UNLIKELY(session.IsEmpty()))
152
    return 0;
153
154
  unsigned char* session_data =
155
289
      reinterpret_cast<unsigned char*>(Buffer::Data(session));
156
157
289
  memset(session_data, 0, size);
158
289
  i2d_SSL_SESSION(sess, &session_data);
159
160
  unsigned int session_id_length;
161
  const unsigned char* session_id_data =
162
289
      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
578
  Local<Object> session_id = Buffer::Copy(
168
      env,
169
      reinterpret_cast<const char*>(session_id_data),
170
867
      session_id_length).FromMaybe(Local<Object>());
171
289
  if (UNLIKELY(session_id.IsEmpty()))
172
    return 0;
173
174
  Local<Value> argv[] = {
175
    session_id,
176
    session
177
867
  };
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
289
  if (w->is_server())
182
8
    w->set_awaiting_new_session(true);
183
184
289
  w->MakeCallback(env->onnewsession_string(), arraysize(argv), argv);
185
186
289
  return 0;
187
}
188
189
893
int SSLCertCallback(SSL* s, void* arg) {
190
893
  TLSWrap* w = static_cast<TLSWrap*>(SSL_get_app_data(s));
191
192

893
  if (!w->is_server() || !w->is_waiting_cert_cb())
193
871
    return 1;
194
195
22
  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
22
  Environment* env = w->env();
201
44
  HandleScope handle_scope(env->isolate());
202
22
  Context::Scope context_scope(env->context());
203
22
  w->set_cert_cb_running();
204
205
22
  Local<Object> info = Object::New(env->isolate());
206
207
22
  const char* servername = GetServerName(s);
208
  Local<String> servername_str = (servername == nullptr)
209
4
      ? String::Empty(env->isolate())
210
26
      : OneByteString(env->isolate(), servername, strlen(servername));
211
212
22
  Local<Value> ocsp = (SSL_get_tlsext_status_type(s) == TLSEXT_STATUSTYPE_ocsp)
213
6
      ? True(env->isolate())
214
38
      : False(env->isolate());
215
216
110
  if (info->Set(env->context(), env->servername_string(), servername_str)
217

44
          .IsNothing() ||
218
110
      info->Set(env->context(), env->ocsp_request_string(), ocsp).IsNothing()) {
219
    return 1;
220
  }
221
222
44
  Local<Value> argv[] = { info };
223
22
  w->MakeCallback(env->oncertcb_string(), arraysize(argv), argv);
224
225
22
  return w->is_cert_cb_running() ? -1 : 1;
226
}
227
228
32
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
32
  TLSWrap* w = static_cast<TLSWrap*>(SSL_get_app_data(s));
236
32
  Environment* env = w->env();
237
64
  HandleScope handle_scope(env->isolate());
238
32
  Context::Scope context_scope(env->context());
239
240
  Local<Value> alpn_buffer =
241
96
      w->object()->GetPrivate(
242
          env->context(),
243
128
          env->alpn_buffer_private_symbol()).FromMaybe(Local<Value>());
244

64
  if (UNLIKELY(alpn_buffer.IsEmpty()) || !alpn_buffer->IsArrayBufferView())
245
    return SSL_TLSEXT_ERR_NOACK;
246
247
32
  ArrayBufferViewContents<unsigned char> alpn_protos(alpn_buffer);
248
32
  int status = SSL_select_next_proto(
249
      const_cast<unsigned char**>(out),
250
      outlen,
251
      alpn_protos.data(),
252
32
      alpn_protos.length(),
253
      in,
254
32
      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
32
      ? SSL_TLSEXT_ERR_OK
262
32
      : 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
12210
void ConfigureSecureContext(SecureContext* sc) {
304
  // OCSP stapling
305
12210
  SSL_CTX_set_tlsext_status_cb(sc->ctx_.get(), TLSExtStatusCallback);
306
12210
  SSL_CTX_set_tlsext_status_arg(sc->ctx_.get(), nullptr);
307
12210
}
308
309
3864
inline bool Set(
310
    Environment* env,
311
    Local<Object> target,
312
    Local<String> name,
313
    const char* value,
314
    bool ignore_null = true) {
315
3864
  if (value == nullptr)
316
687
    return ignore_null;
317
6354
  return !target->Set(
318
      env->context(),
319
      name,
320
12708
      OneByteString(env->isolate(), value))
321
3177
          .IsNothing();
322
}
323
}  // namespace
324
325
12210
TLSWrap::TLSWrap(Environment* env,
326
                 Local<Object> obj,
327
                 Kind kind,
328
                 StreamBase* stream,
329
12210
                 SecureContext* sc)
330
    : AsyncWrap(env, obj, AsyncWrap::PROVIDER_TLSWRAP),
331
      StreamBase(env),
332
      env_(env),
333
      kind_(kind),
334
24420
      sc_(sc) {
335
12210
  MakeWeak();
336
12210
  CHECK(sc_);
337
12210
  ssl_ = sc_->CreateSSL();
338
12210
  CHECK(ssl_);
339
340
12210
  sc_->SetGetSessionCallback(GetSessionCallback);
341
12210
  sc_->SetNewSessionCallback(NewSessionCallback);
342
343
12210
  StreamBase::AttachToObject(GetObject());
344
12210
  stream->PushStreamListener(this);
345
346
12210
  env_->isolate()->AdjustAmountOfExternalAllocatedMemory(kExternalSize);
347
348
12210
  InitSSL();
349
12210
  Debug(this, "Created new TLSWrap");
350
12210
}
351
352
48704
TLSWrap::~TLSWrap() {
353
12176
  Destroy();
354
24352
}
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
98
SSL_SESSION* TLSWrap::ReleaseSession() {
367
98
  return next_sess_.release();
368
}
369
370
20548
void TLSWrap::InvokeQueued(int status, const char* error_str) {
371
20548
  Debug(this, "Invoking queued write callbacks (%d, %s)", status, error_str);
372
20548
  if (!write_callback_scheduled_)
373
4465
    return;
374
375
16083
  if (current_write_) {
376
5480
    BaseObjectPtr<AsyncWrap> current_write = std::move(current_write_);
377
2740
    current_write_.reset();
378
2740
    WriteWrap* w = WriteWrap::FromObject(current_write);
379
2740
    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
12210
void TLSWrap::InitSSL() {
389
  // Initialize SSL – OpenSSL takes ownership of these.
390
12210
  enc_in_ = NodeBIO::New(env()).release();
391
12210
  enc_out_ = NodeBIO::New(env()).release();
392
393
12210
  SSL_set_bio(ssl_.get(), enc_in_, enc_out_);
394
395
  // NOTE: This could be overridden in SetVerifyMode
396
12210
  SSL_set_verify(ssl_.get(), SSL_VERIFY_NONE, VerifyCallback);
397
398
#ifdef SSL_MODE_RELEASE_BUFFERS
399
12210
  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
12210
  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
12210
  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
12210
  SSL_set_info_callback(ssl_.get(), SSLInfoCallback);
421
422
12210
  if (is_server())
423
856
    sc_->SetSelectSNIContextCallback(SelectSNIContextCallback);
424
425
12210
  ConfigureSecureContext(sc_.get());
426
427
12210
  SSL_set_cert_cb(ssl_.get(), SSLCertCallback, this);
428
429
12210
  if (is_server()) {
430
856
    SSL_set_accept_state(ssl_.get());
431
11354
  } else if (is_client()) {
432
    // Enough space for server response (hello, cert)
433
11354
    NodeBIO::FromBIO(enc_in_)->set_initial(kInitialClientBufferLength);
434
11354
    SSL_set_connect_state(ssl_.get());
435
  } else {
436
    // Unexpected
437
    ABORT();
438
  }
439
12210
}
440
441
12210
void TLSWrap::Wrap(const FunctionCallbackInfo<Value>& args) {
442
12210
  Environment* env = Environment::GetCurrent(args);
443
444
12210
  CHECK_EQ(args.Length(), 3);
445
24420
  CHECK(args[0]->IsObject());
446
24420
  CHECK(args[1]->IsObject());
447
24420
  CHECK(args[2]->IsBoolean());
448
449
24420
  Local<Object> sc = args[1].As<Object>();
450
24420
  Kind kind = args[2]->IsTrue() ? Kind::kServer : Kind::kClient;
451
452
24420
  StreamBase* stream = StreamBase::FromObject(args[0].As<Object>());
453
12210
  CHECK_NOT_NULL(stream);
454
455
  Local<Object> obj;
456
36630
  if (!env->tls_wrap_constructor_function()
457
36630
           ->NewInstance(env->context())
458
12210
           .ToLocal(&obj)) {
459
    return;
460
  }
461
462
24420
  TLSWrap* res = new TLSWrap(env, obj, kind, stream, Unwrap<SecureContext>(sc));
463
464
36630
  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
1315
void TLSWrap::Start(const FunctionCallbackInfo<Value>& args) {
490
  TLSWrap* wrap;
491
1315
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
492
493
1315
  CHECK(!wrap->started_);
494
1315
  wrap->started_ = true;
495
496
  // Send ClientHello handshake
497
1315
  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
1315
  wrap->ClearOut();
502
1315
  wrap->EncOut();
503
}
504
505
37761
void TLSWrap::SSLInfoCallback(const SSL* ssl_, int where, int ret) {
506
37761
  if (!(where & (SSL_CB_HANDSHAKE_START | SSL_CB_HANDSHAKE_DONE)))
507
33751
    return;
508
509
  // SSL_renegotiate_pending() should take `const SSL*`, but it does not.
510
4010
  SSL* ssl = const_cast<SSL*>(ssl_);
511
4010
  TLSWrap* c = static_cast<TLSWrap*>(SSL_get_app_data(ssl_));
512
4010
  Environment* env = c->env();
513
8020
  HandleScope handle_scope(env->isolate());
514
4010
  Context::Scope context_scope(env->context());
515
4010
  Local<Object> object = c->object();
516
517
4010
  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
9424
    if (object->Get(env->context(), env->onhandshakestart_string())
524

4712
            .ToLocal(&callback) && callback->IsFunction()) {
525
2356
      Local<Value> argv[] = { env->GetNow() };
526
4712
      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

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

3306
          .ToLocal(&callback) && callback->IsFunction()) {
542
1653
      c->MakeCallback(callback.As<Function>(), 0, nullptr);
543
    }
544
  }
545
}
546
547
19362
void TLSWrap::EncOut() {
548
19362
  Debug(this, "Trying to write encrypted output");
549
550
  // Ignore cycling data if ClientHello wasn't yet parsed
551
19362
  if (!hello_parser_.IsEnded()) {
552
1
    Debug(this, "Returning from EncOut(), hello_parser_ active");
553
12074
    return;
554
  }
555
556
  // Write in progress
557
19361
  if (write_size_ != 0) {
558
3522
    Debug(this, "Returning from EncOut(), write currently in progress");
559
3522
    return;
560
  }
561
562
  // Wait for `newSession` callback to be invoked
563
15839
  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

15832
  if (established_ && current_write_) {
570
5452
    Debug(this, "EncOut() write is scheduled");
571
5452
    write_callback_scheduled_ = true;
572
  }
573
574
15832
  if (ssl_ == nullptr) {
575
1
    Debug(this, "Returning from EncOut(), ssl_ == nullptr");
576
1
    return;
577
  }
578
579
  // No encrypted output ready to write to the underlying stream.
580
15831
  if (BIO_pending(enc_out_) == 0) {
581
8463
    Debug(this, "No pending encrypted output");
582
8463
    if (pending_cleartext_input_.size() == 0) {
583
8273
      if (!in_dowrite_) {
584
8214
        Debug(this, "No pending cleartext input, not inside DoWrite()");
585
8214
        InvokeQueued(0);
586
      } else {
587
59
        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
118
        BaseObjectPtr<TLSWrap> strong_ref{this};
597
354
        env()->SetImmediate([this, strong_ref](Environment* env) {
598
59
          InvokeQueued(0);
599
118
        });
600
      }
601
    }
602
8463
    return;
603
  }
604
605
  char* data[kSimultaneousBufferCount];
606
  size_t size[arraysize(data)];
607
7368
  size_t count = arraysize(data);
608
7368
  write_size_ = NodeBIO::FromBIO(enc_out_)->PeekMultiple(data, size, &count);
609

7368
  CHECK(write_size_ != 0 && count != 0);
610
611
  uv_buf_t buf[arraysize(data)];
612
7368
  uv_buf_t* bufs = buf;
613
14860
  for (size_t i = 0; i < count; i++)
614
7492
    buf[i] = uv_buf_init(data[i], size[i]);
615
616
7368
  Debug(this, "Writing %zu buffers to the underlying stream", count);
617
7368
  StreamWriteResult res = underlying_stream()->Write(bufs, count);
618
7367
  if (res.err != 0) {
619
79
    InvokeQueued(res.err);
620
79
    return;
621
  }
622
623
7288
  if (!res.async) {
624
6729
    Debug(this, "Write finished synchronously");
625
13458
    HandleScope handle_scope(env()->isolate());
626
627
    // Simulate asynchronous finishing, TLS cannot handle this at the moment.
628
13458
    BaseObjectPtr<TLSWrap> strong_ref{this};
629
47103
    env()->SetImmediate([this, strong_ref](Environment* env) {
630
13458
      OnStreamAfterWrite(nullptr, 0);
631
13458
    });
632
  }
633
}
634
635
7387
void TLSWrap::OnStreamAfterWrite(WriteWrap* req_wrap, int status) {
636
7387
  Debug(this, "OnStreamAfterWrite(status = %d)", status);
637
7387
  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
7287
  if (ssl_ == nullptr) {
648
    Debug(this, "ssl_ == nullptr, marking as cancelled");
649
    status = UV_ECANCELED;
650
  }
651
652
  // Handle error
653
7287
  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
7284
  NodeBIO::FromBIO(enc_out_)->Read(nullptr, write_size_);
666
667
  // Ensure that the progress will be made and `InvokeQueued` will be called.
668
7284
  ClearIn();
669
670
  // Try writing more data
671
7284
  write_size_ = 0;
672
7284
  EncOut();
673
}
674
675
8087
MaybeLocal<Value> TLSWrap::GetSSLError(int status, int* err, std::string* msg) {
676
8087
  EscapableHandleScope scope(env()->isolate());
677
678
  // ssl_ is already destroyed in reading EOF by close notify alert.
679
8087
  if (ssl_ == nullptr)
680
    return MaybeLocal<Value>();
681
682
8087
  *err = SSL_get_error(ssl_.get(), status);
683

8087
  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
6296
      return MaybeLocal<Value>();
689
690
    case SSL_ERROR_ZERO_RETURN:
691
2306
      return scope.Escape(env()->zero_return_string());
692
693
    case SSL_ERROR_SSL:
694
    case SSL_ERROR_SYSCALL:
695
      {
696
638
        unsigned long ssl_err = ERR_peek_error();  // NOLINT(runtime/int)
697
638
        BIO* bio = BIO_new(BIO_s_mem());
698
638
        ERR_print_errors(bio);
699
700
        BUF_MEM* mem;
701
638
        BIO_get_mem_ptr(bio, &mem);
702
703
638
        Isolate* isolate = env()->isolate();
704
638
        Local<Context> context = isolate->GetCurrentContext();
705
706
638
        Local<String> message = OneByteString(isolate, mem->data, mem->length);
707
638
        Local<Value> exception = Exception::Error(message);
708
        Local<Object> obj =
709
1276
            exception->ToObject(context).FromMaybe(Local<Object>());
710
638
        if (UNLIKELY(obj.IsEmpty()))
711
          return MaybeLocal<Value>();
712
713
638
        const char* ls = ERR_lib_error_string(ssl_err);
714
638
        const char* fs = ERR_func_error_string(ssl_err);
715
638
        const char* rs = ERR_reason_error_string(ssl_err);
716
717

1276
        if (!Set(env(), obj, env()->library_string(), ls) ||
718
638
            !Set(env(), obj, env()->function_string(), fs)) {
719
          return MaybeLocal<Value>();
720
        }
721
722
638
        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
13687
          for (auto& c : code)
732
13054
            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
638
        if (msg != nullptr)
742
5
          msg->assign(mem->data, mem->data + mem->length);
743
744
638
        BIO_free_all(bio);
745
746
638
        return scope.Escape(exception);
747
      }
748
749
    default:
750
      UNREACHABLE();
751
  }
752
  UNREACHABLE();
753
}
754
755
7708
void TLSWrap::ClearOut() {
756
7708
  Debug(this, "Trying to read cleartext output");
757
  // Ignore cycling data if ClientHello wasn't yet parsed
758
7708
  if (!hello_parser_.IsEnded()) {
759
1
    Debug(this, "Returning from ClearOut(), hello_parser_ active");
760
1159
    return;
761
  }
762
763
  // No reads after EOF
764
7707
  if (eof_) {
765
3
    Debug(this, "Returning from ClearOut(), EOF reached");
766
3
    return;
767
  }
768
769
7704
  if (ssl_ == nullptr) {
770
    Debug(this, "Returning from ClearOut(), ssl_ == nullptr");
771
    return;
772
  }
773
774
14253
  MarkPopErrorOnReturn mark_pop_error_on_return;
775
776
  char out[kClearOutChunkSize];
777
  int read;
778
  for (;;) {
779
10846
    read = SSL_read(ssl_.get(), out, sizeof(out));
780
10846
    Debug(this, "Read %d bytes of cleartext output", read);
781
782
10846
    if (read <= 0)
783
7702
      break;
784
785
3144
    char* current = out;
786
13536
    while (read > 0) {
787
5198
      int avail = read;
788
789
5198
      uv_buf_t buf = EmitAlloc(avail);
790
5198
      if (static_cast<int>(buf.len) < avail)
791
2054
        avail = buf.len;
792
5198
      memcpy(buf.base, current, avail);
793
5198
      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
5197
      if (ssl_ == nullptr) {
799
1
        Debug(this, "Returning from read loop, ssl_ == nullptr");
800
1
        return;
801
      }
802
803
5196
      read -= avail;
804
5196
      current += avail;
805
    }
806
3142
  }
807
808
7702
  int flags = SSL_get_shutdown(ssl_.get());
809

7702
  if (!eof_ && flags & SSL_RECEIVED_SHUTDOWN) {
810
1210
    eof_ = true;
811
1210
    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
7702
  if (read <= 0) {
818
14251
    HandleScope handle_scope(env()->isolate());
819
    int err;
820
821
15404
    Local<Value> arg = GetSSLError(read, &err, nullptr)
822
15404
        .FromMaybe(Local<Value>());
823
824
    // Ignore ZERO_RETURN after EOF, it is basically not a error
825

7702
    if (err == SSL_ERROR_ZERO_RETURN && eof_)
826
1153
      return;
827
828
6549
    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
13343
void TLSWrap::ClearIn() {
841
13343
  Debug(this, "Trying to write cleartext input");
842
  // Ignore cycling data if ClientHello wasn't yet parsed
843
13343
  if (!hello_parser_.IsEnded()) {
844
    Debug(this, "Returning from ClearIn(), hello_parser_ active");
845
13133
    return;
846
  }
847
848
13343
  if (ssl_ == nullptr) {
849
    Debug(this, "Returning from ClearIn(), ssl_ == nullptr");
850
    return;
851
  }
852
853
13343
  if (pending_cleartext_input_.size() == 0) {
854
12964
    Debug(this, "Returning from ClearIn(), no pending data");
855
12964
    return;
856
  }
857
858
589
  AllocatedBuffer data = std::move(pending_cleartext_input_);
859
589
  MarkPopErrorOnReturn mark_pop_error_on_return;
860
861
379
  NodeBIO::FromBIO(enc_out_)->set_allocate_tls_hint(data.size());
862
379
  int written = SSL_write(ssl_.get(), data.data(), data.size());
863
758
  Debug(this, "Writing %zu bytes, written = %d", data.size(), written);
864

379
  CHECK(written == -1 || written == static_cast<int>(data.size()));
865
866
  // All written
867
379
  if (written != -1) {
868
167
    Debug(this, "Successfully wrote all data to SSL");
869
167
    return;
870
  }
871
872
  // Error or partial write
873
422
  HandleScope handle_scope(env()->isolate());
874
422
  Context::Scope context_scope(env()->context());
875
876
  int err;
877
422
  std::string error_str;
878
212
  MaybeLocal<Value> arg = GetSSLError(written, &err, &error_str);
879
212
  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
210
  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
210
  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
27236
AsyncWrap* TLSWrap::GetAsyncWrap() {
901
27236
  return static_cast<AsyncWrap*>(this);
902
}
903
904
1130
bool TLSWrap::IsIPCPipe() {
905
1130
  return underlying_stream()->IsIPCPipe();
906
}
907
908
3
int TLSWrap::GetFD() {
909
3
  return underlying_stream()->GetFD();
910
}
911
912
5226
bool TLSWrap::IsAlive() {
913
5226
  return ssl_ &&
914

10451
      underlying_stream() != nullptr &&
915
10451
      underlying_stream()->IsAlive();
916
}
917
918
3
bool TLSWrap::IsClosing() {
919
3
  return underlying_stream()->IsClosing();
920
}
921
922
2441
int TLSWrap::ReadStart() {
923
2441
  Debug(this, "ReadStart()");
924
2441
  if (underlying_stream() != nullptr)
925
2441
    return underlying_stream()->ReadStart();
926
  return 0;
927
}
928
929
3072
int TLSWrap::ReadStop() {
930
3072
  Debug(this, "ReadStop()");
931
3072
  return underlying_stream() != nullptr ? underlying_stream()->ReadStop() : 0;
932
}
933
934
5552
const char* TLSWrap::Error() const {
935
5552
  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
2848
int TLSWrap::DoWrite(WriteWrap* w,
945
                     uv_buf_t* bufs,
946
                     size_t count,
947
                     uv_stream_t* send_handle) {
948
2848
  CHECK_NULL(send_handle);
949
2848
  Debug(this, "DoWrite()");
950
951
2848
  if (ssl_ == nullptr) {
952
4
    ClearError();
953
4
    error_ = "Write after DestroySSL";
954
4
    return UV_EPROTO;
955
  }
956
957
2844
  size_t length = 0;
958
  size_t i;
959
2844
  size_t nonempty_i = 0;
960
2844
  size_t nonempty_count = 0;
961
13387
  for (i = 0; i < count; i++) {
962
10543
    length += bufs[i].len;
963
10543
    if (bufs[i].len > 0) {
964
10240
      nonempty_i = i;
965
10240
      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
2844
  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
100
          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
2744
  CHECK(!current_write_);
1000
2744
  current_write_.reset(w->GetAsyncWrap());
1001
1002
  // Write encrypted data to underlying stream and call Done().
1003
2744
  if (length == 0) {
1004
101
    EncOut();
1005
101
    return 0;
1006
  }
1007
1008
5286
  AllocatedBuffer data;
1009
5286
  MarkPopErrorOnReturn mark_pop_error_on_return;
1010
1011
2643
  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
2643
  if (nonempty_count != 1) {
1022
1650
    data = AllocatedBuffer::AllocateManaged(env(), length);
1023
1650
    size_t offset = 0;
1024
10901
    for (i = 0; i < count; i++) {
1025
9251
      memcpy(data.data() + offset, bufs[i].base, bufs[i].len);
1026
9251
      offset += bufs[i].len;
1027
    }
1028
1029
1650
    NodeBIO::FromBIO(enc_out_)->set_allocate_tls_hint(length);
1030
1650
    written = SSL_write(ssl_.get(), data.data(), length);
1031
  } else {
1032
    // Only one buffer: try to write directly, only store if it fails
1033
993
    uv_buf_t* buf = &bufs[nonempty_i];
1034
993
    NodeBIO::FromBIO(enc_out_)->set_allocate_tls_hint(buf->len);
1035
993
    written = SSL_write(ssl_.get(), buf->base, buf->len);
1036
1037
993
    if (written == -1) {
1038
168
      data = AllocatedBuffer::AllocateManaged(env(), length);
1039
168
      memcpy(data.data(), buf->base, buf->len);
1040
    }
1041
  }
1042
1043

2643
  CHECK(written == -1 || written == static_cast<int>(length));
1044
2643
  Debug(this, "Writing %zu bytes, written = %d", length, written);
1045
1046
2643
  if (written == -1) {
1047
    int err;
1048
173
    MaybeLocal<Value> arg = GetSSLError(written, &err, &error_);
1049
1050
    // If we stopped writing because of an error, it's fatal, discard the data.
1051
173
    if (!arg.IsEmpty()) {
1052
      // TODO(@jasnell): What are we doing with the error?
1053
3
      Debug(this, "Got SSL error (%d), returning UV_EPROTO", err);
1054
3
      current_write_.reset();
1055
3
      return UV_EPROTO;
1056
    }
1057
1058
170
    Debug(this, "Saving data for later write");
1059
    // Otherwise, save unwritten data so it can be written later by ClearIn().
1060
170
    CHECK_EQ(pending_cleartext_input_.size(), 0);
1061
170
    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
2640
  in_dowrite_ = true;
1067
2640
  EncOut();
1068
2640
  in_dowrite_ = false;
1069
1070
2640
  return 0;
1071
}
1072
1073
6162
uv_buf_t TLSWrap::OnStreamAlloc(size_t suggested_size) {
1074
6162
  CHECK_NOT_NULL(ssl_);
1075
1076
6162
  size_t size = suggested_size;
1077
6162
  char* base = NodeBIO::FromBIO(enc_in_)->PeekWritable(&size);
1078
6162
  return uv_buf_init(base, size);
1079
}
1080
1081
6168
void TLSWrap::OnStreamRead(ssize_t nread, const uv_buf_t& buf) {
1082
6168
  Debug(this, "Read %zd bytes from underlying stream", nread);
1083
6168
  if (nread < 0)  {
1084
    // Error should be emitted only after all data was read
1085
133
    ClearOut();
1086
1087
    // Ignore EOF if received close_notify
1088
133
    if (nread == UV_EOF) {
1089
131
      if (eof_)
1090
3
        return;
1091
128
      eof_ = true;
1092
    }
1093
1094
130
    EmitRead(nread);
1095
130
    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
6035
  CHECK(ssl_);
1102
1103
  // Commit the amount of data actually read into the peeked/allocated buffer
1104
  // from the underlying stream.
1105
6035
  NodeBIO* enc_in = NodeBIO::FromBIO(enc_in_);
1106
6035
  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
6035
  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
6015
  Cycle();
1122
}
1123
1124
1391
ShutdownWrap* TLSWrap::CreateShutdownWrap(Local<Object> req_wrap_object) {
1125
1391
  return underlying_stream()->CreateShutdownWrap(req_wrap_object);
1126
}
1127
1128
1391
int TLSWrap::DoShutdown(ShutdownWrap* req_wrap) {
1129
1391
  Debug(this, "DoShutdown()");
1130
2782
  MarkPopErrorOnReturn mark_pop_error_on_return;
1131
1132

1391
  if (ssl_ && SSL_shutdown(ssl_.get()) == 0)
1133
854
    SSL_shutdown(ssl_.get());
1134
1135
1391
  shutdown_ = true;
1136
1391
  EncOut();
1137
2782
  return underlying_stream()->DoShutdown(req_wrap);
1138
}
1139
1140
12189
void TLSWrap::SetVerifyMode(const FunctionCallbackInfo<Value>& args) {
1141
  TLSWrap* wrap;
1142
12189
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1143
1144
12189
  CHECK_EQ(args.Length(), 2);
1145
24378
  CHECK(args[0]->IsBoolean());
1146
24378
  CHECK(args[1]->IsBoolean());
1147
12189
  CHECK_NOT_NULL(wrap->ssl_);
1148
1149
  int verify_mode;
1150
12189
  if (wrap->is_server()) {
1151
1670
    bool request_cert = args[0]->IsTrue();
1152
835
    if (!request_cert) {
1153
      // If no cert is requested, there will be none to reject as unauthorized.
1154
754
      verify_mode = SSL_VERIFY_NONE;
1155
    } else {
1156
162
      bool reject_unauthorized = args[1]->IsTrue();
1157
81
      verify_mode = SSL_VERIFY_PEER;
1158
81
      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
11354
    verify_mode = SSL_VERIFY_NONE;
1166
  }
1167
1168
  // Always allow a connection. We'll reject in javascript.
1169
12189
  SSL_set_verify(wrap->ssl_.get(), verify_mode, VerifyCallback);
1170
}
1171
1172
212
void TLSWrap::EnableSessionCallbacks(const FunctionCallbackInfo<Value>& args) {
1173
  TLSWrap* wrap;
1174
404
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1175
212
  CHECK_NOT_NULL(wrap->ssl_);
1176
212
  wrap->enable_session_callbacks();
1177
1178
  // Clients don't use the HelloParser.
1179
212
  if (wrap->is_client())
1180
192
    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
12138
void TLSWrap::DestroySSL(const FunctionCallbackInfo<Value>& args) {
1229
  TLSWrap* wrap;
1230
12138
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1231
12138
  wrap->Destroy();
1232
12138
  Debug(wrap, "DestroySSL() finished");
1233
}
1234
1235
24314
void TLSWrap::Destroy() {
1236
24314
  if (!ssl_)
1237
12122
    return;
1238
1239
  // If there is a write happening, mark it as finished.
1240
12192
  write_callback_scheduled_ = true;
1241
1242
  // And destroy
1243
12192
  InvokeQueued(UV_ECANCELED, "Canceled because of SSL destruction");
1244
1245
12192
  env()->isolate()->AdjustAmountOfExternalAllocatedMemory(-kExternalSize);
1246
12192
  ssl_.reset();
1247
1248
12192
  enc_in_ = nullptr;
1249
12192
  enc_out_ = nullptr;
1250
1251
12192
  if (underlying_stream() != nullptr)
1252
12155
    underlying_stream()->RemoveStreamListener(this);
1253
1254
12192
  sc_.reset();
1255
}
1256
1257
22
void TLSWrap::EnableCertCb(const FunctionCallbackInfo<Value>& args) {
1258
  TLSWrap* wrap;
1259
22
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1260
22
  wrap->WaitForCertCb(OnClientHelloParseEnd, wrap);
1261
}
1262
1263
22
void TLSWrap::WaitForCertCb(CertCb cb, void* arg) {
1264
22
  cert_cb_ = cb;
1265
22
  cert_cb_arg_ = arg;
1266
22
}
1267
1268
36
void TLSWrap::OnClientHelloParseEnd(void* arg) {
1269
36
  TLSWrap* c = static_cast<TLSWrap*>(arg);
1270
  Debug(c, "OnClientHelloParseEnd()");
1271
36
  c->Cycle();
1272
36
}
1273
1274
1334
void TLSWrap::GetServername(const FunctionCallbackInfo<Value>& args) {
1275
1334
  Environment* env = Environment::GetCurrent(args);
1276
1277
  TLSWrap* wrap;
1278
1334
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1279
1280
1334
  CHECK_NOT_NULL(wrap->ssl_);
1281
1282
1334
  const char* servername = SSL_get_servername(wrap->ssl_.get(),
1283
1334
                                              TLSEXT_NAMETYPE_host_name);
1284
1334
  if (servername != nullptr) {
1285
531
    args.GetReturnValue().Set(OneByteString(env->isolate(), servername));
1286
  } else {
1287
2314
    args.GetReturnValue().Set(false);
1288
  }
1289
}
1290
1291
191
void TLSWrap::SetServername(const FunctionCallbackInfo<Value>& args) {
1292
191
  Environment* env = Environment::GetCurrent(args);
1293
1294
  TLSWrap* wrap;
1295
191
  ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder());
1296
1297
191
  CHECK_EQ(args.Length(), 1);
1298
573
  CHECK(args[0]->IsString());
1299
191
  CHECK(!wrap->started_);
1300
191
  CHECK(wrap->is_client());
1301
1302
191
  CHECK(wrap->ssl_);
1303
1304
573
  Utf8Value servername(env->isolate(), args[0].As<String>());
1305
191
  SSL_set_tlsext_host_name(wrap->ssl_.get(), *servername);
1306
}
1307
1308
899
int TLSWrap::SelectSNIContextCallback(SSL* s, int* ad, void* arg) {
1309
899
  TLSWrap* p = static_cast<TLSWrap*>(SSL_get_app_data(s));
1310
899
  Environment* env = p->env();
1311
1798
  HandleScope handle_scope(env->isolate());
1312
899
  Context::Scope context_scope(env->context());
1313
1314
899
  const char* servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
1315
899
  if (!Set(env, p->GetOwner(), env->servername_string(), servername))
1316
    return SSL_TLSEXT_ERR_NOACK;
1317
1318
3596
  Local<Value> ctx = p->object()->Get(env->context(), env->sni_context_string())
1319
1798
      .FromMaybe(Local<Value>());
1320
1321

1798
  if (UNLIKELY(ctx.IsEmpty()) || !ctx->IsObject())
1322
899
    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
#ifndef OPENSSL_NO_PSK
1343
1344
8
int TLSWrap::SetCACerts(SecureContext* sc) {
1345
8
  int err = SSL_set1_verify_cert_store(
1346
      ssl_.get(), SSL_CTX_get_cert_store(sc->ctx_.get()));
1347
8
  if (err != 1)
1348
    return err;
1349
1350
  STACK_OF(X509_NAME)* list =
1351
8
      SSL_dup_CA_list(SSL_CTX_get_client_CA_list(sc->ctx_.get()));
1352
1353
  // NOTE: `SSL_set_client_CA_list` takes the ownership of `list`
1354
8
  SSL_set_client_CA_list(ssl_.get(), list);
1355
8
  return 1;
1356
}
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
19
void TLSWrap::CertCbDone(const FunctionCallbackInfo<Value>& args) {
1511
19
  Environment* env = Environment::GetCurrent(args);
1512
  TLSWrap* w;
1513
21
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1514
1515

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


9
    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
17
  cb = w->cert_cb_;
1547
17
  arg = w->cert_cb_arg_;
1548
1549
17
  w->cert_cb_running_ = false;
1550
17
  w->cert_cb_ = nullptr;
1551
17
  w->cert_cb_arg_ = nullptr;
1552
1553
17
  cb(arg);
1554
}
1555
1556
215
void TLSWrap::SetALPNProtocols(const FunctionCallbackInfo<Value>& args) {
1557
  TLSWrap* w;
1558
215
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1559
215
  Environment* env = w->env();
1560

430
  if (args.Length() < 1 || !Buffer::HasInstance(args[0]))
1561
    return env->ThrowTypeError("Must give a Buffer as first argument");
1562
1563
215
  if (w->is_client()) {
1564
36
    CHECK(SetALPN(w->ssl_, args[0]));
1565
  } else {
1566
537
    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
179
    SSL_CTX_set_alpn_select_cb(SSL_get_SSL_CTX(w->ssl_.get()),
1573
                               SelectALPNCallback,
1574
179
                               nullptr);
1575
  }
1576
}
1577
1578
440
void TLSWrap::GetPeerCertificate(const FunctionCallbackInfo<Value>& args) {
1579
  TLSWrap* w;
1580
440
  ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder());
1581
440
  Environment* env = w->env();
1582
1583

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

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

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

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

8
  } else if (alpn_proto_len == sizeof("http/1.1") - 1 &&
1963
2
             0 == memcmp(alpn_proto, "http/1.1", sizeof("http/1.1") - 1)) {
1964
4
    result = env->http_1_1_string();
1965
  } else {
1966
8
    result = OneByteString(env->isolate(), alpn_proto, alpn_proto_len);
1967
  }
1968
1969
3302
  args.GetReturnValue().Set(result);
1970
}
1971
1972
6059
void TLSWrap::Cycle() {
1973
  // Prevent recursion
1974
6059
  if (++cycle_depth_ > 1)
1975
11
    return;
1976
1977
18162
  for (; cycle_depth_ > 0; cycle_depth_--) {
1978
6059
    ClearIn();
1979
6059
    ClearOut();
1980
    // EncIn() doesn't exist, it happens via stream listener callbacks.
1981
6058
    EncOut();
1982
  }
1983
}
1984
1985
#ifdef SSL_set_max_send_fragment
1986
3
void TLSWrap::SetMaxSendFragment(const FunctionCallbackInfo<Value>& args) {
1987

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

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