blob: 3c94ecd2ced93d7c72450fb0df209be59754cb8b [file] [log] [blame]
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001/*
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
Steve Anton10542f22019-01-11 09:11:00 -080011#ifndef RTC_BASE_OPENSSL_STREAM_ADAPTER_H_
12#define RTC_BASE_OPENSSL_STREAM_ADAPTER_H_
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000013
Benjamin Wright19aab2e2018-04-05 15:39:06 -070014#include <openssl/ossl_typ.h>
Yves Gerey988cc082018-10-23 12:03:01 +020015#include <stddef.h>
16#include <stdint.h>
Jonas Olssona4d87372019-07-05 19:08:33 +020017
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020018#include <memory>
Yves Gerey665174f2018-06-19 15:03:05 +020019#include <string>
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020020#include <vector>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000021
Ali Tofigh7fa90572022-03-17 15:47:49 +010022#include "absl/strings/string_view.h"
Guido Urdaneta14bba6e2020-09-25 16:00:51 +020023#include "absl/types/optional.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020024#include "rtc_base/buffer.h"
Taylor Brandstetter165c6182020-12-10 16:23:03 -080025#ifdef OPENSSL_IS_BORINGSSL
26#include "rtc_base/boringssl_identity.h"
27#else
Steve Anton10542f22019-01-11 09:11:00 -080028#include "rtc_base/openssl_identity.h"
Taylor Brandstetter165c6182020-12-10 16:23:03 -080029#endif
Artem Titovc374d112022-06-16 21:27:45 +020030#include "api/task_queue/pending_task_safety_flag.h"
Steve Anton10542f22019-01-11 09:11:00 -080031#include "rtc_base/ssl_identity.h"
32#include "rtc_base/ssl_stream_adapter.h"
Yves Gerey988cc082018-10-23 12:03:01 +020033#include "rtc_base/stream.h"
Guido Urdaneta14bba6e2020-09-25 16:00:51 +020034#include "rtc_base/system/rtc_export.h"
Tommi04482982020-10-05 12:43:53 +000035#include "rtc_base/task_utils/repeating_task.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000036
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020037namespace 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
Yves Gerey988cc082018-10-23 12:03:01 +020063class SSLCertChain;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020064
65///////////////////////////////////////////////////////////////////////////////
66
Artem Titov96e3b992021-07-26 16:03:14 +020067// If `allow` has a value, its value determines if legacy TLS protocols are
Guido Urdaneta14bba6e2020-09-25 16:00:51 +020068// allowed, overriding the default configuration.
Artem Titov96e3b992021-07-26 16:03:14 +020069// If `allow` has no value, any previous override is removed and the default
Guido Urdaneta14bba6e2020-09-25 16:00:51 +020070// configuration is restored.
71RTC_EXPORT void SetAllowLegacyTLSProtocols(const absl::optional<bool>& allow);
72
Benjamin Wright61c5cc82018-10-26 17:50:00 -070073class OpenSSLStreamAdapter final : public SSLStreamAdapter {
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020074 public:
Harald Alvestrand8515d5a2020-03-20 22:51:32 +010075 explicit OpenSSLStreamAdapter(std::unique_ptr<StreamInterface> stream);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020076 ~OpenSSLStreamAdapter() override;
77
Harald Alvestrand8515d5a2020-03-20 22:51:32 +010078 void SetIdentity(std::unique_ptr<SSLIdentity> identity) override;
Taylor Brandstetter165c6182020-12-10 16:23:03 -080079 SSLIdentity* GetIdentityForTesting() const override;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020080
81 // Default argument is for compatibility
82 void SetServerRole(SSLRole role = SSL_SERVER) override;
83 bool SetPeerCertificateDigest(
Ali Tofigh7fa90572022-03-17 15:47:49 +010084 absl::string_view digest_alg,
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020085 const unsigned char* digest_val,
86 size_t digest_len,
87 SSLPeerCertificateDigestError* error = nullptr) override;
88
Jian Cui0a8798b2017-11-16 16:58:02 -080089 std::unique_ptr<SSLCertChain> GetPeerSSLCertChain() const override;
90
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020091 // 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
Harald Alvestrand11840ce2022-11-10 10:50:50 +000098 [[deprecated("bugs.webrtc.org/14632")]] StreamResult
99 Read(void* data, size_t data_len, size_t* read, int* error) override;
100 StreamResult Read(rtc::ArrayView<uint8_t> data,
101 size_t& read,
102 int& error) override;
103 [[deprecated("bugs.webrtc.org/14632")]] StreamResult Write(
104 const void* data,
105 size_t data_len,
106 size_t* written,
107 int* error) override;
108 StreamResult Write(rtc::ArrayView<const uint8_t> data,
109 size_t& written,
110 int& error) override;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200111 void Close() override;
112 StreamState GetState() const override;
113
114 // TODO(guoweis): Move this away from a static class method.
115 static std::string SslCipherSuiteToName(int crypto_suite);
116
117 bool GetSslCipherSuite(int* cipher) override;
118
Harald Alvestrand5cb78072019-10-28 09:51:17 +0100119 SSLProtocolVersion GetSslVersion() const override;
120 bool GetSslVersionBytes(int* version) const override;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200121 // Key Extractor interface
Ali Tofigh7fa90572022-03-17 15:47:49 +0100122 bool ExportKeyingMaterial(absl::string_view label,
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200123 const uint8_t* context,
124 size_t context_len,
125 bool use_context,
126 uint8_t* result,
127 size_t result_len) override;
128
129 // DTLS-SRTP interface
130 bool SetDtlsSrtpCryptoSuites(const std::vector<int>& crypto_suites) override;
131 bool GetDtlsSrtpCryptoSuite(int* crypto_suite) override;
132
133 bool IsTlsConnected() override;
134
135 // Capabilities interfaces.
136 static bool IsBoringSsl();
137
138 static bool IsAcceptableCipher(int cipher, KeyType key_type);
Ali Tofigh7fa90572022-03-17 15:47:49 +0100139 static bool IsAcceptableCipher(absl::string_view cipher, KeyType key_type);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200140
141 // Use our timeutils.h source of timing in BoringSSL, allowing us to test
142 // using a fake clock.
Benjamin Wrightb19b4972018-10-25 10:46:49 -0700143 static void EnableTimeCallbackForTesting();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200144
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200145 private:
146 enum SSLState {
147 // Before calling one of the StartSSL methods, data flows
148 // in clear text.
149 SSL_NONE,
Yves Gerey665174f2018-06-19 15:03:05 +0200150 SSL_WAIT, // waiting for the stream to open to start SSL negotiation
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200151 SSL_CONNECTING, // SSL negotiation in progress
Yves Gerey665174f2018-06-19 15:03:05 +0200152 SSL_CONNECTED, // SSL stream successfully established
153 SSL_ERROR, // some SSL error occurred, stream is closed
154 SSL_CLOSED // Clean close
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200155 };
156
Niels Möller0131a4d2021-04-16 09:16:21 +0200157 void OnEvent(StreamInterface* stream, int events, int err);
158
Tommi04482982020-10-05 12:43:53 +0000159 void PostEvent(int events, int err);
160 void SetTimeout(int delay_ms);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200161
162 // The following three methods return 0 on success and a negative
163 // error code on failure. The error code may be from OpenSSL or -1
164 // on some other error cases, so it can't really be interpreted
165 // unfortunately.
166
167 // Prepare SSL library, state is SSL_CONNECTING.
168 int BeginSSL();
169 // Perform SSL negotiation steps.
170 int ContinueSSL();
171
172 // Error handler helper. signal is given as true for errors in
173 // asynchronous contexts (when an error method was not returned
174 // through some other method), and in that case an SE_CLOSE event is
175 // raised on the stream with the specified error.
176 // A 0 error means a graceful close, otherwise there is not really enough
177 // context to interpret the error code.
Artem Titov96e3b992021-07-26 16:03:14 +0200178 // `alert` indicates an alert description (one of the SSL_AD constants) to
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200179 // send to the remote endpoint when closing the association. If 0, a normal
180 // shutdown will be performed.
Ali Tofigh2ab914c2022-04-13 12:55:15 +0200181 void Error(absl::string_view context, int err, uint8_t alert, bool signal);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200182 void Cleanup(uint8_t alert);
183
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200184 // Flush the input buffers by reading left bytes (for DTLS)
185 void FlushInput(unsigned int left);
186
187 // SSL library configuration
188 SSL_CTX* SetupSSLContext();
189 // Verify the peer certificate matches the signaled digest.
190 bool VerifyPeerCertificate();
Taylor Brandstetter165c6182020-12-10 16:23:03 -0800191
192#ifdef OPENSSL_IS_BORINGSSL
193 // SSL certificate verification callback. See SSL_CTX_set_custom_verify.
194 static enum ssl_verify_result_t SSLVerifyCallback(SSL* ssl,
195 uint8_t* out_alert);
196#else
David Benjamindc246562017-09-29 12:14:08 -0400197 // SSL certificate verification callback. See
198 // SSL_CTX_set_cert_verify_callback.
199 static int SSLVerifyCallback(X509_STORE_CTX* store, void* arg);
Taylor Brandstetter165c6182020-12-10 16:23:03 -0800200#endif
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200201
Benjamin Wright5d355542018-10-26 17:57:00 -0700202 bool WaitingToVerifyPeerCertificate() const {
Benjamin Wrightb19b4972018-10-25 10:46:49 -0700203 return GetClientAuthEnabled() && !peer_certificate_verified_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200204 }
205
Benjamin Wright5d355542018-10-26 17:57:00 -0700206 bool HasPeerCertificateDigest() const {
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200207 return !peer_certificate_digest_algorithm_.empty() &&
208 !peer_certificate_digest_value_.empty();
209 }
210
Niels Möller0131a4d2021-04-16 09:16:21 +0200211 const std::unique_ptr<StreamInterface> stream_;
212
Tommi04482982020-10-05 12:43:53 +0000213 rtc::Thread* const owner_;
214 webrtc::ScopedTaskSafety task_safety_;
215 webrtc::RepeatingTaskHandle timeout_task_;
216
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200217 SSLState state_;
218 SSLRole role_;
219 int ssl_error_code_; // valid when state_ == SSL_ERROR or SSL_CLOSED
220 // Whether the SSL negotiation is blocked on needing to read or
221 // write to the wrapped stream.
222 bool ssl_read_needs_write_;
223 bool ssl_write_needs_read_;
224
225 SSL* ssl_;
226 SSL_CTX* ssl_ctx_;
227
228 // Our key and certificate.
Taylor Brandstetter165c6182020-12-10 16:23:03 -0800229#ifdef OPENSSL_IS_BORINGSSL
230 std::unique_ptr<BoringSSLIdentity> identity_;
231#else
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200232 std::unique_ptr<OpenSSLIdentity> identity_;
Taylor Brandstetter165c6182020-12-10 16:23:03 -0800233#endif
Taylor Brandstetterc3928662018-02-23 13:04:51 -0800234 // The certificate chain that the peer presented. Initially null, until the
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200235 // connection is established.
Jian Cui0a8798b2017-11-16 16:58:02 -0800236 std::unique_ptr<SSLCertChain> peer_cert_chain_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200237 bool peer_certificate_verified_ = false;
238 // The digest of the certificate that the peer must present.
239 Buffer peer_certificate_digest_value_;
240 std::string peer_certificate_digest_algorithm_;
241
242 // The DtlsSrtp ciphers
243 std::string srtp_ciphers_;
244
245 // Do DTLS or not
246 SSLMode ssl_mode_;
247
248 // Max. allowed protocol version
249 SSLProtocolVersion ssl_max_version_;
250
251 // A 50-ms initial timeout ensures rapid setup on fast connections, but may
252 // be too aggressive for low bandwidth links.
253 int dtls_handshake_timeout_ms_ = 50;
Harald Alvestrand13799132020-03-09 19:39:36 +0100254
255 // TODO(https://bugs.webrtc.org/10261): Completely remove this option in M84.
256 const bool support_legacy_tls_protocols_flag_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200257};
258
259/////////////////////////////////////////////////////////////////////////////
260
261} // namespace rtc
262
Steve Anton10542f22019-01-11 09:11:00 -0800263#endif // RTC_BASE_OPENSSL_STREAM_ADAPTER_H_