blob: 2e2d6ae0a6af3a77bf7516d1d53fd2dd1014b3de [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
13#include <string>
14#include <vector>
15
16#include "net/base/ip_endpoint.h"
17#include "net/quic/crypto/crypto_server_config_protobuf.h"
18#include "net/quic/crypto/quic_random.h"
19#include "net/quic/crypto/proof_source.h"
20#include "net/quic/crypto/proof_verifier.h"
21#include "net/quic/crypto/quic_crypto_client_config.h"
22#include "net/quic/crypto/quic_crypto_server_config.h"
23#include "net/quic/quic_crypto_client_stream.h"
24#include "net/quic/quic_crypto_server_stream.h"
25#include "webrtc/base/common.h"
26#include "webrtc/base/gunit.h"
27#include "webrtc/p2p/base/faketransportcontroller.h"
28#include "webrtc/p2p/quic/quicconnectionhelper.h"
29#include "webrtc/p2p/quic/reliablequicstream.h"
30
mikescarlettf5377682016-03-29 12:14:55 -070031using net::IPAddress;
mikescarlettcd0e4752016-02-08 17:35:47 -080032using net::IPEndPoint;
mikescarlettf5377682016-03-29 12:14:55 -070033using net::PerPacketOptions;
mikescarlettcd0e4752016-02-08 17:35:47 -080034using net::Perspective;
35using net::ProofVerifyContext;
36using net::ProofVerifyDetails;
37using net::QuicByteCount;
38using net::QuicClock;
39using net::QuicConfig;
40using net::QuicConnection;
41using net::QuicCryptoClientConfig;
42using net::QuicCryptoServerConfig;
43using net::QuicCryptoClientStream;
44using net::QuicCryptoServerStream;
45using net::QuicCryptoStream;
46using net::QuicErrorCode;
47using net::QuicPacketWriter;
48using net::QuicRandom;
49using net::QuicServerConfigProtobuf;
50using net::QuicServerId;
51using net::QuicStreamId;
52using net::WriteResult;
53using net::WriteStatus;
54
55using cricket::FakeTransportChannel;
56using cricket::QuicConnectionHelper;
57using cricket::QuicSession;
58using cricket::ReliableQuicStream;
59using cricket::TransportChannel;
60
61using rtc::Thread;
62
63// Timeout for running asynchronous operations within unit tests.
mikescarlettf5377682016-03-29 12:14:55 -070064static const int kTimeoutMs = 1000;
mikescarlettcd0e4752016-02-08 17:35:47 -080065// Testing SpdyPriority value for creating outgoing ReliableQuicStream.
mikescarlettf5377682016-03-29 12:14:55 -070066static const uint8_t kDefaultPriority = 3;
mikescarlettcd0e4752016-02-08 17:35:47 -080067// TExport keying material function
mikescarlettf5377682016-03-29 12:14:55 -070068static const char kExporterLabel[] = "label";
69static const char kExporterContext[] = "context";
70static const size_t kExporterContextLen = sizeof(kExporterContext);
mikescarlettcd0e4752016-02-08 17:35:47 -080071// Identifies QUIC server session
mikescarlettf5377682016-03-29 12:14:55 -070072static const QuicServerId kServerId("www.google.com", 443);
mikescarlettcd0e4752016-02-08 17:35:47 -080073
74// Used by QuicCryptoServerConfig to provide server credentials, returning a
75// canned response equal to |success|.
76class FakeProofSource : public net::ProofSource {
77 public:
78 explicit FakeProofSource(bool success) : success_(success) {}
79
80 // ProofSource override.
mikescarlettf5377682016-03-29 12:14:55 -070081 bool GetProof(const IPAddress& server_ip,
mikescarlettcd0e4752016-02-08 17:35:47 -080082 const std::string& hostname,
83 const std::string& server_config,
mikescarlettf5377682016-03-29 12:14:55 -070084 net::QuicVersion quic_version,
85 base::StringPiece chlo_hash,
mikescarlettcd0e4752016-02-08 17:35:47 -080086 bool ecdsa_ok,
mikescarlettf5377682016-03-29 12:14:55 -070087 scoped_refptr<net::ProofSource::Chain>* out_certs,
mikescarlettcd0e4752016-02-08 17:35:47 -080088 std::string* out_signature,
89 std::string* out_leaf_cert_sct) override {
90 if (success_) {
mikescarlettf5377682016-03-29 12:14:55 -070091 std::vector<std::string> certs;
92 certs.push_back("Required to establish handshake");
93 *out_certs = new ProofSource::Chain(certs);
94 *out_signature = "Signature";
95 *out_leaf_cert_sct = "Time";
mikescarlettcd0e4752016-02-08 17:35:47 -080096 }
97 return success_;
98 }
99
100 private:
101 // Whether or not obtaining proof source succeeds.
102 bool success_;
103};
104
105// Used by QuicCryptoClientConfig to verify server credentials, returning a
106// canned response of QUIC_SUCCESS if |success| is true.
107class FakeProofVerifier : public net::ProofVerifier {
108 public:
109 explicit FakeProofVerifier(bool success) : success_(success) {}
110
111 // ProofVerifier override
112 net::QuicAsyncStatus VerifyProof(
113 const std::string& hostname,
114 const std::string& server_config,
115 const std::vector<std::string>& certs,
116 const std::string& cert_sct,
117 const std::string& signature,
118 const net::ProofVerifyContext* verify_context,
119 std::string* error_details,
120 scoped_ptr<net::ProofVerifyDetails>* verify_details,
121 net::ProofVerifierCallback* callback) override {
122 return success_ ? net::QUIC_SUCCESS : net::QUIC_FAILURE;
123 }
124
125 private:
126 // Whether or not proof verification succeeds.
127 bool success_;
128};
129
130// Writes QUIC packets to a fake transport channel that simulates a network.
131class FakeQuicPacketWriter : public QuicPacketWriter {
132 public:
133 explicit FakeQuicPacketWriter(FakeTransportChannel* fake_channel)
134 : fake_channel_(fake_channel) {}
135
136 // Sends packets across the network.
137 WriteResult WritePacket(const char* buffer,
138 size_t buf_len,
mikescarlettf5377682016-03-29 12:14:55 -0700139 const IPAddress& self_address,
140 const IPEndPoint& peer_address,
141 PerPacketOptions* options) override {
mikescarlettcd0e4752016-02-08 17:35:47 -0800142 rtc::PacketOptions packet_options;
143 int rv = fake_channel_->SendPacket(buffer, buf_len, packet_options, 0);
144 net::WriteStatus status;
145 if (rv > 0) {
146 status = net::WRITE_STATUS_OK;
147 } else if (fake_channel_->GetError() == EWOULDBLOCK) {
148 status = net::WRITE_STATUS_BLOCKED;
149 } else {
150 status = net::WRITE_STATUS_ERROR;
151 }
152 return net::WriteResult(status, rv);
153 }
154
155 // Returns true if the writer buffers and subsequently rewrites data
156 // when an attempt to write results in the underlying socket becoming
157 // write blocked.
158 bool IsWriteBlockedDataBuffered() const override { return true; }
159
160 // Returns true if the network socket is not writable.
161 bool IsWriteBlocked() const override { return !fake_channel_->writable(); }
162
163 // Records that the socket has become writable, for example when an EPOLLOUT
164 // is received or an asynchronous write completes.
165 void SetWritable() override { fake_channel_->SetWritable(true); }
166
167 // Returns the maximum size of the packet which can be written using this
168 // writer for the supplied peer address. This size may actually exceed the
169 // size of a valid QUIC packet.
170 QuicByteCount GetMaxPacketSize(
171 const IPEndPoint& peer_address) const override {
172 return net::kMaxPacketSize;
173 }
174
175 private:
176 FakeTransportChannel* fake_channel_;
177};
178
mikescarlettcd0e4752016-02-08 17:35:47 -0800179// Wrapper for QuicSession and transport channel that stores incoming data.
180class QuicSessionForTest : public QuicSession {
181 public:
mikescarlettf5377682016-03-29 12:14:55 -0700182 QuicSessionForTest(rtc::scoped_ptr<net::QuicConnection> connection,
mikescarlettcd0e4752016-02-08 17:35:47 -0800183 const net::QuicConfig& config,
mikescarlettf5377682016-03-29 12:14:55 -0700184 rtc::scoped_ptr<FakeTransportChannel> channel)
mikescarlettcd0e4752016-02-08 17:35:47 -0800185 : QuicSession(std::move(connection), config),
186 channel_(std::move(channel)) {
187 channel_->SignalReadPacket.connect(
188 this, &QuicSessionForTest::OnChannelReadPacket);
189 }
190
191 // Called when channel has packets to read.
192 void OnChannelReadPacket(TransportChannel* channel,
193 const char* data,
194 size_t size,
195 const rtc::PacketTime& packet_time,
196 int flags) {
197 OnReadPacket(data, size);
198 }
199
200 // Called when peer receives incoming stream from another peer.
201 void OnIncomingStream(ReliableQuicStream* stream) {
202 stream->SignalDataReceived.connect(this,
203 &QuicSessionForTest::OnDataReceived);
204 last_incoming_stream_ = stream;
205 }
206
207 // Called when peer has data to read from incoming stream.
208 void OnDataReceived(net::QuicStreamId id, const char* data, size_t length) {
209 last_received_data_ = std::string(data, length);
210 }
211
212 std::string data() { return last_received_data_; }
213
214 bool has_data() { return data().size() > 0; }
215
216 FakeTransportChannel* channel() { return channel_.get(); }
217
218 ReliableQuicStream* incoming_stream() { return last_incoming_stream_; }
219
220 private:
221 // Transports QUIC packets to/from peer.
mikescarlettf5377682016-03-29 12:14:55 -0700222 rtc::scoped_ptr<FakeTransportChannel> channel_;
mikescarlettcd0e4752016-02-08 17:35:47 -0800223 // Stores data received by peer once it is sent from the other peer.
224 std::string last_received_data_;
225 // Handles incoming streams from sender.
226 ReliableQuicStream* last_incoming_stream_ = nullptr;
227};
228
229// Simulates data transfer between two peers using QUIC.
230class QuicSessionTest : public ::testing::Test,
231 public QuicCryptoClientStream::ProofHandler {
232 public:
233 QuicSessionTest() : quic_helper_(rtc::Thread::Current()) {}
234
235 // Instantiates |client_peer_| and |server_peer_|.
236 void CreateClientAndServerSessions();
237
mikescarlettf5377682016-03-29 12:14:55 -0700238 rtc::scoped_ptr<QuicSessionForTest> CreateSession(
239 rtc::scoped_ptr<FakeTransportChannel> channel,
mikescarlettcd0e4752016-02-08 17:35:47 -0800240 Perspective perspective);
241
242 QuicCryptoClientStream* CreateCryptoClientStream(QuicSessionForTest* session,
243 bool handshake_success);
244 QuicCryptoServerStream* CreateCryptoServerStream(QuicSessionForTest* session,
245 bool handshake_success);
246
mikescarlettf5377682016-03-29 12:14:55 -0700247 rtc::scoped_ptr<QuicConnection> CreateConnection(
248 FakeTransportChannel* channel,
249 Perspective perspective);
mikescarlettcd0e4752016-02-08 17:35:47 -0800250
251 void StartHandshake(bool client_handshake_success,
252 bool server_handshake_success);
253
254 // Test handshake establishment and sending/receiving of data.
255 void TestStreamConnection(QuicSessionForTest* from_session,
256 QuicSessionForTest* to_session);
257 // Test that client and server are not connected after handshake failure.
258 void TestDisconnectAfterFailedHandshake();
259
260 // QuicCryptoClientStream::ProofHelper overrides.
261 void OnProofValid(
262 const QuicCryptoClientConfig::CachedState& cached) override {}
263 void OnProofVerifyDetailsAvailable(
264 const ProofVerifyDetails& verify_details) override {}
265
266 protected:
267 QuicConnectionHelper quic_helper_;
268 QuicConfig config_;
269 QuicClock clock_;
270
mikescarlettf5377682016-03-29 12:14:55 -0700271 rtc::scoped_ptr<QuicSessionForTest> client_peer_;
272 rtc::scoped_ptr<QuicSessionForTest> server_peer_;
mikescarlettcd0e4752016-02-08 17:35:47 -0800273};
274
275// Initializes "client peer" who begins crypto handshake and "server peer" who
276// establishes encryption with client.
277void QuicSessionTest::CreateClientAndServerSessions() {
mikescarlettf5377682016-03-29 12:14:55 -0700278 rtc::scoped_ptr<FakeTransportChannel> channel1(
mikescarlettb9dd7c52016-02-19 20:43:45 -0800279 new FakeTransportChannel("channel1", 0));
mikescarlettf5377682016-03-29 12:14:55 -0700280 rtc::scoped_ptr<FakeTransportChannel> channel2(
mikescarlettb9dd7c52016-02-19 20:43:45 -0800281 new FakeTransportChannel("channel2", 0));
mikescarlettcd0e4752016-02-08 17:35:47 -0800282
283 // Prevent channel1->OnReadPacket and channel2->OnReadPacket from calling
284 // themselves in a loop, which causes to future packets to be recursively
285 // consumed while the current thread blocks consumption of current ones.
286 channel2->SetAsync(true);
287
288 // Configure peers to send packets to each other.
289 channel1->Connect();
290 channel2->Connect();
291 channel1->SetDestination(channel2.get());
292
293 client_peer_ = CreateSession(std::move(channel1), Perspective::IS_CLIENT);
294 server_peer_ = CreateSession(std::move(channel2), Perspective::IS_SERVER);
295}
296
mikescarlettf5377682016-03-29 12:14:55 -0700297rtc::scoped_ptr<QuicSessionForTest> QuicSessionTest::CreateSession(
298 rtc::scoped_ptr<FakeTransportChannel> channel,
mikescarlettcd0e4752016-02-08 17:35:47 -0800299 Perspective perspective) {
mikescarlettf5377682016-03-29 12:14:55 -0700300 rtc::scoped_ptr<QuicConnection> quic_connection =
mikescarlettcd0e4752016-02-08 17:35:47 -0800301 CreateConnection(channel.get(), perspective);
mikescarlettf5377682016-03-29 12:14:55 -0700302 return rtc::scoped_ptr<QuicSessionForTest>(new QuicSessionForTest(
mikescarlettcd0e4752016-02-08 17:35:47 -0800303 std::move(quic_connection), config_, std::move(channel)));
304}
305
306QuicCryptoClientStream* QuicSessionTest::CreateCryptoClientStream(
307 QuicSessionForTest* session,
308 bool handshake_success) {
309 QuicCryptoClientConfig* client_config =
310 new QuicCryptoClientConfig(new FakeProofVerifier(handshake_success));
311 return new QuicCryptoClientStream(
312 kServerId, session, new ProofVerifyContext(), client_config, this);
313}
314
315QuicCryptoServerStream* QuicSessionTest::CreateCryptoServerStream(
316 QuicSessionForTest* session,
317 bool handshake_success) {
318 QuicCryptoServerConfig* server_config =
319 new QuicCryptoServerConfig("TESTING", QuicRandom::GetInstance(),
320 new FakeProofSource(handshake_success));
321 // Provide server with serialized config string to prove ownership.
322 QuicCryptoServerConfig::ConfigOptions options;
323 QuicServerConfigProtobuf* primary_config = server_config->GenerateConfig(
324 QuicRandom::GetInstance(), &clock_, options);
325 server_config->AddConfig(primary_config, clock_.WallNow());
326 return new QuicCryptoServerStream(server_config, session);
327}
328
mikescarlettf5377682016-03-29 12:14:55 -0700329rtc::scoped_ptr<QuicConnection> QuicSessionTest::CreateConnection(
mikescarlettcd0e4752016-02-08 17:35:47 -0800330 FakeTransportChannel* channel,
331 Perspective perspective) {
mikescarlettf5377682016-03-29 12:14:55 -0700332 FakeQuicPacketWriter* writer = new FakeQuicPacketWriter(channel);
mikescarlettcd0e4752016-02-08 17:35:47 -0800333
mikescarlettf5377682016-03-29 12:14:55 -0700334 IPAddress ip(0, 0, 0, 0);
mikescarlettcd0e4752016-02-08 17:35:47 -0800335 bool owns_writer = true;
336
mikescarlettf5377682016-03-29 12:14:55 -0700337 return rtc::scoped_ptr<QuicConnection>(new QuicConnection(
338 0, net::IPEndPoint(ip, 0), &quic_helper_, writer, owns_writer,
mikescarlettcd0e4752016-02-08 17:35:47 -0800339 perspective, net::QuicSupportedVersions()));
340}
341
342void QuicSessionTest::StartHandshake(bool client_handshake_success,
343 bool server_handshake_success) {
344 server_peer_->StartServerHandshake(
345 CreateCryptoServerStream(server_peer_.get(), server_handshake_success));
346 client_peer_->StartClientHandshake(
347 CreateCryptoClientStream(client_peer_.get(), client_handshake_success));
348}
349
350void QuicSessionTest::TestStreamConnection(QuicSessionForTest* from_session,
351 QuicSessionForTest* to_session) {
352 // Wait for crypto handshake to finish then check if encryption established.
353 ASSERT_TRUE_WAIT(from_session->IsCryptoHandshakeConfirmed() &&
354 to_session->IsCryptoHandshakeConfirmed(),
355 kTimeoutMs);
356
357 ASSERT_TRUE(from_session->IsEncryptionEstablished());
358 ASSERT_TRUE(to_session->IsEncryptionEstablished());
359
360 string from_key;
361 string to_key;
362
363 bool from_success = from_session->ExportKeyingMaterial(
364 kExporterLabel, kExporterContext, kExporterContextLen, &from_key);
365 ASSERT_TRUE(from_success);
366 bool to_success = to_session->ExportKeyingMaterial(
367 kExporterLabel, kExporterContext, kExporterContextLen, &to_key);
368 ASSERT_TRUE(to_success);
369
370 EXPECT_EQ(from_key.size(), kExporterContextLen);
371 EXPECT_EQ(from_key, to_key);
372
373 // Now we can establish encrypted outgoing stream.
374 ReliableQuicStream* outgoing_stream =
375 from_session->CreateOutgoingDynamicStream(kDefaultPriority);
376 ASSERT_NE(nullptr, outgoing_stream);
377 EXPECT_TRUE(from_session->HasOpenDynamicStreams());
378
379 outgoing_stream->SignalDataReceived.connect(
380 from_session, &QuicSessionForTest::OnDataReceived);
381 to_session->SignalIncomingStream.connect(
382 to_session, &QuicSessionForTest::OnIncomingStream);
383
384 // Send a test message from peer 1 to peer 2.
385 const char kTestMessage[] = "Hello, World!";
386 outgoing_stream->Write(kTestMessage, strlen(kTestMessage));
387
388 // Wait for peer 2 to receive messages.
389 ASSERT_TRUE_WAIT(to_session->has_data(), kTimeoutMs);
390
391 ReliableQuicStream* incoming = to_session->incoming_stream();
392 ASSERT_TRUE(incoming);
393 EXPECT_TRUE(to_session->HasOpenDynamicStreams());
394
395 EXPECT_EQ(to_session->data(), kTestMessage);
396
397 // Send a test message from peer 2 to peer 1.
398 const char kTestResponse[] = "Response";
399 incoming->Write(kTestResponse, strlen(kTestResponse));
400
401 // Wait for peer 1 to receive messages.
402 ASSERT_TRUE_WAIT(from_session->has_data(), kTimeoutMs);
403
404 EXPECT_EQ(from_session->data(), kTestResponse);
405}
406
407// Client and server should disconnect when proof verification fails.
408void QuicSessionTest::TestDisconnectAfterFailedHandshake() {
409 EXPECT_TRUE_WAIT(!client_peer_->connection()->connected(), kTimeoutMs);
410 EXPECT_TRUE_WAIT(!server_peer_->connection()->connected(), kTimeoutMs);
411
412 EXPECT_FALSE(client_peer_->IsEncryptionEstablished());
413 EXPECT_FALSE(client_peer_->IsCryptoHandshakeConfirmed());
414
415 EXPECT_FALSE(server_peer_->IsEncryptionEstablished());
416 EXPECT_FALSE(server_peer_->IsCryptoHandshakeConfirmed());
417}
418
419// Establish encryption then send message from client to server.
420TEST_F(QuicSessionTest, ClientToServer) {
421 CreateClientAndServerSessions();
422 StartHandshake(true, true);
423 TestStreamConnection(client_peer_.get(), server_peer_.get());
424}
425
426// Establish encryption then send message from server to client.
427TEST_F(QuicSessionTest, ServerToClient) {
428 CreateClientAndServerSessions();
429 StartHandshake(true, true);
430 TestStreamConnection(server_peer_.get(), client_peer_.get());
431}
432
433// Make client fail to verify proof from server.
434TEST_F(QuicSessionTest, ClientRejection) {
435 CreateClientAndServerSessions();
436 StartHandshake(false, true);
437 TestDisconnectAfterFailedHandshake();
438}
439
440// Make server fail to give proof to client.
441TEST_F(QuicSessionTest, ServerRejection) {
442 CreateClientAndServerSessions();
443 StartHandshake(true, false);
444 TestDisconnectAfterFailedHandshake();
445}
446
447// Test that data streams are not created before handshake.
448TEST_F(QuicSessionTest, CannotCreateDataStreamBeforeHandshake) {
449 CreateClientAndServerSessions();
450 EXPECT_EQ(nullptr, server_peer_->CreateOutgoingDynamicStream(5));
451 EXPECT_EQ(nullptr, client_peer_->CreateOutgoingDynamicStream(5));
452}