Pin Chrome's shortcut to the Win10 Start menu on install and OS upgrade.
[chromium-blink-merge.git] / net / quic / test_tools / crypto_test_utils.cc
blob811da803f1a59c3e60021afc2c6155436fa2a242
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_framer_peer.h"
21 #include "net/quic/test_tools/quic_test_utils.h"
22 #include "net/quic/test_tools/simple_quic_framer.h"
24 using base::StringPiece;
25 using std::make_pair;
26 using std::pair;
27 using std::string;
28 using std::vector;
30 namespace net {
31 namespace test {
33 namespace {
35 const char kServerHostname[] = "test.example.com";
36 const uint16 kServerPort = 80;
38 // CryptoFramerVisitor is a framer visitor that records handshake messages.
39 class CryptoFramerVisitor : public CryptoFramerVisitorInterface {
40 public:
41 CryptoFramerVisitor()
42 : error_(false) {
45 void OnError(CryptoFramer* framer) override { error_ = true; }
47 void OnHandshakeMessage(const CryptoHandshakeMessage& message) override {
48 messages_.push_back(message);
51 bool error() const {
52 return error_;
55 const vector<CryptoHandshakeMessage>& messages() const {
56 return messages_;
59 private:
60 bool error_;
61 vector<CryptoHandshakeMessage> messages_;
64 // MovePackets parses crypto handshake messages from packet number
65 // |*inout_packet_index| through to the last packet (or until a packet fails to
66 // decrypt) and has |dest_stream| process them. |*inout_packet_index| is updated
67 // with an index one greater than the last packet processed.
68 void MovePackets(PacketSavingConnection* source_conn,
69 size_t *inout_packet_index,
70 QuicCryptoStream* dest_stream,
71 PacketSavingConnection* dest_conn) {
72 SimpleQuicFramer framer(source_conn->supported_versions());
73 CryptoFramer crypto_framer;
74 CryptoFramerVisitor crypto_visitor;
76 // In order to properly test the code we need to perform encryption and
77 // decryption so that the crypters latch when expected. The crypters are in
78 // |dest_conn|, but we don't want to try and use them there. Instead we swap
79 // them into |framer|, perform the decryption with them, and then swap them
80 // back.
81 QuicConnectionPeer::SwapCrypters(dest_conn, framer.framer());
83 crypto_framer.set_visitor(&crypto_visitor);
85 size_t index = *inout_packet_index;
86 for (; index < source_conn->encrypted_packets_.size(); index++) {
87 if (!framer.ProcessPacket(*source_conn->encrypted_packets_[index])) {
88 // The framer will be unable to decrypt forward-secure packets sent after
89 // the handshake is complete. Don't treat them as handshake packets.
90 break;
93 for (const QuicStreamFrame& stream_frame : framer.stream_frames()) {
94 ASSERT_TRUE(crypto_framer.ProcessInput(stream_frame.data));
95 ASSERT_FALSE(crypto_visitor.error());
98 *inout_packet_index = index;
100 QuicConnectionPeer::SwapCrypters(dest_conn, framer.framer());
102 ASSERT_EQ(0u, crypto_framer.InputBytesRemaining());
104 for (const CryptoHandshakeMessage& message : crypto_visitor.messages()) {
105 dest_stream->OnHandshakeMessage(message);
109 // HexChar parses |c| as a hex character. If valid, it sets |*value| to the
110 // value of the hex character and returns true. Otherwise it returns false.
111 bool HexChar(char c, uint8* value) {
112 if (c >= '0' && c <= '9') {
113 *value = c - '0';
114 return true;
116 if (c >= 'a' && c <= 'f') {
117 *value = c - 'a' + 10;
118 return true;
120 if (c >= 'A' && c <= 'F') {
121 *value = c - 'A' + 10;
122 return true;
124 return false;
127 // A ChannelIDSource that works in asynchronous mode unless the |callback|
128 // argument to GetChannelIDKey is nullptr.
129 class AsyncTestChannelIDSource : public ChannelIDSource,
130 public CryptoTestUtils::CallbackSource {
131 public:
132 // Takes ownership of |sync_source|, a synchronous ChannelIDSource.
133 explicit AsyncTestChannelIDSource(ChannelIDSource* sync_source)
134 : sync_source_(sync_source) {}
135 ~AsyncTestChannelIDSource() override {}
137 // ChannelIDSource implementation.
138 QuicAsyncStatus GetChannelIDKey(const string& hostname,
139 scoped_ptr<ChannelIDKey>* channel_id_key,
140 ChannelIDSourceCallback* callback) override {
141 // Synchronous mode.
142 if (!callback) {
143 return sync_source_->GetChannelIDKey(hostname, channel_id_key, nullptr);
146 // Asynchronous mode.
147 QuicAsyncStatus status =
148 sync_source_->GetChannelIDKey(hostname, &channel_id_key_, nullptr);
149 if (status != QUIC_SUCCESS) {
150 return QUIC_FAILURE;
152 callback_.reset(callback);
153 return QUIC_PENDING;
156 // CallbackSource implementation.
157 void RunPendingCallbacks() override {
158 if (callback_.get()) {
159 callback_->Run(&channel_id_key_);
160 callback_.reset();
164 private:
165 scoped_ptr<ChannelIDSource> sync_source_;
166 scoped_ptr<ChannelIDSourceCallback> callback_;
167 scoped_ptr<ChannelIDKey> channel_id_key_;
170 } // anonymous namespace
172 CryptoTestUtils::FakeClientOptions::FakeClientOptions()
173 : dont_verify_certs(false),
174 channel_id_enabled(false),
175 channel_id_source_async(false) {
178 // static
179 int CryptoTestUtils::HandshakeWithFakeServer(
180 PacketSavingConnection* client_conn,
181 QuicCryptoClientStream* client) {
182 PacketSavingConnection* server_conn = new PacketSavingConnection(
183 Perspective::IS_SERVER, client_conn->supported_versions());
185 QuicConfig config = DefaultQuicConfig();
186 QuicCryptoServerConfig crypto_config(QuicCryptoServerConfig::TESTING,
187 QuicRandom::GetInstance());
188 SetupCryptoServerConfigForTest(server_conn->clock(),
189 server_conn->random_generator(), &config,
190 &crypto_config);
192 TestQuicSpdyServerSession server_session(server_conn, config, &crypto_config);
194 // The client's handshake must have been started already.
195 CHECK_NE(0u, client_conn->encrypted_packets_.size());
197 CommunicateHandshakeMessages(client_conn, client, server_conn,
198 server_session.GetCryptoStream());
200 CompareClientAndServerKeys(client, server_session.GetCryptoStream());
202 return client->num_sent_client_hellos();
205 // static
206 int CryptoTestUtils::HandshakeWithFakeClient(
207 PacketSavingConnection* server_conn,
208 QuicCryptoServerStream* server,
209 const FakeClientOptions& options) {
210 PacketSavingConnection* client_conn =
211 new PacketSavingConnection(Perspective::IS_CLIENT);
212 // Advance the time, because timers do not like uninitialized times.
213 client_conn->AdvanceTime(QuicTime::Delta::FromSeconds(1));
215 QuicCryptoClientConfig crypto_config;
216 bool is_https = false;
217 AsyncTestChannelIDSource* async_channel_id_source = nullptr;
218 if (options.channel_id_enabled) {
219 is_https = true;
221 ChannelIDSource* source = ChannelIDSourceForTesting();
222 if (options.channel_id_source_async) {
223 async_channel_id_source = new AsyncTestChannelIDSource(source);
224 source = async_channel_id_source;
226 crypto_config.SetChannelIDSource(source);
228 QuicServerId server_id(kServerHostname, kServerPort, is_https,
229 PRIVACY_MODE_DISABLED);
230 if (!options.dont_verify_certs) {
231 // TODO(wtc): replace this with ProofVerifierForTesting() when we have
232 // a working ProofSourceForTesting().
233 crypto_config.SetProofVerifier(FakeProofVerifierForTesting());
235 TestQuicSpdyClientSession client_session(client_conn, DefaultQuicConfig(),
236 server_id, &crypto_config);
238 client_session.GetCryptoStream()->CryptoConnect();
239 CHECK_EQ(1u, client_conn->encrypted_packets_.size());
241 CommunicateHandshakeMessagesAndRunCallbacks(
242 client_conn, client_session.GetCryptoStream(), server_conn, server,
243 async_channel_id_source);
245 CompareClientAndServerKeys(client_session.GetCryptoStream(), server);
247 if (options.channel_id_enabled) {
248 scoped_ptr<ChannelIDKey> channel_id_key;
249 QuicAsyncStatus status = crypto_config.channel_id_source()->GetChannelIDKey(
250 kServerHostname, &channel_id_key, nullptr);
251 EXPECT_EQ(QUIC_SUCCESS, status);
252 EXPECT_EQ(channel_id_key->SerializeKey(),
253 server->crypto_negotiated_params().channel_id);
254 EXPECT_EQ(
255 options.channel_id_source_async,
256 client_session.GetCryptoStream()->WasChannelIDSourceCallbackRun());
259 return client_session.GetCryptoStream()->num_sent_client_hellos();
262 // static
263 void CryptoTestUtils::SetupCryptoServerConfigForTest(
264 const QuicClock* clock,
265 QuicRandom* rand,
266 QuicConfig* config,
267 QuicCryptoServerConfig* crypto_config) {
268 QuicCryptoServerConfig::ConfigOptions options;
269 options.channel_id_enabled = true;
270 scoped_ptr<CryptoHandshakeMessage> scfg(
271 crypto_config->AddDefaultConfig(rand, clock, options));
274 // static
275 void CryptoTestUtils::CommunicateHandshakeMessages(
276 PacketSavingConnection* a_conn,
277 QuicCryptoStream* a,
278 PacketSavingConnection* b_conn,
279 QuicCryptoStream* b) {
280 CommunicateHandshakeMessagesAndRunCallbacks(a_conn, a, b_conn, b, nullptr);
283 // static
284 void CryptoTestUtils::CommunicateHandshakeMessagesAndRunCallbacks(
285 PacketSavingConnection* a_conn,
286 QuicCryptoStream* a,
287 PacketSavingConnection* b_conn,
288 QuicCryptoStream* b,
289 CallbackSource* callback_source) {
290 size_t a_i = 0, b_i = 0;
291 while (!a->handshake_confirmed()) {
292 ASSERT_GT(a_conn->encrypted_packets_.size(), a_i);
293 VLOG(1) << "Processing " << a_conn->encrypted_packets_.size() - a_i
294 << " packets a->b";
295 MovePackets(a_conn, &a_i, b, b_conn);
296 if (callback_source) {
297 callback_source->RunPendingCallbacks();
300 ASSERT_GT(b_conn->encrypted_packets_.size(), b_i);
301 VLOG(1) << "Processing " << b_conn->encrypted_packets_.size() - b_i
302 << " packets b->a";
303 MovePackets(b_conn, &b_i, a, a_conn);
304 if (callback_source) {
305 callback_source->RunPendingCallbacks();
310 // static
311 pair<size_t, size_t> CryptoTestUtils::AdvanceHandshake(
312 PacketSavingConnection* a_conn,
313 QuicCryptoStream* a,
314 size_t a_i,
315 PacketSavingConnection* b_conn,
316 QuicCryptoStream* b,
317 size_t b_i) {
318 VLOG(1) << "Processing " << a_conn->encrypted_packets_.size() - a_i
319 << " packets a->b";
320 MovePackets(a_conn, &a_i, b, b_conn);
322 VLOG(1) << "Processing " << b_conn->encrypted_packets_.size() - b_i
323 << " packets b->a";
324 if (b_conn->encrypted_packets_.size() - b_i == 2) {
325 VLOG(1) << "here";
327 MovePackets(b_conn, &b_i, a, a_conn);
329 return std::make_pair(a_i, b_i);
332 // static
333 string CryptoTestUtils::GetValueForTag(const CryptoHandshakeMessage& message,
334 QuicTag tag) {
335 QuicTagValueMap::const_iterator it = message.tag_value_map().find(tag);
336 if (it == message.tag_value_map().end()) {
337 return string();
339 return it->second;
342 class MockCommonCertSets : public CommonCertSets {
343 public:
344 MockCommonCertSets(StringPiece cert, uint64 hash, uint32 index)
345 : cert_(cert.as_string()),
346 hash_(hash),
347 index_(index) {
350 StringPiece GetCommonHashes() const override {
351 CHECK(false) << "not implemented";
352 return StringPiece();
355 StringPiece GetCert(uint64 hash, uint32 index) const override {
356 if (hash == hash_ && index == index_) {
357 return cert_;
359 return StringPiece();
362 bool MatchCert(StringPiece cert,
363 StringPiece common_set_hashes,
364 uint64* out_hash,
365 uint32* out_index) const override {
366 if (cert != cert_) {
367 return false;
370 if (common_set_hashes.size() % sizeof(uint64) != 0) {
371 return false;
373 bool client_has_set = false;
374 for (size_t i = 0; i < common_set_hashes.size(); i += sizeof(uint64)) {
375 uint64 hash;
376 memcpy(&hash, common_set_hashes.data() + i, sizeof(hash));
377 if (hash == hash_) {
378 client_has_set = true;
379 break;
383 if (!client_has_set) {
384 return false;
387 *out_hash = hash_;
388 *out_index = index_;
389 return true;
392 private:
393 const string cert_;
394 const uint64 hash_;
395 const uint32 index_;
398 CommonCertSets* CryptoTestUtils::MockCommonCertSets(StringPiece cert,
399 uint64 hash,
400 uint32 index) {
401 return new class MockCommonCertSets(cert, hash, index);
404 void CryptoTestUtils::CompareClientAndServerKeys(
405 QuicCryptoClientStream* client,
406 QuicCryptoServerStream* server) {
407 QuicFramer* client_framer =
408 QuicConnectionPeer::GetFramer(client->session()->connection());
409 QuicFramer* server_framer =
410 QuicConnectionPeer::GetFramer(server->session()->connection());
411 const QuicEncrypter* client_encrypter(
412 QuicFramerPeer::GetEncrypter(client_framer, ENCRYPTION_INITIAL));
413 const QuicDecrypter* client_decrypter(
414 client->session()->connection()->decrypter());
415 const QuicEncrypter* client_forward_secure_encrypter(
416 QuicFramerPeer::GetEncrypter(client_framer, ENCRYPTION_FORWARD_SECURE));
417 const QuicDecrypter* client_forward_secure_decrypter(
418 client->session()->connection()->alternative_decrypter());
419 const QuicEncrypter* server_encrypter(
420 QuicFramerPeer::GetEncrypter(server_framer, ENCRYPTION_INITIAL));
421 const QuicDecrypter* server_decrypter(
422 server->session()->connection()->decrypter());
423 const QuicEncrypter* server_forward_secure_encrypter(
424 QuicFramerPeer::GetEncrypter(server_framer, ENCRYPTION_FORWARD_SECURE));
425 const QuicDecrypter* server_forward_secure_decrypter(
426 server->session()->connection()->alternative_decrypter());
428 StringPiece client_encrypter_key = client_encrypter->GetKey();
429 StringPiece client_encrypter_iv = client_encrypter->GetNoncePrefix();
430 StringPiece client_decrypter_key = client_decrypter->GetKey();
431 StringPiece client_decrypter_iv = client_decrypter->GetNoncePrefix();
432 StringPiece client_forward_secure_encrypter_key =
433 client_forward_secure_encrypter->GetKey();
434 StringPiece client_forward_secure_encrypter_iv =
435 client_forward_secure_encrypter->GetNoncePrefix();
436 StringPiece client_forward_secure_decrypter_key =
437 client_forward_secure_decrypter->GetKey();
438 StringPiece client_forward_secure_decrypter_iv =
439 client_forward_secure_decrypter->GetNoncePrefix();
440 StringPiece server_encrypter_key = server_encrypter->GetKey();
441 StringPiece server_encrypter_iv = server_encrypter->GetNoncePrefix();
442 StringPiece server_decrypter_key = server_decrypter->GetKey();
443 StringPiece server_decrypter_iv = server_decrypter->GetNoncePrefix();
444 StringPiece server_forward_secure_encrypter_key =
445 server_forward_secure_encrypter->GetKey();
446 StringPiece server_forward_secure_encrypter_iv =
447 server_forward_secure_encrypter->GetNoncePrefix();
448 StringPiece server_forward_secure_decrypter_key =
449 server_forward_secure_decrypter->GetKey();
450 StringPiece server_forward_secure_decrypter_iv =
451 server_forward_secure_decrypter->GetNoncePrefix();
453 StringPiece client_subkey_secret =
454 client->crypto_negotiated_params().subkey_secret;
455 StringPiece server_subkey_secret =
456 server->crypto_negotiated_params().subkey_secret;
459 const char kSampleLabel[] = "label";
460 const char kSampleContext[] = "context";
461 const size_t kSampleOutputLength = 32;
462 string client_key_extraction;
463 string server_key_extraction;
464 EXPECT_TRUE(client->ExportKeyingMaterial(kSampleLabel,
465 kSampleContext,
466 kSampleOutputLength,
467 &client_key_extraction));
468 EXPECT_TRUE(server->ExportKeyingMaterial(kSampleLabel,
469 kSampleContext,
470 kSampleOutputLength,
471 &server_key_extraction));
473 CompareCharArraysWithHexError("client write key",
474 client_encrypter_key.data(),
475 client_encrypter_key.length(),
476 server_decrypter_key.data(),
477 server_decrypter_key.length());
478 CompareCharArraysWithHexError("client write IV",
479 client_encrypter_iv.data(),
480 client_encrypter_iv.length(),
481 server_decrypter_iv.data(),
482 server_decrypter_iv.length());
483 CompareCharArraysWithHexError("server write key",
484 server_encrypter_key.data(),
485 server_encrypter_key.length(),
486 client_decrypter_key.data(),
487 client_decrypter_key.length());
488 CompareCharArraysWithHexError("server write IV",
489 server_encrypter_iv.data(),
490 server_encrypter_iv.length(),
491 client_decrypter_iv.data(),
492 client_decrypter_iv.length());
493 CompareCharArraysWithHexError("client forward secure write key",
494 client_forward_secure_encrypter_key.data(),
495 client_forward_secure_encrypter_key.length(),
496 server_forward_secure_decrypter_key.data(),
497 server_forward_secure_decrypter_key.length());
498 CompareCharArraysWithHexError("client forward secure write IV",
499 client_forward_secure_encrypter_iv.data(),
500 client_forward_secure_encrypter_iv.length(),
501 server_forward_secure_decrypter_iv.data(),
502 server_forward_secure_decrypter_iv.length());
503 CompareCharArraysWithHexError("server forward secure write key",
504 server_forward_secure_encrypter_key.data(),
505 server_forward_secure_encrypter_key.length(),
506 client_forward_secure_decrypter_key.data(),
507 client_forward_secure_decrypter_key.length());
508 CompareCharArraysWithHexError("server forward secure write IV",
509 server_forward_secure_encrypter_iv.data(),
510 server_forward_secure_encrypter_iv.length(),
511 client_forward_secure_decrypter_iv.data(),
512 client_forward_secure_decrypter_iv.length());
513 CompareCharArraysWithHexError("subkey secret",
514 client_subkey_secret.data(),
515 client_subkey_secret.length(),
516 server_subkey_secret.data(),
517 server_subkey_secret.length());
518 CompareCharArraysWithHexError("sample key extraction",
519 client_key_extraction.data(),
520 client_key_extraction.length(),
521 server_key_extraction.data(),
522 server_key_extraction.length());
525 // static
526 QuicTag CryptoTestUtils::ParseTag(const char* tagstr) {
527 const size_t len = strlen(tagstr);
528 CHECK_NE(0u, len);
530 QuicTag tag = 0;
532 if (tagstr[0] == '#') {
533 CHECK_EQ(static_cast<size_t>(1 + 2*4), len);
534 tagstr++;
536 for (size_t i = 0; i < 8; i++) {
537 tag <<= 4;
539 uint8 v = 0;
540 CHECK(HexChar(tagstr[i], &v));
541 tag |= v;
544 return tag;
547 CHECK_LE(len, 4u);
548 for (size_t i = 0; i < 4; i++) {
549 tag >>= 8;
550 if (i < len) {
551 tag |= static_cast<uint32>(tagstr[i]) << 24;
555 return tag;
558 // static
559 CryptoHandshakeMessage CryptoTestUtils::Message(const char* message_tag, ...) {
560 va_list ap;
561 va_start(ap, message_tag);
563 CryptoHandshakeMessage message = BuildMessage(message_tag, ap);
564 va_end(ap);
565 return message;
568 // static
569 CryptoHandshakeMessage CryptoTestUtils::BuildMessage(const char* message_tag,
570 va_list ap) {
571 CryptoHandshakeMessage msg;
572 msg.set_tag(ParseTag(message_tag));
574 for (;;) {
575 const char* tagstr = va_arg(ap, const char*);
576 if (tagstr == nullptr) {
577 break;
580 if (tagstr[0] == '$') {
581 // Special value.
582 const char* const special = tagstr + 1;
583 if (strcmp(special, "padding") == 0) {
584 const int min_bytes = va_arg(ap, int);
585 msg.set_minimum_size(min_bytes);
586 } else {
587 CHECK(false) << "Unknown special value: " << special;
590 continue;
593 const QuicTag tag = ParseTag(tagstr);
594 const char* valuestr = va_arg(ap, const char*);
596 size_t len = strlen(valuestr);
597 if (len > 0 && valuestr[0] == '#') {
598 valuestr++;
599 len--;
601 CHECK_EQ(0u, len % 2);
602 scoped_ptr<uint8[]> buf(new uint8[len/2]);
604 for (size_t i = 0; i < len/2; i++) {
605 uint8 v = 0;
606 CHECK(HexChar(valuestr[i*2], &v));
607 buf[i] = v << 4;
608 CHECK(HexChar(valuestr[i*2 + 1], &v));
609 buf[i] |= v;
612 msg.SetStringPiece(
613 tag, StringPiece(reinterpret_cast<char*>(buf.get()), len/2));
614 continue;
617 msg.SetStringPiece(tag, valuestr);
620 // The CryptoHandshakeMessage needs to be serialized and parsed to ensure
621 // that any padding is included.
622 scoped_ptr<QuicData> bytes(CryptoFramer::ConstructHandshakeMessage(msg));
623 scoped_ptr<CryptoHandshakeMessage> parsed(
624 CryptoFramer::ParseMessage(bytes->AsStringPiece()));
625 CHECK(parsed.get());
627 return *parsed;
630 } // namespace test
631 } // namespace net