[Cronet] Delay StartNetLog and StopNetLog until native request context is initialized
[chromium-blink-merge.git] / net / quic / test_tools / crypto_test_utils.cc
blob29e86de24d352cd2dc9fc0f99b2d8ff7180adec1
1 // Copyright (c) 2012 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.
5 #include "net/quic/test_tools/crypto_test_utils.h"
7 #include "net/quic/crypto/channel_id.h"
8 #include "net/quic/crypto/common_cert_set.h"
9 #include "net/quic/crypto/crypto_handshake.h"
10 #include "net/quic/crypto/quic_crypto_server_config.h"
11 #include "net/quic/crypto/quic_decrypter.h"
12 #include "net/quic/crypto/quic_encrypter.h"
13 #include "net/quic/crypto/quic_random.h"
14 #include "net/quic/quic_clock.h"
15 #include "net/quic/quic_crypto_client_stream.h"
16 #include "net/quic/quic_crypto_server_stream.h"
17 #include "net/quic/quic_crypto_stream.h"
18 #include "net/quic/quic_server_id.h"
19 #include "net/quic/test_tools/quic_connection_peer.h"
20 #include "net/quic/test_tools/quic_test_utils.h"
21 #include "net/quic/test_tools/simple_quic_framer.h"
23 using base::StringPiece;
24 using std::make_pair;
25 using std::pair;
26 using std::string;
27 using std::vector;
29 namespace net {
30 namespace test {
32 namespace {
34 const char kServerHostname[] = "test.example.com";
35 const uint16 kServerPort = 80;
37 // CryptoFramerVisitor is a framer visitor that records handshake messages.
38 class CryptoFramerVisitor : public CryptoFramerVisitorInterface {
39 public:
40 CryptoFramerVisitor()
41 : error_(false) {
44 void OnError(CryptoFramer* framer) override { error_ = true; }
46 void OnHandshakeMessage(const CryptoHandshakeMessage& message) override {
47 messages_.push_back(message);
50 bool error() const {
51 return error_;
54 const vector<CryptoHandshakeMessage>& messages() const {
55 return messages_;
58 private:
59 bool error_;
60 vector<CryptoHandshakeMessage> messages_;
63 // MovePackets parses crypto handshake messages from packet number
64 // |*inout_packet_index| through to the last packet (or until a packet fails to
65 // decrypt) and has |dest_stream| process them. |*inout_packet_index| is updated
66 // with an index one greater than the last packet processed.
67 void MovePackets(PacketSavingConnection* source_conn,
68 size_t *inout_packet_index,
69 QuicCryptoStream* dest_stream,
70 PacketSavingConnection* dest_conn) {
71 SimpleQuicFramer framer(source_conn->supported_versions());
72 CryptoFramer crypto_framer;
73 CryptoFramerVisitor crypto_visitor;
75 // In order to properly test the code we need to perform encryption and
76 // decryption so that the crypters latch when expected. The crypters are in
77 // |dest_conn|, but we don't want to try and use them there. Instead we swap
78 // them into |framer|, perform the decryption with them, and then swap them
79 // back.
80 QuicConnectionPeer::SwapCrypters(dest_conn, framer.framer());
82 crypto_framer.set_visitor(&crypto_visitor);
84 size_t index = *inout_packet_index;
85 for (; index < source_conn->encrypted_packets_.size(); index++) {
86 if (!framer.ProcessPacket(*source_conn->encrypted_packets_[index])) {
87 // The framer will be unable to decrypt forward-secure packets sent after
88 // the handshake is complete. Don't treat them as handshake packets.
89 break;
92 for (vector<QuicStreamFrame>::const_iterator
93 i = framer.stream_frames().begin();
94 i != framer.stream_frames().end(); ++i) {
95 scoped_ptr<string> frame_data(i->GetDataAsString());
96 ASSERT_TRUE(crypto_framer.ProcessInput(*frame_data));
97 ASSERT_FALSE(crypto_visitor.error());
100 *inout_packet_index = index;
102 QuicConnectionPeer::SwapCrypters(dest_conn, framer.framer());
104 ASSERT_EQ(0u, crypto_framer.InputBytesRemaining());
106 for (vector<CryptoHandshakeMessage>::const_iterator
107 i = crypto_visitor.messages().begin();
108 i != crypto_visitor.messages().end(); ++i) {
109 dest_stream->OnHandshakeMessage(*i);
113 // HexChar parses |c| as a hex character. If valid, it sets |*value| to the
114 // value of the hex character and returns true. Otherwise it returns false.
115 bool HexChar(char c, uint8* value) {
116 if (c >= '0' && c <= '9') {
117 *value = c - '0';
118 return true;
120 if (c >= 'a' && c <= 'f') {
121 *value = c - 'a' + 10;
122 return true;
124 if (c >= 'A' && c <= 'F') {
125 *value = c - 'A' + 10;
126 return true;
128 return false;
131 // A ChannelIDSource that works in asynchronous mode unless the |callback|
132 // argument to GetChannelIDKey is nullptr.
133 class AsyncTestChannelIDSource : public ChannelIDSource,
134 public CryptoTestUtils::CallbackSource {
135 public:
136 // Takes ownership of |sync_source|, a synchronous ChannelIDSource.
137 explicit AsyncTestChannelIDSource(ChannelIDSource* sync_source)
138 : sync_source_(sync_source) {}
139 ~AsyncTestChannelIDSource() override {}
141 // ChannelIDSource implementation.
142 QuicAsyncStatus GetChannelIDKey(const string& hostname,
143 scoped_ptr<ChannelIDKey>* channel_id_key,
144 ChannelIDSourceCallback* callback) override {
145 // Synchronous mode.
146 if (!callback) {
147 return sync_source_->GetChannelIDKey(hostname, channel_id_key, nullptr);
150 // Asynchronous mode.
151 QuicAsyncStatus status =
152 sync_source_->GetChannelIDKey(hostname, &channel_id_key_, nullptr);
153 if (status != QUIC_SUCCESS) {
154 return QUIC_FAILURE;
156 callback_.reset(callback);
157 return QUIC_PENDING;
160 // CallbackSource implementation.
161 void RunPendingCallbacks() override {
162 if (callback_.get()) {
163 callback_->Run(&channel_id_key_);
164 callback_.reset();
168 private:
169 scoped_ptr<ChannelIDSource> sync_source_;
170 scoped_ptr<ChannelIDSourceCallback> callback_;
171 scoped_ptr<ChannelIDKey> channel_id_key_;
174 } // anonymous namespace
176 CryptoTestUtils::FakeClientOptions::FakeClientOptions()
177 : dont_verify_certs(false),
178 channel_id_enabled(false),
179 channel_id_source_async(false) {
182 // static
183 int CryptoTestUtils::HandshakeWithFakeServer(
184 PacketSavingConnection* client_conn,
185 QuicCryptoClientStream* client) {
186 PacketSavingConnection* server_conn = new PacketSavingConnection(
187 Perspective::IS_SERVER, client_conn->supported_versions());
188 TestSession server_session(server_conn, DefaultQuicConfig());
189 server_session.InitializeSession();
190 QuicCryptoServerConfig crypto_config(QuicCryptoServerConfig::TESTING,
191 QuicRandom::GetInstance());
193 SetupCryptoServerConfigForTest(
194 server_session.connection()->clock(),
195 server_session.connection()->random_generator(),
196 server_session.config(), &crypto_config);
198 QuicCryptoServerStream server(&crypto_config, &server_session);
199 server_session.SetCryptoStream(&server);
201 // The client's handshake must have been started already.
202 CHECK_NE(0u, client_conn->encrypted_packets_.size());
204 CommunicateHandshakeMessages(client_conn, client, server_conn, &server);
206 CompareClientAndServerKeys(client, &server);
208 return client->num_sent_client_hellos();
211 // static
212 int CryptoTestUtils::HandshakeWithFakeClient(
213 PacketSavingConnection* server_conn,
214 QuicCryptoServerStream* server,
215 const FakeClientOptions& options) {
216 PacketSavingConnection* client_conn =
217 new PacketSavingConnection(Perspective::IS_CLIENT);
218 // Advance the time, because timers do not like uninitialized times.
219 client_conn->AdvanceTime(QuicTime::Delta::FromSeconds(1));
220 TestClientSession client_session(client_conn, DefaultQuicConfig());
221 QuicCryptoClientConfig crypto_config;
223 if (!options.dont_verify_certs) {
224 // TODO(wtc): replace this with ProofVerifierForTesting() when we have
225 // a working ProofSourceForTesting().
226 crypto_config.SetProofVerifier(FakeProofVerifierForTesting());
228 bool is_https = false;
229 AsyncTestChannelIDSource* async_channel_id_source = nullptr;
230 if (options.channel_id_enabled) {
231 is_https = true;
233 ChannelIDSource* source = ChannelIDSourceForTesting();
234 if (options.channel_id_source_async) {
235 async_channel_id_source = new AsyncTestChannelIDSource(source);
236 source = async_channel_id_source;
238 crypto_config.SetChannelIDSource(source);
240 QuicServerId server_id(kServerHostname, kServerPort, is_https,
241 PRIVACY_MODE_DISABLED);
242 QuicCryptoClientStream client(server_id, &client_session,
243 ProofVerifyContextForTesting(),
244 &crypto_config);
245 client_session.SetCryptoStream(&client);
247 client.CryptoConnect();
248 CHECK_EQ(1u, client_conn->encrypted_packets_.size());
250 CommunicateHandshakeMessagesAndRunCallbacks(
251 client_conn, &client, server_conn, server, async_channel_id_source);
253 CompareClientAndServerKeys(&client, server);
255 if (options.channel_id_enabled) {
256 scoped_ptr<ChannelIDKey> channel_id_key;
257 QuicAsyncStatus status = crypto_config.channel_id_source()->GetChannelIDKey(
258 kServerHostname, &channel_id_key, nullptr);
259 EXPECT_EQ(QUIC_SUCCESS, status);
260 EXPECT_EQ(channel_id_key->SerializeKey(),
261 server->crypto_negotiated_params().channel_id);
262 EXPECT_EQ(options.channel_id_source_async,
263 client.WasChannelIDSourceCallbackRun());
266 return client.num_sent_client_hellos();
269 // static
270 void CryptoTestUtils::SetupCryptoServerConfigForTest(
271 const QuicClock* clock,
272 QuicRandom* rand,
273 QuicConfig* config,
274 QuicCryptoServerConfig* crypto_config) {
275 QuicCryptoServerConfig::ConfigOptions options;
276 options.channel_id_enabled = true;
277 scoped_ptr<CryptoHandshakeMessage> scfg(
278 crypto_config->AddDefaultConfig(rand, clock, options));
281 // static
282 void CryptoTestUtils::CommunicateHandshakeMessages(
283 PacketSavingConnection* a_conn,
284 QuicCryptoStream* a,
285 PacketSavingConnection* b_conn,
286 QuicCryptoStream* b) {
287 CommunicateHandshakeMessagesAndRunCallbacks(a_conn, a, b_conn, b, nullptr);
290 // static
291 void CryptoTestUtils::CommunicateHandshakeMessagesAndRunCallbacks(
292 PacketSavingConnection* a_conn,
293 QuicCryptoStream* a,
294 PacketSavingConnection* b_conn,
295 QuicCryptoStream* b,
296 CallbackSource* callback_source) {
297 size_t a_i = 0, b_i = 0;
298 while (!a->handshake_confirmed()) {
299 ASSERT_GT(a_conn->encrypted_packets_.size(), a_i);
300 VLOG(1) << "Processing " << a_conn->encrypted_packets_.size() - a_i
301 << " packets a->b";
302 MovePackets(a_conn, &a_i, b, b_conn);
303 if (callback_source) {
304 callback_source->RunPendingCallbacks();
307 ASSERT_GT(b_conn->encrypted_packets_.size(), b_i);
308 VLOG(1) << "Processing " << b_conn->encrypted_packets_.size() - b_i
309 << " packets b->a";
310 MovePackets(b_conn, &b_i, a, a_conn);
311 if (callback_source) {
312 callback_source->RunPendingCallbacks();
317 // static
318 pair<size_t, size_t> CryptoTestUtils::AdvanceHandshake(
319 PacketSavingConnection* a_conn,
320 QuicCryptoStream* a,
321 size_t a_i,
322 PacketSavingConnection* b_conn,
323 QuicCryptoStream* b,
324 size_t b_i) {
325 VLOG(1) << "Processing " << a_conn->encrypted_packets_.size() - a_i
326 << " packets a->b";
327 MovePackets(a_conn, &a_i, b, b_conn);
329 VLOG(1) << "Processing " << b_conn->encrypted_packets_.size() - b_i
330 << " packets b->a";
331 if (b_conn->encrypted_packets_.size() - b_i == 2) {
332 VLOG(1) << "here";
334 MovePackets(b_conn, &b_i, a, a_conn);
336 return std::make_pair(a_i, b_i);
339 // static
340 string CryptoTestUtils::GetValueForTag(const CryptoHandshakeMessage& message,
341 QuicTag tag) {
342 QuicTagValueMap::const_iterator it = message.tag_value_map().find(tag);
343 if (it == message.tag_value_map().end()) {
344 return string();
346 return it->second;
349 class MockCommonCertSets : public CommonCertSets {
350 public:
351 MockCommonCertSets(StringPiece cert, uint64 hash, uint32 index)
352 : cert_(cert.as_string()),
353 hash_(hash),
354 index_(index) {
357 StringPiece GetCommonHashes() const override {
358 CHECK(false) << "not implemented";
359 return StringPiece();
362 StringPiece GetCert(uint64 hash, uint32 index) const override {
363 if (hash == hash_ && index == index_) {
364 return cert_;
366 return StringPiece();
369 bool MatchCert(StringPiece cert,
370 StringPiece common_set_hashes,
371 uint64* out_hash,
372 uint32* out_index) const override {
373 if (cert != cert_) {
374 return false;
377 if (common_set_hashes.size() % sizeof(uint64) != 0) {
378 return false;
380 bool client_has_set = false;
381 for (size_t i = 0; i < common_set_hashes.size(); i += sizeof(uint64)) {
382 uint64 hash;
383 memcpy(&hash, common_set_hashes.data() + i, sizeof(hash));
384 if (hash == hash_) {
385 client_has_set = true;
386 break;
390 if (!client_has_set) {
391 return false;
394 *out_hash = hash_;
395 *out_index = index_;
396 return true;
399 private:
400 const string cert_;
401 const uint64 hash_;
402 const uint32 index_;
405 CommonCertSets* CryptoTestUtils::MockCommonCertSets(StringPiece cert,
406 uint64 hash,
407 uint32 index) {
408 return new class MockCommonCertSets(cert, hash, index);
411 void CryptoTestUtils::CompareClientAndServerKeys(
412 QuicCryptoClientStream* client,
413 QuicCryptoServerStream* server) {
414 const QuicEncrypter* client_encrypter(
415 client->session()->connection()->encrypter(ENCRYPTION_INITIAL));
416 const QuicDecrypter* client_decrypter(
417 client->session()->connection()->decrypter());
418 const QuicEncrypter* client_forward_secure_encrypter(
419 client->session()->connection()->encrypter(ENCRYPTION_FORWARD_SECURE));
420 const QuicDecrypter* client_forward_secure_decrypter(
421 client->session()->connection()->alternative_decrypter());
422 const QuicEncrypter* server_encrypter(
423 server->session()->connection()->encrypter(ENCRYPTION_INITIAL));
424 const QuicDecrypter* server_decrypter(
425 server->session()->connection()->decrypter());
426 const QuicEncrypter* server_forward_secure_encrypter(
427 server->session()->connection()->encrypter(ENCRYPTION_FORWARD_SECURE));
428 const QuicDecrypter* server_forward_secure_decrypter(
429 server->session()->connection()->alternative_decrypter());
431 StringPiece client_encrypter_key = client_encrypter->GetKey();
432 StringPiece client_encrypter_iv = client_encrypter->GetNoncePrefix();
433 StringPiece client_decrypter_key = client_decrypter->GetKey();
434 StringPiece client_decrypter_iv = client_decrypter->GetNoncePrefix();
435 StringPiece client_forward_secure_encrypter_key =
436 client_forward_secure_encrypter->GetKey();
437 StringPiece client_forward_secure_encrypter_iv =
438 client_forward_secure_encrypter->GetNoncePrefix();
439 StringPiece client_forward_secure_decrypter_key =
440 client_forward_secure_decrypter->GetKey();
441 StringPiece client_forward_secure_decrypter_iv =
442 client_forward_secure_decrypter->GetNoncePrefix();
443 StringPiece server_encrypter_key = server_encrypter->GetKey();
444 StringPiece server_encrypter_iv = server_encrypter->GetNoncePrefix();
445 StringPiece server_decrypter_key = server_decrypter->GetKey();
446 StringPiece server_decrypter_iv = server_decrypter->GetNoncePrefix();
447 StringPiece server_forward_secure_encrypter_key =
448 server_forward_secure_encrypter->GetKey();
449 StringPiece server_forward_secure_encrypter_iv =
450 server_forward_secure_encrypter->GetNoncePrefix();
451 StringPiece server_forward_secure_decrypter_key =
452 server_forward_secure_decrypter->GetKey();
453 StringPiece server_forward_secure_decrypter_iv =
454 server_forward_secure_decrypter->GetNoncePrefix();
456 StringPiece client_subkey_secret =
457 client->crypto_negotiated_params().subkey_secret;
458 StringPiece server_subkey_secret =
459 server->crypto_negotiated_params().subkey_secret;
462 const char kSampleLabel[] = "label";
463 const char kSampleContext[] = "context";
464 const size_t kSampleOutputLength = 32;
465 string client_key_extraction;
466 string server_key_extraction;
467 EXPECT_TRUE(client->ExportKeyingMaterial(kSampleLabel,
468 kSampleContext,
469 kSampleOutputLength,
470 &client_key_extraction));
471 EXPECT_TRUE(server->ExportKeyingMaterial(kSampleLabel,
472 kSampleContext,
473 kSampleOutputLength,
474 &server_key_extraction));
476 CompareCharArraysWithHexError("client write key",
477 client_encrypter_key.data(),
478 client_encrypter_key.length(),
479 server_decrypter_key.data(),
480 server_decrypter_key.length());
481 CompareCharArraysWithHexError("client write IV",
482 client_encrypter_iv.data(),
483 client_encrypter_iv.length(),
484 server_decrypter_iv.data(),
485 server_decrypter_iv.length());
486 CompareCharArraysWithHexError("server write key",
487 server_encrypter_key.data(),
488 server_encrypter_key.length(),
489 client_decrypter_key.data(),
490 client_decrypter_key.length());
491 CompareCharArraysWithHexError("server write IV",
492 server_encrypter_iv.data(),
493 server_encrypter_iv.length(),
494 client_decrypter_iv.data(),
495 client_decrypter_iv.length());
496 CompareCharArraysWithHexError("client forward secure write key",
497 client_forward_secure_encrypter_key.data(),
498 client_forward_secure_encrypter_key.length(),
499 server_forward_secure_decrypter_key.data(),
500 server_forward_secure_decrypter_key.length());
501 CompareCharArraysWithHexError("client forward secure write IV",
502 client_forward_secure_encrypter_iv.data(),
503 client_forward_secure_encrypter_iv.length(),
504 server_forward_secure_decrypter_iv.data(),
505 server_forward_secure_decrypter_iv.length());
506 CompareCharArraysWithHexError("server forward secure write key",
507 server_forward_secure_encrypter_key.data(),
508 server_forward_secure_encrypter_key.length(),
509 client_forward_secure_decrypter_key.data(),
510 client_forward_secure_decrypter_key.length());
511 CompareCharArraysWithHexError("server forward secure write IV",
512 server_forward_secure_encrypter_iv.data(),
513 server_forward_secure_encrypter_iv.length(),
514 client_forward_secure_decrypter_iv.data(),
515 client_forward_secure_decrypter_iv.length());
516 CompareCharArraysWithHexError("subkey secret",
517 client_subkey_secret.data(),
518 client_subkey_secret.length(),
519 server_subkey_secret.data(),
520 server_subkey_secret.length());
521 CompareCharArraysWithHexError("sample key extraction",
522 client_key_extraction.data(),
523 client_key_extraction.length(),
524 server_key_extraction.data(),
525 server_key_extraction.length());
528 // static
529 QuicTag CryptoTestUtils::ParseTag(const char* tagstr) {
530 const size_t len = strlen(tagstr);
531 CHECK_NE(0u, len);
533 QuicTag tag = 0;
535 if (tagstr[0] == '#') {
536 CHECK_EQ(static_cast<size_t>(1 + 2*4), len);
537 tagstr++;
539 for (size_t i = 0; i < 8; i++) {
540 tag <<= 4;
542 uint8 v = 0;
543 CHECK(HexChar(tagstr[i], &v));
544 tag |= v;
547 return tag;
550 CHECK_LE(len, 4u);
551 for (size_t i = 0; i < 4; i++) {
552 tag >>= 8;
553 if (i < len) {
554 tag |= static_cast<uint32>(tagstr[i]) << 24;
558 return tag;
561 // static
562 CryptoHandshakeMessage CryptoTestUtils::Message(const char* message_tag, ...) {
563 va_list ap;
564 va_start(ap, message_tag);
566 CryptoHandshakeMessage message = BuildMessage(message_tag, ap);
567 va_end(ap);
568 return message;
571 // static
572 CryptoHandshakeMessage CryptoTestUtils::BuildMessage(const char* message_tag,
573 va_list ap) {
574 CryptoHandshakeMessage msg;
575 msg.set_tag(ParseTag(message_tag));
577 for (;;) {
578 const char* tagstr = va_arg(ap, const char*);
579 if (tagstr == nullptr) {
580 break;
583 if (tagstr[0] == '$') {
584 // Special value.
585 const char* const special = tagstr + 1;
586 if (strcmp(special, "padding") == 0) {
587 const int min_bytes = va_arg(ap, int);
588 msg.set_minimum_size(min_bytes);
589 } else {
590 CHECK(false) << "Unknown special value: " << special;
593 continue;
596 const QuicTag tag = ParseTag(tagstr);
597 const char* valuestr = va_arg(ap, const char*);
599 size_t len = strlen(valuestr);
600 if (len > 0 && valuestr[0] == '#') {
601 valuestr++;
602 len--;
604 CHECK_EQ(0u, len % 2);
605 scoped_ptr<uint8[]> buf(new uint8[len/2]);
607 for (size_t i = 0; i < len/2; i++) {
608 uint8 v = 0;
609 CHECK(HexChar(valuestr[i*2], &v));
610 buf[i] = v << 4;
611 CHECK(HexChar(valuestr[i*2 + 1], &v));
612 buf[i] |= v;
615 msg.SetStringPiece(
616 tag, StringPiece(reinterpret_cast<char*>(buf.get()), len/2));
617 continue;
620 msg.SetStringPiece(tag, valuestr);
623 // The CryptoHandshakeMessage needs to be serialized and parsed to ensure
624 // that any padding is included.
625 scoped_ptr<QuicData> bytes(CryptoFramer::ConstructHandshakeMessage(msg));
626 scoped_ptr<CryptoHandshakeMessage> parsed(
627 CryptoFramer::ParseMessage(bytes->AsStringPiece()));
628 CHECK(parsed.get());
630 return *parsed;
633 } // namespace test
634 } // namespace net