blob: eae0a2b451b0ca69a708134dbb1f8db89e74be89 [file] [log] [blame]
mikescarlettcd0e4752016-02-08 17:35:47 -08001/*
2 * Copyright 2016 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11#include "webrtc/p2p/quic/quicsession.h"
12
kwiberg3ec46792016-04-27 07:22:53 -070013#include <memory>
mikescarlettcd0e4752016-02-08 17:35:47 -080014#include <string>
15#include <vector>
16
17#include "net/base/ip_endpoint.h"
18#include "net/quic/crypto/crypto_server_config_protobuf.h"
19#include "net/quic/crypto/quic_random.h"
20#include "net/quic/crypto/proof_source.h"
21#include "net/quic/crypto/proof_verifier.h"
22#include "net/quic/crypto/quic_crypto_client_config.h"
23#include "net/quic/crypto/quic_crypto_server_config.h"
24#include "net/quic/quic_crypto_client_stream.h"
25#include "net/quic/quic_crypto_server_stream.h"
26#include "webrtc/base/common.h"
27#include "webrtc/base/gunit.h"
28#include "webrtc/p2p/base/faketransportcontroller.h"
29#include "webrtc/p2p/quic/quicconnectionhelper.h"
30#include "webrtc/p2p/quic/reliablequicstream.h"
31
mikescarlettf5377682016-03-29 12:14:55 -070032using net::IPAddress;
mikescarlettcd0e4752016-02-08 17:35:47 -080033using net::IPEndPoint;
mikescarlettf5377682016-03-29 12:14:55 -070034using net::PerPacketOptions;
mikescarlettcd0e4752016-02-08 17:35:47 -080035using net::Perspective;
36using net::ProofVerifyContext;
37using net::ProofVerifyDetails;
38using net::QuicByteCount;
39using net::QuicClock;
40using net::QuicConfig;
41using net::QuicConnection;
42using net::QuicCryptoClientConfig;
43using net::QuicCryptoServerConfig;
44using net::QuicCryptoClientStream;
45using net::QuicCryptoServerStream;
46using net::QuicCryptoStream;
47using net::QuicErrorCode;
48using net::QuicPacketWriter;
49using net::QuicRandom;
50using net::QuicServerConfigProtobuf;
51using net::QuicServerId;
52using net::QuicStreamId;
53using net::WriteResult;
54using net::WriteStatus;
55
56using cricket::FakeTransportChannel;
57using cricket::QuicConnectionHelper;
58using cricket::QuicSession;
59using cricket::ReliableQuicStream;
60using cricket::TransportChannel;
61
62using rtc::Thread;
63
64// Timeout for running asynchronous operations within unit tests.
mikescarlettf5377682016-03-29 12:14:55 -070065static const int kTimeoutMs = 1000;
mikescarlettcd0e4752016-02-08 17:35:47 -080066// Testing SpdyPriority value for creating outgoing ReliableQuicStream.
mikescarlettf5377682016-03-29 12:14:55 -070067static const uint8_t kDefaultPriority = 3;
mikescarlettcd0e4752016-02-08 17:35:47 -080068// TExport keying material function
mikescarlettf5377682016-03-29 12:14:55 -070069static const char kExporterLabel[] = "label";
70static const char kExporterContext[] = "context";
71static const size_t kExporterContextLen = sizeof(kExporterContext);
mikescarlettcd0e4752016-02-08 17:35:47 -080072// Identifies QUIC server session
mikescarlettf5377682016-03-29 12:14:55 -070073static const QuicServerId kServerId("www.google.com", 443);
mikescarlettcd0e4752016-02-08 17:35:47 -080074
75// Used by QuicCryptoServerConfig to provide server credentials, returning a
76// canned response equal to |success|.
77class FakeProofSource : public net::ProofSource {
78 public:
79 explicit FakeProofSource(bool success) : success_(success) {}
80
81 // ProofSource override.
mikescarlettf5377682016-03-29 12:14:55 -070082 bool GetProof(const IPAddress& server_ip,
mikescarlettcd0e4752016-02-08 17:35:47 -080083 const std::string& hostname,
84 const std::string& server_config,
mikescarlettf5377682016-03-29 12:14:55 -070085 net::QuicVersion quic_version,
86 base::StringPiece chlo_hash,
mikescarlettcd0e4752016-02-08 17:35:47 -080087 bool ecdsa_ok,
mikescarlettf5377682016-03-29 12:14:55 -070088 scoped_refptr<net::ProofSource::Chain>* out_certs,
mikescarlettcd0e4752016-02-08 17:35:47 -080089 std::string* out_signature,
90 std::string* out_leaf_cert_sct) override {
91 if (success_) {
mikescarlettf5377682016-03-29 12:14:55 -070092 std::vector<std::string> certs;
93 certs.push_back("Required to establish handshake");
94 *out_certs = new ProofSource::Chain(certs);
95 *out_signature = "Signature";
96 *out_leaf_cert_sct = "Time";
mikescarlettcd0e4752016-02-08 17:35:47 -080097 }
98 return success_;
99 }
100
101 private:
102 // Whether or not obtaining proof source succeeds.
103 bool success_;
104};
105
106// Used by QuicCryptoClientConfig to verify server credentials, returning a
107// canned response of QUIC_SUCCESS if |success| is true.
108class FakeProofVerifier : public net::ProofVerifier {
109 public:
110 explicit FakeProofVerifier(bool success) : success_(success) {}
111
112 // ProofVerifier override
113 net::QuicAsyncStatus VerifyProof(
114 const std::string& hostname,
115 const std::string& server_config,
116 const std::vector<std::string>& certs,
117 const std::string& cert_sct,
118 const std::string& signature,
119 const net::ProofVerifyContext* verify_context,
120 std::string* error_details,
kwiberg3ec46792016-04-27 07:22:53 -0700121 std::unique_ptr<net::ProofVerifyDetails>* verify_details,
mikescarlettcd0e4752016-02-08 17:35:47 -0800122 net::ProofVerifierCallback* callback) override {
123 return success_ ? net::QUIC_SUCCESS : net::QUIC_FAILURE;
124 }
125
126 private:
127 // Whether or not proof verification succeeds.
128 bool success_;
129};
130
131// Writes QUIC packets to a fake transport channel that simulates a network.
132class FakeQuicPacketWriter : public QuicPacketWriter {
133 public:
134 explicit FakeQuicPacketWriter(FakeTransportChannel* fake_channel)
135 : fake_channel_(fake_channel) {}
136
137 // Sends packets across the network.
138 WriteResult WritePacket(const char* buffer,
139 size_t buf_len,
mikescarlettf5377682016-03-29 12:14:55 -0700140 const IPAddress& self_address,
141 const IPEndPoint& peer_address,
142 PerPacketOptions* options) override {
mikescarlettcd0e4752016-02-08 17:35:47 -0800143 rtc::PacketOptions packet_options;
144 int rv = fake_channel_->SendPacket(buffer, buf_len, packet_options, 0);
145 net::WriteStatus status;
146 if (rv > 0) {
147 status = net::WRITE_STATUS_OK;
148 } else if (fake_channel_->GetError() == EWOULDBLOCK) {
149 status = net::WRITE_STATUS_BLOCKED;
150 } else {
151 status = net::WRITE_STATUS_ERROR;
152 }
153 return net::WriteResult(status, rv);
154 }
155
156 // Returns true if the writer buffers and subsequently rewrites data
157 // when an attempt to write results in the underlying socket becoming
158 // write blocked.
159 bool IsWriteBlockedDataBuffered() const override { return true; }
160
161 // Returns true if the network socket is not writable.
162 bool IsWriteBlocked() const override { return !fake_channel_->writable(); }
163
164 // Records that the socket has become writable, for example when an EPOLLOUT
165 // is received or an asynchronous write completes.
166 void SetWritable() override { fake_channel_->SetWritable(true); }
167
168 // Returns the maximum size of the packet which can be written using this
169 // writer for the supplied peer address. This size may actually exceed the
170 // size of a valid QUIC packet.
171 QuicByteCount GetMaxPacketSize(
172 const IPEndPoint& peer_address) const override {
173 return net::kMaxPacketSize;
174 }
175
176 private:
177 FakeTransportChannel* fake_channel_;
178};
179
mikescarlettcd0e4752016-02-08 17:35:47 -0800180// Wrapper for QuicSession and transport channel that stores incoming data.
181class QuicSessionForTest : public QuicSession {
182 public:
kwiberg3ec46792016-04-27 07:22:53 -0700183 QuicSessionForTest(std::unique_ptr<net::QuicConnection> connection,
mikescarlettcd0e4752016-02-08 17:35:47 -0800184 const net::QuicConfig& config,
kwiberg3ec46792016-04-27 07:22:53 -0700185 std::unique_ptr<FakeTransportChannel> channel)
mikescarlettcd0e4752016-02-08 17:35:47 -0800186 : QuicSession(std::move(connection), config),
187 channel_(std::move(channel)) {
188 channel_->SignalReadPacket.connect(
189 this, &QuicSessionForTest::OnChannelReadPacket);
190 }
191
192 // Called when channel has packets to read.
193 void OnChannelReadPacket(TransportChannel* channel,
194 const char* data,
195 size_t size,
196 const rtc::PacketTime& packet_time,
197 int flags) {
198 OnReadPacket(data, size);
199 }
200
201 // Called when peer receives incoming stream from another peer.
202 void OnIncomingStream(ReliableQuicStream* stream) {
203 stream->SignalDataReceived.connect(this,
204 &QuicSessionForTest::OnDataReceived);
205 last_incoming_stream_ = stream;
206 }
207
208 // Called when peer has data to read from incoming stream.
209 void OnDataReceived(net::QuicStreamId id, const char* data, size_t length) {
210 last_received_data_ = std::string(data, length);
211 }
212
213 std::string data() { return last_received_data_; }
214
215 bool has_data() { return data().size() > 0; }
216
217 FakeTransportChannel* channel() { return channel_.get(); }
218
219 ReliableQuicStream* incoming_stream() { return last_incoming_stream_; }
220
221 private:
222 // Transports QUIC packets to/from peer.
kwiberg3ec46792016-04-27 07:22:53 -0700223 std::unique_ptr<FakeTransportChannel> channel_;
mikescarlettcd0e4752016-02-08 17:35:47 -0800224 // Stores data received by peer once it is sent from the other peer.
225 std::string last_received_data_;
226 // Handles incoming streams from sender.
227 ReliableQuicStream* last_incoming_stream_ = nullptr;
228};
229
230// Simulates data transfer between two peers using QUIC.
231class QuicSessionTest : public ::testing::Test,
232 public QuicCryptoClientStream::ProofHandler {
233 public:
234 QuicSessionTest() : quic_helper_(rtc::Thread::Current()) {}
235
236 // Instantiates |client_peer_| and |server_peer_|.
237 void CreateClientAndServerSessions();
238
kwiberg3ec46792016-04-27 07:22:53 -0700239 std::unique_ptr<QuicSessionForTest> CreateSession(
240 std::unique_ptr<FakeTransportChannel> channel,
mikescarlettcd0e4752016-02-08 17:35:47 -0800241 Perspective perspective);
242
243 QuicCryptoClientStream* CreateCryptoClientStream(QuicSessionForTest* session,
244 bool handshake_success);
245 QuicCryptoServerStream* CreateCryptoServerStream(QuicSessionForTest* session,
246 bool handshake_success);
247
kwiberg3ec46792016-04-27 07:22:53 -0700248 std::unique_ptr<QuicConnection> CreateConnection(
mikescarlettf5377682016-03-29 12:14:55 -0700249 FakeTransportChannel* channel,
250 Perspective perspective);
mikescarlettcd0e4752016-02-08 17:35:47 -0800251
252 void StartHandshake(bool client_handshake_success,
253 bool server_handshake_success);
254
255 // Test handshake establishment and sending/receiving of data.
256 void TestStreamConnection(QuicSessionForTest* from_session,
257 QuicSessionForTest* to_session);
258 // Test that client and server are not connected after handshake failure.
259 void TestDisconnectAfterFailedHandshake();
260
261 // QuicCryptoClientStream::ProofHelper overrides.
262 void OnProofValid(
263 const QuicCryptoClientConfig::CachedState& cached) override {}
264 void OnProofVerifyDetailsAvailable(
265 const ProofVerifyDetails& verify_details) override {}
266
267 protected:
268 QuicConnectionHelper quic_helper_;
269 QuicConfig config_;
270 QuicClock clock_;
271
kwiberg3ec46792016-04-27 07:22:53 -0700272 std::unique_ptr<QuicSessionForTest> client_peer_;
273 std::unique_ptr<QuicSessionForTest> server_peer_;
mikescarlettcd0e4752016-02-08 17:35:47 -0800274};
275
276// Initializes "client peer" who begins crypto handshake and "server peer" who
277// establishes encryption with client.
278void QuicSessionTest::CreateClientAndServerSessions() {
kwiberg3ec46792016-04-27 07:22:53 -0700279 std::unique_ptr<FakeTransportChannel> channel1(
mikescarlettb9dd7c52016-02-19 20:43:45 -0800280 new FakeTransportChannel("channel1", 0));
kwiberg3ec46792016-04-27 07:22:53 -0700281 std::unique_ptr<FakeTransportChannel> channel2(
mikescarlettb9dd7c52016-02-19 20:43:45 -0800282 new FakeTransportChannel("channel2", 0));
mikescarlettcd0e4752016-02-08 17:35:47 -0800283
284 // Prevent channel1->OnReadPacket and channel2->OnReadPacket from calling
285 // themselves in a loop, which causes to future packets to be recursively
286 // consumed while the current thread blocks consumption of current ones.
287 channel2->SetAsync(true);
288
289 // Configure peers to send packets to each other.
290 channel1->Connect();
291 channel2->Connect();
292 channel1->SetDestination(channel2.get());
293
294 client_peer_ = CreateSession(std::move(channel1), Perspective::IS_CLIENT);
295 server_peer_ = CreateSession(std::move(channel2), Perspective::IS_SERVER);
296}
297
kwiberg3ec46792016-04-27 07:22:53 -0700298std::unique_ptr<QuicSessionForTest> QuicSessionTest::CreateSession(
299 std::unique_ptr<FakeTransportChannel> channel,
mikescarlettcd0e4752016-02-08 17:35:47 -0800300 Perspective perspective) {
kwiberg3ec46792016-04-27 07:22:53 -0700301 std::unique_ptr<QuicConnection> quic_connection =
mikescarlettcd0e4752016-02-08 17:35:47 -0800302 CreateConnection(channel.get(), perspective);
kwiberg3ec46792016-04-27 07:22:53 -0700303 return std::unique_ptr<QuicSessionForTest>(new QuicSessionForTest(
mikescarlettcd0e4752016-02-08 17:35:47 -0800304 std::move(quic_connection), config_, std::move(channel)));
305}
306
307QuicCryptoClientStream* QuicSessionTest::CreateCryptoClientStream(
308 QuicSessionForTest* session,
309 bool handshake_success) {
310 QuicCryptoClientConfig* client_config =
311 new QuicCryptoClientConfig(new FakeProofVerifier(handshake_success));
312 return new QuicCryptoClientStream(
313 kServerId, session, new ProofVerifyContext(), client_config, this);
314}
315
316QuicCryptoServerStream* QuicSessionTest::CreateCryptoServerStream(
317 QuicSessionForTest* session,
318 bool handshake_success) {
319 QuicCryptoServerConfig* server_config =
320 new QuicCryptoServerConfig("TESTING", QuicRandom::GetInstance(),
321 new FakeProofSource(handshake_success));
322 // Provide server with serialized config string to prove ownership.
323 QuicCryptoServerConfig::ConfigOptions options;
324 QuicServerConfigProtobuf* primary_config = server_config->GenerateConfig(
325 QuicRandom::GetInstance(), &clock_, options);
326 server_config->AddConfig(primary_config, clock_.WallNow());
327 return new QuicCryptoServerStream(server_config, session);
328}
329
kwiberg3ec46792016-04-27 07:22:53 -0700330std::unique_ptr<QuicConnection> QuicSessionTest::CreateConnection(
mikescarlettcd0e4752016-02-08 17:35:47 -0800331 FakeTransportChannel* channel,
332 Perspective perspective) {
mikescarlettf5377682016-03-29 12:14:55 -0700333 FakeQuicPacketWriter* writer = new FakeQuicPacketWriter(channel);
mikescarlettcd0e4752016-02-08 17:35:47 -0800334
mikescarlettf5377682016-03-29 12:14:55 -0700335 IPAddress ip(0, 0, 0, 0);
mikescarlettcd0e4752016-02-08 17:35:47 -0800336 bool owns_writer = true;
337
kwiberg3ec46792016-04-27 07:22:53 -0700338 return std::unique_ptr<QuicConnection>(new QuicConnection(
mikescarlettf5377682016-03-29 12:14:55 -0700339 0, net::IPEndPoint(ip, 0), &quic_helper_, writer, owns_writer,
mikescarlettcd0e4752016-02-08 17:35:47 -0800340 perspective, net::QuicSupportedVersions()));
341}
342
343void QuicSessionTest::StartHandshake(bool client_handshake_success,
344 bool server_handshake_success) {
345 server_peer_->StartServerHandshake(
346 CreateCryptoServerStream(server_peer_.get(), server_handshake_success));
347 client_peer_->StartClientHandshake(
348 CreateCryptoClientStream(client_peer_.get(), client_handshake_success));
349}
350
351void QuicSessionTest::TestStreamConnection(QuicSessionForTest* from_session,
352 QuicSessionForTest* to_session) {
353 // Wait for crypto handshake to finish then check if encryption established.
354 ASSERT_TRUE_WAIT(from_session->IsCryptoHandshakeConfirmed() &&
355 to_session->IsCryptoHandshakeConfirmed(),
356 kTimeoutMs);
357
358 ASSERT_TRUE(from_session->IsEncryptionEstablished());
359 ASSERT_TRUE(to_session->IsEncryptionEstablished());
360
361 string from_key;
362 string to_key;
363
364 bool from_success = from_session->ExportKeyingMaterial(
365 kExporterLabel, kExporterContext, kExporterContextLen, &from_key);
366 ASSERT_TRUE(from_success);
367 bool to_success = to_session->ExportKeyingMaterial(
368 kExporterLabel, kExporterContext, kExporterContextLen, &to_key);
369 ASSERT_TRUE(to_success);
370
371 EXPECT_EQ(from_key.size(), kExporterContextLen);
372 EXPECT_EQ(from_key, to_key);
373
374 // Now we can establish encrypted outgoing stream.
375 ReliableQuicStream* outgoing_stream =
376 from_session->CreateOutgoingDynamicStream(kDefaultPriority);
377 ASSERT_NE(nullptr, outgoing_stream);
378 EXPECT_TRUE(from_session->HasOpenDynamicStreams());
379
380 outgoing_stream->SignalDataReceived.connect(
381 from_session, &QuicSessionForTest::OnDataReceived);
382 to_session->SignalIncomingStream.connect(
383 to_session, &QuicSessionForTest::OnIncomingStream);
384
385 // Send a test message from peer 1 to peer 2.
386 const char kTestMessage[] = "Hello, World!";
387 outgoing_stream->Write(kTestMessage, strlen(kTestMessage));
388
389 // Wait for peer 2 to receive messages.
390 ASSERT_TRUE_WAIT(to_session->has_data(), kTimeoutMs);
391
392 ReliableQuicStream* incoming = to_session->incoming_stream();
393 ASSERT_TRUE(incoming);
394 EXPECT_TRUE(to_session->HasOpenDynamicStreams());
395
396 EXPECT_EQ(to_session->data(), kTestMessage);
397
398 // Send a test message from peer 2 to peer 1.
399 const char kTestResponse[] = "Response";
400 incoming->Write(kTestResponse, strlen(kTestResponse));
401
402 // Wait for peer 1 to receive messages.
403 ASSERT_TRUE_WAIT(from_session->has_data(), kTimeoutMs);
404
405 EXPECT_EQ(from_session->data(), kTestResponse);
406}
407
408// Client and server should disconnect when proof verification fails.
409void QuicSessionTest::TestDisconnectAfterFailedHandshake() {
410 EXPECT_TRUE_WAIT(!client_peer_->connection()->connected(), kTimeoutMs);
411 EXPECT_TRUE_WAIT(!server_peer_->connection()->connected(), kTimeoutMs);
412
413 EXPECT_FALSE(client_peer_->IsEncryptionEstablished());
414 EXPECT_FALSE(client_peer_->IsCryptoHandshakeConfirmed());
415
416 EXPECT_FALSE(server_peer_->IsEncryptionEstablished());
417 EXPECT_FALSE(server_peer_->IsCryptoHandshakeConfirmed());
418}
419
420// Establish encryption then send message from client to server.
421TEST_F(QuicSessionTest, ClientToServer) {
422 CreateClientAndServerSessions();
423 StartHandshake(true, true);
424 TestStreamConnection(client_peer_.get(), server_peer_.get());
425}
426
427// Establish encryption then send message from server to client.
428TEST_F(QuicSessionTest, ServerToClient) {
429 CreateClientAndServerSessions();
430 StartHandshake(true, true);
431 TestStreamConnection(server_peer_.get(), client_peer_.get());
432}
433
434// Make client fail to verify proof from server.
435TEST_F(QuicSessionTest, ClientRejection) {
436 CreateClientAndServerSessions();
437 StartHandshake(false, true);
438 TestDisconnectAfterFailedHandshake();
439}
440
441// Make server fail to give proof to client.
442TEST_F(QuicSessionTest, ServerRejection) {
443 CreateClientAndServerSessions();
444 StartHandshake(true, false);
445 TestDisconnectAfterFailedHandshake();
446}
447
448// Test that data streams are not created before handshake.
449TEST_F(QuicSessionTest, CannotCreateDataStreamBeforeHandshake) {
450 CreateClientAndServerSessions();
451 EXPECT_EQ(nullptr, server_peer_->CreateOutgoingDynamicStream(5));
452 EXPECT_EQ(nullptr, client_peer_->CreateOutgoingDynamicStream(5));
453}
mikescarlett18b67a52016-04-11 16:56:23 -0700454
455// Test that closing a QUIC stream causes the QuicSession to remove it.
456TEST_F(QuicSessionTest, CloseQuicStream) {
457 CreateClientAndServerSessions();
458 StartHandshake(true, true);
459 ASSERT_TRUE_WAIT(client_peer_->IsCryptoHandshakeConfirmed() &&
460 server_peer_->IsCryptoHandshakeConfirmed(),
461 kTimeoutMs);
462 ReliableQuicStream* stream = client_peer_->CreateOutgoingDynamicStream(5);
463 ASSERT_NE(nullptr, stream);
464 EXPECT_FALSE(client_peer_->IsClosedStream(stream->id()));
465 stream->Close();
466 EXPECT_TRUE(client_peer_->IsClosedStream(stream->id()));
467}