openssl_stream_adapter.h 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. /*
  2. * Copyright 2004 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 RTC_BASE_OPENSSL_STREAM_ADAPTER_H_
  11. #define RTC_BASE_OPENSSL_STREAM_ADAPTER_H_
  12. #include <openssl/ossl_typ.h>
  13. #include <stddef.h>
  14. #include <stdint.h>
  15. #include <memory>
  16. #include <string>
  17. #include <vector>
  18. #include "absl/types/optional.h"
  19. #include "rtc_base/buffer.h"
  20. #include "rtc_base/openssl_identity.h"
  21. #include "rtc_base/ssl_identity.h"
  22. #include "rtc_base/ssl_stream_adapter.h"
  23. #include "rtc_base/stream.h"
  24. #include "rtc_base/system/rtc_export.h"
  25. namespace rtc {
  26. // This class was written with OpenSSLAdapter (a socket adapter) as a
  27. // starting point. It has similar structure and functionality, but uses a
  28. // "peer-to-peer" mode, verifying the peer's certificate using a digest
  29. // sent over a secure signaling channel.
  30. //
  31. // Static methods to initialize and deinit the SSL library are in
  32. // OpenSSLAdapter. These should probably be moved out to a neutral class.
  33. //
  34. // In a few cases I have factored out some OpenSSLAdapter code into static
  35. // methods so it can be reused from this class. Eventually that code should
  36. // probably be moved to a common support class. Unfortunately there remain a
  37. // few duplicated sections of code. I have not done more restructuring because
  38. // I did not want to affect existing code that uses OpenSSLAdapter.
  39. //
  40. // This class does not support the SSL connection restart feature present in
  41. // OpenSSLAdapter. I am not entirely sure how the feature is useful and I am
  42. // not convinced that it works properly.
  43. //
  44. // This implementation is careful to disallow data exchange after an SSL error,
  45. // and it has an explicit SSL_CLOSED state. It should not be possible to send
  46. // any data in clear after one of the StartSSL methods has been called.
  47. // Look in sslstreamadapter.h for documentation of the methods.
  48. class SSLCertChain;
  49. ///////////////////////////////////////////////////////////////////////////////
  50. // If |allow| has a value, its value determines if legacy TLS protocols are
  51. // allowed, overriding the default configuration.
  52. // If |allow| has no value, any previous override is removed and the default
  53. // configuration is restored.
  54. RTC_EXPORT void SetAllowLegacyTLSProtocols(const absl::optional<bool>& allow);
  55. class OpenSSLStreamAdapter final : public SSLStreamAdapter {
  56. public:
  57. explicit OpenSSLStreamAdapter(std::unique_ptr<StreamInterface> stream);
  58. ~OpenSSLStreamAdapter() override;
  59. void SetIdentity(std::unique_ptr<SSLIdentity> identity) override;
  60. OpenSSLIdentity* GetIdentityForTesting() const override;
  61. // Default argument is for compatibility
  62. void SetServerRole(SSLRole role = SSL_SERVER) override;
  63. bool SetPeerCertificateDigest(
  64. const std::string& digest_alg,
  65. const unsigned char* digest_val,
  66. size_t digest_len,
  67. SSLPeerCertificateDigestError* error = nullptr) override;
  68. std::unique_ptr<SSLCertChain> GetPeerSSLCertChain() const override;
  69. // Goes from state SSL_NONE to either SSL_CONNECTING or SSL_WAIT, depending
  70. // on whether the underlying stream is already open or not.
  71. int StartSSL() override;
  72. void SetMode(SSLMode mode) override;
  73. void SetMaxProtocolVersion(SSLProtocolVersion version) override;
  74. void SetInitialRetransmissionTimeout(int timeout_ms) override;
  75. StreamResult Read(void* data,
  76. size_t data_len,
  77. size_t* read,
  78. int* error) override;
  79. StreamResult Write(const void* data,
  80. size_t data_len,
  81. size_t* written,
  82. int* error) override;
  83. void Close() override;
  84. StreamState GetState() const override;
  85. // TODO(guoweis): Move this away from a static class method.
  86. static std::string SslCipherSuiteToName(int crypto_suite);
  87. bool GetSslCipherSuite(int* cipher) override;
  88. SSLProtocolVersion GetSslVersion() const override;
  89. bool GetSslVersionBytes(int* version) const override;
  90. // Key Extractor interface
  91. bool ExportKeyingMaterial(const std::string& label,
  92. const uint8_t* context,
  93. size_t context_len,
  94. bool use_context,
  95. uint8_t* result,
  96. size_t result_len) override;
  97. // DTLS-SRTP interface
  98. bool SetDtlsSrtpCryptoSuites(const std::vector<int>& crypto_suites) override;
  99. bool GetDtlsSrtpCryptoSuite(int* crypto_suite) override;
  100. bool IsTlsConnected() override;
  101. // Capabilities interfaces.
  102. static bool IsBoringSsl();
  103. static bool IsAcceptableCipher(int cipher, KeyType key_type);
  104. static bool IsAcceptableCipher(const std::string& cipher, KeyType key_type);
  105. // Use our timeutils.h source of timing in BoringSSL, allowing us to test
  106. // using a fake clock.
  107. static void EnableTimeCallbackForTesting();
  108. protected:
  109. void OnEvent(StreamInterface* stream, int events, int err) override;
  110. private:
  111. enum SSLState {
  112. // Before calling one of the StartSSL methods, data flows
  113. // in clear text.
  114. SSL_NONE,
  115. SSL_WAIT, // waiting for the stream to open to start SSL negotiation
  116. SSL_CONNECTING, // SSL negotiation in progress
  117. SSL_CONNECTED, // SSL stream successfully established
  118. SSL_ERROR, // some SSL error occurred, stream is closed
  119. SSL_CLOSED // Clean close
  120. };
  121. enum { MSG_TIMEOUT = MSG_MAX + 1 };
  122. // The following three methods return 0 on success and a negative
  123. // error code on failure. The error code may be from OpenSSL or -1
  124. // on some other error cases, so it can't really be interpreted
  125. // unfortunately.
  126. // Prepare SSL library, state is SSL_CONNECTING.
  127. int BeginSSL();
  128. // Perform SSL negotiation steps.
  129. int ContinueSSL();
  130. // Error handler helper. signal is given as true for errors in
  131. // asynchronous contexts (when an error method was not returned
  132. // through some other method), and in that case an SE_CLOSE event is
  133. // raised on the stream with the specified error.
  134. // A 0 error means a graceful close, otherwise there is not really enough
  135. // context to interpret the error code.
  136. // |alert| indicates an alert description (one of the SSL_AD constants) to
  137. // send to the remote endpoint when closing the association. If 0, a normal
  138. // shutdown will be performed.
  139. void Error(const char* context, int err, uint8_t alert, bool signal);
  140. void Cleanup(uint8_t alert);
  141. // Override MessageHandler
  142. void OnMessage(Message* msg) override;
  143. // Flush the input buffers by reading left bytes (for DTLS)
  144. void FlushInput(unsigned int left);
  145. // SSL library configuration
  146. SSL_CTX* SetupSSLContext();
  147. // Verify the peer certificate matches the signaled digest.
  148. bool VerifyPeerCertificate();
  149. // SSL certificate verification callback. See
  150. // SSL_CTX_set_cert_verify_callback.
  151. static int SSLVerifyCallback(X509_STORE_CTX* store, void* arg);
  152. bool WaitingToVerifyPeerCertificate() const {
  153. return GetClientAuthEnabled() && !peer_certificate_verified_;
  154. }
  155. bool HasPeerCertificateDigest() const {
  156. return !peer_certificate_digest_algorithm_.empty() &&
  157. !peer_certificate_digest_value_.empty();
  158. }
  159. SSLState state_;
  160. SSLRole role_;
  161. int ssl_error_code_; // valid when state_ == SSL_ERROR or SSL_CLOSED
  162. // Whether the SSL negotiation is blocked on needing to read or
  163. // write to the wrapped stream.
  164. bool ssl_read_needs_write_;
  165. bool ssl_write_needs_read_;
  166. SSL* ssl_;
  167. SSL_CTX* ssl_ctx_;
  168. // Our key and certificate.
  169. std::unique_ptr<OpenSSLIdentity> identity_;
  170. // The certificate chain that the peer presented. Initially null, until the
  171. // connection is established.
  172. std::unique_ptr<SSLCertChain> peer_cert_chain_;
  173. bool peer_certificate_verified_ = false;
  174. // The digest of the certificate that the peer must present.
  175. Buffer peer_certificate_digest_value_;
  176. std::string peer_certificate_digest_algorithm_;
  177. // The DtlsSrtp ciphers
  178. std::string srtp_ciphers_;
  179. // Do DTLS or not
  180. SSLMode ssl_mode_;
  181. // Max. allowed protocol version
  182. SSLProtocolVersion ssl_max_version_;
  183. // A 50-ms initial timeout ensures rapid setup on fast connections, but may
  184. // be too aggressive for low bandwidth links.
  185. int dtls_handshake_timeout_ms_ = 50;
  186. // TODO(https://bugs.webrtc.org/10261): Completely remove this option in M84.
  187. const bool support_legacy_tls_protocols_flag_;
  188. };
  189. /////////////////////////////////////////////////////////////////////////////
  190. } // namespace rtc
  191. #endif // RTC_BASE_OPENSSL_STREAM_ADAPTER_H_