blob: d5e8b9e63815abc2d78eed02bd798faef9cd5aef [file] [log] [blame]
henrike@webrtc.orgf0488722014-05-13 18:00:261/*
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 17:11:0011#ifndef RTC_BASE_OPENSSL_ADAPTER_H_
12#define RTC_BASE_OPENSSL_ADAPTER_H_
henrike@webrtc.orgf0488722014-05-13 18:00:2613
Taylor Brandstetter165c6182020-12-11 00:23:0314#include <openssl/ossl_typ.h>
Yves Gerey988cc082018-10-23 10:03:0115#include <stddef.h>
16#include <stdint.h>
Jonas Olssona4d87372019-07-05 17:08:3317
Benjamin Wright19aab2e2018-04-05 22:39:0618#include <memory>
Henrik Kjellanderec78f1c2017-06-29 05:52:5019#include <string>
Benjamin Wright19aab2e2018-04-05 22:39:0620#include <vector>
21
Ali Tofigh7fa90572022-03-17 14:47:4922#include "absl/strings/string_view.h"
Yves Gerey988cc082018-10-23 10:03:0123#include "rtc_base/buffer.h"
Steve Anton10542f22019-01-11 17:11:0024#include "rtc_base/message_handler.h"
Taylor Brandstetter165c6182020-12-11 00:23:0325#ifdef OPENSSL_IS_BORINGSSL
26#include "rtc_base/boringssl_identity.h"
27#else
Steve Anton10542f22019-01-11 17:11:0028#include "rtc_base/openssl_identity.h"
Taylor Brandstetter165c6182020-12-11 00:23:0329#endif
Steve Anton10542f22019-01-11 17:11:0030#include "rtc_base/openssl_session_cache.h"
Yves Gerey988cc082018-10-23 10:03:0131#include "rtc_base/socket.h"
Steve Anton10542f22019-01-11 17:11:0032#include "rtc_base/socket_address.h"
33#include "rtc_base/ssl_adapter.h"
34#include "rtc_base/ssl_certificate.h"
35#include "rtc_base/ssl_identity.h"
36#include "rtc_base/ssl_stream_adapter.h"
henrike@webrtc.orgf0488722014-05-13 18:00:2637
Henrik Kjellanderec78f1c2017-06-29 05:52:5038namespace rtc {
39
Tomas Gunnarssonabdb4702020-09-05 16:43:3640class OpenSSLAdapter final : public SSLAdapter,
41 public MessageHandlerAutoCleanup {
Justin Uberti1d445502017-08-15 00:04:3442 public:
Benjamin Wrightd6f86e82018-05-08 20:12:2543 static bool InitializeSSL();
Henrik Kjellanderec78f1c2017-06-29 05:52:5044 static bool CleanupSSL();
45
Benjamin Wrightd6f86e82018-05-08 20:12:2546 // Creating an OpenSSLAdapter requires a socket to bind to, an optional
47 // session cache if you wish to improve performance by caching sessions for
48 // hostnames you have previously connected to and an optional
49 // SSLCertificateVerifier which can override any existing trusted roots to
50 // validate a peer certificate. The cache and verifier are effectively
51 // immutable after the the SSL connection starts.
Niels Möllerd0b88792021-08-12 08:32:3052 explicit OpenSSLAdapter(Socket* socket,
Benjamin Wrightd6f86e82018-05-08 20:12:2553 OpenSSLSessionCache* ssl_session_cache = nullptr,
54 SSLCertificateVerifier* ssl_cert_verifier = nullptr);
Henrik Kjellanderec78f1c2017-06-29 05:52:5055 ~OpenSSLAdapter() override;
56
Sergey Silkin9c147dd2018-09-12 10:45:3857 void SetIgnoreBadCert(bool ignore) override;
58 void SetAlpnProtocols(const std::vector<std::string>& protos) override;
59 void SetEllipticCurves(const std::vector<std::string>& curves) override;
Henrik Kjellanderec78f1c2017-06-29 05:52:5060 void SetMode(SSLMode mode) override;
Benjamin Wrightd6f86e82018-05-08 20:12:2561 void SetCertVerifier(SSLCertificateVerifier* ssl_cert_verifier) override;
Harald Alvestrand8515d5a2020-03-20 21:51:3262 void SetIdentity(std::unique_ptr<SSLIdentity> identity) override;
Steve Anton786de702017-08-17 22:15:4663 void SetRole(SSLRole role) override;
Ali Tofigh2ab914c2022-04-13 10:55:1564 int StartSSL(absl::string_view hostname) override;
Henrik Kjellanderec78f1c2017-06-29 05:52:5065 int Send(const void* pv, size_t cb) override;
66 int SendTo(const void* pv, size_t cb, const SocketAddress& addr) override;
67 int Recv(void* pv, size_t cb, int64_t* timestamp) override;
68 int RecvFrom(void* pv,
69 size_t cb,
70 SocketAddress* paddr,
71 int64_t* timestamp) override;
72 int Close() override;
Henrik Kjellanderec78f1c2017-06-29 05:52:5073 // Note that the socket returns ST_CONNECTING while SSL is being negotiated.
74 ConnState GetState() const override;
Justin Uberti1d445502017-08-15 00:04:3475 bool IsResumedSession() override;
Justin Uberti1d445502017-08-15 00:04:3476 // Creates a new SSL_CTX object, configured for client-to-server usage
Artem Titov96e3b992021-07-26 14:03:1477 // with SSLMode `mode`, and if `enable_cache` is true, with support for
Justin Uberti1d445502017-08-15 00:04:3478 // storing successful sessions so that they can be later resumed.
79 // OpenSSLAdapterFactory will call this method to create its own internal
80 // SSL_CTX, and OpenSSLAdapter will also call this when used without a
81 // factory.
82 static SSL_CTX* CreateContext(SSLMode mode, bool enable_cache);
Henrik Kjellanderec78f1c2017-06-29 05:52:5083
Justin Uberti1d445502017-08-15 00:04:3484 protected:
Niels Möllerd0b88792021-08-12 08:32:3085 void OnConnectEvent(Socket* socket) override;
86 void OnReadEvent(Socket* socket) override;
87 void OnWriteEvent(Socket* socket) override;
88 void OnCloseEvent(Socket* socket, int err) override;
Justin Uberti1d445502017-08-15 00:04:3489
90 private:
Vojin Ilicf11f0e02021-06-30 12:22:1191 class EarlyExitCatcher {
92 public:
93 EarlyExitCatcher(OpenSSLAdapter& adapter_ptr);
94 void disable();
95 ~EarlyExitCatcher();
96
97 private:
98 bool disabled_ = false;
99 OpenSSLAdapter& adapter_ptr_;
100 };
Henrik Kjellanderec78f1c2017-06-29 05:52:50101 enum SSLState {
Yves Gerey665174f2018-06-19 13:03:05102 SSL_NONE,
103 SSL_WAIT,
104 SSL_CONNECTING,
105 SSL_CONNECTED,
106 SSL_ERROR
Henrik Kjellanderec78f1c2017-06-29 05:52:50107 };
108
109 enum { MSG_TIMEOUT };
110
111 int BeginSSL();
112 int ContinueSSL();
Ali Tofigh2ab914c2022-04-13 10:55:15113 void Error(absl::string_view context, int err, bool signal = true);
Henrik Kjellanderec78f1c2017-06-29 05:52:50114 void Cleanup();
115
Artem Titov96e3b992021-07-26 14:03:14116 // Return value and arguments have the same meanings as for Send; `error` is
Henrik Kjellanderec78f1c2017-06-29 05:52:50117 // an output parameter filled with the result of SSL_get_error.
118 int DoSslWrite(const void* pv, size_t cb, int* error);
Henrik Kjellanderec78f1c2017-06-29 05:52:50119 void OnMessage(Message* msg) override;
Ali Tofigh7fa90572022-03-17 14:47:49120 bool SSLPostConnectionCheck(SSL* ssl, absl::string_view host);
Benjamin Wright9201d1a2018-04-05 19:12:26121
Henrik Kjellanderec78f1c2017-06-29 05:52:50122#if !defined(NDEBUG)
Justin Uberti1d445502017-08-15 00:04:34123 // In debug builds, logs info about the state of the SSL connection.
124 static void SSLInfoCallback(const SSL* ssl, int where, int ret);
Henrik Kjellanderec78f1c2017-06-29 05:52:50125#endif
Taylor Brandstetter165c6182020-12-11 00:23:03126
127#if defined(OPENSSL_IS_BORINGSSL) && \
128 defined(WEBRTC_EXCLUDE_BUILT_IN_SSL_ROOT_CERTS)
129 static enum ssl_verify_result_t SSLVerifyCallback(SSL* ssl,
130 uint8_t* out_alert);
131 enum ssl_verify_result_t SSLVerifyInternal(SSL* ssl, uint8_t* out_alert);
132#else
Henrik Kjellanderec78f1c2017-06-29 05:52:50133 static int SSLVerifyCallback(int ok, X509_STORE_CTX* store);
Harald Alvestrandb32650e2021-09-10 08:03:22134 // Call a custom verifier, if installed.
135 // Returns 1 on success, `status_on_error` on error or verification failure.
136 int SSLVerifyInternal(int status_on_error, SSL* ssl, X509_STORE_CTX* store);
Taylor Brandstetter165c6182020-12-11 00:23:03137#endif
Henrik Kjellanderec78f1c2017-06-29 05:52:50138 friend class OpenSSLStreamAdapter; // for custom_verify_callback_;
139
Artem Titov96e3b992021-07-26 14:03:14140 // If the SSL_CTX was created with `enable_cache` set to true, this callback
Justin Uberti1d445502017-08-15 00:04:34141 // will be called when a SSL session has been successfully established,
142 // to allow its SSL_SESSION* to be cached for later resumption.
143 static int NewSSLSessionCallback(SSL* ssl, SSL_SESSION* session);
144
Benjamin Wrightd6f86e82018-05-08 20:12:25145 // Optional SSL Shared session cache to improve performance.
Benjamin Wright19aab2e2018-04-05 22:39:06146 OpenSSLSessionCache* ssl_session_cache_ = nullptr;
Benjamin Wrightd6f86e82018-05-08 20:12:25147 // Optional SSL Certificate verifier which can be set by a third party.
148 SSLCertificateVerifier* ssl_cert_verifier_ = nullptr;
149 // The current connection state of the (d)TLS connection.
Henrik Kjellanderec78f1c2017-06-29 05:52:50150 SSLState state_;
Taylor Brandstetter165c6182020-12-11 00:23:03151
152#ifdef OPENSSL_IS_BORINGSSL
153 std::unique_ptr<BoringSSLIdentity> identity_;
154#else
Steve Anton786de702017-08-17 22:15:46155 std::unique_ptr<OpenSSLIdentity> identity_;
Taylor Brandstetter165c6182020-12-11 00:23:03156#endif
Benjamin Wrightd6f86e82018-05-08 20:12:25157 // Indicates whethere this is a client or a server.
Steve Anton786de702017-08-17 22:15:46158 SSLRole role_;
Henrik Kjellanderec78f1c2017-06-29 05:52:50159 bool ssl_read_needs_write_;
160 bool ssl_write_needs_read_;
Henrik Kjellanderec78f1c2017-06-29 05:52:50161 // This buffer is used if SSL_write fails with SSL_ERROR_WANT_WRITE, which
162 // means we need to keep retrying with *the same exact data* until it
163 // succeeds. Afterwards it will be cleared.
164 Buffer pending_data_;
Henrik Kjellanderec78f1c2017-06-29 05:52:50165 SSL* ssl_;
Benjamin Wrightd6f86e82018-05-08 20:12:25166 // Holds the SSL context, which may be shared if an session cache is provided.
Henrik Kjellanderec78f1c2017-06-29 05:52:50167 SSL_CTX* ssl_ctx_;
Benjamin Wrightd6f86e82018-05-08 20:12:25168 // Hostname of server that is being connected, used for SNI.
Henrik Kjellanderec78f1c2017-06-29 05:52:50169 std::string ssl_host_name_;
Benjamin Wrightd6f86e82018-05-08 20:12:25170 // Set the adapter to DTLS or TLS mode before creating the context.
Henrik Kjellanderec78f1c2017-06-29 05:52:50171 SSLMode ssl_mode_;
Sergey Silkin9c147dd2018-09-12 10:45:38172 // If true, the server certificate need not match the configured hostname.
173 bool ignore_bad_cert_;
174 // List of protocols to be used in the TLS ALPN extension.
175 std::vector<std::string> alpn_protocols_;
176 // List of elliptic curves to be used in the TLS elliptic curves extension.
177 std::vector<std::string> elliptic_curves_;
Benjamin Wrightd6f86e82018-05-08 20:12:25178 // Holds the result of the call to run of the ssl_cert_verify_->Verify()
179 bool custom_cert_verifier_status_;
Henrik Kjellanderec78f1c2017-06-29 05:52:50180};
181
Benjamin Wright19aab2e2018-04-05 22:39:06182// The OpenSSLAdapterFactory is responsbile for creating multiple new
183// OpenSSLAdapters with a shared SSL_CTX and a shared SSL_SESSION cache. The
184// SSL_SESSION cache allows existing SSL_SESSIONS to be reused instead of
185// recreating them leading to a significant performance improvement.
Justin Uberti1d445502017-08-15 00:04:34186class OpenSSLAdapterFactory : public SSLAdapterFactory {
187 public:
188 OpenSSLAdapterFactory();
189 ~OpenSSLAdapterFactory() override;
Benjamin Wright19aab2e2018-04-05 22:39:06190 // Set the SSL Mode to use with this factory. This should only be set before
191 // the first adapter is created with the factory. If it is called after it
192 // will DCHECK.
Justin Uberti1d445502017-08-15 00:04:34193 void SetMode(SSLMode mode) override;
Niels Möllerac9a2882021-10-20 13:25:09194
Benjamin Wrightd6f86e82018-05-08 20:12:25195 // Set a custom certificate verifier to be passed down to each instance
196 // created with this factory. This should only ever be set before the first
197 // call to the factory and cannot be changed after the fact.
198 void SetCertVerifier(SSLCertificateVerifier* ssl_cert_verifier) override;
Niels Möllerac9a2882021-10-20 13:25:09199
200 void SetIdentity(std::unique_ptr<SSLIdentity> identity) override;
201
202 // Choose whether the socket acts as a server socket or client socket.
203 void SetRole(SSLRole role) override;
204
205 // Methods that control server certificate verification, used in unit tests.
206 // Do not call these methods in production code.
207 void SetIgnoreBadCert(bool ignore) override;
208
Benjamin Wright19aab2e2018-04-05 22:39:06209 // Constructs a new socket using the shared OpenSSLSessionCache. This means
210 // existing SSLSessions already in the cache will be reused instead of
211 // re-created for improved performance.
Niels Möllerd0b88792021-08-12 08:32:30212 OpenSSLAdapter* CreateAdapter(Socket* socket) override;
Henrik Kjellanderc0362762017-06-29 06:03:04213
Justin Uberti1d445502017-08-15 00:04:34214 private:
Benjamin Wright19aab2e2018-04-05 22:39:06215 // Holds the SSLMode (DTLS,TLS) that will be used to set the session cache.
216 SSLMode ssl_mode_ = SSL_MODE_TLS;
Niels Möllerac9a2882021-10-20 13:25:09217 SSLRole ssl_role_ = SSL_CLIENT;
218 bool ignore_bad_cert_ = false;
219
220 std::unique_ptr<SSLIdentity> identity_;
221
Benjamin Wright19aab2e2018-04-05 22:39:06222 // Holds a cache of existing SSL Sessions.
223 std::unique_ptr<OpenSSLSessionCache> ssl_session_cache_;
Benjamin Wrightd6f86e82018-05-08 20:12:25224 // Provides an optional custom callback for verifying SSL certificates, this
225 // in currently only used for TLS-TURN connections.
226 SSLCertificateVerifier* ssl_cert_verifier_ = nullptr;
Benjamin Wright19aab2e2018-04-05 22:39:06227 // TODO(benwright): Remove this when context is moved to OpenSSLCommon.
228 // Hold a friend class to the OpenSSLAdapter to retrieve the context.
Justin Uberti1d445502017-08-15 00:04:34229 friend class OpenSSLAdapter;
Justin Uberti1d445502017-08-15 00:04:34230};
231
Vojin Ilicf11f0e02021-06-30 12:22:11232// The EarlyExitCatcher is responsible for calling OpenSSLAdapter::Cleanup on
233// destruction. By doing this we have scoped cleanup which can be disabled if
234// there were no errors, aka early exits.
235
Benjamin Wrightd6f86e82018-05-08 20:12:25236std::string TransformAlpnProtocols(const std::vector<std::string>& protos);
237
Justin Uberti1d445502017-08-15 00:04:34238} // namespace rtc
239
Steve Anton10542f22019-01-11 17:11:00240#endif // RTC_BASE_OPENSSL_ADAPTER_H_