GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: crypto/crypto_tls.cc Lines: 1030 1119 92.0 %
Date: 2021-12-02 04:14:02 Branches: 437 668 65.4 %

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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