Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(151)

Side by Side Diff: webrtc/p2p/quic/quictransportchannel.cc

Issue 1721673004: Create QuicTransportChannel (Closed) Base URL: https://chromium.googlesource.com/external/webrtc.git@master
Patch Set: Update documentation before committing Created 4 years, 9 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 /*
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/quictransportchannel.h"
12
13 #include <utility>
14
15 #include "net/quic/crypto/proof_source.h"
16 #include "net/quic/crypto/proof_verifier.h"
17 #include "net/quic/crypto/quic_crypto_client_config.h"
18 #include "net/quic/crypto/quic_crypto_server_config.h"
19 #include "net/quic/quic_connection.h"
20 #include "net/quic/quic_crypto_client_stream.h"
21 #include "net/quic/quic_crypto_server_stream.h"
22 #include "net/quic/quic_protocol.h"
23 #include "webrtc/base/checks.h"
24 #include "webrtc/base/helpers.h"
25 #include "webrtc/base/logging.h"
26 #include "webrtc/base/socket.h"
27 #include "webrtc/base/thread.h"
28 #include "webrtc/p2p/base/common.h"
29
30 namespace {
31
32 // QUIC public header constants for net::QuicConnection. These are arbitrary
33 // given that |channel_| only receives packets specific to this channel,
34 // in which case we already know the QUIC packets have the correct destination.
35 const net::QuicConnectionId kConnectionId = 0;
36 const net::IPAddressNumber kConnectionIpAddress(net::kIPv4AddressSize, 0);
37 const net::IPEndPoint kConnectionIpEndpoint(kConnectionIpAddress, 0);
38
39 // Arbitrary server port number for net::QuicCryptoClientConfig.
40 const int kQuicServerPort = 0;
41
42 // QUIC connection timeout. This is large so that |channel_| can
43 // be responsible for connection timeout.
44 const int kIdleConnectionStateLifetime = 1000; // seconds
45
46 // Length of HKDF input keying material, equal to its number of bytes.
47 // https://tools.ietf.org/html/rfc5869#section-2.2.
48 // TODO(mikescarlett): Verify that input keying material length is correct.
49 const size_t kInputKeyingMaterialLength = 32;
50
51 // We don't pull the RTP constants from rtputils.h, to avoid a layer violation.
52 const size_t kMinRtpPacketLen = 12;
53
54 bool IsRtpPacket(const char* data, size_t len) {
55 const uint8_t* u = reinterpret_cast<const uint8_t*>(data);
56 return (len >= kMinRtpPacketLen && (u[0] & 0xC0) == 0x80);
57 }
58
59 // Function for detecting QUIC packets based off
60 // https://tools.ietf.org/html/draft-tsvwg-quic-protocol-02#section-6.
61 const size_t kMinQuicPacketLen = 2;
62
63 bool IsQuicPacket(const char* data, size_t len) {
64 const uint8_t* u = reinterpret_cast<const uint8_t*>(data);
65 return (len >= kMinQuicPacketLen && (u[0] & 0x80) == 0);
66 }
67
68 // Used by QuicCryptoServerConfig to provide dummy proof credentials.
69 // TODO(mikescarlett): Remove when secure P2P QUIC handshake is possible.
70 class DummyProofSource : public net::ProofSource {
71 public:
72 DummyProofSource() {}
73 ~DummyProofSource() override {}
74
75 // ProofSource override.
76 bool GetProof(const net::IPAddressNumber& server_ip,
77 const std::string& hostname,
78 const std::string& server_config,
79 bool ecdsa_ok,
80 const std::vector<std::string>** out_certs,
81 std::string* out_signature,
82 std::string* out_leaf_cert_sct) override {
83 LOG(INFO) << "GetProof() providing dummy credentials for insecure QUIC";
84 std::vector<std::string>* certs = new std::vector<std::string>();
85 certs->push_back("Dummy cert");
86 std::string signature("Dummy signature");
87
88 *out_certs = certs;
89 *out_signature = signature;
90
91 return true;
92 }
93 };
94
95 // Used by QuicCryptoClientConfig to ignore the peer's credentials
96 // and establish an insecure QUIC connection.
97 // TODO(mikescarlett): Remove when secure P2P QUIC handshake is possible.
98 class InsecureProofVerifier : public net::ProofVerifier {
99 public:
100 InsecureProofVerifier() {}
101 ~InsecureProofVerifier() override {}
102
103 // ProofVerifier override.
104 net::QuicAsyncStatus VerifyProof(
105 const std::string& hostname,
106 const std::string& server_config,
107 const std::vector<std::string>& certs,
108 const std::string& cert_sct,
109 const std::string& signature,
110 const net::ProofVerifyContext* verify_context,
111 std::string* error_details,
112 scoped_ptr<net::ProofVerifyDetails>* verify_details,
113 net::ProofVerifierCallback* callback) override {
114 LOG(INFO) << "VerifyProof() ignoring credentials and returning success";
115 return net::QUIC_SUCCESS;
116 }
117 };
118
119 } // namespace
120
121 namespace cricket {
122
123 QuicTransportChannel::QuicTransportChannel(TransportChannelImpl* channel)
124 : TransportChannelImpl(channel->transport_name(), channel->component()),
125 worker_thread_(rtc::Thread::Current()),
126 channel_(channel),
127 helper_(worker_thread_) {
128 channel_->SignalWritableState.connect(this,
129 &QuicTransportChannel::OnWritableState);
130 channel_->SignalReadPacket.connect(this, &QuicTransportChannel::OnReadPacket);
131 channel_->SignalSentPacket.connect(this, &QuicTransportChannel::OnSentPacket);
132 channel_->SignalReadyToSend.connect(this,
133 &QuicTransportChannel::OnReadyToSend);
134 channel_->SignalGatheringState.connect(
135 this, &QuicTransportChannel::OnGatheringState);
136 channel_->SignalCandidateGathered.connect(
137 this, &QuicTransportChannel::OnCandidateGathered);
138 channel_->SignalRoleConflict.connect(this,
139 &QuicTransportChannel::OnRoleConflict);
140 channel_->SignalRouteChange.connect(this,
141 &QuicTransportChannel::OnRouteChange);
142 channel_->SignalConnectionRemoved.connect(
143 this, &QuicTransportChannel::OnConnectionRemoved);
144 channel_->SignalReceivingState.connect(
145 this, &QuicTransportChannel::OnReceivingState);
146
147 // Set the QUIC connection timeout.
148 config_.SetIdleConnectionStateLifetime(
149 net::QuicTime::Delta::FromSeconds(kIdleConnectionStateLifetime),
150 net::QuicTime::Delta::FromSeconds(kIdleConnectionStateLifetime));
151 // Set the bytes reserved for the QUIC connection ID to zero.
152 config_.SetBytesForConnectionIdToSend(0);
153 }
154
155 QuicTransportChannel::~QuicTransportChannel() {}
156
157 bool QuicTransportChannel::SetLocalCertificate(
158 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
159 if (!certificate) {
160 LOG_J(ERROR, this) << "No local certificate was supplied. Not doing QUIC.";
161 return false;
162 }
163 if (!local_certificate_) {
164 local_certificate_ = certificate;
165 return true;
166 }
167 if (certificate == local_certificate_) {
168 // This may happen during renegotiation.
169 LOG_J(INFO, this) << "Ignoring identical certificate";
170 return true;
171 }
172 LOG_J(ERROR, this) << "Local certificate of the QUIC connection already set. "
173 "Can't change the local certificate once it's active.";
174 return false;
175 }
176
177 rtc::scoped_refptr<rtc::RTCCertificate>
178 QuicTransportChannel::GetLocalCertificate() const {
179 return local_certificate_;
180 }
181
182 bool QuicTransportChannel::SetSslRole(rtc::SSLRole role) {
183 if (ssl_role_ && *ssl_role_ == role) {
184 LOG_J(WARNING, this) << "Ignoring SSL Role identical to current role.";
185 return true;
186 }
187 if (quic_state_ != QUIC_TRANSPORT_CONNECTED) {
188 ssl_role_ = rtc::Optional<rtc::SSLRole>(role);
189 return true;
190 }
191 LOG_J(ERROR, this)
192 << "SSL Role can't be reversed after the session is setup.";
193 return false;
194 }
195
196 bool QuicTransportChannel::GetSslRole(rtc::SSLRole* role) const {
197 if (!ssl_role_) {
198 return false;
199 }
200 *role = *ssl_role_;
201 return true;
202 }
203
204 bool QuicTransportChannel::SetRemoteFingerprint(const std::string& digest_alg,
205 const uint8_t* digest,
206 size_t digest_len) {
207 if (digest_alg.empty()) {
208 RTC_DCHECK(!digest_len);
209 LOG_J(ERROR, this) << "Remote peer doesn't support digest algorithm.";
210 return false;
211 }
212 std::string remote_fingerprint_value(reinterpret_cast<const char*>(digest),
213 digest_len);
214 // Once we have the local certificate, the same remote fingerprint can be set
215 // multiple times. This may happen during renegotiation.
216 if (remote_fingerprint_ &&
217 remote_fingerprint_->value == remote_fingerprint_value &&
218 remote_fingerprint_->algorithm == digest_alg) {
219 LOG_J(INFO, this) << "Ignoring identical remote fingerprint and algorithm";
220 return true;
221 }
222 remote_fingerprint_ = rtc::Optional<RemoteFingerprint>(RemoteFingerprint());
223 remote_fingerprint_->value = remote_fingerprint_value;
224 remote_fingerprint_->algorithm = digest_alg;
225 return true;
226 }
227
228 bool QuicTransportChannel::ExportKeyingMaterial(const std::string& label,
229 const uint8_t* context,
230 size_t context_len,
231 bool use_context,
232 uint8_t* result,
233 size_t result_len) {
234 std::string quic_context(reinterpret_cast<const char*>(context), context_len);
235 std::string quic_result;
236 if (!quic_->ExportKeyingMaterial(label, quic_context, result_len,
237 &quic_result)) {
238 return false;
239 }
240 quic_result.copy(reinterpret_cast<char*>(result), result_len);
241 return true;
242 }
243
244 bool QuicTransportChannel::GetSrtpCryptoSuite(int* cipher) {
245 *cipher = rtc::SRTP_AES128_CM_SHA1_80;
246 return true;
247 }
248
249 // Called from upper layers to send a media packet.
250 int QuicTransportChannel::SendPacket(const char* data,
251 size_t size,
252 const rtc::PacketOptions& options,
253 int flags) {
254 if ((flags & PF_SRTP_BYPASS) && IsRtpPacket(data, size)) {
255 return channel_->SendPacket(data, size, options);
256 }
257 LOG(ERROR) << "Failed to send an invalid SRTP bypass packet using QUIC.";
258 return -1;
259 }
260
261 // The state transition logic here is as follows:
262 // - Before the QUIC handshake is complete, the QUIC channel is unwritable.
263 // - When |channel_| goes writable we start the QUIC handshake.
264 // - Once the QUIC handshake completes, the state is that of the
265 // |channel_| again.
266 void QuicTransportChannel::OnWritableState(TransportChannel* channel) {
267 ASSERT(rtc::Thread::Current() == worker_thread_);
268 ASSERT(channel == channel_);
269 LOG_J(VERBOSE, this)
270 << "QuicTransportChannel: channel writable state changed to "
271 << channel_->writable();
272 switch (quic_state_) {
273 case QUIC_TRANSPORT_NEW:
274 // Start the QUIC handshake when |channel_| is writable.
275 // This will fail if the SSL role or remote fingerprint are not set.
276 // Otherwise failure could result from network or QUIC errors.
277 MaybeStartQuic();
278 break;
279 case QUIC_TRANSPORT_CONNECTED:
280 // Note: SignalWritableState fired by set_writable.
281 set_writable(channel_->writable());
282 if (HasDataToWrite()) {
283 OnCanWrite();
284 }
285 break;
286 case QUIC_TRANSPORT_CONNECTING:
287 // This channel is not writable until the QUIC handshake finishes. It
288 // might have been write blocked.
289 if (HasDataToWrite()) {
290 OnCanWrite();
291 }
292 break;
293 case QUIC_TRANSPORT_CLOSED:
294 // TODO(mikescarlett): Allow the QUIC connection to be reset if it drops
295 // due to a non-failure.
296 break;
297 }
298 }
299
300 void QuicTransportChannel::OnReceivingState(TransportChannel* channel) {
301 ASSERT(rtc::Thread::Current() == worker_thread_);
302 ASSERT(channel == channel_);
303 LOG_J(VERBOSE, this)
304 << "QuicTransportChannel: channel receiving state changed to "
305 << channel_->receiving();
306 if (quic_state_ == QUIC_TRANSPORT_CONNECTED) {
307 // Note: SignalReceivingState fired by set_receiving.
308 set_receiving(channel_->receiving());
309 }
310 }
311
312 void QuicTransportChannel::OnReadPacket(TransportChannel* channel,
313 const char* data,
314 size_t size,
315 const rtc::PacketTime& packet_time,
316 int flags) {
317 ASSERT(rtc::Thread::Current() == worker_thread_);
318 ASSERT(channel == channel_);
319 ASSERT(flags == 0);
320
321 switch (quic_state_) {
322 case QUIC_TRANSPORT_NEW:
323 // This would occur if other peer is ready to start QUIC but this peer
324 // hasn't started QUIC.
325 LOG_J(INFO, this) << "Dropping packet received before QUIC started.";
326 break;
327 case QUIC_TRANSPORT_CONNECTING:
328 case QUIC_TRANSPORT_CONNECTED:
329 // We should only get QUIC or SRTP packets; STUN's already been demuxed.
330 // Is this potentially a QUIC packet?
331 if (IsQuicPacket(data, size)) {
332 if (!HandleQuicPacket(data, size)) {
333 LOG_J(ERROR, this) << "Failed to handle QUIC packet.";
334 return;
335 }
336 } else {
337 // If this is an RTP packet, signal upwards as a bypass packet.
338 if (!IsRtpPacket(data, size)) {
339 LOG_J(ERROR, this) << "Received unexpected non-QUIC, non-RTP packet.";
340 return;
341 }
342 SignalReadPacket(this, data, size, packet_time, PF_SRTP_BYPASS);
343 }
344 break;
345 case QUIC_TRANSPORT_CLOSED:
346 // This shouldn't be happening. Drop the packet.
347 break;
348 }
349 }
350
351 void QuicTransportChannel::OnSentPacket(TransportChannel* channel,
352 const rtc::SentPacket& sent_packet) {
353 ASSERT(rtc::Thread::Current() == worker_thread_);
354 SignalSentPacket(this, sent_packet);
355 }
356
357 void QuicTransportChannel::OnReadyToSend(TransportChannel* channel) {
358 if (writable()) {
359 SignalReadyToSend(this);
360 }
361 }
362
363 void QuicTransportChannel::OnGatheringState(TransportChannelImpl* channel) {
364 ASSERT(channel == channel_);
365 SignalGatheringState(this);
366 }
367
368 void QuicTransportChannel::OnCandidateGathered(TransportChannelImpl* channel,
369 const Candidate& c) {
370 ASSERT(channel == channel_);
371 SignalCandidateGathered(this, c);
372 }
373
374 void QuicTransportChannel::OnRoleConflict(TransportChannelImpl* channel) {
375 ASSERT(channel == channel_);
376 SignalRoleConflict(this);
377 }
378
379 void QuicTransportChannel::OnRouteChange(TransportChannel* channel,
380 const Candidate& candidate) {
381 ASSERT(channel == channel_);
382 SignalRouteChange(this, candidate);
383 }
384
385 void QuicTransportChannel::OnConnectionRemoved(TransportChannelImpl* channel) {
386 ASSERT(channel == channel_);
387 SignalConnectionRemoved(this);
388 }
389
390 bool QuicTransportChannel::MaybeStartQuic() {
391 if (!channel_->writable()) {
392 LOG_J(ERROR, this) << "Couldn't start QUIC handshake.";
393 return false;
394 }
395 if (!CreateQuicSession() || !StartQuicHandshake()) {
396 LOG_J(WARNING, this) << "Underlying channel is writable but cannot start "
397 "the QUIC handshake.";
398 return false;
399 }
400 // Verify connection is not closed due to QUIC bug or network failure.
401 // A closed connection should not happen since |channel_| is writable.
402 if (!quic_->connection()->connected()) {
403 LOG_J(ERROR, this) << "QUIC connection should not be closed if underlying "
404 "channel is writable.";
405 return false;
406 }
407 // Indicate that |quic_| is ready to receive QUIC packets.
408 set_quic_state(QUIC_TRANSPORT_CONNECTING);
409 return true;
410 }
411
412 bool QuicTransportChannel::CreateQuicSession() {
413 if (!ssl_role_ || !remote_fingerprint_) {
414 return false;
415 }
416 net::Perspective perspective = (*ssl_role_ == rtc::SSL_CLIENT)
417 ? net::Perspective::IS_CLIENT
418 : net::Perspective::IS_SERVER;
419 bool owns_writer = false;
420 scoped_ptr<net::QuicConnection> connection(new net::QuicConnection(
421 kConnectionId, kConnectionIpEndpoint, &helper_, this, owns_writer,
422 perspective, net::QuicSupportedVersions()));
423 quic_.reset(new QuicSession(std::move(connection), config_));
424 quic_->SignalHandshakeComplete.connect(
425 this, &QuicTransportChannel::OnHandshakeComplete);
426 quic_->SignalConnectionClosed.connect(
427 this, &QuicTransportChannel::OnConnectionClosed);
428 return true;
429 }
430
431 bool QuicTransportChannel::StartQuicHandshake() {
432 if (*ssl_role_ == rtc::SSL_CLIENT) {
433 // Unique identifier for remote peer.
434 net::QuicServerId server_id(remote_fingerprint_->value, kQuicServerPort);
435 // Perform authentication of remote peer; owned by QuicCryptoClientConfig.
436 // TODO(mikescarlett): Actually verify proof.
437 net::ProofVerifier* proof_verifier = new InsecureProofVerifier();
438 quic_crypto_client_config_.reset(
439 new net::QuicCryptoClientConfig(proof_verifier));
440 net::QuicCryptoClientStream* crypto_stream =
441 new net::QuicCryptoClientStream(server_id, quic_.get(),
442 new net::ProofVerifyContext(),
443 quic_crypto_client_config_.get(), this);
444 quic_->StartClientHandshake(crypto_stream);
445 LOG_J(INFO, this) << "QuicTransportChannel: Started client handshake.";
446 } else {
447 RTC_DCHECK_EQ(*ssl_role_, rtc::SSL_SERVER);
448 // Provide credentials to remote peer; owned by QuicCryptoServerConfig.
449 // TODO(mikescarlett): Actually provide credentials.
450 net::ProofSource* proof_source = new DummyProofSource();
451 // Input keying material to HKDF, per http://tools.ietf.org/html/rfc5869.
452 // This is pseudorandom so that HKDF-Extract outputs a pseudorandom key,
453 // since QuicCryptoServerConfig does not use a salt value.
454 std::string source_address_token_secret;
455 if (!rtc::CreateRandomString(kInputKeyingMaterialLength,
456 &source_address_token_secret)) {
457 LOG_J(ERROR, this) << "Error generating input keying material for HKDF.";
458 return false;
459 }
460 quic_crypto_server_config_.reset(new net::QuicCryptoServerConfig(
461 source_address_token_secret, helper_.GetRandomGenerator(),
462 proof_source));
463 // Provide server with serialized config string to prove ownership.
464 net::QuicCryptoServerConfig::ConfigOptions options;
465 quic_crypto_server_config_->AddDefaultConfig(helper_.GetRandomGenerator(),
466 helper_.GetClock(), options);
467 net::QuicCryptoServerStream* crypto_stream =
468 new net::QuicCryptoServerStream(quic_crypto_server_config_.get(),
469 quic_.get());
470 quic_->StartServerHandshake(crypto_stream);
471 LOG_J(INFO, this) << "QuicTransportChannel: Started server handshake.";
472 }
473 return true;
474 }
475
476 bool QuicTransportChannel::HandleQuicPacket(const char* data, size_t size) {
477 ASSERT(rtc::Thread::Current() == worker_thread_);
478 return quic_->OnReadPacket(data, size);
479 }
480
481 net::WriteResult QuicTransportChannel::WritePacket(
482 const char* buffer,
483 size_t buf_len,
484 const net::IPAddressNumber& self_address,
485 const net::IPEndPoint& peer_address) {
486 // QUIC should never call this if IsWriteBlocked, but just in case...
487 if (IsWriteBlocked()) {
488 return net::WriteResult(net::WRITE_STATUS_BLOCKED, EWOULDBLOCK);
489 }
490 // TODO(mikescarlett): Figure out how to tell QUIC "I dropped your packet, but
491 // don't block" without the QUIC connection tearing itself down.
492 int sent = channel_->SendPacket(buffer, buf_len, rtc::PacketOptions());
493 int bytes_written = sent > 0 ? sent : 0;
494 return net::WriteResult(net::WRITE_STATUS_OK, bytes_written);
495 }
496
497 // TODO(mikescarlett): Implement check for whether |channel_| is currently
498 // write blocked so that |quic_| does not try to write packet. This is
499 // necessary because |channel_| can be writable yet write blocked and
500 // channel_->GetError() is not flushed when there is no error.
501 bool QuicTransportChannel::IsWriteBlocked() const {
502 return !channel_->writable();
503 }
504
505 void QuicTransportChannel::OnHandshakeComplete() {
506 set_quic_state(QUIC_TRANSPORT_CONNECTED);
507 set_writable(true);
508 // OnReceivingState might have been called before the QUIC channel was
509 // connected, in which case the QUIC channel is now receiving.
510 if (channel_->receiving()) {
511 set_receiving(true);
512 }
513 }
514
515 void QuicTransportChannel::OnConnectionClosed(net::QuicErrorCode error,
516 bool from_peer) {
517 LOG_J(INFO, this) << "Connection closed by " << (from_peer ? "other" : "this")
518 << " peer "
519 << "with QUIC error " << error;
520 // TODO(mikescarlett): Allow the QUIC session to be reset when the connection
521 // does not close due to failure.
522 set_quic_state(QUIC_TRANSPORT_CLOSED);
523 set_writable(false);
524 }
525
526 void QuicTransportChannel::OnProofValid(
527 const net::QuicCryptoClientConfig::CachedState& cached) {
528 LOG_J(INFO, this) << "Cached proof marked valid";
529 }
530
531 void QuicTransportChannel::OnProofVerifyDetailsAvailable(
532 const net::ProofVerifyDetails& verify_details) {
533 LOG_J(INFO, this) << "Proof verify details available from"
534 << " QuicCryptoClientStream";
535 }
536
537 bool QuicTransportChannel::HasDataToWrite() const {
538 return quic_ && quic_->HasDataToWrite();
539 }
540
541 void QuicTransportChannel::OnCanWrite() {
542 RTC_DCHECK(quic_ != nullptr);
543 quic_->connection()->OnCanWrite();
544 }
545
546 void QuicTransportChannel::set_quic_state(QuicTransportState state) {
547 LOG_J(VERBOSE, this) << "set_quic_state from:" << quic_state_ << " to "
548 << state;
549 quic_state_ = state;
550 }
551
552 } // namespace cricket
OLDNEW
« no previous file with comments | « webrtc/p2p/quic/quictransportchannel.h ('k') | webrtc/p2p/quic/quictransportchannel_unittest.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698