1 // Copyright 2013 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/crypto/quic_crypto_server_config.h"
10 #include "base/stl_util.h"
11 #include "base/strings/string_number_conversions.h"
12 #include "crypto/hkdf.h"
13 #include "crypto/secure_hash.h"
14 #include "net/base/net_util.h"
15 #include "net/quic/crypto/aes_128_gcm_12_decrypter.h"
16 #include "net/quic/crypto/aes_128_gcm_12_encrypter.h"
17 #include "net/quic/crypto/cert_compressor.h"
18 #include "net/quic/crypto/chacha20_poly1305_encrypter.h"
19 #include "net/quic/crypto/channel_id.h"
20 #include "net/quic/crypto/crypto_framer.h"
21 #include "net/quic/crypto/crypto_handshake_message.h"
22 #include "net/quic/crypto/crypto_server_config_protobuf.h"
23 #include "net/quic/crypto/crypto_utils.h"
24 #include "net/quic/crypto/curve25519_key_exchange.h"
25 #include "net/quic/crypto/ephemeral_key_source.h"
26 #include "net/quic/crypto/key_exchange.h"
27 #include "net/quic/crypto/local_strike_register_client.h"
28 #include "net/quic/crypto/p256_key_exchange.h"
29 #include "net/quic/crypto/proof_source.h"
30 #include "net/quic/crypto/quic_decrypter.h"
31 #include "net/quic/crypto/quic_encrypter.h"
32 #include "net/quic/crypto/quic_random.h"
33 #include "net/quic/crypto/strike_register.h"
34 #include "net/quic/crypto/strike_register_client.h"
35 #include "net/quic/proto/source_address_token.pb.h"
36 #include "net/quic/quic_clock.h"
37 #include "net/quic/quic_flags.h"
38 #include "net/quic/quic_protocol.h"
39 #include "net/quic/quic_socket_address_coder.h"
40 #include "net/quic/quic_utils.h"
42 using base::StringPiece
;
43 using crypto::SecureHash
;
53 const int kMaxTokenAddresses
= 4;
55 string
DeriveSourceAddressTokenKey(StringPiece source_address_token_secret
) {
56 crypto::HKDF
hkdf(source_address_token_secret
,
57 StringPiece() /* no salt */,
58 "QUIC source address token key",
59 CryptoSecretBoxer::GetKeySize(),
60 0 /* no fixed IV needed */,
61 0 /* no subkey secret */);
62 return hkdf
.server_write_key().as_string();
65 IPAddressNumber
DualstackIPAddress(const IPAddressNumber
& ip
) {
66 if (ip
.size() == kIPv4AddressSize
) {
67 return ConvertIPv4NumberToIPv6Number(ip
);
74 class ValidateClientHelloHelper
{
76 ValidateClientHelloHelper(ValidateClientHelloResultCallback::Result
* result
,
77 ValidateClientHelloResultCallback
* done_cb
)
78 : result_(result
), done_cb_(done_cb
) {
81 ~ValidateClientHelloHelper() {
82 LOG_IF(DFATAL
, done_cb_
!= nullptr)
83 << "Deleting ValidateClientHelloHelper with a pending callback.";
86 void ValidationComplete(QuicErrorCode error_code
, const char* error_details
) {
87 result_
->error_code
= error_code
;
88 result_
->error_details
= error_details
;
89 done_cb_
->Run(result_
);
93 void StartedAsyncCallback() {
98 void DetachCallback() {
99 LOG_IF(DFATAL
, done_cb_
== nullptr) << "Callback already detached.";
103 ValidateClientHelloResultCallback::Result
* result_
;
104 ValidateClientHelloResultCallback
* done_cb_
;
106 DISALLOW_COPY_AND_ASSIGN(ValidateClientHelloHelper
);
109 class VerifyNonceIsValidAndUniqueCallback
110 : public StrikeRegisterClient::ResultCallback
{
112 VerifyNonceIsValidAndUniqueCallback(
113 ValidateClientHelloResultCallback::Result
* result
,
114 ValidateClientHelloResultCallback
* done_cb
)
115 : result_(result
), done_cb_(done_cb
) {
119 void RunImpl(bool nonce_is_valid_and_unique
,
120 InsertStatus nonce_error
) override
{
121 DVLOG(1) << "Using client nonce, unique: " << nonce_is_valid_and_unique
122 << " nonce_error: " << nonce_error
;
123 result_
->info
.unique
= nonce_is_valid_and_unique
;
124 if (!nonce_is_valid_and_unique
) {
125 HandshakeFailureReason client_nonce_error
;
126 switch (nonce_error
) {
127 case NONCE_INVALID_FAILURE
:
128 client_nonce_error
= CLIENT_NONCE_INVALID_FAILURE
;
130 case NONCE_NOT_UNIQUE_FAILURE
:
131 client_nonce_error
= CLIENT_NONCE_NOT_UNIQUE_FAILURE
;
133 case NONCE_INVALID_ORBIT_FAILURE
:
134 client_nonce_error
= CLIENT_NONCE_INVALID_ORBIT_FAILURE
;
136 case NONCE_INVALID_TIME_FAILURE
:
137 client_nonce_error
= CLIENT_NONCE_INVALID_TIME_FAILURE
;
139 case STRIKE_REGISTER_TIMEOUT
:
140 client_nonce_error
= CLIENT_NONCE_STRIKE_REGISTER_TIMEOUT
;
142 case STRIKE_REGISTER_FAILURE
:
143 client_nonce_error
= CLIENT_NONCE_STRIKE_REGISTER_FAILURE
;
145 case NONCE_UNKNOWN_FAILURE
:
146 client_nonce_error
= CLIENT_NONCE_UNKNOWN_FAILURE
;
150 LOG(DFATAL
) << "Unexpected client nonce error: " << nonce_error
;
151 client_nonce_error
= CLIENT_NONCE_UNKNOWN_FAILURE
;
154 result_
->info
.reject_reasons
.push_back(client_nonce_error
);
156 done_cb_
->Run(result_
);
160 ValidateClientHelloResultCallback::Result
* result_
;
161 ValidateClientHelloResultCallback
* done_cb_
;
163 DISALLOW_COPY_AND_ASSIGN(VerifyNonceIsValidAndUniqueCallback
);
167 const char QuicCryptoServerConfig::TESTING
[] = "secret string for testing";
169 ClientHelloInfo::ClientHelloInfo(const IPAddressNumber
& in_client_ip
,
171 : client_ip(in_client_ip
),
173 valid_source_address_token(false),
174 client_nonce_well_formed(false),
178 ClientHelloInfo::~ClientHelloInfo() {
181 PrimaryConfigChangedCallback::PrimaryConfigChangedCallback() {
184 PrimaryConfigChangedCallback::~PrimaryConfigChangedCallback() {
187 ValidateClientHelloResultCallback::Result::Result(
188 const CryptoHandshakeMessage
& in_client_hello
,
189 IPAddressNumber in_client_ip
,
191 : client_hello(in_client_hello
),
192 info(in_client_ip
, in_now
),
193 error_code(QUIC_NO_ERROR
) {
196 ValidateClientHelloResultCallback::Result::~Result() {
199 ValidateClientHelloResultCallback::ValidateClientHelloResultCallback() {
202 ValidateClientHelloResultCallback::~ValidateClientHelloResultCallback() {
205 void ValidateClientHelloResultCallback::Run(const Result
* result
) {
206 RunImpl(result
->client_hello
, *result
);
211 QuicCryptoServerConfig::ConfigOptions::ConfigOptions()
212 : expiry_time(QuicWallTime::Zero()),
213 channel_id_enabled(false),
216 QuicCryptoServerConfig::QuicCryptoServerConfig(
217 StringPiece source_address_token_secret
,
219 : replay_protection_(true),
221 primary_config_(nullptr),
222 next_config_promotion_time_(QuicWallTime::Zero()),
223 server_nonce_strike_register_lock_(),
224 strike_register_no_startup_period_(false),
225 strike_register_max_entries_(1 << 10),
226 strike_register_window_secs_(600),
227 source_address_token_future_secs_(3600),
228 source_address_token_lifetime_secs_(86400),
229 server_nonce_strike_register_max_entries_(1 << 10),
230 server_nonce_strike_register_window_secs_(120) {
231 default_source_address_token_boxer_
.SetKey(
232 DeriveSourceAddressTokenKey(source_address_token_secret
));
234 // Generate a random key and orbit for server nonces.
235 rand
->RandBytes(server_nonce_orbit_
, sizeof(server_nonce_orbit_
));
236 const size_t key_size
= server_nonce_boxer_
.GetKeySize();
237 scoped_ptr
<uint8
[]> key_bytes(new uint8
[key_size
]);
238 rand
->RandBytes(key_bytes
.get(), key_size
);
240 server_nonce_boxer_
.SetKey(
241 StringPiece(reinterpret_cast<char*>(key_bytes
.get()), key_size
));
244 QuicCryptoServerConfig::~QuicCryptoServerConfig() {
245 primary_config_
= nullptr;
249 QuicServerConfigProtobuf
* QuicCryptoServerConfig::GenerateConfig(
251 const QuicClock
* clock
,
252 const ConfigOptions
& options
) {
253 CryptoHandshakeMessage msg
;
255 const string curve25519_private_key
=
256 Curve25519KeyExchange::NewPrivateKey(rand
);
257 scoped_ptr
<Curve25519KeyExchange
> curve25519(
258 Curve25519KeyExchange::New(curve25519_private_key
));
259 StringPiece curve25519_public_value
= curve25519
->public_value();
261 string encoded_public_values
;
262 // First three bytes encode the length of the public value.
263 DCHECK_LT(curve25519_public_value
.size(), (1U << 24));
264 encoded_public_values
.push_back(
265 static_cast<char>(curve25519_public_value
.size()));
266 encoded_public_values
.push_back(
267 static_cast<char>(curve25519_public_value
.size() >> 8));
268 encoded_public_values
.push_back(
269 static_cast<char>(curve25519_public_value
.size() >> 16));
270 encoded_public_values
.append(curve25519_public_value
.data(),
271 curve25519_public_value
.size());
273 string p256_private_key
;
275 p256_private_key
= P256KeyExchange::NewPrivateKey();
276 scoped_ptr
<P256KeyExchange
> p256(P256KeyExchange::New(p256_private_key
));
277 StringPiece p256_public_value
= p256
->public_value();
279 DCHECK_LT(p256_public_value
.size(), (1U << 24));
280 encoded_public_values
.push_back(
281 static_cast<char>(p256_public_value
.size()));
282 encoded_public_values
.push_back(
283 static_cast<char>(p256_public_value
.size() >> 8));
284 encoded_public_values
.push_back(
285 static_cast<char>(p256_public_value
.size() >> 16));
286 encoded_public_values
.append(p256_public_value
.data(),
287 p256_public_value
.size());
292 msg
.SetTaglist(kKEXS
, kC255
, kP256
, 0);
294 msg
.SetTaglist(kKEXS
, kC255
, 0);
296 if (ChaCha20Poly1305Encrypter::IsSupported()) {
297 msg
.SetTaglist(kAEAD
, kAESG
, kCC12
, 0);
299 msg
.SetTaglist(kAEAD
, kAESG
, 0);
301 msg
.SetStringPiece(kPUBS
, encoded_public_values
);
303 if (options
.expiry_time
.IsZero()) {
304 const QuicWallTime now
= clock
->WallNow();
305 const QuicWallTime expiry
= now
.Add(QuicTime::Delta::FromSeconds(
306 60 * 60 * 24 * 180 /* 180 days, ~six months */));
307 const uint64 expiry_seconds
= expiry
.ToUNIXSeconds();
308 msg
.SetValue(kEXPY
, expiry_seconds
);
310 msg
.SetValue(kEXPY
, options
.expiry_time
.ToUNIXSeconds());
313 char orbit_bytes
[kOrbitSize
];
314 if (options
.orbit
.size() == sizeof(orbit_bytes
)) {
315 memcpy(orbit_bytes
, options
.orbit
.data(), sizeof(orbit_bytes
));
317 DCHECK(options
.orbit
.empty());
318 rand
->RandBytes(orbit_bytes
, sizeof(orbit_bytes
));
320 msg
.SetStringPiece(kORBT
, StringPiece(orbit_bytes
, sizeof(orbit_bytes
)));
322 if (options
.channel_id_enabled
) {
323 msg
.SetTaglist(kPDMD
, kCHID
, 0);
326 if (options
.id
.empty()) {
327 // We need to ensure that the SCID changes whenever the server config does
328 // thus we make it a hash of the rest of the server config.
329 scoped_ptr
<QuicData
> serialized(
330 CryptoFramer::ConstructHandshakeMessage(msg
));
331 scoped_ptr
<SecureHash
> hash(SecureHash::Create(SecureHash::SHA256
));
332 hash
->Update(serialized
->data(), serialized
->length());
335 hash
->Finish(scid_bytes
, sizeof(scid_bytes
));
336 msg
.SetStringPiece(kSCID
, StringPiece(scid_bytes
, sizeof(scid_bytes
)));
338 msg
.SetStringPiece(kSCID
, options
.id
);
340 // Don't put new tags below this point. The SCID generation should hash over
341 // everything but itself and so extra tags should be added prior to the
342 // preceeding if block.
344 scoped_ptr
<QuicData
> serialized(CryptoFramer::ConstructHandshakeMessage(msg
));
346 scoped_ptr
<QuicServerConfigProtobuf
> config(new QuicServerConfigProtobuf
);
347 config
->set_config(serialized
->AsStringPiece());
348 QuicServerConfigProtobuf::PrivateKey
* curve25519_key
= config
->add_key();
349 curve25519_key
->set_tag(kC255
);
350 curve25519_key
->set_private_key(curve25519_private_key
);
353 QuicServerConfigProtobuf::PrivateKey
* p256_key
= config
->add_key();
354 p256_key
->set_tag(kP256
);
355 p256_key
->set_private_key(p256_private_key
);
358 return config
.release();
361 CryptoHandshakeMessage
* QuicCryptoServerConfig::AddConfig(
362 QuicServerConfigProtobuf
* protobuf
,
363 const QuicWallTime now
) {
364 scoped_ptr
<CryptoHandshakeMessage
> msg(
365 CryptoFramer::ParseMessage(protobuf
->config()));
368 LOG(WARNING
) << "Failed to parse server config message";
372 scoped_refptr
<Config
> config(ParseConfigProtobuf(protobuf
));
374 LOG(WARNING
) << "Failed to parse server config message";
379 base::AutoLock
locked(configs_lock_
);
380 if (configs_
.find(config
->id
) != configs_
.end()) {
381 LOG(WARNING
) << "Failed to add config because another with the same "
382 "server config id already exists: "
383 << base::HexEncode(config
->id
.data(), config
->id
.size());
387 configs_
[config
->id
] = config
;
388 SelectNewPrimaryConfig(now
);
389 DCHECK(primary_config_
.get());
390 DCHECK_EQ(configs_
.find(primary_config_
->id
)->second
, primary_config_
);
393 return msg
.release();
396 CryptoHandshakeMessage
* QuicCryptoServerConfig::AddDefaultConfig(
398 const QuicClock
* clock
,
399 const ConfigOptions
& options
) {
400 scoped_ptr
<QuicServerConfigProtobuf
> config(
401 GenerateConfig(rand
, clock
, options
));
402 return AddConfig(config
.get(), clock
->WallNow());
405 bool QuicCryptoServerConfig::SetConfigs(
406 const vector
<QuicServerConfigProtobuf
*>& protobufs
,
407 const QuicWallTime now
) {
408 vector
<scoped_refptr
<Config
> > parsed_configs
;
411 for (vector
<QuicServerConfigProtobuf
*>::const_iterator i
= protobufs
.begin();
412 i
!= protobufs
.end(); ++i
) {
413 scoped_refptr
<Config
> config(ParseConfigProtobuf(*i
));
419 parsed_configs
.push_back(config
);
422 if (parsed_configs
.empty()) {
423 LOG(WARNING
) << "New config list is empty.";
428 LOG(WARNING
) << "Rejecting QUIC configs because of above errors";
430 VLOG(1) << "Updating configs:";
432 base::AutoLock
locked(configs_lock_
);
433 ConfigMap new_configs
;
435 for (vector
<scoped_refptr
<Config
> >::const_iterator i
=
436 parsed_configs
.begin();
437 i
!= parsed_configs
.end(); ++i
) {
438 scoped_refptr
<Config
> config
= *i
;
440 ConfigMap::iterator it
= configs_
.find(config
->id
);
441 if (it
!= configs_
.end()) {
443 << "Keeping scid: " << base::HexEncode(
444 config
->id
.data(), config
->id
.size())
445 << " orbit: " << base::HexEncode(
446 reinterpret_cast<const char *>(config
->orbit
), kOrbitSize
)
447 << " new primary_time " << config
->primary_time
.ToUNIXSeconds()
448 << " old primary_time " << it
->second
->primary_time
.ToUNIXSeconds()
449 << " new priority " << config
->priority
450 << " old priority " << it
->second
->priority
;
451 // Update primary_time and priority.
452 it
->second
->primary_time
= config
->primary_time
;
453 it
->second
->priority
= config
->priority
;
454 new_configs
.insert(*it
);
456 VLOG(1) << "Adding scid: " << base::HexEncode(
457 config
->id
.data(), config
->id
.size())
458 << " orbit: " << base::HexEncode(
459 reinterpret_cast<const char *>(config
->orbit
), kOrbitSize
)
460 << " primary_time " << config
->primary_time
.ToUNIXSeconds()
461 << " priority " << config
->priority
;
462 new_configs
.insert(std::make_pair(config
->id
, config
));
466 configs_
.swap(new_configs
);
467 SelectNewPrimaryConfig(now
);
468 DCHECK(primary_config_
.get());
469 DCHECK_EQ(configs_
.find(primary_config_
->id
)->second
, primary_config_
);
475 void QuicCryptoServerConfig::GetConfigIds(vector
<string
>* scids
) const {
476 base::AutoLock
locked(configs_lock_
);
477 for (ConfigMap::const_iterator it
= configs_
.begin();
478 it
!= configs_
.end(); ++it
) {
479 scids
->push_back(it
->first
);
483 void QuicCryptoServerConfig::ValidateClientHello(
484 const CryptoHandshakeMessage
& client_hello
,
485 IPAddressNumber client_ip
,
486 const QuicClock
* clock
,
487 ValidateClientHelloResultCallback
* done_cb
) const {
488 const QuicWallTime
now(clock
->WallNow());
490 ValidateClientHelloResultCallback::Result
* result
=
491 new ValidateClientHelloResultCallback::Result(
492 client_hello
, client_ip
, now
);
494 StringPiece requested_scid
;
495 client_hello
.GetStringPiece(kSCID
, &requested_scid
);
497 uint8 primary_orbit
[kOrbitSize
];
498 scoped_refptr
<Config
> requested_config
;
500 base::AutoLock
locked(configs_lock_
);
502 if (!primary_config_
.get()) {
503 result
->error_code
= QUIC_CRYPTO_INTERNAL_ERROR
;
504 result
->error_details
= "No configurations loaded";
506 if (!next_config_promotion_time_
.IsZero() &&
507 next_config_promotion_time_
.IsAfter(now
)) {
508 SelectNewPrimaryConfig(now
);
509 DCHECK(primary_config_
.get());
510 DCHECK_EQ(configs_
.find(primary_config_
->id
)->second
, primary_config_
);
513 memcpy(primary_orbit
, primary_config_
->orbit
, sizeof(primary_orbit
));
516 requested_config
= GetConfigWithScid(requested_scid
);
519 if (result
->error_code
== QUIC_NO_ERROR
) {
520 EvaluateClientHello(primary_orbit
, requested_config
, result
, done_cb
);
522 done_cb
->Run(result
);
526 QuicErrorCode
QuicCryptoServerConfig::ProcessClientHello(
527 const ValidateClientHelloResultCallback::Result
& validate_chlo_result
,
528 QuicConnectionId connection_id
,
529 const IPAddressNumber
& server_ip
,
530 const IPEndPoint
& client_address
,
532 const QuicVersionVector
& supported_versions
,
533 const QuicClock
* clock
,
535 QuicCryptoNegotiatedParameters
* params
,
536 CryptoHandshakeMessage
* out
,
537 string
* error_details
) const {
538 DCHECK(error_details
);
540 const CryptoHandshakeMessage
& client_hello
=
541 validate_chlo_result
.client_hello
;
542 const ClientHelloInfo
& info
= validate_chlo_result
.info
;
544 // If the client's preferred version is not the version we are currently
545 // speaking, then the client went through a version negotiation. In this
546 // case, we need to make sure that we actually do not support this version
547 // and that it wasn't a downgrade attack.
548 QuicTag client_version_tag
;
549 if (client_hello
.GetUint32(kVER
, &client_version_tag
) != QUIC_NO_ERROR
) {
550 *error_details
= "client hello missing version list";
551 return QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER
;
553 QuicVersion client_version
= QuicTagToQuicVersion(client_version_tag
);
554 if (client_version
!= version
) {
555 // Just because client_version is a valid version enum doesn't mean that
556 // this server actually supports that version, so we check to see if
557 // it's actually in the supported versions list.
558 for (size_t i
= 0; i
< supported_versions
.size(); ++i
) {
559 if (client_version
== supported_versions
[i
]) {
560 *error_details
= "Downgrade attack detected";
561 return QUIC_VERSION_NEGOTIATION_MISMATCH
;
566 StringPiece requested_scid
;
567 client_hello
.GetStringPiece(kSCID
, &requested_scid
);
568 const QuicWallTime
now(clock
->WallNow());
570 scoped_refptr
<Config
> requested_config
;
571 scoped_refptr
<Config
> primary_config
;
573 base::AutoLock
locked(configs_lock_
);
575 if (!primary_config_
.get()) {
576 *error_details
= "No configurations loaded";
577 return QUIC_CRYPTO_INTERNAL_ERROR
;
580 if (!next_config_promotion_time_
.IsZero() &&
581 next_config_promotion_time_
.IsAfter(now
)) {
582 SelectNewPrimaryConfig(now
);
583 DCHECK(primary_config_
.get());
584 DCHECK_EQ(configs_
.find(primary_config_
->id
)->second
, primary_config_
);
587 // We'll use the config that the client requested in order to do
588 // key-agreement. Otherwise we'll give it a copy of |primary_config_|
590 primary_config
= primary_config_
;
592 requested_config
= GetConfigWithScid(requested_scid
);
595 if (validate_chlo_result
.error_code
!= QUIC_NO_ERROR
) {
596 *error_details
= validate_chlo_result
.error_details
;
597 return validate_chlo_result
.error_code
;
602 if (!info
.valid_source_address_token
||
603 !info
.client_nonce_well_formed
||
605 !requested_config
.get()) {
606 BuildRejection(server_ip
, *primary_config
.get(), client_hello
, info
,
607 validate_chlo_result
.cached_network_params
, rand
, params
,
609 return QUIC_NO_ERROR
;
612 const QuicTag
* their_aeads
;
613 const QuicTag
* their_key_exchanges
;
614 size_t num_their_aeads
, num_their_key_exchanges
;
615 if (client_hello
.GetTaglist(kAEAD
, &their_aeads
,
616 &num_their_aeads
) != QUIC_NO_ERROR
||
617 client_hello
.GetTaglist(kKEXS
, &their_key_exchanges
,
618 &num_their_key_exchanges
) != QUIC_NO_ERROR
||
619 num_their_aeads
!= 1 ||
620 num_their_key_exchanges
!= 1) {
621 *error_details
= "Missing or invalid AEAD or KEXS";
622 return QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER
;
625 size_t key_exchange_index
;
626 if (!QuicUtils::FindMutualTag(requested_config
->aead
, their_aeads
,
627 num_their_aeads
, QuicUtils::LOCAL_PRIORITY
,
628 ¶ms
->aead
, nullptr) ||
629 !QuicUtils::FindMutualTag(
630 requested_config
->kexs
, their_key_exchanges
, num_their_key_exchanges
,
631 QuicUtils::LOCAL_PRIORITY
, ¶ms
->key_exchange
,
632 &key_exchange_index
)) {
633 *error_details
= "Unsupported AEAD or KEXS";
634 return QUIC_CRYPTO_NO_SUPPORT
;
637 StringPiece public_value
;
638 if (!client_hello
.GetStringPiece(kPUBS
, &public_value
)) {
639 *error_details
= "Missing public value";
640 return QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER
;
643 const KeyExchange
* key_exchange
=
644 requested_config
->key_exchanges
[key_exchange_index
];
645 if (!key_exchange
->CalculateSharedKey(public_value
,
646 ¶ms
->initial_premaster_secret
)) {
647 *error_details
= "Invalid public value";
648 return QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER
;
651 if (!info
.sni
.empty()) {
652 scoped_ptr
<char[]> sni_tmp(new char[info
.sni
.length() + 1]);
653 memcpy(sni_tmp
.get(), info
.sni
.data(), info
.sni
.length());
654 sni_tmp
[info
.sni
.length()] = 0;
655 params
->sni
= CryptoUtils::NormalizeHostname(sni_tmp
.get());
659 const QuicData
& client_hello_serialized
= client_hello
.GetSerialized();
660 hkdf_suffix
.reserve(sizeof(connection_id
) + client_hello_serialized
.length() +
661 requested_config
->serialized
.size());
662 hkdf_suffix
.append(reinterpret_cast<char*>(&connection_id
),
663 sizeof(connection_id
));
664 hkdf_suffix
.append(client_hello_serialized
.data(),
665 client_hello_serialized
.length());
666 hkdf_suffix
.append(requested_config
->serialized
);
668 StringPiece cetv_ciphertext
;
669 if (requested_config
->channel_id_enabled
&&
670 client_hello
.GetStringPiece(kCETV
, &cetv_ciphertext
)) {
671 CryptoHandshakeMessage
client_hello_copy(client_hello
);
672 client_hello_copy
.Erase(kCETV
);
673 client_hello_copy
.Erase(kPAD
);
675 const QuicData
& client_hello_copy_serialized
=
676 client_hello_copy
.GetSerialized();
678 hkdf_input
.append(QuicCryptoConfig::kCETVLabel
,
679 strlen(QuicCryptoConfig::kCETVLabel
) + 1);
680 hkdf_input
.append(reinterpret_cast<char*>(&connection_id
),
681 sizeof(connection_id
));
682 hkdf_input
.append(client_hello_copy_serialized
.data(),
683 client_hello_copy_serialized
.length());
684 hkdf_input
.append(requested_config
->serialized
);
686 CrypterPair crypters
;
687 if (!CryptoUtils::DeriveKeys(params
->initial_premaster_secret
, params
->aead
,
688 info
.client_nonce
, info
.server_nonce
,
689 hkdf_input
, Perspective::IS_SERVER
, &crypters
,
690 nullptr /* subkey secret */)) {
691 *error_details
= "Symmetric key setup failed";
692 return QUIC_CRYPTO_SYMMETRIC_KEY_SETUP_FAILED
;
695 char plaintext
[kMaxPacketSize
];
696 size_t plaintext_length
= 0;
697 const bool success
= crypters
.decrypter
->DecryptPacket(
698 0 /* sequence number */, StringPiece() /* associated data */,
699 cetv_ciphertext
, plaintext
, &plaintext_length
, kMaxPacketSize
);
701 *error_details
= "CETV decryption failure";
702 return QUIC_PACKET_TOO_LARGE
;
704 scoped_ptr
<CryptoHandshakeMessage
> cetv(
705 CryptoFramer::ParseMessage(StringPiece(plaintext
, plaintext_length
)));
707 *error_details
= "CETV parse error";
708 return QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER
;
711 StringPiece key
, signature
;
712 if (cetv
->GetStringPiece(kCIDK
, &key
) &&
713 cetv
->GetStringPiece(kCIDS
, &signature
)) {
714 if (!ChannelIDVerifier::Verify(key
, hkdf_input
, signature
)) {
715 *error_details
= "ChannelID signature failure";
716 return QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER
;
719 params
->channel_id
= key
.as_string();
724 size_t label_len
= strlen(QuicCryptoConfig::kInitialLabel
) + 1;
725 hkdf_input
.reserve(label_len
+ hkdf_suffix
.size());
726 hkdf_input
.append(QuicCryptoConfig::kInitialLabel
, label_len
);
727 hkdf_input
.append(hkdf_suffix
);
729 if (!CryptoUtils::DeriveKeys(
730 params
->initial_premaster_secret
, params
->aead
, info
.client_nonce
,
731 info
.server_nonce
, hkdf_input
, Perspective::IS_SERVER
,
732 ¶ms
->initial_crypters
, nullptr /* subkey secret */)) {
733 *error_details
= "Symmetric key setup failed";
734 return QUIC_CRYPTO_SYMMETRIC_KEY_SETUP_FAILED
;
737 string forward_secure_public_value
;
738 if (ephemeral_key_source_
.get()) {
739 params
->forward_secure_premaster_secret
=
740 ephemeral_key_source_
->CalculateForwardSecureKey(
741 key_exchange
, rand
, clock
->ApproximateNow(), public_value
,
742 &forward_secure_public_value
);
744 scoped_ptr
<KeyExchange
> forward_secure_key_exchange(
745 key_exchange
->NewKeyPair(rand
));
746 forward_secure_public_value
=
747 forward_secure_key_exchange
->public_value().as_string();
748 if (!forward_secure_key_exchange
->CalculateSharedKey(
749 public_value
, ¶ms
->forward_secure_premaster_secret
)) {
750 *error_details
= "Invalid public value";
751 return QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER
;
755 string forward_secure_hkdf_input
;
756 label_len
= strlen(QuicCryptoConfig::kForwardSecureLabel
) + 1;
757 forward_secure_hkdf_input
.reserve(label_len
+ hkdf_suffix
.size());
758 forward_secure_hkdf_input
.append(QuicCryptoConfig::kForwardSecureLabel
,
760 forward_secure_hkdf_input
.append(hkdf_suffix
);
762 if (!CryptoUtils::DeriveKeys(
763 params
->forward_secure_premaster_secret
, params
->aead
,
764 info
.client_nonce
, info
.server_nonce
, forward_secure_hkdf_input
,
765 Perspective::IS_SERVER
, ¶ms
->forward_secure_crypters
,
766 ¶ms
->subkey_secret
)) {
767 *error_details
= "Symmetric key setup failed";
768 return QUIC_CRYPTO_SYMMETRIC_KEY_SETUP_FAILED
;
772 QuicTagVector supported_version_tags
;
773 for (size_t i
= 0; i
< supported_versions
.size(); ++i
) {
774 supported_version_tags
.push_back
775 (QuicVersionToQuicTag(supported_versions
[i
]));
777 out
->SetVector(kVER
, supported_version_tags
);
779 kSourceAddressTokenTag
,
780 NewSourceAddressToken(*requested_config
.get(), info
.source_address_tokens
,
781 client_address
.address(), rand
, info
.now
, nullptr));
782 QuicSocketAddressCoder
address_coder(client_address
);
783 out
->SetStringPiece(kCADR
, address_coder
.Encode());
784 out
->SetStringPiece(kPUBS
, forward_secure_public_value
);
786 return QUIC_NO_ERROR
;
789 scoped_refptr
<QuicCryptoServerConfig::Config
>
790 QuicCryptoServerConfig::GetConfigWithScid(StringPiece requested_scid
) const {
791 // In Chromium, we will dead lock if the lock is held by the current thread.
792 // Chromium doesn't have AssertReaderHeld API call.
793 // configs_lock_.AssertReaderHeld();
795 if (!requested_scid
.empty()) {
796 ConfigMap::const_iterator it
= configs_
.find(requested_scid
.as_string());
797 if (it
!= configs_
.end()) {
798 // We'll use the config that the client requested in order to do
800 return scoped_refptr
<Config
>(it
->second
);
804 return scoped_refptr
<Config
>();
807 // ConfigPrimaryTimeLessThan is a comparator that implements "less than" for
808 // Config's based on their primary_time.
810 bool QuicCryptoServerConfig::ConfigPrimaryTimeLessThan(
811 const scoped_refptr
<Config
>& a
,
812 const scoped_refptr
<Config
>& b
) {
813 if (a
->primary_time
.IsBefore(b
->primary_time
) ||
814 b
->primary_time
.IsBefore(a
->primary_time
)) {
815 // Primary times differ.
816 return a
->primary_time
.IsBefore(b
->primary_time
);
817 } else if (a
->priority
!= b
->priority
) {
818 // Primary times are equal, sort backwards by priority.
819 return a
->priority
< b
->priority
;
821 // Primary times and priorities are equal, sort by config id.
822 return a
->id
< b
->id
;
826 void QuicCryptoServerConfig::SelectNewPrimaryConfig(
827 const QuicWallTime now
) const {
828 vector
<scoped_refptr
<Config
> > configs
;
829 configs
.reserve(configs_
.size());
831 for (ConfigMap::const_iterator it
= configs_
.begin();
832 it
!= configs_
.end(); ++it
) {
833 // TODO(avd) Exclude expired configs?
834 configs
.push_back(it
->second
);
837 if (configs
.empty()) {
838 if (primary_config_
.get()) {
839 LOG(DFATAL
) << "No valid QUIC server config. Keeping the current config.";
841 LOG(DFATAL
) << "No valid QUIC server config.";
846 std::sort(configs
.begin(), configs
.end(), ConfigPrimaryTimeLessThan
);
848 Config
* best_candidate
= configs
[0].get();
850 for (size_t i
= 0; i
< configs
.size(); ++i
) {
851 const scoped_refptr
<Config
> config(configs
[i
]);
852 if (!config
->primary_time
.IsAfter(now
)) {
853 if (config
->primary_time
.IsAfter(best_candidate
->primary_time
)) {
854 best_candidate
= config
.get();
859 // This is the first config with a primary_time in the future. Thus the
860 // previous Config should be the primary and this one should determine the
861 // next_config_promotion_time_.
862 scoped_refptr
<Config
> new_primary(best_candidate
);
864 // We need the primary_time of the next config.
865 if (configs
.size() > 1) {
866 next_config_promotion_time_
= configs
[1]->primary_time
;
868 next_config_promotion_time_
= QuicWallTime::Zero();
871 next_config_promotion_time_
= config
->primary_time
;
874 if (primary_config_
.get()) {
875 primary_config_
->is_primary
= false;
877 primary_config_
= new_primary
;
878 new_primary
->is_primary
= true;
879 DVLOG(1) << "New primary config. orbit: "
881 reinterpret_cast<const char*>(primary_config_
->orbit
),
883 if (primary_config_changed_cb_
.get() != nullptr) {
884 primary_config_changed_cb_
->Run(primary_config_
->id
);
890 // All config's primary times are in the past. We should make the most recent
891 // and highest priority candidate primary.
892 scoped_refptr
<Config
> new_primary(best_candidate
);
893 if (primary_config_
.get()) {
894 primary_config_
->is_primary
= false;
896 primary_config_
= new_primary
;
897 new_primary
->is_primary
= true;
898 DVLOG(1) << "New primary config. orbit: "
900 reinterpret_cast<const char*>(primary_config_
->orbit
),
902 << " scid: " << base::HexEncode(primary_config_
->id
.data(),
903 primary_config_
->id
.size());
904 next_config_promotion_time_
= QuicWallTime::Zero();
905 if (primary_config_changed_cb_
.get() != nullptr) {
906 primary_config_changed_cb_
->Run(primary_config_
->id
);
910 void QuicCryptoServerConfig::EvaluateClientHello(
911 const uint8
* primary_orbit
,
912 scoped_refptr
<Config
> requested_config
,
913 ValidateClientHelloResultCallback::Result
* client_hello_state
,
914 ValidateClientHelloResultCallback
* done_cb
) const {
915 ValidateClientHelloHelper
helper(client_hello_state
, done_cb
);
917 const CryptoHandshakeMessage
& client_hello
=
918 client_hello_state
->client_hello
;
919 ClientHelloInfo
* info
= &(client_hello_state
->info
);
921 if (client_hello
.size() < kClientHelloMinimumSize
) {
922 helper
.ValidationComplete(QUIC_CRYPTO_INVALID_VALUE_LENGTH
,
923 "Client hello too small");
927 if (client_hello
.GetStringPiece(kSNI
, &info
->sni
) &&
928 !CryptoUtils::IsValidSNI(info
->sni
)) {
929 helper
.ValidationComplete(QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER
,
934 client_hello
.GetStringPiece(kUAID
, &info
->user_agent_id
);
936 if (!requested_config
.get()) {
937 StringPiece requested_scid
;
938 if (client_hello
.GetStringPiece(kSCID
, &requested_scid
)) {
939 info
->reject_reasons
.push_back(SERVER_CONFIG_UNKNOWN_CONFIG_FAILURE
);
941 info
->reject_reasons
.push_back(SERVER_CONFIG_INCHOATE_HELLO_FAILURE
);
943 // No server config with the requested ID.
944 helper
.ValidationComplete(QUIC_NO_ERROR
, "");
948 HandshakeFailureReason source_address_token_error
;
950 if (client_hello
.GetStringPiece(kSourceAddressTokenTag
, &srct
)) {
951 if (!FLAGS_quic_use_multiple_address_in_source_tokens
) {
952 source_address_token_error
= ValidateSourceAddressToken(
953 *requested_config
.get(), srct
, info
->client_ip
, info
->now
,
954 &client_hello_state
->cached_network_params
);
956 source_address_token_error
= ParseSourceAddressToken(
957 *requested_config
.get(), srct
, &info
->source_address_tokens
);
959 if (source_address_token_error
== HANDSHAKE_OK
) {
960 source_address_token_error
= ValidateSourceAddressTokens(
961 info
->source_address_tokens
, info
->client_ip
, info
->now
,
962 &client_hello_state
->cached_network_params
);
965 info
->valid_source_address_token
=
966 (source_address_token_error
== HANDSHAKE_OK
);
968 source_address_token_error
= SOURCE_ADDRESS_TOKEN_INVALID_FAILURE
;
971 bool found_error
= false;
972 if (source_address_token_error
!= HANDSHAKE_OK
) {
973 info
->reject_reasons
.push_back(source_address_token_error
);
974 // No valid source address token.
975 if (FLAGS_use_early_return_when_verifying_chlo
) {
976 helper
.ValidationComplete(QUIC_NO_ERROR
, "");
982 if (client_hello
.GetStringPiece(kNONC
, &info
->client_nonce
) &&
983 info
->client_nonce
.size() == kNonceSize
) {
984 info
->client_nonce_well_formed
= true;
986 info
->reject_reasons
.push_back(CLIENT_NONCE_INVALID_FAILURE
);
987 // Invalid client nonce.
988 DVLOG(1) << "Invalid client nonce.";
989 if (FLAGS_use_early_return_when_verifying_chlo
) {
990 helper
.ValidationComplete(QUIC_NO_ERROR
, "");
996 if (!replay_protection_
) {
1000 DVLOG(1) << "No replay protection.";
1001 helper
.ValidationComplete(QUIC_NO_ERROR
, "");
1005 client_hello
.GetStringPiece(kServerNonceTag
, &info
->server_nonce
);
1006 if (!info
->server_nonce
.empty()) {
1007 // If the server nonce is present, use it to establish uniqueness.
1008 HandshakeFailureReason server_nonce_error
=
1009 ValidateServerNonce(info
->server_nonce
, info
->now
);
1010 if (server_nonce_error
== HANDSHAKE_OK
) {
1011 info
->unique
= true;
1013 info
->reject_reasons
.push_back(server_nonce_error
);
1014 info
->unique
= false;
1016 DVLOG(1) << "Using server nonce, unique: " << info
->unique
;
1017 helper
.ValidationComplete(QUIC_NO_ERROR
, "");
1021 // We want to contact strike register only if there are no errors because it
1022 // is a RPC call and is expensive.
1024 helper
.ValidationComplete(QUIC_NO_ERROR
, "");
1028 // Use the client nonce to establish uniqueness.
1029 StrikeRegisterClient
* strike_register_client
;
1031 base::AutoLock
locked(strike_register_client_lock_
);
1033 if (strike_register_client_
.get() == nullptr) {
1034 strike_register_client_
.reset(new LocalStrikeRegisterClient(
1035 strike_register_max_entries_
,
1036 static_cast<uint32
>(info
->now
.ToUNIXSeconds()),
1037 strike_register_window_secs_
,
1039 strike_register_no_startup_period_
?
1040 StrikeRegister::NO_STARTUP_PERIOD_NEEDED
:
1041 StrikeRegister::DENY_REQUESTS_AT_STARTUP
));
1043 strike_register_client
= strike_register_client_
.get();
1046 strike_register_client
->VerifyNonceIsValidAndUnique(
1049 new VerifyNonceIsValidAndUniqueCallback(client_hello_state
, done_cb
));
1050 helper
.StartedAsyncCallback();
1053 bool QuicCryptoServerConfig::BuildServerConfigUpdateMessage(
1054 const SourceAddressTokens
& previous_source_address_tokens
,
1055 const IPAddressNumber
& server_ip
,
1056 const IPAddressNumber
& client_ip
,
1057 const QuicClock
* clock
,
1059 const QuicCryptoNegotiatedParameters
& params
,
1060 const CachedNetworkParameters
* cached_network_params
,
1061 CryptoHandshakeMessage
* out
) const {
1062 base::AutoLock
locked(configs_lock_
);
1063 out
->set_tag(kSCUP
);
1064 out
->SetStringPiece(kSCFG
, primary_config_
->serialized
);
1065 out
->SetStringPiece(
1066 kSourceAddressTokenTag
,
1067 NewSourceAddressToken(*primary_config_
.get(),
1068 previous_source_address_tokens
, client_ip
, rand
,
1069 clock
->WallNow(), cached_network_params
));
1071 if (proof_source_
== nullptr) {
1072 // Insecure QUIC, can send SCFG without proof.
1076 const vector
<string
>* certs
;
1078 if (!proof_source_
->GetProof(
1079 server_ip
, params
.sni
, primary_config_
->serialized
,
1080 params
.x509_ecdsa_supported
, &certs
, &signature
)) {
1081 DVLOG(1) << "Server: failed to get proof.";
1085 const string compressed
= CertCompressor::CompressChain(
1086 *certs
, params
.client_common_set_hashes
, params
.client_cached_cert_hashes
,
1087 primary_config_
->common_cert_sets
);
1089 out
->SetStringPiece(kCertificateTag
, compressed
);
1090 out
->SetStringPiece(kPROF
, signature
);
1094 void QuicCryptoServerConfig::BuildRejection(
1095 const IPAddressNumber
& server_ip
,
1096 const Config
& config
,
1097 const CryptoHandshakeMessage
& client_hello
,
1098 const ClientHelloInfo
& info
,
1099 const CachedNetworkParameters
& cached_network_params
,
1101 QuicCryptoNegotiatedParameters
* params
,
1102 CryptoHandshakeMessage
* out
) const {
1104 out
->SetStringPiece(kSCFG
, config
.serialized
);
1105 out
->SetStringPiece(
1106 kSourceAddressTokenTag
,
1107 NewSourceAddressToken(config
, info
.source_address_tokens
, info
.client_ip
,
1108 rand
, info
.now
, &cached_network_params
));
1109 if (replay_protection_
) {
1110 out
->SetStringPiece(kServerNonceTag
, NewServerNonce(rand
, info
.now
));
1113 // Send client the reject reason for debugging purposes.
1114 DCHECK_LT(0u, info
.reject_reasons
.size());
1115 out
->SetVector(kRREJ
, info
.reject_reasons
);
1117 // The client may have requested a certificate chain.
1118 const QuicTag
* their_proof_demands
;
1119 size_t num_their_proof_demands
;
1121 if (proof_source_
.get() == nullptr ||
1122 client_hello
.GetTaglist(kPDMD
, &their_proof_demands
,
1123 &num_their_proof_demands
) !=
1128 bool x509_supported
= false;
1129 for (size_t i
= 0; i
< num_their_proof_demands
; i
++) {
1130 switch (their_proof_demands
[i
]) {
1132 x509_supported
= true;
1133 params
->x509_ecdsa_supported
= true;
1136 x509_supported
= true;
1141 if (!x509_supported
) {
1145 const vector
<string
>* certs
;
1147 if (!proof_source_
->GetProof(server_ip
, info
.sni
.as_string(),
1148 config
.serialized
, params
->x509_ecdsa_supported
,
1149 &certs
, &signature
)) {
1153 StringPiece client_common_set_hashes
;
1154 if (client_hello
.GetStringPiece(kCCS
, &client_common_set_hashes
)) {
1155 params
->client_common_set_hashes
= client_common_set_hashes
.as_string();
1158 StringPiece client_cached_cert_hashes
;
1159 if (client_hello
.GetStringPiece(kCCRT
, &client_cached_cert_hashes
)) {
1160 params
->client_cached_cert_hashes
= client_cached_cert_hashes
.as_string();
1163 const string compressed
= CertCompressor::CompressChain(
1164 *certs
, params
->client_common_set_hashes
,
1165 params
->client_cached_cert_hashes
, config
.common_cert_sets
);
1167 // kREJOverheadBytes is a very rough estimate of how much of a REJ
1168 // message is taken up by things other than the certificates.
1174 const size_t kREJOverheadBytes
= 166;
1175 // kMultiplier is the multiple of the CHLO message size that a REJ message
1176 // must stay under when the client doesn't present a valid source-address
1178 const size_t kMultiplier
= 2;
1179 // max_unverified_size is the number of bytes that the certificate chain
1180 // and signature can consume before we will demand a valid source-address
1182 const size_t max_unverified_size
=
1183 client_hello
.size() * kMultiplier
- kREJOverheadBytes
;
1184 static_assert(kClientHelloMinimumSize
* kMultiplier
>= kREJOverheadBytes
,
1185 "overhead calculation may overflow");
1186 if (info
.valid_source_address_token
||
1187 signature
.size() + compressed
.size() < max_unverified_size
) {
1188 out
->SetStringPiece(kCertificateTag
, compressed
);
1189 out
->SetStringPiece(kPROF
, signature
);
1193 scoped_refptr
<QuicCryptoServerConfig::Config
>
1194 QuicCryptoServerConfig::ParseConfigProtobuf(
1195 QuicServerConfigProtobuf
* protobuf
) {
1196 scoped_ptr
<CryptoHandshakeMessage
> msg(
1197 CryptoFramer::ParseMessage(protobuf
->config()));
1199 if (msg
->tag() != kSCFG
) {
1200 LOG(WARNING
) << "Server config message has tag " << msg
->tag()
1201 << " expected " << kSCFG
;
1205 scoped_refptr
<Config
> config(new Config
);
1206 config
->serialized
= protobuf
->config();
1208 if (!protobuf
->has_source_address_token_secret_override()) {
1209 // Use the default boxer.
1210 config
->source_address_token_boxer
= &default_source_address_token_boxer_
;
1212 // Create override boxer instance.
1213 CryptoSecretBoxer
* boxer
= new CryptoSecretBoxer
;
1214 boxer
->SetKey(DeriveSourceAddressTokenKey(
1215 protobuf
->source_address_token_secret_override()));
1216 config
->source_address_token_boxer_storage
.reset(boxer
);
1217 config
->source_address_token_boxer
= boxer
;
1220 if (protobuf
->has_primary_time()) {
1221 config
->primary_time
=
1222 QuicWallTime::FromUNIXSeconds(protobuf
->primary_time());
1225 config
->priority
= protobuf
->priority();
1228 if (!msg
->GetStringPiece(kSCID
, &scid
)) {
1229 LOG(WARNING
) << "Server config message is missing SCID";
1232 config
->id
= scid
.as_string();
1234 const QuicTag
* aead_tags
;
1236 if (msg
->GetTaglist(kAEAD
, &aead_tags
, &aead_len
) != QUIC_NO_ERROR
) {
1237 LOG(WARNING
) << "Server config message is missing AEAD";
1240 config
->aead
= vector
<QuicTag
>(aead_tags
, aead_tags
+ aead_len
);
1242 const QuicTag
* kexs_tags
;
1244 if (msg
->GetTaglist(kKEXS
, &kexs_tags
, &kexs_len
) != QUIC_NO_ERROR
) {
1245 LOG(WARNING
) << "Server config message is missing KEXS";
1250 if (!msg
->GetStringPiece(kORBT
, &orbit
)) {
1251 LOG(WARNING
) << "Server config message is missing ORBT";
1255 if (orbit
.size() != kOrbitSize
) {
1256 LOG(WARNING
) << "Orbit value in server config is the wrong length."
1257 " Got " << orbit
.size() << " want " << kOrbitSize
;
1260 static_assert(sizeof(config
->orbit
) == kOrbitSize
,
1261 "orbit has incorrect size");
1262 memcpy(config
->orbit
, orbit
.data(), sizeof(config
->orbit
));
1265 StrikeRegisterClient
* strike_register_client
;
1267 base::AutoLock
locked(strike_register_client_lock_
);
1268 strike_register_client
= strike_register_client_
.get();
1271 if (strike_register_client
!= nullptr &&
1272 !strike_register_client
->IsKnownOrbit(orbit
)) {
1274 << "Rejecting server config with orbit that the strike register "
1275 "client doesn't know about.";
1280 if (kexs_len
!= protobuf
->key_size()) {
1281 LOG(WARNING
) << "Server config has " << kexs_len
1282 << " key exchange methods configured, but "
1283 << protobuf
->key_size() << " private keys";
1287 const QuicTag
* proof_demand_tags
;
1288 size_t num_proof_demand_tags
;
1289 if (msg
->GetTaglist(kPDMD
, &proof_demand_tags
, &num_proof_demand_tags
) ==
1291 for (size_t i
= 0; i
< num_proof_demand_tags
; i
++) {
1292 if (proof_demand_tags
[i
] == kCHID
) {
1293 config
->channel_id_enabled
= true;
1299 for (size_t i
= 0; i
< kexs_len
; i
++) {
1300 const QuicTag tag
= kexs_tags
[i
];
1303 config
->kexs
.push_back(tag
);
1305 for (size_t j
= 0; j
< protobuf
->key_size(); j
++) {
1306 const QuicServerConfigProtobuf::PrivateKey
& key
= protobuf
->key(i
);
1307 if (key
.tag() == tag
) {
1308 private_key
= key
.private_key();
1313 if (private_key
.empty()) {
1314 LOG(WARNING
) << "Server config contains key exchange method without "
1315 "corresponding private key: " << tag
;
1319 scoped_ptr
<KeyExchange
> ka
;
1322 ka
.reset(Curve25519KeyExchange::New(private_key
));
1324 LOG(WARNING
) << "Server config contained an invalid curve25519"
1330 ka
.reset(P256KeyExchange::New(private_key
));
1332 LOG(WARNING
) << "Server config contained an invalid P-256"
1338 LOG(WARNING
) << "Server config message contains unknown key exchange "
1343 for (const KeyExchange
* key_exchange
: config
->key_exchanges
) {
1344 if (key_exchange
->tag() == tag
) {
1345 LOG(WARNING
) << "Duplicate key exchange in config: " << tag
;
1350 config
->key_exchanges
.push_back(ka
.release());
1356 void QuicCryptoServerConfig::SetProofSource(ProofSource
* proof_source
) {
1357 proof_source_
.reset(proof_source
);
1360 void QuicCryptoServerConfig::SetEphemeralKeySource(
1361 EphemeralKeySource
* ephemeral_key_source
) {
1362 ephemeral_key_source_
.reset(ephemeral_key_source
);
1365 void QuicCryptoServerConfig::SetStrikeRegisterClient(
1366 StrikeRegisterClient
* strike_register_client
) {
1367 base::AutoLock
locker(strike_register_client_lock_
);
1368 DCHECK(!strike_register_client_
.get());
1369 strike_register_client_
.reset(strike_register_client
);
1372 void QuicCryptoServerConfig::set_replay_protection(bool on
) {
1373 replay_protection_
= on
;
1376 void QuicCryptoServerConfig::set_strike_register_no_startup_period() {
1377 base::AutoLock
locker(strike_register_client_lock_
);
1378 DCHECK(!strike_register_client_
.get());
1379 strike_register_no_startup_period_
= true;
1382 void QuicCryptoServerConfig::set_strike_register_max_entries(
1383 uint32 max_entries
) {
1384 base::AutoLock
locker(strike_register_client_lock_
);
1385 DCHECK(!strike_register_client_
.get());
1386 strike_register_max_entries_
= max_entries
;
1389 void QuicCryptoServerConfig::set_strike_register_window_secs(
1390 uint32 window_secs
) {
1391 base::AutoLock
locker(strike_register_client_lock_
);
1392 DCHECK(!strike_register_client_
.get());
1393 strike_register_window_secs_
= window_secs
;
1396 void QuicCryptoServerConfig::set_source_address_token_future_secs(
1397 uint32 future_secs
) {
1398 source_address_token_future_secs_
= future_secs
;
1401 void QuicCryptoServerConfig::set_source_address_token_lifetime_secs(
1402 uint32 lifetime_secs
) {
1403 source_address_token_lifetime_secs_
= lifetime_secs
;
1406 void QuicCryptoServerConfig::set_server_nonce_strike_register_max_entries(
1407 uint32 max_entries
) {
1408 DCHECK(!server_nonce_strike_register_
.get());
1409 server_nonce_strike_register_max_entries_
= max_entries
;
1412 void QuicCryptoServerConfig::set_server_nonce_strike_register_window_secs(
1413 uint32 window_secs
) {
1414 DCHECK(!server_nonce_strike_register_
.get());
1415 server_nonce_strike_register_window_secs_
= window_secs
;
1418 void QuicCryptoServerConfig::AcquirePrimaryConfigChangedCb(
1419 PrimaryConfigChangedCallback
* cb
) {
1420 base::AutoLock
locked(configs_lock_
);
1421 primary_config_changed_cb_
.reset(cb
);
1424 string
QuicCryptoServerConfig::NewSourceAddressToken(
1425 const Config
& config
,
1426 const SourceAddressTokens
& previous_tokens
,
1427 const IPAddressNumber
& ip
,
1430 const CachedNetworkParameters
* cached_network_params
) const {
1431 SourceAddressTokens source_address_tokens
;
1432 SourceAddressToken
* source_address_token
= source_address_tokens
.add_tokens();
1433 source_address_token
->set_ip(IPAddressToPackedString(DualstackIPAddress(ip
)));
1434 source_address_token
->set_timestamp(now
.ToUNIXSeconds());
1435 if (cached_network_params
!= nullptr) {
1436 *(source_address_token
->mutable_cached_network_parameters()) =
1437 *cached_network_params
;
1440 if (!FLAGS_quic_use_multiple_address_in_source_tokens
) {
1441 return config
.source_address_token_boxer
->Box(
1442 rand
, source_address_token
->SerializeAsString());
1445 // Append previous tokens.
1446 for (const SourceAddressToken
& token
: previous_tokens
.tokens()) {
1447 if (source_address_tokens
.tokens_size() > kMaxTokenAddresses
) {
1451 if (token
.ip() == source_address_token
->ip()) {
1452 // It's for the same IP address.
1456 if (ValidateSourceAddressTokenTimestamp(token
, now
) != HANDSHAKE_OK
) {
1460 *(source_address_tokens
.add_tokens()) = token
;
1463 return config
.source_address_token_boxer
->Box(
1464 rand
, source_address_tokens
.SerializeAsString());
1467 bool QuicCryptoServerConfig::HasProofSource() const {
1468 return proof_source_
!= nullptr;
1471 int QuicCryptoServerConfig::NumberOfConfigs() const {
1472 base::AutoLock
locked(configs_lock_
);
1473 return configs_
.size();
1476 HandshakeFailureReason
QuicCryptoServerConfig::ParseSourceAddressToken(
1477 const Config
& config
,
1479 SourceAddressTokens
* tokens
) const {
1481 StringPiece plaintext
;
1482 if (!config
.source_address_token_boxer
->Unbox(token
, &storage
, &plaintext
)) {
1483 return SOURCE_ADDRESS_TOKEN_DECRYPTION_FAILURE
;
1486 if (!FLAGS_quic_use_multiple_address_in_source_tokens
) {
1487 SourceAddressToken source_address_token
;
1488 if (!source_address_token
.ParseFromArray(plaintext
.data(),
1489 plaintext
.size())) {
1490 return SOURCE_ADDRESS_TOKEN_PARSE_FAILURE
;
1492 *(tokens
->add_tokens()) = source_address_token
;
1493 return HANDSHAKE_OK
;
1496 if (!tokens
->ParseFromArray(plaintext
.data(), plaintext
.size())) {
1497 // Some clients might still be using the old source token format so
1498 // attempt to parse that format.
1499 // TODO(rch): remove this code once the new format is ubiquitous.
1500 SourceAddressToken source_address_token
;
1501 if (!source_address_token
.ParseFromArray(plaintext
.data(),
1502 plaintext
.size())) {
1503 return SOURCE_ADDRESS_TOKEN_PARSE_FAILURE
;
1505 *tokens
->add_tokens() = source_address_token
;
1508 return HANDSHAKE_OK
;
1511 HandshakeFailureReason
QuicCryptoServerConfig::ValidateSourceAddressToken(
1512 const Config
& config
,
1514 const IPAddressNumber
& ip
,
1516 CachedNetworkParameters
* cached_network_params
) const {
1518 StringPiece plaintext
;
1519 if (!config
.source_address_token_boxer
->Unbox(token
, &storage
, &plaintext
)) {
1520 return SOURCE_ADDRESS_TOKEN_DECRYPTION_FAILURE
;
1523 SourceAddressToken source_address_token
;
1524 if (!source_address_token
.ParseFromArray(plaintext
.data(),
1525 plaintext
.size())) {
1526 return SOURCE_ADDRESS_TOKEN_PARSE_FAILURE
;
1529 if (source_address_token
.ip() !=
1530 IPAddressToPackedString(DualstackIPAddress(ip
))) {
1531 // It's for a different IP address.
1532 return SOURCE_ADDRESS_TOKEN_DIFFERENT_IP_ADDRESS_FAILURE
;
1535 const QuicWallTime
timestamp(
1536 QuicWallTime::FromUNIXSeconds(source_address_token
.timestamp()));
1537 const QuicTime::Delta
delta(now
.AbsoluteDifference(timestamp
));
1539 if (now
.IsBefore(timestamp
) &&
1540 delta
.ToSeconds() > source_address_token_future_secs_
) {
1541 return SOURCE_ADDRESS_TOKEN_CLOCK_SKEW_FAILURE
;
1544 if (now
.IsAfter(timestamp
) &&
1545 delta
.ToSeconds() > source_address_token_lifetime_secs_
) {
1546 return SOURCE_ADDRESS_TOKEN_EXPIRED_FAILURE
;
1549 if (source_address_token
.has_cached_network_parameters()) {
1550 *cached_network_params
= source_address_token
.cached_network_parameters();
1553 return HANDSHAKE_OK
;
1556 HandshakeFailureReason
QuicCryptoServerConfig::ValidateSourceAddressTokens(
1557 const SourceAddressTokens
& source_address_tokens
,
1558 const IPAddressNumber
& ip
,
1560 CachedNetworkParameters
* cached_network_params
) const {
1561 HandshakeFailureReason reason
=
1562 SOURCE_ADDRESS_TOKEN_DIFFERENT_IP_ADDRESS_FAILURE
;
1563 for (const SourceAddressToken
& token
: source_address_tokens
.tokens()) {
1564 reason
= ValidateSingleSourceAddressToken(token
, ip
, now
);
1565 if (reason
== HANDSHAKE_OK
) {
1566 if (token
.has_cached_network_parameters()) {
1567 *cached_network_params
= token
.cached_network_parameters();
1575 HandshakeFailureReason
QuicCryptoServerConfig::ValidateSingleSourceAddressToken(
1576 const SourceAddressToken
& source_address_token
,
1577 const IPAddressNumber
& ip
,
1578 QuicWallTime now
) const {
1579 if (source_address_token
.ip() !=
1580 IPAddressToPackedString(DualstackIPAddress(ip
))) {
1581 // It's for a different IP address.
1582 return SOURCE_ADDRESS_TOKEN_DIFFERENT_IP_ADDRESS_FAILURE
;
1585 return ValidateSourceAddressTokenTimestamp(source_address_token
, now
);
1588 HandshakeFailureReason
1589 QuicCryptoServerConfig::ValidateSourceAddressTokenTimestamp(
1590 const SourceAddressToken
& source_address_token
,
1591 QuicWallTime now
) const {
1592 const QuicWallTime
timestamp(
1593 QuicWallTime::FromUNIXSeconds(source_address_token
.timestamp()));
1594 const QuicTime::Delta
delta(now
.AbsoluteDifference(timestamp
));
1596 if (now
.IsBefore(timestamp
) &&
1597 delta
.ToSeconds() > source_address_token_future_secs_
) {
1598 return SOURCE_ADDRESS_TOKEN_CLOCK_SKEW_FAILURE
;
1601 if (now
.IsAfter(timestamp
) &&
1602 delta
.ToSeconds() > source_address_token_lifetime_secs_
) {
1603 return SOURCE_ADDRESS_TOKEN_EXPIRED_FAILURE
;
1606 return HANDSHAKE_OK
;
1609 // kServerNoncePlaintextSize is the number of bytes in an unencrypted server
1611 static const size_t kServerNoncePlaintextSize
=
1612 4 /* timestamp */ + 20 /* random bytes */;
1614 string
QuicCryptoServerConfig::NewServerNonce(QuicRandom
* rand
,
1615 QuicWallTime now
) const {
1616 const uint32 timestamp
= static_cast<uint32
>(now
.ToUNIXSeconds());
1618 uint8 server_nonce
[kServerNoncePlaintextSize
];
1619 static_assert(sizeof(server_nonce
) > sizeof(timestamp
), "nonce too small");
1620 server_nonce
[0] = static_cast<uint8
>(timestamp
>> 24);
1621 server_nonce
[1] = static_cast<uint8
>(timestamp
>> 16);
1622 server_nonce
[2] = static_cast<uint8
>(timestamp
>> 8);
1623 server_nonce
[3] = static_cast<uint8
>(timestamp
);
1624 rand
->RandBytes(&server_nonce
[sizeof(timestamp
)],
1625 sizeof(server_nonce
) - sizeof(timestamp
));
1627 return server_nonce_boxer_
.Box(
1629 StringPiece(reinterpret_cast<char*>(server_nonce
), sizeof(server_nonce
)));
1632 HandshakeFailureReason
QuicCryptoServerConfig::ValidateServerNonce(
1634 QuicWallTime now
) const {
1636 StringPiece plaintext
;
1637 if (!server_nonce_boxer_
.Unbox(token
, &storage
, &plaintext
)) {
1638 return SERVER_NONCE_DECRYPTION_FAILURE
;
1641 // plaintext contains:
1643 // uint8[20] random bytes
1645 if (plaintext
.size() != kServerNoncePlaintextSize
) {
1646 // This should never happen because the value decrypted correctly.
1647 LOG(DFATAL
) << "Seemingly valid server nonce had incorrect length.";
1648 return SERVER_NONCE_INVALID_FAILURE
;
1651 uint8 server_nonce
[32];
1652 memcpy(server_nonce
, plaintext
.data(), 4);
1653 memcpy(server_nonce
+ 4, server_nonce_orbit_
, sizeof(server_nonce_orbit_
));
1654 memcpy(server_nonce
+ 4 + sizeof(server_nonce_orbit_
), plaintext
.data() + 4,
1656 static_assert(4 + sizeof(server_nonce_orbit_
) + 20 == sizeof(server_nonce
),
1657 "bad nonce buffer length");
1659 InsertStatus nonce_error
;
1661 base::AutoLock
auto_lock(server_nonce_strike_register_lock_
);
1662 if (server_nonce_strike_register_
.get() == nullptr) {
1663 server_nonce_strike_register_
.reset(new StrikeRegister(
1664 server_nonce_strike_register_max_entries_
,
1665 static_cast<uint32
>(now
.ToUNIXSeconds()),
1666 server_nonce_strike_register_window_secs_
, server_nonce_orbit_
,
1667 StrikeRegister::NO_STARTUP_PERIOD_NEEDED
));
1669 nonce_error
= server_nonce_strike_register_
->Insert(
1670 server_nonce
, static_cast<uint32
>(now
.ToUNIXSeconds()));
1673 switch (nonce_error
) {
1675 return HANDSHAKE_OK
;
1676 case NONCE_INVALID_FAILURE
:
1677 case NONCE_INVALID_ORBIT_FAILURE
:
1678 return SERVER_NONCE_INVALID_FAILURE
;
1679 case NONCE_NOT_UNIQUE_FAILURE
:
1680 return SERVER_NONCE_NOT_UNIQUE_FAILURE
;
1681 case NONCE_INVALID_TIME_FAILURE
:
1682 return SERVER_NONCE_INVALID_TIME_FAILURE
;
1683 case NONCE_UNKNOWN_FAILURE
:
1684 case STRIKE_REGISTER_TIMEOUT
:
1685 case STRIKE_REGISTER_FAILURE
:
1687 LOG(DFATAL
) << "Unexpected server nonce error: " << nonce_error
;
1688 return SERVER_NONCE_NOT_UNIQUE_FAILURE
;
1692 QuicCryptoServerConfig::Config::Config()
1693 : channel_id_enabled(false),
1695 primary_time(QuicWallTime::Zero()),
1697 source_address_token_boxer(nullptr) {}
1699 QuicCryptoServerConfig::Config::~Config() { STLDeleteElements(&key_exchanges
); }