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.
5 #include "net/quic/quic_crypto_client_stream.h"
7 #include "base/metrics/histogram_macros.h"
8 #include "base/profiler/scoped_tracker.h"
9 #include "net/quic/crypto/crypto_protocol.h"
10 #include "net/quic/crypto/crypto_utils.h"
11 #include "net/quic/crypto/null_encrypter.h"
12 #include "net/quic/quic_client_session_base.h"
13 #include "net/quic/quic_flags.h"
14 #include "net/quic/quic_protocol.h"
15 #include "net/quic/quic_session.h"
21 QuicCryptoClientStream::ChannelIDSourceCallbackImpl::
22 ChannelIDSourceCallbackImpl(QuicCryptoClientStream
* stream
)
25 QuicCryptoClientStream::ChannelIDSourceCallbackImpl::
26 ~ChannelIDSourceCallbackImpl() {}
28 void QuicCryptoClientStream::ChannelIDSourceCallbackImpl::Run(
29 scoped_ptr
<ChannelIDKey
>* channel_id_key
) {
30 if (stream_
== nullptr) {
34 stream_
->channel_id_key_
.reset(channel_id_key
->release());
35 stream_
->channel_id_source_callback_run_
= true;
36 stream_
->channel_id_source_callback_
= nullptr;
37 stream_
->DoHandshakeLoop(nullptr);
39 // The ChannelIDSource owns this object and will delete it when this method
43 void QuicCryptoClientStream::ChannelIDSourceCallbackImpl::Cancel() {
47 QuicCryptoClientStream::ProofVerifierCallbackImpl::ProofVerifierCallbackImpl(
48 QuicCryptoClientStream
* stream
)
51 QuicCryptoClientStream::ProofVerifierCallbackImpl::
52 ~ProofVerifierCallbackImpl() {}
54 void QuicCryptoClientStream::ProofVerifierCallbackImpl::Run(
56 const string
& error_details
,
57 scoped_ptr
<ProofVerifyDetails
>* details
) {
58 if (stream_
== nullptr) {
62 stream_
->verify_ok_
= ok
;
63 stream_
->verify_error_details_
= error_details
;
64 stream_
->verify_details_
.reset(details
->release());
65 stream_
->proof_verify_callback_
= nullptr;
66 stream_
->DoHandshakeLoop(nullptr);
68 // The ProofVerifier owns this object and will delete it when this method
72 void QuicCryptoClientStream::ProofVerifierCallbackImpl::Cancel() {
76 QuicCryptoClientStream::QuicCryptoClientStream(
77 const QuicServerId
& server_id
,
78 QuicClientSessionBase
* session
,
79 ProofVerifyContext
* verify_context
,
80 QuicCryptoClientConfig
* crypto_config
)
81 : QuicCryptoStream(session
),
82 next_state_(STATE_IDLE
),
83 num_client_hellos_(0),
84 crypto_config_(crypto_config
),
85 server_id_(server_id
),
86 generation_counter_(0),
87 channel_id_sent_(false),
88 channel_id_source_callback_run_(false),
89 channel_id_source_callback_(nullptr),
90 verify_context_(verify_context
),
91 proof_verify_callback_(nullptr),
92 stateless_reject_received_(false) {
93 DCHECK_EQ(Perspective::IS_CLIENT
, session
->connection()->perspective());
96 QuicCryptoClientStream::~QuicCryptoClientStream() {
97 if (channel_id_source_callback_
) {
98 channel_id_source_callback_
->Cancel();
100 if (proof_verify_callback_
) {
101 proof_verify_callback_
->Cancel();
105 void QuicCryptoClientStream::OnHandshakeMessage(
106 const CryptoHandshakeMessage
& message
) {
107 QuicCryptoStream::OnHandshakeMessage(message
);
109 if (message
.tag() == kSCUP
) {
110 if (!handshake_confirmed()) {
111 CloseConnection(QUIC_CRYPTO_UPDATE_BEFORE_HANDSHAKE_COMPLETE
);
115 // |message| is an update from the server, so we treat it differently from a
116 // handshake message.
117 HandleServerConfigUpdateMessage(message
);
121 // Do not process handshake messages after the handshake is confirmed.
122 if (handshake_confirmed()) {
123 CloseConnection(QUIC_CRYPTO_MESSAGE_AFTER_HANDSHAKE_COMPLETE
);
127 DoHandshakeLoop(&message
);
130 void QuicCryptoClientStream::CryptoConnect() {
131 next_state_
= STATE_INITIALIZE
;
132 DoHandshakeLoop(nullptr);
135 int QuicCryptoClientStream::num_sent_client_hellos() const {
136 return num_client_hellos_
;
139 // Used in Chromium, but not in the server.
140 bool QuicCryptoClientStream::WasChannelIDSent() const {
141 return channel_id_sent_
;
144 bool QuicCryptoClientStream::WasChannelIDSourceCallbackRun() const {
145 return channel_id_source_callback_run_
;
148 void QuicCryptoClientStream::HandleServerConfigUpdateMessage(
149 const CryptoHandshakeMessage
& server_config_update
) {
150 DCHECK(server_config_update
.tag() == kSCUP
);
151 string error_details
;
152 QuicCryptoClientConfig::CachedState
* cached
=
153 crypto_config_
->LookupOrCreate(server_id_
);
154 QuicErrorCode error
= crypto_config_
->ProcessServerConfigUpdate(
155 server_config_update
,
156 session()->connection()->clock()->WallNow(),
158 &crypto_negotiated_params_
,
161 if (error
!= QUIC_NO_ERROR
) {
162 CloseConnectionWithDetails(
163 error
, "Server config update invalid: " + error_details
);
167 DCHECK(handshake_confirmed());
168 if (proof_verify_callback_
) {
169 proof_verify_callback_
->Cancel();
171 next_state_
= STATE_INITIALIZE_SCUP
;
172 DoHandshakeLoop(nullptr);
175 void QuicCryptoClientStream::DoHandshakeLoop(
176 const CryptoHandshakeMessage
* in
) {
177 QuicCryptoClientConfig::CachedState
* cached
=
178 crypto_config_
->LookupOrCreate(server_id_
);
180 QuicAsyncStatus rv
= QUIC_SUCCESS
;
182 CHECK_NE(STATE_NONE
, next_state_
);
183 const State state
= next_state_
;
184 next_state_
= STATE_IDLE
;
187 case STATE_INITIALIZE
:
188 DoInitialize(cached
);
190 case STATE_SEND_CHLO
:
191 DoSendCHLO(in
, cached
);
192 return; // return waiting to hear from server.
194 DoReceiveREJ(in
, cached
);
196 case STATE_VERIFY_PROOF
:
197 rv
= DoVerifyProof(cached
);
199 case STATE_VERIFY_PROOF_COMPLETE
:
200 DoVerifyProofComplete(cached
);
202 case STATE_GET_CHANNEL_ID
:
203 rv
= DoGetChannelID(cached
);
205 case STATE_GET_CHANNEL_ID_COMPLETE
:
206 DoGetChannelIDComplete();
208 case STATE_RECV_SHLO
:
209 DoReceiveSHLO(in
, cached
);
212 // This means that the peer sent us a message that we weren't expecting.
213 CloseConnection(QUIC_INVALID_CRYPTO_MESSAGE_TYPE
);
215 case STATE_INITIALIZE_SCUP
:
216 DoInitializeServerConfigUpdate(cached
);
220 return; // We are done.
222 } while (rv
!= QUIC_PENDING
&& next_state_
!= STATE_NONE
);
225 void QuicCryptoClientStream::DoInitialize(
226 QuicCryptoClientConfig::CachedState
* cached
) {
227 if (!cached
->IsEmpty() && !cached
->signature().empty() &&
228 server_id_
.is_https()) {
229 // Note that we verify the proof even if the cached proof is valid.
230 // This allows us to respond to CA trust changes or certificate
231 // expiration because it may have been a while since we last verified
233 DCHECK(crypto_config_
->proof_verifier());
234 // If the cached state needs to be verified, do it now.
235 next_state_
= STATE_VERIFY_PROOF
;
237 next_state_
= STATE_GET_CHANNEL_ID
;
241 void QuicCryptoClientStream::DoSendCHLO(
242 const CryptoHandshakeMessage
* in
,
243 QuicCryptoClientConfig::CachedState
* cached
) {
244 if (stateless_reject_received_
) {
245 // If we've gotten to this point, we've sent at least one hello
246 // and received a stateless reject in response. We cannot
247 // continue to send hellos because the server has abandoned state
248 // for this connection. Abandon further handshakes.
249 next_state_
= STATE_NONE
;
250 if (session()->connection()->connected()) {
251 session()->connection()->CloseConnection(
252 QUIC_CRYPTO_HANDSHAKE_STATELESS_REJECT
, false);
257 // Send the client hello in plaintext.
258 session()->connection()->SetDefaultEncryptionLevel(ENCRYPTION_NONE
);
259 if (num_client_hellos_
> kMaxClientHellos
) {
260 CloseConnection(QUIC_CRYPTO_TOO_MANY_REJECTS
);
263 num_client_hellos_
++;
265 CryptoHandshakeMessage out
;
266 DCHECK(session() != nullptr);
267 DCHECK(session()->config() != nullptr);
268 // Send all the options, regardless of whether we're sending an
269 // inchoate or subsequent hello.
270 session()->config()->ToHandshakeMessage(&out
);
271 if (!cached
->IsComplete(session()->connection()->clock()->WallNow())) {
272 crypto_config_
->FillInchoateClientHello(
274 session()->connection()->supported_versions().front(),
275 cached
, &crypto_negotiated_params_
, &out
);
276 // Pad the inchoate client hello to fill up a packet.
277 const QuicByteCount kFramingOverhead
= 50; // A rough estimate.
278 const QuicByteCount max_packet_size
=
279 session()->connection()->max_packet_length();
280 if (max_packet_size
<= kFramingOverhead
) {
281 DLOG(DFATAL
) << "max_packet_length (" << max_packet_size
282 << ") has no room for framing overhead.";
283 CloseConnection(QUIC_INTERNAL_ERROR
);
286 if (kClientHelloMinimumSize
> max_packet_size
- kFramingOverhead
) {
287 DLOG(DFATAL
) << "Client hello won't fit in a single packet.";
288 CloseConnection(QUIC_INTERNAL_ERROR
);
291 out
.set_minimum_size(
292 static_cast<size_t>(max_packet_size
- kFramingOverhead
));
293 next_state_
= STATE_RECV_REJ
;
294 SendHandshakeMessage(out
);
298 // If the server nonce is empty, copy over the server nonce from a previous
299 // SREJ, if there is one.
300 if (FLAGS_enable_quic_stateless_reject_support
&&
301 crypto_negotiated_params_
.server_nonce
.empty() &&
302 cached
->has_server_nonce()) {
303 crypto_negotiated_params_
.server_nonce
= cached
->GetNextServerNonce();
304 DCHECK(!crypto_negotiated_params_
.server_nonce
.empty());
307 string error_details
;
308 QuicErrorCode error
= crypto_config_
->FillClientHello(
310 session()->connection()->connection_id(),
311 session()->connection()->supported_versions().front(),
313 session()->connection()->clock()->WallNow(),
314 session()->connection()->random_generator(),
315 channel_id_key_
.get(),
316 &crypto_negotiated_params_
,
320 if (error
!= QUIC_NO_ERROR
) {
321 // Flush the cached config so that, if it's bad, the server has a
322 // chance to send us another in the future.
323 cached
->InvalidateServerConfig();
324 CloseConnectionWithDetails(error
, error_details
);
327 channel_id_sent_
= (channel_id_key_
.get() != nullptr);
328 if (cached
->proof_verify_details()) {
329 client_session()->OnProofVerifyDetailsAvailable(
330 *cached
->proof_verify_details());
332 next_state_
= STATE_RECV_SHLO
;
333 SendHandshakeMessage(out
);
334 // Be prepared to decrypt with the new server write key.
335 session()->connection()->SetAlternativeDecrypter(
337 crypto_negotiated_params_
.initial_crypters
.decrypter
.release(),
338 true /* latch once used */);
339 // Send subsequent packets under encryption on the assumption that the
340 // server will accept the handshake.
341 session()->connection()->SetEncrypter(
343 crypto_negotiated_params_
.initial_crypters
.encrypter
.release());
344 session()->connection()->SetDefaultEncryptionLevel(
346 if (!encryption_established_
) {
347 encryption_established_
= true;
348 session()->OnCryptoHandshakeEvent(
349 QuicSession::ENCRYPTION_FIRST_ESTABLISHED
);
351 session()->OnCryptoHandshakeEvent(
352 QuicSession::ENCRYPTION_REESTABLISHED
);
356 void QuicCryptoClientStream::DoReceiveREJ(
357 const CryptoHandshakeMessage
* in
,
358 QuicCryptoClientConfig::CachedState
* cached
) {
359 // TODO(rtenneti): Remove ScopedTracker below once crbug.com/422516 is fixed.
360 tracked_objects::ScopedTracker
tracking_profile(
361 FROM_HERE_WITH_EXPLICIT_FUNCTION(
362 "422516 QuicCryptoClientStream::DoReceiveREJ"));
364 // We sent a dummy CHLO because we didn't have enough information to
365 // perform a handshake, or we sent a full hello that the server
366 // rejected. Here we hope to have a REJ that contains the information
368 if ((in
->tag() != kREJ
) && (in
->tag() != kSREJ
)) {
369 next_state_
= STATE_NONE
;
370 CloseConnectionWithDetails(QUIC_INVALID_CRYPTO_MESSAGE_TYPE
,
374 stateless_reject_received_
= in
->tag() == kSREJ
;
375 string error_details
;
376 QuicErrorCode error
= crypto_config_
->ProcessRejection(
377 *in
, session()->connection()->clock()->WallNow(), cached
,
378 server_id_
.is_https(), &crypto_negotiated_params_
, &error_details
);
380 if (error
!= QUIC_NO_ERROR
) {
381 next_state_
= STATE_NONE
;
382 CloseConnectionWithDetails(error
, error_details
);
385 if (!cached
->proof_valid()) {
386 if (!server_id_
.is_https()) {
387 // We don't check the certificates for insecure QUIC connections.
388 SetCachedProofValid(cached
);
389 } else if (!cached
->signature().empty()) {
390 // Note that we only verify the proof if the cached proof is not
391 // valid. If the cached proof is valid here, someone else must have
392 // just added the server config to the cache and verified the proof,
393 // so we can assume no CA trust changes or certificate expiration
394 // has happened since then.
395 next_state_
= STATE_VERIFY_PROOF
;
399 next_state_
= STATE_GET_CHANNEL_ID
;
402 QuicAsyncStatus
QuicCryptoClientStream::DoVerifyProof(
403 QuicCryptoClientConfig::CachedState
* cached
) {
404 ProofVerifier
* verifier
= crypto_config_
->proof_verifier();
406 next_state_
= STATE_VERIFY_PROOF_COMPLETE
;
407 generation_counter_
= cached
->generation_counter();
409 ProofVerifierCallbackImpl
* proof_verify_callback
=
410 new ProofVerifierCallbackImpl(this);
414 QuicAsyncStatus status
= verifier
->VerifyProof(
415 server_id_
.host(), cached
->server_config(), cached
->certs(),
416 cached
->signature(), verify_context_
.get(), &verify_error_details_
,
417 &verify_details_
, proof_verify_callback
);
421 proof_verify_callback_
= proof_verify_callback
;
422 DVLOG(1) << "Doing VerifyProof";
425 delete proof_verify_callback
;
428 delete proof_verify_callback
;
435 void QuicCryptoClientStream::DoVerifyProofComplete(
436 QuicCryptoClientConfig::CachedState
* cached
) {
438 next_state_
= STATE_NONE
;
439 if (verify_details_
.get()) {
440 client_session()->OnProofVerifyDetailsAvailable(*verify_details_
);
442 UMA_HISTOGRAM_BOOLEAN("Net.QuicVerifyProofFailed.HandshakeConfirmed",
443 handshake_confirmed());
444 CloseConnectionWithDetails(
445 QUIC_PROOF_INVALID
, "Proof invalid: " + verify_error_details_
);
449 // Check if generation_counter has changed between STATE_VERIFY_PROOF and
450 // STATE_VERIFY_PROOF_COMPLETE state changes.
451 if (generation_counter_
!= cached
->generation_counter()) {
452 next_state_
= STATE_VERIFY_PROOF
;
454 SetCachedProofValid(cached
);
455 cached
->SetProofVerifyDetails(verify_details_
.release());
456 if (!handshake_confirmed()) {
457 next_state_
= STATE_GET_CHANNEL_ID
;
459 next_state_
= STATE_NONE
;
464 QuicAsyncStatus
QuicCryptoClientStream::DoGetChannelID(
465 QuicCryptoClientConfig::CachedState
* cached
) {
466 next_state_
= STATE_GET_CHANNEL_ID_COMPLETE
;
467 channel_id_key_
.reset();
468 if (!RequiresChannelID(cached
)) {
469 next_state_
= STATE_SEND_CHLO
;
473 ChannelIDSourceCallbackImpl
* channel_id_source_callback
=
474 new ChannelIDSourceCallbackImpl(this);
475 QuicAsyncStatus status
=
476 crypto_config_
->channel_id_source()->GetChannelIDKey(
477 server_id_
.host(), &channel_id_key_
,
478 channel_id_source_callback
);
482 channel_id_source_callback_
= channel_id_source_callback
;
483 DVLOG(1) << "Looking up channel ID";
486 next_state_
= STATE_NONE
;
487 delete channel_id_source_callback
;
488 CloseConnectionWithDetails(QUIC_INVALID_CHANNEL_ID_SIGNATURE
,
489 "Channel ID lookup failed");
492 delete channel_id_source_callback
;
498 void QuicCryptoClientStream::DoGetChannelIDComplete() {
499 if (!channel_id_key_
.get()) {
500 next_state_
= STATE_NONE
;
501 CloseConnectionWithDetails(QUIC_INVALID_CHANNEL_ID_SIGNATURE
,
502 "Channel ID lookup failed");
505 next_state_
= STATE_SEND_CHLO
;
508 void QuicCryptoClientStream::DoReceiveSHLO(
509 const CryptoHandshakeMessage
* in
,
510 QuicCryptoClientConfig::CachedState
* cached
) {
511 next_state_
= STATE_NONE
;
512 // We sent a CHLO that we expected to be accepted and now we're
513 // hoping for a SHLO from the server to confirm that. First check
514 // to see whether the response was a reject, and if so, move on to
515 // the reject-processing state.
516 if ((in
->tag() == kREJ
) || (in
->tag() == kSREJ
)) {
517 // alternative_decrypter will be nullptr if the original alternative
518 // decrypter latched and became the primary decrypter. That happens
519 // if we received a message encrypted with the INITIAL key.
520 if (session()->connection()->alternative_decrypter() == nullptr) {
521 // The rejection was sent encrypted!
522 CloseConnectionWithDetails(QUIC_CRYPTO_ENCRYPTION_LEVEL_INCORRECT
,
523 "encrypted REJ message");
526 next_state_
= STATE_RECV_REJ
;
530 if (in
->tag() != kSHLO
) {
531 CloseConnectionWithDetails(QUIC_INVALID_CRYPTO_MESSAGE_TYPE
,
532 "Expected SHLO or REJ");
536 // alternative_decrypter will be nullptr if the original alternative
537 // decrypter latched and became the primary decrypter. That happens
538 // if we received a message encrypted with the INITIAL key.
539 if (session()->connection()->alternative_decrypter() != nullptr) {
540 // The server hello was sent without encryption.
541 CloseConnectionWithDetails(QUIC_CRYPTO_ENCRYPTION_LEVEL_INCORRECT
,
542 "unencrypted SHLO message");
546 string error_details
;
547 QuicErrorCode error
= crypto_config_
->ProcessServerHello(
548 *in
, session()->connection()->connection_id(),
549 session()->connection()->server_supported_versions(),
550 cached
, &crypto_negotiated_params_
, &error_details
);
552 if (error
!= QUIC_NO_ERROR
) {
553 CloseConnectionWithDetails(error
, "Server hello invalid: " + error_details
);
556 error
= session()->config()->ProcessPeerHello(*in
, SERVER
, &error_details
);
557 if (error
!= QUIC_NO_ERROR
) {
558 CloseConnectionWithDetails(error
, "Server hello invalid: " + error_details
);
561 session()->OnConfigNegotiated();
563 CrypterPair
* crypters
= &crypto_negotiated_params_
.forward_secure_crypters
;
564 // TODO(agl): we don't currently latch this decrypter because the idea
565 // has been floated that the server shouldn't send packets encrypted
566 // with the FORWARD_SECURE key until it receives a FORWARD_SECURE
567 // packet from the client.
568 session()->connection()->SetAlternativeDecrypter(
569 ENCRYPTION_FORWARD_SECURE
, crypters
->decrypter
.release(),
570 false /* don't latch */);
571 session()->connection()->SetEncrypter(
572 ENCRYPTION_FORWARD_SECURE
, crypters
->encrypter
.release());
573 session()->connection()->SetDefaultEncryptionLevel(
574 ENCRYPTION_FORWARD_SECURE
);
576 handshake_confirmed_
= true;
577 session()->OnCryptoHandshakeEvent(QuicSession::HANDSHAKE_CONFIRMED
);
578 session()->connection()->OnHandshakeComplete();
581 void QuicCryptoClientStream::DoInitializeServerConfigUpdate(
582 QuicCryptoClientConfig::CachedState
* cached
) {
583 bool update_ignored
= false;
584 if (!server_id_
.is_https()) {
585 // We don't check the certificates for insecure QUIC connections.
586 SetCachedProofValid(cached
);
587 next_state_
= STATE_NONE
;
588 } else if (!cached
->IsEmpty() && !cached
->signature().empty()) {
589 // Note that we verify the proof even if the cached proof is valid.
590 DCHECK(crypto_config_
->proof_verifier());
591 next_state_
= STATE_VERIFY_PROOF
;
593 update_ignored
= true;
594 next_state_
= STATE_NONE
;
596 UMA_HISTOGRAM_COUNTS("Net.QuicNumServerConfig.UpdateMessagesIgnored",
600 void QuicCryptoClientStream::SetCachedProofValid(
601 QuicCryptoClientConfig::CachedState
* cached
) {
602 cached
->SetProofValid();
603 client_session()->OnProofValid(*cached
);
606 bool QuicCryptoClientStream::RequiresChannelID(
607 QuicCryptoClientConfig::CachedState
* cached
) {
608 if (!server_id_
.is_https() ||
609 server_id_
.privacy_mode() == PRIVACY_MODE_ENABLED
||
610 !crypto_config_
->channel_id_source()) {
613 const CryptoHandshakeMessage
* scfg
= cached
->GetServerConfig();
614 if (!scfg
) { // scfg may be null then we send an inchoate CHLO.
617 const QuicTag
* their_proof_demands
;
618 size_t num_their_proof_demands
;
619 if (scfg
->GetTaglist(kPDMD
, &their_proof_demands
,
620 &num_their_proof_demands
) != QUIC_NO_ERROR
) {
623 for (size_t i
= 0; i
< num_their_proof_demands
; i
++) {
624 if (their_proof_demands
[i
] == kCHID
) {
631 QuicClientSessionBase
* QuicCryptoClientStream::client_session() {
632 return reinterpret_cast<QuicClientSessionBase
*>(session());