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 NET_QUIC_CRYPTO_QUIC_CRYPTO_CLIENT_CONFIG_H_
6#define NET_QUIC_CRYPTO_QUIC_CRYPTO_CLIENT_CONFIG_H_
7
8#include <map>
9#include <string>
10#include <vector>
11
12#include "base/memory/scoped_ptr.h"
13#include "base/strings/string_piece.h"
14#include "net/base/net_export.h"
15#include "net/quic/crypto/crypto_handshake.h"
16#include "net/quic/quic_protocol.h"
17#include "net/quic/quic_server_id.h"
18
19namespace net {
20
21class ChannelIDKey;
22class ChannelIDSource;
23class CryptoHandshakeMessage;
24class ProofVerifier;
25class ProofVerifyDetails;
26class QuicRandom;
27
28// QuicCryptoClientConfig contains crypto-related configuration settings for a
29// client. Note that this object isn't thread-safe. It's designed to be used on
30// a single thread at a time.
31class NET_EXPORT_PRIVATE QuicCryptoClientConfig : public QuicCryptoConfig {
32 public:
33  // A CachedState contains the information that the client needs in order to
34  // perform a 0-RTT handshake with a server. This information can be reused
35  // over several connections to the same server.
36  class NET_EXPORT_PRIVATE CachedState {
37   public:
38    CachedState();
39    ~CachedState();
40
41    // IsComplete returns true if this object contains enough information to
42    // perform a handshake with the server. |now| is used to judge whether any
43    // cached server config has expired.
44    bool IsComplete(QuicWallTime now) const;
45
46    // IsEmpty returns true if |server_config_| is empty.
47    bool IsEmpty() const;
48
49    // GetServerConfig returns the parsed contents of |server_config|, or NULL
50    // if |server_config| is empty. The return value is owned by this object
51    // and is destroyed when this object is.
52    const CryptoHandshakeMessage* GetServerConfig() const;
53
54    // SetServerConfig checks that |server_config| parses correctly and stores
55    // it in |server_config_|. |now| is used to judge whether |server_config|
56    // has expired.
57    QuicErrorCode SetServerConfig(base::StringPiece server_config,
58                                  QuicWallTime now,
59                                  std::string* error_details);
60
61    // InvalidateServerConfig clears the cached server config (if any).
62    void InvalidateServerConfig();
63
64    // SetProof stores a certificate chain and signature.
65    void SetProof(const std::vector<std::string>& certs,
66                  base::StringPiece signature);
67
68    // Clears all the data.
69    void Clear();
70
71    // Clears the certificate chain and signature and invalidates the proof.
72    void ClearProof();
73
74    // SetProofValid records that the certificate chain and signature have been
75    // validated and that it's safe to assume that the server is legitimate.
76    // (Note: this does not check the chain or signature.)
77    void SetProofValid();
78
79    // If the server config or the proof has changed then it needs to be
80    // revalidated. Helper function to keep server_config_valid_ and
81    // generation_counter_ in sync.
82    void SetProofInvalid();
83
84    const std::string& server_config() const;
85    const std::string& source_address_token() const;
86    const std::vector<std::string>& certs() const;
87    const std::string& signature() const;
88    bool proof_valid() const;
89    uint64 generation_counter() const;
90    const ProofVerifyDetails* proof_verify_details() const;
91
92    void set_source_address_token(base::StringPiece token);
93
94    // SetProofVerifyDetails takes ownership of |details|.
95    void SetProofVerifyDetails(ProofVerifyDetails* details);
96
97    // Copy the |server_config_|, |source_address_token_|, |certs_| and
98    // |server_config_sig_| from the |other|.  The remaining fields,
99    // |generation_counter_|, |proof_verify_details_|, and |scfg_| remain
100    // unchanged.
101    void InitializeFrom(const CachedState& other);
102
103    // Initializes this cached state based on the arguments provided.
104    // Returns false if there is a problem parsing the server config.
105    bool Initialize(base::StringPiece server_config,
106                    base::StringPiece source_address_token,
107                    const std::vector<std::string>& certs,
108                    base::StringPiece signature,
109                    QuicWallTime now);
110
111   private:
112    std::string server_config_;         // A serialized handshake message.
113    std::string source_address_token_;  // An opaque proof of IP ownership.
114    std::vector<std::string> certs_;    // A list of certificates in leaf-first
115                                        // order.
116    std::string server_config_sig_;     // A signature of |server_config_|.
117    bool server_config_valid_;          // True if |server_config_| is correctly
118                                        // signed and |certs_| has been
119                                        // validated.
120    // Generation counter associated with the |server_config_|, |certs_| and
121    // |server_config_sig_| combination. It is incremented whenever we set
122    // server_config_valid_ to false.
123    uint64 generation_counter_;
124
125    scoped_ptr<ProofVerifyDetails> proof_verify_details_;
126
127    // scfg contains the cached, parsed value of |server_config|.
128    mutable scoped_ptr<CryptoHandshakeMessage> scfg_;
129
130    DISALLOW_COPY_AND_ASSIGN(CachedState);
131  };
132
133  QuicCryptoClientConfig();
134  ~QuicCryptoClientConfig();
135
136  // Sets the members to reasonable, default values.
137  void SetDefaults();
138
139  // LookupOrCreate returns a CachedState for the given |server_id|. If no such
140  // CachedState currently exists, it will be created and cached.
141  CachedState* LookupOrCreate(const QuicServerId& server_id);
142
143  // Delete all CachedState objects from cached_states_.
144  void ClearCachedStates();
145
146  // FillInchoateClientHello sets |out| to be a CHLO message that elicits a
147  // source-address token or SCFG from a server. If |cached| is non-NULL, the
148  // source-address token will be taken from it. |out_params| is used in order
149  // to store the cached certs that were sent as hints to the server in
150  // |out_params->cached_certs|. |preferred_version| is the version of the
151  // QUIC protocol that this client chose to use initially. This allows the
152  // server to detect downgrade attacks.
153  void FillInchoateClientHello(const QuicServerId& server_id,
154                               const QuicVersion preferred_version,
155                               const CachedState* cached,
156                               QuicCryptoNegotiatedParameters* out_params,
157                               CryptoHandshakeMessage* out) const;
158
159  // FillClientHello sets |out| to be a CHLO message based on the configuration
160  // of this object. This object must have cached enough information about
161  // the server's hostname in order to perform a handshake. This can be checked
162  // with the |IsComplete| member of |CachedState|.
163  //
164  // |now| and |rand| are used to generate the nonce and |out_params| is
165  // filled with the results of the handshake that the server is expected to
166  // accept. |preferred_version| is the version of the QUIC protocol that this
167  // client chose to use initially. This allows the server to detect downgrade
168  // attacks.
169  //
170  // If |channel_id_key| is not null, it is used to sign a secret value derived
171  // from the client and server's keys, and the Channel ID public key and the
172  // signature are placed in the CETV value of the CHLO.
173  QuicErrorCode FillClientHello(const QuicServerId& server_id,
174                                QuicConnectionId connection_id,
175                                const QuicVersion preferred_version,
176                                const CachedState* cached,
177                                QuicWallTime now,
178                                QuicRandom* rand,
179                                const ChannelIDKey* channel_id_key,
180                                QuicCryptoNegotiatedParameters* out_params,
181                                CryptoHandshakeMessage* out,
182                                std::string* error_details) const;
183
184  // ProcessRejection processes a REJ message from a server and updates the
185  // cached information about that server. After this, |IsComplete| may return
186  // true for that server's CachedState. If the rejection message contains
187  // state about a future handshake (i.e. an nonce value from the server), then
188  // it will be saved in |out_params|. |now| is used to judge whether the
189  // server config in the rejection message has expired. |is_https| is used to
190  // track reject reason for secure vs insecure QUIC.
191  QuicErrorCode ProcessRejection(const CryptoHandshakeMessage& rej,
192                                 QuicWallTime now,
193                                 CachedState* cached,
194                                 bool is_https,
195                                 QuicCryptoNegotiatedParameters* out_params,
196                                 std::string* error_details);
197
198  // ProcessServerHello processes the message in |server_hello|, updates the
199  // cached information about that server, writes the negotiated parameters to
200  // |out_params| and returns QUIC_NO_ERROR. If |server_hello| is unacceptable
201  // then it puts an error message in |error_details| and returns an error
202  // code. |negotiated_versions| contains the list of version, if any, that were
203  // present in a version negotiation packet previously recevied from the
204  // server. The contents of this list will be compared against the list of
205  // versions provided in the VER tag of the server hello.
206  QuicErrorCode ProcessServerHello(const CryptoHandshakeMessage& server_hello,
207                                   QuicConnectionId connection_id,
208                                   const QuicVersionVector& negotiated_versions,
209                                   CachedState* cached,
210                                   QuicCryptoNegotiatedParameters* out_params,
211                                   std::string* error_details);
212
213  // Processes the message in |server_update|, updating the cached source
214  // address token, and server config.
215  // If |server_update| is invalid then |error_details| will contain an error
216  // message, and an error code will be returned. If all has gone well
217  // QUIC_NO_ERROR is returned.
218  QuicErrorCode ProcessServerConfigUpdate(
219      const CryptoHandshakeMessage& server_update,
220      QuicWallTime now,
221      CachedState* cached,
222      QuicCryptoNegotiatedParameters* out_params,
223      std::string* error_details);
224
225  ProofVerifier* proof_verifier() const;
226
227  // SetProofVerifier takes ownership of a |ProofVerifier| that clients are
228  // free to use in order to verify certificate chains from servers. If a
229  // ProofVerifier is set then the client will request a certificate chain from
230  // the server.
231  void SetProofVerifier(ProofVerifier* verifier);
232
233  ChannelIDSource* channel_id_source() const;
234
235  // SetChannelIDSource sets a ChannelIDSource that will be called, when the
236  // server supports channel IDs, to obtain a channel ID for signing a message
237  // proving possession of the channel ID. This object takes ownership of
238  // |source|.
239  void SetChannelIDSource(ChannelIDSource* source);
240
241  // Initialize the CachedState from |canonical_crypto_config| for the
242  // |canonical_server_id| as the initial CachedState for |server_id|. We will
243  // copy config data only if |canonical_crypto_config| has valid proof.
244  void InitializeFrom(const QuicServerId& server_id,
245                      const QuicServerId& canonical_server_id,
246                      QuicCryptoClientConfig* canonical_crypto_config);
247
248  // Adds |suffix| as a domain suffix for which the server's crypto config
249  // is expected to be shared among servers with the domain suffix. If a server
250  // matches this suffix, then the server config from another server with the
251  // suffix will be used to initialize the cached state for this server.
252  void AddCanonicalSuffix(const std::string& suffix);
253
254  // Prefers AES-GCM (kAESG) over other AEAD algorithms. Call this method if
255  // the CPU has hardware acceleration for AES-GCM. This method can only be
256  // called after SetDefaults().
257  void PreferAesGcm();
258
259  // Disables the use of ECDSA for proof verification.
260  // Call this method on platforms that do not support ECDSA.
261  // TODO(rch): remove this method when we drop support for Windows XP.
262  void DisableEcdsa();
263
264  // Saves the |user_agent_id| that will be passed in QUIC's CHLO message.
265  void set_user_agent_id(const std::string& user_agent_id) {
266    user_agent_id_ = user_agent_id;
267  }
268
269 private:
270  typedef std::map<QuicServerId, CachedState*> CachedStateMap;
271
272  // CacheNewServerConfig checks for SCFG, STK, PROF, and CRT tags in |message|,
273  // verifies them, and stores them in the cached state if they validate.
274  // This is used on receipt of a REJ from a server, or when a server sends
275  // updated server config during a connection.
276  QuicErrorCode CacheNewServerConfig(
277      const CryptoHandshakeMessage& message,
278      QuicWallTime now,
279      const std::vector<std::string>& cached_certs,
280      CachedState* cached,
281      std::string* error_details);
282
283  // If the suffix of the hostname in |server_id| is in |canoncial_suffixes_|,
284  // then populate |cached| with the canonical cached state from
285  // |canonical_server_map_| for that suffix.
286  void PopulateFromCanonicalConfig(const QuicServerId& server_id,
287                                   CachedState* cached);
288
289  // cached_states_ maps from the server_id to the cached information about
290  // that server.
291  CachedStateMap cached_states_;
292
293  // Contains a map of servers which could share the same server config. Map
294  // from a canonical host suffix/port/scheme to a representative server with
295  // the canonical suffix, which has a plausible set of initial certificates
296  // (or at least server public key).
297  std::map<QuicServerId, QuicServerId> canonical_server_map_;
298
299  // Contains list of suffixes (for exmaple ".c.youtube.com",
300  // ".googlevideo.com") of canoncial hostnames.
301  std::vector<std::string> canoncial_suffixes_;
302
303  scoped_ptr<ProofVerifier> proof_verifier_;
304  scoped_ptr<ChannelIDSource> channel_id_source_;
305
306  // True if ECDSA should be disabled.
307  bool disable_ecdsa_;
308
309  // The |user_agent_id_| passed in QUIC's CHLO message.
310  std::string user_agent_id_;
311
312  DISALLOW_COPY_AND_ASSIGN(QuicCryptoClientConfig);
313};
314
315}  // namespace net
316
317#endif  // NET_QUIC_CRYPTO_QUIC_CRYPTO_CLIENT_CONFIG_H_
318