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
;
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
{
44 void OnError(CryptoFramer
* framer
) override
{ error_
= true; }
46 void OnHandshakeMessage(const CryptoHandshakeMessage
& message
) override
{
47 messages_
.push_back(message
);
54 const vector
<CryptoHandshakeMessage
>& messages() const {
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
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.
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') {
120 if (c
>= 'a' && c
<= 'f') {
121 *value
= c
- 'a' + 10;
124 if (c
>= 'A' && c
<= 'F') {
125 *value
= c
- 'A' + 10;
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
{
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
{
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
) {
156 callback_
.reset(callback
);
160 // CallbackSource implementation.
161 void RunPendingCallbacks() override
{
162 if (callback_
.get()) {
163 callback_
->Run(&channel_id_key_
);
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) {
183 int CryptoTestUtils::HandshakeWithFakeServer(
184 PacketSavingConnection
* client_conn
,
185 QuicCryptoClientStream
* client
) {
186 PacketSavingConnection
* server_conn
=
187 new PacketSavingConnection(true, 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
->packets_
.size());
204 CommunicateHandshakeMessages(client_conn
, client
, server_conn
, &server
);
206 CompareClientAndServerKeys(client
, &server
);
208 return client
->num_sent_client_hellos();
212 int CryptoTestUtils::HandshakeWithFakeClient(
213 PacketSavingConnection
* server_conn
,
214 QuicCryptoServerStream
* server
,
215 const FakeClientOptions
& options
) {
216 PacketSavingConnection
* client_conn
= new PacketSavingConnection(false);
217 TestClientSession
client_session(client_conn
, DefaultQuicConfig());
218 QuicCryptoClientConfig crypto_config
;
220 if (!options
.dont_verify_certs
) {
221 // TODO(wtc): replace this with ProofVerifierForTesting() when we have
222 // a working ProofSourceForTesting().
223 crypto_config
.SetProofVerifier(FakeProofVerifierForTesting());
225 bool is_https
= false;
226 AsyncTestChannelIDSource
* async_channel_id_source
= nullptr;
227 if (options
.channel_id_enabled
) {
230 ChannelIDSource
* source
= ChannelIDSourceForTesting();
231 if (options
.channel_id_source_async
) {
232 async_channel_id_source
= new AsyncTestChannelIDSource(source
);
233 source
= async_channel_id_source
;
235 crypto_config
.SetChannelIDSource(source
);
237 QuicServerId
server_id(kServerHostname
, kServerPort
, is_https
,
238 PRIVACY_MODE_DISABLED
);
239 QuicCryptoClientStream
client(server_id
, &client_session
,
240 ProofVerifyContextForTesting(),
242 client_session
.SetCryptoStream(&client
);
244 CHECK(client
.CryptoConnect());
245 CHECK_EQ(1u, client_conn
->packets_
.size());
247 CommunicateHandshakeMessagesAndRunCallbacks(
248 client_conn
, &client
, server_conn
, server
, async_channel_id_source
);
250 CompareClientAndServerKeys(&client
, server
);
252 if (options
.channel_id_enabled
) {
253 scoped_ptr
<ChannelIDKey
> channel_id_key
;
254 QuicAsyncStatus status
= crypto_config
.channel_id_source()->GetChannelIDKey(
255 kServerHostname
, &channel_id_key
, nullptr);
256 EXPECT_EQ(QUIC_SUCCESS
, status
);
257 EXPECT_EQ(channel_id_key
->SerializeKey(),
258 server
->crypto_negotiated_params().channel_id
);
259 EXPECT_EQ(options
.channel_id_source_async
,
260 client
.WasChannelIDSourceCallbackRun());
263 return client
.num_sent_client_hellos();
267 void CryptoTestUtils::SetupCryptoServerConfigForTest(
268 const QuicClock
* clock
,
271 QuicCryptoServerConfig
* crypto_config
) {
272 QuicCryptoServerConfig::ConfigOptions options
;
273 options
.channel_id_enabled
= true;
274 scoped_ptr
<CryptoHandshakeMessage
> scfg(
275 crypto_config
->AddDefaultConfig(rand
, clock
, options
));
279 void CryptoTestUtils::CommunicateHandshakeMessages(
280 PacketSavingConnection
* a_conn
,
282 PacketSavingConnection
* b_conn
,
283 QuicCryptoStream
* b
) {
284 CommunicateHandshakeMessagesAndRunCallbacks(a_conn
, a
, b_conn
, b
, nullptr);
288 void CryptoTestUtils::CommunicateHandshakeMessagesAndRunCallbacks(
289 PacketSavingConnection
* a_conn
,
291 PacketSavingConnection
* b_conn
,
293 CallbackSource
* callback_source
) {
294 size_t a_i
= 0, b_i
= 0;
295 while (!a
->handshake_confirmed()) {
296 ASSERT_GT(a_conn
->packets_
.size(), a_i
);
297 LOG(INFO
) << "Processing " << a_conn
->packets_
.size() - a_i
299 MovePackets(a_conn
, &a_i
, b
, b_conn
);
300 if (callback_source
) {
301 callback_source
->RunPendingCallbacks();
304 ASSERT_GT(b_conn
->packets_
.size(), b_i
);
305 LOG(INFO
) << "Processing " << b_conn
->packets_
.size() - b_i
307 MovePackets(b_conn
, &b_i
, a
, a_conn
);
308 if (callback_source
) {
309 callback_source
->RunPendingCallbacks();
315 pair
<size_t, size_t> CryptoTestUtils::AdvanceHandshake(
316 PacketSavingConnection
* a_conn
,
319 PacketSavingConnection
* b_conn
,
322 LOG(INFO
) << "Processing " << a_conn
->packets_
.size() - a_i
324 MovePackets(a_conn
, &a_i
, b
, b_conn
);
326 LOG(INFO
) << "Processing " << b_conn
->packets_
.size() - b_i
328 if (b_conn
->packets_
.size() - b_i
== 2) {
331 MovePackets(b_conn
, &b_i
, a
, a_conn
);
333 return make_pair(a_i
, b_i
);
337 string
CryptoTestUtils::GetValueForTag(const CryptoHandshakeMessage
& message
,
339 QuicTagValueMap::const_iterator it
= message
.tag_value_map().find(tag
);
340 if (it
== message
.tag_value_map().end()) {
346 class MockCommonCertSets
: public CommonCertSets
{
348 MockCommonCertSets(StringPiece cert
, uint64 hash
, uint32 index
)
349 : cert_(cert
.as_string()),
354 StringPiece
GetCommonHashes() const override
{
355 CHECK(false) << "not implemented";
356 return StringPiece();
359 StringPiece
GetCert(uint64 hash
, uint32 index
) const override
{
360 if (hash
== hash_
&& index
== index_
) {
363 return StringPiece();
366 bool MatchCert(StringPiece cert
,
367 StringPiece common_set_hashes
,
369 uint32
* out_index
) const override
{
374 if (common_set_hashes
.size() % sizeof(uint64
) != 0) {
377 bool client_has_set
= false;
378 for (size_t i
= 0; i
< common_set_hashes
.size(); i
+= sizeof(uint64
)) {
380 memcpy(&hash
, common_set_hashes
.data() + i
, sizeof(hash
));
382 client_has_set
= true;
387 if (!client_has_set
) {
402 CommonCertSets
* CryptoTestUtils::MockCommonCertSets(StringPiece cert
,
405 return new class MockCommonCertSets(cert
, hash
, index
);
408 void CryptoTestUtils::CompareClientAndServerKeys(
409 QuicCryptoClientStream
* client
,
410 QuicCryptoServerStream
* server
) {
411 const QuicEncrypter
* client_encrypter(
412 client
->session()->connection()->encrypter(ENCRYPTION_INITIAL
));
413 const QuicDecrypter
* client_decrypter(
414 client
->session()->connection()->decrypter());
415 const QuicEncrypter
* client_forward_secure_encrypter(
416 client
->session()->connection()->encrypter(ENCRYPTION_FORWARD_SECURE
));
417 const QuicDecrypter
* client_forward_secure_decrypter(
418 client
->session()->connection()->alternative_decrypter());
419 const QuicEncrypter
* server_encrypter(
420 server
->session()->connection()->encrypter(ENCRYPTION_INITIAL
));
421 const QuicDecrypter
* server_decrypter(
422 server
->session()->connection()->decrypter());
423 const QuicEncrypter
* server_forward_secure_encrypter(
424 server
->session()->connection()->encrypter(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
,
467 &client_key_extraction
));
468 EXPECT_TRUE(server
->ExportKeyingMaterial(kSampleLabel
,
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());
526 QuicTag
CryptoTestUtils::ParseTag(const char* tagstr
) {
527 const size_t len
= strlen(tagstr
);
532 if (tagstr
[0] == '#') {
533 CHECK_EQ(static_cast<size_t>(1 + 2*4), len
);
536 for (size_t i
= 0; i
< 8; i
++) {
540 CHECK(HexChar(tagstr
[i
], &v
));
548 for (size_t i
= 0; i
< 4; i
++) {
551 tag
|= static_cast<uint32
>(tagstr
[i
]) << 24;
559 CryptoHandshakeMessage
CryptoTestUtils::Message(const char* message_tag
, ...) {
561 va_start(ap
, message_tag
);
563 CryptoHandshakeMessage message
= BuildMessage(message_tag
, ap
);
569 CryptoHandshakeMessage
CryptoTestUtils::BuildMessage(const char* message_tag
,
571 CryptoHandshakeMessage msg
;
572 msg
.set_tag(ParseTag(message_tag
));
575 const char* tagstr
= va_arg(ap
, const char*);
576 if (tagstr
== nullptr) {
580 if (tagstr
[0] == '$') {
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
);
587 CHECK(false) << "Unknown special value: " << special
;
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] == '#') {
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
++) {
606 CHECK(HexChar(valuestr
[i
*2], &v
));
608 CHECK(HexChar(valuestr
[i
*2 + 1], &v
));
613 tag
, StringPiece(reinterpret_cast<char*>(buf
.get()), len
/2));
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()));