dtlstransportchannel_unittest.cc revision cbecd358e032021eac11fb13e04ec7f070d4f407
1/*
2 *  Copyright 2011 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 <set>
12
13#include "webrtc/p2p/base/dtlstransport.h"
14#include "webrtc/p2p/base/faketransportcontroller.h"
15#include "webrtc/base/common.h"
16#include "webrtc/base/dscp.h"
17#include "webrtc/base/gunit.h"
18#include "webrtc/base/helpers.h"
19#include "webrtc/base/scoped_ptr.h"
20#include "webrtc/base/ssladapter.h"
21#include "webrtc/base/sslidentity.h"
22#include "webrtc/base/sslstreamadapter.h"
23#include "webrtc/base/stringutils.h"
24
25#define MAYBE_SKIP_TEST(feature)                    \
26  if (!(rtc::SSLStreamAdapter::feature())) {  \
27    LOG(LS_INFO) << "Feature disabled... skipping"; \
28    return;                                         \
29  }
30
31static const char AES_CM_128_HMAC_SHA1_80[] = "AES_CM_128_HMAC_SHA1_80";
32static const char kIceUfrag1[] = "TESTICEUFRAG0001";
33static const char kIcePwd1[] = "TESTICEPWD00000000000001";
34static const size_t kPacketNumOffset = 8;
35static const size_t kPacketHeaderLen = 12;
36
37static bool IsRtpLeadByte(uint8 b) {
38  return ((b & 0xC0) == 0x80);
39}
40
41using cricket::ConnectionRole;
42
43enum Flags { NF_REOFFER = 0x1, NF_EXPECT_FAILURE = 0x2 };
44
45class DtlsTestClient : public sigslot::has_slots<> {
46 public:
47  DtlsTestClient(const std::string& name)
48      : name_(name),
49        packet_size_(0),
50        use_dtls_srtp_(false),
51        ssl_max_version_(rtc::SSL_PROTOCOL_DTLS_10),
52        negotiated_dtls_(false),
53        received_dtls_client_hello_(false),
54        received_dtls_server_hello_(false) {}
55  void CreateCertificate(rtc::KeyType key_type) {
56    certificate_ = rtc::RTCCertificate::Create(
57        rtc::scoped_ptr<rtc::SSLIdentity>(
58            rtc::SSLIdentity::Generate(name_, key_type)).Pass());
59  }
60  const rtc::scoped_refptr<rtc::RTCCertificate>& certificate() {
61    return certificate_;
62  }
63  void SetupSrtp() {
64    ASSERT(certificate_);
65    use_dtls_srtp_ = true;
66  }
67  void SetupMaxProtocolVersion(rtc::SSLProtocolVersion version) {
68    ASSERT(!transport_);
69    ssl_max_version_ = version;
70  }
71  void SetupChannels(int count, cricket::IceRole role) {
72    transport_.reset(new cricket::DtlsTransport<cricket::FakeTransport>(
73        "dtls content name", nullptr, certificate_));
74    transport_->SetAsync(true);
75    transport_->SetIceRole(role);
76    transport_->SetIceTiebreaker(
77        (role == cricket::ICEROLE_CONTROLLING) ? 1 : 2);
78    transport_->SignalWritableState.connect(this,
79        &DtlsTestClient::OnTransportWritableState);
80
81    for (int i = 0; i < count; ++i) {
82      cricket::DtlsTransportChannelWrapper* channel =
83          static_cast<cricket::DtlsTransportChannelWrapper*>(
84              transport_->CreateChannel(i));
85      ASSERT_TRUE(channel != NULL);
86      channel->SetSslMaxProtocolVersion(ssl_max_version_);
87      channel->SignalWritableState.connect(this,
88        &DtlsTestClient::OnTransportChannelWritableState);
89      channel->SignalReadPacket.connect(this,
90        &DtlsTestClient::OnTransportChannelReadPacket);
91      channels_.push_back(channel);
92
93      // Hook the raw packets so that we can verify they are encrypted.
94      channel->channel()->SignalReadPacket.connect(
95          this, &DtlsTestClient::OnFakeTransportChannelReadPacket);
96    }
97  }
98
99  cricket::Transport* transport() { return transport_.get(); }
100
101  cricket::FakeTransportChannel* GetFakeChannel(int component) {
102    cricket::TransportChannelImpl* ch = transport_->GetChannel(component);
103    cricket::DtlsTransportChannelWrapper* wrapper =
104        static_cast<cricket::DtlsTransportChannelWrapper*>(ch);
105    return (wrapper) ?
106        static_cast<cricket::FakeTransportChannel*>(wrapper->channel()) : NULL;
107  }
108
109  // Offer DTLS if we have an identity; pass in a remote fingerprint only if
110  // both sides support DTLS.
111  void Negotiate(DtlsTestClient* peer, cricket::ContentAction action,
112                 ConnectionRole local_role, ConnectionRole remote_role,
113                 int flags) {
114    Negotiate(certificate_, certificate_ ? peer->certificate_ : nullptr, action,
115              local_role, remote_role, flags);
116  }
117
118  // Allow any DTLS configuration to be specified (including invalid ones).
119  void Negotiate(const rtc::scoped_refptr<rtc::RTCCertificate>& local_cert,
120                 const rtc::scoped_refptr<rtc::RTCCertificate>& remote_cert,
121                 cricket::ContentAction action,
122                 ConnectionRole local_role,
123                 ConnectionRole remote_role,
124                 int flags) {
125    rtc::scoped_ptr<rtc::SSLFingerprint> local_fingerprint;
126    rtc::scoped_ptr<rtc::SSLFingerprint> remote_fingerprint;
127    if (local_cert) {
128      std::string digest_algorithm;
129      ASSERT_TRUE(local_cert->ssl_certificate().GetSignatureDigestAlgorithm(
130          &digest_algorithm));
131      ASSERT_FALSE(digest_algorithm.empty());
132      local_fingerprint.reset(rtc::SSLFingerprint::Create(
133          digest_algorithm, local_cert->identity()));
134      ASSERT_TRUE(local_fingerprint.get() != NULL);
135      EXPECT_EQ(rtc::DIGEST_SHA_256, digest_algorithm);
136    }
137    if (remote_cert) {
138      std::string digest_algorithm;
139      ASSERT_TRUE(remote_cert->ssl_certificate().GetSignatureDigestAlgorithm(
140          &digest_algorithm));
141      ASSERT_FALSE(digest_algorithm.empty());
142      remote_fingerprint.reset(rtc::SSLFingerprint::Create(
143          digest_algorithm, remote_cert->identity()));
144      ASSERT_TRUE(remote_fingerprint.get() != NULL);
145      EXPECT_EQ(rtc::DIGEST_SHA_256, digest_algorithm);
146    }
147
148    if (use_dtls_srtp_ && !(flags & NF_REOFFER)) {
149      // SRTP ciphers will be set only in the beginning.
150      for (std::vector<cricket::DtlsTransportChannelWrapper*>::iterator it =
151           channels_.begin(); it != channels_.end(); ++it) {
152        std::vector<std::string> ciphers;
153        ciphers.push_back(AES_CM_128_HMAC_SHA1_80);
154        ASSERT_TRUE((*it)->SetSrtpCiphers(ciphers));
155      }
156    }
157
158    cricket::TransportDescription local_desc(
159        std::vector<std::string>(), kIceUfrag1, kIcePwd1, cricket::ICEMODE_FULL,
160        local_role,
161        // If remote if the offerer and has no DTLS support, answer will be
162        // without any fingerprint.
163        (action == cricket::CA_ANSWER && !remote_cert)
164            ? nullptr
165            : local_fingerprint.get(),
166        cricket::Candidates());
167
168    cricket::TransportDescription remote_desc(
169        std::vector<std::string>(), kIceUfrag1, kIcePwd1, cricket::ICEMODE_FULL,
170        remote_role, remote_fingerprint.get(), cricket::Candidates());
171
172    bool expect_success = (flags & NF_EXPECT_FAILURE) ? false : true;
173    // If |expect_success| is false, expect SRTD or SLTD to fail when
174    // content action is CA_ANSWER.
175    if (action == cricket::CA_OFFER) {
176      ASSERT_TRUE(transport_->SetLocalTransportDescription(
177          local_desc, cricket::CA_OFFER, NULL));
178      ASSERT_EQ(expect_success, transport_->SetRemoteTransportDescription(
179          remote_desc, cricket::CA_ANSWER, NULL));
180    } else {
181      ASSERT_TRUE(transport_->SetRemoteTransportDescription(
182          remote_desc, cricket::CA_OFFER, NULL));
183      ASSERT_EQ(expect_success, transport_->SetLocalTransportDescription(
184          local_desc, cricket::CA_ANSWER, NULL));
185    }
186    negotiated_dtls_ = (local_cert && remote_cert);
187  }
188
189  bool Connect(DtlsTestClient* peer) {
190    transport_->ConnectChannels();
191    transport_->SetDestination(peer->transport_.get());
192    return true;
193  }
194
195  bool all_channels_writable() const {
196    return transport_->all_channels_writable();
197  }
198
199  void CheckRole(rtc::SSLRole role) {
200    if (role == rtc::SSL_CLIENT) {
201      ASSERT_FALSE(received_dtls_client_hello_);
202      ASSERT_TRUE(received_dtls_server_hello_);
203    } else {
204      ASSERT_TRUE(received_dtls_client_hello_);
205      ASSERT_FALSE(received_dtls_server_hello_);
206    }
207  }
208
209  void CheckSrtp(const std::string& expected_cipher) {
210    for (std::vector<cricket::DtlsTransportChannelWrapper*>::iterator it =
211           channels_.begin(); it != channels_.end(); ++it) {
212      std::string cipher;
213
214      bool rv = (*it)->GetSrtpCipher(&cipher);
215      if (negotiated_dtls_ && !expected_cipher.empty()) {
216        ASSERT_TRUE(rv);
217
218        ASSERT_EQ(cipher, expected_cipher);
219      } else {
220        ASSERT_FALSE(rv);
221      }
222    }
223  }
224
225  void CheckSsl(const std::string& expected_cipher) {
226    for (std::vector<cricket::DtlsTransportChannelWrapper*>::iterator it =
227           channels_.begin(); it != channels_.end(); ++it) {
228      std::string cipher;
229
230      bool rv = (*it)->GetSslCipher(&cipher);
231      if (negotiated_dtls_ && !expected_cipher.empty()) {
232        ASSERT_TRUE(rv);
233
234        ASSERT_EQ(cipher, expected_cipher);
235      } else {
236        ASSERT_FALSE(rv);
237      }
238    }
239  }
240
241  void SendPackets(size_t channel, size_t size, size_t count, bool srtp) {
242    ASSERT(channel < channels_.size());
243    rtc::scoped_ptr<char[]> packet(new char[size]);
244    size_t sent = 0;
245    do {
246      // Fill the packet with a known value and a sequence number to check
247      // against, and make sure that it doesn't look like DTLS.
248      memset(packet.get(), sent & 0xff, size);
249      packet[0] = (srtp) ? 0x80 : 0x00;
250      rtc::SetBE32(packet.get() + kPacketNumOffset,
251                         static_cast<uint32>(sent));
252
253      // Only set the bypass flag if we've activated DTLS.
254      int flags = (certificate_ && srtp) ? cricket::PF_SRTP_BYPASS : 0;
255      rtc::PacketOptions packet_options;
256      int rv = channels_[channel]->SendPacket(
257          packet.get(), size, packet_options, flags);
258      ASSERT_GT(rv, 0);
259      ASSERT_EQ(size, static_cast<size_t>(rv));
260      ++sent;
261    } while (sent < count);
262  }
263
264  int SendInvalidSrtpPacket(size_t channel, size_t size) {
265    ASSERT(channel < channels_.size());
266    rtc::scoped_ptr<char[]> packet(new char[size]);
267    // Fill the packet with 0 to form an invalid SRTP packet.
268    memset(packet.get(), 0, size);
269
270    rtc::PacketOptions packet_options;
271    return channels_[channel]->SendPacket(
272        packet.get(), size, packet_options, cricket::PF_SRTP_BYPASS);
273  }
274
275  void ExpectPackets(size_t channel, size_t size) {
276    packet_size_ = size;
277    received_.clear();
278  }
279
280  size_t NumPacketsReceived() {
281    return received_.size();
282  }
283
284  bool VerifyPacket(const char* data, size_t size, uint32* out_num) {
285    if (size != packet_size_ ||
286        (data[0] != 0 && static_cast<uint8>(data[0]) != 0x80)) {
287      return false;
288    }
289    uint32 packet_num = rtc::GetBE32(data + kPacketNumOffset);
290    for (size_t i = kPacketHeaderLen; i < size; ++i) {
291      if (static_cast<uint8>(data[i]) != (packet_num & 0xff)) {
292        return false;
293      }
294    }
295    if (out_num) {
296      *out_num = packet_num;
297    }
298    return true;
299  }
300  bool VerifyEncryptedPacket(const char* data, size_t size) {
301    // This is an encrypted data packet; let's make sure it's mostly random;
302    // less than 10% of the bytes should be equal to the cleartext packet.
303    if (size <= packet_size_) {
304      return false;
305    }
306    uint32 packet_num = rtc::GetBE32(data + kPacketNumOffset);
307    int num_matches = 0;
308    for (size_t i = kPacketNumOffset; i < size; ++i) {
309      if (static_cast<uint8>(data[i]) == (packet_num & 0xff)) {
310        ++num_matches;
311      }
312    }
313    return (num_matches < ((static_cast<int>(size) - 5) / 10));
314  }
315
316  // Transport callbacks
317  void OnTransportWritableState(cricket::Transport* transport) {
318    LOG(LS_INFO) << name_ << ": is writable";
319  }
320
321  // Transport channel callbacks
322  void OnTransportChannelWritableState(cricket::TransportChannel* channel) {
323    LOG(LS_INFO) << name_ << ": Channel '" << channel->component()
324                 << "' is writable";
325  }
326
327  void OnTransportChannelReadPacket(cricket::TransportChannel* channel,
328                                    const char* data, size_t size,
329                                    const rtc::PacketTime& packet_time,
330                                    int flags) {
331    uint32 packet_num = 0;
332    ASSERT_TRUE(VerifyPacket(data, size, &packet_num));
333    received_.insert(packet_num);
334    // Only DTLS-SRTP packets should have the bypass flag set.
335    int expected_flags =
336        (certificate_ && IsRtpLeadByte(data[0])) ? cricket::PF_SRTP_BYPASS : 0;
337    ASSERT_EQ(expected_flags, flags);
338  }
339
340  // Hook into the raw packet stream to make sure DTLS packets are encrypted.
341  void OnFakeTransportChannelReadPacket(cricket::TransportChannel* channel,
342                                        const char* data, size_t size,
343                                        const rtc::PacketTime& time,
344                                        int flags) {
345    // Flags shouldn't be set on the underlying TransportChannel packets.
346    ASSERT_EQ(0, flags);
347
348    // Look at the handshake packets to see what role we played.
349    // Check that non-handshake packets are DTLS data or SRTP bypass.
350    if (negotiated_dtls_) {
351      if (data[0] == 22 && size > 17) {
352        if (data[13] == 1) {
353          received_dtls_client_hello_ = true;
354        } else if (data[13] == 2) {
355          received_dtls_server_hello_ = true;
356        }
357      } else if (!(data[0] >= 20 && data[0] <= 22)) {
358        ASSERT_TRUE(data[0] == 23 || IsRtpLeadByte(data[0]));
359        if (data[0] == 23) {
360          ASSERT_TRUE(VerifyEncryptedPacket(data, size));
361        } else if (IsRtpLeadByte(data[0])) {
362          ASSERT_TRUE(VerifyPacket(data, size, NULL));
363        }
364      }
365    }
366  }
367
368 private:
369  std::string name_;
370  rtc::scoped_refptr<rtc::RTCCertificate> certificate_;
371  rtc::scoped_ptr<cricket::FakeTransport> transport_;
372  std::vector<cricket::DtlsTransportChannelWrapper*> channels_;
373  size_t packet_size_;
374  std::set<int> received_;
375  bool use_dtls_srtp_;
376  rtc::SSLProtocolVersion ssl_max_version_;
377  bool negotiated_dtls_;
378  bool received_dtls_client_hello_;
379  bool received_dtls_server_hello_;
380};
381
382
383class DtlsTransportChannelTest : public testing::Test {
384 public:
385  DtlsTransportChannelTest()
386      : client1_("P1"),
387        client2_("P2"),
388        channel_ct_(1),
389        use_dtls_(false),
390        use_dtls_srtp_(false),
391        ssl_expected_version_(rtc::SSL_PROTOCOL_DTLS_10) {}
392
393  void SetChannelCount(size_t channel_ct) {
394    channel_ct_ = static_cast<int>(channel_ct);
395  }
396  void SetMaxProtocolVersions(rtc::SSLProtocolVersion c1,
397                              rtc::SSLProtocolVersion c2) {
398    client1_.SetupMaxProtocolVersion(c1);
399    client2_.SetupMaxProtocolVersion(c2);
400    ssl_expected_version_ = std::min(c1, c2);
401  }
402  void PrepareDtls(bool c1, bool c2, rtc::KeyType key_type) {
403    if (c1) {
404      client1_.CreateCertificate(key_type);
405    }
406    if (c2) {
407      client2_.CreateCertificate(key_type);
408    }
409    if (c1 && c2)
410      use_dtls_ = true;
411  }
412  void PrepareDtlsSrtp(bool c1, bool c2) {
413    if (!use_dtls_)
414      return;
415
416    if (c1)
417      client1_.SetupSrtp();
418    if (c2)
419      client2_.SetupSrtp();
420
421    if (c1 && c2)
422      use_dtls_srtp_ = true;
423  }
424
425  bool Connect(ConnectionRole client1_role, ConnectionRole client2_role) {
426    Negotiate(client1_role, client2_role);
427
428    bool rv = client1_.Connect(&client2_);
429    EXPECT_TRUE(rv);
430    if (!rv)
431      return false;
432
433    EXPECT_TRUE_WAIT(
434        client1_.all_channels_writable() && client2_.all_channels_writable(),
435        10000);
436    if (!client1_.all_channels_writable() || !client2_.all_channels_writable())
437      return false;
438
439    // Check that we used the right roles.
440    if (use_dtls_) {
441      rtc::SSLRole client1_ssl_role =
442          (client1_role == cricket::CONNECTIONROLE_ACTIVE ||
443           (client2_role == cricket::CONNECTIONROLE_PASSIVE &&
444            client1_role == cricket::CONNECTIONROLE_ACTPASS)) ?
445              rtc::SSL_CLIENT : rtc::SSL_SERVER;
446
447      rtc::SSLRole client2_ssl_role =
448          (client2_role == cricket::CONNECTIONROLE_ACTIVE ||
449           (client1_role == cricket::CONNECTIONROLE_PASSIVE &&
450            client2_role == cricket::CONNECTIONROLE_ACTPASS)) ?
451              rtc::SSL_CLIENT : rtc::SSL_SERVER;
452
453      client1_.CheckRole(client1_ssl_role);
454      client2_.CheckRole(client2_ssl_role);
455    }
456
457    // Check that we negotiated the right ciphers.
458    if (use_dtls_srtp_) {
459      client1_.CheckSrtp(AES_CM_128_HMAC_SHA1_80);
460      client2_.CheckSrtp(AES_CM_128_HMAC_SHA1_80);
461    } else {
462      client1_.CheckSrtp("");
463      client2_.CheckSrtp("");
464    }
465    client1_.CheckSsl(
466        rtc::SSLStreamAdapter::GetDefaultSslCipher(ssl_expected_version_));
467    client2_.CheckSsl(
468        rtc::SSLStreamAdapter::GetDefaultSslCipher(ssl_expected_version_));
469
470    return true;
471  }
472
473  bool Connect() {
474    // By default, Client1 will be Server and Client2 will be Client.
475    return Connect(cricket::CONNECTIONROLE_ACTPASS,
476                   cricket::CONNECTIONROLE_ACTIVE);
477  }
478
479  void Negotiate() {
480    Negotiate(cricket::CONNECTIONROLE_ACTPASS, cricket::CONNECTIONROLE_ACTIVE);
481  }
482
483  void Negotiate(ConnectionRole client1_role, ConnectionRole client2_role) {
484    client1_.SetupChannels(channel_ct_, cricket::ICEROLE_CONTROLLING);
485    client2_.SetupChannels(channel_ct_, cricket::ICEROLE_CONTROLLED);
486    // Expect success from SLTD and SRTD.
487    client1_.Negotiate(&client2_, cricket::CA_OFFER,
488                       client1_role, client2_role, 0);
489    client2_.Negotiate(&client1_, cricket::CA_ANSWER,
490                       client2_role, client1_role, 0);
491  }
492
493  // Negotiate with legacy client |client2|. Legacy client doesn't use setup
494  // attributes, except NONE.
495  void NegotiateWithLegacy() {
496    client1_.SetupChannels(channel_ct_, cricket::ICEROLE_CONTROLLING);
497    client2_.SetupChannels(channel_ct_, cricket::ICEROLE_CONTROLLED);
498    // Expect success from SLTD and SRTD.
499    client1_.Negotiate(&client2_, cricket::CA_OFFER,
500                       cricket::CONNECTIONROLE_ACTPASS,
501                       cricket::CONNECTIONROLE_NONE, 0);
502    client2_.Negotiate(&client1_, cricket::CA_ANSWER,
503                       cricket::CONNECTIONROLE_ACTIVE,
504                       cricket::CONNECTIONROLE_NONE, 0);
505  }
506
507  void Renegotiate(DtlsTestClient* reoffer_initiator,
508                   ConnectionRole client1_role, ConnectionRole client2_role,
509                   int flags) {
510    if (reoffer_initiator == &client1_) {
511      client1_.Negotiate(&client2_, cricket::CA_OFFER,
512                         client1_role, client2_role, flags);
513      client2_.Negotiate(&client1_, cricket::CA_ANSWER,
514                         client2_role, client1_role, flags);
515    } else {
516      client2_.Negotiate(&client1_, cricket::CA_OFFER,
517                         client2_role, client1_role, flags);
518      client1_.Negotiate(&client2_, cricket::CA_ANSWER,
519                         client1_role, client2_role, flags);
520    }
521  }
522
523  void TestTransfer(size_t channel, size_t size, size_t count, bool srtp) {
524    LOG(LS_INFO) << "Expect packets, size=" << size;
525    client2_.ExpectPackets(channel, size);
526    client1_.SendPackets(channel, size, count, srtp);
527    EXPECT_EQ_WAIT(count, client2_.NumPacketsReceived(), 10000);
528  }
529
530 protected:
531  DtlsTestClient client1_;
532  DtlsTestClient client2_;
533  int channel_ct_;
534  bool use_dtls_;
535  bool use_dtls_srtp_;
536  rtc::SSLProtocolVersion ssl_expected_version_;
537};
538
539// Test that transport negotiation of ICE, no DTLS works properly.
540TEST_F(DtlsTransportChannelTest, TestChannelSetupIce) {
541  Negotiate();
542  cricket::FakeTransportChannel* channel1 = client1_.GetFakeChannel(0);
543  cricket::FakeTransportChannel* channel2 = client2_.GetFakeChannel(0);
544  ASSERT_TRUE(channel1 != NULL);
545  ASSERT_TRUE(channel2 != NULL);
546  EXPECT_EQ(cricket::ICEROLE_CONTROLLING, channel1->GetIceRole());
547  EXPECT_EQ(1U, channel1->IceTiebreaker());
548  EXPECT_EQ(kIceUfrag1, channel1->ice_ufrag());
549  EXPECT_EQ(kIcePwd1, channel1->ice_pwd());
550  EXPECT_EQ(cricket::ICEROLE_CONTROLLED, channel2->GetIceRole());
551  EXPECT_EQ(2U, channel2->IceTiebreaker());
552}
553
554// Connect without DTLS, and transfer some data.
555TEST_F(DtlsTransportChannelTest, TestTransfer) {
556  ASSERT_TRUE(Connect());
557  TestTransfer(0, 1000, 100, false);
558}
559
560// Create two channels without DTLS, and transfer some data.
561TEST_F(DtlsTransportChannelTest, TestTransferTwoChannels) {
562  SetChannelCount(2);
563  ASSERT_TRUE(Connect());
564  TestTransfer(0, 1000, 100, false);
565  TestTransfer(1, 1000, 100, false);
566}
567
568// Connect without DTLS, and transfer SRTP data.
569TEST_F(DtlsTransportChannelTest, TestTransferSrtp) {
570  ASSERT_TRUE(Connect());
571  TestTransfer(0, 1000, 100, true);
572}
573
574// Create two channels without DTLS, and transfer SRTP data.
575TEST_F(DtlsTransportChannelTest, TestTransferSrtpTwoChannels) {
576  SetChannelCount(2);
577  ASSERT_TRUE(Connect());
578  TestTransfer(0, 1000, 100, true);
579  TestTransfer(1, 1000, 100, true);
580}
581
582// Connect with DTLS, and transfer some data.
583TEST_F(DtlsTransportChannelTest, TestTransferDtls) {
584  MAYBE_SKIP_TEST(HaveDtls);
585  PrepareDtls(true, true, rtc::KT_DEFAULT);
586  ASSERT_TRUE(Connect());
587  TestTransfer(0, 1000, 100, false);
588}
589
590// Create two channels with DTLS, and transfer some data.
591TEST_F(DtlsTransportChannelTest, TestTransferDtlsTwoChannels) {
592  MAYBE_SKIP_TEST(HaveDtls);
593  SetChannelCount(2);
594  PrepareDtls(true, true, rtc::KT_DEFAULT);
595  ASSERT_TRUE(Connect());
596  TestTransfer(0, 1000, 100, false);
597  TestTransfer(1, 1000, 100, false);
598}
599
600// Connect with A doing DTLS and B not, and transfer some data.
601TEST_F(DtlsTransportChannelTest, TestTransferDtlsRejected) {
602  PrepareDtls(true, false, rtc::KT_DEFAULT);
603  ASSERT_TRUE(Connect());
604  TestTransfer(0, 1000, 100, false);
605}
606
607// Connect with B doing DTLS and A not, and transfer some data.
608TEST_F(DtlsTransportChannelTest, TestTransferDtlsNotOffered) {
609  PrepareDtls(false, true, rtc::KT_DEFAULT);
610  ASSERT_TRUE(Connect());
611  TestTransfer(0, 1000, 100, false);
612}
613
614// Create two channels with DTLS 1.0 and check ciphers.
615TEST_F(DtlsTransportChannelTest, TestDtls12None) {
616  MAYBE_SKIP_TEST(HaveDtls);
617  SetChannelCount(2);
618  PrepareDtls(true, true, rtc::KT_DEFAULT);
619  SetMaxProtocolVersions(rtc::SSL_PROTOCOL_DTLS_10, rtc::SSL_PROTOCOL_DTLS_10);
620  ASSERT_TRUE(Connect());
621}
622
623// Create two channels with DTLS 1.2 and check ciphers.
624TEST_F(DtlsTransportChannelTest, TestDtls12Both) {
625  MAYBE_SKIP_TEST(HaveDtls);
626  SetChannelCount(2);
627  PrepareDtls(true, true, rtc::KT_DEFAULT);
628  SetMaxProtocolVersions(rtc::SSL_PROTOCOL_DTLS_12, rtc::SSL_PROTOCOL_DTLS_12);
629  ASSERT_TRUE(Connect());
630}
631
632// Create two channels with DTLS 1.0 / DTLS 1.2 and check ciphers.
633TEST_F(DtlsTransportChannelTest, TestDtls12Client1) {
634  MAYBE_SKIP_TEST(HaveDtls);
635  SetChannelCount(2);
636  PrepareDtls(true, true, rtc::KT_DEFAULT);
637  SetMaxProtocolVersions(rtc::SSL_PROTOCOL_DTLS_12, rtc::SSL_PROTOCOL_DTLS_10);
638  ASSERT_TRUE(Connect());
639}
640
641// Create two channels with DTLS 1.2 / DTLS 1.0 and check ciphers.
642TEST_F(DtlsTransportChannelTest, TestDtls12Client2) {
643  MAYBE_SKIP_TEST(HaveDtls);
644  SetChannelCount(2);
645  PrepareDtls(true, true, rtc::KT_DEFAULT);
646  SetMaxProtocolVersions(rtc::SSL_PROTOCOL_DTLS_10, rtc::SSL_PROTOCOL_DTLS_12);
647  ASSERT_TRUE(Connect());
648}
649
650// Connect with DTLS, negotiate DTLS-SRTP, and transfer SRTP using bypass.
651TEST_F(DtlsTransportChannelTest, TestTransferDtlsSrtp) {
652  MAYBE_SKIP_TEST(HaveDtlsSrtp);
653  PrepareDtls(true, true, rtc::KT_DEFAULT);
654  PrepareDtlsSrtp(true, true);
655  ASSERT_TRUE(Connect());
656  TestTransfer(0, 1000, 100, true);
657}
658
659// Connect with DTLS-SRTP, transfer an invalid SRTP packet, and expects -1
660// returned.
661TEST_F(DtlsTransportChannelTest, TestTransferDtlsInvalidSrtpPacket) {
662  MAYBE_SKIP_TEST(HaveDtls);
663  PrepareDtls(true, true, rtc::KT_DEFAULT);
664  PrepareDtlsSrtp(true, true);
665  ASSERT_TRUE(Connect());
666  int result = client1_.SendInvalidSrtpPacket(0, 100);
667  ASSERT_EQ(-1, result);
668}
669
670// Connect with DTLS. A does DTLS-SRTP but B does not.
671TEST_F(DtlsTransportChannelTest, TestTransferDtlsSrtpRejected) {
672  MAYBE_SKIP_TEST(HaveDtlsSrtp);
673  PrepareDtls(true, true, rtc::KT_DEFAULT);
674  PrepareDtlsSrtp(true, false);
675  ASSERT_TRUE(Connect());
676}
677
678// Connect with DTLS. B does DTLS-SRTP but A does not.
679TEST_F(DtlsTransportChannelTest, TestTransferDtlsSrtpNotOffered) {
680  MAYBE_SKIP_TEST(HaveDtlsSrtp);
681  PrepareDtls(true, true, rtc::KT_DEFAULT);
682  PrepareDtlsSrtp(false, true);
683  ASSERT_TRUE(Connect());
684}
685
686// Create two channels with DTLS, negotiate DTLS-SRTP, and transfer bypass SRTP.
687TEST_F(DtlsTransportChannelTest, TestTransferDtlsSrtpTwoChannels) {
688  MAYBE_SKIP_TEST(HaveDtlsSrtp);
689  SetChannelCount(2);
690  PrepareDtls(true, true, rtc::KT_DEFAULT);
691  PrepareDtlsSrtp(true, true);
692  ASSERT_TRUE(Connect());
693  TestTransfer(0, 1000, 100, true);
694  TestTransfer(1, 1000, 100, true);
695}
696
697// Create a single channel with DTLS, and send normal data and SRTP data on it.
698TEST_F(DtlsTransportChannelTest, TestTransferDtlsSrtpDemux) {
699  MAYBE_SKIP_TEST(HaveDtlsSrtp);
700  PrepareDtls(true, true, rtc::KT_DEFAULT);
701  PrepareDtlsSrtp(true, true);
702  ASSERT_TRUE(Connect());
703  TestTransfer(0, 1000, 100, false);
704  TestTransfer(0, 1000, 100, true);
705}
706
707// Testing when the remote is passive.
708TEST_F(DtlsTransportChannelTest, TestTransferDtlsAnswererIsPassive) {
709  MAYBE_SKIP_TEST(HaveDtlsSrtp);
710  SetChannelCount(2);
711  PrepareDtls(true, true, rtc::KT_DEFAULT);
712  PrepareDtlsSrtp(true, true);
713  ASSERT_TRUE(Connect(cricket::CONNECTIONROLE_ACTPASS,
714                      cricket::CONNECTIONROLE_PASSIVE));
715  TestTransfer(0, 1000, 100, true);
716  TestTransfer(1, 1000, 100, true);
717}
718
719// Testing with the legacy DTLS client which doesn't use setup attribute.
720// In this case legacy is the answerer.
721TEST_F(DtlsTransportChannelTest, TestDtlsSetupWithLegacyAsAnswerer) {
722  MAYBE_SKIP_TEST(HaveDtlsSrtp);
723  PrepareDtls(true, true, rtc::KT_DEFAULT);
724  NegotiateWithLegacy();
725  rtc::SSLRole channel1_role;
726  rtc::SSLRole channel2_role;
727  EXPECT_TRUE(client1_.transport()->GetSslRole(&channel1_role));
728  EXPECT_TRUE(client2_.transport()->GetSslRole(&channel2_role));
729  EXPECT_EQ(rtc::SSL_SERVER, channel1_role);
730  EXPECT_EQ(rtc::SSL_CLIENT, channel2_role);
731}
732
733// Testing re offer/answer after the session is estbalished. Roles will be
734// kept same as of the previous negotiation.
735TEST_F(DtlsTransportChannelTest, TestDtlsReOfferFromOfferer) {
736  MAYBE_SKIP_TEST(HaveDtlsSrtp);
737  SetChannelCount(2);
738  PrepareDtls(true, true, rtc::KT_DEFAULT);
739  PrepareDtlsSrtp(true, true);
740  // Initial role for client1 is ACTPASS and client2 is ACTIVE.
741  ASSERT_TRUE(Connect(cricket::CONNECTIONROLE_ACTPASS,
742                      cricket::CONNECTIONROLE_ACTIVE));
743  TestTransfer(0, 1000, 100, true);
744  TestTransfer(1, 1000, 100, true);
745  // Using input roles for the re-offer.
746  Renegotiate(&client1_, cricket::CONNECTIONROLE_ACTPASS,
747              cricket::CONNECTIONROLE_ACTIVE, NF_REOFFER);
748  TestTransfer(0, 1000, 100, true);
749  TestTransfer(1, 1000, 100, true);
750}
751
752TEST_F(DtlsTransportChannelTest, TestDtlsReOfferFromAnswerer) {
753  MAYBE_SKIP_TEST(HaveDtlsSrtp);
754  SetChannelCount(2);
755  PrepareDtls(true, true, rtc::KT_DEFAULT);
756  PrepareDtlsSrtp(true, true);
757  // Initial role for client1 is ACTPASS and client2 is ACTIVE.
758  ASSERT_TRUE(Connect(cricket::CONNECTIONROLE_ACTPASS,
759                      cricket::CONNECTIONROLE_ACTIVE));
760  TestTransfer(0, 1000, 100, true);
761  TestTransfer(1, 1000, 100, true);
762  // Using input roles for the re-offer.
763  Renegotiate(&client2_, cricket::CONNECTIONROLE_PASSIVE,
764              cricket::CONNECTIONROLE_ACTPASS, NF_REOFFER);
765  TestTransfer(0, 1000, 100, true);
766  TestTransfer(1, 1000, 100, true);
767}
768
769// Test that any change in role after the intial setup will result in failure.
770TEST_F(DtlsTransportChannelTest, TestDtlsRoleReversal) {
771  MAYBE_SKIP_TEST(HaveDtlsSrtp);
772  SetChannelCount(2);
773  PrepareDtls(true, true, rtc::KT_DEFAULT);
774  PrepareDtlsSrtp(true, true);
775  ASSERT_TRUE(Connect(cricket::CONNECTIONROLE_ACTPASS,
776                      cricket::CONNECTIONROLE_PASSIVE));
777
778  // Renegotiate from client2 with actpass and client1 as active.
779  Renegotiate(&client2_, cricket::CONNECTIONROLE_ACTPASS,
780              cricket::CONNECTIONROLE_ACTIVE,
781              NF_REOFFER | NF_EXPECT_FAILURE);
782}
783
784// Test that using different setup attributes which results in similar ssl
785// role as the initial negotiation will result in success.
786TEST_F(DtlsTransportChannelTest, TestDtlsReOfferWithDifferentSetupAttr) {
787  MAYBE_SKIP_TEST(HaveDtlsSrtp);
788  SetChannelCount(2);
789  PrepareDtls(true, true, rtc::KT_DEFAULT);
790  PrepareDtlsSrtp(true, true);
791  ASSERT_TRUE(Connect(cricket::CONNECTIONROLE_ACTPASS,
792                      cricket::CONNECTIONROLE_PASSIVE));
793  // Renegotiate from client2 with actpass and client1 as active.
794  Renegotiate(&client2_, cricket::CONNECTIONROLE_ACTIVE,
795              cricket::CONNECTIONROLE_ACTPASS, NF_REOFFER);
796  TestTransfer(0, 1000, 100, true);
797  TestTransfer(1, 1000, 100, true);
798}
799
800// Test that re-negotiation can be started before the clients become connected
801// in the first negotiation.
802TEST_F(DtlsTransportChannelTest, TestRenegotiateBeforeConnect) {
803  MAYBE_SKIP_TEST(HaveDtlsSrtp);
804  SetChannelCount(2);
805  PrepareDtls(true, true, rtc::KT_DEFAULT);
806  PrepareDtlsSrtp(true, true);
807  Negotiate();
808
809  Renegotiate(&client1_, cricket::CONNECTIONROLE_ACTPASS,
810              cricket::CONNECTIONROLE_ACTIVE, NF_REOFFER);
811  bool rv = client1_.Connect(&client2_);
812  EXPECT_TRUE(rv);
813  EXPECT_TRUE_WAIT(
814      client1_.all_channels_writable() && client2_.all_channels_writable(),
815      10000);
816
817  TestTransfer(0, 1000, 100, true);
818  TestTransfer(1, 1000, 100, true);
819}
820
821// Test Certificates state after negotiation but before connection.
822TEST_F(DtlsTransportChannelTest, TestCertificatesBeforeConnect) {
823  MAYBE_SKIP_TEST(HaveDtls);
824  PrepareDtls(true, true, rtc::KT_DEFAULT);
825  Negotiate();
826
827  rtc::scoped_refptr<rtc::RTCCertificate> certificate1;
828  rtc::scoped_refptr<rtc::RTCCertificate> certificate2;
829  rtc::scoped_ptr<rtc::SSLCertificate> remote_cert1;
830  rtc::scoped_ptr<rtc::SSLCertificate> remote_cert2;
831
832  // After negotiation, each side has a distinct local certificate, but still no
833  // remote certificate, because connection has not yet occurred.
834  ASSERT_TRUE(client1_.transport()->GetLocalCertificate(&certificate1));
835  ASSERT_TRUE(client2_.transport()->GetLocalCertificate(&certificate2));
836  ASSERT_NE(certificate1->ssl_certificate().ToPEMString(),
837            certificate2->ssl_certificate().ToPEMString());
838  ASSERT_FALSE(
839      client1_.transport()->GetRemoteSSLCertificate(remote_cert1.accept()));
840  ASSERT_FALSE(remote_cert1 != NULL);
841  ASSERT_FALSE(
842      client2_.transport()->GetRemoteSSLCertificate(remote_cert2.accept()));
843  ASSERT_FALSE(remote_cert2 != NULL);
844}
845
846// Test Certificates state after connection.
847TEST_F(DtlsTransportChannelTest, TestCertificatesAfterConnect) {
848  MAYBE_SKIP_TEST(HaveDtls);
849  PrepareDtls(true, true, rtc::KT_DEFAULT);
850  ASSERT_TRUE(Connect());
851
852  rtc::scoped_refptr<rtc::RTCCertificate> certificate1;
853  rtc::scoped_refptr<rtc::RTCCertificate> certificate2;
854  rtc::scoped_ptr<rtc::SSLCertificate> remote_cert1;
855  rtc::scoped_ptr<rtc::SSLCertificate> remote_cert2;
856
857  // After connection, each side has a distinct local certificate.
858  ASSERT_TRUE(client1_.transport()->GetLocalCertificate(&certificate1));
859  ASSERT_TRUE(client2_.transport()->GetLocalCertificate(&certificate2));
860  ASSERT_NE(certificate1->ssl_certificate().ToPEMString(),
861            certificate2->ssl_certificate().ToPEMString());
862
863  // Each side's remote certificate is the other side's local certificate.
864  ASSERT_TRUE(
865      client1_.transport()->GetRemoteSSLCertificate(remote_cert1.accept()));
866  ASSERT_EQ(remote_cert1->ToPEMString(),
867            certificate2->ssl_certificate().ToPEMString());
868  ASSERT_TRUE(
869      client2_.transport()->GetRemoteSSLCertificate(remote_cert2.accept()));
870  ASSERT_EQ(remote_cert2->ToPEMString(),
871            certificate1->ssl_certificate().ToPEMString());
872}
873