blob: fbfccd6844096d0ebd57510d8107e8cc0ce8db7a [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
Guido Urdaneta14bba6e2020-09-25 16:00:51 +020022#include "absl/types/optional.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020023#include "rtc_base/buffer.h"
Steve Anton10542f22019-01-11 09:11:00 -080024#include "rtc_base/openssl_identity.h"
25#include "rtc_base/ssl_identity.h"
26#include "rtc_base/ssl_stream_adapter.h"
Yves Gerey988cc082018-10-23 12:03:01 +020027#include "rtc_base/stream.h"
Guido Urdaneta14bba6e2020-09-25 16:00:51 +020028#include "rtc_base/system/rtc_export.h"
Tommi04482982020-10-05 12:43:53 +000029#include "rtc_base/task_utils/pending_task_safety_flag.h"
30#include "rtc_base/task_utils/repeating_task.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000031
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020032namespace rtc {
33
34// This class was written with OpenSSLAdapter (a socket adapter) as a
35// starting point. It has similar structure and functionality, but uses a
36// "peer-to-peer" mode, verifying the peer's certificate using a digest
37// sent over a secure signaling channel.
38//
39// Static methods to initialize and deinit the SSL library are in
40// OpenSSLAdapter. These should probably be moved out to a neutral class.
41//
42// In a few cases I have factored out some OpenSSLAdapter code into static
43// methods so it can be reused from this class. Eventually that code should
44// probably be moved to a common support class. Unfortunately there remain a
45// few duplicated sections of code. I have not done more restructuring because
46// I did not want to affect existing code that uses OpenSSLAdapter.
47//
48// This class does not support the SSL connection restart feature present in
49// OpenSSLAdapter. I am not entirely sure how the feature is useful and I am
50// not convinced that it works properly.
51//
52// This implementation is careful to disallow data exchange after an SSL error,
53// and it has an explicit SSL_CLOSED state. It should not be possible to send
54// any data in clear after one of the StartSSL methods has been called.
55
56// Look in sslstreamadapter.h for documentation of the methods.
57
Yves Gerey988cc082018-10-23 12:03:01 +020058class SSLCertChain;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020059
60///////////////////////////////////////////////////////////////////////////////
61
Guido Urdaneta14bba6e2020-09-25 16:00:51 +020062// If |allow| has a value, its value determines if legacy TLS protocols are
63// allowed, overriding the default configuration.
64// If |allow| has no value, any previous override is removed and the default
65// configuration is restored.
66RTC_EXPORT void SetAllowLegacyTLSProtocols(const absl::optional<bool>& allow);
67
Benjamin Wright61c5cc82018-10-26 17:50:00 -070068class OpenSSLStreamAdapter final : public SSLStreamAdapter {
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020069 public:
Harald Alvestrand8515d5a2020-03-20 22:51:32 +010070 explicit OpenSSLStreamAdapter(std::unique_ptr<StreamInterface> stream);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020071 ~OpenSSLStreamAdapter() override;
72
Harald Alvestrand8515d5a2020-03-20 22:51:32 +010073 void SetIdentity(std::unique_ptr<SSLIdentity> identity) override;
Sam Zackrisson7e6290d2020-12-10 07:55:28 +000074 OpenSSLIdentity* GetIdentityForTesting() const override;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020075
76 // Default argument is for compatibility
77 void SetServerRole(SSLRole role = SSL_SERVER) override;
78 bool SetPeerCertificateDigest(
79 const std::string& digest_alg,
80 const unsigned char* digest_val,
81 size_t digest_len,
82 SSLPeerCertificateDigestError* error = nullptr) override;
83
Jian Cui0a8798b2017-11-16 16:58:02 -080084 std::unique_ptr<SSLCertChain> GetPeerSSLCertChain() const override;
85
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020086 // Goes from state SSL_NONE to either SSL_CONNECTING or SSL_WAIT, depending
87 // on whether the underlying stream is already open or not.
88 int StartSSL() override;
89 void SetMode(SSLMode mode) override;
90 void SetMaxProtocolVersion(SSLProtocolVersion version) override;
91 void SetInitialRetransmissionTimeout(int timeout_ms) override;
92
93 StreamResult Read(void* data,
94 size_t data_len,
95 size_t* read,
96 int* error) override;
97 StreamResult Write(const void* data,
98 size_t data_len,
99 size_t* written,
100 int* error) override;
101 void Close() override;
102 StreamState GetState() const override;
103
104 // TODO(guoweis): Move this away from a static class method.
105 static std::string SslCipherSuiteToName(int crypto_suite);
106
107 bool GetSslCipherSuite(int* cipher) override;
108
Harald Alvestrand5cb78072019-10-28 09:51:17 +0100109 SSLProtocolVersion GetSslVersion() const override;
110 bool GetSslVersionBytes(int* version) const override;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200111 // Key Extractor interface
112 bool ExportKeyingMaterial(const std::string& label,
113 const uint8_t* context,
114 size_t context_len,
115 bool use_context,
116 uint8_t* result,
117 size_t result_len) override;
118
119 // DTLS-SRTP interface
120 bool SetDtlsSrtpCryptoSuites(const std::vector<int>& crypto_suites) override;
121 bool GetDtlsSrtpCryptoSuite(int* crypto_suite) override;
122
123 bool IsTlsConnected() override;
124
125 // Capabilities interfaces.
126 static bool IsBoringSsl();
127
128 static bool IsAcceptableCipher(int cipher, KeyType key_type);
129 static bool IsAcceptableCipher(const std::string& cipher, KeyType key_type);
130
131 // Use our timeutils.h source of timing in BoringSSL, allowing us to test
132 // using a fake clock.
Benjamin Wrightb19b4972018-10-25 10:46:49 -0700133 static void EnableTimeCallbackForTesting();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200134
135 protected:
136 void OnEvent(StreamInterface* stream, int events, int err) override;
137
138 private:
139 enum SSLState {
140 // Before calling one of the StartSSL methods, data flows
141 // in clear text.
142 SSL_NONE,
Yves Gerey665174f2018-06-19 15:03:05 +0200143 SSL_WAIT, // waiting for the stream to open to start SSL negotiation
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200144 SSL_CONNECTING, // SSL negotiation in progress
Yves Gerey665174f2018-06-19 15:03:05 +0200145 SSL_CONNECTED, // SSL stream successfully established
146 SSL_ERROR, // some SSL error occurred, stream is closed
147 SSL_CLOSED // Clean close
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200148 };
149
Tommi04482982020-10-05 12:43:53 +0000150 void PostEvent(int events, int err);
151 void SetTimeout(int delay_ms);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200152
153 // The following three methods return 0 on success and a negative
154 // error code on failure. The error code may be from OpenSSL or -1
155 // on some other error cases, so it can't really be interpreted
156 // unfortunately.
157
158 // Prepare SSL library, state is SSL_CONNECTING.
159 int BeginSSL();
160 // Perform SSL negotiation steps.
161 int ContinueSSL();
162
163 // Error handler helper. signal is given as true for errors in
164 // asynchronous contexts (when an error method was not returned
165 // through some other method), and in that case an SE_CLOSE event is
166 // raised on the stream with the specified error.
167 // A 0 error means a graceful close, otherwise there is not really enough
168 // context to interpret the error code.
169 // |alert| indicates an alert description (one of the SSL_AD constants) to
170 // send to the remote endpoint when closing the association. If 0, a normal
171 // shutdown will be performed.
172 void Error(const char* context, int err, uint8_t alert, bool signal);
173 void Cleanup(uint8_t alert);
174
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200175 // Flush the input buffers by reading left bytes (for DTLS)
176 void FlushInput(unsigned int left);
177
178 // SSL library configuration
179 SSL_CTX* SetupSSLContext();
180 // Verify the peer certificate matches the signaled digest.
181 bool VerifyPeerCertificate();
David Benjamindc246562017-09-29 12:14:08 -0400182 // SSL certificate verification callback. See
183 // SSL_CTX_set_cert_verify_callback.
184 static int SSLVerifyCallback(X509_STORE_CTX* store, void* arg);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200185
Benjamin Wright5d355542018-10-26 17:57:00 -0700186 bool WaitingToVerifyPeerCertificate() const {
Benjamin Wrightb19b4972018-10-25 10:46:49 -0700187 return GetClientAuthEnabled() && !peer_certificate_verified_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200188 }
189
Benjamin Wright5d355542018-10-26 17:57:00 -0700190 bool HasPeerCertificateDigest() const {
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200191 return !peer_certificate_digest_algorithm_.empty() &&
192 !peer_certificate_digest_value_.empty();
193 }
194
Tommi04482982020-10-05 12:43:53 +0000195 rtc::Thread* const owner_;
196 webrtc::ScopedTaskSafety task_safety_;
197 webrtc::RepeatingTaskHandle timeout_task_;
198
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200199 SSLState state_;
200 SSLRole role_;
201 int ssl_error_code_; // valid when state_ == SSL_ERROR or SSL_CLOSED
202 // Whether the SSL negotiation is blocked on needing to read or
203 // write to the wrapped stream.
204 bool ssl_read_needs_write_;
205 bool ssl_write_needs_read_;
206
207 SSL* ssl_;
208 SSL_CTX* ssl_ctx_;
209
210 // Our key and certificate.
211 std::unique_ptr<OpenSSLIdentity> identity_;
Taylor Brandstetterc3928662018-02-23 13:04:51 -0800212 // The certificate chain that the peer presented. Initially null, until the
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200213 // connection is established.
Jian Cui0a8798b2017-11-16 16:58:02 -0800214 std::unique_ptr<SSLCertChain> peer_cert_chain_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200215 bool peer_certificate_verified_ = false;
216 // The digest of the certificate that the peer must present.
217 Buffer peer_certificate_digest_value_;
218 std::string peer_certificate_digest_algorithm_;
219
220 // The DtlsSrtp ciphers
221 std::string srtp_ciphers_;
222
223 // Do DTLS or not
224 SSLMode ssl_mode_;
225
226 // Max. allowed protocol version
227 SSLProtocolVersion ssl_max_version_;
228
229 // A 50-ms initial timeout ensures rapid setup on fast connections, but may
230 // be too aggressive for low bandwidth links.
231 int dtls_handshake_timeout_ms_ = 50;
Harald Alvestrand13799132020-03-09 19:39:36 +0100232
233 // TODO(https://bugs.webrtc.org/10261): Completely remove this option in M84.
234 const bool support_legacy_tls_protocols_flag_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200235};
236
237/////////////////////////////////////////////////////////////////////////////
238
239} // namespace rtc
240
Steve Anton10542f22019-01-11 09:11:00 -0800241#endif // RTC_BASE_OPENSSL_STREAM_ADAPTER_H_