blob: de20ba93ce1644f51dd1b115225f7848945500eb [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
Steve Anton10542f22019-01-11 09:11:00 -080030#include "rtc_base/ssl_identity.h"
31#include "rtc_base/ssl_stream_adapter.h"
Yves Gerey988cc082018-10-23 12:03:01 +020032#include "rtc_base/stream.h"
Guido Urdaneta14bba6e2020-09-25 16:00:51 +020033#include "rtc_base/system/rtc_export.h"
Tommi04482982020-10-05 12:43:53 +000034#include "rtc_base/task_utils/pending_task_safety_flag.h"
35#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
98 StreamResult Read(void* data,
99 size_t data_len,
100 size_t* read,
101 int* error) override;
102 StreamResult Write(const void* data,
103 size_t data_len,
104 size_t* written,
105 int* error) override;
106 void Close() override;
107 StreamState GetState() const override;
108
109 // TODO(guoweis): Move this away from a static class method.
110 static std::string SslCipherSuiteToName(int crypto_suite);
111
112 bool GetSslCipherSuite(int* cipher) override;
113
Harald Alvestrand5cb78072019-10-28 09:51:17 +0100114 SSLProtocolVersion GetSslVersion() const override;
115 bool GetSslVersionBytes(int* version) const override;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200116 // Key Extractor interface
Ali Tofigh7fa90572022-03-17 15:47:49 +0100117 bool ExportKeyingMaterial(absl::string_view label,
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200118 const uint8_t* context,
119 size_t context_len,
120 bool use_context,
121 uint8_t* result,
122 size_t result_len) override;
123
124 // DTLS-SRTP interface
125 bool SetDtlsSrtpCryptoSuites(const std::vector<int>& crypto_suites) override;
126 bool GetDtlsSrtpCryptoSuite(int* crypto_suite) override;
127
128 bool IsTlsConnected() override;
129
130 // Capabilities interfaces.
131 static bool IsBoringSsl();
132
133 static bool IsAcceptableCipher(int cipher, KeyType key_type);
Ali Tofigh7fa90572022-03-17 15:47:49 +0100134 static bool IsAcceptableCipher(absl::string_view cipher, KeyType key_type);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200135
136 // Use our timeutils.h source of timing in BoringSSL, allowing us to test
137 // using a fake clock.
Benjamin Wrightb19b4972018-10-25 10:46:49 -0700138 static void EnableTimeCallbackForTesting();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200139
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200140 private:
141 enum SSLState {
142 // Before calling one of the StartSSL methods, data flows
143 // in clear text.
144 SSL_NONE,
Yves Gerey665174f2018-06-19 15:03:05 +0200145 SSL_WAIT, // waiting for the stream to open to start SSL negotiation
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200146 SSL_CONNECTING, // SSL negotiation in progress
Yves Gerey665174f2018-06-19 15:03:05 +0200147 SSL_CONNECTED, // SSL stream successfully established
148 SSL_ERROR, // some SSL error occurred, stream is closed
149 SSL_CLOSED // Clean close
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200150 };
151
Niels Möller0131a4d2021-04-16 09:16:21 +0200152 void OnEvent(StreamInterface* stream, int events, int err);
153
Tommi04482982020-10-05 12:43:53 +0000154 void PostEvent(int events, int err);
155 void SetTimeout(int delay_ms);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200156
157 // The following three methods return 0 on success and a negative
158 // error code on failure. The error code may be from OpenSSL or -1
159 // on some other error cases, so it can't really be interpreted
160 // unfortunately.
161
162 // Prepare SSL library, state is SSL_CONNECTING.
163 int BeginSSL();
164 // Perform SSL negotiation steps.
165 int ContinueSSL();
166
167 // Error handler helper. signal is given as true for errors in
168 // asynchronous contexts (when an error method was not returned
169 // through some other method), and in that case an SE_CLOSE event is
170 // raised on the stream with the specified error.
171 // A 0 error means a graceful close, otherwise there is not really enough
172 // context to interpret the error code.
Artem Titov96e3b992021-07-26 16:03:14 +0200173 // `alert` indicates an alert description (one of the SSL_AD constants) to
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200174 // send to the remote endpoint when closing the association. If 0, a normal
175 // shutdown will be performed.
176 void Error(const char* context, int err, uint8_t alert, bool signal);
177 void Cleanup(uint8_t alert);
178
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200179 // Flush the input buffers by reading left bytes (for DTLS)
180 void FlushInput(unsigned int left);
181
182 // SSL library configuration
183 SSL_CTX* SetupSSLContext();
184 // Verify the peer certificate matches the signaled digest.
185 bool VerifyPeerCertificate();
Taylor Brandstetter165c6182020-12-10 16:23:03 -0800186
187#ifdef OPENSSL_IS_BORINGSSL
188 // SSL certificate verification callback. See SSL_CTX_set_custom_verify.
189 static enum ssl_verify_result_t SSLVerifyCallback(SSL* ssl,
190 uint8_t* out_alert);
191#else
David Benjamindc246562017-09-29 12:14:08 -0400192 // SSL certificate verification callback. See
193 // SSL_CTX_set_cert_verify_callback.
194 static int SSLVerifyCallback(X509_STORE_CTX* store, void* arg);
Taylor Brandstetter165c6182020-12-10 16:23:03 -0800195#endif
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200196
Benjamin Wright5d355542018-10-26 17:57:00 -0700197 bool WaitingToVerifyPeerCertificate() const {
Benjamin Wrightb19b4972018-10-25 10:46:49 -0700198 return GetClientAuthEnabled() && !peer_certificate_verified_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200199 }
200
Benjamin Wright5d355542018-10-26 17:57:00 -0700201 bool HasPeerCertificateDigest() const {
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200202 return !peer_certificate_digest_algorithm_.empty() &&
203 !peer_certificate_digest_value_.empty();
204 }
205
Niels Möller0131a4d2021-04-16 09:16:21 +0200206 const std::unique_ptr<StreamInterface> stream_;
207
Tommi04482982020-10-05 12:43:53 +0000208 rtc::Thread* const owner_;
209 webrtc::ScopedTaskSafety task_safety_;
210 webrtc::RepeatingTaskHandle timeout_task_;
211
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200212 SSLState state_;
213 SSLRole role_;
214 int ssl_error_code_; // valid when state_ == SSL_ERROR or SSL_CLOSED
215 // Whether the SSL negotiation is blocked on needing to read or
216 // write to the wrapped stream.
217 bool ssl_read_needs_write_;
218 bool ssl_write_needs_read_;
219
220 SSL* ssl_;
221 SSL_CTX* ssl_ctx_;
222
223 // Our key and certificate.
Taylor Brandstetter165c6182020-12-10 16:23:03 -0800224#ifdef OPENSSL_IS_BORINGSSL
225 std::unique_ptr<BoringSSLIdentity> identity_;
226#else
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200227 std::unique_ptr<OpenSSLIdentity> identity_;
Taylor Brandstetter165c6182020-12-10 16:23:03 -0800228#endif
Taylor Brandstetterc3928662018-02-23 13:04:51 -0800229 // The certificate chain that the peer presented. Initially null, until the
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200230 // connection is established.
Jian Cui0a8798b2017-11-16 16:58:02 -0800231 std::unique_ptr<SSLCertChain> peer_cert_chain_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200232 bool peer_certificate_verified_ = false;
233 // The digest of the certificate that the peer must present.
234 Buffer peer_certificate_digest_value_;
235 std::string peer_certificate_digest_algorithm_;
236
237 // The DtlsSrtp ciphers
238 std::string srtp_ciphers_;
239
240 // Do DTLS or not
241 SSLMode ssl_mode_;
242
243 // Max. allowed protocol version
244 SSLProtocolVersion ssl_max_version_;
245
246 // A 50-ms initial timeout ensures rapid setup on fast connections, but may
247 // be too aggressive for low bandwidth links.
248 int dtls_handshake_timeout_ms_ = 50;
Harald Alvestrand13799132020-03-09 19:39:36 +0100249
250 // TODO(https://bugs.webrtc.org/10261): Completely remove this option in M84.
251 const bool support_legacy_tls_protocols_flag_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200252};
253
254/////////////////////////////////////////////////////////////////////////////
255
256} // namespace rtc
257
Steve Anton10542f22019-01-11 09:11:00 -0800258#endif // RTC_BASE_OPENSSL_STREAM_ADAPTER_H_