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. 4 5 #ifndef QUICHE_QUIC_CORE_CRYPTO_QUIC_CRYPTO_CLIENT_CONFIG_H_ 6 #define QUICHE_QUIC_CORE_CRYPTO_QUIC_CRYPTO_CLIENT_CONFIG_H_ 7 8 #include <cstdint> 9 #include <map> 10 #include <memory> 11 #include <string> 12 #include <vector> 13 14 #include "third_party/boringssl/src/include/openssl/base.h" 15 #include "third_party/boringssl/src/include/openssl/ssl.h" 16 #include "net/third_party/quiche/src/quic/core/crypto/crypto_handshake.h" 17 #include "net/third_party/quiche/src/quic/core/crypto/crypto_protocol.h" 18 #include "net/third_party/quiche/src/quic/core/crypto/proof_source.h" 19 #include "net/third_party/quiche/src/quic/core/crypto/transport_parameters.h" 20 #include "net/third_party/quiche/src/quic/core/quic_packets.h" 21 #include "net/third_party/quiche/src/quic/core/quic_server_id.h" 22 #include "net/third_party/quiche/src/quic/platform/api/quic_export.h" 23 #include "net/third_party/quiche/src/quic/platform/api/quic_reference_counted.h" 24 #include "net/third_party/quiche/src/common/platform/api/quiche_string_piece.h" 25 26 namespace quic { 27 28 class CryptoHandshakeMessage; 29 class ProofVerifier; 30 class ProofVerifyDetails; 31 class QuicRandom; 32 33 // QuicResumptionState stores the state a client needs for performing connection 34 // resumption. 35 struct QUIC_EXPORT_PRIVATE QuicResumptionState { 36 // |tls_session| holds the cryptographic state necessary for a resumption. It 37 // includes the ALPN negotiated on the connection where the ticket was 38 // received. 39 bssl::UniquePtr<SSL_SESSION> tls_session; 40 41 // If the application using QUIC doesn't support 0-RTT handshakes or the 42 // client didn't receive a 0-RTT capable session ticket from the server, 43 // |transport_params| will be null. Otherwise, it will contain the transport 44 // parameters received from the server on the original connection. 45 std::unique_ptr<TransportParameters> transport_params; 46 47 // If |transport_params| is null, then |application_state| is ignored and 48 // should be empty. |application_state| contains serialized state that the 49 // client received from the server at the application layer that the client 50 // needs to remember when performing a 0-RTT handshake. 51 std::vector<uint8_t> application_state; 52 }; 53 54 // SessionCache is an interface for managing storing and retrieving 55 // QuicResumptionState structs. 56 class QUIC_EXPORT_PRIVATE SessionCache { 57 public: ~SessionCache()58 virtual ~SessionCache() {} 59 60 // Inserts |state| into the cache, keyed by |server_id|. Insert is called 61 // after a session ticket is received. If the session ticket is valid for 62 // 0-RTT, there may be a delay between its receipt and the call to Insert 63 // while waiting for application state for |state|. 64 // 65 // Insert may be called multiple times per connection. SessionCache 66 // implementations should support storing multiple entries per server ID. 67 virtual void Insert(const QuicServerId& server_id, 68 std::unique_ptr<QuicResumptionState> state) = 0; 69 70 // Lookup is called once at the beginning of each TLS handshake to potentially 71 // provide the saved state both for the TLS handshake and for sending 0-RTT 72 // data (if supported). Lookup may return a nullptr. Implementations should 73 // delete cache entries after returning them in Lookup so that session tickets 74 // are used only once. 75 virtual std::unique_ptr<QuicResumptionState> Lookup( 76 const QuicServerId& server_id, 77 const SSL_CTX* ctx) = 0; 78 }; 79 80 // QuicCryptoClientConfig contains crypto-related configuration settings for a 81 // client. Note that this object isn't thread-safe. It's designed to be used on 82 // a single thread at a time. 83 class QUIC_EXPORT_PRIVATE QuicCryptoClientConfig : public QuicCryptoConfig { 84 public: 85 // A CachedState contains the information that the client needs in order to 86 // perform a 0-RTT handshake with a server. This information can be reused 87 // over several connections to the same server. 88 class QUIC_EXPORT_PRIVATE CachedState { 89 public: 90 // Enum to track if the server config is valid or not. If it is not valid, 91 // it specifies why it is invalid. 92 enum ServerConfigState { 93 // WARNING: Do not change the numerical values of any of server config 94 // state. Do not remove deprecated server config states - just comment 95 // them as deprecated. 96 SERVER_CONFIG_EMPTY = 0, 97 SERVER_CONFIG_INVALID = 1, 98 SERVER_CONFIG_CORRUPTED = 2, 99 SERVER_CONFIG_EXPIRED = 3, 100 SERVER_CONFIG_INVALID_EXPIRY = 4, 101 SERVER_CONFIG_VALID = 5, 102 // NOTE: Add new server config states only immediately above this line. 103 // Make sure to update the QuicServerConfigState enum in 104 // tools/metrics/histograms/histograms.xml accordingly. 105 SERVER_CONFIG_COUNT 106 }; 107 108 CachedState(); 109 CachedState(const CachedState&) = delete; 110 CachedState& operator=(const CachedState&) = delete; 111 ~CachedState(); 112 113 // IsComplete returns true if this object contains enough information to 114 // perform a handshake with the server. |now| is used to judge whether any 115 // cached server config has expired. 116 bool IsComplete(QuicWallTime now) const; 117 118 // IsEmpty returns true if |server_config_| is empty. 119 bool IsEmpty() const; 120 121 // GetServerConfig returns the parsed contents of |server_config|, or 122 // nullptr if |server_config| is empty. The return value is owned by this 123 // object and is destroyed when this object is. 124 const CryptoHandshakeMessage* GetServerConfig() const; 125 126 // SetServerConfig checks that |server_config| parses correctly and stores 127 // it in |server_config_|. |now| is used to judge whether |server_config| 128 // has expired. 129 ServerConfigState SetServerConfig(quiche::QuicheStringPiece server_config, 130 QuicWallTime now, 131 QuicWallTime expiry_time, 132 std::string* error_details); 133 134 // InvalidateServerConfig clears the cached server config (if any). 135 void InvalidateServerConfig(); 136 137 // SetProof stores a cert chain, cert signed timestamp and signature. 138 void SetProof(const std::vector<std::string>& certs, 139 quiche::QuicheStringPiece cert_sct, 140 quiche::QuicheStringPiece chlo_hash, 141 quiche::QuicheStringPiece signature); 142 143 // Clears all the data. 144 void Clear(); 145 146 // Clears the certificate chain and signature and invalidates the proof. 147 void ClearProof(); 148 149 // SetProofValid records that the certificate chain and signature have been 150 // validated and that it's safe to assume that the server is legitimate. 151 // (Note: this does not check the chain or signature.) 152 void SetProofValid(); 153 154 // If the server config or the proof has changed then it needs to be 155 // revalidated. Helper function to keep server_config_valid_ and 156 // generation_counter_ in sync. 157 void SetProofInvalid(); 158 159 const std::string& server_config() const; 160 const std::string& source_address_token() const; 161 const std::vector<std::string>& certs() const; 162 const std::string& cert_sct() const; 163 const std::string& chlo_hash() const; 164 const std::string& signature() const; 165 bool proof_valid() const; 166 uint64_t generation_counter() const; 167 const ProofVerifyDetails* proof_verify_details() const; 168 169 void set_source_address_token(quiche::QuicheStringPiece token); 170 171 void set_cert_sct(quiche::QuicheStringPiece cert_sct); 172 173 // Adds the connection ID to the queue of server-designated connection-ids. 174 void add_server_designated_connection_id(QuicConnectionId connection_id); 175 176 // If true, the crypto config contains at least one connection ID specified 177 // by the server, and the client should use one of these IDs when initiating 178 // the next connection. 179 bool has_server_designated_connection_id() const; 180 181 // This function should only be called when 182 // has_server_designated_connection_id is true. Returns the next 183 // connection_id specified by the server and removes it from the 184 // queue of ids. 185 QuicConnectionId GetNextServerDesignatedConnectionId(); 186 187 // Adds the servernonce to the queue of server nonces. 188 void add_server_nonce(const std::string& server_nonce); 189 190 // If true, the crypto config contains at least one server nonce, and the 191 // client should use one of these nonces. 192 bool has_server_nonce() const; 193 194 // This function should only be called when has_server_nonce is true. 195 // Returns the next server_nonce specified by the server and removes it 196 // from the queue of nonces. 197 std::string GetNextServerNonce(); 198 199 // SetProofVerifyDetails takes ownership of |details|. 200 void SetProofVerifyDetails(ProofVerifyDetails* details); 201 202 // Copy the |server_config_|, |source_address_token_|, |certs_|, 203 // |expiration_time_|, |cert_sct_|, |chlo_hash_| and |server_config_sig_| 204 // from the |other|. The remaining fields, |generation_counter_|, 205 // |proof_verify_details_|, and |scfg_| remain unchanged. 206 void InitializeFrom(const CachedState& other); 207 208 // Initializes this cached state based on the arguments provided. 209 // Returns false if there is a problem parsing the server config. 210 bool Initialize(quiche::QuicheStringPiece server_config, 211 quiche::QuicheStringPiece source_address_token, 212 const std::vector<std::string>& certs, 213 const std::string& cert_sct, 214 quiche::QuicheStringPiece chlo_hash, 215 quiche::QuicheStringPiece signature, 216 QuicWallTime now, 217 QuicWallTime expiration_time); 218 219 private: 220 std::string server_config_; // A serialized handshake message. 221 std::string source_address_token_; // An opaque proof of IP ownership. 222 std::vector<std::string> certs_; // A list of certificates in leaf-first 223 // order. 224 std::string cert_sct_; // Signed timestamp of the leaf cert. 225 std::string chlo_hash_; // Hash of the CHLO message. 226 std::string server_config_sig_; // A signature of |server_config_|. 227 bool server_config_valid_; // True if |server_config_| is correctly 228 // signed and |certs_| has been validated. 229 QuicWallTime expiration_time_; // Time when the config is no longer valid. 230 // Generation counter associated with the |server_config_|, |certs_| and 231 // |server_config_sig_| combination. It is incremented whenever we set 232 // server_config_valid_ to false. 233 uint64_t generation_counter_; 234 235 std::unique_ptr<ProofVerifyDetails> proof_verify_details_; 236 237 // scfg contains the cached, parsed value of |server_config|. 238 mutable std::unique_ptr<CryptoHandshakeMessage> scfg_; 239 240 // TODO(jokulik): Consider using a hash-set as extra book-keeping to ensure 241 // that no connection-id is added twice. Also, consider keeping the server 242 // nonces and connection_ids together in one queue. 243 QuicQueue<QuicConnectionId> server_designated_connection_ids_; 244 QuicQueue<std::string> server_nonces_; 245 }; 246 247 // Used to filter server ids for partial config deletion. 248 class QUIC_EXPORT_PRIVATE ServerIdFilter { 249 public: ~ServerIdFilter()250 virtual ~ServerIdFilter() {} 251 252 // Returns true if |server_id| matches the filter. 253 virtual bool Matches(const QuicServerId& server_id) const = 0; 254 }; 255 256 // DEPRECATED: Use the constructor below instead. 257 explicit QuicCryptoClientConfig( 258 std::unique_ptr<ProofVerifier> proof_verifier); 259 QuicCryptoClientConfig(std::unique_ptr<ProofVerifier> proof_verifier, 260 std::unique_ptr<SessionCache> session_cache); 261 QuicCryptoClientConfig(const QuicCryptoClientConfig&) = delete; 262 QuicCryptoClientConfig& operator=(const QuicCryptoClientConfig&) = delete; 263 ~QuicCryptoClientConfig(); 264 265 // LookupOrCreate returns a CachedState for the given |server_id|. If no such 266 // CachedState currently exists, it will be created and cached. 267 CachedState* LookupOrCreate(const QuicServerId& server_id); 268 269 // Delete CachedState objects whose server ids match |filter| from 270 // cached_states. 271 void ClearCachedStates(const ServerIdFilter& filter); 272 273 // FillInchoateClientHello sets |out| to be a CHLO message that elicits a 274 // source-address token or SCFG from a server. If |cached| is non-nullptr, the 275 // source-address token will be taken from it. |out_params| is used in order 276 // to store the cached certs that were sent as hints to the server in 277 // |out_params->cached_certs|. |preferred_version| is the version of the 278 // QUIC protocol that this client chose to use initially. This allows the 279 // server to detect downgrade attacks. If |demand_x509_proof| is true, 280 // then |out| will include an X509 proof demand, and the associated 281 // certificate related fields. 282 void FillInchoateClientHello( 283 const QuicServerId& server_id, 284 const ParsedQuicVersion preferred_version, 285 const CachedState* cached, 286 QuicRandom* rand, 287 bool demand_x509_proof, 288 QuicReferenceCountedPointer<QuicCryptoNegotiatedParameters> out_params, 289 CryptoHandshakeMessage* out) const; 290 291 // FillClientHello sets |out| to be a CHLO message based on the configuration 292 // of this object. This object must have cached enough information about 293 // the server's hostname in order to perform a handshake. This can be checked 294 // with the |IsComplete| member of |CachedState|. 295 // 296 // |now| and |rand| are used to generate the nonce and |out_params| is 297 // filled with the results of the handshake that the server is expected to 298 // accept. |preferred_version| is the version of the QUIC protocol that this 299 // client chose to use initially. This allows the server to detect downgrade 300 // attacks. 301 // 302 // If |channel_id_key| is not null, it is used to sign a secret value derived 303 // from the client and server's keys, and the Channel ID public key and the 304 // signature are placed in the CETV value of the CHLO. 305 QuicErrorCode FillClientHello( 306 const QuicServerId& server_id, 307 QuicConnectionId connection_id, 308 const ParsedQuicVersion preferred_version, 309 const ParsedQuicVersion actual_version, 310 const CachedState* cached, 311 QuicWallTime now, 312 QuicRandom* rand, 313 QuicReferenceCountedPointer<QuicCryptoNegotiatedParameters> out_params, 314 CryptoHandshakeMessage* out, 315 std::string* error_details) const; 316 317 // ProcessRejection processes a REJ message from a server and updates the 318 // cached information about that server. After this, |IsComplete| may return 319 // true for that server's CachedState. If the rejection message contains state 320 // about a future handshake (i.e. an nonce value from the server), then it 321 // will be saved in |out_params|. |now| is used to judge whether the server 322 // config in the rejection message has expired. 323 QuicErrorCode ProcessRejection( 324 const CryptoHandshakeMessage& rej, 325 QuicWallTime now, 326 QuicTransportVersion version, 327 quiche::QuicheStringPiece chlo_hash, 328 CachedState* cached, 329 QuicReferenceCountedPointer<QuicCryptoNegotiatedParameters> out_params, 330 std::string* error_details); 331 332 // ProcessServerHello processes the message in |server_hello|, updates the 333 // cached information about that server, writes the negotiated parameters to 334 // |out_params| and returns QUIC_NO_ERROR. If |server_hello| is unacceptable 335 // then it puts an error message in |error_details| and returns an error 336 // code. |version| is the QUIC version for the current connection. 337 // |negotiated_versions| contains the list of version, if any, that were 338 // present in a version negotiation packet previously received from the 339 // server. The contents of this list will be compared against the list of 340 // versions provided in the VER tag of the server hello. 341 QuicErrorCode ProcessServerHello( 342 const CryptoHandshakeMessage& server_hello, 343 QuicConnectionId connection_id, 344 ParsedQuicVersion version, 345 const ParsedQuicVersionVector& negotiated_versions, 346 CachedState* cached, 347 QuicReferenceCountedPointer<QuicCryptoNegotiatedParameters> out_params, 348 std::string* error_details); 349 350 // Processes the message in |server_update|, updating the cached source 351 // address token, and server config. 352 // If |server_update| is invalid then |error_details| will contain an error 353 // message, and an error code will be returned. If all has gone well 354 // QUIC_NO_ERROR is returned. 355 QuicErrorCode ProcessServerConfigUpdate( 356 const CryptoHandshakeMessage& server_update, 357 QuicWallTime now, 358 const QuicTransportVersion version, 359 quiche::QuicheStringPiece chlo_hash, 360 CachedState* cached, 361 QuicReferenceCountedPointer<QuicCryptoNegotiatedParameters> out_params, 362 std::string* error_details); 363 364 ProofVerifier* proof_verifier() const; 365 SessionCache* session_cache() const; 366 ProofSource* proof_source() const; 367 void set_proof_source(std::unique_ptr<ProofSource> proof_source); 368 SSL_CTX* ssl_ctx() const; 369 370 // Initialize the CachedState from |canonical_crypto_config| for the 371 // |canonical_server_id| as the initial CachedState for |server_id|. We will 372 // copy config data only if |canonical_crypto_config| has valid proof. 373 void InitializeFrom(const QuicServerId& server_id, 374 const QuicServerId& canonical_server_id, 375 QuicCryptoClientConfig* canonical_crypto_config); 376 377 // Adds |suffix| as a domain suffix for which the server's crypto config 378 // is expected to be shared among servers with the domain suffix. If a server 379 // matches this suffix, then the server config from another server with the 380 // suffix will be used to initialize the cached state for this server. 381 void AddCanonicalSuffix(const std::string& suffix); 382 383 // Saves the |user_agent_id| that will be passed in QUIC's CHLO message. set_user_agent_id(const std::string & user_agent_id)384 void set_user_agent_id(const std::string& user_agent_id) { 385 user_agent_id_ = user_agent_id; 386 } 387 388 // Returns the user_agent_id that will be provided in the client hello 389 // handshake message. user_agent_id()390 const std::string& user_agent_id() const { return user_agent_id_; } 391 392 // Saves the |alpn| that will be passed in QUIC's CHLO message. set_alpn(const std::string & alpn)393 void set_alpn(const std::string& alpn) { alpn_ = alpn; } 394 set_pre_shared_key(quiche::QuicheStringPiece psk)395 void set_pre_shared_key(quiche::QuicheStringPiece psk) { 396 pre_shared_key_ = std::string(psk); 397 } 398 pad_inchoate_hello()399 bool pad_inchoate_hello() const { return pad_inchoate_hello_; } set_pad_inchoate_hello(bool new_value)400 void set_pad_inchoate_hello(bool new_value) { 401 pad_inchoate_hello_ = new_value; 402 } 403 pad_full_hello()404 bool pad_full_hello() const { return pad_full_hello_; } set_pad_full_hello(bool new_value)405 void set_pad_full_hello(bool new_value) { pad_full_hello_ = new_value; } 406 407 private: 408 // Sets the members to reasonable, default values. 409 void SetDefaults(); 410 411 // CacheNewServerConfig checks for SCFG, STK, PROF, and CRT tags in |message|, 412 // verifies them, and stores them in the cached state if they validate. 413 // This is used on receipt of a REJ from a server, or when a server sends 414 // updated server config during a connection. 415 QuicErrorCode CacheNewServerConfig( 416 const CryptoHandshakeMessage& message, 417 QuicWallTime now, 418 QuicTransportVersion version, 419 quiche::QuicheStringPiece chlo_hash, 420 const std::vector<std::string>& cached_certs, 421 CachedState* cached, 422 std::string* error_details); 423 424 // If the suffix of the hostname in |server_id| is in |canonical_suffixes_|, 425 // then populate |cached| with the canonical cached state from 426 // |canonical_server_map_| for that suffix. Returns true if |cached| is 427 // initialized with canonical cached state. 428 bool PopulateFromCanonicalConfig(const QuicServerId& server_id, 429 CachedState* cached); 430 431 // cached_states_ maps from the server_id to the cached information about 432 // that server. 433 std::map<QuicServerId, std::unique_ptr<CachedState>> cached_states_; 434 435 // Contains a map of servers which could share the same server config. Map 436 // from a canonical host suffix/port/scheme to a representative server with 437 // the canonical suffix, which has a plausible set of initial certificates 438 // (or at least server public key). 439 std::map<QuicServerId, QuicServerId> canonical_server_map_; 440 441 // Contains list of suffixes (for exmaple ".c.youtube.com", 442 // ".googlevideo.com") of canonical hostnames. 443 std::vector<std::string> canonical_suffixes_; 444 445 std::unique_ptr<ProofVerifier> proof_verifier_; 446 std::unique_ptr<SessionCache> session_cache_; 447 std::unique_ptr<ProofSource> proof_source_; 448 bssl::UniquePtr<SSL_CTX> ssl_ctx_; 449 450 // The |user_agent_id_| passed in QUIC's CHLO message. 451 std::string user_agent_id_; 452 453 // The |alpn_| passed in QUIC's CHLO message. 454 std::string alpn_; 455 456 // If non-empty, the client will operate in the pre-shared key mode by 457 // incorporating |pre_shared_key_| into the key schedule. 458 std::string pre_shared_key_; 459 460 // In QUIC, technically, client hello should be fully padded. 461 // However, fully padding on slow network connection (e.g. 50kbps) can add 462 // 150ms latency to one roundtrip. Therefore, you can disable padding of 463 // individual messages. It is recommend to leave at least one message in 464 // each direction fully padded (e.g. full CHLO and SHLO), but if you know 465 // the lower-bound MTU, you don't need to pad all of them (keep in mind that 466 // it's not OK to do it according to the standard). 467 // 468 // Also, if you disable padding, you must disable (change) the 469 // anti-amplification protection. You should only do so if you have some 470 // other means of verifying the client. 471 bool pad_inchoate_hello_ = true; 472 bool pad_full_hello_ = true; 473 }; 474 475 } // namespace quic 476 477 #endif // QUICHE_QUIC_CORE_CRYPTO_QUIC_CRYPTO_CLIENT_CONFIG_H_ 478