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 #ifndef NET_QUIC_CRYPTO_QUIC_CRYPTO_SERVER_CONFIG_H_
6 #define NET_QUIC_CRYPTO_QUIC_CRYPTO_SERVER_CONFIG_H_
12 #include "base/memory/ref_counted.h"
13 #include "base/memory/scoped_ptr.h"
14 #include "base/strings/string_piece.h"
15 #include "base/synchronization/lock.h"
16 #include "net/base/ip_endpoint.h"
17 #include "net/base/net_export.h"
18 #include "net/quic/crypto/crypto_handshake.h"
19 #include "net/quic/crypto/crypto_handshake_message.h"
20 #include "net/quic/crypto/crypto_protocol.h"
21 #include "net/quic/crypto/crypto_secret_boxer.h"
22 #include "net/quic/proto/cached_network_parameters.pb.h"
23 #include "net/quic/proto/source_address_token.pb.h"
24 #include "net/quic/quic_time.h"
28 class CryptoHandshakeMessage
;
29 class EphemeralKeySource
;
36 class QuicServerConfigProtobuf
;
38 class StrikeRegisterClient
;
40 // ClientHelloInfo contains information about a client hello message that is
41 // only kept for as long as it's being processed.
42 struct ClientHelloInfo
{
43 ClientHelloInfo(const IPAddressNumber
& in_client_ip
, QuicWallTime in_now
);
46 // Inputs to EvaluateClientHello.
47 const IPAddressNumber client_ip
;
48 const QuicWallTime now
;
50 // Outputs from EvaluateClientHello.
51 bool valid_source_address_token
;
52 bool client_nonce_well_formed
;
54 base::StringPiece sni
;
55 base::StringPiece client_nonce
;
56 base::StringPiece server_nonce
;
57 base::StringPiece user_agent_id
;
58 SourceAddressTokens source_address_tokens
;
60 // Errors from EvaluateClientHello.
61 std::vector
<uint32
> reject_reasons
;
62 COMPILE_ASSERT(sizeof(QuicTag
) == sizeof(uint32
), header_out_of_sync
);
66 class QuicCryptoServerConfigPeer
;
69 // Hook that allows application code to subscribe to primary config changes.
70 class PrimaryConfigChangedCallback
{
72 PrimaryConfigChangedCallback();
73 virtual ~PrimaryConfigChangedCallback();
74 virtual void Run(const std::string
& scid
) = 0;
77 DISALLOW_COPY_AND_ASSIGN(PrimaryConfigChangedCallback
);
80 // Callback used to accept the result of the |client_hello| validation step.
81 class NET_EXPORT_PRIVATE ValidateClientHelloResultCallback
{
83 // Opaque token that holds information about the client_hello and
84 // its validity. Can be interpreted by calling ProcessClientHello.
86 Result(const CryptoHandshakeMessage
& in_client_hello
,
87 IPAddressNumber in_client_ip
,
91 CryptoHandshakeMessage client_hello
;
93 QuicErrorCode error_code
;
94 std::string error_details
;
96 // Populated if the CHLO STK contained a CachedNetworkParameters proto.
97 CachedNetworkParameters cached_network_params
;
100 ValidateClientHelloResultCallback();
101 virtual ~ValidateClientHelloResultCallback();
102 void Run(const Result
* result
);
105 virtual void RunImpl(const CryptoHandshakeMessage
& client_hello
,
106 const Result
& result
) = 0;
109 DISALLOW_COPY_AND_ASSIGN(ValidateClientHelloResultCallback
);
112 // QuicCryptoServerConfig contains the crypto configuration of a QUIC server.
113 // Unlike a client, a QUIC server can have multiple configurations active in
114 // order to support clients resuming with a previous configuration.
115 // TODO(agl): when adding configurations at runtime is added, this object will
116 // need to consider locking.
117 class NET_EXPORT_PRIVATE QuicCryptoServerConfig
{
119 // ConfigOptions contains options for generating server configs.
120 struct NET_EXPORT_PRIVATE ConfigOptions
{
123 // expiry_time is the time, in UNIX seconds, when the server config will
124 // expire. If unset, it defaults to the current time plus six months.
125 QuicWallTime expiry_time
;
126 // channel_id_enabled controls whether the server config will indicate
127 // support for ChannelIDs.
128 bool channel_id_enabled
;
129 // id contains the server config id for the resulting config. If empty, a
130 // random id is generated.
132 // orbit contains the kOrbitSize bytes of the orbit value for the server
133 // config. If |orbit| is empty then a random orbit is generated.
135 // p256 determines whether a P-256 public key will be included in the
136 // server config. Note that this breaks deterministic server-config
137 // generation since P-256 key generation doesn't use the QuicRandom given
138 // to DefaultConfig().
142 // |source_address_token_secret|: secret key material used for encrypting and
143 // decrypting source address tokens. It can be of any length as it is fed
144 // into a KDF before use. In tests, use TESTING.
145 // |server_nonce_entropy|: an entropy source used to generate the orbit and
146 // key for server nonces, which are always local to a given instance of a
148 QuicCryptoServerConfig(base::StringPiece source_address_token_secret
,
149 QuicRandom
* server_nonce_entropy
);
150 ~QuicCryptoServerConfig();
152 // TESTING is a magic parameter for passing to the constructor in tests.
153 static const char TESTING
[];
155 // Generates a QuicServerConfigProtobuf protobuf suitable for
156 // AddConfig and SetConfigs.
157 static QuicServerConfigProtobuf
* GenerateConfig(
159 const QuicClock
* clock
,
160 const ConfigOptions
& options
);
162 // AddConfig adds a QuicServerConfigProtobuf to the availible configurations.
163 // It returns the SCFG message from the config if successful. The caller
164 // takes ownership of the CryptoHandshakeMessage. |now| is used in
165 // conjunction with |protobuf->primary_time()| to determine whether the
166 // config should be made primary.
167 CryptoHandshakeMessage
* AddConfig(QuicServerConfigProtobuf
* protobuf
,
170 // AddDefaultConfig calls DefaultConfig to create a config and then calls
171 // AddConfig to add it. See the comment for |DefaultConfig| for details of
173 CryptoHandshakeMessage
* AddDefaultConfig(
175 const QuicClock
* clock
,
176 const ConfigOptions
& options
);
178 // SetConfigs takes a vector of config protobufs and the current time.
179 // Configs are assumed to be uniquely identified by their server config ID.
180 // Previously unknown configs are added and possibly made the primary config
181 // depending on their |primary_time| and the value of |now|. Configs that are
182 // known, but are missing from the protobufs are deleted, unless they are
183 // currently the primary config. SetConfigs returns false if any errors were
184 // encountered and no changes to the QuicCryptoServerConfig will occur.
185 bool SetConfigs(const std::vector
<QuicServerConfigProtobuf
*>& protobufs
,
188 // Get the server config ids for all known configs.
189 void GetConfigIds(std::vector
<std::string
>* scids
) const;
191 // Checks |client_hello| for gross errors and determines whether it
192 // can be shown to be fresh (i.e. not a replay). The result of the
193 // validation step must be interpreted by calling
194 // QuicCryptoServerConfig::ProcessClientHello from the done_cb.
196 // ValidateClientHello may invoke the done_cb before unrolling the
197 // stack if it is able to assess the validity of the client_nonce
198 // without asynchronous operations.
200 // client_hello: the incoming client hello message.
201 // client_ip: the IP address of the client, which is used to generate and
202 // validate source-address tokens.
203 // clock: used to validate client nonces and ephemeral keys.
204 // done_cb: single-use callback that accepts an opaque
205 // ValidatedClientHelloMsg token that holds information about
206 // the client hello. The callback will always be called exactly
207 // once, either under the current call stack, or after the
208 // completion of an asynchronous operation.
209 void ValidateClientHello(const CryptoHandshakeMessage
& client_hello
,
210 IPAddressNumber client_ip
,
211 const QuicClock
* clock
,
212 ValidateClientHelloResultCallback
* done_cb
) const;
214 // ProcessClientHello processes |client_hello| and decides whether to accept
215 // or reject the connection. If the connection is to be accepted, |out| is
216 // set to the contents of the ServerHello, |out_params| is completed and
217 // QUIC_NO_ERROR is returned. Otherwise |out| is set to be a REJ message and
218 // an error code is returned.
220 // validate_chlo_result: Output from the asynchronous call to
221 // ValidateClientHello. Contains the client hello message and
222 // information about it.
223 // connection_id: the ConnectionId for the connection, which is used in key
225 // server_ip: the IP address and port of the server. The IP address may be
226 // used for certificate selection.
227 // client_address: the IP address and port of the client. The IP address is
228 // used to generate and validate source-address tokens.
229 // version: version of the QUIC protocol in use for this connection
230 // supported_versions: versions of the QUIC protocol that this server
232 // initial_flow_control_window: size of initial flow control window this
233 // server uses for new streams.
234 // clock: used to validate client nonces and ephemeral keys.
235 // rand: an entropy source
236 // params: the state of the handshake. This may be updated with a server
237 // nonce when we send a rejection. After a successful handshake, this will
238 // contain the state of the connection.
239 // out: the resulting handshake message (either REJ or SHLO)
240 // error_details: used to store a string describing any error.
241 QuicErrorCode
ProcessClientHello(
242 const ValidateClientHelloResultCallback::Result
& validate_chlo_result
,
243 QuicConnectionId connection_id
,
244 const IPAddressNumber
& server_ip
,
245 const IPEndPoint
& client_address
,
247 const QuicVersionVector
& supported_versions
,
248 const QuicClock
* clock
,
250 QuicCryptoNegotiatedParameters
* params
,
251 CryptoHandshakeMessage
* out
,
252 std::string
* error_details
) const;
254 // BuildServerConfigUpdateMessage sets |out| to be a SCUP message containing
255 // the current primary config, an up to date source-address token, and cert
256 // chain and proof in the case of secure QUIC. Returns true if successfully
259 // |cached_network_params| is optional, and can be nullptr.
260 bool BuildServerConfigUpdateMessage(
261 const SourceAddressTokens
& previous_source_address_tokens
,
262 const IPAddressNumber
& server_ip
,
263 const IPAddressNumber
& client_ip
,
264 const QuicClock
* clock
,
266 const QuicCryptoNegotiatedParameters
& params
,
267 const CachedNetworkParameters
* cached_network_params
,
268 CryptoHandshakeMessage
* out
) const;
270 // SetProofSource installs |proof_source| as the ProofSource for handshakes.
271 // This object takes ownership of |proof_source|.
272 void SetProofSource(ProofSource
* proof_source
);
274 // SetEphemeralKeySource installs an object that can cache ephemeral keys for
275 // a short period of time. This object takes ownership of
276 // |ephemeral_key_source|. If not set then ephemeral keys will be generated
278 void SetEphemeralKeySource(EphemeralKeySource
* ephemeral_key_source
);
280 // Install an externall created StrikeRegisterClient for use to
281 // interact with the strike register. This object takes ownership
282 // of the |strike_register_client|.
283 void SetStrikeRegisterClient(StrikeRegisterClient
* strike_register_client
);
285 // set_replay_protection controls whether replay protection is enabled. If
286 // replay protection is disabled then no strike registers are needed and
287 // frontends can share an orbit value without a shared strike-register.
288 // However, an attacker can duplicate a handshake and cause a client's
289 // request to be processed twice.
290 void set_replay_protection(bool on
);
292 // set_strike_register_no_startup_period configures the strike register to
293 // not have a startup period.
294 void set_strike_register_no_startup_period();
296 // set_strike_register_max_entries sets the maximum number of entries that
297 // the internal strike register will hold. If the strike register fills up
298 // then the oldest entries (by the client's clock) will be dropped.
299 void set_strike_register_max_entries(uint32 max_entries
);
301 // set_strike_register_window_secs sets the number of seconds around the
302 // current time that the strike register will attempt to be authoritative
303 // for. Setting a larger value allows for greater client clock-skew, but
304 // means that the quiescent startup period must be longer.
305 void set_strike_register_window_secs(uint32 window_secs
);
307 // set_source_address_token_future_secs sets the number of seconds into the
308 // future that source-address tokens will be accepted from. Since
309 // source-address tokens are authenticated, this should only happen if
310 // another, valid server has clock-skew.
311 void set_source_address_token_future_secs(uint32 future_secs
);
313 // set_source_address_token_lifetime_secs sets the number of seconds that a
314 // source-address token will be valid for.
315 void set_source_address_token_lifetime_secs(uint32 lifetime_secs
);
317 // set_server_nonce_strike_register_max_entries sets the number of entries in
318 // the server-nonce strike-register. This is used to record that server nonce
319 // values have been used. If the number of entries is too small then clients
320 // which are depending on server nonces may fail to handshake because their
321 // nonce has expired in the amount of time it took to go from the server to
322 // the client and back.
323 void set_server_nonce_strike_register_max_entries(uint32 max_entries
);
325 // set_server_nonce_strike_register_window_secs sets the number of seconds
326 // around the current time that the server-nonce strike-register will accept
327 // nonces from. Setting a larger value allows for clients to delay follow-up
328 // client hellos for longer and still use server nonces as proofs of
330 void set_server_nonce_strike_register_window_secs(uint32 window_secs
);
332 // Set and take ownership of the callback to invoke on primary config changes.
333 void AcquirePrimaryConfigChangedCb(PrimaryConfigChangedCallback
* cb
);
335 // Returns true if this config has a |proof_source_|.
336 bool HasProofSource() const;
338 // Returns the number of configs this object owns.
339 int NumberOfConfigs() const;
342 friend class test::QuicCryptoServerConfigPeer
;
344 // Config represents a server config: a collection of preferences and
345 // Diffie-Hellman public values.
346 class NET_EXPORT_PRIVATE Config
: public QuicCryptoConfig
,
347 public base::RefCounted
<Config
> {
351 // TODO(rtenneti): since this is a class, we should probably do
352 // getters/setters here.
353 // |serialized| contains the bytes of this server config, suitable for
354 // sending on the wire.
355 std::string serialized
;
356 // id contains the SCID of this server config.
358 // orbit contains the orbit value for this config: an opaque identifier
359 // used to identify clusters of server frontends.
360 unsigned char orbit
[kOrbitSize
];
362 // key_exchanges contains key exchange objects with the private keys
363 // already loaded. The values correspond, one-to-one, with the tags in
364 // |kexs| from the parent class.
365 std::vector
<KeyExchange
*> key_exchanges
;
367 // tag_value_map contains the raw key/value pairs for the config.
368 QuicTagValueMap tag_value_map
;
370 // channel_id_enabled is true if the config in |serialized| specifies that
371 // ChannelIDs are supported.
372 bool channel_id_enabled
;
374 // is_primary is true if this config is the one that we'll give out to
375 // clients as the current one.
378 // primary_time contains the timestamp when this config should become the
379 // primary config. A value of QuicWallTime::Zero() means that this config
380 // will not be promoted at a specific time.
381 QuicWallTime primary_time
;
383 // Secondary sort key for use when selecting primary configs and
384 // there are multiple configs with the same primary time.
385 // Smaller numbers mean higher priority.
388 // source_address_token_boxer_ is used to protect the
389 // source-address tokens that are given to clients.
390 // Points to either source_address_token_boxer_storage or the
391 // default boxer provided by QuicCryptoServerConfig.
392 const CryptoSecretBoxer
* source_address_token_boxer
;
394 // Holds the override source_address_token_boxer instance if the
395 // Config is not using the default source address token boxer
396 // instance provided by QuicCryptoServerConfig.
397 scoped_ptr
<CryptoSecretBoxer
> source_address_token_boxer_storage
;
400 friend class base::RefCounted
<Config
>;
404 DISALLOW_COPY_AND_ASSIGN(Config
);
407 typedef std::map
<ServerConfigID
, scoped_refptr
<Config
> > ConfigMap
;
409 // Get a ref to the config with a given server config id.
410 scoped_refptr
<Config
> GetConfigWithScid(
411 base::StringPiece requested_scid
) const;
413 // ConfigPrimaryTimeLessThan returns true if a->primary_time <
415 static bool ConfigPrimaryTimeLessThan(const scoped_refptr
<Config
>& a
,
416 const scoped_refptr
<Config
>& b
);
418 // SelectNewPrimaryConfig reevaluates the primary config based on the
419 // "primary_time" deadlines contained in each.
420 void SelectNewPrimaryConfig(QuicWallTime now
) const;
422 // EvaluateClientHello checks |client_hello| for gross errors and determines
423 // whether it can be shown to be fresh (i.e. not a replay). The results are
424 // written to |info|.
425 void EvaluateClientHello(
426 const uint8
* primary_orbit
,
427 scoped_refptr
<Config
> requested_config
,
428 ValidateClientHelloResultCallback::Result
* client_hello_state
,
429 ValidateClientHelloResultCallback
* done_cb
) const;
431 // BuildRejection sets |out| to be a REJ message in reply to |client_hello|.
432 void BuildRejection(const IPAddressNumber
& server_address
,
433 const Config
& config
,
434 const CryptoHandshakeMessage
& client_hello
,
435 const ClientHelloInfo
& info
,
436 const CachedNetworkParameters
& cached_network_params
,
438 QuicCryptoNegotiatedParameters
* params
,
439 CryptoHandshakeMessage
* out
) const;
441 // ParseConfigProtobuf parses the given config protobuf and returns a
442 // scoped_refptr<Config> if successful. The caller adopts the reference to the
443 // Config. On error, ParseConfigProtobuf returns nullptr.
444 scoped_refptr
<Config
> ParseConfigProtobuf(QuicServerConfigProtobuf
* protobuf
);
446 // NewSourceAddressToken returns a fresh source address token for the given
447 // IP address. |cached_network_params| is optional, and can be nullptr.
448 std::string
NewSourceAddressToken(
449 const Config
& config
,
450 const SourceAddressTokens
& previous_tokens
,
451 const IPAddressNumber
& ip
,
454 const CachedNetworkParameters
* cached_network_params
) const;
456 // ParseSourceAddressToken parses the source address tokens contained in
457 // the encrypted |token|, and populates |tokens| with the parsed tokens.
458 // Returns HANDSHAKE_OK if |token| could be parsed, or the reason for the
460 HandshakeFailureReason
ParseSourceAddressToken(
461 const Config
& config
,
462 base::StringPiece token
,
463 SourceAddressTokens
* tokens
) const;
465 // ValidateSourceAddressToken returns HANDSHAKE_OK if the source address
466 // tokens in |tokens| contain a valid and timely token for the IP address
467 // |ip| given that the current time is |now|. Otherwise it returns the
468 // reason for failure. |cached_network_params| is populated if the valid
469 // token contains a CachedNetworkParameters proto.
470 // TODO(rch): remove this method when we remove:
471 // FLAGS_quic_use_multiple_address_in_source_tokens.
472 HandshakeFailureReason
ValidateSourceAddressToken(
473 const Config
& config
,
474 base::StringPiece token
,
475 const IPAddressNumber
& ip
,
477 CachedNetworkParameters
* cached_network_params
) const;
479 // ValidateSourceAddressTokens returns HANDSHAKE_OK if the source address
480 // tokens in |tokens| contain a valid and timely token for the IP address
481 // |ip| given that the current time is |now|. Otherwise it returns the
482 // reason for failure. |cached_network_params| is populated if the valid
483 // token contains a CachedNetworkParameters proto.
484 HandshakeFailureReason
ValidateSourceAddressTokens(
485 const SourceAddressTokens
& tokens
,
486 const IPAddressNumber
& ip
,
488 CachedNetworkParameters
* cached_network_params
) const;
490 // ValidateSingleSourceAddressToken returns HANDSHAKE_OK if the source
491 // address token in |token| is a timely token for the IP address |ip|
492 // given that the current time is |now|. Otherwise it returns the reason
494 HandshakeFailureReason
ValidateSingleSourceAddressToken(
495 const SourceAddressToken
& token
,
496 const IPAddressNumber
& ip
,
497 QuicWallTime now
) const;
499 // Returns HANDSHAKE_OK if the source address token in |token| is a timely
500 // token given that the current time is |now|. Otherwise it returns the
501 // reason for failure.
502 HandshakeFailureReason
ValidateSourceAddressTokenTimestamp(
503 const SourceAddressToken
& token
,
504 QuicWallTime now
) const;
506 // NewServerNonce generates and encrypts a random nonce.
507 std::string
NewServerNonce(QuicRandom
* rand
, QuicWallTime now
) const;
509 // ValidateServerNonce decrypts |token| and verifies that it hasn't been
510 // previously used and is recent enough that it is plausible that it was part
511 // of a very recently provided rejection ("recent" will be on the order of
512 // 10-30 seconds). If so, it records that it has been used and returns
513 // HANDSHAKE_OK. Otherwise it returns the reason for failure.
514 HandshakeFailureReason
ValidateServerNonce(
515 base::StringPiece echoed_server_nonce
,
516 QuicWallTime now
) const;
518 // replay_protection_ controls whether the server enforces that handshakes
520 bool replay_protection_
;
522 // configs_ satisfies the following invariants:
523 // 1) configs_.empty() <-> primary_config_ == nullptr
524 // 2) primary_config_ != nullptr -> primary_config_->is_primary
525 // 3) ∀ c∈configs_, c->is_primary <-> c == primary_config_
526 mutable base::Lock configs_lock_
;
527 // configs_ contains all active server configs. It's expected that there are
528 // about half-a-dozen configs active at any one time.
530 // primary_config_ points to a Config (which is also in |configs_|) which is
531 // the primary config - i.e. the one that we'll give out to new clients.
532 mutable scoped_refptr
<Config
> primary_config_
;
533 // next_config_promotion_time_ contains the nearest, future time when an
534 // active config will be promoted to primary.
535 mutable QuicWallTime next_config_promotion_time_
;
536 // Callback to invoke when the primary config changes.
537 scoped_ptr
<PrimaryConfigChangedCallback
> primary_config_changed_cb_
;
539 // Protects access to the pointer held by strike_register_client_.
540 mutable base::Lock strike_register_client_lock_
;
541 // strike_register_ contains a data structure that keeps track of previously
542 // observed client nonces in order to prevent replay attacks.
543 mutable scoped_ptr
<StrikeRegisterClient
> strike_register_client_
;
545 // Default source_address_token_boxer_ used to protect the
546 // source-address tokens that are given to clients. Individual
547 // configs may use boxers with alternate secrets.
548 CryptoSecretBoxer default_source_address_token_boxer_
;
550 // server_nonce_boxer_ is used to encrypt and validate suggested server
552 CryptoSecretBoxer server_nonce_boxer_
;
554 // server_nonce_orbit_ contains the random, per-server orbit values that this
555 // server will use to generate server nonces (the moral equivalent of a SYN
557 uint8 server_nonce_orbit_
[8];
559 mutable base::Lock server_nonce_strike_register_lock_
;
560 // server_nonce_strike_register_ contains a data structure that keeps track of
561 // previously observed server nonces from this server, in order to prevent
563 mutable scoped_ptr
<StrikeRegister
> server_nonce_strike_register_
;
565 // proof_source_ contains an object that can provide certificate chains and
567 scoped_ptr
<ProofSource
> proof_source_
;
569 // ephemeral_key_source_ contains an object that caches ephemeral keys for a
570 // short period of time.
571 scoped_ptr
<EphemeralKeySource
> ephemeral_key_source_
;
573 // These fields store configuration values. See the comments for their
574 // respective setter functions.
575 bool strike_register_no_startup_period_
;
576 uint32 strike_register_max_entries_
;
577 uint32 strike_register_window_secs_
;
578 uint32 source_address_token_future_secs_
;
579 uint32 source_address_token_lifetime_secs_
;
580 uint32 server_nonce_strike_register_max_entries_
;
581 uint32 server_nonce_strike_register_window_secs_
;
583 DISALLOW_COPY_AND_ASSIGN(QuicCryptoServerConfig
);
588 #endif // NET_QUIC_CRYPTO_QUIC_CRYPTO_SERVER_CONFIG_H_