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