forked from nodejs/node
-
Notifications
You must be signed in to change notification settings - Fork 6
/
node_quic_session.cc
3689 lines (3295 loc) · 124 KB
/
node_quic_session.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
#include "node_quic_session-inl.h" // NOLINT(build/include)
#include "aliased_buffer.h"
#include "aliased_struct-inl.h"
#include "allocated_buffer-inl.h"
#include "async_wrap-inl.h"
#include "debug_utils-inl.h"
#include "env-inl.h"
#include "node_crypto_common.h"
#include "ngtcp2/ngtcp2.h"
#include "nghttp3/nghttp3.h" // NGHTTP3_ALPN_H3
#include "ngtcp2/ngtcp2_crypto.h"
#include "ngtcp2/ngtcp2_crypto_openssl.h"
#include "node.h"
#include "node_buffer.h"
#include "node_crypto.h"
#include "node_errors.h"
#include "node_internals.h"
#include "node_http_common-inl.h"
#include "node_mem-inl.h"
#include "node_process.h"
#include "node_quic_buffer-inl.h"
#include "node_quic_crypto.h"
#include "node_quic_socket-inl.h"
#include "node_quic_stream-inl.h"
#include "node_quic_util-inl.h"
#include "node_quic_default_application.h"
#include "node_quic_http3_application.h"
#include "node_sockaddr-inl.h"
#include "stream_base-inl.h"
#include "v8.h"
#include "uv.h"
#include <algorithm>
#include <vector>
#include <string>
#include <utility>
namespace node {
using crypto::EntropySource;
using crypto::SecureContext;
using v8::Array;
using v8::ArrayBufferView;
using v8::Context;
using v8::Function;
using v8::FunctionCallbackInfo;
using v8::FunctionTemplate;
using v8::HandleScope;
using v8::Integer;
using v8::Local;
using v8::Number;
using v8::Object;
using v8::ObjectTemplate;
using v8::PropertyAttribute;
using v8::String;
using v8::Undefined;
using v8::Value;
namespace quic {
namespace {
void SetConfig(QuicState* quic_state, int idx, uint64_t* val) {
AliasedFloat64Array& buffer = quic_state->quicsessionconfig_buffer;
uint64_t flags = static_cast<uint64_t>(buffer[IDX_QUIC_SESSION_CONFIG_COUNT]);
if (flags & (1ULL << idx))
*val = static_cast<uint64_t>(buffer[idx]);
}
// Forwards detailed(verbose) debugging information from ngtcp2. Enabled using
// the NODE_DEBUG_NATIVE=NGTCP2_DEBUG category.
void Ngtcp2DebugLog(void* user_data, const char* fmt, ...) {
va_list ap;
va_start(ap, fmt);
std::string format(fmt, strlen(fmt) + 1);
format[strlen(fmt)] = '\n';
// Debug() does not work with the va_list here. So we use vfprintf
// directly instead. Ngtcp2DebugLog is only enabled when the debug
// category is enabled.
vfprintf(stderr, format.c_str(), ap);
va_end(ap);
}
void CopyPreferredAddress(
uint8_t* dest,
size_t destlen,
uint16_t* port,
const sockaddr* addr) {
const sockaddr_in* src = reinterpret_cast<const sockaddr_in*>(addr);
memcpy(dest, &src->sin_addr, destlen);
*port = SocketAddress::GetPort(addr);
}
} // namespace
std::string QuicSession::RemoteTransportParamsDebug::ToString() const {
ngtcp2_transport_params params;
ngtcp2_conn_get_remote_transport_params(session->connection(), ¶ms);
std::string out = "Remote Transport Params:\n";
out += " Ack Delay Exponent: " +
std::to_string(params.ack_delay_exponent) + "\n";
out += " Active Connection ID Limit: " +
std::to_string(params.active_connection_id_limit) + "\n";
out += " Disable Active Migration: " +
std::string(params.disable_active_migration ? "Yes" : "No") + "\n";
out += " Initial Max Data: " +
std::to_string(params.initial_max_data) + "\n";
out += " Initial Max Stream Data Bidi Local: " +
std::to_string(params.initial_max_stream_data_bidi_local) + "\n";
out += " Initial Max Stream Data Bidi Remote: " +
std::to_string(params.initial_max_stream_data_bidi_remote) + "\n";
out += " Initial Max Stream Data Uni: " +
std::to_string(params.initial_max_stream_data_uni) + "\n";
out += " Initial Max Streams Bidi: " +
std::to_string(params.initial_max_streams_bidi) + "\n";
out += " Initial Max Streams Uni: " +
std::to_string(params.initial_max_streams_uni) + "\n";
out += " Max Ack Delay: " +
std::to_string(params.max_ack_delay) + "\n";
out += " Max Idle Timeout: " +
std::to_string(params.max_idle_timeout) + "\n";
out += " Max Packet Size: " +
std::to_string(params.max_udp_payload_size) + "\n";
if (!session->is_server()) {
if (params.retry_scid_present) {
QuicCID cid(params.original_dcid);
QuicCID retry(params.retry_scid);
out += " Original Connection ID: " + cid.ToString() + "\n";
out += " Retry SCID: " + retry.ToString() + "\n";
} else {
out += " Original Connection ID: N/A \n";
}
if (params.preferred_address_present) {
out += " Preferred Address Present: Yes\n";
// TODO(@jasnell): Serialize the IPv4 and IPv6 address options
} else {
out += " Preferred Address Present: No\n";
}
if (params.stateless_reset_token_present) {
StatelessResetToken token(params.stateless_reset_token);
out += " Stateless Reset Token: " + token.ToString() + "\n";
} else {
out += " Stateless Reset Token: N/A";
}
}
return out;
}
void QuicSessionConfig::ResetToDefaults(QuicState* quic_state) {
ngtcp2_settings_default(this);
initial_ts = uv_hrtime();
// Detailed(verbose) logging provided by ngtcp2 is only enabled
// when the NODE_DEBUG_NATIVE=NGTCP2_DEBUG category is used.
if (UNLIKELY(quic_state->env()->enabled_debug_list()->enabled(
DebugCategory::NGTCP2_DEBUG))) {
log_printf = Ngtcp2DebugLog;
}
transport_params.active_connection_id_limit =
DEFAULT_ACTIVE_CONNECTION_ID_LIMIT;
transport_params.initial_max_stream_data_bidi_local =
DEFAULT_MAX_STREAM_DATA_BIDI_LOCAL;
transport_params.initial_max_stream_data_bidi_remote =
DEFAULT_MAX_STREAM_DATA_BIDI_REMOTE;
transport_params.initial_max_stream_data_uni =
DEFAULT_MAX_STREAM_DATA_UNI;
transport_params.initial_max_streams_bidi =
DEFAULT_MAX_STREAMS_BIDI;
transport_params.initial_max_streams_uni =
DEFAULT_MAX_STREAMS_UNI;
transport_params.initial_max_data = DEFAULT_MAX_DATA;
transport_params.max_idle_timeout = DEFAULT_MAX_IDLE_TIMEOUT;
transport_params.max_udp_payload_size =
NGTCP2_DEFAULT_MAX_UDP_PAYLOAD_SIZE;
transport_params.max_ack_delay =
NGTCP2_DEFAULT_MAX_ACK_DELAY;
transport_params.disable_active_migration = 0;
transport_params.preferred_address_present = 0;
transport_params.stateless_reset_token_present = 0;
cc_algo = NGTCP2_CC_ALGO_RENO;
}
// Sets the QuicSessionConfig using an AliasedBuffer for efficiency.
void QuicSessionConfig::Set(
QuicState* quic_state,
const sockaddr* preferred_addr) {
ResetToDefaults(quic_state);
SetConfig(quic_state, IDX_QUIC_SESSION_ACTIVE_CONNECTION_ID_LIMIT,
&transport_params.active_connection_id_limit);
SetConfig(quic_state, IDX_QUIC_SESSION_MAX_STREAM_DATA_BIDI_LOCAL,
&transport_params.initial_max_stream_data_bidi_local);
SetConfig(quic_state, IDX_QUIC_SESSION_MAX_STREAM_DATA_BIDI_REMOTE,
&transport_params.initial_max_stream_data_bidi_remote);
SetConfig(quic_state, IDX_QUIC_SESSION_MAX_STREAM_DATA_UNI,
&transport_params.initial_max_stream_data_uni);
SetConfig(quic_state, IDX_QUIC_SESSION_MAX_DATA,
&transport_params.initial_max_data);
SetConfig(quic_state, IDX_QUIC_SESSION_MAX_STREAMS_BIDI,
&transport_params.initial_max_streams_bidi);
SetConfig(quic_state, IDX_QUIC_SESSION_MAX_STREAMS_UNI,
&transport_params.initial_max_streams_uni);
SetConfig(quic_state, IDX_QUIC_SESSION_MAX_IDLE_TIMEOUT,
&transport_params.max_idle_timeout);
SetConfig(quic_state, IDX_QUIC_SESSION_MAX_UDP_PAYLOAD_SIZE,
&transport_params.max_udp_payload_size);
SetConfig(quic_state, IDX_QUIC_SESSION_MAX_ACK_DELAY,
&transport_params.max_ack_delay);
SetConfig(quic_state,
IDX_QUIC_SESSION_CC_ALGO,
reinterpret_cast<uint64_t *>(&cc_algo));
transport_params.max_idle_timeout =
transport_params.max_idle_timeout * 1000000000;
// TODO(@jasnell): QUIC allows both IPv4 and IPv6 addresses to be
// specified. Here we're specifying one or the other. Need to
// determine if that's what we want or should we support both.
if (preferred_addr != nullptr) {
transport_params.preferred_address_present = 1;
switch (preferred_addr->sa_family) {
case AF_INET: {
CopyPreferredAddress(
transport_params.preferred_address.ipv4_addr,
sizeof(transport_params.preferred_address.ipv4_addr),
&transport_params.preferred_address.ipv4_port,
preferred_addr);
break;
}
case AF_INET6: {
CopyPreferredAddress(
transport_params.preferred_address.ipv6_addr,
sizeof(transport_params.preferred_address.ipv6_addr),
&transport_params.preferred_address.ipv6_port,
preferred_addr);
break;
}
default:
UNREACHABLE();
}
}
}
void QuicSessionListener::OnKeylog(const char* line, size_t len) {
if (previous_listener_ != nullptr)
previous_listener_->OnKeylog(line, len);
}
void QuicSessionListener::OnClientHello(
const char* alpn,
const char* server_name) {
if (previous_listener_ != nullptr)
previous_listener_->OnClientHello(alpn, server_name);
}
QuicSessionListener::~QuicSessionListener() {
if (session_)
session_->RemoveListener(this);
}
void QuicSessionListener::OnCert(const char* server_name) {
if (previous_listener_ != nullptr)
previous_listener_->OnCert(server_name);
}
void QuicSessionListener::OnOCSP(Local<Value> ocsp) {
if (previous_listener_ != nullptr)
previous_listener_->OnOCSP(ocsp);
}
void QuicSessionListener::OnStreamHeaders(
int64_t stream_id,
int kind,
const std::vector<std::unique_ptr<QuicHeader>>& headers,
int64_t push_id) {
if (previous_listener_ != nullptr)
previous_listener_->OnStreamHeaders(stream_id, kind, headers, push_id);
}
void QuicSessionListener::OnStreamClose(
int64_t stream_id,
uint64_t app_error_code) {
if (previous_listener_ != nullptr)
previous_listener_->OnStreamClose(stream_id, app_error_code);
}
void QuicSessionListener::OnStreamReset(
int64_t stream_id,
uint64_t app_error_code) {
if (previous_listener_ != nullptr)
previous_listener_->OnStreamReset(stream_id, app_error_code);
}
void QuicSessionListener::OnSessionClose(QuicError error, int flags) {
if (previous_listener_ != nullptr)
previous_listener_->OnSessionClose(error, flags);
}
void QuicSessionListener::OnStreamReady(BaseObjectPtr<QuicStream> stream) {
if (previous_listener_ != nullptr)
previous_listener_->OnStreamReady(stream);
}
void QuicSessionListener::OnHandshakeCompleted() {
if (previous_listener_ != nullptr)
previous_listener_->OnHandshakeCompleted();
}
void QuicSessionListener::OnPathValidation(
ngtcp2_path_validation_result res,
const sockaddr* local,
const sockaddr* remote) {
if (previous_listener_ != nullptr)
previous_listener_->OnPathValidation(res, local, remote);
}
void QuicSessionListener::OnSessionTicket(int size, SSL_SESSION* session) {
if (previous_listener_ != nullptr) {
previous_listener_->OnSessionTicket(size, session);
}
}
void QuicSessionListener::OnStreamBlocked(int64_t stream_id) {
if (previous_listener_ != nullptr) {
previous_listener_->OnStreamBlocked(stream_id);
}
}
void QuicSessionListener::OnUsePreferredAddress(
int family,
const PreferredAddress& preferred_address) {
if (previous_listener_ != nullptr)
previous_listener_->OnUsePreferredAddress(family, preferred_address);
}
void QuicSessionListener::OnVersionNegotiation(
uint32_t supported_version,
const uint32_t* versions,
size_t vcnt) {
if (previous_listener_ != nullptr)
previous_listener_->OnVersionNegotiation(supported_version, versions, vcnt);
}
void QuicSessionListener::OnQLog(QLogStream* qlog_stream) {
if (previous_listener_ != nullptr)
previous_listener_->OnQLog(qlog_stream);
}
void JSQuicSessionListener::OnKeylog(const char* line, size_t len) {
Environment* env = session()->env();
HandleScope handle_scope(env->isolate());
Context::Scope context_scope(env->context());
Local<Value> line_bf = Buffer::Copy(env, line, 1 + len).ToLocalChecked();
char* data = Buffer::Data(line_bf);
data[len] = '\n';
// Grab a shared pointer to this to prevent the QuicSession
// from being freed while the MakeCallback is running.
BaseObjectPtr<QuicSession> ptr(session());
session()->MakeCallback(env->quic_on_session_keylog_function(), 1, &line_bf);
}
void JSQuicSessionListener::OnStreamBlocked(int64_t stream_id) {
Environment* env = session()->env();
HandleScope handle_scope(env->isolate());
Context::Scope context_scope(env->context());
BaseObjectPtr<QuicStream> stream = session()->FindStream(stream_id);
stream->MakeCallback(env->quic_on_stream_blocked_function(), 0, nullptr);
}
void JSQuicSessionListener::OnClientHello(
const char* alpn,
const char* server_name) {
Environment* env = session()->env();
HandleScope scope(env->isolate());
Context::Scope context_scope(env->context());
Local<Value> argv[] = {
Undefined(env->isolate()),
Undefined(env->isolate()),
session()->crypto_context()->hello_ciphers().ToLocalChecked()
};
if (alpn != nullptr) {
argv[0] = String::NewFromUtf8(
env->isolate(),
alpn,
v8::NewStringType::kNormal).ToLocalChecked();
}
if (server_name != nullptr) {
argv[1] = String::NewFromUtf8(
env->isolate(),
server_name,
v8::NewStringType::kNormal).ToLocalChecked();
}
// Grab a shared pointer to this to prevent the QuicSession
// from being freed while the MakeCallback is running.
BaseObjectPtr<QuicSession> ptr(session());
session()->MakeCallback(
env->quic_on_session_client_hello_function(),
arraysize(argv), argv);
}
void JSQuicSessionListener::OnCert(const char* server_name) {
Environment* env = session()->env();
HandleScope handle_scope(env->isolate());
Context::Scope context_scope(env->context());
Local<Value> servername = Undefined(env->isolate());
if (server_name != nullptr) {
servername = OneByteString(
env->isolate(),
server_name,
strlen(server_name));
}
// Grab a shared pointer to this to prevent the QuicSession
// from being freed while the MakeCallback is running.
BaseObjectPtr<QuicSession> ptr(session());
session()->MakeCallback(env->quic_on_session_cert_function(), 1, &servername);
}
void JSQuicSessionListener::OnStreamHeaders(
int64_t stream_id,
int kind,
const std::vector<std::unique_ptr<QuicHeader>>& headers,
int64_t push_id) {
Environment* env = session()->env();
HandleScope scope(env->isolate());
Context::Scope context_scope(env->context());
MaybeStackBuffer<Local<Value>, 16> head(headers.size());
size_t n = 0;
for (const auto& header : headers) {
// name and value should never be empty here, and if
// they are, there's an actual bug so go ahead and crash
Local<Value> pair[] = {
header->GetName(session()->application()).ToLocalChecked(),
header->GetValue(session()->application()).ToLocalChecked()
};
head[n++] = Array::New(env->isolate(), pair, arraysize(pair));
}
Local<Value> argv[] = {
Number::New(env->isolate(), static_cast<double>(stream_id)),
Array::New(env->isolate(), head.out(), n),
Integer::New(env->isolate(), kind),
Undefined(env->isolate())
};
if (kind == QUICSTREAM_HEADERS_KIND_PUSH)
argv[3] = Number::New(env->isolate(), static_cast<double>(push_id));
BaseObjectPtr<QuicSession> ptr(session());
session()->MakeCallback(
env->quic_on_stream_headers_function(),
arraysize(argv), argv);
}
void JSQuicSessionListener::OnOCSP(Local<Value> ocsp) {
Environment* env = session()->env();
HandleScope scope(env->isolate());
Context::Scope context_scope(env->context());
BaseObjectPtr<QuicSession> ptr(session());
session()->MakeCallback(env->quic_on_session_status_function(), 1, &ocsp);
}
void JSQuicSessionListener::OnStreamClose(
int64_t stream_id,
uint64_t app_error_code) {
Environment* env = session()->env();
HandleScope scope(env->isolate());
Context::Scope context_scope(env->context());
Local<Value> argv[] = {
Number::New(env->isolate(), static_cast<double>(stream_id)),
Number::New(env->isolate(), static_cast<double>(app_error_code))
};
// Grab a shared pointer to this to prevent the QuicSession
// from being freed while the MakeCallback is running.
BaseObjectPtr<QuicSession> ptr(session());
session()->MakeCallback(
env->quic_on_stream_close_function(),
arraysize(argv),
argv);
}
void JSQuicSessionListener::OnStreamReset(
int64_t stream_id,
uint64_t app_error_code) {
Environment* env = session()->env();
HandleScope scope(env->isolate());
Context::Scope context_scope(env->context());
Local<Value> argv[] = {
Number::New(env->isolate(), static_cast<double>(stream_id)),
Number::New(env->isolate(), static_cast<double>(app_error_code))
};
// Grab a shared pointer to this to prevent the QuicSession
// from being freed while the MakeCallback is running.
BaseObjectPtr<QuicSession> ptr(session());
session()->MakeCallback(
env->quic_on_stream_reset_function(),
arraysize(argv),
argv);
}
void JSQuicSessionListener::OnSessionClose(QuicError error, int flags) {
Environment* env = session()->env();
HandleScope scope(env->isolate());
Context::Scope context_scope(env->context());
Local<Value> argv[] = {
Number::New(env->isolate(), static_cast<double>(error.code)),
Integer::New(env->isolate(), error.family),
flags & SESSION_CLOSE_FLAG_SILENT
? v8::True(env->isolate())
: v8::False(env->isolate()),
flags & SESSION_CLOSE_FLAG_STATELESS_RESET
? v8::True(env->isolate())
: v8::False(env->isolate())
};
// Grab a shared pointer to this to prevent the QuicSession
// from being freed while the MakeCallback is running.
BaseObjectPtr<QuicSession> ptr(session());
session()->MakeCallback(
env->quic_on_session_close_function(),
arraysize(argv), argv);
}
void JSQuicSessionListener::OnStreamReady(BaseObjectPtr<QuicStream> stream) {
Environment* env = session()->env();
HandleScope scope(env->isolate());
Context::Scope context_scope(env->context());
Local<Value> argv[] = {
stream->object(),
Number::New(env->isolate(), static_cast<double>(stream->id())),
Number::New(env->isolate(), static_cast<double>(stream->push_id()))
};
// Grab a shared pointer to this to prevent the QuicSession
// from being freed while the MakeCallback is running.
BaseObjectPtr<QuicSession> ptr(session());
session()->MakeCallback(
env->quic_on_stream_ready_function(),
arraysize(argv), argv);
}
void JSQuicSessionListener::OnHandshakeCompleted() {
Environment* env = session()->env();
HandleScope scope(env->isolate());
Context::Scope context_scope(env->context());
QuicCryptoContext* ctx = session()->crypto_context();
Local<Value> servername = Undefined(env->isolate());
const char* hostname = ctx->servername();
if (hostname != nullptr) {
servername =
String::NewFromUtf8(
env->isolate(),
hostname,
v8::NewStringType::kNormal).ToLocalChecked();
}
int err = ctx->VerifyPeerIdentity(
hostname != nullptr ?
hostname :
session()->hostname().c_str());
Local<Value> argv[] = {
servername,
GetALPNProtocol(*session()),
ctx->cipher_name().ToLocalChecked(),
ctx->cipher_version().ToLocalChecked(),
Integer::New(env->isolate(), session()->max_pktlen_),
crypto::GetValidationErrorReason(env, err).ToLocalChecked(),
crypto::GetValidationErrorCode(env, err).ToLocalChecked(),
session()->crypto_context()->early_data() ?
v8::True(env->isolate()) :
v8::False(env->isolate())
};
// Grab a shared pointer to this to prevent the QuicSession
// from being freed while the MakeCallback is running.
BaseObjectPtr<QuicSession> ptr(session());
session()->MakeCallback(
env->quic_on_session_handshake_function(),
arraysize(argv),
argv);
}
void JSQuicSessionListener::OnPathValidation(
ngtcp2_path_validation_result res,
const sockaddr* local,
const sockaddr* remote) {
// This is a fairly expensive operation because both the local and
// remote addresses have to converted into JavaScript objects. We
// only do this if a pathValidation handler is registered.
Environment* env = session()->env();
HandleScope scope(env->isolate());
Local<Context> context = env->context();
Context::Scope context_scope(context);
Local<Value> argv[] = {
Integer::New(env->isolate(), res),
AddressToJS(env, local),
AddressToJS(env, remote)
};
// Grab a shared pointer to this to prevent the QuicSession
// from being freed while the MakeCallback is running.
BaseObjectPtr<QuicSession> ptr(session());
session()->MakeCallback(
env->quic_on_session_path_validation_function(),
arraysize(argv),
argv);
}
void JSQuicSessionListener::OnSessionTicket(int size, SSL_SESSION* sess) {
Environment* env = session()->env();
HandleScope scope(env->isolate());
Context::Scope context_scope(env->context());
Local<Value> argv[] = {
v8::Undefined(env->isolate()),
v8::Undefined(env->isolate())
};
if (size > 0) {
AllocatedBuffer session_ticket =
AllocatedBuffer::AllocateManaged(env, size);
unsigned char* session_data =
reinterpret_cast<unsigned char*>(session_ticket.data());
memset(session_data, 0, size);
if (i2d_SSL_SESSION(sess, &session_data) > 0)
argv[0] = session_ticket.ToBuffer().ToLocalChecked();
}
if (session()->is_transport_params_set()) {
argv[1] = Buffer::Copy(
env,
reinterpret_cast<const char*>(&session()->transport_params_),
sizeof(session()->transport_params_)).ToLocalChecked();
}
// Grab a shared pointer to this to prevent the QuicSession
// from being freed while the MakeCallback is running.
BaseObjectPtr<QuicSession> ptr(session());
session()->MakeCallback(
env->quic_on_session_ticket_function(),
arraysize(argv), argv);
}
void JSQuicSessionListener::OnUsePreferredAddress(
int family,
const PreferredAddress& preferred_address) {
Environment* env = session()->env();
HandleScope scope(env->isolate());
Local<Context> context = env->context();
Context::Scope context_scope(context);
std::string hostname = family == AF_INET ?
preferred_address.ipv4_address():
preferred_address.ipv6_address();
uint16_t port =
family == AF_INET ?
preferred_address.ipv4_port() :
preferred_address.ipv6_port();
Local<Value> argv[] = {
OneByteString(env->isolate(), hostname.c_str()),
Integer::NewFromUnsigned(env->isolate(), port),
Integer::New(env->isolate(), family)
};
BaseObjectPtr<QuicSession> ptr(session());
session()->MakeCallback(
env->quic_on_session_use_preferred_address_function(),
arraysize(argv), argv);
}
void JSQuicSessionListener::OnVersionNegotiation(
uint32_t supported_version,
const uint32_t* vers,
size_t vcnt) {
Environment* env = session()->env();
HandleScope scope(env->isolate());
Local<Context> context = env->context();
Context::Scope context_scope(context);
MaybeStackBuffer<Local<Value>, 4> versions(vcnt);
for (size_t n = 0; n < vcnt; n++)
versions[n] = Integer::New(env->isolate(), vers[n]);
// Currently, we only support one version of QUIC but in
// the future that may change. The callback below passes
// an array back to the JavaScript side to future-proof.
Local<Value> supported =
Integer::New(env->isolate(), supported_version);
Local<Value> argv[] = {
Integer::New(env->isolate(), NGTCP2_PROTO_VER),
Array::New(env->isolate(), versions.out(), vcnt),
Array::New(env->isolate(), &supported, 1)
};
// Grab a shared pointer to this to prevent the QuicSession
// from being freed while the MakeCallback is running.
BaseObjectPtr<QuicSession> ptr(session());
session()->MakeCallback(
env->quic_on_session_version_negotiation_function(),
arraysize(argv), argv);
}
void JSQuicSessionListener::OnQLog(QLogStream* qlog_stream) {
CHECK_NOT_NULL(qlog_stream);
Environment* env = session()->env();
HandleScope handle_scope(env->isolate());
Context::Scope context_scope(env->context());
Local<Value> obj = qlog_stream->object();
session()->MakeCallback(env->quic_on_session_qlog_function(), 1, &obj);
}
// Generates a new random connection ID.
void QuicSession::RandomConnectionIDStrategy(
QuicSession* session,
ngtcp2_cid* cid,
size_t cidlen) {
// CID min and max length is determined by the QUIC specification.
CHECK_LE(cidlen, NGTCP2_MAX_CIDLEN);
CHECK_GE(cidlen, NGTCP2_MIN_CIDLEN);
cid->datalen = cidlen;
// cidlen shouldn't ever be zero here but just in case that
// behavior changes in ngtcp2 in the future...
if (LIKELY(cidlen > 0))
EntropySource(cid->data, cidlen);
}
// Check required capabilities were not excluded from the OpenSSL build:
// - OPENSSL_NO_SSL_TRACE excludes SSL_trace()
// - OPENSSL_NO_STDIO excludes BIO_new_fp()
// HAVE_SSL_TRACE is available on the internal tcp_wrap binding for the tests.
#if defined(OPENSSL_NO_SSL_TRACE) || defined(OPENSSL_NO_STDIO)
# define HAVE_SSL_TRACE 0
#else
# define HAVE_SSL_TRACE 1
#endif
QuicCryptoContext::~QuicCryptoContext() {
// Free any remaining crypto handshake data (if any)
Cancel();
}
void QuicCryptoContext::MemoryInfo(MemoryTracker* tracker) const {
tracker->TrackField("initial_crypto", handshake_[0]);
tracker->TrackField("handshake_crypto", handshake_[1]);
tracker->TrackField("app_crypto", handshake_[2]);
tracker->TrackField("ocsp_response", ocsp_response_);
}
bool QuicCryptoContext::SetSecrets(
ngtcp2_crypto_level level,
const uint8_t* rx_secret,
const uint8_t* tx_secret,
size_t secretlen) {
static constexpr int kCryptoKeylen = 64;
static constexpr int kCryptoIvlen = 64;
static constexpr char kQuicClientEarlyTrafficSecret[] =
"QUIC_CLIENT_EARLY_TRAFFIC_SECRET";
static constexpr char kQuicClientHandshakeTrafficSecret[] =
"QUIC_CLIENT_HANDSHAKE_TRAFFIC_SECRET";
static constexpr char kQuicClientTrafficSecret0[] =
"QUIC_CLIENT_TRAFFIC_SECRET_0";
static constexpr char kQuicServerHandshakeTrafficSecret[] =
"QUIC_SERVER_HANDSHAKE_TRAFFIC_SECRET";
static constexpr char kQuicServerTrafficSecret[] =
"QUIC_SERVER_TRAFFIC_SECRET_0";
uint8_t rx_key[kCryptoKeylen];
uint8_t rx_hp[kCryptoKeylen];
uint8_t tx_key[kCryptoKeylen];
uint8_t tx_hp[kCryptoKeylen];
uint8_t rx_iv[kCryptoIvlen];
uint8_t tx_iv[kCryptoIvlen];
if (NGTCP2_ERR(ngtcp2_crypto_derive_and_install_rx_key(
session()->connection(),
rx_key,
rx_iv,
rx_hp,
level,
rx_secret,
secretlen))) {
return false;
}
if (NGTCP2_ERR(ngtcp2_crypto_derive_and_install_tx_key(
session()->connection(),
tx_key,
tx_iv,
tx_hp,
level,
tx_secret,
secretlen))) {
return false;
}
switch (level) {
case NGTCP2_CRYPTO_LEVEL_EARLY:
crypto::LogSecret(
ssl_,
kQuicClientEarlyTrafficSecret,
rx_secret,
secretlen);
break;
case NGTCP2_CRYPTO_LEVEL_HANDSHAKE:
crypto::LogSecret(
ssl_,
kQuicClientHandshakeTrafficSecret,
rx_secret,
secretlen);
crypto::LogSecret(
ssl_,
kQuicServerHandshakeTrafficSecret,
tx_secret,
secretlen);
break;
case NGTCP2_CRYPTO_LEVEL_APP:
crypto::LogSecret(
ssl_,
kQuicClientTrafficSecret0,
rx_secret,
secretlen);
crypto::LogSecret(
ssl_,
kQuicServerTrafficSecret,
tx_secret,
secretlen);
break;
default:
UNREACHABLE();
}
return true;
}
void QuicCryptoContext::AcknowledgeCryptoData(
ngtcp2_crypto_level level,
uint64_t datalen) {
// It is possible for the QuicSession to have been destroyed but not yet
// deconstructed. In such cases, we want to ignore the callback as there
// is nothing to do but wait for further cleanup to happen.
if (UNLIKELY(session_->is_destroyed()))
return;
Debug(session(),
"Acknowledging %" PRIu64 " crypto bytes for %s level",
datalen,
crypto_level_name(level));
// Consumes (frees) the given number of bytes in the handshake buffer.
handshake_[level].Consume(static_cast<size_t>(datalen));
// Update the statistics for the handshake, allowing us to track
// how long the handshake is taking to be acknowledged. A malicious
// peer could potentially force the QuicSession to hold on to
// crypto data for a long time by not sending an acknowledgement.
// The histogram will allow us to track the time periods between
// acknowlegements.
session()->RecordAck(&QuicSessionStats::handshake_acked_at);
}
void QuicCryptoContext::EnableTrace() {
#if HAVE_SSL_TRACE
if (!bio_trace_) {
bio_trace_.reset(BIO_new_fp(stderr, BIO_NOCLOSE | BIO_FP_TEXT));
SSL_set_msg_callback(
ssl_.get(),
[](int write_p,
int version,
int content_type,
const void* buf,
size_t len,
SSL* ssl,
void* arg) -> void {
crypto::MarkPopErrorOnReturn mark_pop_error_on_return;
SSL_trace(write_p, version, content_type, buf, len, ssl, arg);
});
SSL_set_msg_callback_arg(ssl_.get(), bio_trace_.get());
}
#endif
}
// If a 'clientHello' event listener is registered on the JavaScript
// QuicServerSession object, the STATE_CLIENT_HELLO_ENABLED state
// will be set and the OnClientHello will cause the 'clientHello'
// event to be emitted.
//
// The 'clientHello' callback will be given it's own callback function
// that must be called when the client has completed handling the event.
// The handshake will not continue until it is called.
//
// The intent here is to allow user code the ability to modify or
// replace the SecurityContext based on the server name, ALPN, or
// other handshake characteristics.
//
// The user can also set a 'cert' event handler that will be called
// when the peer certificate is received, allowing additional tweaks
// and verifications to be performed.
int QuicCryptoContext::OnClientHello() {
if (LIKELY(session_->state_->client_hello_enabled == 0))
return 0;
TLSCallbackScope callback_scope(this);
if (is_in_client_hello())
return -1;
set_in_client_hello();
QuicCryptoContext* ctx = session_->crypto_context();
session_->listener()->OnClientHello(
ctx->hello_alpn(),
ctx->hello_servername());
// Returning -1 here will keep the TLS handshake paused until the
// client hello callback is invoked. Returning 0 means that the
// handshake is ready to proceed. When the OnClientHello callback
// is called above, it may be resolved synchronously or asynchronously.
// In case it is resolved synchronously, we need the check below.
return is_in_client_hello() ? -1 : 0;
}
// The OnCert callback provides an opportunity to prompt the server to
// perform on OCSP request on behalf of the client (when the client
// requests it). If there is a listener for the 'OCSPRequest' event
// on the JavaScript side, the IDX_QUIC_SESSION_STATE_CERT_ENABLED
// session state slot will equal 1, which will cause the callback to
// be invoked. The callback will be given a reference to a JavaScript
// function that must be called in order for the TLS handshake to
// continue.
int QuicCryptoContext::OnOCSP() {
if (LIKELY(session_->state_->cert_enabled == 0)) {
Debug(session(), "No OCSPRequest handler registered");
return 1;
}
Debug(session(), "Client is requesting an OCSP Response");
TLSCallbackScope callback_scope(this);
// As in node_crypto.cc, this is not an error, but does suspend the
// handshake to continue when OnOCSP is complete.
if (is_in_ocsp_request())
return -1;
set_in_ocsp_request();
session_->listener()->OnCert(session_->crypto_context()->servername());
// Returning -1 here means that we are still waiting for the OCSP
// request to be completed. When the OnCert handler is invoked
// above, it can be resolve synchronously or asynchonously. If
// resolved synchronously, we need the check below.
return is_in_ocsp_request() ? -1 : 1;
}
// The OnCertDone function is called by the QuicSessionOnCertDone
// function when usercode is done handling the OCSPRequest event.
void QuicCryptoContext::OnOCSPDone(
BaseObjectPtr<SecureContext> context,
Local<Value> ocsp_response) {
Debug(session(),
"OCSPRequest completed. Context Provided? %s, OCSP Provided? %s",
context ? "Yes" : "No",
ocsp_response->IsArrayBufferView() ? "Yes" : "No");
// Continue the TLS handshake when this function exits
// otherwise it will stall and fail.
TLSHandshakeScope handshake_scope(
this,
[&]() { set_in_ocsp_request(false); });
// Disable the callback at this point so we don't loop continuously
session_->state_->cert_enabled = 0;
if (context) {
int err = crypto::UseSNIContext(ssl_, context);
if (!err) {
unsigned long err = ERR_get_error(); // NOLINT(runtime/int)
return !err ?
THROW_ERR_QUIC_FAILURE_SETTING_SNI_CONTEXT(session_->env()) :
crypto::ThrowCryptoError(session_->env(), err);
}
}
if (ocsp_response->IsArrayBufferView()) {
ocsp_response_.Reset(
session_->env()->isolate(),
ocsp_response.As<ArrayBufferView>());
}
}
// At this point in time, the TLS handshake secrets have been