openssl_adapter.h 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  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_ADAPTER_H_
  11. #define RTC_BASE_OPENSSL_ADAPTER_H_
  12. #include <stddef.h>
  13. #include <stdint.h>
  14. #include <memory>
  15. #include <string>
  16. #include <vector>
  17. #include "rtc_base/async_socket.h"
  18. #include "rtc_base/buffer.h"
  19. #include "rtc_base/message_handler.h"
  20. #include "rtc_base/openssl_identity.h"
  21. #include "rtc_base/openssl_session_cache.h"
  22. #include "rtc_base/socket.h"
  23. #include "rtc_base/socket_address.h"
  24. #include "rtc_base/ssl_adapter.h"
  25. #include "rtc_base/ssl_certificate.h"
  26. #include "rtc_base/ssl_identity.h"
  27. #include "rtc_base/ssl_stream_adapter.h"
  28. namespace rtc {
  29. class OpenSSLAdapter final : public SSLAdapter,
  30. public MessageHandlerAutoCleanup {
  31. public:
  32. static bool InitializeSSL();
  33. static bool CleanupSSL();
  34. // Creating an OpenSSLAdapter requires a socket to bind to, an optional
  35. // session cache if you wish to improve performance by caching sessions for
  36. // hostnames you have previously connected to and an optional
  37. // SSLCertificateVerifier which can override any existing trusted roots to
  38. // validate a peer certificate. The cache and verifier are effectively
  39. // immutable after the the SSL connection starts.
  40. explicit OpenSSLAdapter(AsyncSocket* socket,
  41. OpenSSLSessionCache* ssl_session_cache = nullptr,
  42. SSLCertificateVerifier* ssl_cert_verifier = nullptr);
  43. ~OpenSSLAdapter() override;
  44. void SetIgnoreBadCert(bool ignore) override;
  45. void SetAlpnProtocols(const std::vector<std::string>& protos) override;
  46. void SetEllipticCurves(const std::vector<std::string>& curves) override;
  47. void SetMode(SSLMode mode) override;
  48. void SetCertVerifier(SSLCertificateVerifier* ssl_cert_verifier) override;
  49. void SetIdentity(std::unique_ptr<SSLIdentity> identity) override;
  50. void SetRole(SSLRole role) override;
  51. AsyncSocket* Accept(SocketAddress* paddr) override;
  52. int StartSSL(const char* hostname) override;
  53. int Send(const void* pv, size_t cb) override;
  54. int SendTo(const void* pv, size_t cb, const SocketAddress& addr) override;
  55. int Recv(void* pv, size_t cb, int64_t* timestamp) override;
  56. int RecvFrom(void* pv,
  57. size_t cb,
  58. SocketAddress* paddr,
  59. int64_t* timestamp) override;
  60. int Close() override;
  61. // Note that the socket returns ST_CONNECTING while SSL is being negotiated.
  62. ConnState GetState() const override;
  63. bool IsResumedSession() override;
  64. // Creates a new SSL_CTX object, configured for client-to-server usage
  65. // with SSLMode |mode|, and if |enable_cache| is true, with support for
  66. // storing successful sessions so that they can be later resumed.
  67. // OpenSSLAdapterFactory will call this method to create its own internal
  68. // SSL_CTX, and OpenSSLAdapter will also call this when used without a
  69. // factory.
  70. static SSL_CTX* CreateContext(SSLMode mode, bool enable_cache);
  71. protected:
  72. void OnConnectEvent(AsyncSocket* socket) override;
  73. void OnReadEvent(AsyncSocket* socket) override;
  74. void OnWriteEvent(AsyncSocket* socket) override;
  75. void OnCloseEvent(AsyncSocket* socket, int err) override;
  76. private:
  77. enum SSLState {
  78. SSL_NONE,
  79. SSL_WAIT,
  80. SSL_CONNECTING,
  81. SSL_CONNECTED,
  82. SSL_ERROR
  83. };
  84. enum { MSG_TIMEOUT };
  85. int BeginSSL();
  86. int ContinueSSL();
  87. void Error(const char* context, int err, bool signal = true);
  88. void Cleanup();
  89. // Return value and arguments have the same meanings as for Send; |error| is
  90. // an output parameter filled with the result of SSL_get_error.
  91. int DoSslWrite(const void* pv, size_t cb, int* error);
  92. void OnMessage(Message* msg) override;
  93. bool SSLPostConnectionCheck(SSL* ssl, const std::string& host);
  94. #if !defined(NDEBUG)
  95. // In debug builds, logs info about the state of the SSL connection.
  96. static void SSLInfoCallback(const SSL* ssl, int where, int ret);
  97. #endif
  98. static int SSLVerifyCallback(int ok, X509_STORE_CTX* store);
  99. friend class OpenSSLStreamAdapter; // for custom_verify_callback_;
  100. // If the SSL_CTX was created with |enable_cache| set to true, this callback
  101. // will be called when a SSL session has been successfully established,
  102. // to allow its SSL_SESSION* to be cached for later resumption.
  103. static int NewSSLSessionCallback(SSL* ssl, SSL_SESSION* session);
  104. // Optional SSL Shared session cache to improve performance.
  105. OpenSSLSessionCache* ssl_session_cache_ = nullptr;
  106. // Optional SSL Certificate verifier which can be set by a third party.
  107. SSLCertificateVerifier* ssl_cert_verifier_ = nullptr;
  108. // The current connection state of the (d)TLS connection.
  109. SSLState state_;
  110. std::unique_ptr<OpenSSLIdentity> identity_;
  111. // Indicates whethere this is a client or a server.
  112. SSLRole role_;
  113. bool ssl_read_needs_write_;
  114. bool ssl_write_needs_read_;
  115. // This buffer is used if SSL_write fails with SSL_ERROR_WANT_WRITE, which
  116. // means we need to keep retrying with *the same exact data* until it
  117. // succeeds. Afterwards it will be cleared.
  118. Buffer pending_data_;
  119. SSL* ssl_;
  120. // Holds the SSL context, which may be shared if an session cache is provided.
  121. SSL_CTX* ssl_ctx_;
  122. // Hostname of server that is being connected, used for SNI.
  123. std::string ssl_host_name_;
  124. // Set the adapter to DTLS or TLS mode before creating the context.
  125. SSLMode ssl_mode_;
  126. // If true, the server certificate need not match the configured hostname.
  127. bool ignore_bad_cert_;
  128. // List of protocols to be used in the TLS ALPN extension.
  129. std::vector<std::string> alpn_protocols_;
  130. // List of elliptic curves to be used in the TLS elliptic curves extension.
  131. std::vector<std::string> elliptic_curves_;
  132. // Holds the result of the call to run of the ssl_cert_verify_->Verify()
  133. bool custom_cert_verifier_status_;
  134. };
  135. // The OpenSSLAdapterFactory is responsbile for creating multiple new
  136. // OpenSSLAdapters with a shared SSL_CTX and a shared SSL_SESSION cache. The
  137. // SSL_SESSION cache allows existing SSL_SESSIONS to be reused instead of
  138. // recreating them leading to a significant performance improvement.
  139. class OpenSSLAdapterFactory : public SSLAdapterFactory {
  140. public:
  141. OpenSSLAdapterFactory();
  142. ~OpenSSLAdapterFactory() override;
  143. // Set the SSL Mode to use with this factory. This should only be set before
  144. // the first adapter is created with the factory. If it is called after it
  145. // will DCHECK.
  146. void SetMode(SSLMode mode) override;
  147. // Set a custom certificate verifier to be passed down to each instance
  148. // created with this factory. This should only ever be set before the first
  149. // call to the factory and cannot be changed after the fact.
  150. void SetCertVerifier(SSLCertificateVerifier* ssl_cert_verifier) override;
  151. // Constructs a new socket using the shared OpenSSLSessionCache. This means
  152. // existing SSLSessions already in the cache will be reused instead of
  153. // re-created for improved performance.
  154. OpenSSLAdapter* CreateAdapter(AsyncSocket* socket) override;
  155. private:
  156. // Holds the SSLMode (DTLS,TLS) that will be used to set the session cache.
  157. SSLMode ssl_mode_ = SSL_MODE_TLS;
  158. // Holds a cache of existing SSL Sessions.
  159. std::unique_ptr<OpenSSLSessionCache> ssl_session_cache_;
  160. // Provides an optional custom callback for verifying SSL certificates, this
  161. // in currently only used for TLS-TURN connections.
  162. SSLCertificateVerifier* ssl_cert_verifier_ = nullptr;
  163. // TODO(benwright): Remove this when context is moved to OpenSSLCommon.
  164. // Hold a friend class to the OpenSSLAdapter to retrieve the context.
  165. friend class OpenSSLAdapter;
  166. };
  167. std::string TransformAlpnProtocols(const std::vector<std::string>& protos);
  168. } // namespace rtc
  169. #endif // RTC_BASE_OPENSSL_ADAPTER_H_