openssl_stream_adapter.h 8.2 KB

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