-
Notifications
You must be signed in to change notification settings - Fork 156
/
ClientProtocol.cpp
2571 lines (2254 loc) · 87.2 KB
/
ClientProtocol.cpp
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 (c) 2018-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <fizz/client/ClientProtocol.h>
#include <fizz/client/FizzClientContext.h>
#include <fizz/client/PskCache.h>
#include <fizz/client/State.h>
#include <fizz/crypto/Utils.h>
#include <fizz/crypto/hpke/Utils.h>
#include <fizz/protocol/CertificateVerifier.h>
#include <fizz/protocol/Protocol.h>
#include <fizz/protocol/StateMachine.h>
#include <fizz/protocol/ech/Encryption.h>
#include <fizz/record/Extensions.h>
using folly::Optional;
using namespace fizz::client;
using namespace fizz::client::detail;
namespace fizz {
namespace sm {
FIZZ_DECLARE_EVENT_HANDLER(
ClientTypes,
StateEnum::Uninitialized,
Event::Connect,
StateEnum::ExpectingServerHello);
FIZZ_DECLARE_EVENT_HANDLER(
ClientTypes,
StateEnum::ExpectingServerHello,
Event::HelloRetryRequest,
StateEnum::ExpectingServerHello);
FIZZ_DECLARE_EVENT_HANDLER(
ClientTypes,
StateEnum::ExpectingServerHello,
Event::ServerHello,
StateEnum::ExpectingEncryptedExtensions);
FIZZ_DECLARE_EVENT_HANDLER(
ClientTypes,
StateEnum::ExpectingServerHello,
Event::EarlyAppWrite,
StateEnum::Error);
FIZZ_DECLARE_EVENT_HANDLER(
ClientTypes,
StateEnum::ExpectingEncryptedExtensions,
Event::EncryptedExtensions,
StateEnum::ExpectingCertificate,
StateEnum::ExpectingFinished);
FIZZ_DECLARE_EVENT_HANDLER(
ClientTypes,
StateEnum::ExpectingEncryptedExtensions,
Event::EarlyAppWrite,
StateEnum::Error);
FIZZ_DECLARE_EVENT_HANDLER(
ClientTypes,
StateEnum::ExpectingCertificate,
Event::CertificateRequest,
StateEnum::ExpectingCertificate);
FIZZ_DECLARE_EVENT_HANDLER(
ClientTypes,
StateEnum::ExpectingCertificate,
Event::Certificate,
StateEnum::ExpectingCertificateVerify);
FIZZ_DECLARE_EVENT_HANDLER(
ClientTypes,
StateEnum::ExpectingCertificate,
Event::CompressedCertificate,
StateEnum::ExpectingCertificateVerify);
FIZZ_DECLARE_EVENT_HANDLER(
ClientTypes,
StateEnum::ExpectingCertificate,
Event::EarlyAppWrite,
StateEnum::Error);
FIZZ_DECLARE_EVENT_HANDLER(
ClientTypes,
StateEnum::ExpectingCertificateVerify,
Event::CertificateVerify,
StateEnum::ExpectingFinished);
FIZZ_DECLARE_EVENT_HANDLER(
ClientTypes,
StateEnum::ExpectingCertificateVerify,
Event::EarlyAppWrite,
StateEnum::Error);
FIZZ_DECLARE_EVENT_HANDLER(
ClientTypes,
StateEnum::ExpectingFinished,
Event::Finished,
StateEnum::Established);
FIZZ_DECLARE_EVENT_HANDLER(
ClientTypes,
StateEnum::ExpectingFinished,
Event::EarlyAppWrite,
StateEnum::Error);
FIZZ_DECLARE_EVENT_HANDLER(
ClientTypes,
StateEnum::Established,
Event::EarlyAppWrite,
StateEnum::Error);
FIZZ_DECLARE_EVENT_HANDLER(
ClientTypes,
StateEnum::Established,
Event::NewSessionTicket,
StateEnum::Error);
FIZZ_DECLARE_EVENT_HANDLER(
ClientTypes,
StateEnum::Established,
Event::AppData,
StateEnum::Error);
FIZZ_DECLARE_EVENT_HANDLER(
ClientTypes,
StateEnum::Established,
Event::AppWrite,
StateEnum::Error);
FIZZ_DECLARE_EVENT_HANDLER(
ClientTypes,
StateEnum::Established,
Event::KeyUpdateInitiation,
StateEnum::Error);
FIZZ_DECLARE_EVENT_HANDLER(
ClientTypes,
StateEnum::Established,
Event::KeyUpdate,
StateEnum::Error);
FIZZ_DECLARE_EVENT_HANDLER(
ClientTypes,
StateEnum::Established,
Event::CloseNotify,
StateEnum::Closed);
FIZZ_DECLARE_EVENT_HANDLER(
ClientTypes,
StateEnum::ExpectingCloseNotify,
Event::CloseNotify,
StateEnum::Closed);
} // namespace sm
namespace client {
Actions ClientStateMachine::processConnect(
const State& state,
std::shared_ptr<const FizzClientContext> context,
std::shared_ptr<const CertificateVerifier> verifier,
Optional<std::string> sni,
Optional<CachedPsk> cachedPsk,
const std::shared_ptr<ClientExtensions>& extensions,
Optional<std::vector<ech::ECHConfig>> echConfigs) {
Connect connect;
connect.context = std::move(context);
connect.sni = std::move(sni);
connect.verifier = std::move(verifier);
connect.extensions = extensions;
connect.cachedPsk = std::move(cachedPsk);
connect.echConfigs = std::move(echConfigs);
return detail::processEvent(state, std::move(connect));
}
Actions ClientStateMachine::processSocketData(
const State& state,
folly::IOBufQueue& buf,
Aead::AeadOptions options) {
try {
if (!state.readRecordLayer()) {
return detail::handleError(
state,
ReportError("attempting to process data without record layer"),
folly::none);
}
auto param = state.readRecordLayer()->readEvent(buf, std::move(options));
if (!param.has_value()) {
return actions(WaitForData{param.sizeHint});
}
return detail::processEvent(state, std::move(*param));
} catch (const FizzException& e) {
return detail::handleError(
state,
ReportError(folly::exception_wrapper(std::current_exception())),
e.getAlert());
} catch (...) {
return detail::handleError(
state,
ReportError(folly::make_exception_wrapper<FizzException>(
folly::to<std::string>(
"error decoding record in state ",
toString(state.state()),
": ",
folly::exceptionStr(std::current_exception())),
AlertDescription::decode_error)),
AlertDescription::decode_error);
}
}
Actions ClientStateMachine::processWriteNewSessionTicket(
const State& state,
WriteNewSessionTicket write) {
return detail::processEvent(state, std::move(write));
}
Actions ClientStateMachine::processAppWrite(
const State& state,
AppWrite write) {
return detail::processEvent(state, std::move(write));
}
Actions ClientStateMachine::processEarlyAppWrite(
const State& state,
EarlyAppWrite write) {
return detail::processEvent(state, std::move(write));
}
Actions ClientStateMachine::processAppClose(const State& state) {
return detail::handleAppClose(state);
}
Actions ClientStateMachine::processAppCloseImmediate(const State& state) {
return detail::handleAppCloseImmediate(state);
}
Actions ClientStateMachine::processKeyUpdateInitiation(
const State& state,
KeyUpdateInitiation keyUpdateInitiation) {
return detail::processEvent(state, std::move(keyUpdateInitiation));
}
namespace detail {
Actions processEvent(const State& state, Param param) {
auto event = EventVisitor()(param);
try {
return sm::StateMachine<ClientTypes>::getHandler(state.state(), event)(
state, std::move(param));
} catch (const FizzException& e) {
return detail::handleError(
state,
ReportError(folly::exception_wrapper(std::current_exception())),
e.getAlert());
} catch (...) {
return detail::handleError(
state,
ReportError(folly::exception_wrapper(std::current_exception())),
AlertDescription::unexpected_message);
}
}
Actions handleError(
const State& state,
ReportError error,
Optional<AlertDescription> alertDesc) {
if (state.state() == StateEnum::Error) {
return actions(std::move(error));
}
MutateState transition([](State& newState) {
newState.state() = StateEnum::Error;
newState.writeRecordLayer() = nullptr;
newState.readRecordLayer() = nullptr;
});
if (alertDesc && state.writeRecordLayer()) {
Alert alert(*alertDesc);
WriteToSocket write;
write.contents.emplace_back(
state.writeRecordLayer()->writeAlert(std::move(alert)));
return actions(std::move(transition), std::move(write), std::move(error));
} else {
return actions(std::move(transition), std::move(error));
}
}
Actions handleAppCloseImmediate(const State& state) {
MutateState transition([](State& newState) {
newState.state() = StateEnum::Closed;
newState.writeRecordLayer() = nullptr;
newState.readRecordLayer() = nullptr;
});
if (state.writeRecordLayer()) {
Alert alert(AlertDescription::close_notify);
WriteToSocket write;
write.contents.emplace_back(
state.writeRecordLayer()->writeAlert(std::move(alert)));
return actions(std::move(transition), std::move(write));
} else {
return actions(std::move(transition));
}
}
Actions handleAppClose(const State& state) {
if (state.writeRecordLayer()) {
MutateState transition([](State& newState) {
newState.state() = StateEnum::ExpectingCloseNotify;
newState.writeRecordLayer() = nullptr;
});
Alert alert(AlertDescription::close_notify);
WriteToSocket write;
write.contents.emplace_back(
state.writeRecordLayer()->writeAlert(std::move(alert)));
return actions(std::move(transition), std::move(write));
} else {
MutateState transition([](State& newState) {
newState.state() = StateEnum::Closed;
newState.writeRecordLayer() = nullptr;
newState.readRecordLayer() = nullptr;
});
return actions(std::move(transition));
}
}
Actions handleInvalidEvent(const State& state, Event event, Param param) {
if (event == Event::Alert) {
auto& alert = *param.asAlert();
throw FizzException(
folly::to<std::string>(
"received alert: ",
toString(alert.description),
", in state ",
toString(state.state())),
folly::none);
} else {
throw FizzException(
folly::to<std::string>(
"invalid event: ",
toString(event),
", in state ",
toString(state.state())),
AlertDescription::unexpected_message);
}
}
} // namespace detail
} // namespace client
namespace sm {
static void ensureNoUnparsedHandshakeData(const State& state, Event event) {
if (state.readRecordLayer()->hasUnparsedHandshakeData()) {
throw FizzException(
folly::to<std::string>(
"unprocessed handshake data while handling event ",
toString(event),
" in state ",
toString(state.state())),
AlertDescription::unexpected_message);
}
}
static folly::Optional<CachedPsk> validatePsk(
const FizzClientContext& context,
folly::Optional<CachedPsk> psk) {
if (!psk) {
return folly::none;
}
if (std::find(
context.getSupportedVersions().begin(),
context.getSupportedVersions().end(),
psk->version) == context.getSupportedVersions().end()) {
VLOG(1) << "Ignoring cached psk with protocol version "
<< toString(psk->version);
return folly::none;
}
if (std::find(
context.getSupportedCiphers().begin(),
context.getSupportedCiphers().end(),
psk->cipher) == context.getSupportedCiphers().end()) {
VLOG(1) << "Ignoring cached psk with cipher " << toString(psk->cipher);
return folly::none;
}
// The below checks apply only to resumption tickets
if (psk->type == PskType::Resumption) {
auto now = context.getClock()->getCurrentTime();
if (now > psk->ticketExpirationTime) {
VLOG(1) << "Ignoring expired cached psk";
return folly::none;
}
if (now - psk->ticketHandshakeTime > context.getMaxPskHandshakeLife()) {
VLOG(1) << "Ignoring psk with stale handshake";
return folly::none;
}
if (psk->ticketHandshakeTime > now) {
VLOG(1) << "Ignoring psk from future";
return folly::none;
}
}
return psk;
}
static std::map<NamedGroup, std::unique_ptr<KeyExchange>> getKeyExchangers(
const Factory& factory,
const std::vector<NamedGroup>& groups) {
std::map<NamedGroup, std::unique_ptr<KeyExchange>> keyExchangers;
for (auto group : groups) {
auto kex = factory.makeKeyExchange(group, Factory::KeyExchangeMode::Client);
kex->generateKeyPair();
keyExchangers.emplace(group, std::move(kex));
}
return keyExchangers;
}
static ClientHello getClientHello(
const Factory& /*factory*/,
const Random& random,
const std::vector<CipherSuite>& supportedCiphers,
const std::vector<ProtocolVersion>& supportedVersions,
const std::vector<NamedGroup>& supportedGroups,
const std::map<NamedGroup, std::unique_ptr<KeyExchange>>& shares,
const std::vector<SignatureScheme>& supportedSigSchemes,
const std::vector<PskKeyExchangeMode>& supportedPskModes,
const folly::Optional<std::string>& hostname,
const std::vector<std::string>& supportedAlpns,
const std::vector<CertificateCompressionAlgorithm>& compressionAlgos,
const Optional<EarlyDataParams>& earlyDataParams,
const Buf& legacySessionId,
ClientExtensions* extensions,
Buf cookie = nullptr) {
ClientHello chlo;
chlo.legacy_version = ProtocolVersion::tls_1_2;
chlo.random = random;
chlo.legacy_session_id = legacySessionId->clone();
chlo.cipher_suites = supportedCiphers;
chlo.legacy_compression_methods.push_back(0x00);
SupportedVersions versions;
versions.versions = supportedVersions;
chlo.extensions.push_back(encodeExtension(std::move(versions)));
SupportedGroups groups;
groups.named_group_list = supportedGroups;
chlo.extensions.push_back(encodeExtension(std::move(groups)));
ClientKeyShare keyShare;
for (const auto& share : shares) {
KeyShareEntry entry;
entry.group = share.first;
entry.key_exchange = share.second->getKeyShare();
keyShare.client_shares.push_back(std::move(entry));
}
chlo.extensions.push_back(encodeExtension(std::move(keyShare)));
SignatureAlgorithms sigAlgs;
sigAlgs.supported_signature_algorithms = supportedSigSchemes;
chlo.extensions.push_back(encodeExtension(std::move(sigAlgs)));
if (hostname) {
auto hostnameBuf = folly::IOBuf::copyBuffer(*hostname);
auto sni = ServerNameList(ServerName(std::move(hostnameBuf)));
chlo.extensions.push_back(encodeExtension(sni));
}
if (!supportedAlpns.empty()) {
ProtocolNameList alpn;
for (const auto& protoName : supportedAlpns) {
ProtocolName proto;
proto.name = folly::IOBuf::copyBuffer(protoName);
alpn.protocol_name_list.push_back(std::move(proto));
}
chlo.extensions.push_back(encodeExtension(std::move(alpn)));
}
if (!supportedPskModes.empty()) {
PskKeyExchangeModes modes;
modes.modes = supportedPskModes;
chlo.extensions.push_back(encodeExtension(std::move(modes)));
}
if (earlyDataParams) {
chlo.extensions.push_back(encodeExtension(ClientEarlyData()));
}
if (cookie) {
Cookie monster;
monster.cookie = std::move(cookie);
chlo.extensions.push_back(encodeExtension(std::move(monster)));
}
if (!compressionAlgos.empty()) {
CertificateCompressionAlgorithms algos;
algos.algorithms = compressionAlgos;
chlo.extensions.push_back(encodeExtension(std::move(algos)));
}
if (extensions) {
auto additionalExtensions = extensions->getClientHelloExtensions();
for (auto& ext : additionalExtensions) {
chlo.extensions.push_back(std::move(ext));
}
}
return chlo;
}
static ClientPresharedKey getPskExtension(
const CachedPsk& psk,
const Clock& clock) {
ClientPresharedKey pskExt;
PskIdentity ident;
ident.psk_identity = folly::IOBuf::copyBuffer(psk.psk);
if (psk.type == PskType::Resumption) {
ident.obfuscated_ticket_age =
std::chrono::duration_cast<std::chrono::milliseconds>(
clock.getCurrentTime() - psk.ticketIssueTime)
.count();
ident.obfuscated_ticket_age += psk.ticketAgeAdd;
} else {
ident.obfuscated_ticket_age = 0;
}
pskExt.identities.push_back(std::move(ident));
PskBinder binder;
size_t binderSize = getHashSize(getHashFunction(psk.cipher));
binder.binder = folly::IOBuf::create(binderSize);
memset(binder.binder->writableData(), 0, binderSize);
binder.binder->append(binderSize);
pskExt.binders.push_back(std::move(binder));
return pskExt;
}
/**
* Returns the encoded client hello after updating the binder.
* Will derive the early secret on the key scheduler and create the binder
* using the passed in context.
*/
static Buf encodeAndAddBinders(
ClientHello& chlo,
const CachedPsk& psk,
KeyScheduler& scheduler,
HandshakeContext& handshakeContext,
const Clock& clock) {
scheduler.deriveEarlySecret(folly::range(psk.secret));
auto binderKey = scheduler.getSecret(
psk.type == PskType::External ? EarlySecrets::ExternalPskBinder
: EarlySecrets::ResumptionPskBinder,
handshakeContext.getBlankContext());
auto pskExt = getPskExtension(psk, clock);
chlo.extensions.push_back(encodeExtension(pskExt));
size_t binderLength = getBinderLength(chlo);
auto preEncoded = encodeHandshake(chlo);
// Add the ClientHello up to the binder list to the transcript.
{
folly::IOBufQueue chloQueue(folly::IOBufQueue::cacheChainLength());
chloQueue.append(std::move(preEncoded));
auto chloPrefix = chloQueue.split(chloQueue.chainLength() - binderLength);
handshakeContext.appendToTranscript(chloPrefix);
}
PskBinder binder;
binder.binder =
handshakeContext.getFinishedData(folly::range(binderKey.secret));
pskExt.binders.clear();
pskExt.binders.push_back(std::move(binder));
chlo.extensions.pop_back();
chlo.extensions.push_back(encodeExtension(std::move(pskExt)));
auto encoded = encodeHandshake(chlo);
// Add the binder list to the transcript.
folly::IOBufQueue chloQueue(folly::IOBufQueue::cacheChainLength());
chloQueue.append(encoded->clone());
chloQueue.split(chloQueue.chainLength() - binderLength);
handshakeContext.appendToTranscript(chloQueue.move());
return encoded;
}
static Optional<EarlyDataParams> getEarlyDataParams(
const FizzClientContext& context,
const Optional<CachedPsk>& psk) {
if (!context.getSendEarlyData()) {
return folly::none;
}
if (!psk || psk->maxEarlyDataSize == 0) {
return folly::none;
}
if (psk->alpn &&
std::find(
context.getSupportedAlpns().begin(),
context.getSupportedAlpns().end(),
*psk->alpn) == context.getSupportedAlpns().end()) {
return folly::none;
}
EarlyDataParams params;
params.version = psk->version;
params.cipher = psk->cipher;
params.serverCert = psk->serverCert;
params.clientCert = psk->clientCert;
params.alpn = psk->alpn;
return params;
}
static ech::SupportedECHConfig getSupportedECHConfig(
const std::vector<ech::ECHConfig>& echConfigs,
const std::vector<CipherSuite>& supportedCiphers,
const std::vector<NamedGroup>& supportedGroups) {
// Convert vectors to use HPKE types.
std::vector<hpke::KEMId> supportedKEMs(supportedGroups.size());
for (const auto& group : supportedGroups) {
supportedKEMs.push_back(hpke::getKEMId(group));
}
std::vector<hpke::AeadId> supportedAeads(supportedCiphers.size());
for (const auto& suite : supportedCiphers) {
supportedAeads.push_back(hpke::getAeadId(suite));
}
// Get a supported ECH config.
folly::Optional<ech::SupportedECHConfig> supportedConfig =
selectECHConfig(echConfigs, supportedKEMs, supportedAeads);
if (!supportedConfig.hasValue()) {
throw FizzException(
"ECH requested but we don't support any of the provided configs",
AlertDescription::internal_error);
}
return std::move(supportedConfig.value());
}
namespace {
struct ECHParams {
hpke::SetupResult setupResult;
ech::SupportedECHConfig supportedECHConfig;
Buf fakeSni;
};
} // namespace
static folly::Optional<ECHParams> setupECH(
const folly::Optional<std::vector<ech::ECHConfig>>& echConfigs,
const std::vector<CipherSuite>& supportedCiphers,
const std::vector<NamedGroup>& supportedGroups,
const Factory& factory) {
if (!echConfigs.has_value()) {
return folly::none;
}
auto supportedECHConfig = getSupportedECHConfig(
echConfigs.value(), supportedCiphers, supportedGroups);
auto configContent = supportedECHConfig.config.ech_config_content->clone();
folly::io::Cursor cursor(configContent.get());
auto echConfigContent = decode<ech::ECHConfigContentDraft>(cursor);
auto fakeSni = echConfigContent.public_name->clone();
auto kemId = echConfigContent.key_config.kem_id;
auto kex = factory.makeKeyExchange(
getKexGroup(kemId), Factory::KeyExchangeMode::Client);
auto setupResult =
constructHpkeSetupResult(std::move(kex), supportedECHConfig);
return ECHParams{
std::move(setupResult),
std::move(supportedECHConfig),
std::move(fakeSni)};
}
static void removeExtension(ClientHello& chlo, ExtensionType type) {
auto it = std::find_if(
chlo.extensions.begin(), chlo.extensions.end(), [type](auto& ext) {
return ext.extension_type == type;
});
if (it != chlo.extensions.end()) {
chlo.extensions.erase(it);
}
}
template <typename T>
static void replaceOrAddExtension(std::vector<Extension>& arr, T extension) {
auto it = std::find_if(
arr.begin(), arr.end(), [type = T::extension_type](auto& ext) {
return ext.extension_type == type;
});
if (it == arr.end()) {
// Just add it
arr.push_back(encodeExtension(std::move(extension)));
} else {
// Replace it.
*it = encodeExtension(std::move(extension));
}
}
static ClientHello constructEncryptedClientHello(
Event e,
ClientHello&& chlo,
const ech::SupportedECHConfig& supportedConfig,
hpke::SetupResult& hpkeSetup,
const Random& outerRandom,
Buf fakeSni,
const folly::Optional<ClientPresharedKey>& greasePsk) {
DCHECK(e == Event::ClientHello || e == Event::HelloRetryRequest);
// Outer chlo is missing the inner ECH. We also replace any PSK
// generated earlier with a GREASE one.
auto chloOuter = chlo.clone();
removeExtension(chloOuter, ExtensionType::encrypted_client_hello);
removeExtension(chloOuter, ExtensionType::pre_shared_key);
// ClientHello might have early data
if (e == Event::ClientHello) {
removeExtension(chloOuter, ExtensionType::early_data);
}
// Put in the fake SNI
replaceOrAddExtension(
chloOuter.extensions, ServerNameList(ServerName(std::move(fakeSni))));
// Substitute in outer random
chloOuter.random = outerRandom;
Extension encodedECHExtension;
// Create the encrypted client hello inner extension.
switch (supportedConfig.config.version) {
case (ech::ECHVersion::Draft15): {
ech::OuterECHClientHello clientECHExtension;
if (e == Event::ClientHello) {
clientECHExtension = encryptClientHello(
supportedConfig,
std::move(chlo),
chloOuter.clone(),
hpkeSetup,
greasePsk);
} else {
clientECHExtension = encryptClientHelloHRR(
supportedConfig,
std::move(chlo),
chloOuter.clone(),
hpkeSetup,
greasePsk);
}
chloOuter.extensions.push_back(
encodeExtension(std::move(clientECHExtension)));
if (greasePsk) {
chloOuter.extensions.push_back(encodeExtension(*greasePsk));
}
break;
}
}
return chloOuter;
}
Actions
EventHandler<ClientTypes, StateEnum::Uninitialized, Event::Connect>::handle(
const State& /*state*/,
Param param) {
auto& connect = *param.asConnect();
auto context = std::move(connect.context);
// Set up SNI (including possible replacement ECH SNI)
folly::Optional<std::string> echSni;
auto sni = std::move(connect.sni);
folly::Optional<CachedPsk> psk =
validatePsk(*context, std::move(connect.cachedPsk));
Random random = context->getFactory()->makeRandom();
// If we have a saved PSK, use the group to choose which groups to
// send by default
std::vector<NamedGroup> selectedShares;
if (psk && psk->group &&
std::find(
context->getSupportedGroups().begin(),
context->getSupportedGroups().end(),
*psk->group) != context->getSupportedGroups().end()) {
// key exchange done last time
selectedShares = {*psk->group};
} else if (
context->getSendKeyShare() == SendKeyShare::WhenNecessary && psk &&
!psk->group) {
// psk_ke last time
selectedShares = {};
} else {
selectedShares = context->getDefaultShares();
}
auto earlyDataParams = getEarlyDataParams(*context, psk);
Buf legacySessionId;
if (context->getCompatibilityMode()) {
legacySessionId =
folly::IOBuf::copyBuffer(context->getFactory()->makeRandom());
} else {
legacySessionId = folly::IOBuf::create(0);
}
auto keyExchangers = getKeyExchangers(*context->getFactory(), selectedShares);
// If ECH requested, setup ECH primitives.
// These will also be used later in the construction of the client hello outer
// for ECH.
folly::Optional<ECHParams> echParams = setupECH(
connect.echConfigs,
context->getSupportedCiphers(),
context->getSupportedGroups(),
*context->getFactory());
auto chlo = getClientHello(
*context->getFactory(),
random,
context->getSupportedCiphers(),
context->getSupportedVersions(),
context->getSupportedGroups(),
keyExchangers,
context->getSupportedSigSchemes(),
context->getSupportedPskModes(),
sni,
context->getSupportedAlpns(),
context->getSupportedCertDecompressionAlgorithms(),
earlyDataParams,
legacySessionId,
connect.extensions.get());
std::vector<ExtensionType> requestedExtensions;
for (const auto& extension : chlo.extensions) {
requestedExtensions.push_back(extension.extension_type);
}
if (echParams.has_value() &&
echParams.value().supportedECHConfig.config.version ==
ech::ECHVersion::Draft15) {
ech::InnerECHClientHello chloIsInnerExt;
chlo.extensions.push_back(encodeExtension(std::move(chloIsInnerExt)));
requestedExtensions.push_back(ExtensionType::encrypted_client_hello);
}
Buf encodedClientHello;
std::unique_ptr<EncryptedWriteRecordLayer> earlyWriteRecordLayer;
Optional<ReportEarlyHandshakeSuccess> reportEarlySuccess;
Optional<SecretAvailable> earlyWriteSecretAvailable;
Optional<DerivedSecret> earlyExporterVector;
if (psk) {
requestedExtensions.push_back(ExtensionType::pre_shared_key);
auto keyScheduler = context->getFactory()->makeKeyScheduler(psk->cipher);
auto handshakeContext =
context->getFactory()->makeHandshakeContext(psk->cipher);
encodedClientHello = encodeAndAddBinders(
chlo, *psk, *keyScheduler, *handshakeContext, *context->getClock());
if (earlyDataParams) {
auto earlyWriteSecret = keyScheduler->getSecret(
EarlySecrets::ClientEarlyTraffic,
handshakeContext->getHandshakeContext()->coalesce());
if (!context->getOmitEarlyRecordLayer()) {
earlyWriteRecordLayer =
context->getFactory()->makeEncryptedWriteRecordLayer(
EncryptionLevel::EarlyData);
earlyWriteRecordLayer->setProtocolVersion(psk->version);
Protocol::setAead(
*earlyWriteRecordLayer,
psk->cipher,
folly::range(earlyWriteSecret.secret),
*context->getFactory(),
*keyScheduler);
}
earlyWriteSecretAvailable = SecretAvailable(std::move(earlyWriteSecret));
earlyExporterVector = keyScheduler->getSecret(
EarlySecrets::EarlyExporter,
handshakeContext->getHandshakeContext()->coalesce());
earlyDataParams->earlyExporterSecret =
folly::IOBuf::copyBuffer(earlyExporterVector->secret);
reportEarlySuccess = ReportEarlyHandshakeSuccess();
reportEarlySuccess->maxEarlyDataSize = psk->maxEarlyDataSize;
}
} else {
encodedClientHello = encodeHandshake(chlo);
}
// Create the ECH (both the client hello inner and client hello outer)
Buf encodedECH;
// Random used in the inner (encrypted) client hello.
folly::Optional<Random> echRandom;
folly::Optional<ClientPresharedKey> greasePsk;
if (echParams.has_value()) {
// Swap out randoms first.
echRandom = std::move(random);
random = context->getFactory()->makeRandom();
// Generate GREASE PSK (if needed)
greasePsk = ech::generateGreasePSK(chlo, context->getFactory());
chlo = constructEncryptedClientHello(
Event::ClientHello,
std::move(chlo),
echParams->supportedECHConfig,
echParams->setupResult,
random,
echParams->fakeSni->clone(),
greasePsk);
// Update SNI now
echSni = std::move(sni);
sni = echParams->fakeSni->clone()->moveToFbString().toStdString();
// Save client hello inner
encodedECH = std::move(encodedClientHello);
// Update the client hello with the ECH client hello outer
encodedClientHello = encodeHandshake(chlo);
}
auto readRecordLayer = context->getFactory()->makePlaintextReadRecordLayer();
auto writeRecordLayer =
context->getFactory()->makePlaintextWriteRecordLayer();
WriteToSocket write;
write.contents.emplace_back(
writeRecordLayer->writeInitialClientHello(encodedClientHello->clone()));
EarlyDataType earlyDataType =
earlyDataParams ? EarlyDataType::Attempted : EarlyDataType::NotAttempted;
MutateState saveState([context = std::move(context),
verifier = connect.verifier,
encodedClientHello = std::move(encodedClientHello),
encodedECH = std::move(encodedECH),
readRecordLayer = std::move(readRecordLayer),
writeRecordLayer = std::move(writeRecordLayer),
keyExchangers = std::move(keyExchangers),
sni = std::move(sni),
echSni = std::move(echSni),
echParams = std::move(echParams),
echRandom = std::move(echRandom),
greasePsk = std::move(greasePsk),
random = std::move(random),
legacySessionId = std::move(legacySessionId),
psk = std::move(psk),
extensions = connect.extensions,
requestedExtensions = std::move(requestedExtensions),
earlyDataType](State& newState) mutable {
newState.context() = std::move(context);
newState.verifier() = verifier;
if (echParams.has_value()) {
newState.echState().emplace();
newState.echState()->sni = std::move(echSni);
newState.echState()->encodedECH = std::move(encodedECH);
newState.echState()->supportedConfig =
std::move(echParams->supportedECHConfig);
newState.echState()->hpkeSetup = std::move(echParams->setupResult);
newState.echState()->random = std::move(*echRandom);
newState.echState()->greasePsk = std::move(greasePsk);
}
newState.encodedClientHello() = std::move(encodedClientHello);
newState.readRecordLayer() = std::move(readRecordLayer);
newState.writeRecordLayer() = std::move(writeRecordLayer);
newState.keyExchangers() = std::move(keyExchangers);
newState.sni() = std::move(sni);
newState.clientRandom() = std::move(random);
newState.legacySessionId() = std::move(legacySessionId);
newState.attemptedPsk() = std::move(psk);
newState.extensions() = extensions;
newState.requestedExtensions() = std::move(requestedExtensions);
newState.earlyDataType() = earlyDataType;
});
if (reportEarlySuccess) {
return actions(
std::move(saveState),
MutateState([earlyDataParams = std::move(*earlyDataParams),
earlyWriteRecordLayer = std::move(earlyWriteRecordLayer)](
State& newState) mutable {
newState.earlyDataParams() = std::move(earlyDataParams);
newState.earlyWriteRecordLayer() = std::move(earlyWriteRecordLayer);
}),
std::move(write),