crypto_handshake.h revision eb525c5499e34cc9c4b825d6d9e75bb07cc06ace
1// Copyright (c) 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_CRYPTO_HANDSHAKE_H_ 6#define NET_QUIC_CRYPTO_CRYPTO_HANDSHAKE_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_protocol.h" 16#include "net/quic/quic_protocol.h" 17 18namespace net { 19 20class ChannelIDSigner; 21class CommonCertSets; 22class KeyExchange; 23class ProofVerifier; 24class QuicDecrypter; 25class QuicEncrypter; 26class QuicRandom; 27 28// An intermediate format of a handshake message that's convenient for a 29// CryptoFramer to serialize from or parse into. 30class NET_EXPORT_PRIVATE CryptoHandshakeMessage { 31 public: 32 CryptoHandshakeMessage(); 33 CryptoHandshakeMessage(const CryptoHandshakeMessage& other); 34 ~CryptoHandshakeMessage(); 35 36 CryptoHandshakeMessage& operator=(const CryptoHandshakeMessage& other); 37 38 // Clears state. 39 void Clear(); 40 41 // GetSerialized returns the serialized form of this message and caches the 42 // result. Subsequently altering the message does not invalidate the cache. 43 const QuicData& GetSerialized() const; 44 45 // MarkDirty invalidates the cache created by |GetSerialized|. 46 void MarkDirty(); 47 48 // SetValue sets an element with the given tag to the raw, memory contents of 49 // |v|. 50 template<class T> void SetValue(QuicTag tag, const T& v) { 51 tag_value_map_[tag] = 52 std::string(reinterpret_cast<const char*>(&v), sizeof(v)); 53 } 54 55 // SetVector sets an element with the given tag to the raw contents of an 56 // array of elements in |v|. 57 template<class T> void SetVector(QuicTag tag, const std::vector<T>& v) { 58 if (v.empty()) { 59 tag_value_map_[tag] = std::string(); 60 } else { 61 tag_value_map_[tag] = std::string(reinterpret_cast<const char*>(&v[0]), 62 v.size() * sizeof(T)); 63 } 64 } 65 66 // Returns the message tag. 67 QuicTag tag() const { return tag_; } 68 // Sets the message tag. 69 void set_tag(QuicTag tag) { tag_ = tag; } 70 71 const QuicTagValueMap& tag_value_map() const { return tag_value_map_; } 72 73 void Insert(QuicTagValueMap::const_iterator begin, 74 QuicTagValueMap::const_iterator end); 75 76 // SetTaglist sets an element with the given tag to contain a list of tags, 77 // passed as varargs. The argument list must be terminated with a 0 element. 78 void SetTaglist(QuicTag tag, ...); 79 80 void SetStringPiece(QuicTag tag, base::StringPiece value); 81 82 // Erase removes a tag/value, if present, from the message. 83 void Erase(QuicTag tag); 84 85 // GetTaglist finds an element with the given tag containing zero or more 86 // tags. If such a tag doesn't exist, it returns false. Otherwise it sets 87 // |out_tags| and |out_len| to point to the array of tags and returns true. 88 // The array points into the CryptoHandshakeMessage and is valid only for as 89 // long as the CryptoHandshakeMessage exists and is not modified. 90 QuicErrorCode GetTaglist(QuicTag tag, const QuicTag** out_tags, 91 size_t* out_len) const; 92 93 bool GetStringPiece(QuicTag tag, base::StringPiece* out) const; 94 95 // GetNthValue24 interprets the value with the given tag to be a series of 96 // 24-bit, length prefixed values and it returns the subvalue with the given 97 // index. 98 QuicErrorCode GetNthValue24(QuicTag tag, 99 unsigned index, 100 base::StringPiece* out) const; 101 QuicErrorCode GetUint16(QuicTag tag, uint16* out) const; 102 QuicErrorCode GetUint32(QuicTag tag, uint32* out) const; 103 QuicErrorCode GetUint64(QuicTag tag, uint64* out) const; 104 105 // size returns 4 (message tag) + 2 (uint16, number of entries) + 106 // (4 (tag) + 4 (end offset))*tag_value_map_.size() + ∑ value sizes. 107 size_t size() const; 108 109 // set_minimum_size sets the minimum number of bytes that the message should 110 // consume. The CryptoFramer will add a PAD tag as needed when serializing in 111 // order to ensure this. Setting a value of 0 disables padding. 112 // 113 // Padding is useful in order to ensure that messages are a minimum size. A 114 // QUIC server can require a minimum size in order to reduce the 115 // amplification factor of any mirror DoS attack. 116 void set_minimum_size(size_t min_bytes); 117 118 size_t minimum_size() const; 119 120 // DebugString returns a multi-line, string representation of the message 121 // suitable for including in debug output. 122 std::string DebugString() const; 123 124 private: 125 // GetPOD is a utility function for extracting a plain-old-data value. If 126 // |tag| exists in the message, and has a value of exactly |len| bytes then 127 // it copies |len| bytes of data into |out|. Otherwise |len| bytes at |out| 128 // are zeroed out. 129 // 130 // If used to copy integers then this assumes that the machine is 131 // little-endian. 132 QuicErrorCode GetPOD(QuicTag tag, void* out, size_t len) const; 133 134 std::string DebugStringInternal(size_t indent) const; 135 136 QuicTag tag_; 137 QuicTagValueMap tag_value_map_; 138 139 size_t minimum_size_; 140 141 // The serialized form of the handshake message. This member is constructed 142 // lasily. 143 mutable scoped_ptr<QuicData> serialized_; 144}; 145 146// A CrypterPair contains the encrypter and decrypter for an encryption level. 147struct NET_EXPORT_PRIVATE CrypterPair { 148 CrypterPair(); 149 ~CrypterPair(); 150 scoped_ptr<QuicEncrypter> encrypter; 151 scoped_ptr<QuicDecrypter> decrypter; 152}; 153 154// Parameters negotiated by the crypto handshake. 155struct NET_EXPORT_PRIVATE QuicCryptoNegotiatedParameters { 156 // Initializes the members to 0 or empty values. 157 QuicCryptoNegotiatedParameters(); 158 ~QuicCryptoNegotiatedParameters(); 159 160 uint16 version; 161 QuicTag key_exchange; 162 QuicTag aead; 163 std::string initial_premaster_secret; 164 std::string forward_secure_premaster_secret; 165 CrypterPair initial_crypters; 166 CrypterPair forward_secure_crypters; 167 // Normalized SNI: converted to lower case and trailing '.' removed. 168 std::string sni; 169 std::string client_nonce; 170 std::string server_nonce; 171 // hkdf_input_suffix contains the HKDF input following the label: the GUID, 172 // client hello and server config. This is only populated in the client 173 // because only the client needs to derive the forward secure keys at a later 174 // time from the initial keys. 175 std::string hkdf_input_suffix; 176 // cached_certs contains the cached certificates that a client used when 177 // sending a client hello. 178 std::vector<std::string> cached_certs; 179 // client_key_exchange is used by clients to store the ephemeral KeyExchange 180 // for the connection. 181 scoped_ptr<KeyExchange> client_key_exchange; 182 // channel_id is set by servers to a ChannelID key when the client correctly 183 // proves possession of the corresponding private key. It consists of 32 184 // bytes of x coordinate, followed by 32 bytes of y coordinate. Both values 185 // are big-endian and the pair is a P-256 public key. 186 std::string channel_id; 187}; 188 189// QuicCryptoConfig contains common configuration between clients and servers. 190class NET_EXPORT_PRIVATE QuicCryptoConfig { 191 public: 192 enum { 193 // CONFIG_VERSION is the one (and, for the moment, only) version number that 194 // we implement. 195 CONFIG_VERSION = 0, 196 }; 197 198 // kInitialLabel is a constant that is used when deriving the initial 199 // (non-forward secure) keys for the connection in order to tie the resulting 200 // key to this protocol. 201 static const char kInitialLabel[]; 202 203 // kCETVLabel is a constant that is used when deriving the keys for the 204 // encrypted tag/value block in the client hello. 205 static const char kCETVLabel[]; 206 207 // kForwardSecureLabel is a constant that is used when deriving the forward 208 // secure keys for the connection in order to tie the resulting key to this 209 // protocol. 210 static const char kForwardSecureLabel[]; 211 212 QuicCryptoConfig(); 213 ~QuicCryptoConfig(); 214 215 // Protocol version 216 uint16 version; 217 // Key exchange methods. The following two members' values correspond by 218 // index. 219 QuicTagVector kexs; 220 // Authenticated encryption with associated data (AEAD) algorithms. 221 QuicTagVector aead; 222 223 const CommonCertSets* common_cert_sets; 224 225 private: 226 DISALLOW_COPY_AND_ASSIGN(QuicCryptoConfig); 227}; 228 229// QuicCryptoClientConfig contains crypto-related configuration settings for a 230// client. Note that this object isn't thread-safe. It's designed to be used on 231// a single thread at a time. 232class NET_EXPORT_PRIVATE QuicCryptoClientConfig : public QuicCryptoConfig { 233 public: 234 // A CachedState contains the information that the client needs in order to 235 // perform a 0-RTT handshake with a server. This information can be reused 236 // over several connections to the same server. 237 class CachedState { 238 public: 239 CachedState(); 240 ~CachedState(); 241 242 // IsComplete returns true if this object contains enough information to 243 // perform a handshake with the server. |now| is used to judge whether any 244 // cached server config has expired. 245 bool IsComplete(QuicWallTime now) const; 246 247 // GetServerConfig returns the parsed contents of |server_config|, or NULL 248 // if |server_config| is empty. The return value is owned by this object 249 // and is destroyed when this object is. 250 const CryptoHandshakeMessage* GetServerConfig() const; 251 252 // SetServerConfig checks that |server_config| parses correctly and stores 253 // it in |server_config_|. |now| is used to judge whether |server_config| 254 // has expired. 255 QuicErrorCode SetServerConfig(base::StringPiece server_config, 256 QuicWallTime now, 257 std::string* error_details); 258 259 // InvalidateServerConfig clears the cached server config (if any). 260 void InvalidateServerConfig(); 261 262 // SetProof stores a certificate chain and signature. 263 void SetProof(const std::vector<std::string>& certs, 264 base::StringPiece signature); 265 266 // SetProofValid records that the certificate chain and signature have been 267 // validated and that it's safe to assume that the server is legitimate. 268 // (Note: this does not check the chain or signature.) 269 void SetProofValid(); 270 271 const std::string& server_config() const; 272 const std::string& source_address_token() const; 273 const std::vector<std::string>& certs() const; 274 const std::string& signature() const; 275 bool proof_valid() const; 276 uint64 generation_counter() const; 277 278 void set_source_address_token(base::StringPiece token); 279 280 private: 281 std::string server_config_id_; // An opaque id from the server. 282 std::string server_config_; // A serialized handshake message. 283 std::string source_address_token_; // An opaque proof of IP ownership. 284 std::vector<std::string> certs_; // A list of certificates in leaf-first 285 // order. 286 std::string server_config_sig_; // A signature of |server_config_|. 287 bool server_config_valid_; // True if |server_config_| is correctly 288 // signed and |certs_| has been 289 // validated. 290 uint64 generation_counter_; // Generation counter associated with 291 // the |server_config_|, |certs_| and 292 // |server_config_sig_| combination. 293 294 // scfg contains the cached, parsed value of |server_config|. 295 mutable scoped_ptr<CryptoHandshakeMessage> scfg_; 296 }; 297 298 QuicCryptoClientConfig(); 299 ~QuicCryptoClientConfig(); 300 301 // Sets the members to reasonable, default values. 302 void SetDefaults(); 303 304 // LookupOrCreate returns a CachedState for the given hostname. If no such 305 // CachedState currently exists, it will be created and cached. 306 CachedState* LookupOrCreate(const std::string& server_hostname); 307 308 // FillInchoateClientHello sets |out| to be a CHLO message that elicits a 309 // source-address token or SCFG from a server. If |cached| is non-NULL, the 310 // source-address token will be taken from it. |out_params| is used in order 311 // to store the cached certs that were sent as hints to the server in 312 // |out_params->cached_certs|. 313 void FillInchoateClientHello(const std::string& server_hostname, 314 const CachedState* cached, 315 QuicCryptoNegotiatedParameters* out_params, 316 CryptoHandshakeMessage* out) const; 317 318 // FillClientHello sets |out| to be a CHLO message based on the configuration 319 // of this object. This object must have cached enough information about 320 // |server_hostname| in order to perform a handshake. This can be checked 321 // with the |IsComplete| member of |CachedState|. 322 // 323 // |clock| and |rand| are used to generate the nonce and |out_params| is 324 // filled with the results of the handshake that the server is expected to 325 // accept. 326 QuicErrorCode FillClientHello(const std::string& server_hostname, 327 QuicGuid guid, 328 const CachedState* cached, 329 QuicWallTime now, 330 QuicRandom* rand, 331 QuicCryptoNegotiatedParameters* out_params, 332 CryptoHandshakeMessage* out, 333 std::string* error_details) const; 334 335 // ProcessRejection processes a REJ message from a server and updates the 336 // cached information about that server. After this, |IsComplete| may return 337 // true for that server's CachedState. If the rejection message contains 338 // state about a future handshake (i.e. an nonce value from the server), then 339 // it will be saved in |out_params|. |now| is used to judge whether the 340 // server config in the rejection message has expired. 341 QuicErrorCode ProcessRejection(CachedState* cached, 342 const CryptoHandshakeMessage& rej, 343 QuicWallTime now, 344 QuicCryptoNegotiatedParameters* out_params, 345 std::string* error_details); 346 347 // ProcessServerHello processes the message in |server_hello|, writes the 348 // negotiated parameters to |out_params| and returns QUIC_NO_ERROR. If 349 // |server_hello| is unacceptable then it puts an error message in 350 // |error_details| and returns an error code. 351 QuicErrorCode ProcessServerHello(const CryptoHandshakeMessage& server_hello, 352 QuicGuid guid, 353 QuicCryptoNegotiatedParameters* out_params, 354 std::string* error_details); 355 356 ProofVerifier* proof_verifier() const; 357 358 // SetProofVerifier takes ownership of a |ProofVerifier| that clients are 359 // free to use in order to verify certificate chains from servers. If a 360 // ProofVerifier is set then the client will request a certificate chain from 361 // the server. 362 void SetProofVerifier(ProofVerifier* verifier); 363 364 ChannelIDSigner* channel_id_signer() const; 365 366 // SetChannelIDSigner sets a ChannelIDSigner that will be called when the 367 // server supports channel IDs to sign a message proving possession of the 368 // given ChannelID. This object takes ownership of |signer|. 369 void SetChannelIDSigner(ChannelIDSigner* signer); 370 371 private: 372 // cached_states_ maps from the server hostname to the cached information 373 // about that server. 374 std::map<std::string, CachedState*> cached_states_; 375 376 scoped_ptr<ProofVerifier> proof_verifier_; 377 scoped_ptr<ChannelIDSigner> channel_id_signer_; 378 379 DISALLOW_COPY_AND_ASSIGN(QuicCryptoClientConfig); 380}; 381 382} // namespace net 383 384#endif // NET_QUIC_CRYPTO_CRYPTO_HANDSHAKE_H_ 385