dtls_transport.h 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  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. #ifndef P2P_BASE_DTLS_TRANSPORT_H_
  11. #define P2P_BASE_DTLS_TRANSPORT_H_
  12. #include <memory>
  13. #include <string>
  14. #include <vector>
  15. #include "api/crypto/crypto_options.h"
  16. #include "p2p/base/dtls_transport_internal.h"
  17. #include "p2p/base/ice_transport_internal.h"
  18. #include "rtc_base/buffer.h"
  19. #include "rtc_base/buffer_queue.h"
  20. #include "rtc_base/constructor_magic.h"
  21. #include "rtc_base/ssl_stream_adapter.h"
  22. #include "rtc_base/stream.h"
  23. #include "rtc_base/strings/string_builder.h"
  24. #include "rtc_base/synchronization/sequence_checker.h"
  25. #include "rtc_base/system/no_unique_address.h"
  26. #include "rtc_base/thread_checker.h"
  27. namespace rtc {
  28. class PacketTransportInternal;
  29. }
  30. namespace cricket {
  31. // A bridge between a packet-oriented/transport-type interface on
  32. // the bottom and a StreamInterface on the top.
  33. class StreamInterfaceChannel : public rtc::StreamInterface {
  34. public:
  35. explicit StreamInterfaceChannel(IceTransportInternal* ice_transport);
  36. // Push in a packet; this gets pulled out from Read().
  37. bool OnPacketReceived(const char* data, size_t size);
  38. // Implementations of StreamInterface
  39. rtc::StreamState GetState() const override;
  40. void Close() override;
  41. rtc::StreamResult Read(void* buffer,
  42. size_t buffer_len,
  43. size_t* read,
  44. int* error) override;
  45. rtc::StreamResult Write(const void* data,
  46. size_t data_len,
  47. size_t* written,
  48. int* error) override;
  49. private:
  50. RTC_NO_UNIQUE_ADDRESS webrtc::SequenceChecker sequence_checker_;
  51. IceTransportInternal* const ice_transport_; // owned by DtlsTransport
  52. rtc::StreamState state_ RTC_GUARDED_BY(sequence_checker_);
  53. rtc::BufferQueue packets_ RTC_GUARDED_BY(sequence_checker_);
  54. RTC_DISALLOW_COPY_AND_ASSIGN(StreamInterfaceChannel);
  55. };
  56. // This class provides a DTLS SSLStreamAdapter inside a TransportChannel-style
  57. // packet-based interface, wrapping an existing TransportChannel instance
  58. // (e.g a P2PTransportChannel)
  59. // Here's the way this works:
  60. //
  61. // DtlsTransport {
  62. // SSLStreamAdapter* dtls_ {
  63. // StreamInterfaceChannel downward_ {
  64. // IceTransportInternal* ice_transport_;
  65. // }
  66. // }
  67. // }
  68. //
  69. // - Data which comes into DtlsTransport from the underlying
  70. // ice_transport_ via OnReadPacket() is checked for whether it is DTLS
  71. // or not, and if it is, is passed to DtlsTransport::HandleDtlsPacket,
  72. // which pushes it into to downward_. dtls_ is listening for events on
  73. // downward_, so it immediately calls downward_->Read().
  74. //
  75. // - Data written to DtlsTransport is passed either to downward_ or directly
  76. // to ice_transport_, depending on whether DTLS is negotiated and whether
  77. // the flags include PF_SRTP_BYPASS
  78. //
  79. // - The SSLStreamAdapter writes to downward_->Write() which translates it
  80. // into packet writes on ice_transport_.
  81. //
  82. // This class is not thread safe; all methods must be called on the same thread
  83. // as the constructor.
  84. class DtlsTransport : public DtlsTransportInternal {
  85. public:
  86. // |ice_transport| is the ICE transport this DTLS transport is wrapping. It
  87. // must outlive this DTLS transport.
  88. //
  89. // |crypto_options| are the options used for the DTLS handshake. This affects
  90. // whether GCM crypto suites are negotiated.
  91. //
  92. // |event_log| is an optional RtcEventLog for logging state changes. It should
  93. // outlive the DtlsTransport.
  94. explicit DtlsTransport(IceTransportInternal* ice_transport,
  95. const webrtc::CryptoOptions& crypto_options,
  96. webrtc::RtcEventLog* event_log);
  97. ~DtlsTransport() override;
  98. const webrtc::CryptoOptions& crypto_options() const override;
  99. DtlsTransportState dtls_state() const override;
  100. const std::string& transport_name() const override;
  101. int component() const override;
  102. // DTLS is active if a local certificate was set. Otherwise this acts in a
  103. // "passthrough" mode, sending packets directly through the underlying ICE
  104. // transport.
  105. // TODO(deadbeef): Remove this weirdness, and handle it in the upper layers.
  106. bool IsDtlsActive() const override;
  107. // SetLocalCertificate is what makes DTLS active. It must be called before
  108. // SetRemoteFinterprint.
  109. // TODO(deadbeef): Once DtlsTransport no longer has the concept of being
  110. // "active" or not (acting as a passthrough if not active), just require this
  111. // certificate on construction or "Start".
  112. bool SetLocalCertificate(
  113. const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) override;
  114. rtc::scoped_refptr<rtc::RTCCertificate> GetLocalCertificate() const override;
  115. // SetRemoteFingerprint must be called after SetLocalCertificate, and any
  116. // other methods like SetDtlsRole. It's what triggers the actual DTLS setup.
  117. // TODO(deadbeef): Rename to "Start" like in ORTC?
  118. bool SetRemoteFingerprint(const std::string& digest_alg,
  119. const uint8_t* digest,
  120. size_t digest_len) override;
  121. // Called to send a packet (via DTLS, if turned on).
  122. int SendPacket(const char* data,
  123. size_t size,
  124. const rtc::PacketOptions& options,
  125. int flags) override;
  126. bool GetOption(rtc::Socket::Option opt, int* value) override;
  127. bool SetSslMaxProtocolVersion(rtc::SSLProtocolVersion version) override;
  128. // Find out which TLS version was negotiated
  129. bool GetSslVersionBytes(int* version) const override;
  130. // Find out which DTLS-SRTP cipher was negotiated
  131. bool GetSrtpCryptoSuite(int* cipher) override;
  132. bool GetDtlsRole(rtc::SSLRole* role) const override;
  133. bool SetDtlsRole(rtc::SSLRole role) override;
  134. // Find out which DTLS cipher was negotiated
  135. bool GetSslCipherSuite(int* cipher) override;
  136. // Once DTLS has been established, this method retrieves the certificate
  137. // chain in use by the remote peer, for use in external identity
  138. // verification.
  139. std::unique_ptr<rtc::SSLCertChain> GetRemoteSSLCertChain() const override;
  140. // Once DTLS has established (i.e., this ice_transport is writable), this
  141. // method extracts the keys negotiated during the DTLS handshake, for use in
  142. // external encryption. DTLS-SRTP uses this to extract the needed SRTP keys.
  143. // See the SSLStreamAdapter documentation for info on the specific parameters.
  144. bool ExportKeyingMaterial(const std::string& label,
  145. const uint8_t* context,
  146. size_t context_len,
  147. bool use_context,
  148. uint8_t* result,
  149. size_t result_len) override;
  150. IceTransportInternal* ice_transport() override;
  151. // For informational purposes. Tells if the DTLS handshake has finished.
  152. // This may be true even if writable() is false, if the remote fingerprint
  153. // has not yet been verified.
  154. bool IsDtlsConnected();
  155. bool receiving() const override;
  156. bool writable() const override;
  157. int GetError() override;
  158. absl::optional<rtc::NetworkRoute> network_route() const override;
  159. int SetOption(rtc::Socket::Option opt, int value) override;
  160. std::string ToString() const {
  161. const absl::string_view RECEIVING_ABBREV[2] = {"_", "R"};
  162. const absl::string_view WRITABLE_ABBREV[2] = {"_", "W"};
  163. rtc::StringBuilder sb;
  164. sb << "DtlsTransport[" << transport_name_ << "|" << component_ << "|"
  165. << RECEIVING_ABBREV[receiving()] << WRITABLE_ABBREV[writable()] << "]";
  166. return sb.Release();
  167. }
  168. private:
  169. void ConnectToIceTransport();
  170. void OnWritableState(rtc::PacketTransportInternal* transport);
  171. void OnReadPacket(rtc::PacketTransportInternal* transport,
  172. const char* data,
  173. size_t size,
  174. const int64_t& packet_time_us,
  175. int flags);
  176. void OnSentPacket(rtc::PacketTransportInternal* transport,
  177. const rtc::SentPacket& sent_packet);
  178. void OnReadyToSend(rtc::PacketTransportInternal* transport);
  179. void OnReceivingState(rtc::PacketTransportInternal* transport);
  180. void OnDtlsEvent(rtc::StreamInterface* stream_, int sig, int err);
  181. void OnNetworkRouteChanged(absl::optional<rtc::NetworkRoute> network_route);
  182. bool SetupDtls();
  183. void MaybeStartDtls();
  184. bool HandleDtlsPacket(const char* data, size_t size);
  185. void OnDtlsHandshakeError(rtc::SSLHandshakeError error);
  186. void ConfigureHandshakeTimeout();
  187. void set_receiving(bool receiving);
  188. void set_writable(bool writable);
  189. // Sets the DTLS state, signaling if necessary.
  190. void set_dtls_state(DtlsTransportState state);
  191. rtc::ThreadChecker thread_checker_;
  192. std::string transport_name_;
  193. int component_;
  194. DtlsTransportState dtls_state_ = DTLS_TRANSPORT_NEW;
  195. // Underlying ice_transport, not owned by this class.
  196. IceTransportInternal* ice_transport_;
  197. std::unique_ptr<rtc::SSLStreamAdapter> dtls_; // The DTLS stream
  198. StreamInterfaceChannel*
  199. downward_; // Wrapper for ice_transport_, owned by dtls_.
  200. std::vector<int> srtp_ciphers_; // SRTP ciphers to use with DTLS.
  201. bool dtls_active_ = false;
  202. rtc::scoped_refptr<rtc::RTCCertificate> local_certificate_;
  203. absl::optional<rtc::SSLRole> dtls_role_;
  204. rtc::SSLProtocolVersion ssl_max_version_;
  205. webrtc::CryptoOptions crypto_options_;
  206. rtc::Buffer remote_fingerprint_value_;
  207. std::string remote_fingerprint_algorithm_;
  208. // Cached DTLS ClientHello packet that was received before we started the
  209. // DTLS handshake. This could happen if the hello was received before the
  210. // ice transport became writable, or before a remote fingerprint was received.
  211. rtc::Buffer cached_client_hello_;
  212. bool receiving_ = false;
  213. bool writable_ = false;
  214. webrtc::RtcEventLog* const event_log_;
  215. RTC_DISALLOW_COPY_AND_ASSIGN(DtlsTransport);
  216. };
  217. } // namespace cricket
  218. #endif // P2P_BASE_DTLS_TRANSPORT_H_