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