proxygen
ServerProtocolTest.cpp
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2018-present, Facebook, Inc.
3  * All rights reserved.
4  *
5  * This source code is licensed under the BSD-style license found in the
6  * LICENSE file in the root directory of this source tree.
7  */
8 
9 #include <gmock/gmock.h>
10 #include <gtest/gtest.h>
11 
16 #include <fizz/record/Extensions.h>
17 #include <fizz/record/test/Mocks.h>
19 #include <fizz/server/test/Mocks.h>
21 
22 using namespace fizz::test;
23 using namespace folly;
24 using namespace testing;
25 
26 namespace fizz {
27 namespace server {
28 namespace test {
29 
30 class ServerProtocolTest : public ProtocolTest<ServerTypes, Actions> {
31  public:
32  void SetUp() override {
33  context_ = std::make_shared<FizzServerContext>();
34  context_->setSupportedVersions({ProtocolVersion::tls_1_3});
35  auto mockFactory = std::make_unique<MockFactory>();
36  mockFactory->setDefaults();
37  factory_ = mockFactory.get();
38  context_->setFactory(std::move(mockFactory));
39  cert_ = std::make_shared<MockSelfCert>();
40  auto certManager = std::make_unique<MockCertManager>();
41  certManager_ = certManager.get();
42  certVerifier_ = std::make_shared<MockCertificateVerifier>();
43  context_->setClientCertVerifier(certVerifier_);
44  context_->setCertManager(std::move(certManager));
45  context_->setSupportedAlpns({"h2", "h3"});
46  mockTicketCipher_ = std::make_shared<MockTicketCipher>();
47  mockTicketCipher_->setDefaults();
48  context_->setTicketCipher(mockTicketCipher_);
49  extensions_ = std::make_shared<MockServerExtensions>();
50 
51  ON_CALL(*certManager_, getCert(_, _, _))
52  .WillByDefault(Return(CertManager::CertMatch(
53  std::make_pair(cert_, SignatureScheme::ecdsa_secp256r1_sha256))));
54  ON_CALL(*certManager_, getCert(_)).WillByDefault(Return(cert_));
55  }
56 
57  protected:
58  Actions getActions(AsyncActions asyncActions, bool immediate = true) {
59  while (executor_.run())
60  ;
61  return folly::variant_match(
62  asyncActions,
63  [immediate](folly::Future<Actions>& futureActions) {
64  if (immediate) {
65  EXPECT_TRUE(futureActions.hasValue());
66  }
67  return std::move(futureActions).get();
68  },
69  [](Actions& immediateActions) { return std::move(immediateActions); });
70  }
71 
72  static std::unique_ptr<IOBuf> getEncryptedHandshakeWrite(
73  EncryptedExtensions encryptedExt,
74  CertificateMsg certificate,
76  Finished finished) {
77  auto buf = encodeHandshake(std::move(encryptedExt));
78  buf->prependChain(encodeHandshake(std::move(certificate)));
79  buf->prependChain(encodeHandshake(std::move(verify)));
80  buf->prependChain(encodeHandshake(std::move(finished)));
81  return buf;
82  }
83 
84  static std::unique_ptr<IOBuf> getEncryptedHandshakeWrite(
85  EncryptedExtensions encryptedExt,
86  CertificateRequest request,
87  CertificateMsg certificate,
89  Finished finished) {
90  auto buf = encodeHandshake(std::move(encryptedExt));
91  buf->prependChain(encodeHandshake(std::move(request)));
92  buf->prependChain(encodeHandshake(std::move(certificate)));
93  buf->prependChain(encodeHandshake(std::move(verify)));
94  buf->prependChain(encodeHandshake(std::move(finished)));
95  return buf;
96  }
97 
98  static std::unique_ptr<IOBuf> getEncryptedHandshakeWrite(
99  EncryptedExtensions encryptedExt,
100  CompressedCertificate certificate,
102  Finished finished) {
103  auto buf = encodeHandshake(std::move(encryptedExt));
104  buf->prependChain(encodeHandshake(std::move(certificate)));
105  buf->prependChain(encodeHandshake(std::move(verify)));
106  buf->prependChain(encodeHandshake(std::move(finished)));
107  return buf;
108  }
109 
110  static std::unique_ptr<IOBuf> getEncryptedHandshakeWrite(
111  EncryptedExtensions encryptedExt,
112  Finished finished) {
113  auto buf = encodeHandshake(std::move(encryptedExt));
114  buf->prependChain(encodeHandshake(std::move(finished)));
115  return buf;
116  }
117 
118  void setMockRecord() {
119  mockRead_ = new MockPlaintextReadRecordLayer();
120  mockWrite_ = new MockPlaintextWriteRecordLayer();
121  mockWrite_->setDefaults();
122  state_.readRecordLayer().reset(mockRead_);
123  state_.writeRecordLayer().reset(mockWrite_);
124  }
125 
129  appWrite_->setDefaults();
130  state_.readRecordLayer().reset(appRead_);
131  state_.writeRecordLayer().reset(appWrite_);
132  }
133 
135  mockKeyScheduler_ = new MockKeyScheduler();
136  mockKeyScheduler_->setDefaults();
137  state_.keyScheduler().reset(mockKeyScheduler_);
138  }
139 
141  mockHandshakeContext_ = new MockHandshakeContext();
142  mockHandshakeContext_->setDefaults();
143  state_.handshakeContext().reset(mockHandshakeContext_);
144  }
145 
147  replayCache_ = std::make_shared<MockReplayCache>();
148  ON_CALL(*replayCache_, check(_)).WillByDefault(InvokeWithoutArgs([] {
150  }));
151  context_->setEarlyDataSettings(
152  true,
153  {std::chrono::milliseconds(-1000000),
154  std::chrono::milliseconds(1000000)},
155  replayCache_);
156  }
157 
158  void acceptCookies() {
159  mockCookieCipher_ = std::make_shared<MockCookieCipher>();
160  context_->setCookieCipher(mockCookieCipher_);
161  }
162 
163  void expectCookie() {
164  acceptCookies();
165  EXPECT_CALL(*mockCookieCipher_, _decrypt(_))
166  .WillOnce(Invoke([](Buf& cookie) {
167  if (IOBufEqualTo()(cookie, IOBuf::copyBuffer("cookie"))) {
168  CookieState cs;
171  cs.chloHash = IOBuf::copyBuffer("chlohash");
172  cs.appToken = IOBuf::create(0);
174  } else {
176  }
177  }));
178  }
179 
181  setMockRecord();
182  state_.executor() = &executor_;
183  state_.context() = context_;
184  state_.state() = StateEnum::ExpectingClientHello;
185  if (addExtensions_) {
186  state_.extensions() = extensions_;
187  }
188  }
189 
191  setMockRecord();
192  setMockHandshakeContext();
193  state_.executor() = &executor_;
194  state_.context() = context_;
195  state_.version() = TestProtocolVersion;
196  state_.cipher() = CipherSuite::TLS_AES_128_GCM_SHA256;
197  state_.group() = NamedGroup::x25519;
198  state_.keyExchangeType() = KeyExchangeType::HelloRetryRequest;
199  state_.state() = StateEnum::ExpectingClientHello;
200  if (addExtensions_) {
201  state_.extensions() = extensions_;
202  }
203  }
204 
206  setMockRecord();
207  setMockKeyScheduler();
208  setMockHandshakeContext();
209  state_.executor() = &executor_;
210  state_.context() = context_;
211  state_.clientHandshakeSecret() = IOBuf::copyBuffer("clihandsec");
212  state_.exporterMasterSecret() = IOBuf::copyBuffer("exportermaster");
213  state_.version() = TestProtocolVersion;
214  state_.cipher() = CipherSuite::TLS_AES_128_GCM_SHA256;
215  state_.state() = StateEnum::ExpectingFinished;
216  state_.serverCert() = cert_;
217  state_.pskType() = PskType::NotAttempted;
218  state_.alpn() = "h2";
219  }
220 
222  setMockRecord();
223  setMockKeyScheduler();
224  setMockHandshakeContext();
225  state_.executor() = &executor_;
226  state_.context() = context_;
227  state_.clientHandshakeSecret() = IOBuf::copyBuffer("clihandsec");
228  state_.exporterMasterSecret() = IOBuf::copyBuffer("exportermaster");
229  state_.version() = TestProtocolVersion;
230  state_.cipher() = CipherSuite::TLS_AES_128_GCM_SHA256;
231  state_.state() = StateEnum::ExpectingCertificate;
232  state_.serverCert() = cert_;
233  state_.pskType() = PskType::NotAttempted;
234  state_.alpn() = "h2";
235  context_->setClientAuthMode(ClientAuthMode::Required);
236  }
237 
239  setMockRecord();
240  setMockKeyScheduler();
241  setMockHandshakeContext();
242  state_.executor() = &executor_;
243  state_.context() = context_;
244  state_.clientHandshakeSecret() = IOBuf::copyBuffer("clihandsec");
245  state_.exporterMasterSecret() = IOBuf::copyBuffer("exportermaster");
246  state_.version() = TestProtocolVersion;
247  state_.cipher() = CipherSuite::TLS_AES_128_GCM_SHA256;
248  state_.state() = StateEnum::ExpectingCertificateVerify;
249  state_.serverCert() = cert_;
250  clientIntCert_ = std::make_shared<MockPeerCert>();
251  clientLeafCert_ = std::make_shared<MockPeerCert>();
252  std::vector<std::shared_ptr<const PeerCert>> clientCerts = {clientLeafCert_,
253  clientIntCert_};
254  state_.unverifiedCertChain() = std::move(clientCerts);
255  state_.pskType() = PskType::NotAttempted;
256  state_.alpn() = "h2";
257  context_->setClientAuthMode(ClientAuthMode::Required);
258  }
259 
261  setMockRecord();
262  setMockKeyScheduler();
263  setMockHandshakeContext();
264  state_.handshakeReadRecordLayer().reset(
266  state_.version() = TestProtocolVersion;
267  state_.cipher() = CipherSuite::TLS_AES_128_GCM_SHA256;
268  state_.executor() = &executor_;
269  state_.state() = StateEnum::AcceptingEarlyData;
270  }
271 
273  setMockAppRecord();
274  setMockKeyScheduler();
275  setMockHandshakeContext();
276  state_.executor() = &executor_;
277  state_.version() = TestProtocolVersion;
278  state_.cipher() = CipherSuite::TLS_AES_128_GCM_SHA256;
279  state_.context() = context_;
280  state_.executor() = &executor_;
281  state_.state() = StateEnum::AcceptingData;
282  state_.serverCert() = cert_;
283  state_.pskType() = PskType::NotAttempted;
284  state_.alpn() = "h2";
285  }
286 
294  std::shared_ptr<MockTicketCipher> mockTicketCipher_;
295  std::shared_ptr<MockCookieCipher> mockCookieCipher_;
296  std::shared_ptr<FizzServerContext> context_;
297  std::shared_ptr<MockSelfCert> cert_;
298  std::shared_ptr<MockPeerCert> clientIntCert_;
299  std::shared_ptr<MockPeerCert> clientLeafCert_;
300  std::shared_ptr<MockCertificateVerifier> certVerifier_;
302  std::shared_ptr<MockServerExtensions> extensions_;
303  std::shared_ptr<MockReplayCache> replayCache_;
304  bool addExtensions_ = true;
305 };
306 
307 TEST_F(ServerProtocolTest, TestInvalidTransitionNoAlert) {
308  auto actions =
309  getActions(ServerStateMachine().processAppWrite(state_, AppWrite()));
310  expectError<FizzException>(actions, none, "invalid event");
311 }
312 
313 TEST_F(ServerProtocolTest, TestInvalidTransitionAlert) {
314  setMockRecord();
315  EXPECT_CALL(*mockWrite_, _write(_));
316  auto actions =
317  getActions(ServerStateMachine().processAppWrite(state_, AppWrite()));
318  expectError<FizzException>(
320 }
321 
322 TEST_F(ServerProtocolTest, TestInvalidTransitionError) {
323  state_.state() = StateEnum::Error;
324  auto actions =
325  getActions(ServerStateMachine().processAppWrite(state_, AppWrite()));
326  EXPECT_TRUE(actions.empty());
327 }
328 
329 TEST_F(ServerProtocolTest, TestAlertReceived) {
330  setUpAcceptingData();
331  Alert alert;
333  auto actions = getActions(detail::processEvent(state_, std::move(alert)));
334  expectError<FizzException>(actions, folly::none, "received alert");
335 }
336 
338  ReadRecordLayer* rrl;
339  WriteRecordLayer* wrl;
340  EXPECT_CALL(*factory_, makePlaintextReadRecordLayer())
341  .WillOnce(Invoke([&rrl]() {
342  auto ret = std::make_unique<PlaintextReadRecordLayer>();
343  rrl = ret.get();
344  return ret;
345  }));
346  EXPECT_CALL(*factory_, makePlaintextWriteRecordLayer())
347  .WillOnce(Invoke([&wrl]() {
348  auto ret = std::make_unique<PlaintextWriteRecordLayer>();
349  wrl = ret.get();
350  return ret;
351  }));
352  auto actions = getActions(ServerStateMachine().processAccept(
353  state_, &executor_, context_, extensions_));
354  expectActions<MutateState>(actions);
355  processStateMutations(actions);
356  EXPECT_EQ(state_.state(), StateEnum::ExpectingClientHello);
357  EXPECT_EQ(state_.executor(), &executor_);
358  EXPECT_EQ(state_.context().get(), context_.get());
359  EXPECT_EQ(state_.readRecordLayer().get(), rrl);
360  EXPECT_EQ(
361  state_.readRecordLayer()->getEncryptionLevel(),
363  EXPECT_EQ(state_.writeRecordLayer().get(), wrl);
364  EXPECT_EQ(
365  state_.writeRecordLayer()->getEncryptionLevel(),
367 }
368 
369 TEST_F(ServerProtocolTest, TestAppClose) {
370  setUpAcceptingData();
371  EXPECT_CALL(*appWrite_, _write(_)).WillOnce(Invoke([&](TLSMessage& msg) {
372  TLSContent content;
373  content.contentType = msg.type;
374  content.encryptionLevel = appWrite_->getEncryptionLevel();
378  content.data = IOBuf::copyBuffer("closenotify");
379  return content;
380  }));
381  auto actions = ServerStateMachine().processAppClose(state_);
382  expectActions<MutateState, WriteToSocket>(actions);
383  auto write = expectAction<WriteToSocket>(actions);
384  EXPECT_EQ(write.contents[0].contentType, ContentType::alert);
385  EXPECT_EQ(write.contents[0].encryptionLevel, EncryptionLevel::AppTraffic);
386  processStateMutations(actions);
387  EXPECT_EQ(state_.state(), StateEnum::Error);
388  EXPECT_EQ(state_.readRecordLayer().get(), nullptr);
389  EXPECT_EQ(state_.writeRecordLayer().get(), nullptr);
390 }
391 
392 TEST_F(ServerProtocolTest, TestAppCloseNoWrite) {
393  auto actions = ServerStateMachine().processAppClose(state_);
394  expectActions<MutateState>(actions);
395  processStateMutations(actions);
396  EXPECT_EQ(state_.state(), StateEnum::Error);
397  EXPECT_EQ(state_.readRecordLayer().get(), nullptr);
398  EXPECT_EQ(state_.writeRecordLayer().get(), nullptr);
399 }
400 
401 TEST_F(ServerProtocolTest, TestClientHelloFullHandshakeFlow) {
402  setUpExpectingClientHello();
403  Sequence contextSeq;
404  mockKeyScheduler_ = new MockKeyScheduler();
405  mockHandshakeContext_ = new MockHandshakeContext();
406  EXPECT_CALL(*factory_, makeKeyScheduler(CipherSuite::TLS_AES_128_GCM_SHA256))
407  .WillOnce(InvokeWithoutArgs(
408  [=]() { return std::unique_ptr<KeyScheduler>(mockKeyScheduler_); }));
409  EXPECT_CALL(
410  *factory_, makeHandshakeContext(CipherSuite::TLS_AES_128_GCM_SHA256))
411  .WillOnce(InvokeWithoutArgs([=]() {
412  return std::unique_ptr<HandshakeContext>(mockHandshakeContext_);
413  }));
414  EXPECT_CALL(
415  *mockHandshakeContext_,
416  appendToTranscript(BufMatches("clienthelloencoding")))
417  .InSequence(contextSeq);
418  EXPECT_CALL(*factory_, makeKeyExchange(NamedGroup::x25519))
419  .WillOnce(InvokeWithoutArgs([]() {
420  auto ret = std::make_unique<MockKeyExchange>();
421  EXPECT_CALL(*ret, generateKeyPair());
422  EXPECT_CALL(*ret, generateSharedSecret(RangeMatches("keyshare")))
423  .WillOnce(InvokeWithoutArgs(
424  []() { return IOBuf::copyBuffer("sharedsecret"); }));
425  EXPECT_CALL(*ret, getKeyShare()).WillOnce(InvokeWithoutArgs([]() {
426  return IOBuf::copyBuffer("servershare");
427  }));
428  return ret;
429  }));
430  EXPECT_CALL(*mockHandshakeContext_, appendToTranscript(_))
431  .InSequence(contextSeq);
432  EXPECT_CALL(*mockHandshakeContext_, getHandshakeContext())
433  .InSequence(contextSeq)
434  .WillRepeatedly(Invoke([]() { return IOBuf::copyBuffer("chlo_shlo"); }));
435  EXPECT_CALL(
436  *mockKeyScheduler_, deriveHandshakeSecret(RangeMatches("sharedsecret")));
437  EXPECT_CALL(*factory_, makeRandom()).WillOnce(Invoke([]() {
438  Random random;
439  random.fill(0x44);
440  return random;
441  }));
442  EXPECT_CALL(*mockWrite_, _write(_)).WillOnce(Invoke([&](TLSMessage& msg) {
443  TLSContent content;
444  content.contentType = msg.type;
445  content.encryptionLevel = mockWrite_->getEncryptionLevel();
449  content.data = IOBuf::copyBuffer("writtenshlo");
450  return content;
451  }));
452  EXPECT_CALL(
453  *mockKeyScheduler_,
454  getSecret(
455  HandshakeSecrets::ServerHandshakeTraffic, RangeMatches("chlo_shlo")))
456  .WillOnce(InvokeWithoutArgs([]() {
457  return std::vector<uint8_t>({'s', 'h', 't'});
458  }));
459  EXPECT_CALL(
460  *mockKeyScheduler_,
461  getSecret(
462  HandshakeSecrets::ClientHandshakeTraffic, RangeMatches("chlo_shlo")))
463  .WillOnce(InvokeWithoutArgs([]() {
464  return std::vector<uint8_t>({'c', 'h', 't'});
465  }));
466  EXPECT_CALL(*mockKeyScheduler_, getTrafficKey(RangeMatches("sht"), _, _))
467  .WillOnce(InvokeWithoutArgs([]() {
468  return TrafficKey{IOBuf::copyBuffer("serverkey"),
469  IOBuf::copyBuffer("serveriv")};
470  }));
471  EXPECT_CALL(*mockKeyScheduler_, getTrafficKey(RangeMatches("cht"), _, _))
472  .WillOnce(InvokeWithoutArgs([]() {
473  return TrafficKey{IOBuf::copyBuffer("clientkey"),
474  IOBuf::copyBuffer("clientiv")};
475  }));
476  EXPECT_CALL(*extensions_, getExtensions(_)).WillOnce(InvokeWithoutArgs([]() {
477  Extension ext;
479  ext.extension_data = folly::IOBuf::copyBuffer("someextension");
480  std::vector<Extension> exts;
481  exts.push_back(std::move(ext));
482  return exts;
483  }));
484 
485  MockAead* raead;
486  MockAead* waead;
487  MockAead* appwaead;
491  expectAeadCreation({{"clientkey", &raead},
492  {"serverkey", &waead},
493  {"serverappkey", &appwaead}});
494  expectEncryptedReadRecordLayerCreation(
495  &rrl, &raead, StringPiece("cht"), false);
496  Sequence recSeq;
497  expectEncryptedWriteRecordLayerCreation(
498  &wrl,
499  &waead,
500  StringPiece("sht"),
501  [](TLSMessage& msg, auto writeRecord) {
503 
504  auto modifiedEncryptedExt = TestMessages::encryptedExt();
505  Extension ext;
507  ext.extension_data = folly::IOBuf::copyBuffer("someextension");
508  modifiedEncryptedExt.extensions.push_back(std::move(ext));
510  msg.fragment,
511  getEncryptedHandshakeWrite(
512  std::move(modifiedEncryptedExt),
516  TLSContent content;
517  content.contentType = msg.type;
518  content.encryptionLevel = writeRecord->getEncryptionLevel();
519  content.data = folly::IOBuf::copyBuffer("handshake");
520  return content;
521  },
522  &recSeq);
523  expectEncryptedWriteRecordLayerCreation(
524  &appwrl, &appwaead, StringPiece("sat"), nullptr, &recSeq);
525  EXPECT_CALL(*mockHandshakeContext_, appendToTranscript(_))
526  .InSequence(contextSeq);
527  EXPECT_CALL(*certManager_, getCert(_, _, _))
528  .WillOnce(Invoke(
530  const std::vector<SignatureScheme>& /* supportedSigSchemes */,
531  const std::vector<SignatureScheme>& peerSigSchemes) {
532  EXPECT_EQ(*sni, "www.hostname.com");
533  EXPECT_EQ(peerSigSchemes.size(), 2);
534  EXPECT_EQ(
535  peerSigSchemes[0], SignatureScheme::ecdsa_secp256r1_sha256);
536  EXPECT_EQ(peerSigSchemes[1], SignatureScheme::rsa_pss_sha256);
537  return CertManager::CertMatch(
538  std::make_pair(cert_, SignatureScheme::ecdsa_secp256r1_sha256));
539  }));
540  EXPECT_CALL(*cert_, _getCertMessage(_));
541  EXPECT_CALL(*mockHandshakeContext_, appendToTranscript(_))
542  .InSequence(contextSeq);
543  EXPECT_CALL(*mockHandshakeContext_, getHandshakeContext())
544  .InSequence(contextSeq)
545  .WillRepeatedly(
546  Invoke([]() { return IOBuf::copyBuffer("chlo_shlo_ee_cert"); }));
547  EXPECT_CALL(
548  *cert_,
549  sign(
552  RangeMatches("chlo_shlo_ee_cert")))
553  .WillOnce(
554  InvokeWithoutArgs([]() { return IOBuf::copyBuffer("signature"); }));
555  EXPECT_CALL(*mockHandshakeContext_, appendToTranscript(_))
556  .InSequence(contextSeq);
557  EXPECT_CALL(*mockHandshakeContext_, getFinishedData(RangeMatches("sht")))
558  .InSequence(contextSeq)
559  .WillRepeatedly(
560  InvokeWithoutArgs([]() { return IOBuf::copyBuffer("verifydata"); }));
561  EXPECT_CALL(*mockHandshakeContext_, appendToTranscript(_))
562  .InSequence(contextSeq);
563  EXPECT_CALL(*mockHandshakeContext_, getHandshakeContext())
564  .InSequence(contextSeq)
565  .WillRepeatedly(InvokeWithoutArgs(
566  []() { return IOBuf::copyBuffer("chlo_shlo_ee_cert_sfin"); }));
567  EXPECT_CALL(*mockKeyScheduler_, deriveMasterSecret());
568  EXPECT_CALL(
569  *mockKeyScheduler_,
570  getSecret(
572  RangeMatches("chlo_shlo_ee_cert_sfin")))
573  .WillOnce(InvokeWithoutArgs([]() {
574  return std::vector<uint8_t>({'e', 'x', 'p', 'm'});
575  }));
576  EXPECT_CALL(
577  *mockKeyScheduler_,
578  deriveAppTrafficSecrets(RangeMatches("chlo_shlo_ee_cert_sfin")));
579  EXPECT_CALL(
580  *mockKeyScheduler_, getSecret(AppTrafficSecrets::ServerAppTraffic))
581  .WillOnce(InvokeWithoutArgs([]() {
582  return std::vector<uint8_t>({'s', 'a', 't'});
583  }));
584  EXPECT_CALL(*mockKeyScheduler_, getTrafficKey(RangeMatches("sat"), _, _))
585  .WillOnce(InvokeWithoutArgs([]() {
586  return TrafficKey{IOBuf::copyBuffer("serverappkey"),
587  IOBuf::copyBuffer("serverappiv")};
588  }));
589 
590  auto actions =
591  getActions(detail::processEvent(state_, TestMessages::clientHello()));
592 
593  expectActions<MutateState, WriteToSocket>(actions);
594  auto write = expectAction<WriteToSocket>(actions);
595  ASSERT_EQ(write.contents.size(), 2);
596 
597  EXPECT_EQ(write.contents[0].encryptionLevel, EncryptionLevel::Plaintext);
598  EXPECT_EQ(write.contents[0].contentType, ContentType::handshake);
599  EXPECT_TRUE(
600  IOBufEqualTo()(write.contents[0].data, IOBuf::copyBuffer("writtenshlo")));
601 
602  EXPECT_EQ(write.contents[1].encryptionLevel, EncryptionLevel::Handshake);
603  EXPECT_EQ(write.contents[1].contentType, ContentType::handshake);
604  EXPECT_TRUE(
605  IOBufEqualTo()(write.contents[1].data, IOBuf::copyBuffer("handshake")));
606  processStateMutations(actions);
607  EXPECT_EQ(state_.state(), StateEnum::ExpectingFinished);
608  EXPECT_EQ(state_.readRecordLayer().get(), rrl);
609  EXPECT_EQ(
610  state_.readRecordLayer()->getEncryptionLevel(),
612  EXPECT_EQ(state_.writeRecordLayer().get(), appwrl);
613  EXPECT_EQ(
614  state_.writeRecordLayer()->getEncryptionLevel(),
616  EXPECT_EQ(state_.handshakeContext().get(), mockHandshakeContext_);
617  EXPECT_EQ(state_.keyScheduler().get(), mockKeyScheduler_);
618  EXPECT_EQ(state_.serverCert(), cert_);
619  EXPECT_EQ(state_.version(), TestProtocolVersion);
621  EXPECT_EQ(state_.group(), NamedGroup::x25519);
623  EXPECT_EQ(state_.pskType(), PskType::NotAttempted);
624  EXPECT_FALSE(state_.pskMode().hasValue());
625  EXPECT_EQ(state_.keyExchangeType(), KeyExchangeType::OneRtt);
626  EXPECT_EQ(state_.earlyDataType(), EarlyDataType::NotAttempted);
627  EXPECT_EQ(state_.replayCacheResult(), ReplayCacheResult::NotChecked);
628  EXPECT_FALSE(state_.clientClockSkew().hasValue());
629  EXPECT_EQ(*state_.alpn(), "h2");
631  *state_.clientHandshakeSecret(), IOBuf::copyBuffer("cht")));
633  *state_.exporterMasterSecret(), IOBuf::copyBuffer("expm")));
634  EXPECT_FALSE(state_.earlyExporterMasterSecret().hasValue());
635 }
636 
637 TEST_F(ServerProtocolTest, TestClientHelloCompressedCertFlow) {
638  setUpExpectingClientHello();
639  Sequence contextSeq;
640  mockKeyScheduler_ = new MockKeyScheduler();
641  mockHandshakeContext_ = new MockHandshakeContext();
642  EXPECT_CALL(*factory_, makeKeyScheduler(CipherSuite::TLS_AES_128_GCM_SHA256))
643  .WillOnce(InvokeWithoutArgs(
644  [=]() { return std::unique_ptr<KeyScheduler>(mockKeyScheduler_); }));
645  EXPECT_CALL(
646  *factory_, makeHandshakeContext(CipherSuite::TLS_AES_128_GCM_SHA256))
647  .WillOnce(InvokeWithoutArgs([=]() {
648  return std::unique_ptr<HandshakeContext>(mockHandshakeContext_);
649  }));
650  EXPECT_CALL(
651  *mockHandshakeContext_,
652  appendToTranscript(BufMatches("clienthelloencoding")))
653  .InSequence(contextSeq);
654  EXPECT_CALL(*factory_, makeKeyExchange(NamedGroup::x25519))
655  .WillOnce(InvokeWithoutArgs([]() {
656  auto ret = std::make_unique<MockKeyExchange>();
657  EXPECT_CALL(*ret, generateKeyPair());
658  EXPECT_CALL(*ret, generateSharedSecret(RangeMatches("keyshare")))
659  .WillOnce(InvokeWithoutArgs(
660  []() { return IOBuf::copyBuffer("sharedsecret"); }));
661  EXPECT_CALL(*ret, getKeyShare()).WillOnce(InvokeWithoutArgs([]() {
662  return IOBuf::copyBuffer("servershare");
663  }));
664  return ret;
665  }));
666  EXPECT_CALL(*mockHandshakeContext_, appendToTranscript(_))
667  .InSequence(contextSeq);
668  EXPECT_CALL(*mockHandshakeContext_, getHandshakeContext())
669  .InSequence(contextSeq)
670  .WillRepeatedly(Invoke([]() { return IOBuf::copyBuffer("chlo_shlo"); }));
671  EXPECT_CALL(
672  *mockKeyScheduler_, deriveHandshakeSecret(RangeMatches("sharedsecret")));
673  EXPECT_CALL(*factory_, makeRandom()).WillOnce(Invoke([]() {
674  Random random;
675  random.fill(0x44);
676  return random;
677  }));
678  EXPECT_CALL(*mockWrite_, _write(_)).WillOnce(Invoke([&](TLSMessage& msg) {
679  TLSContent content;
680  content.contentType = msg.type;
681  content.encryptionLevel = mockWrite_->getEncryptionLevel();
685  content.data = IOBuf::copyBuffer("writtenshlo");
686  return content;
687  }));
688  EXPECT_CALL(
689  *mockKeyScheduler_,
690  getSecret(
691  HandshakeSecrets::ServerHandshakeTraffic, RangeMatches("chlo_shlo")))
692  .WillOnce(InvokeWithoutArgs([]() {
693  return std::vector<uint8_t>({'s', 'h', 't'});
694  }));
695  EXPECT_CALL(
696  *mockKeyScheduler_,
697  getSecret(
698  HandshakeSecrets::ClientHandshakeTraffic, RangeMatches("chlo_shlo")))
699  .WillOnce(InvokeWithoutArgs([]() {
700  return std::vector<uint8_t>({'c', 'h', 't'});
701  }));
702  EXPECT_CALL(*mockKeyScheduler_, getTrafficKey(RangeMatches("sht"), _, _))
703  .WillOnce(InvokeWithoutArgs([]() {
704  return TrafficKey{IOBuf::copyBuffer("serverkey"),
705  IOBuf::copyBuffer("serveriv")};
706  }));
707  EXPECT_CALL(*mockKeyScheduler_, getTrafficKey(RangeMatches("cht"), _, _))
708  .WillOnce(InvokeWithoutArgs([]() {
709  return TrafficKey{IOBuf::copyBuffer("clientkey"),
710  IOBuf::copyBuffer("clientiv")};
711  }));
712  EXPECT_CALL(*extensions_, getExtensions(_)).WillOnce(InvokeWithoutArgs([]() {
713  Extension ext;
715  ext.extension_data = folly::IOBuf::copyBuffer("someextension");
716  std::vector<Extension> exts;
717  exts.push_back(std::move(ext));
718  return exts;
719  }));
720 
721  MockAead* raead;
722  MockAead* waead;
723  MockAead* appwaead;
727  expectAeadCreation({{"clientkey", &raead},
728  {"serverkey", &waead},
729  {"serverappkey", &appwaead}});
730  expectEncryptedReadRecordLayerCreation(
731  &rrl, &raead, StringPiece("cht"), false);
732  Sequence recSeq;
733  expectEncryptedWriteRecordLayerCreation(
734  &wrl,
735  &waead,
736  StringPiece("sht"),
737  [](TLSMessage& msg, auto writeRecord) {
739 
740  auto modifiedEncryptedExt = TestMessages::encryptedExt();
741  Extension ext;
743  ext.extension_data = folly::IOBuf::copyBuffer("someextension");
744  modifiedEncryptedExt.extensions.push_back(std::move(ext));
746  msg.fragment,
747  getEncryptedHandshakeWrite(
748  std::move(modifiedEncryptedExt),
752  TLSContent content;
753  content.contentType = msg.type;
754  content.encryptionLevel = writeRecord->getEncryptionLevel();
755  content.data = folly::IOBuf::copyBuffer("handshake");
756  return content;
757  },
758  &recSeq);
759  expectEncryptedWriteRecordLayerCreation(
760  &appwrl, &appwaead, StringPiece("sat"), nullptr, &recSeq);
761  EXPECT_CALL(*mockHandshakeContext_, appendToTranscript(_))
762  .InSequence(contextSeq);
763  EXPECT_CALL(*certManager_, getCert(_, _, _))
764  .WillOnce(Invoke(
766  const std::vector<SignatureScheme>& /* supportedSigSchemes */,
767  const std::vector<SignatureScheme>& peerSigSchemes) {
768  EXPECT_EQ(*sni, "www.hostname.com");
769  EXPECT_EQ(peerSigSchemes.size(), 2);
770  EXPECT_EQ(
771  peerSigSchemes[0], SignatureScheme::ecdsa_secp256r1_sha256);
772  EXPECT_EQ(peerSigSchemes[1], SignatureScheme::rsa_pss_sha256);
773  return CertManager::CertMatch(
774  std::make_pair(cert_, SignatureScheme::ecdsa_secp256r1_sha256));
775  }));
776  context_->setSupportedCompressionAlgorithms(
778  EXPECT_CALL(*cert_, getCompressedCert(_)).WillOnce(InvokeWithoutArgs([]() {
780  }));
781  EXPECT_CALL(*mockHandshakeContext_, appendToTranscript(_))
782  .InSequence(contextSeq);
783  EXPECT_CALL(*mockHandshakeContext_, getHandshakeContext())
784  .InSequence(contextSeq)
785  .WillRepeatedly(
786  Invoke([]() { return IOBuf::copyBuffer("chlo_shlo_ee_compcert"); }));
787  EXPECT_CALL(
788  *cert_,
789  sign(
792  RangeMatches("chlo_shlo_ee_compcert")))
793  .WillOnce(
794  InvokeWithoutArgs([]() { return IOBuf::copyBuffer("signature"); }));
795  EXPECT_CALL(*mockHandshakeContext_, appendToTranscript(_))
796  .InSequence(contextSeq);
797  EXPECT_CALL(*mockHandshakeContext_, getFinishedData(RangeMatches("sht")))
798  .InSequence(contextSeq)
799  .WillRepeatedly(
800  InvokeWithoutArgs([]() { return IOBuf::copyBuffer("verifydata"); }));
801  EXPECT_CALL(*mockHandshakeContext_, appendToTranscript(_))
802  .InSequence(contextSeq);
803  EXPECT_CALL(*mockHandshakeContext_, getHandshakeContext())
804  .InSequence(contextSeq)
805  .WillRepeatedly(InvokeWithoutArgs(
806  []() { return IOBuf::copyBuffer("chlo_shlo_ee_compcert_sfin"); }));
807  EXPECT_CALL(*mockKeyScheduler_, deriveMasterSecret());
808  EXPECT_CALL(
809  *mockKeyScheduler_,
810  getSecret(
812  RangeMatches("chlo_shlo_ee_compcert_sfin")))
813  .WillOnce(InvokeWithoutArgs([]() {
814  return std::vector<uint8_t>({'e', 'x', 'p', 'm'});
815  }));
816  EXPECT_CALL(
817  *mockKeyScheduler_,
818  deriveAppTrafficSecrets(RangeMatches("chlo_shlo_ee_compcert_sfin")));
819  EXPECT_CALL(
820  *mockKeyScheduler_, getSecret(AppTrafficSecrets::ServerAppTraffic))
821  .WillOnce(InvokeWithoutArgs([]() {
822  return std::vector<uint8_t>({'s', 'a', 't'});
823  }));
824  EXPECT_CALL(*mockKeyScheduler_, getTrafficKey(RangeMatches("sat"), _, _))
825  .WillOnce(InvokeWithoutArgs([]() {
826  return TrafficKey{IOBuf::copyBuffer("serverappkey"),
827  IOBuf::copyBuffer("serverappiv")};
828  }));
829 
833  chlo.extensions.push_back(encodeExtension(algos));
834  auto actions = getActions(detail::processEvent(state_, std::move(chlo)));
835 
836  expectActions<MutateState, WriteToSocket>(actions);
837  auto write = expectAction<WriteToSocket>(actions);
838  ASSERT_EQ(write.contents.size(), 2);
839 
840  EXPECT_EQ(write.contents[0].encryptionLevel, EncryptionLevel::Plaintext);
841  EXPECT_EQ(write.contents[0].contentType, ContentType::handshake);
842  EXPECT_TRUE(
843  IOBufEqualTo()(write.contents[0].data, IOBuf::copyBuffer("writtenshlo")));
844 
845  EXPECT_EQ(write.contents[1].encryptionLevel, EncryptionLevel::Handshake);
846  EXPECT_EQ(write.contents[1].contentType, ContentType::handshake);
847  EXPECT_TRUE(
848  IOBufEqualTo()(write.contents[1].data, IOBuf::copyBuffer("handshake")));
849  processStateMutations(actions);
850  EXPECT_EQ(state_.state(), StateEnum::ExpectingFinished);
851  EXPECT_EQ(state_.readRecordLayer().get(), rrl);
852  EXPECT_EQ(state_.writeRecordLayer().get(), appwrl);
853  EXPECT_EQ(state_.handshakeContext().get(), mockHandshakeContext_);
854  EXPECT_EQ(state_.keyScheduler().get(), mockKeyScheduler_);
855  EXPECT_EQ(state_.serverCert(), cert_);
856  EXPECT_EQ(state_.serverCertCompAlgo(), CertificateCompressionAlgorithm::zlib);
857  EXPECT_EQ(state_.version(), TestProtocolVersion);
859  EXPECT_EQ(state_.group(), NamedGroup::x25519);
861  EXPECT_EQ(state_.pskType(), PskType::NotAttempted);
862  EXPECT_FALSE(state_.pskMode().hasValue());
863  EXPECT_EQ(state_.keyExchangeType(), KeyExchangeType::OneRtt);
864  EXPECT_EQ(state_.earlyDataType(), EarlyDataType::NotAttempted);
865  EXPECT_EQ(state_.replayCacheResult(), ReplayCacheResult::NotChecked);
866  EXPECT_FALSE(state_.clientClockSkew().hasValue());
867  EXPECT_EQ(*state_.alpn(), "h2");
869  *state_.clientHandshakeSecret(), IOBuf::copyBuffer("cht")));
871  *state_.exporterMasterSecret(), IOBuf::copyBuffer("expm")));
872  EXPECT_FALSE(state_.earlyExporterMasterSecret().hasValue());
873 }
874 
875 TEST_F(ServerProtocolTest, TestClientHelloCertRequestFlow) {
876  setUpExpectingClientHello();
877  context_->setClientAuthMode(ClientAuthMode::Required);
878  Sequence contextSeq;
879  mockKeyScheduler_ = new MockKeyScheduler();
880  mockHandshakeContext_ = new MockHandshakeContext();
881  EXPECT_CALL(*factory_, makeKeyScheduler(CipherSuite::TLS_AES_128_GCM_SHA256))
882  .WillOnce(InvokeWithoutArgs(
883  [=]() { return std::unique_ptr<KeyScheduler>(mockKeyScheduler_); }));
884  EXPECT_CALL(
885  *factory_, makeHandshakeContext(CipherSuite::TLS_AES_128_GCM_SHA256))
886  .WillOnce(InvokeWithoutArgs([=]() {
887  return std::unique_ptr<HandshakeContext>(mockHandshakeContext_);
888  }));
889  EXPECT_CALL(
890  *mockHandshakeContext_,
891  appendToTranscript(BufMatches("clienthelloencoding")))
892  .InSequence(contextSeq);
893  EXPECT_CALL(*factory_, makeKeyExchange(NamedGroup::x25519))
894  .WillOnce(InvokeWithoutArgs([]() {
895  auto ret = std::make_unique<MockKeyExchange>();
896  EXPECT_CALL(*ret, generateKeyPair());
897  EXPECT_CALL(*ret, generateSharedSecret(RangeMatches("keyshare")))
898  .WillOnce(InvokeWithoutArgs(
899  []() { return IOBuf::copyBuffer("sharedsecret"); }));
900  EXPECT_CALL(*ret, getKeyShare()).WillOnce(InvokeWithoutArgs([]() {
901  return IOBuf::copyBuffer("servershare");
902  }));
903  return ret;
904  }));
905  EXPECT_CALL(*mockHandshakeContext_, appendToTranscript(_))
906  .InSequence(contextSeq);
907  EXPECT_CALL(*mockHandshakeContext_, getHandshakeContext())
908  .InSequence(contextSeq)
909  .WillRepeatedly(Invoke([]() { return IOBuf::copyBuffer("chlo_shlo"); }));
910  EXPECT_CALL(
911  *mockKeyScheduler_, deriveHandshakeSecret(RangeMatches("sharedsecret")));
912  EXPECT_CALL(*factory_, makeRandom()).WillOnce(Invoke([]() {
913  Random random;
914  random.fill(0x44);
915  return random;
916  }));
917  EXPECT_CALL(*mockWrite_, _write(_)).WillOnce(Invoke([&](TLSMessage& msg) {
918  TLSContent content;
919  content.contentType = msg.type;
920  content.encryptionLevel = mockWrite_->getEncryptionLevel();
924  content.data = IOBuf::copyBuffer("writtenshlo");
925  return content;
926  }));
927  EXPECT_CALL(
928  *mockKeyScheduler_,
929  getSecret(
930  HandshakeSecrets::ServerHandshakeTraffic, RangeMatches("chlo_shlo")))
931  .WillOnce(InvokeWithoutArgs([]() {
932  return std::vector<uint8_t>({'s', 'h', 't'});
933  }));
934  EXPECT_CALL(
935  *mockKeyScheduler_,
936  getSecret(
937  HandshakeSecrets::ClientHandshakeTraffic, RangeMatches("chlo_shlo")))
938  .WillOnce(InvokeWithoutArgs([]() {
939  return std::vector<uint8_t>({'c', 'h', 't'});
940  }));
941  EXPECT_CALL(*mockKeyScheduler_, getTrafficKey(RangeMatches("sht"), _, _))
942  .WillOnce(InvokeWithoutArgs([]() {
943  return TrafficKey{IOBuf::copyBuffer("serverkey"),
944  IOBuf::copyBuffer("serveriv")};
945  }));
946  EXPECT_CALL(*mockKeyScheduler_, getTrafficKey(RangeMatches("cht"), _, _))
947  .WillOnce(InvokeWithoutArgs([]() {
948  return TrafficKey{IOBuf::copyBuffer("clientkey"),
949  IOBuf::copyBuffer("clientiv")};
950  }));
951  EXPECT_CALL(*extensions_, getExtensions(_)).WillOnce(InvokeWithoutArgs([]() {
952  Extension ext;
954  ext.extension_data = folly::IOBuf::copyBuffer("someextension");
955  std::vector<Extension> exts;
956  exts.push_back(std::move(ext));
957  return exts;
958  }));
959 
960  MockAead* raead;
961  MockAead* waead;
962  MockAead* appwaead;
966  expectAeadCreation({{"clientkey", &raead},
967  {"serverkey", &waead},
968  {"serverappkey", &appwaead}});
969  expectEncryptedReadRecordLayerCreation(
970  &rrl, &raead, StringPiece("cht"), false);
971  Sequence recSeq;
972  expectEncryptedWriteRecordLayerCreation(
973  &wrl,
974  &waead,
975  StringPiece("sht"),
976  [](TLSMessage& msg, auto writeRecord) {
978  auto modifiedEncryptedExt = TestMessages::encryptedExt();
979  Extension ext;
981  ext.extension_data = folly::IOBuf::copyBuffer("someextension");
982  modifiedEncryptedExt.extensions.push_back(std::move(ext));
984  msg.fragment,
985  getEncryptedHandshakeWrite(
986  std::move(modifiedEncryptedExt),
991  TLSContent content;
992  content.contentType = msg.type;
993  content.encryptionLevel = writeRecord->getEncryptionLevel();
994  content.data = folly::IOBuf::copyBuffer("handshake");
995  return content;
996  },
997  &recSeq);
998  expectEncryptedWriteRecordLayerCreation(
999  &appwrl, &appwaead, StringPiece("sat"), nullptr, &recSeq);
1000  EXPECT_CALL(*mockHandshakeContext_, appendToTranscript(_))
1001  .InSequence(contextSeq);
1002  EXPECT_CALL(*mockHandshakeContext_, appendToTranscript(_))
1003  .InSequence(contextSeq);
1004  EXPECT_CALL(*certManager_, getCert(_, _, _))
1005  .WillOnce(Invoke(
1006  [=](const folly::Optional<std::string>& sni,
1007  const std::vector<SignatureScheme>& /* supportedSigSchemes */,
1008  const std::vector<SignatureScheme>& peerSigSchemes) {
1009  EXPECT_EQ(*sni, "www.hostname.com");
1010  EXPECT_EQ(peerSigSchemes.size(), 2);
1011  EXPECT_EQ(
1012  peerSigSchemes[0], SignatureScheme::ecdsa_secp256r1_sha256);
1013  EXPECT_EQ(peerSigSchemes[1], SignatureScheme::rsa_pss_sha256);
1014  return CertManager::CertMatch(
1015  std::make_pair(cert_, SignatureScheme::ecdsa_secp256r1_sha256));
1016  }));
1017  EXPECT_CALL(*cert_, _getCertMessage(_));
1018  EXPECT_CALL(*mockHandshakeContext_, appendToTranscript(_))
1019  .InSequence(contextSeq);
1020  EXPECT_CALL(*mockHandshakeContext_, getHandshakeContext())
1021  .InSequence(contextSeq)
1022  .WillRepeatedly(
1023  Invoke([]() { return IOBuf::copyBuffer("chlo_shlo_ee_cert"); }));
1024  EXPECT_CALL(
1025  *cert_,
1026  sign(
1029  RangeMatches("chlo_shlo_ee_cert")))
1030  .WillOnce(
1031  InvokeWithoutArgs([]() { return IOBuf::copyBuffer("signature"); }));
1032  EXPECT_CALL(*mockHandshakeContext_, appendToTranscript(_))
1033  .InSequence(contextSeq);
1034  EXPECT_CALL(*mockHandshakeContext_, getFinishedData(RangeMatches("sht")))
1035  .InSequence(contextSeq)
1036  .WillRepeatedly(
1037  InvokeWithoutArgs([]() { return IOBuf::copyBuffer("verifydata"); }));
1038  EXPECT_CALL(*mockHandshakeContext_, appendToTranscript(_))
1039  .InSequence(contextSeq);
1040  EXPECT_CALL(*mockHandshakeContext_, getHandshakeContext())
1041  .InSequence(contextSeq)
1042  .WillRepeatedly(InvokeWithoutArgs(
1043  []() { return IOBuf::copyBuffer("chlo_shlo_ee_cert_sfin"); }));
1044  EXPECT_CALL(*mockKeyScheduler_, deriveMasterSecret());
1045  EXPECT_CALL(
1046  *mockKeyScheduler_,
1047  getSecret(
1049  RangeMatches("chlo_shlo_ee_cert_sfin")))
1050  .WillOnce(InvokeWithoutArgs([]() {
1051  return std::vector<uint8_t>({'e', 'x', 'p', 'm'});
1052  }));
1053  EXPECT_CALL(
1054  *mockKeyScheduler_,
1055  deriveAppTrafficSecrets(RangeMatches("chlo_shlo_ee_cert_sfin")));
1056  EXPECT_CALL(
1057  *mockKeyScheduler_, getSecret(AppTrafficSecrets::ServerAppTraffic))
1058  .WillOnce(InvokeWithoutArgs([]() {
1059  return std::vector<uint8_t>({'s', 'a', 't'});
1060  }));
1061  EXPECT_CALL(*mockKeyScheduler_, getTrafficKey(RangeMatches("sat"), _, _))
1062  .WillOnce(InvokeWithoutArgs([]() {
1063  return TrafficKey{IOBuf::copyBuffer("serverappkey"),
1064  IOBuf::copyBuffer("serverappiv")};
1065  }));
1066 
1067  auto actions =
1068  getActions(detail::processEvent(state_, TestMessages::clientHello()));
1069 
1070  expectActions<MutateState, WriteToSocket>(actions);
1071  auto write = expectAction<WriteToSocket>(actions);
1072  ASSERT_EQ(write.contents.size(), 2);
1073  EXPECT_EQ(write.contents[0].encryptionLevel, EncryptionLevel::Plaintext);
1074  EXPECT_EQ(write.contents[0].contentType, ContentType::handshake);
1075  EXPECT_TRUE(
1076  IOBufEqualTo()(write.contents[0].data, IOBuf::copyBuffer("writtenshlo")));
1077 
1078  EXPECT_EQ(write.contents[1].encryptionLevel, EncryptionLevel::Handshake);
1079  EXPECT_EQ(write.contents[1].contentType, ContentType::handshake);
1080  EXPECT_TRUE(
1081  IOBufEqualTo()(write.contents[1].data, IOBuf::copyBuffer("handshake")));
1082  processStateMutations(actions);
1083  EXPECT_EQ(state_.state(), StateEnum::ExpectingCertificate);
1084  EXPECT_EQ(state_.readRecordLayer().get(), rrl);
1085  EXPECT_EQ(state_.writeRecordLayer().get(), appwrl);
1086  EXPECT_EQ(state_.handshakeContext().get(), mockHandshakeContext_);
1087  EXPECT_EQ(state_.keyScheduler().get(), mockKeyScheduler_);
1088  EXPECT_EQ(state_.serverCert(), cert_);
1089  EXPECT_EQ(state_.version(), TestProtocolVersion);
1091  EXPECT_EQ(state_.group(), NamedGroup::x25519);
1093  EXPECT_EQ(state_.pskType(), PskType::NotAttempted);
1094  EXPECT_FALSE(state_.pskMode().hasValue());
1095  EXPECT_EQ(state_.keyExchangeType(), KeyExchangeType::OneRtt);
1096  EXPECT_EQ(state_.earlyDataType(), EarlyDataType::NotAttempted);
1097  EXPECT_EQ(state_.replayCacheResult(), ReplayCacheResult::NotChecked);
1098  EXPECT_FALSE(state_.clientClockSkew().hasValue());
1099  EXPECT_EQ(*state_.alpn(), "h2");
1101  *state_.clientHandshakeSecret(), IOBuf::copyBuffer("cht")));
1103  *state_.exporterMasterSecret(), IOBuf::copyBuffer("expm")));
1104  EXPECT_FALSE(state_.earlyExporterMasterSecret().hasValue());
1105 }
1106 
1107 TEST_F(ServerProtocolTest, TestClientHelloPskFlow) {
1108  context_->setSupportedPskModes({PskKeyExchangeMode::psk_ke});
1109  setUpExpectingClientHello();
1110  EXPECT_CALL(*mockTicketCipher_, _decrypt(_))
1111  .WillOnce(InvokeWithoutArgs([=]() {
1112  ResumptionState res;
1115  res.resumptionSecret = folly::IOBuf::copyBuffer("resumesecret");
1116  res.serverCert = cert_;
1117  return std::make_pair(PskType::Resumption, std::move(res));
1118  }));
1119  Sequence contextSeq;
1120  mockKeyScheduler_ = new MockKeyScheduler();
1121  mockHandshakeContext_ = new MockHandshakeContext();
1122  EXPECT_CALL(*factory_, makeKeyScheduler(CipherSuite::TLS_AES_128_GCM_SHA256))
1123  .WillOnce(InvokeWithoutArgs(
1124  [=]() { return std::unique_ptr<KeyScheduler>(mockKeyScheduler_); }));
1125  EXPECT_CALL(
1126  *factory_, makeHandshakeContext(CipherSuite::TLS_AES_128_GCM_SHA256))
1127  .WillOnce(InvokeWithoutArgs([=]() {
1128  return std::unique_ptr<HandshakeContext>(mockHandshakeContext_);
1129  }));
1130  EXPECT_CALL(
1131  *mockKeyScheduler_, deriveEarlySecret(RangeMatches("resumesecret")));
1132  EXPECT_CALL(*mockHandshakeContext_, appendToTranscript(BufMatches("client")))
1133  .InSequence(contextSeq);
1134  EXPECT_CALL(*mockHandshakeContext_, getFinishedData(RangeMatches("bdr")))
1135  .InSequence(contextSeq)
1136  .WillRepeatedly(
1137  InvokeWithoutArgs([]() { return IOBuf::copyBuffer("verifydata"); }));
1138  EXPECT_CALL(
1139  *mockHandshakeContext_, appendToTranscript(BufMatches("helloencoding")))
1140  .InSequence(contextSeq);
1141  EXPECT_CALL(
1142  *mockKeyScheduler_,
1143  getSecret(EarlySecrets::ResumptionPskBinder, RangeMatches("")))
1144  .WillOnce(InvokeWithoutArgs([]() {
1145  return std::vector<uint8_t>({'b', 'd', 'r'});
1146  }));
1147  EXPECT_CALL(*mockHandshakeContext_, appendToTranscript(_))
1148  .InSequence(contextSeq);
1149  EXPECT_CALL(*mockHandshakeContext_, getHandshakeContext())
1150  .InSequence(contextSeq)
1151  .WillRepeatedly(Invoke([]() { return IOBuf::copyBuffer("chlo_shlo"); }));
1152  EXPECT_CALL(*mockKeyScheduler_, deriveHandshakeSecret());
1153  EXPECT_CALL(*factory_, makeRandom()).WillOnce(Invoke([]() {
1154  Random random;
1155  random.fill(0x44);
1156  return random;
1157  }));
1158  EXPECT_CALL(*mockWrite_, _write(_)).WillOnce(Invoke([&](TLSMessage& msg) {
1159  TLSContent content;
1160  content.contentType = msg.type;
1161  content.encryptionLevel = mockWrite_->getEncryptionLevel();
1163  auto shlo = TestMessages::serverHello();
1165  ServerPresharedKey serverPsk;
1166  serverPsk.selected_identity = 0;
1167  shlo.extensions.push_back(encodeExtension(std::move(serverPsk)));
1169  content.data = IOBuf::copyBuffer("writtenshlo");
1170  return content;
1171  }));
1172  EXPECT_CALL(
1173  *mockKeyScheduler_,
1174  getSecret(
1175  HandshakeSecrets::ServerHandshakeTraffic, RangeMatches("chlo_shlo")))
1176  .WillOnce(InvokeWithoutArgs([]() {
1177  return std::vector<uint8_t>({'s', 'h', 't'});
1178  }));
1179  EXPECT_CALL(
1180  *mockKeyScheduler_,
1181  getSecret(
1182  HandshakeSecrets::ClientHandshakeTraffic, RangeMatches("chlo_shlo")))
1183  .WillOnce(InvokeWithoutArgs([]() {
1184  return std::vector<uint8_t>({'c', 'h', 't'});
1185  }));
1186  EXPECT_CALL(*mockKeyScheduler_, getTrafficKey(RangeMatches("sht"), _, _))
1187  .WillOnce(InvokeWithoutArgs([]() {
1188  return TrafficKey{IOBuf::copyBuffer("serverkey"),
1189  IOBuf::copyBuffer("serveriv")};
1190  }));
1191  EXPECT_CALL(*mockKeyScheduler_, getTrafficKey(RangeMatches("cht"), _, _))
1192  .WillOnce(InvokeWithoutArgs([]() {
1193  return TrafficKey{IOBuf::copyBuffer("clientkey"),
1194  IOBuf::copyBuffer("clientiv")};
1195  }));
1196  MockAead* raead;
1197  MockAead* waead;
1198  MockAead* appwaead;
1202  expectAeadCreation({{"clientkey", &raead},
1203  {"serverkey", &waead},
1204  {"serverappkey", &appwaead}});
1205  expectEncryptedReadRecordLayerCreation(
1206  &rrl, &raead, StringPiece("cht"), false);
1207  Sequence recSeq;
1208  expectEncryptedWriteRecordLayerCreation(
1209  &wrl,
1210  &waead,
1211  StringPiece("sht"),
1212  [](TLSMessage& msg, auto writeRecord) {
1215  msg.fragment,
1216  getEncryptedHandshakeWrite(
1218  TLSContent content;
1219  content.contentType = msg.type;
1220  content.encryptionLevel = writeRecord->getEncryptionLevel();
1221  content.data = folly::IOBuf::copyBuffer("handshake");
1222  return content;
1223  },
1224  &recSeq);
1225  expectEncryptedWriteRecordLayerCreation(
1226  &appwrl, &appwaead, StringPiece("sat"), nullptr, &recSeq);
1227  EXPECT_CALL(*mockHandshakeContext_, appendToTranscript(_))
1228  .InSequence(contextSeq);
1229  EXPECT_CALL(*mockHandshakeContext_, getFinishedData(RangeMatches("sht")))
1230  .InSequence(contextSeq)
1231  .WillRepeatedly(
1232  InvokeWithoutArgs([]() { return IOBuf::copyBuffer("verifydata"); }));
1233  EXPECT_CALL(*mockHandshakeContext_, appendToTranscript(_))
1234  .InSequence(contextSeq);
1235  EXPECT_CALL(*mockHandshakeContext_, getHandshakeContext())
1236  .InSequence(contextSeq)
1237  .WillRepeatedly(InvokeWithoutArgs(
1238  []() { return IOBuf::copyBuffer("chlo_shlo_sfin"); }));
1239  EXPECT_CALL(*mockKeyScheduler_, deriveMasterSecret());
1240  EXPECT_CALL(
1241  *mockKeyScheduler_,
1242  getSecret(MasterSecrets::ExporterMaster, RangeMatches("chlo_shlo_sfin")))
1243  .WillOnce(InvokeWithoutArgs([]() {
1244  return std::vector<uint8_t>({'e', 'x', 'p', 'm'});
1245  }));
1246  EXPECT_CALL(
1247  *mockKeyScheduler_,
1248  deriveAppTrafficSecrets(RangeMatches("chlo_shlo_sfin")));
1249  EXPECT_CALL(
1250  *mockKeyScheduler_, getSecret(AppTrafficSecrets::ServerAppTraffic))
1251  .WillOnce(InvokeWithoutArgs([]() {
1252  return std::vector<uint8_t>({'s', 'a', 't'});
1253  }));
1254  EXPECT_CALL(*mockKeyScheduler_, getTrafficKey(RangeMatches("sat"), _, _))
1255  .WillOnce(InvokeWithoutArgs([]() {
1256  return TrafficKey{IOBuf::copyBuffer("serverappkey"),
1257  IOBuf::copyBuffer("serverappiv")};
1258  }));
1259 
1260  auto actions =
1261  getActions(detail::processEvent(state_, TestMessages::clientHelloPsk()));
1262 
1263  expectActions<MutateState, WriteToSocket>(actions);
1264  auto write = expectAction<WriteToSocket>(actions);
1265  ASSERT_EQ(write.contents.size(), 2);
1266  EXPECT_EQ(write.contents[0].encryptionLevel, EncryptionLevel::Plaintext);
1267  EXPECT_EQ(write.contents[0].contentType, ContentType::handshake);
1268  EXPECT_TRUE(
1269  IOBufEqualTo()(write.contents[0].data, IOBuf::copyBuffer("writtenshlo")));
1270  EXPECT_EQ(write.contents[1].encryptionLevel, EncryptionLevel::Handshake);
1271  EXPECT_EQ(write.contents[1].contentType, ContentType::handshake);
1272  EXPECT_TRUE(
1273  IOBufEqualTo()(write.contents[1].data, IOBuf::copyBuffer("handshake")));
1274  processStateMutations(actions);
1275  EXPECT_EQ(state_.state(), StateEnum::ExpectingFinished);
1276  EXPECT_EQ(state_.readRecordLayer().get(), rrl);
1277  EXPECT_EQ(
1278  state_.readRecordLayer()->getEncryptionLevel(),
1280  EXPECT_EQ(state_.writeRecordLayer().get(), appwrl);
1281  EXPECT_EQ(
1282  state_.writeRecordLayer()->getEncryptionLevel(),
1284  EXPECT_EQ(state_.handshakeContext().get(), mockHandshakeContext_);
1285  EXPECT_EQ(state_.keyScheduler().get(), mockKeyScheduler_);
1286  EXPECT_EQ(state_.serverCert(), cert_);
1287  EXPECT_EQ(state_.version(), TestProtocolVersion);
1289  EXPECT_FALSE(state_.group().hasValue());
1290  EXPECT_FALSE(state_.sigScheme().hasValue());
1291  EXPECT_EQ(state_.pskType(), PskType::Resumption);
1292  EXPECT_EQ(state_.pskMode(), PskKeyExchangeMode::psk_ke);
1293  EXPECT_EQ(state_.keyExchangeType(), KeyExchangeType::None);
1294  EXPECT_EQ(state_.earlyDataType(), EarlyDataType::NotAttempted);
1295  EXPECT_EQ(state_.replayCacheResult(), ReplayCacheResult::NotChecked);
1296  EXPECT_TRUE(state_.clientClockSkew().hasValue());
1297  EXPECT_EQ(*state_.alpn(), "h2");
1299  *state_.clientHandshakeSecret(), IOBuf::copyBuffer("cht")));
1301  *state_.exporterMasterSecret(), IOBuf::copyBuffer("expm")));
1302  EXPECT_FALSE(state_.earlyExporterMasterSecret().hasValue());
1303 }
1304 
1305 TEST_F(ServerProtocolTest, TestClientHelloPskDheFlow) {
1306  context_->setSupportedPskModes({PskKeyExchangeMode::psk_dhe_ke});
1307  setUpExpectingClientHello();
1308  EXPECT_CALL(*mockTicketCipher_, _decrypt(_))
1309  .WillOnce(InvokeWithoutArgs([=]() {
1310  ResumptionState res;
1313  res.resumptionSecret = folly::IOBuf::copyBuffer("resumesecret");
1314  res.serverCert = cert_;
1315  return std::make_pair(PskType::Resumption, std::move(res));
1316  }));
1317  Sequence contextSeq;
1318  mockKeyScheduler_ = new MockKeyScheduler();
1319  mockHandshakeContext_ = new MockHandshakeContext();
1320  EXPECT_CALL(*factory_, makeKeyScheduler(CipherSuite::TLS_AES_128_GCM_SHA256))
1321  .WillOnce(InvokeWithoutArgs(
1322  [=]() { return std::unique_ptr<KeyScheduler>(mockKeyScheduler_); }));
1323  EXPECT_CALL(
1324  *factory_, makeHandshakeContext(CipherSuite::TLS_AES_128_GCM_SHA256))
1325  .WillOnce(InvokeWithoutArgs([=]() {
1326  return std::unique_ptr<HandshakeContext>(mockHandshakeContext_);
1327  }));
1328  EXPECT_CALL(
1329  *mockKeyScheduler_, deriveEarlySecret(RangeMatches("resumesecret")));
1330  EXPECT_CALL(*mockHandshakeContext_, appendToTranscript(BufMatches("client")))
1331  .InSequence(contextSeq);
1332  EXPECT_CALL(*mockHandshakeContext_, getFinishedData(RangeMatches("bdr")))
1333  .InSequence(contextSeq)
1334  .WillRepeatedly(
1335  InvokeWithoutArgs([]() { return IOBuf::copyBuffer("verifydata"); }));
1336  EXPECT_CALL(
1337  *mockHandshakeContext_, appendToTranscript(BufMatches("helloencoding")))
1338  .InSequence(contextSeq);
1339  EXPECT_CALL(
1340  *mockKeyScheduler_,
1341  getSecret(EarlySecrets::ResumptionPskBinder, RangeMatches("")))
1342  .WillOnce(InvokeWithoutArgs([]() {
1343  return std::vector<uint8_t>({'b', 'd', 'r'});
1344  }));
1345  EXPECT_CALL(*factory_, makeKeyExchange(NamedGroup::x25519))
1346  .WillOnce(InvokeWithoutArgs([]() {
1347  auto ret = std::make_unique<MockKeyExchange>();
1348  EXPECT_CALL(*ret, generateKeyPair());
1349  EXPECT_CALL(*ret, generateSharedSecret(RangeMatches("keyshare")))
1350  .WillOnce(InvokeWithoutArgs(
1351  []() { return IOBuf::copyBuffer("sharedsecret"); }));
1352  EXPECT_CALL(*ret, getKeyShare()).WillOnce(InvokeWithoutArgs([]() {
1353  return IOBuf::copyBuffer("servershare");
1354  }));
1355  return ret;
1356  }));
1357  EXPECT_CALL(*mockHandshakeContext_, appendToTranscript(_))
1358  .InSequence(contextSeq);
1359  EXPECT_CALL(*mockHandshakeContext_, getHandshakeContext())
1360  .InSequence(contextSeq)
1361  .WillRepeatedly(Invoke([]() { return IOBuf::copyBuffer("chlo_shlo"); }));
1362  EXPECT_CALL(
1363  *mockKeyScheduler_, deriveHandshakeSecret(RangeMatches("sharedsecret")));
1364  EXPECT_CALL(*factory_, makeRandom()).WillOnce(Invoke([]() {
1365  Random random;
1366  random.fill(0x44);
1367  return random;
1368  }));
1369  EXPECT_CALL(*mockWrite_, _write(_)).WillOnce(Invoke([&](TLSMessage& msg) {
1371  auto shlo = TestMessages::serverHello();
1372  ServerPresharedKey serverPsk;
1373  serverPsk.selected_identity = 0;
1374  shlo.extensions.push_back(encodeExtension(std::move(serverPsk)));
1376  TLSContent content;
1377  content.contentType = msg.type;
1378  content.encryptionLevel = mockWrite_->getEncryptionLevel();
1379  content.data = IOBuf::copyBuffer("writtenshlo");
1380  return content;
1381  }));
1382  EXPECT_CALL(
1383  *mockKeyScheduler_,
1384  getSecret(
1385  HandshakeSecrets::ServerHandshakeTraffic, RangeMatches("chlo_shlo")))
1386  .WillOnce(InvokeWithoutArgs([]() {
1387  return std::vector<uint8_t>({'s', 'h', 't'});
1388  }));
1389  EXPECT_CALL(
1390  *mockKeyScheduler_,
1391  getSecret(
1392  HandshakeSecrets::ClientHandshakeTraffic, RangeMatches("chlo_shlo")))
1393  .WillOnce(InvokeWithoutArgs([]() {
1394  return std::vector<uint8_t>({'c', 'h', 't'});
1395  }));
1396  EXPECT_CALL(*mockKeyScheduler_, getTrafficKey(RangeMatches("sht"), _, _))
1397  .WillOnce(InvokeWithoutArgs([]() {
1398  return TrafficKey{IOBuf::copyBuffer("serverkey"),
1399  IOBuf::copyBuffer("serveriv")};
1400  }));
1401  EXPECT_CALL(*mockKeyScheduler_, getTrafficKey(RangeMatches("cht"), _, _))
1402  .WillOnce(InvokeWithoutArgs([]() {
1403  return TrafficKey{IOBuf::copyBuffer("clientkey"),
1404  IOBuf::copyBuffer("clientiv")};
1405  }));
1406  MockAead* raead;
1407  MockAead* waead;
1408  MockAead* appwaead;
1412  expectAeadCreation({{"clientkey", &raead},
1413  {"serverkey", &waead},
1414  {"serverappkey", &appwaead}});
1415  expectEncryptedReadRecordLayerCreation(
1416  &rrl, &raead, StringPiece("cht"), false);
1417  Sequence recSeq;
1418  expectEncryptedWriteRecordLayerCreation(
1419  &wrl,
1420  &waead,
1421  StringPiece("sht"),
1422  [](TLSMessage& msg, auto writeRecord) {
1425  msg.fragment,
1426  getEncryptedHandshakeWrite(
1428  TLSContent content;
1429  content.contentType = msg.type;
1430  content.encryptionLevel = writeRecord->getEncryptionLevel();
1431  content.data = folly::IOBuf::copyBuffer("handshake");
1432  return content;
1433  },
1434  &recSeq);
1435  expectEncryptedWriteRecordLayerCreation(
1436  &appwrl, &appwaead, StringPiece("sat"), nullptr, &recSeq);
1437  EXPECT_CALL(*mockHandshakeContext_, appendToTranscript(_))
1438  .InSequence(contextSeq);
1439  EXPECT_CALL(*mockHandshakeContext_, getFinishedData(RangeMatches("sht")))
1440  .InSequence(contextSeq)
1441  .WillRepeatedly(
1442  InvokeWithoutArgs([]() { return IOBuf::copyBuffer("verifydata"); }));
1443  EXPECT_CALL(*mockHandshakeContext_, appendToTranscript(_))
1444  .InSequence(contextSeq);
1445  EXPECT_CALL(*mockHandshakeContext_, getHandshakeContext())
1446  .InSequence(contextSeq)
1447  .WillRepeatedly(InvokeWithoutArgs(
1448  []() { return IOBuf::copyBuffer("chlo_shlo_sfin"); }));
1449  EXPECT_CALL(*mockKeyScheduler_, deriveMasterSecret());
1450  EXPECT_CALL(
1451  *mockKeyScheduler_,
1452  getSecret(MasterSecrets::ExporterMaster, RangeMatches("chlo_shlo_sfin")))
1453  .WillOnce(InvokeWithoutArgs([]() {
1454  return std::vector<uint8_t>({'e', 'x', 'p', 'm'});
1455  }));
1456  EXPECT_CALL(
1457  *mockKeyScheduler_,
1458  deriveAppTrafficSecrets(RangeMatches("chlo_shlo_sfin")));
1459  EXPECT_CALL(
1460  *mockKeyScheduler_, getSecret(AppTrafficSecrets::ServerAppTraffic))
1461  .WillOnce(InvokeWithoutArgs([]() {
1462  return std::vector<uint8_t>({'s', 'a', 't'});
1463  }));
1464  EXPECT_CALL(*mockKeyScheduler_, getTrafficKey(RangeMatches("sat"), _, _))
1465  .WillOnce(InvokeWithoutArgs([]() {
1466  return TrafficKey{IOBuf::copyBuffer("serverappkey"),
1467  IOBuf::copyBuffer("serverappiv")};
1468  }));
1469 
1470  auto actions =
1471  getActions(detail::processEvent(state_, TestMessages::clientHelloPsk()));
1472 
1473  expectActions<MutateState, WriteToSocket>(actions);
1474  auto write = expectAction<WriteToSocket>(actions);
1475  ASSERT_EQ(write.contents.size(), 2);
1476  EXPECT_EQ(write.contents[0].encryptionLevel, EncryptionLevel::Plaintext);
1477  EXPECT_EQ(write.contents[0].contentType, ContentType::handshake);
1478  EXPECT_TRUE(
1479  IOBufEqualTo()(write.contents[0].data, IOBuf::copyBuffer("writtenshlo")));
1480 
1481  EXPECT_EQ(write.contents[1].encryptionLevel, EncryptionLevel::Handshake);
1482  EXPECT_EQ(write.contents[1].contentType, ContentType::handshake);
1483  EXPECT_TRUE(
1484  IOBufEqualTo()(write.contents[1].data, IOBuf::copyBuffer("handshake")));
1485  processStateMutations(actions);
1486  EXPECT_EQ(state_.state(), StateEnum::ExpectingFinished);
1487  EXPECT_EQ(state_.readRecordLayer().get(), rrl);
1488  EXPECT_EQ(
1489  state_.readRecordLayer()->getEncryptionLevel(),
1491  EXPECT_EQ(state_.writeRecordLayer().get(), appwrl);
1492  EXPECT_EQ(
1493  state_.writeRecordLayer()->getEncryptionLevel(),
1495  EXPECT_EQ(state_.handshakeContext().get(), mockHandshakeContext_);
1496  EXPECT_EQ(state_.keyScheduler().get(), mockKeyScheduler_);
1497  EXPECT_EQ(state_.serverCert(), cert_);
1499  EXPECT_EQ(state_.group(), NamedGroup::x25519);
1500  EXPECT_FALSE(state_.sigScheme().hasValue());
1501  EXPECT_EQ(state_.pskType(), PskType::Resumption);
1502  EXPECT_EQ(state_.pskMode(), PskKeyExchangeMode::psk_dhe_ke);
1503  EXPECT_EQ(state_.keyExchangeType(), KeyExchangeType::OneRtt);
1504  EXPECT_EQ(state_.earlyDataType(), EarlyDataType::NotAttempted);
1505  EXPECT_EQ(state_.replayCacheResult(), ReplayCacheResult::NotChecked);
1506  EXPECT_TRUE(state_.clientClockSkew().hasValue());
1507  EXPECT_EQ(*state_.alpn(), "h2");
1509  *state_.clientHandshakeSecret(), IOBuf::copyBuffer("cht")));
1511  *state_.exporterMasterSecret(), IOBuf::copyBuffer("expm")));
1512  EXPECT_FALSE(state_.earlyExporterMasterSecret().hasValue());
1513 }
1514 
1515 TEST_F(ServerProtocolTest, TestClientHelloHelloRetryRequestFlow) {
1516  setUpExpectingClientHello();
1517  auto firstHandshakeContext = new MockHandshakeContext();
1518  Sequence firstContextSeq;
1519  Sequence factorySeq;
1520  EXPECT_CALL(
1521  *factory_, makeHandshakeContext(CipherSuite::TLS_AES_128_GCM_SHA256))
1522  .InSequence(factorySeq)
1523  .WillOnce(InvokeWithoutArgs([=]() {
1524  return std::unique_ptr<HandshakeContext>(firstHandshakeContext);
1525  }));
1526  EXPECT_CALL(
1527  *firstHandshakeContext,
1528  appendToTranscript(BufMatches("clienthelloencoding")))
1529  .InSequence(firstContextSeq);
1530  EXPECT_CALL(*firstHandshakeContext, getHandshakeContext())
1531  .InSequence(firstContextSeq)
1532  .WillRepeatedly(Invoke([]() { return IOBuf::copyBuffer("chlo_hash"); }));
1533  auto secondHandshakeContext = new MockHandshakeContext();
1534  EXPECT_CALL(
1535  *factory_, makeHandshakeContext(CipherSuite::TLS_AES_128_GCM_SHA256))
1536  .InSequence(factorySeq)
1537  .WillOnce(InvokeWithoutArgs([=]() {
1538  return std::unique_ptr<HandshakeContext>(secondHandshakeContext);
1539  }));
1540  EXPECT_CALL(*secondHandshakeContext, appendToTranscript(_)).Times(2);
1541  EXPECT_CALL(*mockWrite_, _write(_)).WillOnce(Invoke([&](TLSMessage& msg) {
1542  TLSContent content;
1543  content.contentType = msg.type;
1544  content.encryptionLevel = mockWrite_->getEncryptionLevel();
1548  content.data = IOBuf::copyBuffer("writtenhrr");
1549  return content;
1550  }));
1551  auto newRrl = new MockPlaintextReadRecordLayer();
1552  EXPECT_CALL(*factory_, makePlaintextReadRecordLayer())
1553  .WillOnce(Invoke([newRrl]() {
1554  return std::unique_ptr<PlaintextReadRecordLayer>(newRrl);
1555  }));
1556  EXPECT_CALL(*newRrl, setSkipEncryptedRecords(false));
1557 
1558  context_->setSupportedGroups({NamedGroup::secp256r1, NamedGroup::x25519});
1559  auto actions =
1560  getActions(detail::processEvent(state_, TestMessages::clientHello()));
1561 
1562  expectActions<MutateState, WriteToSocket>(actions);
1563  auto write = expectAction<WriteToSocket>(actions);
1564  ASSERT_EQ(write.contents.size(), 1);
1565  EXPECT_EQ(write.contents[0].encryptionLevel, EncryptionLevel::Plaintext);
1566  EXPECT_EQ(write.contents[0].contentType, ContentType::handshake);
1567  EXPECT_TRUE(
1568  IOBufEqualTo()(write.contents[0].data, IOBuf::copyBuffer("writtenhrr")));
1569  processStateMutations(actions);
1570  EXPECT_EQ(state_.state(), StateEnum::ExpectingClientHello);
1571  EXPECT_EQ(state_.readRecordLayer().get(), newRrl);
1572  EXPECT_EQ(
1573  state_.readRecordLayer()->getEncryptionLevel(),
1575  EXPECT_EQ(state_.writeRecordLayer().get(), mockWrite_);
1576  EXPECT_EQ(
1577  state_.writeRecordLayer()->getEncryptionLevel(),
1579  EXPECT_EQ(state_.handshakeContext().get(), secondHandshakeContext);
1580  EXPECT_EQ(state_.version(), TestProtocolVersion);
1582  EXPECT_EQ(state_.group(), NamedGroup::secp256r1);
1583  EXPECT_EQ(state_.keyExchangeType(), KeyExchangeType::HelloRetryRequest);
1584  EXPECT_EQ(state_.earlyDataType(), EarlyDataType::NotAttempted);
1585  EXPECT_EQ(state_.replayCacheResult(), ReplayCacheResult::NotChecked);
1586  EXPECT_FALSE(state_.earlyExporterMasterSecret().hasValue());
1587 }
1588 
1589 TEST_F(ServerProtocolTest, TestRetryClientHelloFullHandshakeFlow) {
1590  setUpExpectingClientHelloRetry();
1591  Sequence contextSeq;
1592  mockKeyScheduler_ = new MockKeyScheduler();
1593  EXPECT_CALL(*factory_, makeKeyScheduler(CipherSuite::TLS_AES_128_GCM_SHA256))
1594  .WillOnce(InvokeWithoutArgs(
1595  [=]() { return std::unique_ptr<KeyScheduler>(mockKeyScheduler_); }));
1596  EXPECT_CALL(
1597  *mockHandshakeContext_,
1598  appendToTranscript(BufMatches("clienthelloencoding")))
1599  .InSequence(contextSeq);
1600  EXPECT_CALL(*factory_, makeKeyExchange(NamedGroup::x25519))
1601  .WillOnce(InvokeWithoutArgs([]() {
1602  auto ret = std::make_unique<MockKeyExchange>();
1603  EXPECT_CALL(*ret, generateKeyPair());
1604  EXPECT_CALL(*ret, generateSharedSecret(RangeMatches("keyshare")))
1605  .WillOnce(InvokeWithoutArgs(
1606  []() { return IOBuf::copyBuffer("sharedsecret"); }));
1607  EXPECT_CALL(*ret, getKeyShare()).WillOnce(InvokeWithoutArgs([]() {
1608  return IOBuf::copyBuffer("servershare");
1609  }));
1610  return ret;
1611  }));
1612  EXPECT_CALL(*mockHandshakeContext_, appendToTranscript(_))
1613  .InSequence(contextSeq);
1614  EXPECT_CALL(*mockHandshakeContext_, getHandshakeContext())
1615  .InSequence(contextSeq)
1616  .WillRepeatedly(Invoke([]() { return IOBuf::copyBuffer("chlo_shlo"); }));
1617  EXPECT_CALL(
1618  *mockKeyScheduler_, deriveHandshakeSecret(RangeMatches("sharedsecret")));
1619  EXPECT_CALL(*factory_, makeRandom()).WillOnce(Invoke([]() {
1620  Random random;
1621  random.fill(0x44);
1622  return random;
1623  }));
1624  EXPECT_CALL(*mockWrite_, _write(_)).WillOnce(Invoke([&](TLSMessage& msg) {
1625  TLSContent content;
1626  content.contentType = msg.type;
1627  content.encryptionLevel = mockWrite_->getEncryptionLevel();
1631  content.data = IOBuf::copyBuffer("writtenshlo");
1632  return content;
1633  }));
1634  EXPECT_CALL(
1635  *mockKeyScheduler_,
1636  getSecret(
1637  HandshakeSecrets::ServerHandshakeTraffic, RangeMatches("chlo_shlo")))
1638  .WillOnce(InvokeWithoutArgs([]() {
1639  return std::vector<uint8_t>({'s', 'h', 't'});
1640  }));
1641  EXPECT_CALL(
1642  *mockKeyScheduler_,
1643  getSecret(
1644  HandshakeSecrets::ClientHandshakeTraffic, RangeMatches("chlo_shlo")))
1645  .WillOnce(InvokeWithoutArgs([]() {
1646  return std::vector<uint8_t>({'c', 'h', 't'});
1647  }));
1648  EXPECT_CALL(*mockKeyScheduler_, getTrafficKey(RangeMatches("sht"), _, _))
1649  .WillOnce(InvokeWithoutArgs([]() {
1650  return TrafficKey{IOBuf::copyBuffer("serverkey"),
1651  IOBuf::copyBuffer("serveriv")};
1652  }));
1653  EXPECT_CALL(*mockKeyScheduler_, getTrafficKey(RangeMatches("cht"), _, _))
1654  .WillOnce(InvokeWithoutArgs([]() {
1655  return TrafficKey{IOBuf::copyBuffer("clientkey"),
1656  IOBuf::copyBuffer("clientiv")};
1657  }));
1658  MockAead* raead;
1659  MockAead* waead;
1660  MockAead* appwaead;
1664  expectAeadCreation({{"clientkey", &raead},
1665  {"serverkey", &waead},
1666  {"serverappkey", &appwaead}});
1667  expectEncryptedReadRecordLayerCreation(
1668  &rrl, &raead, StringPiece("cht"), false);
1669  Sequence recSeq;
1670  expectEncryptedWriteRecordLayerCreation(
1671  &wrl,
1672  &waead,
1673  StringPiece("sht"),
1674  [](TLSMessage& msg, auto writeRecord) {
1677  msg.fragment,
1678  getEncryptedHandshakeWrite(
1683  TLSContent content;
1684  content.contentType = msg.type;
1685  content.encryptionLevel = writeRecord->getEncryptionLevel();
1686  content.data = folly::IOBuf::copyBuffer("handshake");
1687  return content;
1688  },
1689  &recSeq);
1690  expectEncryptedWriteRecordLayerCreation(
1691  &appwrl, &appwaead, StringPiece("sat"), nullptr, &recSeq);
1692  EXPECT_CALL(*mockHandshakeContext_, appendToTranscript(_))
1693  .InSequence(contextSeq);
1694  EXPECT_CALL(*certManager_, getCert(_, _, _))
1695  .WillOnce(Invoke(
1696  [=](const folly::Optional<std::string>& sni,
1697  const std::vector<SignatureScheme>& /* supportedSigSchemes */,
1698  const std::vector<SignatureScheme>& peerSigSchemes) {
1699  EXPECT_EQ(*sni, "www.hostname.com");
1700  EXPECT_EQ(peerSigSchemes.size(), 2);
1701  EXPECT_EQ(
1702  peerSigSchemes[0], SignatureScheme::ecdsa_secp256r1_sha256);
1703  EXPECT_EQ(peerSigSchemes[1], SignatureScheme::rsa_pss_sha256);
1704  return CertManager::CertMatch(
1705  std::make_pair(cert_, SignatureScheme::ecdsa_secp256r1_sha256));
1706  }));
1707  EXPECT_CALL(*cert_, _getCertMessage(_));
1708  EXPECT_CALL(*mockHandshakeContext_, appendToTranscript(_))
1709  .InSequence(contextSeq);
1710  EXPECT_CALL(*mockHandshakeContext_, getHandshakeContext())
1711  .InSequence(contextSeq)
1712  .WillRepeatedly(
1713  Invoke([]() { return IOBuf::copyBuffer("chlo_shlo_ee_cert"); }));
1714  EXPECT_CALL(
1715  *cert_,
1716  sign(
1719  RangeMatches("chlo_shlo_ee_cert")))
1720  .WillOnce(
1721  InvokeWithoutArgs([]() { return IOBuf::copyBuffer("signature"); }));
1722  EXPECT_CALL(*mockHandshakeContext_, appendToTranscript(_))
1723  .InSequence(contextSeq);
1724  EXPECT_CALL(*mockHandshakeContext_, getFinishedData(RangeMatches("sht")))
1725  .InSequence(contextSeq)
1726  .WillRepeatedly(
1727  InvokeWithoutArgs([]() { return IOBuf::copyBuffer("verifydata"); }));
1728  EXPECT_CALL(*mockHandshakeContext_, appendToTranscript(_))
1729  .InSequence(contextSeq);
1730  EXPECT_CALL(*mockHandshakeContext_, getHandshakeContext())
1731  .InSequence(contextSeq)
1732  .WillRepeatedly(InvokeWithoutArgs(
1733  []() { return IOBuf::copyBuffer("chlo_shlo_ee_cert_sfin"); }));
1734  EXPECT_CALL(*mockKeyScheduler_, deriveMasterSecret());
1735  EXPECT_CALL(
1736  *mockKeyScheduler_,
1737  getSecret(
1739  RangeMatches("chlo_shlo_ee_cert_sfin")))
1740  .WillOnce(InvokeWithoutArgs([]() {
1741  return std::vector<uint8_t>({'e', 'x', 'p', 'm'});
1742  }));
1743  EXPECT_CALL(
1744  *mockKeyScheduler_,
1745  deriveAppTrafficSecrets(RangeMatches("chlo_shlo_ee_cert_sfin")));
1746  EXPECT_CALL(
1747  *mockKeyScheduler_, getSecret(AppTrafficSecrets::ServerAppTraffic))
1748  .WillOnce(InvokeWithoutArgs([]() {
1749  return std::vector<uint8_t>({'s', 'a', 't'});
1750  }));
1751  EXPECT_CALL(*mockKeyScheduler_, getTrafficKey(RangeMatches("sat"), _, _))
1752  .WillOnce(InvokeWithoutArgs([]() {
1753  return TrafficKey{IOBuf::copyBuffer("serverappkey"),
1754  IOBuf::copyBuffer("serverappiv")};
1755  }));
1756 
1757  auto actions =
1758  getActions(detail::processEvent(state_, TestMessages::clientHello()));
1759 
1760  expectActions<MutateState, WriteToSocket>(actions);
1761  auto write = expectAction<WriteToSocket>(actions);
1762  ASSERT_EQ(write.contents.size(), 2);
1763  EXPECT_EQ(write.contents[0].encryptionLevel, EncryptionLevel::Plaintext);
1764  EXPECT_EQ(write.contents[0].contentType, ContentType::handshake);
1765  EXPECT_TRUE(
1766  IOBufEqualTo()(write.contents[0].data, IOBuf::copyBuffer("writtenshlo")));
1767 
1768  EXPECT_EQ(write.contents[1].encryptionLevel, EncryptionLevel::Handshake);
1769  EXPECT_EQ(write.contents[1].contentType, ContentType::handshake);
1770  EXPECT_TRUE(
1771  IOBufEqualTo()(write.contents[1].data, IOBuf::copyBuffer("handshake")));
1772  processStateMutations(actions);
1773  EXPECT_EQ(state_.state(), StateEnum::ExpectingFinished);
1774  EXPECT_EQ(state_.readRecordLayer().get(), rrl);
1775  EXPECT_EQ(state_.writeRecordLayer().get(), appwrl);
1776  EXPECT_EQ(state_.handshakeContext().get(), mockHandshakeContext_);
1777  EXPECT_EQ(state_.keyScheduler().get(), mockKeyScheduler_);
1778  EXPECT_EQ(state_.serverCert(), cert_);
1779  EXPECT_EQ(state_.version(), TestProtocolVersion);
1781  EXPECT_EQ(state_.group(), NamedGroup::x25519);
1783  EXPECT_EQ(state_.pskType(), PskType::NotAttempted);
1784  EXPECT_FALSE(state_.pskMode().hasValue());
1785  EXPECT_EQ(state_.keyExchangeType(), KeyExchangeType::HelloRetryRequest);
1786  EXPECT_EQ(state_.earlyDataType(), EarlyDataType::NotAttempted);
1787  EXPECT_EQ(state_.replayCacheResult(), ReplayCacheResult::NotChecked);
1788  EXPECT_FALSE(state_.clientClockSkew().hasValue());
1789  EXPECT_EQ(*state_.alpn(), "h2");
1791  *state_.clientHandshakeSecret(), IOBuf::copyBuffer("cht")));
1793  *state_.exporterMasterSecret(), IOBuf::copyBuffer("expm")));
1794  EXPECT_FALSE(state_.earlyExporterMasterSecret().hasValue());
1795 }
1796 
1797 TEST_F(ServerProtocolTest, TestRetryClientHelloPskDheFlow) {
1798  context_->setSupportedPskModes({PskKeyExchangeMode::psk_dhe_ke});
1799  setUpExpectingClientHelloRetry();
1800  EXPECT_CALL(*mockTicketCipher_, _decrypt(_))
1801  .WillOnce(InvokeWithoutArgs([=]() {
1802  ResumptionState res;
1805  res.resumptionSecret = folly::IOBuf::copyBuffer("resumesecret");
1806  res.serverCert = cert_;
1807  return std::make_pair(PskType::Resumption, std::move(res));
1808  }));
1809  Sequence contextSeq;
1810  mockKeyScheduler_ = new MockKeyScheduler();
1811  EXPECT_CALL(*factory_, makeKeyScheduler(CipherSuite::TLS_AES_128_GCM_SHA256))
1812  .WillOnce(InvokeWithoutArgs(
1813  [=]() { return std::unique_ptr<KeyScheduler>(mockKeyScheduler_); }));
1814  EXPECT_CALL(
1815  *mockKeyScheduler_, deriveEarlySecret(RangeMatches("resumesecret")));
1816  EXPECT_CALL(*mockHandshakeContext_, appendToTranscript(BufMatches("client")))
1817  .InSequence(contextSeq);
1818  EXPECT_CALL(*mockHandshakeContext_, getFinishedData(RangeMatches("bdr")))
1819  .InSequence(contextSeq)
1820  .WillRepeatedly(
1821  InvokeWithoutArgs([]() { return IOBuf::copyBuffer("verifydata"); }));
1822  EXPECT_CALL(
1823  *mockHandshakeContext_, appendToTranscript(BufMatches("helloencoding")))
1824  .InSequence(contextSeq);
1825  EXPECT_CALL(
1826  *mockKeyScheduler_,
1827  getSecret(EarlySecrets::ResumptionPskBinder, RangeMatches("")))
1828  .WillOnce(InvokeWithoutArgs([]() {
1829  return std::vector<uint8_t>({'b', 'd', 'r'});
1830  }));
1831  EXPECT_CALL(*factory_, makeKeyExchange(NamedGroup::x25519))
1832  .WillOnce(InvokeWithoutArgs([]() {
1833  auto ret = std::make_unique<MockKeyExchange>();
1834  EXPECT_CALL(*ret, generateKeyPair());
1835  EXPECT_CALL(*ret, generateSharedSecret(RangeMatches("keyshare")))
1836  .WillOnce(InvokeWithoutArgs(
1837  []() { return IOBuf::copyBuffer("sharedsecret"); }));
1838  EXPECT_CALL(*ret, getKeyShare()).WillOnce(InvokeWithoutArgs([]() {
1839  return IOBuf::copyBuffer("servershare");
1840  }));
1841  return ret;
1842  }));
1843  EXPECT_CALL(*mockHandshakeContext_, appendToTranscript(_))
1844  .InSequence(contextSeq);
1845  EXPECT_CALL(*mockHandshakeContext_, getHandshakeContext())
1846  .InSequence(contextSeq)
1847  .WillRepeatedly(Invoke([]() { return IOBuf::copyBuffer("chlo_shlo"); }));
1848  EXPECT_CALL(
1849  *mockKeyScheduler_, deriveHandshakeSecret(RangeMatches("sharedsecret")));
1850  EXPECT_CALL(*factory_, makeRandom()).WillOnce(Invoke([]() {
1851  Random random;
1852  random.fill(0x44);
1853  return random;
1854  }));
1855  EXPECT_CALL(*mockWrite_, _write(_)).WillOnce(Invoke([&](TLSMessage& msg) {
1856  TLSContent content;
1857  content.contentType = msg.type;
1858  content.encryptionLevel = mockWrite_->getEncryptionLevel();
1860  auto shlo = TestMessages::serverHello();
1861  ServerPresharedKey serverPsk;
1862  serverPsk.selected_identity = 0;
1863  shlo.extensions.push_back(encodeExtension(std::move(serverPsk)));
1865  content.data = IOBuf::copyBuffer("writtenshlo");
1866  return content;
1867  }));
1868  EXPECT_CALL(
1869  *mockKeyScheduler_,
1870  getSecret(
1871  HandshakeSecrets::ServerHandshakeTraffic, RangeMatches("chlo_shlo")))
1872  .WillOnce(InvokeWithoutArgs([]() {
1873  return std::vector<uint8_t>({'s', 'h', 't'});
1874  }));
1875  EXPECT_CALL(
1876  *mockKeyScheduler_,
1877  getSecret(
1878  HandshakeSecrets::ClientHandshakeTraffic, RangeMatches("chlo_shlo")))
1879  .WillOnce(InvokeWithoutArgs([]() {
1880  return std::vector<uint8_t>({'c', 'h', 't'});
1881  }));
1882  EXPECT_CALL(*mockKeyScheduler_, getTrafficKey(RangeMatches("sht"), _, _))
1883  .WillOnce(InvokeWithoutArgs([]() {
1884  return TrafficKey{IOBuf::copyBuffer("serverkey"),
1885  IOBuf::copyBuffer("serveriv")};
1886  }));
1887  EXPECT_CALL(*mockKeyScheduler_, getTrafficKey(RangeMatches("cht"), _, _))
1888  .WillOnce(InvokeWithoutArgs([]() {
1889  return TrafficKey{IOBuf::copyBuffer("clientkey"),
1890  IOBuf::copyBuffer("clientiv")};
1891  }));
1892  MockAead* raead;
1893  MockAead* waead;
1894  MockAead* appwaead;
1898  expectAeadCreation({{"clientkey", &raead},
1899  {"serverkey", &waead},
1900  {"serverappkey", &appwaead}});
1901  expectEncryptedReadRecordLayerCreation(
1902  &rrl, &raead, StringPiece("cht"), false);
1903  Sequence recSeq;
1904  expectEncryptedWriteRecordLayerCreation(
1905  &wrl,
1906  &waead,
1907  StringPiece("sht"),
1908  [](TLSMessage& msg, auto writeRecord) {
1911  msg.fragment,
1912  getEncryptedHandshakeWrite(
1914  TLSContent content;
1915  content.contentType = msg.type;
1916  content.encryptionLevel = writeRecord->getEncryptionLevel();
1917  content.data = folly::IOBuf::copyBuffer("handshake");
1918  return content;
1919  },
1920  &recSeq);
1921  expectEncryptedWriteRecordLayerCreation(
1922  &appwrl, &appwaead, StringPiece("sat"), nullptr, &recSeq);
1923  EXPECT_CALL(*mockHandshakeContext_, appendToTranscript(_))
1924  .InSequence(contextSeq);
1925  EXPECT_CALL(*mockHandshakeContext_, getFinishedData(RangeMatches("sht")))
1926  .InSequence(contextSeq)
1927  .WillRepeatedly(
1928  InvokeWithoutArgs([]() { return IOBuf::copyBuffer("verifydata"); }));
1929  EXPECT_CALL(*mockHandshakeContext_, appendToTranscript(_))
1930  .InSequence(contextSeq);
1931  EXPECT_CALL(*mockHandshakeContext_, getHandshakeContext())
1932  .InSequence(contextSeq)
1933  .WillRepeatedly(InvokeWithoutArgs(
1934  []() { return IOBuf::copyBuffer("chlo_shlo_sfin"); }));
1935  EXPECT_CALL(*mockKeyScheduler_, deriveMasterSecret());
1936  EXPECT_CALL(
1937  *mockKeyScheduler_,
1938  getSecret(MasterSecrets::ExporterMaster, RangeMatches("chlo_shlo_sfin")))
1939  .WillOnce(InvokeWithoutArgs([]() {
1940  return std::vector<uint8_t>({'e', 'x', 'p', 'm'});
1941  }));
1942  EXPECT_CALL(
1943  *mockKeyScheduler_,
1944  deriveAppTrafficSecrets(RangeMatches("chlo_shlo_sfin")));
1945  EXPECT_CALL(
1946  *mockKeyScheduler_, getSecret(AppTrafficSecrets::ServerAppTraffic))
1947  .WillOnce(InvokeWithoutArgs([]() {
1948  return std::vector<uint8_t>({'s', 'a', 't'});
1949  }));
1950  EXPECT_CALL(*mockKeyScheduler_, getTrafficKey(RangeMatches("sat"), _, _))
1951  .WillOnce(InvokeWithoutArgs([]() {
1952  return TrafficKey{IOBuf::copyBuffer("serverappkey"),
1953  IOBuf::copyBuffer("serverappiv")};
1954  }));
1955 
1956  auto actions =
1957  getActions(detail::processEvent(state_, TestMessages::clientHelloPsk()));
1958 
1959  expectActions<MutateState, WriteToSocket>(actions);
1960  auto write = expectAction<WriteToSocket>(actions);
1961  ASSERT_EQ(write.contents.size(), 2);
1962  EXPECT_EQ(write.contents[0].encryptionLevel, EncryptionLevel::Plaintext);
1963  EXPECT_EQ(write.contents[0].contentType, ContentType::handshake);
1964  EXPECT_TRUE(
1965  IOBufEqualTo()(write.contents[0].data, IOBuf::copyBuffer("writtenshlo")));
1966 
1967  EXPECT_EQ(write.contents[1].encryptionLevel, EncryptionLevel::Handshake);
1968  EXPECT_EQ(write.contents[1].contentType, ContentType::handshake);
1969  EXPECT_TRUE(
1970  IOBufEqualTo()(write.contents[1].data, IOBuf::copyBuffer("handshake")));
1971  processStateMutations(actions);
1972  EXPECT_EQ(state_.state(), StateEnum::ExpectingFinished);
1973  EXPECT_EQ(state_.readRecordLayer().get(), rrl);
1974  EXPECT_EQ(state_.writeRecordLayer().get(), appwrl);
1975  EXPECT_EQ(state_.handshakeContext().get(), mockHandshakeContext_);
1976  EXPECT_EQ(state_.keyScheduler().get(), mockKeyScheduler_);
1977  EXPECT_EQ(state_.serverCert(), cert_);
1979  EXPECT_EQ(state_.group(), NamedGroup::x25519);
1980  EXPECT_FALSE(state_.sigScheme().hasValue());
1981  EXPECT_EQ(state_.pskType(), PskType::Resumption);
1982  EXPECT_EQ(state_.pskMode(), PskKeyExchangeMode::psk_dhe_ke);
1983  EXPECT_EQ(state_.keyExchangeType(), KeyExchangeType::HelloRetryRequest);
1984  EXPECT_EQ(state_.earlyDataType(), EarlyDataType::NotAttempted);
1985  EXPECT_EQ(state_.replayCacheResult(), ReplayCacheResult::NotChecked);
1986  EXPECT_TRUE(state_.clientClockSkew().hasValue());
1987  EXPECT_EQ(*state_.alpn(), "h2");
1989  *state_.clientHandshakeSecret(), IOBuf::copyBuffer("cht")));
1991  *state_.exporterMasterSecret(), IOBuf::copyBuffer("expm")));
1992  EXPECT_FALSE(state_.earlyExporterMasterSecret().hasValue());
1993 }
1994 
1995 TEST_F(ServerProtocolTest, TestClientHelloPskDheEarlyFlow) {
1996  context_->setSupportedPskModes({PskKeyExchangeMode::psk_dhe_ke});
1997  acceptEarlyData();
1998  setUpExpectingClientHello();
1999  EXPECT_CALL(*mockTicketCipher_, _decrypt(_))
2000  .WillOnce(InvokeWithoutArgs([=]() {
2001  ResumptionState res;
2004  res.resumptionSecret = folly::IOBuf::copyBuffer("resumesecret");
2005  res.serverCert = cert_;
2006  res.alpn = "h2";
2007  res.ticketAgeAdd = 0;
2008  res.ticketIssueTime =
2009  std::chrono::system_clock::now() - std::chrono::seconds(100);
2010  return std::make_pair(PskType::Resumption, std::move(res));
2011  }));
2012  Sequence contextSeq;
2013  mockKeyScheduler_ = new MockKeyScheduler();
2014  mockHandshakeContext_ = new MockHandshakeContext();
2015  EXPECT_CALL(*factory_, makeKeyScheduler(CipherSuite::TLS_AES_128_GCM_SHA256))
2016  .WillOnce(InvokeWithoutArgs(
2017  [=]() { return std::unique_ptr<KeyScheduler>(mockKeyScheduler_); }));
2018  EXPECT_CALL(
2019  *factory_, makeHandshakeContext(CipherSuite::TLS_AES_128_GCM_SHA256))
2020  .WillOnce(InvokeWithoutArgs([=]() {
2021  return std::unique_ptr<HandshakeContext>(mockHandshakeContext_);
2022  }));
2023  EXPECT_CALL(
2024  *mockKeyScheduler_, deriveEarlySecret(RangeMatches("resumesecret")));
2025  EXPECT_CALL(*mockHandshakeContext_, appendToTranscript(BufMatches("client")))
2026  .InSequence(contextSeq);
2027  EXPECT_CALL(*mockHandshakeContext_, getFinishedData(RangeMatches("bdr")))
2028  .InSequence(contextSeq)
2029  .WillRepeatedly(
2030  InvokeWithoutArgs([]() { return IOBuf::copyBuffer("verifydata"); }));
2031  EXPECT_CALL(
2032  *mockHandshakeContext_, appendToTranscript(BufMatches("helloencoding")))
2033  .InSequence(contextSeq);
2034  EXPECT_CALL(*mockHandshakeContext_, getHandshakeContext())
2035  .InSequence(contextSeq)
2036  .WillRepeatedly(Invoke([]() { return IOBuf::copyBuffer("chlo"); }));
2037  EXPECT_CALL(
2038  *mockKeyScheduler_,
2039  getSecret(EarlySecrets::ResumptionPskBinder, RangeMatches("")))
2040  .WillOnce(InvokeWithoutArgs([]() {
2041  return std::vector<uint8_t>({'b', 'd', 'r'});
2042  }));
2043  EXPECT_CALL(
2044  *mockKeyScheduler_,
2045  getSecret(EarlySecrets::ClientEarlyTraffic, RangeMatches("chlo")))
2046  .WillOnce(InvokeWithoutArgs([]() {
2047  return std::vector<uint8_t>({'c', 'e', 't'});
2048  }));
2049  EXPECT_CALL(
2050  *mockKeyScheduler_,
2051  getSecret(EarlySecrets::EarlyExporter, RangeMatches("chlo")))
2052  .WillOnce(InvokeWithoutArgs([]() {
2053  return std::vector<uint8_t>({'e', 'e', 'm'});
2054  }));
2055  EXPECT_CALL(*factory_, makeKeyExchange(NamedGroup::x25519))
2056  .WillOnce(InvokeWithoutArgs([]() {
2057  auto ret = std::make_unique<MockKeyExchange>();
2058  EXPECT_CALL(*ret, generateKeyPair());
2059  EXPECT_CALL(*ret, generateSharedSecret(RangeMatches("keyshare")))
2060  .WillOnce(InvokeWithoutArgs(
2061  []() { return IOBuf::copyBuffer("sharedsecret"); }));
2062  EXPECT_CALL(*ret, getKeyShare()).WillOnce(InvokeWithoutArgs([]() {
2063  return IOBuf::copyBuffer("servershare");
2064  }));
2065  return ret;
2066  }));
2067  EXPECT_CALL(*mockHandshakeContext_, appendToTranscript(_))
2068  .InSequence(contextSeq);
2069  EXPECT_CALL(*mockHandshakeContext_, getHandshakeContext())
2070  .InSequence(contextSeq)
2071  .WillRepeatedly(Invoke([]() { return IOBuf::copyBuffer("chlo_shlo"); }));
2072  EXPECT_CALL(
2073  *mockKeyScheduler_, deriveHandshakeSecret(RangeMatches("sharedsecret")));
2074  EXPECT_CALL(*factory_, makeRandom()).WillOnce(Invoke([]() {
2075  Random random;
2076  random.fill(0x44);
2077  return random;
2078  }));
2079  EXPECT_CALL(*mockWrite_, _write(_)).WillOnce(Invoke([&](TLSMessage& msg) {
2080  TLSContent content;
2081  content.contentType = msg.type;
2082  content.encryptionLevel = mockWrite_->getEncryptionLevel();
2084  auto shlo = TestMessages::serverHello();
2085  ServerPresharedKey serverPsk;
2086  serverPsk.selected_identity = 0;
2087  shlo.extensions.push_back(encodeExtension(std::move(serverPsk)));
2089  content.data = IOBuf::copyBuffer("writtenshlo");
2090  return content;
2091  }));
2092  EXPECT_CALL(
2093  *mockKeyScheduler_,
2094  getSecret(
2095  HandshakeSecrets::ServerHandshakeTraffic, RangeMatches("chlo_shlo")))
2096  .WillOnce(InvokeWithoutArgs([]() {
2097  return std::vector<uint8_t>({'s', 'h', 't'});
2098  }));
2099  EXPECT_CALL(
2100  *mockKeyScheduler_,
2101  getSecret(
2102  HandshakeSecrets::ClientHandshakeTraffic, RangeMatches("chlo_shlo")))
2103  .WillOnce(InvokeWithoutArgs([]() {
2104  return std::vector<uint8_t>({'c', 'h', 't'});
2105  }));
2106  EXPECT_CALL(*mockKeyScheduler_, getTrafficKey(RangeMatches("cet"), _, _))
2107  .WillOnce(InvokeWithoutArgs([]() {
2108  return TrafficKey{IOBuf::copyBuffer("earlykey"),
2109  IOBuf::copyBuffer("earlyiv")};
2110  }));
2111  EXPECT_CALL(*mockKeyScheduler_, getTrafficKey(RangeMatches("sht"), _, _))
2112  .WillOnce(InvokeWithoutArgs([]() {
2113  return TrafficKey{IOBuf::copyBuffer("serverkey"),
2114  IOBuf::copyBuffer("serveriv")};
2115  }));
2116  EXPECT_CALL(*mockKeyScheduler_, getTrafficKey(RangeMatches("cht"), _, _))
2117  .WillOnce(InvokeWithoutArgs([]() {
2118  return TrafficKey{IOBuf::copyBuffer("clientkey"),
2119  IOBuf::copyBuffer("clientiv")};
2120  }));
2121  MockAead* earlyaead;
2122  MockAead* raead;
2123  MockAead* waead;
2124  MockAead* appwaead;
2125  MockEncryptedReadRecordLayer* earlyrrl;
2126  MockEncryptedReadRecordLayer* handshakerrl;
2129  expectAeadCreation({{"earlykey", &earlyaead},
2130  {"clientkey", &raead},
2131  {"serverkey", &waead},
2132  {"serverappkey", &appwaead}});
2133  Sequence readRecSeq;
2134  expectEncryptedReadRecordLayerCreation(
2135  &earlyrrl, &earlyaead, StringPiece("cet"), folly::none, &readRecSeq);
2136  expectEncryptedReadRecordLayerCreation(
2137  &handshakerrl, &raead, StringPiece("cht"), false, &readRecSeq);
2138  Sequence recSeq;
2139  expectEncryptedWriteRecordLayerCreation(
2140  &wrl,
2141  &waead,
2142  StringPiece("sht"),
2143  [](TLSMessage& msg, auto writeRecord) {
2146  msg.fragment,
2147  getEncryptedHandshakeWrite(
2149  TLSContent content;
2150  content.contentType = msg.type;
2151  content.encryptionLevel = writeRecord->getEncryptionLevel();
2152  content.data = folly::IOBuf::copyBuffer("handshake");
2153  return content;
2154  },
2155  &recSeq);
2156  expectEncryptedWriteRecordLayerCreation(
2157  &appwrl, &appwaead, StringPiece("sat"), nullptr, &recSeq);
2158  EXPECT_CALL(*mockHandshakeContext_, appendToTranscript(_))
2159  .InSequence(contextSeq);
2160  EXPECT_CALL(*mockHandshakeContext_, getFinishedData(RangeMatches("sht")))
2161  .InSequence(contextSeq)
2162  .WillRepeatedly(
2163  InvokeWithoutArgs([]() { return IOBuf::copyBuffer("verifydata"); }));
2164  EXPECT_CALL(*mockHandshakeContext_, appendToTranscript(_))
2165  .InSequence(contextSeq);
2166  EXPECT_CALL(*mockHandshakeContext_, getHandshakeContext())
2167  .InSequence(contextSeq)
2168  .WillRepeatedly(InvokeWithoutArgs(
2169  []() { return IOBuf::copyBuffer("chlo_shlo_sfin"); }));
2170  EXPECT_CALL(*mockKeyScheduler_, deriveMasterSecret());
2171  EXPECT_CALL(
2172  *mockKeyScheduler_,
2173  getSecret(MasterSecrets::ExporterMaster, RangeMatches("chlo_shlo_sfin")))
2174  .WillOnce(InvokeWithoutArgs([]() {
2175  return std::vector<uint8_t>({'e', 'x', 'p', 'm'});
2176  }));
2177  EXPECT_CALL(
2178  *mockKeyScheduler_,
2179  deriveAppTrafficSecrets(RangeMatches("chlo_shlo_sfin")));
2180  EXPECT_CALL(
2181  *mockKeyScheduler_, getSecret(AppTrafficSecrets::ServerAppTraffic))
2182  .WillOnce(InvokeWithoutArgs([]() {
2183  return std::vector<uint8_t>({'s', 'a', 't'});
2184  }));
2185  EXPECT_CALL(*mockKeyScheduler_, getTrafficKey(RangeMatches("sat"), _, _))
2186  .WillOnce(InvokeWithoutArgs([]() {
2187  return TrafficKey{IOBuf::copyBuffer("serverappkey"),
2188  IOBuf::copyBuffer("serverappiv")};
2189  }));
2190 
2191  auto actions = getActions(
2193 
2194  expectActions<MutateState, WriteToSocket, ReportEarlyHandshakeSuccess>(
2195  actions);
2196  auto write = expectAction<WriteToSocket>(actions);
2197  ASSERT_EQ(write.contents.size(), 2);
2198  EXPECT_EQ(write.contents[0].encryptionLevel, EncryptionLevel::Plaintext);
2199  EXPECT_EQ(write.contents[0].contentType, ContentType::handshake);
2200  EXPECT_TRUE(
2201  IOBufEqualTo()(write.contents[0].data, IOBuf::copyBuffer("writtenshlo")));
2202 
2203  EXPECT_EQ(write.contents[1].encryptionLevel, EncryptionLevel::Handshake);
2204  EXPECT_EQ(write.contents[1].contentType, ContentType::handshake);
2205  EXPECT_TRUE(
2206  IOBufEqualTo()(write.contents[1].data, IOBuf::copyBuffer("handshake")));
2207  processStateMutations(actions);
2208  EXPECT_EQ(state_.state(), StateEnum::AcceptingEarlyData);
2209  EXPECT_EQ(state_.handshakeReadRecordLayer().get(), handshakerrl);
2210  EXPECT_EQ(state_.readRecordLayer().get(), earlyrrl);
2211  EXPECT_EQ(
2212  state_.readRecordLayer()->getEncryptionLevel(),
2214  EXPECT_EQ(state_.writeRecordLayer().get(), appwrl);
2215  EXPECT_EQ(
2216  state_.writeRecordLayer()->getEncryptionLevel(),
2218  EXPECT_EQ(state_.handshakeContext().get(), mockHandshakeContext_);
2219  EXPECT_EQ(state_.keyScheduler().get(), mockKeyScheduler_);
2220  EXPECT_EQ(state_.serverCert(), cert_);
2222  EXPECT_EQ(state_.group(), NamedGroup::x25519);
2223  EXPECT_FALSE(state_.sigScheme().hasValue());
2224  EXPECT_EQ(state_.pskType(), PskType::Resumption);
2225  EXPECT_EQ(state_.pskMode(), PskKeyExchangeMode::psk_dhe_ke);
2226  EXPECT_EQ(state_.keyExchangeType(), KeyExchangeType::OneRtt);
2227  EXPECT_EQ(state_.earlyDataType(), EarlyDataType::Accepted);
2228  EXPECT_EQ(state_.replayCacheResult(), ReplayCacheResult::NotReplay);
2229  EXPECT_TRUE(state_.clientClockSkew().hasValue());
2230  EXPECT_EQ(*state_.alpn(), "h2");
2232  *state_.clientHandshakeSecret(), IOBuf::copyBuffer("cht")));
2234  *state_.exporterMasterSecret(), IOBuf::copyBuffer("expm")));
2236  *state_.earlyExporterMasterSecret(), IOBuf::copyBuffer("eem")));
2237 }
2238 
2239 TEST_F(ServerProtocolTest, TestClientHelloPskEarlyFlow) {
2240  context_->setSupportedPskModes({PskKeyExchangeMode::psk_ke});
2241  acceptEarlyData();
2242  setUpExpectingClientHello();
2243  EXPECT_CALL(*mockTicketCipher_, _decrypt(_))
2244  .WillOnce(InvokeWithoutArgs([=]() {
2245  ResumptionState res;
2248  res.resumptionSecret = folly::IOBuf::copyBuffer("resumesecret");
2249  res.serverCert = cert_;
2250  res.alpn = "h2";
2251  res.ticketAgeAdd = 0;
2252  res.ticketIssueTime =
2253  std::chrono::system_clock::now() - std::chrono::seconds(100);
2254  return std::make_pair(PskType::Resumption, std::move(res));
2255  }));
2256  Sequence contextSeq;
2257  mockKeyScheduler_ = new MockKeyScheduler();
2258  mockHandshakeContext_ = new MockHandshakeContext();
2259  EXPECT_CALL(*factory_, makeKeyScheduler(CipherSuite::TLS_AES_128_GCM_SHA256))
2260  .WillOnce(InvokeWithoutArgs(
2261  [=]() { return std::unique_ptr<KeyScheduler>(mockKeyScheduler_); }));
2262  EXPECT_CALL(
2263  *factory_, makeHandshakeContext(CipherSuite::TLS_AES_128_GCM_SHA256))
2264  .WillOnce(InvokeWithoutArgs([=]() {
2265  return std::unique_ptr<HandshakeContext>(mockHandshakeContext_);
2266  }));
2267  EXPECT_CALL(
2268  *mockKeyScheduler_, deriveEarlySecret(RangeMatches("resumesecret")));
2269  EXPECT_CALL(*mockHandshakeContext_, appendToTranscript(BufMatches("client")))
2270  .InSequence(contextSeq);
2271  EXPECT_CALL(*mockHandshakeContext_, getFinishedData(RangeMatches("bdr")))
2272  .InSequence(contextSeq)
2273  .WillRepeatedly(
2274  InvokeWithoutArgs([]() { return IOBuf::copyBuffer("verifydata"); }));
2275  EXPECT_CALL(
2276  *mockHandshakeContext_, appendToTranscript(BufMatches("helloencoding")))
2277  .InSequence(contextSeq);
2278  EXPECT_CALL(*mockHandshakeContext_, getHandshakeContext())
2279  .InSequence(contextSeq)
2280  .WillRepeatedly(Invoke([]() { return IOBuf::copyBuffer("chlo"); }));
2281  EXPECT_CALL(
2282  *mockKeyScheduler_,
2283  getSecret(EarlySecrets::ResumptionPskBinder, RangeMatches("")))
2284  .WillOnce(InvokeWithoutArgs([]() {
2285  return std::vector<uint8_t>({'b', 'd', 'r'});
2286  }));
2287  EXPECT_CALL(
2288  *mockKeyScheduler_,
2289  getSecret(EarlySecrets::ClientEarlyTraffic, RangeMatches("chlo")))
2290  .WillOnce(InvokeWithoutArgs([]() {
2291  return std::vector<uint8_t>({'c', 'e', 't'});
2292  }));
2293  EXPECT_CALL(
2294  *mockKeyScheduler_,
2295  getSecret(EarlySecrets::EarlyExporter, RangeMatches("chlo")))
2296  .WillOnce(InvokeWithoutArgs([]() {
2297  return std::vector<uint8_t>({'e', 'e', 'm'});
2298  }));
2299  EXPECT_CALL(*mockHandshakeContext_, appendToTranscript(_))
2300  .InSequence(contextSeq);
2301  EXPECT_CALL(*mockHandshakeContext_, getHandshakeContext())
2302  .InSequence(contextSeq)
2303  .WillRepeatedly(Invoke([]() { return IOBuf::copyBuffer("chlo_shlo"); }));
2304  EXPECT_CALL(*mockKeyScheduler_, deriveHandshakeSecret());
2305  EXPECT_CALL(*factory_, makeRandom()).WillOnce(Invoke([]() {
2306  Random random;
2307  random.fill(0x44);
2308  return random;
2309  }));
2310  EXPECT_CALL(*mockWrite_, _write(_)).WillOnce(Invoke([&](TLSMessage& msg) {
2311  TLSContent content;
2312  content.contentType = msg.type;
2313  content.encryptionLevel = mockWrite_->getEncryptionLevel();
2315  auto shlo = TestMessages::serverHello();
2317  ServerPresharedKey serverPsk;
2318  serverPsk.selected_identity = 0;
2319  shlo.extensions.push_back(encodeExtension(std::move(serverPsk)));
2321  content.data = IOBuf::copyBuffer("writtenshlo");
2322  return content;
2323  }));
2324  EXPECT_CALL(
2325  *mockKeyScheduler_,
2326  getSecret(
2327  HandshakeSecrets::ServerHandshakeTraffic, RangeMatches("chlo_shlo")))
2328  .WillOnce(InvokeWithoutArgs([]() {
2329  return std::vector<uint8_t>({'s', 'h', 't'});
2330  }));
2331  EXPECT_CALL(
2332  *mockKeyScheduler_,
2333  getSecret(
2334  HandshakeSecrets::ClientHandshakeTraffic, RangeMatches("chlo_shlo")))
2335  .WillOnce(InvokeWithoutArgs([]() {
2336  return std::vector<uint8_t>({'c', 'h', 't'});
2337  }));
2338  EXPECT_CALL(*mockKeyScheduler_, getTrafficKey(RangeMatches("cet"), _, _))
2339  .WillOnce(InvokeWithoutArgs([]() {
2340  return TrafficKey{IOBuf::copyBuffer("earlykey"),
2341  IOBuf::copyBuffer("earlyiv")};
2342  }));
2343  EXPECT_CALL(*mockKeyScheduler_, getTrafficKey(RangeMatches("sht"), _, _))
2344  .WillOnce(InvokeWithoutArgs([]() {
2345  return TrafficKey{IOBuf::copyBuffer("serverkey"),
2346  IOBuf::copyBuffer("serveriv")};
2347  }));
2348  EXPECT_CALL(*mockKeyScheduler_, getTrafficKey(RangeMatches("cht"), _, _))
2349  .WillOnce(InvokeWithoutArgs([]() {
2350  return TrafficKey{IOBuf::copyBuffer("clientkey"),
2351  IOBuf::copyBuffer("clientiv")};
2352  }));
2353  MockAead* earlyaead;
2354  MockAead* raead;
2355  MockAead* waead;
2356  MockAead* appwaead;
2357  MockEncryptedReadRecordLayer* earlyrrl;
2358  MockEncryptedReadRecordLayer* handshakerrl;
2361  expectAeadCreation({{"earlykey", &earlyaead},
2362  {"clientkey", &raead},
2363  {"serverkey", &waead},
2364  {"serverappkey", &appwaead}});
2365  Sequence readRecSeq;
2366  expectEncryptedReadRecordLayerCreation(
2367  &earlyrrl, &earlyaead, StringPiece("cet"), folly::none, &readRecSeq);
2368  expectEncryptedReadRecordLayerCreation(
2369  &handshakerrl, &raead, StringPiece("cht"), false, &readRecSeq);
2370  Sequence recSeq;
2371  expectEncryptedWriteRecordLayerCreation(
2372  &wrl,
2373  &waead,
2374  StringPiece("sht"),
2375  [](TLSMessage& msg, auto writeRecord) {
2378  msg.fragment,
2379  getEncryptedHandshakeWrite(
2381  TLSContent content;
2382  content.contentType = msg.type;
2383  content.encryptionLevel = writeRecord->getEncryptionLevel();
2384  content.data = folly::IOBuf::copyBuffer("handshake");
2385  return content;
2386  },
2387  &recSeq);
2388  expectEncryptedWriteRecordLayerCreation(
2389  &appwrl, &appwaead, StringPiece("sat"), nullptr, &recSeq);
2390  EXPECT_CALL(*mockHandshakeContext_, appendToTranscript(_))
2391  .InSequence(contextSeq);
2392  EXPECT_CALL(*mockHandshakeContext_, getFinishedData(RangeMatches("sht")))
2393  .InSequence(contextSeq)
2394  .WillRepeatedly(
2395  InvokeWithoutArgs([]() { return IOBuf::copyBuffer("verifydata"); }));
2396  EXPECT_CALL(*mockHandshakeContext_, appendToTranscript(_))
2397  .InSequence(contextSeq);
2398  EXPECT_CALL(*mockHandshakeContext_, getHandshakeContext())
2399  .InSequence(contextSeq)
2400  .WillRepeatedly(InvokeWithoutArgs(
2401  []() { return IOBuf::copyBuffer("chlo_shlo_sfin"); }));
2402  EXPECT_CALL(*mockKeyScheduler_, deriveMasterSecret());
2403  EXPECT_CALL(
2404  *mockKeyScheduler_,
2405  getSecret(MasterSecrets::ExporterMaster, RangeMatches("chlo_shlo_sfin")))
2406  .WillOnce(InvokeWithoutArgs([]() {
2407  return std::vector<uint8_t>({'e', 'x', 'p', 'm'});
2408  }));
2409  EXPECT_CALL(
2410  *mockKeyScheduler_,
2411  deriveAppTrafficSecrets(RangeMatches("chlo_shlo_sfin")));
2412  EXPECT_CALL(
2413  *mockKeyScheduler_, getSecret(AppTrafficSecrets::ServerAppTraffic))
2414  .WillOnce(InvokeWithoutArgs([]() {
2415  return std::vector<uint8_t>({'s', 'a', 't'});
2416  }));
2417  EXPECT_CALL(*mockKeyScheduler_, getTrafficKey(RangeMatches("sat"), _, _))
2418  .WillOnce(InvokeWithoutArgs([]() {
2419  return TrafficKey{IOBuf::copyBuffer("serverappkey"),
2420  IOBuf::copyBuffer("serverappiv")};
2421  }));
2422 
2423  auto actions = getActions(
2425 
2426  expectActions<MutateState, WriteToSocket, ReportEarlyHandshakeSuccess>(
2427  actions);
2428  auto write = expectAction<WriteToSocket>(actions);
2429  ASSERT_EQ(write.contents.size(), 2);
2430  EXPECT_TRUE(
2431  IOBufEqualTo()(write.contents[0].data, IOBuf::copyBuffer("writtenshlo")));
2432  EXPECT_EQ(write.contents[0].contentType, ContentType::handshake);
2433  EXPECT_EQ(write.contents[0].encryptionLevel, EncryptionLevel::Plaintext);
2434 
2435  EXPECT_TRUE(
2436  IOBufEqualTo()(write.contents[1].data, IOBuf::copyBuffer("handshake")));
2437  EXPECT_EQ(write.contents[1].contentType, ContentType::handshake);
2438  EXPECT_EQ(write.contents[1].encryptionLevel, EncryptionLevel::Handshake);
2439 
2440  processStateMutations(actions);
2441  EXPECT_EQ(state_.state(), StateEnum::AcceptingEarlyData);
2442  EXPECT_EQ(state_.handshakeReadRecordLayer().get(), handshakerrl);
2443  EXPECT_EQ(state_.readRecordLayer().get(), earlyrrl);
2444  EXPECT_EQ(
2445  state_.readRecordLayer()->getEncryptionLevel(),
2447  EXPECT_EQ(state_.writeRecordLayer().get(), appwrl);
2448  EXPECT_EQ(
2449  state_.writeRecordLayer()->getEncryptionLevel(),
2451  EXPECT_EQ(state_.handshakeContext().get(), mockHandshakeContext_);
2452  EXPECT_EQ(state_.keyScheduler().get(), mockKeyScheduler_);
2453  EXPECT_EQ(state_.serverCert(), cert_);
2454  EXPECT_EQ(state_.version(), TestProtocolVersion);
2456  EXPECT_FALSE(state_.group().hasValue());
2457  EXPECT_FALSE(state_.sigScheme().hasValue());
2458  EXPECT_EQ(state_.pskType(), PskType::Resumption);
2459  EXPECT_EQ(state_.pskMode(), PskKeyExchangeMode::psk_ke);
2460  EXPECT_EQ(state_.keyExchangeType(), KeyExchangeType::None);
2461  EXPECT_EQ(state_.earlyDataType(), EarlyDataType::Accepted);
2462  EXPECT_EQ(state_.replayCacheResult(), ReplayCacheResult::NotReplay);
2463  EXPECT_TRUE(state_.clientClockSkew().hasValue());
2464  EXPECT_EQ(*state_.alpn(), "h2");
2466  *state_.clientHandshakeSecret(), IOBuf::copyBuffer("cht")));
2468  *state_.exporterMasterSecret(), IOBuf::copyBuffer("expm")));
2470  *state_.earlyExporterMasterSecret(), IOBuf::copyBuffer("eem")));
2471 }
2472 
2473 TEST_F(ServerProtocolTest, TestClientHelloNullExtensions) {
2474  addExtensions_ = false;
2475  setUpExpectingClientHello();
2476  auto actions =
2477  getActions(detail::processEvent(state_, TestMessages::clientHello()));
2478  expectActions<MutateState, WriteToSocket>(actions);
2479  processStateMutations(actions);
2480  EXPECT_CALL(*extensions_, getExtensions(_)).Times(0);
2481 }
2482 
2483 TEST_F(ServerProtocolTest, TestClientHelloLegacySessionId) {
2484  setUpExpectingClientHello();
2485  auto chloWithLegacy = TestMessages::clientHello();
2486  chloWithLegacy.legacy_session_id = IOBuf::copyBuffer("middleboxes");
2487  auto actions =
2488  getActions(detail::processEvent(state_, std::move(chloWithLegacy)));
2489  expectActions<MutateState, WriteToSocket>(actions);
2490  auto write = expectAction<WriteToSocket>(actions);
2491  EXPECT_EQ(write.contents.size(), 3);
2492  EXPECT_EQ(write.contents[0].contentType, ContentType::handshake);
2493  EXPECT_EQ(write.contents[0].encryptionLevel, EncryptionLevel::Plaintext);
2494  EXPECT_EQ(write.contents[1].contentType, ContentType::change_cipher_spec);
2495  EXPECT_EQ(write.contents[1].encryptionLevel, EncryptionLevel::Plaintext);
2496  EXPECT_EQ(write.contents[2].contentType, ContentType::handshake);
2497  EXPECT_EQ(write.contents[2].encryptionLevel, EncryptionLevel::Handshake);
2498 }
2499 
2500 TEST_F(ServerProtocolTest, TestClientHelloLegacyHrr) {
2501  setUpExpectingClientHello();
2502  auto chloWithLegacy = TestMessages::clientHello();
2503  chloWithLegacy.legacy_session_id = IOBuf::copyBuffer("middleboxes");
2504  context_->setSupportedGroups({NamedGroup::secp256r1, NamedGroup::x25519});
2505  auto actions =
2506  getActions(detail::processEvent(state_, std::move(chloWithLegacy)));
2507  expectActions<MutateState, WriteToSocket>(actions);
2508  auto write = expectAction<WriteToSocket>(actions);
2509  EXPECT_EQ(write.contents.size(), 2);
2510  EXPECT_EQ(write.contents[0].contentType, ContentType::handshake);
2511  EXPECT_EQ(write.contents[0].encryptionLevel, EncryptionLevel::Plaintext);
2512  EXPECT_EQ(write.contents[1].contentType, ContentType::change_cipher_spec);
2513  EXPECT_EQ(write.contents[1].encryptionLevel, EncryptionLevel::Plaintext);
2514  processStateMutations(actions);
2515  EXPECT_EQ(state_.state(), StateEnum::ExpectingClientHello);
2516 }
2517 
2518 TEST_F(ServerProtocolTest, TestClientHelloFullHandshake) {
2519  setUpExpectingClientHello();
2520  auto actions =
2521  getActions(detail::processEvent(state_, TestMessages::clientHello()));
2522  expectActions<MutateState, WriteToSocket>(actions);
2523 }
2524 
2525 TEST_F(ServerProtocolTest, TestClientHelloPsk) {
2526  context_->setSupportedPskModes({PskKeyExchangeMode::psk_ke});
2527  setUpExpectingClientHello();
2528  auto actions =
2529  getActions(detail::processEvent(state_, TestMessages::clientHelloPsk()));
2530  expectActions<MutateState, WriteToSocket>(actions);
2531 }
2532 
2533 TEST_F(ServerProtocolTest, TestClientHelloPskDhe) {
2534  context_->setSupportedPskModes({PskKeyExchangeMode::psk_dhe_ke});
2535  setUpExpectingClientHello();
2536  auto actions =
2537  getActions(detail::processEvent(state_, TestMessages::clientHelloPsk()));
2538  expectActions<MutateState, WriteToSocket>(actions);
2539 }
2540 
2541 TEST_F(ServerProtocolTest, TestClientHelloPskModeMismatch) {
2542  setUpExpectingClientHello();
2545  PskKeyExchangeModes modes;
2546  chlo.extensions.push_back(encodeExtension(std::move(modes)));
2548  auto actions = getActions(detail::processEvent(state_, std::move(chlo)));
2549  expectActions<MutateState, WriteToSocket>(actions);
2550 }
2551 
2552 TEST_F(ServerProtocolTest, TestClientHelloNoSni) {
2553  setUpExpectingClientHello();
2556  auto actions = getActions(detail::processEvent(state_, std::move(chlo)));
2557  expectActions<MutateState, WriteToSocket>(actions);
2558 }
2559 
2560 TEST_F(ServerProtocolTest, TestClientHelloFullHandshakeRejectedPsk) {
2561  setUpExpectingClientHello();
2562  EXPECT_CALL(*mockTicketCipher_, _decrypt(_)).WillOnce(InvokeWithoutArgs([]() {
2563  return std::make_pair(PskType::Rejected, none);
2564  }));
2565 
2566  auto actions =
2567  getActions(detail::processEvent(state_, TestMessages::clientHelloPsk()));
2568  expectActions<MutateState, WriteToSocket>(actions);
2569  processStateMutations(actions);
2570  EXPECT_EQ(state_.state(), StateEnum::ExpectingFinished);
2571  EXPECT_EQ(state_.pskType(), PskType::Rejected);
2572 }
2573 
2574 TEST_F(ServerProtocolTest, TestClientHelloPskNoModes) {
2575  setUpExpectingClientHello();
2578  auto actions = getActions(detail::processEvent(state_, std::move(chlo)));
2579  expectError<FizzException>(
2580  actions, AlertDescription::missing_extension, "no psk modes");
2581 }
2582 
2583 TEST_F(ServerProtocolTest, TestClientHelloPskNotSupported) {
2584  setUpExpectingClientHello();
2587  auto actions = getActions(detail::processEvent(state_, std::move(chlo)));
2588  expectActions<MutateState, WriteToSocket>(actions);
2589  processStateMutations(actions);
2590  EXPECT_EQ(state_.state(), StateEnum::ExpectingFinished);
2591  EXPECT_EQ(state_.pskType(), PskType::NotSupported);
2592  EXPECT_FALSE(state_.pskMode().hasValue());
2593 }
2594 
2595 TEST_F(ServerProtocolTest, TestClientHelloPskBadBinder) {
2596  setUpExpectingClientHello();
2599  ClientPresharedKey cpk;
2600  PskIdentity ident;
2601  ident.psk_identity = folly::IOBuf::copyBuffer("ident");
2602  cpk.identities.push_back(std::move(ident));
2603  PskBinder binder;
2604  binder.binder = folly::IOBuf::copyBuffer("verifyxxxx");
2605  cpk.binders.push_back(std::move(binder));
2606  chlo.extensions.push_back(encodeExtension(std::move(cpk)));
2607  auto actions = getActions(detail::processEvent(state_, std::move(chlo)));
2608  expectError<FizzException>(
2609  actions, AlertDescription::bad_record_mac, "binder does not match");
2610 }
2611 
2612 TEST_F(ServerProtocolTest, TestClientHelloFallback) {
2613  context_->setVersionFallbackEnabled(true);
2614  setUpExpectingClientHello();
2615  auto clientHello = TestMessages::clientHello();
2617  auto actions =
2618  getActions(detail::processEvent(state_, std::move(clientHello)));
2619  expectActions<MutateState, AttemptVersionFallback>(actions);
2620  processStateMutations(actions);
2621  EXPECT_EQ(state_.state(), StateEnum::Error);
2622 
2623  auto fallback = expectAction<AttemptVersionFallback>(actions);
2624  std::string expected(
2625  "\x16\x03\x01\x00\x13"
2626  "clienthelloencoding",
2627  24);
2628  EXPECT_EQ(fallback.clientHello->moveToFbString().toStdString(), expected);
2629 }
2630 
2631 TEST_F(ServerProtocolTest, TestClientHelloNoSupportedVersions) {
2632  setUpExpectingClientHello();
2633  auto clientHello = TestMessages::clientHello();
2635  auto actions =
2636  getActions(detail::processEvent(state_, std::move(clientHello)));
2637  expectError<FizzException>(
2638  actions,
2640  "supported version mismatch");
2641 }
2642 
2643 TEST_F(ServerProtocolTest, TestClientHelloSupportedVersionsMismatch) {
2644  setUpExpectingClientHello();
2645  auto clientHello = TestMessages::clientHello();
2647  SupportedVersions supportedVersions;
2648  supportedVersions.versions.push_back(static_cast<ProtocolVersion>(0x0200));
2649  clientHello.extensions.push_back(
2650  encodeExtension(std::move(supportedVersions)));
2651  auto actions =
2652  getActions(detail::processEvent(state_, std::move(clientHello)));
2653  expectError<FizzException>(
2654  actions,
2656  "supported version mismatch");
2657 }
2658 
2659 TEST_F(ServerProtocolTest, TestClientHelloCipherMismatch) {
2660  setUpExpectingClientHello();
2661  auto clientHello = TestMessages::clientHello();
2662  clientHello.cipher_suites.clear();
2663  auto actions =
2664  getActions(detail::processEvent(state_, std::move(clientHello)));
2665  expectError<FizzException>(
2666  actions, AlertDescription::handshake_failure, "no cipher match");
2667 }
2668 
2669 TEST_F(ServerProtocolTest, TestClientHelloNoSupportedGroups) {
2670  setUpExpectingClientHello();
2671  auto clientHello = TestMessages::clientHello();
2673  auto actions =
2674  getActions(detail::processEvent(state_, std::move(clientHello)));
2675  expectError<FizzException>(
2676  actions, AlertDescription::missing_extension, "no named groups");
2677 }
2678 
2679 TEST_F(ServerProtocolTest, TestClientHelloNamedGroupsMismatch) {
2680  setUpExpectingClientHello();
2681  auto clientHello = TestMessages::clientHello();
2683  SupportedGroups sg;
2684  sg.named_group_list.push_back(static_cast<NamedGroup>(0x0707));
2685  clientHello.extensions.push_back(encodeExtension(std::move(sg)));
2686  auto actions =
2687  getActions(detail::processEvent(state_, std::move(clientHello)));
2688  expectError<FizzException>(
2689  actions, AlertDescription::handshake_failure, "no group match");
2690 }
2691 
2692 TEST_F(ServerProtocolTest, TestClientHelloNoClientKeyShare) {
2693  setUpExpectingClientHello();
2694  auto clientHello = TestMessages::clientHello();
2696  auto actions =
2697  getActions(detail::processEvent(state_, std::move(clientHello)));
2698  expectError<FizzException>(
2699  actions, AlertDescription::missing_extension, "no client share");
2700 }
2701 
2702 TEST_F(ServerProtocolTest, TestClientHelloNoSigScemes) {
2703  setUpExpectingClientHello();
2704  auto clientHello = TestMessages::clientHello();
2707  auto actions =
2708  getActions(detail::processEvent(state_, std::move(clientHello)));
2709  expectError<FizzException>(
2710  actions, AlertDescription::missing_extension, "no sig schemes");
2711 }
2712 
2713 TEST_F(ServerProtocolTest, TestClientHelloDataAfter) {
2714  setUpExpectingClientHello();
2715  EXPECT_CALL(*mockRead_, hasUnparsedHandshakeData())
2716  .WillRepeatedly(Return(true));
2717  auto actions =
2718  getActions(detail::processEvent(state_, TestMessages::clientHello()));
2719  expectError<FizzException>(
2720  actions, AlertDescription::unexpected_message, "data after client hello");
2721 }
2722 
2723 TEST_F(ServerProtocolTest, TestClientHelloNoAlpn) {
2724  setUpExpectingClientHello();
2728  auto actions = getActions(detail::processEvent(state_, std::move(chlo)));
2729  expectActions<MutateState, WriteToSocket>(actions);
2730  processStateMutations(actions);
2731  EXPECT_FALSE(state_.alpn().hasValue());
2732 }
2733 
2734 TEST_F(ServerProtocolTest, TestClientHelloAlpnMismatch) {
2735  setUpExpectingClientHello();
2740  ProtocolName gopher;
2741  gopher.name = folly::IOBuf::copyBuffer("gopher");
2742  alpn.protocol_name_list.push_back(std::move(gopher));
2743  chlo.extensions.push_back(encodeExtension(std::move(alpn)));
2744  auto actions = getActions(detail::processEvent(state_, std::move(chlo)));
2745  expectActions<MutateState, WriteToSocket>(actions);
2746  processStateMutations(actions);
2747  EXPECT_FALSE(state_.alpn().hasValue());
2748 }
2749 
2750 TEST_F(ServerProtocolTest, TestClientHelloServerPref) {
2751  setUpExpectingClientHello();
2756  ProtocolName gopher;
2757  gopher.name = folly::IOBuf::copyBuffer("gopher");
2758  alpn.protocol_name_list.push_back(std::move(gopher));
2759  ProtocolName h2;
2760  h2.name = folly::IOBuf::copyBuffer("h2");
2761  alpn.protocol_name_list.push_back(std::move(h2));
2762  chlo.extensions.push_back(encodeExtension(std::move(alpn)));
2763  auto actions = getActions(detail::processEvent(state_, std::move(chlo)));
2764  expectActions<MutateState, WriteToSocket>(actions);
2765  processStateMutations(actions);
2766  EXPECT_EQ(*state_.alpn(), "h2");
2767 }
2768 
2769 TEST_F(ServerProtocolTest, TestClientHelloAcceptEarlyData) {
2770  acceptEarlyData();
2771  setUpExpectingClientHello();
2772 
2773  auto actions = getActions(
2775  expectActions<MutateState, WriteToSocket, ReportEarlyHandshakeSuccess>(
2776  actions);
2777  processStateMutations(actions);
2778  EXPECT_EQ(state_.state(), StateEnum::AcceptingEarlyData);
2779  EXPECT_EQ(state_.pskType(), PskType::Resumption);
2780  EXPECT_EQ(state_.earlyDataType(), EarlyDataType::Accepted);
2781  EXPECT_EQ(state_.replayCacheResult(), ReplayCacheResult::NotReplay);
2782  EXPECT_EQ(
2783  state_.readRecordLayer()->getEncryptionLevel(),
2785 }
2786 
2789  TestClientHelloEarlyDataNotAttemptedWithAppTokenValidator) {
2790  acceptEarlyData();
2791  setUpExpectingClientHello();
2792  auto validator = std::make_unique<MockAppTokenValidator>();
2793  auto validatorPtr = validator.get();
2794  state_.appTokenValidator() = std::move(validator);
2795 
2796  ON_CALL(*validatorPtr, validate(_)).WillByDefault(InvokeWithoutArgs([]() {
2797  EXPECT_TRUE(false)
2798  << "Early data not attempted, validator shoudn't be called";
2799  return false;
2800  }));
2801  auto actions =
2802  getActions(detail::processEvent(state_, TestMessages::clientHelloPsk()));
2803  expectActions<MutateState, WriteToSocket>(actions);
2804  processStateMutations(actions);
2805  EXPECT_EQ(state_.state(), StateEnum::ExpectingFinished);
2806  EXPECT_EQ(state_.pskType(), PskType::Resumption);
2807  EXPECT_EQ(state_.earlyDataType(), EarlyDataType::NotAttempted);
2808 }
2809 
2810 TEST_F(ServerProtocolTest, TestClientHelloAcceptEarlyDataWithValidAppToken) {
2811  acceptEarlyData();
2812  setUpExpectingClientHello();
2813  auto validator = std::make_unique<MockAppTokenValidator>();
2814  auto validatorPtr = validator.get();
2815  state_.appTokenValidator() = std::move(validator);
2816 
2817  std::string appTokenStr("appToken");
2818 
2819  EXPECT_CALL(*validatorPtr, validate(_))
2820  .WillOnce(Invoke([&appTokenStr](const ResumptionState& resumptionState) {
2822  resumptionState.appToken, IOBuf::copyBuffer(appTokenStr)));
2823  return true;
2824  }));
2825  EXPECT_CALL(*mockTicketCipher_, _decrypt(_))
2826  .WillOnce(InvokeWithoutArgs([=]() {
2827  ResumptionState res;
2830  res.resumptionSecret = folly::IOBuf::copyBuffer("resumesecret");
2831  res.alpn = "h2";
2832  res.ticketAgeAdd = 0xffffffff;
2833  res.ticketIssueTime =
2834  std::chrono::system_clock::now() - std::chrono::seconds(100);
2835  res.appToken = IOBuf::copyBuffer(appTokenStr);
2836  return std::make_pair(PskType::Resumption, std::move(res));
2837  }));
2838 
2839  auto actions = getActions(
2841  expectActions<MutateState, WriteToSocket, ReportEarlyHandshakeSuccess>(
2842  actions);
2843  processStateMutations(actions);
2844  EXPECT_EQ(state_.state(), StateEnum::AcceptingEarlyData);
2845  EXPECT_EQ(state_.pskType(), PskType::Resumption);
2846  EXPECT_EQ(state_.earlyDataType(), EarlyDataType::Accepted);
2847  EXPECT_EQ(state_.replayCacheResult(), ReplayCacheResult::NotReplay);
2848 }
2849 
2850 TEST_F(ServerProtocolTest, TestClientHelloRejectEarlyData) {
2851  setUpExpectingClientHello();
2852 
2854  EXPECT_CALL(*factory_, makeEncryptedReadRecordLayer(_))
2855  .WillOnce(InvokeWithoutArgs(
2856  [rrl]() { return std::unique_ptr<EncryptedReadRecordLayer>(rrl); }));
2857  EXPECT_CALL(*rrl, setSkipFailedDecryption(true));
2858 
2859  auto actions = getActions(
2861  expectActions<MutateState, WriteToSocket>(actions);
2862  processStateMutations(actions);
2863  EXPECT_EQ(state_.state(), StateEnum::ExpectingFinished);
2864  EXPECT_EQ(state_.readRecordLayer().get(), rrl);
2865  EXPECT_EQ(state_.pskType(), PskType::Resumption);
2866  EXPECT_EQ(state_.earlyDataType(), EarlyDataType::Rejected);
2867  EXPECT_FALSE(state_.earlyExporterMasterSecret().hasValue());
2868  EXPECT_EQ(
2869  state_.readRecordLayer()->getEncryptionLevel(),
2871 }
2872 
2873 TEST_F(ServerProtocolTest, TestClientHelloHrrRejectEarlyData) {
2874  acceptEarlyData();
2875  context_->setSupportedGroups({NamedGroup::secp256r1, NamedGroup::x25519});
2876  setUpExpectingClientHello();
2877 
2878  auto rrl = new MockPlaintextReadRecordLayer();
2879  EXPECT_CALL(*factory_, makePlaintextReadRecordLayer())
2880  .WillOnce(Invoke(
2881  [rrl]() { return std::unique_ptr<PlaintextReadRecordLayer>(rrl); }));
2882  EXPECT_CALL(*rrl, setSkipEncryptedRecords(true));
2883 
2884  auto actions = getActions(
2886  expectActions<MutateState, WriteToSocket>(actions);
2887  processStateMutations(actions);
2888  EXPECT_EQ(state_.state(), StateEnum::ExpectingClientHello);
2889  EXPECT_EQ(state_.readRecordLayer().get(), rrl);
2890  EXPECT_EQ(state_.earlyDataType(), EarlyDataType::Rejected);
2891  EXPECT_FALSE(state_.earlyExporterMasterSecret().hasValue());
2892  EXPECT_EQ(
2893  state_.readRecordLayer()->getEncryptionLevel(),
2895  EXPECT_EQ(
2896  state_.writeRecordLayer()->getEncryptionLevel(),
2898 }
2899 
2900 TEST_F(ServerProtocolTest, TestClientHelloCookieRejectEarlyData) {
2901  acceptEarlyData();
2902  expectCookie();
2903  setUpExpectingClientHello();
2904 
2906  chlo.extensions.push_back(encodeExtension(ClientEarlyData()));
2907  Cookie c;
2908  c.cookie = IOBuf::copyBuffer("cookie");
2909  chlo.extensions.push_back(encodeExtension(std::move(c)));
2911 
2912  auto actions = getActions(detail::processEvent(state_, std::move(chlo)));
2913  expectActions<MutateState, WriteToSocket>(actions);
2914  processStateMutations(actions);
2915  EXPECT_EQ(state_.state(), StateEnum::ExpectingFinished);
2916  EXPECT_EQ(state_.pskType(), PskType::Resumption);
2917  EXPECT_EQ(state_.earlyDataType(), EarlyDataType::Rejected);
2918  EXPECT_EQ(
2919  state_.readRecordLayer()->getEncryptionLevel(),
2921  EXPECT_EQ(
2922  state_.writeRecordLayer()->getEncryptionLevel(),
2924 }
2925 
2926 TEST_F(ServerProtocolTest, TestClientHelloRejectEarlyDataPskRejected) {
2927  acceptEarlyData();
2928  setUpExpectingClientHello();
2929 
2930  EXPECT_CALL(*mockTicketCipher_, _decrypt(_)).WillOnce(InvokeWithoutArgs([]() {
2931  return std::make_pair(PskType::Rejected, none);
2932  }));
2933 
2934  auto actions = getActions(
2936  expectActions<MutateState, WriteToSocket>(actions);
2937  processStateMutations(actions);
2938  EXPECT_EQ(state_.state(), StateEnum::ExpectingFinished);
2939  EXPECT_EQ(state_.pskType(), PskType::Rejected);
2940  EXPECT_EQ(state_.earlyDataType(), EarlyDataType::Rejected);
2941  EXPECT_EQ(
2942  state_.readRecordLayer()->getEncryptionLevel(),
2944  EXPECT_EQ(
2945  state_.writeRecordLayer()->getEncryptionLevel(),
2947 }
2948 
2949 TEST_F(ServerProtocolTest, TestClientHelloRejectEarlyDataReplayCache) {
2950  acceptEarlyData();
2951  setUpExpectingClientHello();
2952 
2953  EXPECT_CALL(*replayCache_, check(_)).WillOnce(InvokeWithoutArgs([] {
2955  }));
2956 
2957  auto actions = getActions(
2959  expectActions<MutateState, WriteToSocket>(actions);
2960  processStateMutations(actions);
2961  EXPECT_EQ(state_.state(), StateEnum::ExpectingFinished);
2962  EXPECT_EQ(state_.pskType(), PskType::Resumption);
2963  EXPECT_EQ(state_.earlyDataType(), EarlyDataType::Rejected);
2964  EXPECT_EQ(state_.replayCacheResult(), ReplayCacheResult::DefinitelyReplay);
2965 }
2966 
2967 TEST_F(ServerProtocolTest, TestClientHelloRejectEarlyDataNoAlpn) {
2968  acceptEarlyData();
2969  setUpExpectingClientHello();
2970 
2974 
2975  auto actions = getActions(detail::processEvent(state_, std::move(chlo)));
2976  expectActions<MutateState, WriteToSocket>(actions);
2977  processStateMutations(actions);
2978  EXPECT_EQ(state_.state(), StateEnum::ExpectingFinished);
2979  EXPECT_EQ(state_.pskType(), PskType::Resumption);
2980  EXPECT_EQ(state_.earlyDataType(), EarlyDataType::Rejected);
2981 }
2982 
2983 TEST_F(ServerProtocolTest, TestClientHelloRejectEarlyDataDiffAlpn) {
2984  acceptEarlyData();
2985  setUpExpectingClientHello();
2986 
2991  ProtocolName h2;
2992  h2.name = folly::IOBuf::copyBuffer("h3");
2993  alpn.protocol_name_list.push_back(std::move(h2));
2994  chlo.extensions.push_back(encodeExtension(std::move(alpn)));
2995  chlo.extensions.push_back(encodeExtension(ClientEarlyData()));
2997 
2998  auto actions = getActions(detail::processEvent(state_, std::move(chlo)));
2999  expectActions<MutateState, WriteToSocket>(actions);
3000  processStateMutations(actions);
3001  EXPECT_EQ(state_.state(), StateEnum::ExpectingFinished);
3002  EXPECT_EQ(state_.pskType(), PskType::Resumption);
3003  EXPECT_EQ(state_.earlyDataType(), EarlyDataType::Rejected);
3004 }
3005 
3006 TEST_F(ServerProtocolTest, TestClientHelloRejectEarlyDataAfterHrr) {
3007  acceptEarlyData();
3008  setUpExpectingClientHelloRetry();
3009 
3010  auto actions = getActions(
3012  expectActions<MutateState, WriteToSocket>(actions);
3013  processStateMutations(actions);
3014  EXPECT_EQ(state_.state(), StateEnum::ExpectingFinished);
3015  EXPECT_EQ(state_.pskType(), PskType::Resumption);
3016  EXPECT_EQ(state_.earlyDataType(), EarlyDataType::Rejected);
3017 }
3018 
3019 TEST_F(ServerProtocolTest, TestClientHelloRejectEarlyDataClockBehind) {
3020  context_->setEarlyDataSettings(
3021  true,
3022  {std::chrono::milliseconds(-10), std::chrono::milliseconds(10)},
3023  replayCache_);
3024  setUpExpectingClientHello();
3025 
3027  chlo.extensions.push_back(encodeExtension(ClientEarlyData()));
3028  TestMessages::addPsk(chlo, 1000);
3029 
3030  auto actions = getActions(detail::processEvent(state_, std::move(chlo)));
3031  expectActions<MutateState, WriteToSocket>(actions);
3032  processStateMutations(actions);
3033  EXPECT_EQ(state_.state(), StateEnum::ExpectingFinished);
3034  EXPECT_EQ(state_.pskType(), PskType::Resumption);
3035  EXPECT_EQ(state_.earlyDataType(), EarlyDataType::Rejected);
3036  EXPECT_LT(*state_.clientClockSkew(), std::chrono::milliseconds(-5000));
3037 }
3038 
3039 TEST_F(ServerProtocolTest, TestClientHelloRejectEarlyDataClockAhead) {
3040  context_->setEarlyDataSettings(
3041  true,
3042  {std::chrono::milliseconds(-10), std::chrono::milliseconds(10)},
3043  replayCache_);
3044  setUpExpectingClientHello();
3045 
3047  chlo.extensions.push_back(encodeExtension(ClientEarlyData()));
3048  TestMessages::addPsk(chlo, 200000);
3049 
3050  auto actions = getActions(detail::processEvent(state_, std::move(chlo)));
3051  expectActions<MutateState, WriteToSocket>(actions);
3052  processStateMutations(actions);
3053  EXPECT_EQ(state_.state(), StateEnum::ExpectingFinished);
3054  EXPECT_EQ(state_.pskType(), PskType::Resumption);
3055  EXPECT_EQ(state_.earlyDataType(), EarlyDataType::Rejected);
3056  EXPECT_GT(*state_.clientClockSkew(), std::chrono::milliseconds(5000));
3057 }
3058 
3059 TEST_F(ServerProtocolTest, TestClientHelloRejectEarlyDataTicketAgeOverflow) {
3060  acceptEarlyData();
3061  setUpExpectingClientHello();
3062 
3063  EXPECT_CALL(*mockTicketCipher_, _decrypt(_))
3064  .WillOnce(InvokeWithoutArgs([=]() {
3065  ResumptionState res;
3068  res.resumptionSecret = folly::IOBuf::copyBuffer("resumesecret");
3069  res.alpn = "h2";
3070  res.ticketAgeAdd = 0xffffffff;
3071  res.ticketIssueTime =
3072  std::chrono::system_clock::now() - std::chrono::seconds(100);
3073  return std::make_pair(PskType::Resumption, std::move(res));
3074  }));
3075 
3077  chlo.extensions.push_back(encodeExtension(ClientEarlyData()));
3078  TestMessages::addPsk(chlo, 2000000);
3079 
3080  auto actions = getActions(detail::processEvent(state_, std::move(chlo)));
3081  expectActions<MutateState, WriteToSocket>(actions);
3082  processStateMutations(actions);
3083  EXPECT_EQ(state_.state(), StateEnum::ExpectingFinished);
3084  EXPECT_EQ(state_.pskType(), PskType::Resumption);
3085  EXPECT_EQ(state_.earlyDataType(), EarlyDataType::Rejected);
3086  EXPECT_GT(*state_.clientClockSkew(), std::chrono::milliseconds(5000));
3087 }
3088 
3089 TEST_F(ServerProtocolTest, TestClientHelloRejectEarlyDataNegativeExpectedAge) {
3090  acceptEarlyData();
3091  setUpExpectingClientHello();
3092 
3093  EXPECT_CALL(*mockTicketCipher_, _decrypt(_))
3094  .WillOnce(InvokeWithoutArgs([=]() {
3095  ResumptionState res;
3098  res.resumptionSecret = folly::IOBuf::copyBuffer("resumesecret");
3099  res.alpn = "h2";
3100  res.ticketAgeAdd = 0;
3101  res.ticketIssueTime =
3102  std::chrono::system_clock::now() + std::chrono::seconds(100);
3103  return std::make_pair(PskType::Resumption, std::move(res));
3104  }));
3105 
3107  chlo.extensions.push_back(encodeExtension(ClientEarlyData()));
3108  TestMessages::addPsk(chlo, 2000000);
3109 
3110  auto actions = getActions(detail::processEvent(state_, std::move(chlo)));
3111  expectActions<MutateState, WriteToSocket>(actions);
3112  processStateMutations(actions);
3113  EXPECT_EQ(state_.state(), StateEnum::ExpectingFinished);
3114  EXPECT_EQ(state_.pskType(), PskType::Resumption);
3115  EXPECT_EQ(state_.earlyDataType(), EarlyDataType::Rejected);
3116  EXPECT_GT(*state_.clientClockSkew(), std::chrono::milliseconds(5000));
3117 }
3118 
3119 TEST_F(ServerProtocolTest, TestClientHelloRejectEarlyDataInvalidAppToken) {
3120  acceptEarlyData();
3121  setUpExpectingClientHello();
3122  auto validator = std::make_unique<MockAppTokenValidator>();
3123  auto validatorPtr = validator.get();
3124  state_.appTokenValidator() = std::move(validator);
3125 
3126  std::string appTokenStr("appToken");
3127 
3128  EXPECT_CALL(*validatorPtr, validate(_))
3129  .WillOnce(Invoke([&appTokenStr](const ResumptionState& resumptionState) {
3131  resumptionState.appToken, IOBuf::copyBuffer(appTokenStr)));
3132  return false;
3133  }));
3134 
3135  EXPECT_CALL(*mockTicketCipher_, _decrypt(_))
3136  .WillOnce(InvokeWithoutArgs([=]() {
3137  ResumptionState res;
3140  res.resumptionSecret = folly::IOBuf::copyBuffer("resumesecret");
3141  res.alpn = "h2";
3142  res.ticketAgeAdd = 0xffffffff;
3143  res.ticketIssueTime =
3144  std::chrono::system_clock::now() - std::chrono::seconds(100);
3145  res.appToken = IOBuf::copyBuffer(appTokenStr);
3146  return std::make_pair(PskType::Resumption, std::move(res));
3147  }));
3148 
3149  auto actions = getActions(
3151  expectActions<MutateState, WriteToSocket>(actions);
3152  processStateMutations(actions);
3153  EXPECT_EQ(state_.state(), StateEnum::ExpectingFinished);
3154  EXPECT_EQ(state_.pskType(), PskType::Resumption);
3155  EXPECT_EQ(state_.earlyDataType(), EarlyDataType::Rejected);
3156 }
3157 
3158 TEST_F(ServerProtocolTest, TestClientHelloHandshakeLogging) {
3159  setUpExpectingClientHello();
3160  state_.handshakeLogging() = std::make_unique<HandshakeLogging>();
3161  auto actions =
3162  getActions(detail::processEvent(state_, TestMessages::clientHello()));
3163  processStateMutations(actions);
3164  EXPECT_EQ(
3165  state_.handshakeLogging()->clientLegacyVersion, ProtocolVersion::tls_1_2);
3166  EXPECT_EQ(
3167  state_.handshakeLogging()->clientSupportedVersions,
3168  std::vector<ProtocolVersion>({TestProtocolVersion}));
3169  EXPECT_EQ(
3170  state_.handshakeLogging()->clientCiphers,
3171  std::vector<CipherSuite>({CipherSuite::TLS_AES_128_GCM_SHA256,
3173  EXPECT_EQ(
3174  state_.handshakeLogging()->clientExtensions,
3175  std::vector<ExtensionType>(
3183  EXPECT_EQ(
3184  state_.handshakeLogging()->clientSignatureAlgorithms,
3185  std::vector<SignatureScheme>({SignatureScheme::ecdsa_secp256r1_sha256,
3187  EXPECT_EQ(*state_.handshakeLogging()->clientSessionIdSent, false);
3188  EXPECT_TRUE(state_.handshakeLogging()->clientRandom.hasValue());
3189 }
3190 
3191 TEST_F(ServerProtocolTest, TestClientHelloHandshakeLoggingError) {
3192  setUpExpectingClientHello();
3193  state_.handshakeLogging() = std::make_unique<HandshakeLogging>();
3194  ClientHello chlo;
3195  chlo.legacy_version = static_cast<ProtocolVersion>(0x0301);
3196  auto actions = getActions(detail::processEvent(state_, std::move(chlo)));
3197  EXPECT_EQ(
3198  state_.handshakeLogging()->clientLegacyVersion,
3199  static_cast<ProtocolVersion>(0x0301));
3200 }
3201 
3202 TEST_F(ServerProtocolTest, TestClientHelloNoCompressionMethods) {
3203  setUpExpectingClientHello();
3205  chlo.legacy_compression_methods.clear();
3206  auto actions = getActions(detail::processEvent(state_, std::move(chlo)));
3207  expectError<FizzException>(
3208  actions, AlertDescription::illegal_parameter, "compression methods");
3209 }
3210 
3211 TEST_F(ServerProtocolTest, TestClientHelloDuplicateExtensions) {
3212  setUpExpectingClientHello();
3214  chlo.extensions.push_back(encodeExtension(SupportedGroups()));
3215  auto actions = getActions(detail::processEvent(state_, std::move(chlo)));
3216  expectError<FizzException>(
3217  actions, AlertDescription::illegal_parameter, "duplicate extension");
3218 }
3219 
3220 TEST_F(ServerProtocolTest, TestClientHelloDuplicateGroups) {
3221  setUpExpectingClientHello();
3224 
3225  ClientKeyShare keyShare;
3226  KeyShareEntry entry1, entry2;
3227 
3228  entry1.group = NamedGroup::x25519;
3229  entry1.key_exchange = folly::IOBuf::copyBuffer("keyshare");
3230  keyShare.client_shares.push_back(std::move(entry1));
3231 
3232  entry2.group = NamedGroup::x25519;
3233  entry2.key_exchange = folly::IOBuf::copyBuffer("keyshare");
3234  keyShare.client_shares.push_back(std::move(entry2));
3235 
3236  chlo.extensions.push_back(encodeExtension(std::move(keyShare)));
3237 
3238  auto actions = getActions(detail::processEvent(state_, std::move(chlo)));
3239  expectError<FizzException>(
3240  actions,
3242  "duplicate client key share");
3243 }
3244 
3245 TEST_F(ServerProtocolTest, TestRetryClientHelloStillNoKeyShare) {
3246  setUpExpectingClientHelloRetry();
3247  auto clientHello = TestMessages::clientHello();
3249  ClientKeyShare keyShare;
3250  clientHello.extensions.push_back(encodeExtension(std::move(keyShare)));
3251  auto actions =
3252  getActions(detail::processEvent(state_, std::move(clientHello)));
3253  expectError<FizzException>(
3254  actions, AlertDescription::illegal_parameter, "key share not found");
3255 }
3256 
3257 TEST_F(ServerProtocolTest, TestRetryClientHelloCookie) {
3258  setUpExpectingClientHelloRetry();
3259  expectCookie();
3260  auto clientHello = TestMessages::clientHello();
3261  Cookie c;
3262  c.cookie = IOBuf::copyBuffer("cookie");
3263  clientHello.extensions.push_back(encodeExtension(std::move(c)));
3264  auto actions =
3265  getActions(detail::processEvent(state_, std::move(clientHello)));
3266  expectError<FizzException>(
3267  actions,
3269  "cookie after statefull hrr");
3270 }
3271 
3272 TEST_F(ServerProtocolTest, TestRetryClientHelloDifferentVersion) {
3273  context_->setVersionFallbackEnabled(true);
3274  setUpExpectingClientHelloRetry();
3275  auto clientHello = TestMessages::clientHello();
3277  auto actions =
3278  getActions(detail::processEvent(state_, std::move(clientHello)));
3279  expectError<FizzException>(
3280  actions,
3282  "version mismatch with previous negotiation");
3283 }
3284 
3285 TEST_F(ServerProtocolTest, TestClientHelloRenegotiatePskCipher) {
3286  setUpExpectingClientHello();
3287 
3288  EXPECT_CALL(*mockTicketCipher_, _decrypt(_))
3289  .WillOnce(InvokeWithoutArgs([=]() {
3290  ResumptionState res;
3293  res.resumptionSecret = folly::IOBuf::copyBuffer("resumesecret");
3294  res.alpn = "h2";
3295  res.ticketAgeAdd = 0;
3296  res.ticketIssueTime =
3297  std::chrono::system_clock::now() + std::chrono::seconds(100);
3298  return std::make_pair(PskType::Resumption, std::move(res));
3299  }));
3300 
3301  auto actions =
3302  getActions(detail::processEvent(state_, TestMessages::clientHelloPsk()));
3303  expectActions<MutateState, WriteToSocket>(actions);
3304  processStateMutations(actions);
3305  EXPECT_EQ(state_.state(), StateEnum::ExpectingFinished);
3306  EXPECT_EQ(state_.pskType(), PskType::Resumption);
3308 }
3309 
3310 TEST_F(ServerProtocolTest, TestClientHelloRenegotiatePskCipherIncompatible) {
3311  setUpExpectingClientHello();
3312 
3313  EXPECT_CALL(*mockTicketCipher_, _decrypt(_))
3314  .WillOnce(InvokeWithoutArgs([=]() {
3315  ResumptionState res;
3318  res.resumptionSecret = folly::IOBuf::copyBuffer("resumesecret");
3319  res.alpn = "h2";
3320  res.ticketAgeAdd = 0;
3321  res.ticketIssueTime =
3322  std::chrono::system_clock::now() + std::chrono::seconds(100);
3323  return std::make_pair(PskType::Resumption, std::move(res));
3324  }));
3325 
3326  auto actions =
3327  getActions(detail::processEvent(state_, TestMessages::clientHelloPsk()));
3328  expectActions<MutateState, WriteToSocket>(actions);
3329  processStateMutations(actions);
3330  EXPECT_EQ(state_.state(), StateEnum::ExpectingFinished);
3331  EXPECT_EQ(state_.pskType(), PskType::Rejected);
3333 }
3334 
3335 TEST_F(ServerProtocolTest, TestClientHelloCookie) {
3336  expectCookie();
3337  setUpExpectingClientHello();
3338 
3340  Cookie c;
3341  c.cookie = IOBuf::copyBuffer("cookie");
3342  chlo.extensions.push_back(encodeExtension(std::move(c)));
3343 
3344  auto actions = getActions(detail::processEvent(state_, std::move(chlo)));
3345  expectActions<MutateState, WriteToSocket>(actions);
3346  processStateMutations(actions);
3347  EXPECT_EQ(state_.state(), StateEnum::ExpectingFinished);
3349 }
3350 
3351 TEST_F(ServerProtocolTest, TestClientHelloCookieFail) {
3352  expectCookie();
3353  setUpExpectingClientHello();
3354 
3356  Cookie c;
3357  c.cookie = IOBuf::copyBuffer("xyz");
3358  chlo.extensions.push_back(encodeExtension(std::move(c)));
3359 
3360  auto actions = getActions(detail::processEvent(state_, std::move(chlo)));
3361  expectError<FizzException>(
3362  actions, AlertDescription::decrypt_error, "decrypt cookie");
3363 }
3364 
3365 TEST_F(ServerProtocolTest, TestClientHelloCookieNoCipher) {
3366  setUpExpectingClientHello();
3367 
3369  Cookie c;
3370  c.cookie = IOBuf::copyBuffer("cookie");
3371  chlo.extensions.push_back(encodeExtension(std::move(c)));
3372 
3373  auto actions = getActions(detail::processEvent(state_, std::move(chlo)));
3374  expectError<FizzException>(
3375  actions, AlertDescription::unsupported_extension, "no cookie cipher");
3376 }
3377 
3378 TEST_F(ServerProtocolTest, TestClientHelloCookieVersionMismatch) {
3379  setUpExpectingClientHello();
3380  acceptCookies();
3381 
3382  EXPECT_CALL(*mockCookieCipher_, _decrypt(_)).WillOnce(Invoke([](Buf& cookie) {
3383  EXPECT_TRUE(IOBufEqualTo()(cookie, IOBuf::copyBuffer("cookie")));
3384  CookieState cs;
3387  cs.chloHash = IOBuf::copyBuffer("chlohash");
3388  cs.appToken = IOBuf::create(0);
3390  }));
3391 
3393  Cookie c;
3394  c.cookie = IOBuf::copyBuffer("cookie");
3395  chlo.extensions.push_back(encodeExtension(std::move(c)));
3396 
3397  auto actions = getActions(detail::processEvent(state_, std::move(chlo)));
3398  expectError<FizzException>(
3399  actions,
3401  "version mismatch with cookie");
3402 }
3403 
3404 TEST_F(ServerProtocolTest, TestClientHelloCookieCipherMismatch) {
3405  setUpExpectingClientHello();
3406  acceptCookies();
3407 
3408  EXPECT_CALL(*mockCookieCipher_, _decrypt(_)).WillOnce(Invoke([](Buf& cookie) {
3409  EXPECT_TRUE(IOBufEqualTo()(cookie, IOBuf::copyBuffer("cookie")));
3410  CookieState cs;
3413  cs.chloHash = IOBuf::copyBuffer("chlohash");
3414  cs.appToken = IOBuf::create(0);
3416  }));
3417 
3419  Cookie c;
3420  c.cookie = IOBuf::copyBuffer("cookie");
3421  chlo.extensions.push_back(encodeExtension(std::move(c)));
3422 
3423  auto actions = getActions(detail::processEvent(state_, std::move(chlo)));
3424  expectError<FizzException>(
3425  actions,
3427  "cipher mismatch with cookie");
3428 }
3429 
3430 TEST_F(ServerProtocolTest, TestClientHelloCookieGroupMismatch) {
3431  setUpExpectingClientHello();
3432  acceptCookies();
3433 
3434  EXPECT_CALL(*mockCookieCipher_, _decrypt(_)).WillOnce(Invoke([](Buf& cookie) {
3435  EXPECT_TRUE(IOBufEqualTo()(cookie, IOBuf::copyBuffer("cookie")));
3436  CookieState cs;
3440  cs.chloHash = IOBuf::copyBuffer("chlohash");
3441  cs.appToken = IOBuf::create(0);
3443  }));
3444 
3446  Cookie c;
3447  c.cookie = IOBuf::copyBuffer("cookie");
3448  chlo.extensions.push_back(encodeExtension(std::move(c)));
3449 
3450  auto actions = getActions(detail::processEvent(state_, std::move(chlo)));
3451  expectError<FizzException>(
3452  actions,
3454  "group mismatch with cookie");
3455 }
3456 
3457 TEST_F(ServerProtocolTest, TestClientHelloCookieNoGroup) {
3458  expectCookie();
3459  setUpExpectingClientHello();
3460 
3462  Cookie c;
3463  c.cookie = IOBuf::copyBuffer("cookie");
3464  chlo.extensions.push_back(encodeExtension(std::move(c)));
3466  ClientKeyShare keyShare;
3467  chlo.extensions.push_back(encodeExtension(std::move(keyShare)));
3468 
3469  auto actions = getActions(detail::processEvent(state_, std::move(chlo)));
3470  expectError<FizzException>(
3471  actions, AlertDescription::illegal_parameter, "key share not found");
3472 }
3473 
3474 TEST_F(ServerProtocolTest, TestNoCertCompressionAlgorithmMatch) {
3475  setUpExpectingClientHello();
3476  context_->setSupportedCompressionAlgorithms(
3480  algos.algorithms = {static_cast<CertificateCompressionAlgorithm>(0xfb)};
3481  chlo.extensions.push_back(encodeExtension(algos));
3482  auto actions = getActions(detail::processEvent(state_, std::move(chlo)));
3483  expectActions<MutateState, WriteToSocket>(actions);
3484  processStateMutations(actions);
3485  EXPECT_EQ(state_.state(), StateEnum::ExpectingFinished);
3486  EXPECT_EQ(state_.serverCertCompAlgo(), folly::none);
3487 }
3488 
3489 TEST_F(ServerProtocolTest, TestCertCompressionRequestedNotSupported) {
3490  setUpExpectingClientHello();
3493  algos.algorithms = {static_cast<CertificateCompressionAlgorithm>(0xfb)};
3494  chlo.extensions.push_back(encodeExtension(algos));
3495  auto actions = getActions(detail::processEvent(state_, std::move(chlo)));
3496  expectActions<MutateState, WriteToSocket>(actions);
3497  processStateMutations(actions);
3498  EXPECT_EQ(state_.state(), StateEnum::ExpectingFinished);
3499  EXPECT_EQ(state_.serverCertCompAlgo(), folly::none);
3500 }
3501 
3502 TEST_F(ServerProtocolTest, TestEarlyAppData) {
3503  setUpAcceptingEarlyData();
3504 
3505  auto actions =
3506  getActions(detail::processEvent(state_, TestMessages::appData()));
3507 
3508  expectSingleAction<DeliverAppData>(std::move(actions));
3509 }
3510 
3511 TEST_F(ServerProtocolTest, TestEarlyAppWrite) {
3512  setUpAcceptingEarlyData();
3513  EXPECT_CALL(*mockWrite_, _write(_)).WillOnce(Invoke([&](TLSMessage& msg) {
3514  TLSContent content;
3515  content.contentType = msg.type;
3516  content.encryptionLevel = mockWrite_->getEncryptionLevel();
3518  EXPECT_TRUE(IOBufEqualTo()(msg.fragment, IOBuf::copyBuffer("appdata")));
3519  content.data = IOBuf::copyBuffer("writtenappdata");
3520  return content;
3521  }));
3522 
3523  auto actions =
3524  getActions(detail::processEvent(state_, TestMessages::appWrite()));
3525 
3526  auto write = expectSingleAction<WriteToSocket>(std::move(actions));
3528  write.contents[0].data, IOBuf::copyBuffer("writtenappdata")));
3529 }
3530 
3531 TEST_F(ServerProtocolTest, TestEndOfEarlyData) {
3532  setUpAcceptingEarlyData();
3533  auto handshakeReadRecordLayer = state_.handshakeReadRecordLayer().get();
3534 
3535  EXPECT_CALL(
3536  *mockHandshakeContext_, appendToTranscript(BufMatches("eoedencoding")));
3537 
3538  auto actions =
3539  getActions(detail::processEvent(state_, TestMessages::endOfEarlyData()));
3540  expectActions<MutateState>(actions);
3541  processStateMutations(actions);
3542  EXPECT_EQ(state_.state(), StateEnum::ExpectingFinished);
3543  EXPECT_EQ(state_.readRecordLayer().get(), handshakeReadRecordLayer);
3544  EXPECT_EQ(state_.writeRecordLayer().get(), mockWrite_);
3545  EXPECT_EQ(
3546  state_.readRecordLayer()->getEncryptionLevel(),
3548 }
3549 
3550 TEST_F(ServerProtocolTest, TestEndOfEarlyDataExtraData) {
3551  setUpAcceptingEarlyData();
3552 
3553  EXPECT_CALL(*mockRead_, hasUnparsedHandshakeData())
3554  .WillRepeatedly(Return(true));
3555 
3556  auto actions =
3557  getActions(detail::processEvent(state_, TestMessages::endOfEarlyData()));
3558  expectError<FizzException>(
3559  actions, AlertDescription::unexpected_message, "data after eoed");
3560 }
3561 
3562 TEST_F(ServerProtocolTest, TestFullHandshakeFinished) {
3563  setUpExpectingFinished();
3564  Sequence contextSeq;
3565  EXPECT_CALL(
3566  *mockHandshakeContext_, getFinishedData(RangeMatches("clihandsec")))
3567  .InSequence(contextSeq)
3568  .WillOnce(
3569  InvokeWithoutArgs([]() { return IOBuf::copyBuffer("verifydata"); }));
3570  EXPECT_CALL(*mockHandshakeContext_, getHandshakeContext())
3571  .InSequence(contextSeq)
3572  .WillRepeatedly(
3573  Invoke([]() { return IOBuf::copyBuffer("sfincontext"); }));
3574  EXPECT_CALL(
3575  *mockHandshakeContext_,
3576  appendToTranscript(BufMatches("finishedencoding")))
3577  .InSequence(contextSeq);
3578  EXPECT_CALL(*mockHandshakeContext_, getHandshakeContext())
3579  .InSequence(contextSeq)
3580  .WillRepeatedly(
3581  Invoke([]() { return IOBuf::copyBuffer("clifincontext"); }));
3582  EXPECT_CALL(
3583  *mockKeyScheduler_,
3584  getSecret(MasterSecrets::ResumptionMaster, RangeMatches("clifincontext")))
3585  .WillOnce(InvokeWithoutArgs([]() {
3586  return std::vector<uint8_t>({'r', 's', 'e', 'c'});
3587  }));
3588  EXPECT_CALL(
3589  *mockKeyScheduler_, getSecret(AppTrafficSecrets::ClientAppTraffic))
3590  .WillOnce(InvokeWithoutArgs([]() {
3591  return std::vector<uint8_t>({'c', 'a', 't'});
3592  }));
3593  EXPECT_CALL(*mockKeyScheduler_, getTrafficKey(RangeMatches("cat"), _, _))
3594  .WillOnce(InvokeWithoutArgs([]() {
3595  return TrafficKey{IOBuf::copyBuffer("clientkey"),
3596  IOBuf::copyBuffer("clientiv")};
3597  }));
3598  EXPECT_CALL(
3599  *mockKeyScheduler_,
3600  getResumptionSecret(RangeMatches("rsec"), RangeMatches("")))
3601  .WillOnce(
3602  InvokeWithoutArgs([]() { return IOBuf::copyBuffer("derivedrsec"); }));
3603 
3604  MockAead* raead;
3606  expectAeadCreation(&raead, nullptr);
3607  expectEncryptedReadRecordLayerCreation(&rrl, &raead, StringPiece("cat"));
3608  EXPECT_CALL(*factory_, makeTicketAgeAdd()).WillOnce(Return(0x44444444));
3609  EXPECT_CALL(*mockTicketCipher_, _encrypt(_))
3610  .WillOnce(Invoke([=](ResumptionState& resState) {
3614  resState.resumptionSecret, IOBuf::copyBuffer("derivedrsec")));
3615  EXPECT_EQ(resState.serverCert, cert_);
3616  EXPECT_EQ(*resState.alpn, "h2");
3617  EXPECT_EQ(resState.ticketAgeAdd, 0x44444444);
3618  return std::make_pair(
3619  IOBuf::copyBuffer("ticket"), std::chrono::seconds(100));
3620  }));
3621  EXPECT_CALL(*mockWrite_, _write(_)).WillOnce(Invoke([&](TLSMessage& msg) {
3622  TLSContent content;
3623  content.contentType = msg.type;
3624  content.encryptionLevel = mockWrite_->getEncryptionLevel();
3628  content.data = folly::IOBuf::copyBuffer("handshake");
3629  return content;
3630  }));
3631  EXPECT_CALL(*mockKeyScheduler_, clearMasterSecret());
3632 
3633  auto actions =
3634  getActions(detail::processEvent(state_, TestMessages::finished()));
3635 
3636  expectActions<MutateState, ReportHandshakeSuccess, WriteToSocket>(actions);
3637  processStateMutations(actions);
3638  EXPECT_EQ(state_.state(), StateEnum::AcceptingData);
3639  EXPECT_EQ(state_.readRecordLayer().get(), rrl);
3640  EXPECT_EQ(
3641  state_.readRecordLayer()->getEncryptionLevel(),
3643  EXPECT_EQ(state_.writeRecordLayer().get(), mockWrite_);
3644  ASSERT_THAT(state_.resumptionMasterSecret(), ElementsAre('r', 's', 'e', 'c'));
3645 }
3646 
3647 TEST_F(ServerProtocolTest, TestFinishedNoTicket) {
3648  setUpExpectingFinished();
3649  EXPECT_CALL(*mockTicketCipher_, _encrypt(_)).WillOnce(InvokeWithoutArgs([]() {
3650  return none;
3651  }));
3652 
3653  auto actions =
3654  getActions(detail::processEvent(state_, TestMessages::finished()));
3655  expectActions<MutateState, ReportHandshakeSuccess>(actions);
3656  processStateMutations(actions);
3657  EXPECT_EQ(state_.state(), StateEnum::AcceptingData);
3658 }
3659 
3660 TEST_F(ServerProtocolTest, TestFinishedTicketEarly) {
3661  acceptEarlyData();
3662  setUpExpectingFinished();
3663 
3664  EXPECT_CALL(*factory_, makeTicketAgeAdd()).WillOnce(Return(0x44444444));
3665  EXPECT_CALL(*mockWrite_, _write(_)).WillOnce(Invoke([&](TLSMessage& msg) {
3666  TLSContent content;
3667  content.contentType = msg.type;
3668  content.encryptionLevel = mockWrite_->getEncryptionLevel();
3671  TicketEarlyData early;
3672  early.max_early_data_size = 0xffffffff;
3673  nst.extensions.push_back(encodeExtension(std::move(early)));
3675  content.data = folly::IOBuf::copyBuffer("handshake");
3676  return content;
3677  }));
3678 
3679  auto actions =
3680  getActions(detail::processEvent(state_, TestMessages::finished()));
3681  expectActions<MutateState, ReportHandshakeSuccess, WriteToSocket>(actions);
3682  processStateMutations(actions);
3683  EXPECT_EQ(state_.state(), StateEnum::AcceptingData);
3684 }
3685 
3686 TEST_F(ServerProtocolTest, TestFinishedPskNotSupported) {
3687  setUpExpectingFinished();
3688  state_.pskType() = PskType::NotSupported;
3689 
3690  auto actions =
3691  getActions(detail::processEvent(state_, TestMessages::finished()));
3692  expectActions<MutateState, ReportHandshakeSuccess>(actions);
3693  processStateMutations(actions);
3694  EXPECT_EQ(state_.state(), StateEnum::AcceptingData);
3695 }
3696 
3697 TEST_F(ServerProtocolTest, TestFinishedNoAutomaticNewSessionTicket) {
3698  setUpExpectingFinished();
3699  context_->setSendNewSessionTicket(false);
3700 
3701  EXPECT_CALL(*mockKeyScheduler_, clearMasterSecret());
3702  auto actions =
3703  getActions(detail::processEvent(state_, TestMessages::finished()));
3704  expectActions<MutateState, ReportHandshakeSuccess>(actions);
3705  processStateMutations(actions);
3706  EXPECT_EQ(state_.state(), StateEnum::AcceptingData);
3707 }
3708 
3709 TEST_F(ServerProtocolTest, TestFinishedMismatch) {
3710  setUpExpectingFinished();
3711  EXPECT_CALL(
3712  *mockHandshakeContext_, getFinishedData(RangeMatches("clihandsec")))
3713  .WillOnce(InvokeWithoutArgs(
3714  []() { return IOBuf::copyBuffer("wrongverifydata"); }));
3715 
3716  auto actions =
3717  getActions(detail::processEvent(state_, TestMessages::finished()));
3718 
3719  expectError<FizzException>(actions, none, "finished verify failure");
3720 }
3721 
3722 TEST_F(ServerProtocolTest, TestFinishedExtraData) {
3723  setUpExpectingFinished();
3724  EXPECT_CALL(*mockRead_, hasUnparsedHandshakeData())
3725  .WillRepeatedly(Return(true));
3726 
3727  auto actions =
3728  getActions(detail::processEvent(state_, TestMessages::finished()));
3729 
3730  expectError<FizzException>(actions, none, "data after finished");
3731 }
3732 
3733 TEST_F(ServerProtocolTest, TestExpectingFinishedAppWrite) {
3734  setUpExpectingFinished();
3735  EXPECT_CALL(*mockWrite_, _write(_)).WillOnce(Invoke([&](TLSMessage& msg) {
3736  TLSContent content;
3737  content.contentType = msg.type;
3738  content.encryptionLevel = mockWrite_->getEncryptionLevel();
3740  EXPECT_TRUE(IOBufEqualTo()(msg.fragment, IOBuf::copyBuffer("appdata")));
3741  content.data = IOBuf::copyBuffer("writtenappdata");
3742  return content;
3743  }));
3744 
3745  auto actions =
3746  getActions(detail::processEvent(state_, TestMessages::appWrite()));
3747 
3748  auto write = expectSingleAction<WriteToSocket>(std::move(actions));
3750  write.contents[0].data, IOBuf::copyBuffer("writtenappdata")));
3751 }
3752 
3753 TEST_F(ServerProtocolTest, TestWriteNewSessionTicket) {
3754  setUpAcceptingData();
3755  context_->setSendNewSessionTicket(false);
3756  state_.resumptionMasterSecret() = std::vector<uint8_t>({'r', 's', 'e', 'c'});
3757 
3758  EXPECT_CALL(*mockHandshakeContext_, getHandshakeContext())
3759  .WillRepeatedly(
3760  Invoke([]() { return IOBuf::copyBuffer("clifincontext"); }));
3761  EXPECT_CALL(
3762  *mockKeyScheduler_,
3763  getResumptionSecret(RangeMatches("rsec"), RangeMatches("")))
3764  .WillOnce(
3765  InvokeWithoutArgs([]() { return IOBuf::copyBuffer("derivedrsec"); }));
3766 
3767  EXPECT_CALL(*factory_, makeTicketAgeAdd()).WillOnce(Return(0x44444444));
3768  EXPECT_CALL(*mockTicketCipher_, _encrypt(_))
3769  .WillOnce(Invoke([=](ResumptionState& resState) {
3773  resState.resumptionSecret, IOBuf::copyBuffer("derivedrsec")));
3774  EXPECT_EQ(resState.serverCert, cert_);
3775  EXPECT_EQ(*resState.alpn, "h2");
3776  EXPECT_EQ(resState.ticketAgeAdd, 0x44444444);
3777  return std::make_pair(
3778  IOBuf::copyBuffer("ticket"), std::chrono::seconds(100));
3779  }));
3780  auto nstBuf = folly::IOBuf::copyBuffer("nst");
3781  EXPECT_CALL(*appWrite_, _write(_)).WillOnce(Invoke([&](TLSMessage& msg) {
3782  TLSContent content;
3783  content.contentType = msg.type;
3784  content.encryptionLevel = appWrite_->getEncryptionLevel();
3788  content.data = nstBuf->clone();
3789  return content;
3790  }));
3791 
3792  auto actions =
3793  getActions(detail::processEvent(state_, WriteNewSessionTicket()));
3794  auto write = expectSingleAction<WriteToSocket>(std::move(actions));
3795  EXPECT_EQ(write.contents[0].contentType, ContentType::handshake);
3796  EXPECT_EQ(write.contents[0].encryptionLevel, EncryptionLevel::AppTraffic);
3797  EXPECT_TRUE(IOBufEqualTo()(nstBuf, write.contents[0].data));
3798 }
3799 
3800 TEST_F(ServerProtocolTest, TestWriteNewSessionTicketWithTicketEarly) {
3801  acceptEarlyData();
3802  setUpAcceptingData();
3803  context_->setSendNewSessionTicket(false);
3804 
3805  EXPECT_CALL(*appWrite_, _write(_)).WillOnce(Invoke([&](TLSMessage& msg) {
3806  TLSContent content;
3807  content.contentType = msg.type;
3808  content.encryptionLevel = appWrite_->getEncryptionLevel();
3811  TicketEarlyData early;
3812  early.max_early_data_size = 0xffffffff;
3813  nst.extensions.push_back(encodeExtension(std::move(early)));
3815  content.data = folly::IOBuf::copyBuffer("handshake");
3816  return content;
3817  }));
3818 
3819  auto actions =
3820  getActions(detail::processEvent(state_, WriteNewSessionTicket()));
3821  expectSingleAction<WriteToSocket>(std::move(actions));
3822 }
3823 
3824 TEST_F(ServerProtocolTest, TestWriteNewSessionTicketWithAppToken) {
3825  setUpAcceptingData();
3826  context_->setSendNewSessionTicket(false);
3827 
3828  std::string appToken("appToken");
3829 
3830  EXPECT_CALL(*factory_, makeTicketAgeAdd()).WillOnce(Return(0x44444444));
3831  EXPECT_CALL(*mockTicketCipher_, _encrypt(_))
3832  .WillOnce(Invoke([=](ResumptionState& resState) {
3833  EXPECT_EQ(resState.serverCert, cert_);
3834  EXPECT_EQ(*resState.alpn, "h2");
3835  EXPECT_EQ(resState.ticketAgeAdd, 0x44444444);
3836  EXPECT_TRUE(
3837  IOBufEqualTo()(resState.appToken, IOBuf::copyBuffer(appToken)));
3838  return std::make_pair(
3839  IOBuf::copyBuffer("ticket"), std::chrono::seconds(100));
3840  }));
3841 
3843  writeNewSessionTicket.appToken = IOBuf::copyBuffer(appToken);
3844  auto actions = getActions(
3845  detail::processEvent(state_, std::move(writeNewSessionTicket)));
3846  expectSingleAction<WriteToSocket>(std::move(actions));
3847 }
3848 
3851  TestWriteNewSessionTicketWithAppTokenAfterAutomaticSend) {
3852  setUpExpectingFinished();
3853  context_->setSendNewSessionTicket(true);
3854 
3855  // ExpectingFinished -> AcceptingData
3856  EXPECT_CALL(*factory_, makeTicketAgeAdd()).WillOnce(Return(0x44444444));
3857  EXPECT_CALL(*mockTicketCipher_, _encrypt(_))
3858  .WillOnce(Invoke([=](ResumptionState& resState) {
3859  EXPECT_EQ(resState.serverCert, cert_);
3860  EXPECT_EQ(*resState.alpn, "h2");
3861  EXPECT_EQ(resState.ticketAgeAdd, 0x44444444);
3862  EXPECT_FALSE(resState.appToken);
3863  return std::make_pair(
3864  IOBuf::copyBuffer("ticket"), std::chrono::seconds(100));
3865  }));
3866  auto actions =
3867  getActions(detail::processEvent(state_, TestMessages::finished()));
3868  expectActions<MutateState, ReportHandshakeSuccess, WriteToSocket>(actions);
3869  processStateMutations(actions);
3870  EXPECT_EQ(state_.state(), StateEnum::AcceptingData);
3871 
3872  // AcceptingData: WriteNewSessionTicket
3873  std::string appToken("appToken");
3874  EXPECT_CALL(*factory_, makeTicketAgeAdd()).WillOnce(Return(0x44444444));
3875  EXPECT_CALL(*mockTicketCipher_, _encrypt(_))
3876  .WillOnce(Invoke([=](ResumptionState& resState) {
3877  EXPECT_EQ(resState.serverCert, cert_);
3878  EXPECT_EQ(*resState.alpn, "h2");
3879  EXPECT_EQ(resState.ticketAgeAdd, 0x44444444);
3880  EXPECT_TRUE(
3881  IOBufEqualTo()(resState.appToken, IOBuf::copyBuffer(appToken)));
3882  return std::make_pair(
3883  IOBuf::copyBuffer("ticket"), std::chrono::seconds(100));
3884  }));
3886  writeNewSessionTicket.appToken = IOBuf::copyBuffer(appToken);
3887  auto writeNewSessionTicketActions = getActions(
3888  detail::processEvent(state_, std::move(writeNewSessionTicket)));
3889  expectSingleAction<WriteToSocket>(std::move(writeNewSessionTicketActions));
3890 }
3891 
3892 TEST_F(ServerProtocolTest, TestWriteNewSessionTicketNoTicket) {
3893  setUpAcceptingData();
3894  context_->setSendNewSessionTicket(false);
3895 
3896  EXPECT_CALL(*mockTicketCipher_, _encrypt(_)).WillOnce(InvokeWithoutArgs([]() {
3897  return none;
3898  }));
3899 
3900  auto actions =
3901  getActions(detail::processEvent(state_, WriteNewSessionTicket()));
3902  EXPECT_TRUE(actions.empty());
3903 }
3904 
3905 TEST_F(ServerProtocolTest, TestWriteNewSessionTicketPskNotSupported) {
3906  setUpAcceptingData();
3907  context_->setSendNewSessionTicket(false);
3908  state_.pskType() = PskType::NotSupported;
3909 
3910  auto actions =
3911  getActions(detail::processEvent(state_, WriteNewSessionTicket()));
3912  EXPECT_TRUE(actions.empty());
3913 }
3914 
3916  setUpAcceptingData();
3917 
3918  auto actions =
3919  getActions(detail::processEvent(state_, TestMessages::appData()));
3920 
3921  expectSingleAction<DeliverAppData>(std::move(actions));
3922 }
3923 
3924 TEST_F(ServerProtocolTest, TestAppWrite) {
3925  setUpAcceptingData();
3926  EXPECT_CALL(*appWrite_, _write(_)).WillOnce(Invoke([&](TLSMessage& msg) {
3927  TLSContent content;
3928  content.contentType = msg.type;
3929  content.encryptionLevel = appWrite_->getEncryptionLevel();
3931  EXPECT_TRUE(IOBufEqualTo()(msg.fragment, IOBuf::copyBuffer("appdata")));
3932  content.data = IOBuf::copyBuffer("writtenappdata");
3933  return content;
3934  }));
3935 
3936  auto actions =
3937  getActions(detail::processEvent(state_, TestMessages::appWrite()));
3938 
3939  auto write = expectSingleAction<WriteToSocket>(std::move(actions));
3941  write.contents[0].data, IOBuf::copyBuffer("writtenappdata")));
3942  EXPECT_EQ(write.contents[0].encryptionLevel, EncryptionLevel::AppTraffic);
3943  EXPECT_EQ(write.contents[0].contentType, ContentType::application_data);
3944 }
3945 
3946 TEST_F(ServerProtocolTest, TestKeyUpdateNotRequested) {
3947  setUpAcceptingData();
3948  auto actions =
3949  getActions(detail::processEvent(state_, TestMessages::keyUpdate(false)));
3950  expectActions<MutateState>(actions);
3951  EXPECT_EQ(getNumActions<WriteToSocket>(actions, false), 0);
3952 }
3953 
3954 TEST_F(ServerProtocolTest, TestKeyUpdateExtraData) {
3955  setUpAcceptingData();
3956  EXPECT_CALL(*appRead_, hasUnparsedHandshakeData())
3957  .WillRepeatedly(Return(true));
3958  auto actions =
3959  getActions(detail::processEvent(state_, TestMessages::keyUpdate(false)));
3960 
3961  expectError<FizzException>(actions, none, "data after key_update");
3962 }
3963 
3964 TEST_F(ServerProtocolTest, TestKeyUpdateRequest) {
3965  setUpAcceptingData();
3966  EXPECT_CALL(*mockKeyScheduler_, clientKeyUpdate());
3967  EXPECT_CALL(*appRead_, hasUnparsedHandshakeData()).WillOnce(Return(false));
3968 
3969  EXPECT_CALL(
3970  *mockKeyScheduler_, getSecret(AppTrafficSecrets::ClientAppTraffic))
3971  .WillOnce(InvokeWithoutArgs([]() {
3972  return std::vector<uint8_t>({'c', 'a', 't'});
3973  }));
3974 
3975  EXPECT_CALL(*appWrite_, _write(_)).WillOnce(Invoke([&](TLSMessage& msg) {
3976  TLSContent content;
3977  content.contentType = msg.type;
3978  content.encryptionLevel = appWrite_->getEncryptionLevel();
3982  content.data = folly::IOBuf::copyBuffer("keyupdated");
3983  return content;
3984  }));
3985 
3986  EXPECT_CALL(*mockKeyScheduler_, serverKeyUpdate());
3987  EXPECT_CALL(
3988  *mockKeyScheduler_, getSecret(AppTrafficSecrets::ServerAppTraffic))
3989  .WillOnce(InvokeWithoutArgs([]() {
3990  return std::vector<uint8_t>({'s', 'a', 't'});
3991  }));
3992 
3993  EXPECT_CALL(*mockKeyScheduler_, getTrafficKey(RangeMatches("cat"), _, _))
3994  .WillOnce(InvokeWithoutArgs([]() {
3995  return TrafficKey{IOBuf::copyBuffer("clientkey"),
3996  IOBuf::copyBuffer("clientiv")};
3997  }));
3998 
3999  EXPECT_CALL(*mockKeyScheduler_, getTrafficKey(RangeMatches("sat"), _, _))
4000  .WillOnce(InvokeWithoutArgs([]() {
4001  return TrafficKey{IOBuf::copyBuffer("serverkey"),
4002  IOBuf::copyBuffer("serveriv")};
4003  }));
4004 
4005  MockAead* raead;
4006  MockAead* waead;
4009 
4010  expectAeadCreation(&raead, &waead);
4011  expectEncryptedReadRecordLayerCreation(&rrl, &raead, StringPiece("cat"));
4012  expectEncryptedWriteRecordLayerCreation(&wrl, &waead, StringPiece("sat"));
4013  auto actions =
4014  getActions(detail::processEvent(state_, TestMessages::keyUpdate(true)));
4015  expectActions<MutateState, WriteToSocket>(actions);
4016  auto write = expectAction<WriteToSocket>(actions);
4017  EXPECT_TRUE(
4018  IOBufEqualTo()(write.contents[0].data, IOBuf::copyBuffer("keyupdated")));
4019  processStateMutations(actions);
4020  EXPECT_EQ(state_.readRecordLayer().get(), rrl);
4021  EXPECT_EQ(state_.writeRecordLayer().get(), wrl);
4022  EXPECT_EQ(state_.state(), StateEnum::AcceptingData);
4023 }
4024 
4025 TEST_F(ServerProtocolTest, TestCertificate) {
4026  setUpExpectingCertificate();
4027  EXPECT_CALL(
4028  *mockHandshakeContext_, appendToTranscript(BufMatches("certencoding")));
4029  clientLeafCert_ = std::make_shared<MockPeerCert>();
4030  clientIntCert_ = std::make_shared<MockPeerCert>();
4031  EXPECT_CALL(*factory_, _makePeerCert(BufMatches("cert1")))
4032  .WillOnce(Return(clientLeafCert_));
4033  EXPECT_CALL(*factory_, _makePeerCert(BufMatches("cert2")))
4034  .WillOnce(Return(clientIntCert_));
4035 
4037  CertificateEntry entry1;
4038  entry1.cert_data = folly::IOBuf::copyBuffer("cert1");
4039  certificate.certificate_list.push_back(std::move(entry1));
4040  CertificateEntry entry2;
4041  entry2.cert_data = folly::IOBuf::copyBuffer("cert2");
4042  certificate.certificate_list.push_back(std::move(entry2));
4043  auto actions =
4044  getActions(detail::processEvent(state_, std::move(certificate)));
4045 
4046  expectActions<MutateState>(actions);
4047  processStateMutations(actions);
4048  EXPECT_EQ(state_.unverifiedCertChain()->size(), 2);
4049  EXPECT_EQ(state_.unverifiedCertChain()->at(0), clientLeafCert_);
4050  EXPECT_EQ(state_.unverifiedCertChain()->at(1), clientIntCert_);
4051  EXPECT_EQ(state_.state(), StateEnum::ExpectingCertificateVerify);
4052 }
4053 
4054 TEST_F(ServerProtocolTest, TestCertificateNonemptyContext) {
4055  setUpExpectingCertificate();
4056  EXPECT_CALL(
4057  *mockHandshakeContext_, appendToTranscript(BufMatches("certencoding")));
4058 
4059  auto badCertMsg = TestMessages::certificate();
4060  badCertMsg.certificate_request_context =
4061  folly::IOBuf::copyBuffer("garbagecontext");
4062  auto actions =
4063  getActions(detail::processEvent(state_, std::move(badCertMsg)));
4064 
4065  expectError<FizzException>(
4066  actions,
4068  "certificate request context must be empty");
4069 }
4070 
4071 TEST_F(ServerProtocolTest, TestCertificateEmptyForbidden) {
4072  setUpExpectingCertificate();
4073  EXPECT_CALL(
4074  *mockHandshakeContext_, appendToTranscript(BufMatches("certencoding")));
4075 
4076  auto actions =
4077  getActions(detail::processEvent(state_, TestMessages::certificate()));
4078 
4079  expectError<FizzException>(
4080  actions,
4082  "certificate requested but none received");
4083 }
4084 
4085 TEST_F(ServerProtocolTest, TestCertificateEmptyPermitted) {
4086  setUpExpectingCertificate();
4087  context_->setClientAuthMode(ClientAuthMode::Optional);
4088  EXPECT_CALL(
4089  *mockHandshakeContext_, appendToTranscript(BufMatches("certencoding")));
4090 
4091  auto actions =
4092  getActions(detail::processEvent(state_, TestMessages::certificate()));
4093 
4094  expectActions<MutateState>(actions);
4095  processStateMutations(actions);
4096  EXPECT_FALSE(state_.unverifiedCertChain().hasValue());
4097  EXPECT_EQ(state_.clientCert(), nullptr);
4098  EXPECT_EQ(state_.state(), StateEnum::ExpectingFinished);
4099 }
4100 
4101 TEST_F(ServerProtocolTest, TestCertificateVerifyNoVerifier) {
4102  setUpExpectingCertificateVerify();
4103  context_->setClientCertVerifier(nullptr);
4104  Sequence contextSeq;
4105  EXPECT_CALL(*mockHandshakeContext_, getHandshakeContext())
4106  .InSequence(contextSeq)
4107  .WillRepeatedly(
4108  Invoke([]() { return IOBuf::copyBuffer("certcontext"); }));
4109 
4110  EXPECT_CALL(
4111  *clientLeafCert_,
4112  verify(
4115  RangeMatches("certcontext"),
4116  RangeMatches("signature")))
4117  .InSequence(contextSeq);
4118 
4119  EXPECT_CALL(
4120  *mockHandshakeContext_,
4121  appendToTranscript(BufMatches("certverifyencoding")))
4122  .InSequence(contextSeq);
4123 
4124  auto actions = getActions(
4126 
4127  expectActions<MutateState>(actions);
4128  processStateMutations(actions);
4129  EXPECT_EQ(state_.unverifiedCertChain(), folly::none);
4130  EXPECT_EQ(state_.clientCert(), clientLeafCert_);
4131  EXPECT_EQ(state_.state(), StateEnum::ExpectingFinished);
4132 }
4133 
4134 TEST_F(ServerProtocolTest, TestCertificateVerifyWithVerifier) {
4135  setUpExpectingCertificateVerify();
4136  Sequence contextSeq;
4137  EXPECT_CALL(*mockHandshakeContext_, getHandshakeContext())
4138  .InSequence(contextSeq)
4139  .WillRepeatedly(
4140  Invoke([]() { return IOBuf::copyBuffer("certcontext"); }));
4141 
4142  EXPECT_CALL(
4143  *clientLeafCert_,
4144  verify(
4147  RangeMatches("certcontext"),
4148  RangeMatches("signature")))
4149  .InSequence(contextSeq);
4150 
4151  EXPECT_CALL(*certVerifier_, verify(_))
4152  .InSequence(contextSeq)
4153  .WillOnce(Invoke(
4154  [this](const std::vector<std::shared_ptr<const PeerCert>>& certs) {
4155  EXPECT_EQ(certs.size(), 2);
4156  EXPECT_EQ(certs[0], clientLeafCert_);
4157  EXPECT_EQ(certs[1], clientIntCert_);
4158  }));
4159 
4160  EXPECT_CALL(
4161  *mockHandshakeContext_,
4162  appendToTranscript(BufMatches("certverifyencoding")))
4163  .InSequence(contextSeq);
4164 
4165  auto actions = getActions(
4167 
4168  expectActions<MutateState>(actions);
4169  processStateMutations(actions);
4170  EXPECT_EQ(state_.unverifiedCertChain(), folly::none);
4171  EXPECT_EQ(state_.clientCert(), clientLeafCert_);
4172  EXPECT_EQ(state_.state(), StateEnum::ExpectingFinished);
4173 }
4174 
4175 TEST_F(ServerProtocolTest, TestCertificateVerifyAlgoMismatch) {
4176  setUpExpectingCertificateVerify();
4177 
4178  context_->setSupportedSigSchemes({SignatureScheme::ed25519});
4179 
4180  auto actions = getActions(
4182 
4183  expectError<FizzException>(
4184  actions,
4186  "client chose unsupported sig scheme:");
4187 }
4188 
4189 TEST_F(ServerProtocolTest, TestCertificateVerifySignatureFailure) {
4190  setUpExpectingCertificateVerify();
4191  Sequence contextSeq;
4192  EXPECT_CALL(*mockHandshakeContext_, getHandshakeContext())
4193  .InSequence(contextSeq)
4194  .WillRepeatedly(
4195  Invoke([]() { return IOBuf::copyBuffer("certcontext"); }));
4196 
4197  EXPECT_CALL(
4198  *clientLeafCert_,
4199  verify(
4202  RangeMatches("certcontext"),
4203  RangeMatches("signature")))
4204  .InSequence(contextSeq)
4205  .WillOnce(Throw(
4206  FizzException("verify failed", AlertDescription::bad_record_mac)));
4207 
4208  auto actions = getActions(
4210 
4211  expectError<FizzException>(
4212  actions, AlertDescription::bad_record_mac, "verify failed");
4213 }
4214 
4215 TEST_F(ServerProtocolTest, TestCertificateVerifyVerifierFailure) {
4216  setUpExpectingCertificateVerify();
4217  Sequence contextSeq;
4218  EXPECT_CALL(*mockHandshakeContext_, getHandshakeContext())
4219  .InSequence(contextSeq)
4220  .WillRepeatedly(
4221  Invoke([]() { return IOBuf::copyBuffer("certcontext"); }));
4222 
4223  EXPECT_CALL(
4224  *clientLeafCert_,
4225  verify(
4228  RangeMatches("certcontext"),
4229  RangeMatches("signature")))
4230  .InSequence(contextSeq);
4231 
4232  EXPECT_CALL(*certVerifier_, verify(_))
4233  .InSequence(contextSeq)
4234  .WillOnce(Throw(FizzVerificationException(
4235  "verifier failed", AlertDescription::bad_certificate)));
4236 
4237  auto actions = getActions(
4239 
4240  expectError<FizzVerificationException>(
4241  actions, AlertDescription::bad_certificate, "verifier failed");
4242 }
4243 
4244 TEST_F(ServerProtocolTest, TestOptionalCertificateVerifySignatureFailure) {
4245  setUpExpectingCertificateVerify();
4246  context_->setClientAuthMode(ClientAuthMode::Optional);
4247  Sequence contextSeq;
4248  EXPECT_CALL(*mockHandshakeContext_, getHandshakeContext())
4249  .InSequence(contextSeq)
4250  .WillRepeatedly(
4251  Invoke([]() { return IOBuf::copyBuffer("certcontext"); }));
4252 
4253  EXPECT_CALL(
4254  *clientLeafCert_,
4255  verify(
4258  RangeMatches("certcontext"),
4259  RangeMatches("signature")))
4260  .InSequence(contextSeq)
4261  .WillOnce(Throw(
4262  FizzException("verify failed", AlertDescription::bad_record_mac)));
4263 
4264  auto actions = getActions(
4266 
4267  expectError<FizzException>(
4268  actions, AlertDescription::bad_record_mac, "verify failed");
4269 }
4270 
4271 TEST_F(ServerProtocolTest, TestOptionalCertificateVerifyVerifierFailure) {
4272  setUpExpectingCertificateVerify();
4273  context_->setClientAuthMode(ClientAuthMode::Optional);
4274  Sequence contextSeq;
4275  EXPECT_CALL(*mockHandshakeContext_, getHandshakeContext())
4276  .InSequence(contextSeq)
4277  .WillRepeatedly(
4278  Invoke([]() { return IOBuf::copyBuffer("certcontext"); }));
4279 
4280  EXPECT_CALL(
4281  *clientLeafCert_,
4282  verify(
4285  RangeMatches("certcontext"),
4286  RangeMatches("signature")))
4287  .InSequence(contextSeq);
4288 
4289  EXPECT_CALL(*certVerifier_, verify(_))
4290  .InSequence(contextSeq)
4291  .WillOnce(Throw(
4292  FizzException("verifier failed", AlertDescription::bad_certificate)));
4293 
4294  auto actions = getActions(
4296 
4297  expectError<FizzException>(
4298  actions, AlertDescription::bad_certificate, "verifier failed");
4299 }
4300 
4301 TEST_F(ServerProtocolTest, TestCertificateVerifyVerifierGenericFailure) {
4302  setUpExpectingCertificateVerify();
4303  Sequence contextSeq;
4304  EXPECT_CALL(*mockHandshakeContext_, getHandshakeContext())
4305  .InSequence(contextSeq)
4306  .WillRepeatedly(
4307  Invoke([]() { return IOBuf::copyBuffer("certcontext"); }));
4308 
4309  EXPECT_CALL(
4310  *clientLeafCert_,
4311  verify(
4314  RangeMatches("certcontext"),
4315  RangeMatches("signature")))
4316  .InSequence(contextSeq);
4317 
4318  EXPECT_CALL(*certVerifier_, verify(_))
4319  .InSequence(contextSeq)
4320  .WillOnce(Throw(std::runtime_error("oops")));
4321 
4322  auto actions = getActions(
4324 
4325  expectError<FizzException>(
4326  actions,
4328  "client certificate failure: oops");
4329 }
4330 
4331 TEST_F(ServerProtocolTest, TestEarlyWriteError) {
4332  setUpAcceptingData();
4333  auto actions = getActions(
4334  ServerStateMachine().processEarlyAppWrite(state_, EarlyAppWrite()));
4335  expectError<FizzException>(
4336  actions, AlertDescription::unexpected_message, "invalid event");
4337 }
4338 } // namespace test
4339 } // namespace server
4340 } // namespace fizz
Buf fragment
Definition: Types.h:56
Buf encodeHandshake(T &&handshakeMsg)
Definition: Types-inl.h:515
Integral2 random(Integral1 low, Integral2 up)
std::vector< PskBinder > binders
Definition: Extensions.h:65
static std::unique_ptr< IOBuf > getEncryptedHandshakeWrite(EncryptedExtensions encryptedExt, CertificateRequest request, CertificateMsg certificate, CertificateVerify verify, Finished finished)
void verify(int extras)
static WriteNewSessionTicket writeNewSessionTicket(const std::string &str)
void write(const T &in, folly::io::Appender &appender)
Definition: Types-inl.h:112
uint32_t max_early_data_size
Definition: Extensions.h:83
static void addPsk(ClientHello &chlo, uint32_t ticketAge=100000)
Definition: TestMessages.h:70
CertificateCompressionAlgorithm
Definition: Types.h:167
MockPlaintextReadRecordLayer * mockRead_
#define ASSERT_EQ(val1, val2)
Definition: gtest.h:1956
static const std::string chlo
static std::unique_ptr< IOBuf > create(std::size_t capacity)
Definition: IOBuf.cpp:229
static NewSessionTicket newSessionTicket()
Definition: TestMessages.h:203
AlertDescription description
Definition: Types.h:313
StringPiece cookie
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
std::chrono::steady_clock::time_point now()
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
boost::variant< Actions, folly::Future< Actions >> AsyncActions
Definition: Actions.h:52
StringPiece alpn
static CertificateMsg certificate()
Definition: TestMessages.h:158
std::shared_ptr< MockCertificateVerifier > certVerifier_
Buf extension_data
Definition: Types.h:175
std::vector< NamedGroup > named_group_list
Definition: Extensions.h:23
—— Concurrent Priority Queue Implementation ——
Definition: AtomicBitSet.h:29
folly::Optional< std::string > alpn
std::shared_ptr< MockTicketCipher > mockTicketCipher_
Actions getActions(AsyncActions asyncActions, bool immediate=true)
static std::unique_ptr< IOBuf > getEncryptedHandshakeWrite(EncryptedExtensions encryptedExt, CertificateMsg certificate, CertificateVerify verify, Finished finished)
std::chrono::system_clock::time_point ticketIssueTime
PolymorphicAction< internal::InvokeWithoutArgsAction< FunctionImpl > > InvokeWithoutArgs(FunctionImpl function_impl)
folly::ssl::X509UniquePtr getCert(folly::StringPiece cert)
Definition: TestUtil.cpp:48
std::vector< KeyShareEntry > client_shares
Definition: Extensions.h:34
MockPlaintextWriteRecordLayer * mockWrite_
static ServerHello serverHello()
Definition: TestMessages.h:109
static Finished finished()
Definition: TestMessages.h:196
NamedGroup group
Definition: Extensions.h:29
ProtocolVersion
Definition: Types.h:24
virtual Actions processAppClose(const State &)
std::shared_ptr< MockReplayCache > replayCache_
std::shared_ptr< MockPeerCert > clientIntCert_
static CertificateRequest certificateRequest()
Definition: TestMessages.h:183
PolymorphicAction< internal::InvokeAction< FunctionImpl > > Invoke(FunctionImpl function_impl)
static std::unique_ptr< IOBuf > getEncryptedHandshakeWrite(EncryptedExtensions encryptedExt, CompressedCertificate certificate, CertificateVerify verify, Finished finished)
static AppWrite appWrite()
Definition: TestMessages.h:217
static EncryptedExtensions encryptedExt()
Definition: TestMessages.h:141
EncryptionLevel encryptionLevel
Definition: RecordLayer.h:21
static EndOfEarlyData endOfEarlyData()
Definition: TestMessages.h:135
Definition: Actions.h:16
static CertificateVerify certificateVerify()
Definition: TestMessages.h:175
static ClientHello clientHelloPsk()
Definition: TestMessages.h:82
static CompressedCertificate compressedCertificate()
Definition: TestMessages.h:165
std::unique_ptr< folly::IOBuf > makeRandom(size_t n)
std::vector< ProtocolVersion > versions
Definition: Extensions.h:93
static void removeExtension(T &msg, ExtensionType ext)
Definition: TestMessages.h:21
static AppData appData()
Definition: TestMessages.h:212
Buf getFinishedData(std::unique_ptr< KeyDerivation > &deriver, Buf &finishedMacKey, const Buf &finishedTranscript)
ProtocolVersion version
Definition: CookieCipher.h:18
Actions actions(Args &&...act)
Definition: Actions.h:86
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
#define ON_CALL(obj, call)
#define ASSERT_THAT(value, matcher)
StringPiece sni
Buf encode(TokenBindingMessage &&message)
Definition: Types.cpp:124
TEST_F(RSAPSSTest, TestSignVerify)
std::shared_ptr< MockCookieCipher > mockCookieCipher_
static const std::string nst
static HelloRetryRequest helloRetryRequest()
Definition: TestMessages.h:95
const char * string
Definition: Conv.cpp:212
ExtensionType extension_type
Definition: Types.h:174
MockEncryptedWriteRecordLayer * appWrite_
ContentType contentType
Definition: RecordLayer.h:20
std::unique_ptr< folly::IOBuf > Buf
Definition: Types.h:22
std::shared_ptr< MockSelfCert > cert_
folly::Optional< NamedGroup > group
Definition: CookieCipher.h:20
#define EXPECT_CALL(obj, call)
static EncryptedExtensions encryptedExtEarly()
Definition: TestMessages.h:152
const internal::AnythingMatcher _
decltype(auto) variant_match(Variant &&variant, Cases &&...cases)
Definition: Overload.h:74
std::shared_ptr< FizzServerContext > context_
std::vector< ProtocolName > protocol_name_list
Definition: Extensions.h:115
std::vector< PskIdentity > identities
Definition: Extensions.h:64
static KeyUpdate keyUpdate(bool reqUpdate)
Definition: TestMessages.h:229
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
std::shared_ptr< const Cert > serverCert
Extension encodeExtension(const TokenBindingParameters &params)
Definition: Types.cpp:113
ContentType type
Definition: Types.h:55
Range< const char * > StringPiece
#define EXPECT_LT(val1, val2)
Definition: gtest.h:1930
Actions processEvent(const State &state, Param param)
static std::unique_ptr< IOBuf > copyBuffer(const void *buf, std::size_t size, std::size_t headroom=0, std::size_t minTailroom=0)
Definition: IOBuf.h:1587
MockEncryptedReadRecordLayer * appRead_
char c
internal::ElementsAreMatcher< ::testing::tuple<> > ElementsAre()
std::shared_ptr< MockServerExtensions > extensions_
static ClientHello clientHello()
Definition: TestMessages.h:26
bool check(const dynamic &schema, const dynamic &value, bool check=true)
Future< typename std::decay< T >::type > makeFuture(T &&t)
Definition: Future-inl.h:1310
static std::unique_ptr< IOBuf > getEncryptedHandshakeWrite(EncryptedExtensions encryptedExt, Finished finished)
constexpr ProtocolVersion TestProtocolVersion
Definition: ProtocolTest.h:22
static ClientHello clientHelloPskEarly()
Definition: TestMessages.h:88
std::vector< CertificateCompressionAlgorithm > algorithms
Definition: Extensions.h:143
constexpr None none
Definition: Optional.h:87
internal::ReturnAction< R > Return(R value)
#define EXPECT_GT(val1, val2)
Definition: gtest.h:1934
std::shared_ptr< MockPeerCert > clientLeafCert_