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