-
Notifications
You must be signed in to change notification settings - Fork 29.8k
/
crypto_tls.cc
2295 lines (1888 loc) Β· 72 KB
/
crypto_tls.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
#include "crypto/crypto_tls.h"
#include <cstdio>
#include "async_wrap-inl.h"
#include "crypto/crypto_bio.h"
#include "crypto/crypto_clienthello-inl.h"
#include "crypto/crypto_common.h"
#include "crypto/crypto_context.h"
#include "crypto/crypto_util.h"
#include "debug_utils-inl.h"
#include "memory_tracker-inl.h"
#include "node_buffer.h"
#include "node_errors.h"
#include "stream_base-inl.h"
#include "util-inl.h"
namespace node {
using v8::Array;
using v8::ArrayBuffer;
using v8::ArrayBufferView;
using v8::BackingStore;
using v8::Boolean;
using v8::Context;
using v8::DontDelete;
using v8::Exception;
using v8::False;
using v8::Function;
using v8::FunctionCallbackInfo;
using v8::FunctionTemplate;
using v8::HandleScope;
using v8::Integer;
using v8::Isolate;
using v8::Local;
using v8::MaybeLocal;
using v8::Null;
using v8::Object;
using v8::PropertyAttribute;
using v8::ReadOnly;
using v8::Signature;
using v8::String;
using v8::Uint32;
using v8::Value;
namespace crypto {
namespace {
// Our custom implementation of the certificate verify callback
// used when establishing a TLS handshake. Because we cannot perform
// I/O quickly enough with X509_STORE_CTX_ APIs in this callback,
// we ignore preverify_ok errors here and let the handshake continue.
// In other words, this VerifyCallback is a non-op. It is imperative
// that the user user Connection::VerifyError after the `secure`
// callback has been made.
int VerifyCallback(int preverify_ok, X509_STORE_CTX* ctx) {
// From https://www.openssl.org/docs/man1.1.1/man3/SSL_verify_cb:
//
// If VerifyCallback returns 1, the verification process is continued. If
// VerifyCallback always returns 1, the TLS/SSL handshake will not be
// terminated with respect to verification failures and the connection will
// be established. The calling process can however retrieve the error code
// of the last verification error using SSL_get_verify_result(3) or by
// maintaining its own error storage managed by VerifyCallback.
return 1;
}
SSL_SESSION* GetSessionCallback(
SSL* s,
const unsigned char* key,
int len,
int* copy) {
TLSWrap* w = static_cast<TLSWrap*>(SSL_get_app_data(s));
*copy = 0;
return w->ReleaseSession();
}
void OnClientHello(
void* arg,
const ClientHelloParser::ClientHello& hello) {
TLSWrap* w = static_cast<TLSWrap*>(arg);
Environment* env = w->env();
HandleScope handle_scope(env->isolate());
Context::Scope context_scope(env->context());
Local<Object> hello_obj = Object::New(env->isolate());
Local<String> servername = (hello.servername() == nullptr)
? String::Empty(env->isolate())
: OneByteString(env->isolate(),
hello.servername(),
hello.servername_size());
Local<Object> buf =
Buffer::Copy(
env,
reinterpret_cast<const char*>(hello.session_id()),
hello.session_size()).FromMaybe(Local<Object>());
if ((buf.IsEmpty() ||
hello_obj->Set(env->context(), env->session_id_string(), buf)
.IsNothing()) ||
hello_obj->Set(env->context(), env->servername_string(), servername)
.IsNothing() ||
hello_obj
->Set(env->context(),
env->tls_ticket_string(),
Boolean::New(env->isolate(), hello.has_ticket()))
.IsNothing()) {
return;
}
Local<Value> argv[] = { hello_obj };
w->MakeCallback(env->onclienthello_string(), arraysize(argv), argv);
}
void KeylogCallback(const SSL* s, const char* line) {
TLSWrap* w = static_cast<TLSWrap*>(SSL_get_app_data(s));
Environment* env = w->env();
HandleScope handle_scope(env->isolate());
Context::Scope context_scope(env->context());
const size_t size = strlen(line);
Local<Value> line_bf = Buffer::Copy(env, line, 1 + size)
.FromMaybe(Local<Value>());
if (line_bf.IsEmpty()) [[unlikely]]
return;
char* data = Buffer::Data(line_bf);
data[size] = '\n';
w->MakeCallback(env->onkeylog_string(), 1, &line_bf);
}
int NewSessionCallback(SSL* s, SSL_SESSION* sess) {
TLSWrap* w = static_cast<TLSWrap*>(SSL_get_app_data(s));
Environment* env = w->env();
HandleScope handle_scope(env->isolate());
Context::Scope context_scope(env->context());
if (!w->has_session_callbacks())
return 0;
// Check if session is small enough to be stored
int size = i2d_SSL_SESSION(sess, nullptr);
if (size > SecureContext::kMaxSessionSize) [[unlikely]]
return 0;
// Serialize session
Local<Object> session = Buffer::New(env, size).FromMaybe(Local<Object>());
if (session.IsEmpty()) [[unlikely]]
return 0;
unsigned char* session_data =
reinterpret_cast<unsigned char*>(Buffer::Data(session));
CHECK_EQ(i2d_SSL_SESSION(sess, &session_data), size);
unsigned int session_id_length;
const unsigned char* session_id_data =
SSL_SESSION_get_id(sess, &session_id_length);
Local<Object> session_id = Buffer::Copy(
env,
reinterpret_cast<const char*>(session_id_data),
session_id_length).FromMaybe(Local<Object>());
if (session_id.IsEmpty()) [[unlikely]]
return 0;
Local<Value> argv[] = {
session_id,
session
};
// On servers, we pause the handshake until callback of 'newSession', which
// calls NewSessionDoneCb(). On clients, there is no callback to wait for.
if (w->is_server())
w->set_awaiting_new_session(true);
w->MakeCallback(env->onnewsession_string(), arraysize(argv), argv);
return 0;
}
int SSLCertCallback(SSL* s, void* arg) {
TLSWrap* w = static_cast<TLSWrap*>(SSL_get_app_data(s));
if (!w->is_server() || !w->is_waiting_cert_cb())
return 1;
if (w->is_cert_cb_running())
// Not an error. Suspend handshake with SSL_ERROR_WANT_X509_LOOKUP, and
// handshake will continue after certcb is done.
return -1;
Environment* env = w->env();
HandleScope handle_scope(env->isolate());
Context::Scope context_scope(env->context());
w->set_cert_cb_running();
Local<Object> info = Object::New(env->isolate());
const char* servername = GetServerName(s);
Local<String> servername_str = (servername == nullptr)
? String::Empty(env->isolate())
: OneByteString(env->isolate(), servername, strlen(servername));
Local<Value> ocsp = Boolean::New(
env->isolate(), SSL_get_tlsext_status_type(s) == TLSEXT_STATUSTYPE_ocsp);
if (info->Set(env->context(), env->servername_string(), servername_str)
.IsNothing() ||
info->Set(env->context(), env->ocsp_request_string(), ocsp).IsNothing()) {
return 1;
}
Local<Value> argv[] = { info };
w->MakeCallback(env->oncertcb_string(), arraysize(argv), argv);
return w->is_cert_cb_running() ? -1 : 1;
}
int SelectALPNCallback(
SSL* s,
const unsigned char** out,
unsigned char* outlen,
const unsigned char* in,
unsigned int inlen,
void* arg) {
TLSWrap* w = static_cast<TLSWrap*>(SSL_get_app_data(s));
if (w->alpn_callback_enabled_) {
Environment* env = w->env();
HandleScope handle_scope(env->isolate());
Local<Value> callback_arg =
Buffer::Copy(env, reinterpret_cast<const char*>(in), inlen)
.ToLocalChecked();
MaybeLocal<Value> maybe_callback_result =
w->MakeCallback(env->alpn_callback_string(), 1, &callback_arg);
if (maybe_callback_result.IsEmpty()) [[unlikely]] {
// Implies the callback didn't return, because some exception was thrown
// during processing, e.g. if callback returned an invalid ALPN value.
return SSL_TLSEXT_ERR_ALERT_FATAL;
}
Local<Value> callback_result = maybe_callback_result.ToLocalChecked();
if (callback_result->IsUndefined()) {
// If you set an ALPN callback, but you return undefined for an ALPN
// request, you're rejecting all proposed ALPN protocols, and so we send
// a fatal alert:
return SSL_TLSEXT_ERR_ALERT_FATAL;
}
CHECK(callback_result->IsNumber());
unsigned int result_int = callback_result.As<v8::Number>()->Value();
// The callback returns an offset into the given buffer, for the selected
// protocol that should be returned. We then set outlen & out to point
// to the selected input length & value directly:
*outlen = *(in + result_int);
*out = (in + result_int + 1);
return SSL_TLSEXT_ERR_OK;
}
const std::vector<unsigned char>& alpn_protos = w->alpn_protos_;
if (alpn_protos.empty()) return SSL_TLSEXT_ERR_NOACK;
int status = SSL_select_next_proto(const_cast<unsigned char**>(out),
outlen,
alpn_protos.data(),
alpn_protos.size(),
in,
inlen);
// Previous versions of Node.js returned SSL_TLSEXT_ERR_NOACK if no protocol
// match was found. This would neither cause a fatal alert nor would it result
// in a useful ALPN response as part of the Server Hello message.
// We now return SSL_TLSEXT_ERR_ALERT_FATAL in that case as per Section 3.2
// of RFC 7301, which causes a fatal no_application_protocol alert.
return status == OPENSSL_NPN_NEGOTIATED ? SSL_TLSEXT_ERR_OK
: SSL_TLSEXT_ERR_ALERT_FATAL;
}
int TLSExtStatusCallback(SSL* s, void* arg) {
TLSWrap* w = static_cast<TLSWrap*>(SSL_get_app_data(s));
Environment* env = w->env();
HandleScope handle_scope(env->isolate());
if (w->is_client()) {
// Incoming response
Local<Value> arg;
if (GetSSLOCSPResponse(env, s, Null(env->isolate())).ToLocal(&arg))
w->MakeCallback(env->onocspresponse_string(), 1, &arg);
// No async acceptance is possible, so always return 1 to accept the
// response. The listener for 'OCSPResponse' event has no control over
// return value, but it can .destroy() the connection if the response is not
// acceptable.
return 1;
}
// Outgoing response
Local<ArrayBufferView> obj =
w->ocsp_response().FromMaybe(Local<ArrayBufferView>());
if (obj.IsEmpty()) [[unlikely]]
return SSL_TLSEXT_ERR_NOACK;
size_t len = obj->ByteLength();
// OpenSSL takes control of the pointer after accepting it
unsigned char* data = MallocOpenSSL<unsigned char>(len);
obj->CopyContents(data, len);
if (!SSL_set_tlsext_status_ocsp_resp(s, data, len))
OPENSSL_free(data);
w->ClearOcspResponse();
return SSL_TLSEXT_ERR_OK;
}
void ConfigureSecureContext(SecureContext* sc) {
// OCSP stapling
SSL_CTX_set_tlsext_status_cb(sc->ctx().get(), TLSExtStatusCallback);
SSL_CTX_set_tlsext_status_arg(sc->ctx().get(), nullptr);
}
inline bool Set(
Environment* env,
Local<Object> target,
Local<String> name,
const char* value,
bool ignore_null = true) {
if (value == nullptr)
return ignore_null;
return !target->Set(
env->context(),
name,
OneByteString(env->isolate(), value))
.IsNothing();
}
std::string GetBIOError() {
std::string ret;
ERR_print_errors_cb(
[](const char* str, size_t len, void* opaque) {
static_cast<std::string*>(opaque)->assign(str, len);
return 0;
},
static_cast<void*>(&ret));
return ret;
}
} // namespace
TLSWrap::TLSWrap(Environment* env,
Local<Object> obj,
Kind kind,
StreamBase* stream,
SecureContext* sc,
UnderlyingStreamWriteStatus under_stream_ws)
: AsyncWrap(env, obj, AsyncWrap::PROVIDER_TLSWRAP),
StreamBase(env),
env_(env),
kind_(kind),
sc_(sc),
has_active_write_issued_by_prev_listener_(
under_stream_ws == UnderlyingStreamWriteStatus::kHasActive) {
MakeWeak();
CHECK(sc_);
ssl_ = sc_->CreateSSL();
CHECK(ssl_);
sc_->SetGetSessionCallback(GetSessionCallback);
sc_->SetNewSessionCallback(NewSessionCallback);
StreamBase::AttachToObject(GetObject());
stream->PushStreamListener(this);
env_->isolate()->AdjustAmountOfExternalAllocatedMemory(kExternalSize);
InitSSL();
Debug(this, "Created new TLSWrap");
}
TLSWrap::~TLSWrap() {
Destroy();
}
MaybeLocal<ArrayBufferView> TLSWrap::ocsp_response() const {
if (ocsp_response_.IsEmpty())
return MaybeLocal<ArrayBufferView>();
return PersistentToLocal::Default(env()->isolate(), ocsp_response_);
}
void TLSWrap::ClearOcspResponse() {
ocsp_response_.Reset();
}
SSL_SESSION* TLSWrap::ReleaseSession() {
return next_sess_.release();
}
void TLSWrap::InvokeQueued(int status, const char* error_str) {
Debug(this, "Invoking queued write callbacks (%d, %s)", status, error_str);
if (!write_callback_scheduled_)
return;
if (current_write_) {
BaseObjectPtr<AsyncWrap> current_write = std::move(current_write_);
current_write_.reset();
WriteWrap* w = WriteWrap::FromObject(current_write);
w->Done(status, error_str);
}
}
void TLSWrap::NewSessionDoneCb() {
Debug(this, "New session callback done");
Cycle();
}
void TLSWrap::InitSSL() {
// Initialize SSL β OpenSSL takes ownership of these.
enc_in_ = NodeBIO::New(env()).release();
enc_out_ = NodeBIO::New(env()).release();
SSL_set_bio(ssl_.get(), enc_in_, enc_out_);
// NOTE: This could be overridden in SetVerifyMode
SSL_set_verify(ssl_.get(), SSL_VERIFY_NONE, VerifyCallback);
#ifdef SSL_MODE_RELEASE_BUFFERS
SSL_set_mode(ssl_.get(), SSL_MODE_RELEASE_BUFFERS);
#endif // SSL_MODE_RELEASE_BUFFERS
// This is default in 1.1.1, but set it anyway, Cycle() doesn't currently
// re-call ClearIn() if SSL_read() returns SSL_ERROR_WANT_READ, so data can be
// left sitting in the incoming enc_in_ and never get processed.
// - https://wiki.openssl.org/index.php/TLS1.3#Non-application_data_records
SSL_set_mode(ssl_.get(), SSL_MODE_AUTO_RETRY);
#ifdef OPENSSL_IS_BORINGSSL
// OpenSSL allows renegotiation by default, but BoringSSL disables it.
// Configure BoringSSL to match OpenSSL's behavior.
SSL_set_renegotiate_mode(ssl_.get(), ssl_renegotiate_freely);
#endif
SSL_set_app_data(ssl_.get(), this);
// Using InfoCallback isn't how we are supposed to check handshake progress:
// https://github.com/openssl/openssl/issues/7199#issuecomment-420915993
//
// Note on when this gets called on various openssl versions:
// https://github.com/openssl/openssl/issues/7199#issuecomment-420670544
SSL_set_info_callback(ssl_.get(), SSLInfoCallback);
if (is_server())
sc_->SetSelectSNIContextCallback(SelectSNIContextCallback);
ConfigureSecureContext(sc_.get());
SSL_set_cert_cb(ssl_.get(), SSLCertCallback, this);
if (is_server()) {
SSL_set_accept_state(ssl_.get());
} else if (is_client()) {
// Enough space for server response (hello, cert)
NodeBIO::FromBIO(enc_in_)->set_initial(kInitialClientBufferLength);
SSL_set_connect_state(ssl_.get());
} else {
// Unexpected
ABORT();
}
}
void TLSWrap::Wrap(const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args);
CHECK_EQ(args.Length(), 4);
CHECK(args[0]->IsObject());
CHECK(args[1]->IsObject());
CHECK(args[2]->IsBoolean());
CHECK(args[3]->IsBoolean());
Local<Object> sc = args[1].As<Object>();
Kind kind = args[2]->IsTrue() ? Kind::kServer : Kind::kClient;
UnderlyingStreamWriteStatus under_stream_ws =
args[3]->IsTrue() ? UnderlyingStreamWriteStatus::kHasActive
: UnderlyingStreamWriteStatus::kVacancy;
StreamBase* stream = StreamBase::FromObject(args[0].As<Object>());
CHECK_NOT_NULL(stream);
Local<Object> obj;
if (!env->tls_wrap_constructor_function()
->NewInstance(env->context())
.ToLocal(&obj)) {
return;
}
TLSWrap* res = new TLSWrap(
env, obj, kind, stream, Unwrap<SecureContext>(sc), under_stream_ws);
args.GetReturnValue().Set(res->object());
}
void TLSWrap::Receive(const FunctionCallbackInfo<Value>& args) {
TLSWrap* wrap;
ASSIGN_OR_RETURN_UNWRAP(&wrap, args.This());
ArrayBufferViewContents<char> buffer(args[0]);
const char* data = buffer.data();
size_t len = buffer.length();
Debug(wrap, "Receiving %zu bytes injected from JS", len);
// Copy given buffer entirely or partiall if handle becomes closed
while (len > 0 && wrap->IsAlive() && !wrap->IsClosing()) {
uv_buf_t buf = wrap->OnStreamAlloc(len);
size_t copy = buf.len > len ? len : buf.len;
memcpy(buf.base, data, copy);
buf.len = copy;
wrap->OnStreamRead(copy, buf);
data += copy;
len -= copy;
}
}
void TLSWrap::Start(const FunctionCallbackInfo<Value>& args) {
TLSWrap* wrap;
ASSIGN_OR_RETURN_UNWRAP(&wrap, args.This());
CHECK(!wrap->started_);
wrap->started_ = true;
// Send ClientHello handshake
CHECK(wrap->is_client());
// Seems odd to read when when we want to send, but SSL_read() triggers a
// handshake if a session isn't established, and handshake will cause
// encrypted data to become available for output.
wrap->ClearOut();
wrap->EncOut();
}
void TLSWrap::SSLInfoCallback(const SSL* ssl_, int where, int ret) {
if (!(where & (SSL_CB_HANDSHAKE_START | SSL_CB_HANDSHAKE_DONE)))
return;
// SSL_renegotiate_pending() should take `const SSL*`, but it does not.
SSL* ssl = const_cast<SSL*>(ssl_);
TLSWrap* c = static_cast<TLSWrap*>(SSL_get_app_data(ssl_));
Environment* env = c->env();
HandleScope handle_scope(env->isolate());
Context::Scope context_scope(env->context());
Local<Object> object = c->object();
if (where & SSL_CB_HANDSHAKE_START) {
Debug(c, "SSLInfoCallback(SSL_CB_HANDSHAKE_START);");
// Start is tracked to limit number and frequency of renegotiation attempts,
// since excessive renegotiation may be an attack.
Local<Value> callback;
if (object->Get(env->context(), env->onhandshakestart_string())
.ToLocal(&callback) && callback->IsFunction()) {
Local<Value> argv[] = { env->GetNow() };
c->MakeCallback(callback.As<Function>(), arraysize(argv), argv);
}
}
// SSL_CB_HANDSHAKE_START and SSL_CB_HANDSHAKE_DONE are called
// sending HelloRequest in OpenSSL-1.1.1.
// We need to check whether this is in a renegotiation state or not.
if (where & SSL_CB_HANDSHAKE_DONE && !SSL_renegotiate_pending(ssl)) {
Debug(c, "SSLInfoCallback(SSL_CB_HANDSHAKE_DONE);");
CHECK(!SSL_renegotiate_pending(ssl));
Local<Value> callback;
c->established_ = true;
if (object->Get(env->context(), env->onhandshakedone_string())
.ToLocal(&callback) && callback->IsFunction()) {
c->MakeCallback(callback.As<Function>(), 0, nullptr);
}
}
}
void TLSWrap::EncOut() {
Debug(this, "Trying to write encrypted output");
// Ignore cycling data if ClientHello wasn't yet parsed
if (!hello_parser_.IsEnded()) {
Debug(this, "Returning from EncOut(), hello_parser_ active");
return;
}
// Write in progress
if (write_size_ != 0) {
Debug(this, "Returning from EncOut(), write currently in progress");
return;
}
// Wait for `newSession` callback to be invoked
if (is_awaiting_new_session()) {
Debug(this, "Returning from EncOut(), awaiting new session");
return;
}
if (has_active_write_issued_by_prev_listener_) [[unlikely]] {
Debug(this,
"Returning from EncOut(), "
"has_active_write_issued_by_prev_listener_ is true");
return;
}
// Split-off queue
if (established_ && current_write_) {
Debug(this, "EncOut() write is scheduled");
write_callback_scheduled_ = true;
}
if (ssl_ == nullptr) {
Debug(this, "Returning from EncOut(), ssl_ == nullptr");
return;
}
// No encrypted output ready to write to the underlying stream.
if (BIO_pending(enc_out_) == 0) {
Debug(this, "No pending encrypted output");
if (!pending_cleartext_input_ ||
pending_cleartext_input_->ByteLength() == 0) {
if (!in_dowrite_) {
Debug(this, "No pending cleartext input, not inside DoWrite()");
InvokeQueued(0);
} else {
Debug(this, "No pending cleartext input, inside DoWrite()");
// TODO(@sam-github, @addaleax) If in_dowrite_ is true, appdata was
// passed to SSL_write(). If we are here, the data was not encrypted to
// enc_out_ yet. Calling Done() "works", but since the write is not
// flushed, its too soon. Just returning and letting the next EncOut()
// call Done() passes the test suite, but without more careful analysis,
// its not clear if it is always correct. Not calling Done() could block
// data flow, so for now continue to call Done(), just do it in the next
// tick.
BaseObjectPtr<TLSWrap> strong_ref{this};
env()->SetImmediate([this, strong_ref](Environment* env) {
InvokeQueued(0);
});
}
}
return;
}
char* data[kSimultaneousBufferCount];
size_t size[arraysize(data)];
size_t count = arraysize(data);
write_size_ = NodeBIO::FromBIO(enc_out_)->PeekMultiple(data, size, &count);
CHECK(write_size_ != 0 && count != 0);
uv_buf_t buf[arraysize(data)];
uv_buf_t* bufs = buf;
for (size_t i = 0; i < count; i++)
buf[i] = uv_buf_init(data[i], size[i]);
Debug(this, "Writing %zu buffers to the underlying stream", count);
StreamWriteResult res = underlying_stream()->Write(bufs, count);
if (res.err != 0) {
InvokeQueued(res.err);
return;
}
if (!res.async) {
Debug(this, "Write finished synchronously");
HandleScope handle_scope(env()->isolate());
// Simulate asynchronous finishing, TLS cannot handle this at the moment.
BaseObjectPtr<TLSWrap> strong_ref{this};
env()->SetImmediate([this, strong_ref](Environment* env) {
OnStreamAfterWrite(nullptr, 0);
});
}
}
void TLSWrap::OnStreamAfterWrite(WriteWrap* req_wrap, int status) {
Debug(this, "OnStreamAfterWrite(status = %d)", status);
if (has_active_write_issued_by_prev_listener_) [[unlikely]] {
Debug(this, "Notify write finish to the previous_listener_");
CHECK_EQ(write_size_, 0); // we must have restrained writes
previous_listener_->OnStreamAfterWrite(req_wrap, status);
return;
}
if (current_empty_write_) {
Debug(this, "Had empty write");
BaseObjectPtr<AsyncWrap> current_empty_write =
std::move(current_empty_write_);
current_empty_write_.reset();
WriteWrap* finishing = WriteWrap::FromObject(current_empty_write);
finishing->Done(status);
return;
}
if (ssl_ == nullptr) {
Debug(this, "ssl_ == nullptr, marking as cancelled");
status = UV_ECANCELED;
}
// Handle error
if (status) {
if (shutdown_) {
Debug(this, "Ignoring error after shutdown");
return;
}
// Notify about error
InvokeQueued(status);
return;
}
// Commit
NodeBIO::FromBIO(enc_out_)->Read(nullptr, write_size_);
// Ensure that the progress will be made and `InvokeQueued` will be called.
ClearIn();
// Try writing more data
write_size_ = 0;
EncOut();
}
void TLSWrap::ClearOut() {
Debug(this, "Trying to read cleartext output");
// Ignore cycling data if ClientHello wasn't yet parsed
if (!hello_parser_.IsEnded()) {
Debug(this, "Returning from ClearOut(), hello_parser_ active");
return;
}
// No reads after EOF
if (eof_) {
Debug(this, "Returning from ClearOut(), EOF reached");
return;
}
if (ssl_ == nullptr) {
Debug(this, "Returning from ClearOut(), ssl_ == nullptr");
return;
}
MarkPopErrorOnReturn mark_pop_error_on_return;
char out[kClearOutChunkSize];
int read;
for (;;) {
read = SSL_read(ssl_.get(), out, sizeof(out));
Debug(this, "Read %d bytes of cleartext output", read);
if (read <= 0)
break;
char* current = out;
while (read > 0) {
int avail = read;
uv_buf_t buf = EmitAlloc(avail);
if (static_cast<int>(buf.len) < avail)
avail = buf.len;
memcpy(buf.base, current, avail);
EmitRead(avail, buf);
// Caveat emptor: OnRead() calls into JS land which can result in
// the SSL context object being destroyed. We have to carefully
// check that ssl_ != nullptr afterwards.
if (ssl_ == nullptr) {
Debug(this, "Returning from read loop, ssl_ == nullptr");
return;
}
read -= avail;
current += avail;
}
}
// We need to check whether an error occurred or the connection was
// shutdown cleanly (SSL_ERROR_ZERO_RETURN) even when read == 0.
// See node#1642 and SSL_read(3SSL) for details. SSL_get_error must be
// called immediately after SSL_read, without calling into JS, which may
// change OpenSSL's error queue, modify ssl_, or even destroy ssl_
// altogether.
if (read <= 0) {
HandleScope handle_scope(env()->isolate());
Local<Value> error;
int err = SSL_get_error(ssl_.get(), read);
switch (err) {
case SSL_ERROR_ZERO_RETURN:
if (!eof_) {
eof_ = true;
EmitRead(UV_EOF);
}
return;
case SSL_ERROR_SSL:
case SSL_ERROR_SYSCALL:
{
unsigned long ssl_err = ERR_peek_error(); // NOLINT(runtime/int)
Local<Context> context = env()->isolate()->GetCurrentContext();
if (context.IsEmpty()) [[unlikely]]
return;
const std::string error_str = GetBIOError();
Local<String> message = OneByteString(
env()->isolate(), error_str.c_str(), error_str.size());
if (message.IsEmpty()) [[unlikely]]
return;
error = Exception::Error(message);
if (error.IsEmpty()) [[unlikely]]
return;
Local<Object> obj;
if (!error->ToObject(context).ToLocal(&obj)) [[unlikely]]
return;
const char* ls = ERR_lib_error_string(ssl_err);
const char* fs = ERR_func_error_string(ssl_err);
const char* rs = ERR_reason_error_string(ssl_err);
if (!Set(env(), obj, env()->library_string(), ls) ||
!Set(env(), obj, env()->function_string(), fs) ||
!Set(env(), obj, env()->reason_string(), rs, false)) return;
// SSL has no API to recover the error name from the number, so we
// transform reason strings like "this error" to "ERR_SSL_THIS_ERROR",
// which ends up being close to the original error macro name.
std::string code(rs);
// TODO(RaisinTen): Pass an appropriate execution policy when it is
// implemented in our supported compilers.
std::transform(code.begin(), code.end(), code.begin(),
[](char c) { return c == ' ' ? '_' : ToUpper(c); });
if (!Set(env(), obj,
env()->code_string(), ("ERR_SSL_" + code).c_str())) return;
}
break;
default:
return;
}
Debug(this, "Got SSL error (%d), calling onerror", err);
// When TLS Alert are stored in wbio,
// it should be flushed to socket before destroyed.
if (BIO_pending(enc_out_) != 0)
EncOut();
MakeCallback(env()->onerror_string(), 1, &error);
}
}
void TLSWrap::ClearIn() {
Debug(this, "Trying to write cleartext input");
// Ignore cycling data if ClientHello wasn't yet parsed
if (!hello_parser_.IsEnded()) {
Debug(this, "Returning from ClearIn(), hello_parser_ active");
return;
}
if (ssl_ == nullptr) {
Debug(this, "Returning from ClearIn(), ssl_ == nullptr");
return;
}
if (!pending_cleartext_input_ ||
pending_cleartext_input_->ByteLength() == 0) {
Debug(this, "Returning from ClearIn(), no pending data");
return;
}
std::unique_ptr<BackingStore> bs = std::move(pending_cleartext_input_);
MarkPopErrorOnReturn mark_pop_error_on_return;
NodeBIO::FromBIO(enc_out_)->set_allocate_tls_hint(bs->ByteLength());
int written = SSL_write(ssl_.get(), bs->Data(), bs->ByteLength());
Debug(this, "Writing %zu bytes, written = %d", bs->ByteLength(), written);
CHECK(written == -1 || written == static_cast<int>(bs->ByteLength()));
// All written
if (written != -1) {
Debug(this, "Successfully wrote all data to SSL");
return;
}
// Error or partial write
int err = SSL_get_error(ssl_.get(), written);
if (err == SSL_ERROR_SSL || err == SSL_ERROR_SYSCALL) {
Debug(this, "Got SSL error (%d)", err);
write_callback_scheduled_ = true;
// TODO(@sam-github) Should forward an error object with
// .code/.function/.etc, if possible.
InvokeQueued(UV_EPROTO, GetBIOError().c_str());
return;
}
Debug(this, "Pushing data back");
// Push back the not-yet-written data. This can be skipped in the error
// case because no further writes would succeed anyway.
pending_cleartext_input_ = std::move(bs);
}
std::string TLSWrap::diagnostic_name() const {
std::string name = "TLSWrap ";
name += is_server() ? "server (" : "client (";
name += std::to_string(static_cast<int64_t>(get_async_id())) + ")";
return name;
}
AsyncWrap* TLSWrap::GetAsyncWrap() {
return static_cast<AsyncWrap*>(this);
}
bool TLSWrap::IsIPCPipe() {
return underlying_stream()->IsIPCPipe();
}
int TLSWrap::GetFD() {
return underlying_stream()->GetFD();
}
bool TLSWrap::IsAlive() {
return ssl_ &&
underlying_stream() != nullptr &&
underlying_stream()->IsAlive();
}
bool TLSWrap::IsClosing() {
return underlying_stream()->IsClosing();
}
int TLSWrap::ReadStart() {
Debug(this, "ReadStart()");
if (underlying_stream() != nullptr && !eof_)
return underlying_stream()->ReadStart();
return 0;
}
int TLSWrap::ReadStop() {
Debug(this, "ReadStop()");
return underlying_stream() != nullptr ? underlying_stream()->ReadStop() : 0;
}
const char* TLSWrap::Error() const {
return error_.empty() ? nullptr : error_.c_str();
}
void TLSWrap::ClearError() {
error_.clear();
}
// Called by StreamBase::Write() to request async write of clear text into SSL.
// TODO(@sam-github) Should there be a TLSWrap::DoTryWrite()?
int TLSWrap::DoWrite(WriteWrap* w,
uv_buf_t* bufs,
size_t count,
uv_stream_t* send_handle) {
CHECK_NULL(send_handle);
Debug(this, "DoWrite()");
if (ssl_ == nullptr) {
ClearError();
error_ = "Write after DestroySSL";
return UV_EPROTO;
}
size_t length = 0;
size_t i;
size_t nonempty_i = 0;
size_t nonempty_count = 0;
for (i = 0; i < count; i++) {
length += bufs[i].len;
if (bufs[i].len > 0) {
nonempty_i = i;
nonempty_count += 1;
}