1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include <memory>
6 #include <string>
7 #include <utility>
8
9 #include "absl/base/macros.h"
10 #include "openssl/hpke.h"
11 #include "openssl/ssl.h"
12 #include "quiche/quic/core/crypto/quic_decrypter.h"
13 #include "quiche/quic/core/crypto/quic_encrypter.h"
14 #include "quiche/quic/core/quic_error_codes.h"
15 #include "quiche/quic/core/quic_packets.h"
16 #include "quiche/quic/core/quic_server_id.h"
17 #include "quiche/quic/core/quic_types.h"
18 #include "quiche/quic/core/quic_utils.h"
19 #include "quiche/quic/core/quic_versions.h"
20 #include "quiche/quic/platform/api/quic_expect_bug.h"
21 #include "quiche/quic/platform/api/quic_flags.h"
22 #include "quiche/quic/platform/api/quic_test.h"
23 #include "quiche/quic/test_tools/crypto_test_utils.h"
24 #include "quiche/quic/test_tools/quic_connection_peer.h"
25 #include "quiche/quic/test_tools/quic_framer_peer.h"
26 #include "quiche/quic/test_tools/quic_session_peer.h"
27 #include "quiche/quic/test_tools/quic_test_utils.h"
28 #include "quiche/quic/test_tools/simple_session_cache.h"
29 #include "quiche/quic/tools/fake_proof_verifier.h"
30 #include "quiche/common/test_tools/quiche_test_utils.h"
31
32 using testing::_;
33
34 namespace quic {
35 namespace test {
36 namespace {
37
38 constexpr char kServerHostname[] = "test.example.com";
39 constexpr uint16_t kServerPort = 443;
40
41 // TestProofVerifier wraps ProofVerifierForTesting, except for VerifyCertChain
42 // which, if TestProofVerifier is active, always returns QUIC_PENDING. (If this
43 // test proof verifier is not active, it delegates VerifyCertChain to the
44 // ProofVerifierForTesting.) The pending VerifyCertChain operation can be
45 // completed by calling InvokePendingCallback. This allows for testing
46 // asynchronous VerifyCertChain operations.
47 class TestProofVerifier : public ProofVerifier {
48 public:
TestProofVerifier()49 TestProofVerifier()
50 : verifier_(crypto_test_utils::ProofVerifierForTesting()) {}
51
VerifyProof(const std::string & hostname,const uint16_t port,const std::string & server_config,QuicTransportVersion quic_version,absl::string_view chlo_hash,const std::vector<std::string> & certs,const std::string & cert_sct,const std::string & signature,const ProofVerifyContext * context,std::string * error_details,std::unique_ptr<ProofVerifyDetails> * details,std::unique_ptr<ProofVerifierCallback> callback)52 QuicAsyncStatus VerifyProof(
53 const std::string& hostname, const uint16_t port,
54 const std::string& server_config, QuicTransportVersion quic_version,
55 absl::string_view chlo_hash, const std::vector<std::string>& certs,
56 const std::string& cert_sct, const std::string& signature,
57 const ProofVerifyContext* context, std::string* error_details,
58 std::unique_ptr<ProofVerifyDetails>* details,
59 std::unique_ptr<ProofVerifierCallback> callback) override {
60 return verifier_->VerifyProof(
61 hostname, port, server_config, quic_version, chlo_hash, certs, cert_sct,
62 signature, context, error_details, details, std::move(callback));
63 }
64
VerifyCertChain(const std::string & hostname,const uint16_t port,const std::vector<std::string> & certs,const std::string & ocsp_response,const std::string & cert_sct,const ProofVerifyContext * context,std::string * error_details,std::unique_ptr<ProofVerifyDetails> * details,uint8_t * out_alert,std::unique_ptr<ProofVerifierCallback> callback)65 QuicAsyncStatus VerifyCertChain(
66 const std::string& hostname, const uint16_t port,
67 const std::vector<std::string>& certs, const std::string& ocsp_response,
68 const std::string& cert_sct, const ProofVerifyContext* context,
69 std::string* error_details, std::unique_ptr<ProofVerifyDetails>* details,
70 uint8_t* out_alert,
71 std::unique_ptr<ProofVerifierCallback> callback) override {
72 if (!active_) {
73 return verifier_->VerifyCertChain(
74 hostname, port, certs, ocsp_response, cert_sct, context,
75 error_details, details, out_alert, std::move(callback));
76 }
77 pending_ops_.push_back(std::make_unique<VerifyChainPendingOp>(
78 hostname, port, certs, ocsp_response, cert_sct, context, error_details,
79 details, out_alert, std::move(callback), verifier_.get()));
80 return QUIC_PENDING;
81 }
82
CreateDefaultContext()83 std::unique_ptr<ProofVerifyContext> CreateDefaultContext() override {
84 return nullptr;
85 }
86
Activate()87 void Activate() { active_ = true; }
88
NumPendingCallbacks() const89 size_t NumPendingCallbacks() const { return pending_ops_.size(); }
90
InvokePendingCallback(size_t n)91 void InvokePendingCallback(size_t n) {
92 ASSERT_GT(NumPendingCallbacks(), n);
93 pending_ops_[n]->Run();
94 auto it = pending_ops_.begin() + n;
95 pending_ops_.erase(it);
96 }
97
98 private:
99 // Implementation of ProofVerifierCallback that fails if the callback is ever
100 // run.
101 class FailingProofVerifierCallback : public ProofVerifierCallback {
102 public:
Run(bool,const std::string &,std::unique_ptr<ProofVerifyDetails> *)103 void Run(bool /*ok*/, const std::string& /*error_details*/,
104 std::unique_ptr<ProofVerifyDetails>* /*details*/) override {
105 FAIL();
106 }
107 };
108
109 class VerifyChainPendingOp {
110 public:
VerifyChainPendingOp(const std::string & hostname,const uint16_t port,const std::vector<std::string> & certs,const std::string & ocsp_response,const std::string & cert_sct,const ProofVerifyContext * context,std::string * error_details,std::unique_ptr<ProofVerifyDetails> * details,uint8_t * out_alert,std::unique_ptr<ProofVerifierCallback> callback,ProofVerifier * delegate)111 VerifyChainPendingOp(const std::string& hostname, const uint16_t port,
112 const std::vector<std::string>& certs,
113 const std::string& ocsp_response,
114 const std::string& cert_sct,
115 const ProofVerifyContext* context,
116 std::string* error_details,
117 std::unique_ptr<ProofVerifyDetails>* details,
118 uint8_t* out_alert,
119 std::unique_ptr<ProofVerifierCallback> callback,
120 ProofVerifier* delegate)
121 : hostname_(hostname),
122 port_(port),
123 certs_(certs),
124 ocsp_response_(ocsp_response),
125 cert_sct_(cert_sct),
126 context_(context),
127 error_details_(error_details),
128 details_(details),
129 out_alert_(out_alert),
130 callback_(std::move(callback)),
131 delegate_(delegate) {}
132
Run()133 void Run() {
134 // TestProofVerifier depends on crypto_test_utils::ProofVerifierForTesting
135 // running synchronously. It passes a FailingProofVerifierCallback and
136 // runs the original callback after asserting that the verification ran
137 // synchronously.
138 QuicAsyncStatus status = delegate_->VerifyCertChain(
139 hostname_, port_, certs_, ocsp_response_, cert_sct_, context_,
140 error_details_, details_, out_alert_,
141 std::make_unique<FailingProofVerifierCallback>());
142 ASSERT_NE(status, QUIC_PENDING);
143 callback_->Run(status == QUIC_SUCCESS, *error_details_, details_);
144 }
145
146 private:
147 std::string hostname_;
148 const uint16_t port_;
149 std::vector<std::string> certs_;
150 std::string ocsp_response_;
151 std::string cert_sct_;
152 const ProofVerifyContext* context_;
153 std::string* error_details_;
154 std::unique_ptr<ProofVerifyDetails>* details_;
155 uint8_t* out_alert_;
156 std::unique_ptr<ProofVerifierCallback> callback_;
157 ProofVerifier* delegate_;
158 };
159
160 std::unique_ptr<ProofVerifier> verifier_;
161 bool active_ = false;
162 std::vector<std::unique_ptr<VerifyChainPendingOp>> pending_ops_;
163 };
164
165 class TlsClientHandshakerTest : public QuicTestWithParam<ParsedQuicVersion> {
166 public:
TlsClientHandshakerTest()167 TlsClientHandshakerTest()
168 : supported_versions_({GetParam()}),
169 server_id_(kServerHostname, kServerPort, false),
170 server_compressed_certs_cache_(
171 QuicCompressedCertsCache::kQuicCompressedCertsCacheSize) {
172 crypto_config_ = std::make_unique<QuicCryptoClientConfig>(
173 std::make_unique<TestProofVerifier>(),
174 std::make_unique<test::SimpleSessionCache>());
175 server_crypto_config_ = crypto_test_utils::CryptoServerConfigForTesting();
176 CreateConnection();
177 }
178
CreateSession()179 void CreateSession() {
180 session_ = std::make_unique<TestQuicSpdyClientSession>(
181 connection_, DefaultQuicConfig(), supported_versions_, server_id_,
182 crypto_config_.get(), ssl_config_);
183 EXPECT_CALL(*session_, GetAlpnsToOffer())
184 .WillRepeatedly(testing::Return(std::vector<std::string>(
185 {AlpnForVersion(connection_->version())})));
186 }
187
CreateConnection()188 void CreateConnection() {
189 connection_ =
190 new PacketSavingConnection(&client_helper_, &alarm_factory_,
191 Perspective::IS_CLIENT, supported_versions_);
192 // Advance the time, because timers do not like uninitialized times.
193 connection_->AdvanceTime(QuicTime::Delta::FromSeconds(1));
194 CreateSession();
195 }
196
CompleteCryptoHandshake()197 void CompleteCryptoHandshake() {
198 CompleteCryptoHandshakeWithServerALPN(
199 AlpnForVersion(connection_->version()));
200 }
201
CompleteCryptoHandshakeWithServerALPN(const std::string & alpn)202 void CompleteCryptoHandshakeWithServerALPN(const std::string& alpn) {
203 EXPECT_CALL(*connection_, SendCryptoData(_, _, _))
204 .Times(testing::AnyNumber());
205 stream()->CryptoConnect();
206 QuicConfig config;
207 crypto_test_utils::HandshakeWithFakeServer(
208 &config, server_crypto_config_.get(), &server_helper_, &alarm_factory_,
209 connection_, stream(), alpn);
210 }
211
stream()212 QuicCryptoClientStream* stream() {
213 return session_->GetMutableCryptoStream();
214 }
215
server_stream()216 QuicCryptoServerStreamBase* server_stream() {
217 return server_session_->GetMutableCryptoStream();
218 }
219
220 // Initializes a fake server, and all its associated state, for testing.
InitializeFakeServer()221 void InitializeFakeServer() {
222 TestQuicSpdyServerSession* server_session = nullptr;
223 CreateServerSessionForTest(
224 server_id_, QuicTime::Delta::FromSeconds(100000), supported_versions_,
225 &server_helper_, &alarm_factory_, server_crypto_config_.get(),
226 &server_compressed_certs_cache_, &server_connection_, &server_session);
227 server_session_.reset(server_session);
228 std::string alpn = AlpnForVersion(connection_->version());
229 EXPECT_CALL(*server_session_, SelectAlpn(_))
230 .WillRepeatedly([alpn](const std::vector<absl::string_view>& alpns) {
231 return std::find(alpns.cbegin(), alpns.cend(), alpn);
232 });
233 }
234
MakeTestEchKeys(const char * public_name,size_t max_name_len,std::string * ech_config_list)235 static bssl::UniquePtr<SSL_ECH_KEYS> MakeTestEchKeys(
236 const char* public_name, size_t max_name_len,
237 std::string* ech_config_list) {
238 bssl::ScopedEVP_HPKE_KEY key;
239 if (!EVP_HPKE_KEY_generate(key.get(), EVP_hpke_x25519_hkdf_sha256())) {
240 return nullptr;
241 }
242
243 uint8_t* ech_config;
244 size_t ech_config_len;
245 if (!SSL_marshal_ech_config(&ech_config, &ech_config_len,
246 /*config_id=*/1, key.get(), public_name,
247 max_name_len)) {
248 return nullptr;
249 }
250 bssl::UniquePtr<uint8_t> scoped_ech_config(ech_config);
251
252 uint8_t* ech_config_list_raw;
253 size_t ech_config_list_len;
254 bssl::UniquePtr<SSL_ECH_KEYS> keys(SSL_ECH_KEYS_new());
255 if (!keys ||
256 !SSL_ECH_KEYS_add(keys.get(), /*is_retry_config=*/1, ech_config,
257 ech_config_len, key.get()) ||
258 !SSL_ECH_KEYS_marshal_retry_configs(keys.get(), &ech_config_list_raw,
259 &ech_config_list_len)) {
260 return nullptr;
261 }
262 bssl::UniquePtr<uint8_t> scoped_ech_config_list(ech_config_list_raw);
263
264 ech_config_list->assign(ech_config_list_raw,
265 ech_config_list_raw + ech_config_list_len);
266 return keys;
267 }
268
269 MockQuicConnectionHelper server_helper_;
270 MockQuicConnectionHelper client_helper_;
271 MockAlarmFactory alarm_factory_;
272 PacketSavingConnection* connection_;
273 ParsedQuicVersionVector supported_versions_;
274 std::unique_ptr<TestQuicSpdyClientSession> session_;
275 QuicServerId server_id_;
276 CryptoHandshakeMessage message_;
277 std::unique_ptr<QuicCryptoClientConfig> crypto_config_;
278 std::optional<QuicSSLConfig> ssl_config_;
279
280 // Server state.
281 std::unique_ptr<QuicCryptoServerConfig> server_crypto_config_;
282 PacketSavingConnection* server_connection_;
283 std::unique_ptr<TestQuicSpdyServerSession> server_session_;
284 QuicCompressedCertsCache server_compressed_certs_cache_;
285 };
286
287 INSTANTIATE_TEST_SUITE_P(TlsHandshakerTests, TlsClientHandshakerTest,
288 ::testing::ValuesIn(AllSupportedVersionsWithTls()),
289 ::testing::PrintToStringParamName());
290
TEST_P(TlsClientHandshakerTest,NotInitiallyConnected)291 TEST_P(TlsClientHandshakerTest, NotInitiallyConnected) {
292 EXPECT_FALSE(stream()->encryption_established());
293 EXPECT_FALSE(stream()->one_rtt_keys_available());
294 }
295
TEST_P(TlsClientHandshakerTest,ConnectedAfterHandshake)296 TEST_P(TlsClientHandshakerTest, ConnectedAfterHandshake) {
297 CompleteCryptoHandshake();
298 EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol());
299 EXPECT_TRUE(stream()->encryption_established());
300 EXPECT_TRUE(stream()->one_rtt_keys_available());
301 EXPECT_FALSE(stream()->IsResumption());
302 }
303
TEST_P(TlsClientHandshakerTest,ConnectionClosedOnTlsError)304 TEST_P(TlsClientHandshakerTest, ConnectionClosedOnTlsError) {
305 // Have client send ClientHello.
306 stream()->CryptoConnect();
307 EXPECT_CALL(*connection_, CloseConnection(QUIC_HANDSHAKE_FAILED, _, _, _));
308
309 // Send a zero-length ServerHello from server to client.
310 char bogus_handshake_message[] = {
311 // Handshake struct (RFC 8446 appendix B.3)
312 2, // HandshakeType server_hello
313 0, 0, 0, // uint24 length
314 };
315 stream()->crypto_message_parser()->ProcessInput(
316 absl::string_view(bogus_handshake_message,
317 ABSL_ARRAYSIZE(bogus_handshake_message)),
318 ENCRYPTION_INITIAL);
319
320 EXPECT_FALSE(stream()->one_rtt_keys_available());
321 }
322
TEST_P(TlsClientHandshakerTest,ProofVerifyDetailsAvailableAfterHandshake)323 TEST_P(TlsClientHandshakerTest, ProofVerifyDetailsAvailableAfterHandshake) {
324 EXPECT_CALL(*session_, OnProofVerifyDetailsAvailable(testing::_));
325 stream()->CryptoConnect();
326 QuicConfig config;
327 crypto_test_utils::HandshakeWithFakeServer(
328 &config, server_crypto_config_.get(), &server_helper_, &alarm_factory_,
329 connection_, stream(), AlpnForVersion(connection_->version()));
330 EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol());
331 EXPECT_TRUE(stream()->encryption_established());
332 EXPECT_TRUE(stream()->one_rtt_keys_available());
333 }
334
TEST_P(TlsClientHandshakerTest,HandshakeWithAsyncProofVerifier)335 TEST_P(TlsClientHandshakerTest, HandshakeWithAsyncProofVerifier) {
336 InitializeFakeServer();
337
338 // Enable TestProofVerifier to capture call to VerifyCertChain and run it
339 // asynchronously.
340 TestProofVerifier* proof_verifier =
341 static_cast<TestProofVerifier*>(crypto_config_->proof_verifier());
342 proof_verifier->Activate();
343
344 stream()->CryptoConnect();
345 // Exchange handshake messages.
346 std::pair<size_t, size_t> moved_message_counts =
347 crypto_test_utils::AdvanceHandshake(
348 connection_, stream(), 0, server_connection_, server_stream(), 0);
349
350 ASSERT_EQ(proof_verifier->NumPendingCallbacks(), 1u);
351 proof_verifier->InvokePendingCallback(0);
352
353 // Exchange more handshake messages.
354 crypto_test_utils::AdvanceHandshake(
355 connection_, stream(), moved_message_counts.first, server_connection_,
356 server_stream(), moved_message_counts.second);
357
358 EXPECT_TRUE(stream()->encryption_established());
359 EXPECT_TRUE(stream()->one_rtt_keys_available());
360 }
361
TEST_P(TlsClientHandshakerTest,Resumption)362 TEST_P(TlsClientHandshakerTest, Resumption) {
363 // Disable 0-RTT on the server so that we're only testing 1-RTT resumption:
364 SSL_CTX_set_early_data_enabled(server_crypto_config_->ssl_ctx(), false);
365 // Finish establishing the first connection:
366 CompleteCryptoHandshake();
367
368 EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol());
369 EXPECT_TRUE(stream()->encryption_established());
370 EXPECT_TRUE(stream()->one_rtt_keys_available());
371 EXPECT_FALSE(stream()->ResumptionAttempted());
372 EXPECT_FALSE(stream()->IsResumption());
373
374 // Create a second connection
375 CreateConnection();
376 CompleteCryptoHandshake();
377
378 EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol());
379 EXPECT_TRUE(stream()->encryption_established());
380 EXPECT_TRUE(stream()->one_rtt_keys_available());
381 EXPECT_TRUE(stream()->ResumptionAttempted());
382 EXPECT_TRUE(stream()->IsResumption());
383 }
384
TEST_P(TlsClientHandshakerTest,ResumptionRejection)385 TEST_P(TlsClientHandshakerTest, ResumptionRejection) {
386 // Disable 0-RTT on the server before the first connection so the client
387 // doesn't attempt a 0-RTT resumption, only a 1-RTT resumption.
388 SSL_CTX_set_early_data_enabled(server_crypto_config_->ssl_ctx(), false);
389 // Finish establishing the first connection:
390 CompleteCryptoHandshake();
391
392 EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol());
393 EXPECT_TRUE(stream()->encryption_established());
394 EXPECT_TRUE(stream()->one_rtt_keys_available());
395 EXPECT_FALSE(stream()->ResumptionAttempted());
396 EXPECT_FALSE(stream()->IsResumption());
397
398 // Create a second connection, but disable resumption on the server.
399 SSL_CTX_set_options(server_crypto_config_->ssl_ctx(), SSL_OP_NO_TICKET);
400 CreateConnection();
401 CompleteCryptoHandshake();
402
403 EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol());
404 EXPECT_TRUE(stream()->encryption_established());
405 EXPECT_TRUE(stream()->one_rtt_keys_available());
406 EXPECT_TRUE(stream()->ResumptionAttempted());
407 EXPECT_FALSE(stream()->IsResumption());
408 EXPECT_FALSE(stream()->EarlyDataAccepted());
409 EXPECT_EQ(stream()->EarlyDataReason(),
410 ssl_early_data_unsupported_for_session);
411 }
412
TEST_P(TlsClientHandshakerTest,ZeroRttResumption)413 TEST_P(TlsClientHandshakerTest, ZeroRttResumption) {
414 // Finish establishing the first connection:
415 CompleteCryptoHandshake();
416
417 EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol());
418 EXPECT_TRUE(stream()->encryption_established());
419 EXPECT_TRUE(stream()->one_rtt_keys_available());
420 EXPECT_FALSE(stream()->IsResumption());
421
422 // Create a second connection
423 CreateConnection();
424 // OnConfigNegotiated should be called twice - once when processing saved
425 // 0-RTT transport parameters, and then again when receiving transport
426 // parameters from the server.
427 EXPECT_CALL(*session_, OnConfigNegotiated()).Times(2);
428 EXPECT_CALL(*connection_, SendCryptoData(_, _, _))
429 .Times(testing::AnyNumber());
430 // Start the second handshake and confirm we have keys before receiving any
431 // messages from the server.
432 stream()->CryptoConnect();
433 EXPECT_TRUE(stream()->encryption_established());
434 EXPECT_NE(stream()->crypto_negotiated_params().cipher_suite, 0);
435 EXPECT_NE(stream()->crypto_negotiated_params().key_exchange_group, 0);
436 EXPECT_NE(stream()->crypto_negotiated_params().peer_signature_algorithm, 0);
437 // Finish the handshake with the server.
438 QuicConfig config;
439 crypto_test_utils::HandshakeWithFakeServer(
440 &config, server_crypto_config_.get(), &server_helper_, &alarm_factory_,
441 connection_, stream(), AlpnForVersion(connection_->version()));
442
443 EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol());
444 EXPECT_TRUE(stream()->encryption_established());
445 EXPECT_TRUE(stream()->one_rtt_keys_available());
446 EXPECT_TRUE(stream()->IsResumption());
447 EXPECT_TRUE(stream()->EarlyDataAccepted());
448 EXPECT_EQ(stream()->EarlyDataReason(), ssl_early_data_accepted);
449 }
450
451 // Regression test for b/186438140.
TEST_P(TlsClientHandshakerTest,ZeroRttResumptionWithAyncProofVerifier)452 TEST_P(TlsClientHandshakerTest, ZeroRttResumptionWithAyncProofVerifier) {
453 // Finish establishing the first connection, so the second connection can
454 // resume.
455 CompleteCryptoHandshake();
456
457 EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol());
458 EXPECT_TRUE(stream()->encryption_established());
459 EXPECT_TRUE(stream()->one_rtt_keys_available());
460 EXPECT_FALSE(stream()->IsResumption());
461
462 // Create a second connection.
463 CreateConnection();
464 InitializeFakeServer();
465 EXPECT_CALL(*session_, OnConfigNegotiated());
466 EXPECT_CALL(*connection_, SendCryptoData(_, _, _))
467 .Times(testing::AnyNumber());
468 // Enable TestProofVerifier to capture the call to VerifyCertChain and run it
469 // asynchronously.
470 TestProofVerifier* proof_verifier =
471 static_cast<TestProofVerifier*>(crypto_config_->proof_verifier());
472 proof_verifier->Activate();
473 // Start the second handshake.
474 stream()->CryptoConnect();
475
476 ASSERT_EQ(proof_verifier->NumPendingCallbacks(), 1u);
477
478 // Advance the handshake with the server. Since cert verification has not
479 // finished yet, client cannot derive HANDSHAKE and 1-RTT keys.
480 crypto_test_utils::AdvanceHandshake(connection_, stream(), 0,
481 server_connection_, server_stream(), 0);
482
483 EXPECT_FALSE(stream()->one_rtt_keys_available());
484 EXPECT_FALSE(server_stream()->one_rtt_keys_available());
485
486 // Finish cert verification after receiving packets from server.
487 proof_verifier->InvokePendingCallback(0);
488
489 QuicFramer* framer = QuicConnectionPeer::GetFramer(connection_);
490 // Verify client has derived HANDSHAKE key.
491 EXPECT_NE(nullptr,
492 QuicFramerPeer::GetEncrypter(framer, ENCRYPTION_HANDSHAKE));
493
494 // Ideally, we should also verify that the process_undecryptable_packets_alarm
495 // is set and processing the undecryptable packets can advance the handshake
496 // to completion. Unfortunately, the test facilities used in this test does
497 // not support queuing and processing undecryptable packets.
498 }
499
TEST_P(TlsClientHandshakerTest,ZeroRttRejection)500 TEST_P(TlsClientHandshakerTest, ZeroRttRejection) {
501 // Finish establishing the first connection:
502 CompleteCryptoHandshake();
503
504 EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol());
505 EXPECT_TRUE(stream()->encryption_established());
506 EXPECT_TRUE(stream()->one_rtt_keys_available());
507 EXPECT_FALSE(stream()->IsResumption());
508
509 // Create a second connection, but disable 0-RTT on the server.
510 SSL_CTX_set_early_data_enabled(server_crypto_config_->ssl_ctx(), false);
511 CreateConnection();
512
513 // OnConfigNegotiated should be called twice - once when processing saved
514 // 0-RTT transport parameters, and then again when receiving transport
515 // parameters from the server.
516 EXPECT_CALL(*session_, OnConfigNegotiated()).Times(2);
517
518 // 4 packets will be sent in this connection: initial handshake packet, 0-RTT
519 // packet containing SETTINGS, handshake packet upon 0-RTT rejection, 0-RTT
520 // packet retransmission.
521 EXPECT_CALL(*connection_,
522 OnPacketSent(ENCRYPTION_INITIAL, NOT_RETRANSMISSION));
523 if (VersionUsesHttp3(session_->transport_version())) {
524 EXPECT_CALL(*connection_,
525 OnPacketSent(ENCRYPTION_ZERO_RTT, NOT_RETRANSMISSION));
526 }
527 EXPECT_CALL(*connection_,
528 OnPacketSent(ENCRYPTION_HANDSHAKE, NOT_RETRANSMISSION));
529 if (VersionUsesHttp3(session_->transport_version())) {
530 // TODO(b/158027651): change transmission type to
531 // ALL_ZERO_RTT_RETRANSMISSION.
532 EXPECT_CALL(*connection_,
533 OnPacketSent(ENCRYPTION_FORWARD_SECURE, LOSS_RETRANSMISSION));
534 }
535
536 CompleteCryptoHandshake();
537
538 QuicFramer* framer = QuicConnectionPeer::GetFramer(connection_);
539 EXPECT_EQ(nullptr, QuicFramerPeer::GetEncrypter(framer, ENCRYPTION_ZERO_RTT));
540
541 EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol());
542 EXPECT_TRUE(stream()->encryption_established());
543 EXPECT_TRUE(stream()->one_rtt_keys_available());
544 EXPECT_TRUE(stream()->IsResumption());
545 EXPECT_FALSE(stream()->EarlyDataAccepted());
546 EXPECT_EQ(stream()->EarlyDataReason(), ssl_early_data_peer_declined);
547 }
548
TEST_P(TlsClientHandshakerTest,ZeroRttAndResumptionRejection)549 TEST_P(TlsClientHandshakerTest, ZeroRttAndResumptionRejection) {
550 // Finish establishing the first connection:
551 CompleteCryptoHandshake();
552
553 EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol());
554 EXPECT_TRUE(stream()->encryption_established());
555 EXPECT_TRUE(stream()->one_rtt_keys_available());
556 EXPECT_FALSE(stream()->IsResumption());
557
558 // Create a second connection, but disable resumption on the server.
559 SSL_CTX_set_options(server_crypto_config_->ssl_ctx(), SSL_OP_NO_TICKET);
560 CreateConnection();
561
562 // OnConfigNegotiated should be called twice - once when processing saved
563 // 0-RTT transport parameters, and then again when receiving transport
564 // parameters from the server.
565 EXPECT_CALL(*session_, OnConfigNegotiated()).Times(2);
566
567 // 4 packets will be sent in this connection: initial handshake packet, 0-RTT
568 // packet containing SETTINGS, handshake packet upon 0-RTT rejection, 0-RTT
569 // packet retransmission.
570 EXPECT_CALL(*connection_,
571 OnPacketSent(ENCRYPTION_INITIAL, NOT_RETRANSMISSION));
572 if (VersionUsesHttp3(session_->transport_version())) {
573 EXPECT_CALL(*connection_,
574 OnPacketSent(ENCRYPTION_ZERO_RTT, NOT_RETRANSMISSION));
575 }
576 EXPECT_CALL(*connection_,
577 OnPacketSent(ENCRYPTION_HANDSHAKE, NOT_RETRANSMISSION));
578 if (VersionUsesHttp3(session_->transport_version())) {
579 // TODO(b/158027651): change transmission type to
580 // ALL_ZERO_RTT_RETRANSMISSION.
581 EXPECT_CALL(*connection_,
582 OnPacketSent(ENCRYPTION_FORWARD_SECURE, LOSS_RETRANSMISSION));
583 }
584
585 CompleteCryptoHandshake();
586
587 QuicFramer* framer = QuicConnectionPeer::GetFramer(connection_);
588 EXPECT_EQ(nullptr, QuicFramerPeer::GetEncrypter(framer, ENCRYPTION_ZERO_RTT));
589
590 EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol());
591 EXPECT_TRUE(stream()->encryption_established());
592 EXPECT_TRUE(stream()->one_rtt_keys_available());
593 EXPECT_FALSE(stream()->IsResumption());
594 EXPECT_FALSE(stream()->EarlyDataAccepted());
595 EXPECT_EQ(stream()->EarlyDataReason(), ssl_early_data_session_not_resumed);
596 }
597
TEST_P(TlsClientHandshakerTest,ClientSendsNoSNI)598 TEST_P(TlsClientHandshakerTest, ClientSendsNoSNI) {
599 // Reconfigure client to sent an empty server hostname. The crypto config also
600 // needs to be recreated to use a FakeProofVerifier since the server's cert
601 // won't match the empty hostname.
602 server_id_ = QuicServerId("", 443);
603 crypto_config_.reset(new QuicCryptoClientConfig(
604 std::make_unique<FakeProofVerifier>(), nullptr));
605 CreateConnection();
606 InitializeFakeServer();
607
608 stream()->CryptoConnect();
609 crypto_test_utils::CommunicateHandshakeMessages(
610 connection_, stream(), server_connection_, server_stream());
611
612 EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol());
613 EXPECT_TRUE(stream()->encryption_established());
614 EXPECT_TRUE(stream()->one_rtt_keys_available());
615
616 EXPECT_EQ(server_stream()->crypto_negotiated_params().sni, "");
617 }
618
TEST_P(TlsClientHandshakerTest,ClientSendingTooManyALPNs)619 TEST_P(TlsClientHandshakerTest, ClientSendingTooManyALPNs) {
620 std::string long_alpn(250, 'A');
621 EXPECT_QUIC_BUG(
622 {
623 EXPECT_CALL(*session_, GetAlpnsToOffer())
624 .WillOnce(testing::Return(std::vector<std::string>({
625 long_alpn + "1",
626 long_alpn + "2",
627 long_alpn + "3",
628 long_alpn + "4",
629 long_alpn + "5",
630 long_alpn + "6",
631 long_alpn + "7",
632 long_alpn + "8",
633 })));
634 stream()->CryptoConnect();
635 },
636 "Failed to set ALPN");
637 }
638
TEST_P(TlsClientHandshakerTest,ServerRequiresCustomALPN)639 TEST_P(TlsClientHandshakerTest, ServerRequiresCustomALPN) {
640 InitializeFakeServer();
641 const std::string kTestAlpn = "An ALPN That Client Did Not Offer";
642 EXPECT_CALL(*server_session_, SelectAlpn(_))
643 .WillOnce([kTestAlpn](const std::vector<absl::string_view>& alpns) {
644 return std::find(alpns.cbegin(), alpns.cend(), kTestAlpn);
645 });
646
647 EXPECT_CALL(*server_connection_,
648 CloseConnection(QUIC_HANDSHAKE_FAILED,
649 static_cast<QuicIetfTransportErrorCodes>(
650 CRYPTO_ERROR_FIRST + 120),
651 "TLS handshake failure (ENCRYPTION_INITIAL) 120: "
652 "no application protocol",
653 _));
654
655 stream()->CryptoConnect();
656 crypto_test_utils::AdvanceHandshake(connection_, stream(), 0,
657 server_connection_, server_stream(), 0);
658
659 EXPECT_FALSE(stream()->one_rtt_keys_available());
660 EXPECT_FALSE(server_stream()->one_rtt_keys_available());
661 EXPECT_FALSE(stream()->encryption_established());
662 EXPECT_FALSE(server_stream()->encryption_established());
663 }
664
TEST_P(TlsClientHandshakerTest,ZeroRTTNotAttemptedOnALPNChange)665 TEST_P(TlsClientHandshakerTest, ZeroRTTNotAttemptedOnALPNChange) {
666 // Finish establishing the first connection:
667 CompleteCryptoHandshake();
668
669 EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol());
670 EXPECT_TRUE(stream()->encryption_established());
671 EXPECT_TRUE(stream()->one_rtt_keys_available());
672 EXPECT_FALSE(stream()->IsResumption());
673
674 // Create a second connection
675 CreateConnection();
676 // Override the ALPN to send on the second connection.
677 const std::string kTestAlpn = "Test ALPN";
678 EXPECT_CALL(*session_, GetAlpnsToOffer())
679 .WillRepeatedly(testing::Return(std::vector<std::string>({kTestAlpn})));
680 // OnConfigNegotiated should only be called once: when transport parameters
681 // are received from the server.
682 EXPECT_CALL(*session_, OnConfigNegotiated()).Times(1);
683
684 CompleteCryptoHandshakeWithServerALPN(kTestAlpn);
685 EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol());
686 EXPECT_TRUE(stream()->encryption_established());
687 EXPECT_TRUE(stream()->one_rtt_keys_available());
688 EXPECT_FALSE(stream()->EarlyDataAccepted());
689 EXPECT_EQ(stream()->EarlyDataReason(), ssl_early_data_alpn_mismatch);
690 }
691
TEST_P(TlsClientHandshakerTest,InvalidSNI)692 TEST_P(TlsClientHandshakerTest, InvalidSNI) {
693 // Test that a client will skip sending SNI if configured to send an invalid
694 // hostname. In this case, the inclusion of '!' is invalid.
695 server_id_ = QuicServerId("invalid!.example.com", 443);
696 crypto_config_.reset(new QuicCryptoClientConfig(
697 std::make_unique<FakeProofVerifier>(), nullptr));
698 CreateConnection();
699 InitializeFakeServer();
700
701 stream()->CryptoConnect();
702 crypto_test_utils::CommunicateHandshakeMessages(
703 connection_, stream(), server_connection_, server_stream());
704
705 EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol());
706 EXPECT_TRUE(stream()->encryption_established());
707 EXPECT_TRUE(stream()->one_rtt_keys_available());
708
709 EXPECT_EQ(server_stream()->crypto_negotiated_params().sni, "");
710 }
711
TEST_P(TlsClientHandshakerTest,BadTransportParams)712 TEST_P(TlsClientHandshakerTest, BadTransportParams) {
713 if (!connection_->version().UsesHttp3()) {
714 return;
715 }
716 // Finish establishing the first connection:
717 CompleteCryptoHandshake();
718
719 // Create a second connection
720 CreateConnection();
721
722 stream()->CryptoConnect();
723 auto* id_manager = QuicSessionPeer::ietf_streamid_manager(session_.get());
724 EXPECT_EQ(kDefaultMaxStreamsPerConnection,
725 id_manager->max_outgoing_bidirectional_streams());
726 QuicConfig config;
727 config.SetMaxBidirectionalStreamsToSend(
728 config.GetMaxBidirectionalStreamsToSend() - 1);
729
730 EXPECT_CALL(*connection_,
731 CloseConnection(QUIC_ZERO_RTT_REJECTION_LIMIT_REDUCED, _, _))
732 .WillOnce(testing::Invoke(connection_,
733 &MockQuicConnection::ReallyCloseConnection));
734 // Close connection will be called again in the handshaker, but this will be
735 // no-op as the connection is already closed.
736 EXPECT_CALL(*connection_, CloseConnection(QUIC_HANDSHAKE_FAILED, _, _));
737
738 crypto_test_utils::HandshakeWithFakeServer(
739 &config, server_crypto_config_.get(), &server_helper_, &alarm_factory_,
740 connection_, stream(), AlpnForVersion(connection_->version()));
741 }
742
TEST_P(TlsClientHandshakerTest,ECH)743 TEST_P(TlsClientHandshakerTest, ECH) {
744 ssl_config_.emplace();
745 bssl::UniquePtr<SSL_ECH_KEYS> ech_keys =
746 MakeTestEchKeys("public-name.example", /*max_name_len=*/64,
747 &ssl_config_->ech_config_list);
748 ASSERT_TRUE(ech_keys);
749
750 // Configure the server to use the test ECH keys.
751 ASSERT_TRUE(
752 SSL_CTX_set1_ech_keys(server_crypto_config_->ssl_ctx(), ech_keys.get()));
753
754 // Recreate the client to pick up the new `ssl_config_`.
755 CreateConnection();
756
757 // The handshake should complete and negotiate ECH.
758 CompleteCryptoHandshake();
759 EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol());
760 EXPECT_TRUE(stream()->encryption_established());
761 EXPECT_TRUE(stream()->one_rtt_keys_available());
762 EXPECT_TRUE(stream()->crypto_negotiated_params().encrypted_client_hello);
763 }
764
TEST_P(TlsClientHandshakerTest,ECHWithConfigAndGREASE)765 TEST_P(TlsClientHandshakerTest, ECHWithConfigAndGREASE) {
766 ssl_config_.emplace();
767 bssl::UniquePtr<SSL_ECH_KEYS> ech_keys =
768 MakeTestEchKeys("public-name.example", /*max_name_len=*/64,
769 &ssl_config_->ech_config_list);
770 ASSERT_TRUE(ech_keys);
771 ssl_config_->ech_grease_enabled = true;
772
773 // Configure the server to use the test ECH keys.
774 ASSERT_TRUE(
775 SSL_CTX_set1_ech_keys(server_crypto_config_->ssl_ctx(), ech_keys.get()));
776
777 // Recreate the client to pick up the new `ssl_config_`.
778 CreateConnection();
779
780 // When both ECH and ECH GREASE are enabled, ECH should take precedence.
781 // The handshake should complete and negotiate ECH.
782 CompleteCryptoHandshake();
783 EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol());
784 EXPECT_TRUE(stream()->encryption_established());
785 EXPECT_TRUE(stream()->one_rtt_keys_available());
786 EXPECT_TRUE(stream()->crypto_negotiated_params().encrypted_client_hello);
787 }
788
TEST_P(TlsClientHandshakerTest,ECHInvalidConfig)789 TEST_P(TlsClientHandshakerTest, ECHInvalidConfig) {
790 // An invalid ECHConfigList should fail before sending a ClientHello.
791 ssl_config_.emplace();
792 ssl_config_->ech_config_list = "invalid config";
793 CreateConnection();
794 EXPECT_CALL(*connection_, CloseConnection(QUIC_HANDSHAKE_FAILED, _, _));
795 stream()->CryptoConnect();
796 }
797
TEST_P(TlsClientHandshakerTest,ECHWrongKeys)798 TEST_P(TlsClientHandshakerTest, ECHWrongKeys) {
799 ssl_config_.emplace();
800 bssl::UniquePtr<SSL_ECH_KEYS> ech_keys1 =
801 MakeTestEchKeys("public-name.example", /*max_name_len=*/64,
802 &ssl_config_->ech_config_list);
803 ASSERT_TRUE(ech_keys1);
804
805 std::string ech_config_list2;
806 bssl::UniquePtr<SSL_ECH_KEYS> ech_keys2 = MakeTestEchKeys(
807 "public-name.example", /*max_name_len=*/64, &ech_config_list2);
808 ASSERT_TRUE(ech_keys2);
809
810 // Configure the server to use different keys from what the client has.
811 ASSERT_TRUE(
812 SSL_CTX_set1_ech_keys(server_crypto_config_->ssl_ctx(), ech_keys2.get()));
813
814 // Recreate the client to pick up the new `ssl_config_`.
815 CreateConnection();
816
817 // TODO(crbug.com/1287248): This should instead output sufficient information
818 // to run the recovery flow.
819 EXPECT_CALL(*connection_,
820 CloseConnection(QUIC_HANDSHAKE_FAILED,
821 static_cast<QuicIetfTransportErrorCodes>(
822 CRYPTO_ERROR_FIRST + SSL_AD_ECH_REQUIRED),
823 _, _))
824 .WillOnce(testing::Invoke(connection_,
825 &MockQuicConnection::ReallyCloseConnection4));
826
827 // The handshake should complete and negotiate ECH.
828 CompleteCryptoHandshake();
829 }
830
831 // Test that ECH GREASE can be configured.
TEST_P(TlsClientHandshakerTest,ECHGrease)832 TEST_P(TlsClientHandshakerTest, ECHGrease) {
833 ssl_config_.emplace();
834 ssl_config_->ech_grease_enabled = true;
835 CreateConnection();
836
837 // Add a DoS callback on the server, to test that the client sent a GREASE
838 // message. This is a bit of a hack. TlsServerHandshaker already configures
839 // the certificate selection callback, but does not usefully expose any way
840 // for tests to inspect the ClientHello. So, instead, we register a different
841 // callback that also gets the ClientHello.
842 static bool callback_ran;
843 callback_ran = false;
844 SSL_CTX_set_dos_protection_cb(
845 server_crypto_config_->ssl_ctx(),
846 [](const SSL_CLIENT_HELLO* client_hello) -> int {
847 const uint8_t* data;
848 size_t len;
849 EXPECT_TRUE(SSL_early_callback_ctx_extension_get(
850 client_hello, TLSEXT_TYPE_encrypted_client_hello, &data, &len));
851 callback_ran = true;
852 return 1;
853 });
854
855 CompleteCryptoHandshake();
856 EXPECT_TRUE(callback_ran);
857
858 EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol());
859 EXPECT_TRUE(stream()->encryption_established());
860 EXPECT_TRUE(stream()->one_rtt_keys_available());
861 // Sending an ignored ECH GREASE extension does not count as negotiating ECH.
862 EXPECT_FALSE(stream()->crypto_negotiated_params().encrypted_client_hello);
863 }
864
865 #if BORINGSSL_API_VERSION >= 22
TEST_P(TlsClientHandshakerTest,EnableKyber)866 TEST_P(TlsClientHandshakerTest, EnableKyber) {
867 crypto_config_->set_preferred_groups({SSL_GROUP_X25519_KYBER768_DRAFT00});
868 server_crypto_config_->set_preferred_groups(
869 {SSL_GROUP_X25519_KYBER768_DRAFT00, SSL_GROUP_X25519, SSL_GROUP_SECP256R1,
870 SSL_GROUP_SECP384R1});
871 CreateConnection();
872
873 CompleteCryptoHandshake();
874 EXPECT_TRUE(stream()->encryption_established());
875 EXPECT_TRUE(stream()->one_rtt_keys_available());
876 EXPECT_EQ(SSL_GROUP_X25519_KYBER768_DRAFT00,
877 SSL_get_group_id(stream()->GetSsl()));
878 }
879 #endif // BORINGSSL_API_VERSION
880
881 #if BORINGSSL_API_VERSION >= 27
TEST_P(TlsClientHandshakerTest,EnableClientAlpsUseNewCodepoint)882 TEST_P(TlsClientHandshakerTest, EnableClientAlpsUseNewCodepoint) {
883 // The intent of this test is to demonstrate no matter whether server
884 // allows the new ALPS codepoint or not, the handshake should complete
885 // successfully.
886 for (bool server_allow_alps_new_codepoint : {true, false}) {
887 SCOPED_TRACE(absl::StrCat("Test allows alps new codepoint:",
888 server_allow_alps_new_codepoint));
889 crypto_config_->set_alps_use_new_codepoint(true);
890 SetQuicReloadableFlag(quic_gfe_allow_alps_new_codepoint,
891 server_allow_alps_new_codepoint);
892 CreateConnection();
893
894 // Add a DoS callback on the server, to test that the client sent the new
895 // ALPS codepoint.
896 static bool callback_ran;
897 callback_ran = false;
898 SSL_CTX_set_dos_protection_cb(
899 server_crypto_config_->ssl_ctx(),
900 [](const SSL_CLIENT_HELLO* client_hello) -> int {
901 const uint8_t* data;
902 size_t len;
903 EXPECT_TRUE(SSL_early_callback_ctx_extension_get(
904 client_hello, TLSEXT_TYPE_application_settings, &data, &len));
905 callback_ran = true;
906 return 1;
907 });
908
909 CompleteCryptoHandshake();
910 EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol());
911 EXPECT_TRUE(callback_ran);
912 }
913 }
914 #endif // BORINGSSL_API_VERSION
915
916 } // namespace
917 } // namespace test
918 } // namespace quic
919