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
;
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
{
45 void OnError(CryptoFramer
* framer
) override
{ error_
= true; }
47 void OnHandshakeMessage(const CryptoHandshakeMessage
& message
) override
{
48 messages_
.push_back(message
);
55 const vector
<CryptoHandshakeMessage
>& messages() const {
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
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.
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') {
116 if (c
>= 'a' && c
<= 'f') {
117 *value
= c
- 'a' + 10;
120 if (c
>= 'A' && c
<= 'F') {
121 *value
= c
- 'A' + 10;
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
{
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
{
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
) {
152 callback_
.reset(callback
);
156 // CallbackSource implementation.
157 void RunPendingCallbacks() override
{
158 if (callback_
.get()) {
159 callback_
->Run(&channel_id_key_
);
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) {
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
,
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();
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
) {
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
);
255 options
.channel_id_source_async
,
256 client_session
.GetCryptoStream()->WasChannelIDSourceCallbackRun());
259 return client_session
.GetCryptoStream()->num_sent_client_hellos();
263 void CryptoTestUtils::SetupCryptoServerConfigForTest(
264 const QuicClock
* clock
,
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
));
275 void CryptoTestUtils::CommunicateHandshakeMessages(
276 PacketSavingConnection
* a_conn
,
278 PacketSavingConnection
* b_conn
,
279 QuicCryptoStream
* b
) {
280 CommunicateHandshakeMessagesAndRunCallbacks(a_conn
, a
, b_conn
, b
, nullptr);
284 void CryptoTestUtils::CommunicateHandshakeMessagesAndRunCallbacks(
285 PacketSavingConnection
* a_conn
,
287 PacketSavingConnection
* b_conn
,
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
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
303 MovePackets(b_conn
, &b_i
, a
, a_conn
);
304 if (callback_source
) {
305 callback_source
->RunPendingCallbacks();
311 pair
<size_t, size_t> CryptoTestUtils::AdvanceHandshake(
312 PacketSavingConnection
* a_conn
,
315 PacketSavingConnection
* b_conn
,
318 VLOG(1) << "Processing " << a_conn
->encrypted_packets_
.size() - a_i
320 MovePackets(a_conn
, &a_i
, b
, b_conn
);
322 VLOG(1) << "Processing " << b_conn
->encrypted_packets_
.size() - b_i
324 if (b_conn
->encrypted_packets_
.size() - b_i
== 2) {
327 MovePackets(b_conn
, &b_i
, a
, a_conn
);
329 return std::make_pair(a_i
, b_i
);
333 string
CryptoTestUtils::GetValueForTag(const CryptoHandshakeMessage
& message
,
335 QuicTagValueMap::const_iterator it
= message
.tag_value_map().find(tag
);
336 if (it
== message
.tag_value_map().end()) {
342 class MockCommonCertSets
: public CommonCertSets
{
344 MockCommonCertSets(StringPiece cert
, uint64 hash
, uint32 index
)
345 : cert_(cert
.as_string()),
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_
) {
359 return StringPiece();
362 bool MatchCert(StringPiece cert
,
363 StringPiece common_set_hashes
,
365 uint32
* out_index
) const override
{
370 if (common_set_hashes
.size() % sizeof(uint64
) != 0) {
373 bool client_has_set
= false;
374 for (size_t i
= 0; i
< common_set_hashes
.size(); i
+= sizeof(uint64
)) {
376 memcpy(&hash
, common_set_hashes
.data() + i
, sizeof(hash
));
378 client_has_set
= true;
383 if (!client_has_set
) {
398 CommonCertSets
* CryptoTestUtils::MockCommonCertSets(StringPiece cert
,
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
,
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()));