blob: 8d42967c71c54842df2ca2d499393f4da0970d66 [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_ADAPTER_H_
12#define RTC_BASE_OPENSSL_ADAPTER_H_
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000013
Taylor Brandstetter165c6182020-12-10 16:23:03 -080014#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
Benjamin Wright19aab2e2018-04-05 15:39:06 -070018#include <memory>
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020019#include <string>
Benjamin Wright19aab2e2018-04-05 15:39:06 -070020#include <vector>
21
Steve Anton10542f22019-01-11 09:11:00 -080022#include "rtc_base/async_socket.h"
Yves Gerey988cc082018-10-23 12:03:01 +020023#include "rtc_base/buffer.h"
Steve Anton10542f22019-01-11 09:11:00 -080024#include "rtc_base/message_handler.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/openssl_session_cache.h"
Yves Gerey988cc082018-10-23 12:03:01 +020031#include "rtc_base/socket.h"
Steve Anton10542f22019-01-11 09:11:00 -080032#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:26 +000037
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020038namespace rtc {
39
Tomas Gunnarssonabdb4702020-09-05 18:43:36 +020040class OpenSSLAdapter final : public SSLAdapter,
41 public MessageHandlerAutoCleanup {
Justin Uberti1d445502017-08-14 17:04:34 -070042 public:
Benjamin Wrightd6f86e82018-05-08 13:12:25 -070043 static bool InitializeSSL();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020044 static bool CleanupSSL();
45
Benjamin Wrightd6f86e82018-05-08 13:12:25 -070046 // 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.
Justin Uberti1d445502017-08-14 17:04:34 -070052 explicit OpenSSLAdapter(AsyncSocket* socket,
Benjamin Wrightd6f86e82018-05-08 13:12:25 -070053 OpenSSLSessionCache* ssl_session_cache = nullptr,
54 SSLCertificateVerifier* ssl_cert_verifier = nullptr);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020055 ~OpenSSLAdapter() override;
56
Sergey Silkin9c147dd2018-09-12 10:45:38 +000057 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 07:52:50 +020060 void SetMode(SSLMode mode) override;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -070061 void SetCertVerifier(SSLCertificateVerifier* ssl_cert_verifier) override;
Harald Alvestrand8515d5a2020-03-20 22:51:32 +010062 void SetIdentity(std::unique_ptr<SSLIdentity> identity) override;
Steve Anton786de702017-08-17 15:15:46 -070063 void SetRole(SSLRole role) override;
64 AsyncSocket* Accept(SocketAddress* paddr) override;
Mirko Bonadei2d2c2942020-04-11 00:01:43 +020065 int StartSSL(const char* hostname) override;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020066 int Send(const void* pv, size_t cb) override;
67 int SendTo(const void* pv, size_t cb, const SocketAddress& addr) override;
68 int Recv(void* pv, size_t cb, int64_t* timestamp) override;
69 int RecvFrom(void* pv,
70 size_t cb,
71 SocketAddress* paddr,
72 int64_t* timestamp) override;
73 int Close() override;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020074 // Note that the socket returns ST_CONNECTING while SSL is being negotiated.
75 ConnState GetState() const override;
Justin Uberti1d445502017-08-14 17:04:34 -070076 bool IsResumedSession() override;
Justin Uberti1d445502017-08-14 17:04:34 -070077 // Creates a new SSL_CTX object, configured for client-to-server usage
Artem Titov96e3b992021-07-26 16:03:14 +020078 // with SSLMode `mode`, and if `enable_cache` is true, with support for
Justin Uberti1d445502017-08-14 17:04:34 -070079 // storing successful sessions so that they can be later resumed.
80 // OpenSSLAdapterFactory will call this method to create its own internal
81 // SSL_CTX, and OpenSSLAdapter will also call this when used without a
82 // factory.
83 static SSL_CTX* CreateContext(SSLMode mode, bool enable_cache);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020084
Justin Uberti1d445502017-08-14 17:04:34 -070085 protected:
86 void OnConnectEvent(AsyncSocket* socket) override;
87 void OnReadEvent(AsyncSocket* socket) override;
88 void OnWriteEvent(AsyncSocket* socket) override;
89 void OnCloseEvent(AsyncSocket* socket, int err) override;
90
91 private:
Vojin Ilicf11f0e02021-06-30 14:22:11 +020092 class EarlyExitCatcher {
93 public:
94 EarlyExitCatcher(OpenSSLAdapter& adapter_ptr);
95 void disable();
96 ~EarlyExitCatcher();
97
98 private:
99 bool disabled_ = false;
100 OpenSSLAdapter& adapter_ptr_;
101 };
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200102 enum SSLState {
Yves Gerey665174f2018-06-19 15:03:05 +0200103 SSL_NONE,
104 SSL_WAIT,
105 SSL_CONNECTING,
106 SSL_CONNECTED,
107 SSL_ERROR
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200108 };
109
110 enum { MSG_TIMEOUT };
111
112 int BeginSSL();
113 int ContinueSSL();
114 void Error(const char* context, int err, bool signal = true);
115 void Cleanup();
116
Artem Titov96e3b992021-07-26 16:03:14 +0200117 // Return value and arguments have the same meanings as for Send; `error` is
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200118 // an output parameter filled with the result of SSL_get_error.
119 int DoSslWrite(const void* pv, size_t cb, int* error);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200120 void OnMessage(Message* msg) override;
Benjamin Wright9201d1a2018-04-05 12:12:26 -0700121 bool SSLPostConnectionCheck(SSL* ssl, const std::string& host);
122
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200123#if !defined(NDEBUG)
Justin Uberti1d445502017-08-14 17:04:34 -0700124 // In debug builds, logs info about the state of the SSL connection.
125 static void SSLInfoCallback(const SSL* ssl, int where, int ret);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200126#endif
Taylor Brandstetter165c6182020-12-10 16:23:03 -0800127
128#if defined(OPENSSL_IS_BORINGSSL) && \
129 defined(WEBRTC_EXCLUDE_BUILT_IN_SSL_ROOT_CERTS)
130 static enum ssl_verify_result_t SSLVerifyCallback(SSL* ssl,
131 uint8_t* out_alert);
132 enum ssl_verify_result_t SSLVerifyInternal(SSL* ssl, uint8_t* out_alert);
133#else
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200134 static int SSLVerifyCallback(int ok, X509_STORE_CTX* store);
Taylor Brandstetter165c6182020-12-10 16:23:03 -0800135 int SSLVerifyInternal(int ok, SSL* ssl, X509_STORE_CTX* store);
136#endif
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200137 friend class OpenSSLStreamAdapter; // for custom_verify_callback_;
138
Artem Titov96e3b992021-07-26 16:03:14 +0200139 // If the SSL_CTX was created with `enable_cache` set to true, this callback
Justin Uberti1d445502017-08-14 17:04:34 -0700140 // will be called when a SSL session has been successfully established,
141 // to allow its SSL_SESSION* to be cached for later resumption.
142 static int NewSSLSessionCallback(SSL* ssl, SSL_SESSION* session);
143
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700144 // Optional SSL Shared session cache to improve performance.
Benjamin Wright19aab2e2018-04-05 15:39:06 -0700145 OpenSSLSessionCache* ssl_session_cache_ = nullptr;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700146 // Optional SSL Certificate verifier which can be set by a third party.
147 SSLCertificateVerifier* ssl_cert_verifier_ = nullptr;
148 // The current connection state of the (d)TLS connection.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200149 SSLState state_;
Taylor Brandstetter165c6182020-12-10 16:23:03 -0800150
151#ifdef OPENSSL_IS_BORINGSSL
152 std::unique_ptr<BoringSSLIdentity> identity_;
153#else
Steve Anton786de702017-08-17 15:15:46 -0700154 std::unique_ptr<OpenSSLIdentity> identity_;
Taylor Brandstetter165c6182020-12-10 16:23:03 -0800155#endif
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700156 // Indicates whethere this is a client or a server.
Steve Anton786de702017-08-17 15:15:46 -0700157 SSLRole role_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200158 bool ssl_read_needs_write_;
159 bool ssl_write_needs_read_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200160 // This buffer is used if SSL_write fails with SSL_ERROR_WANT_WRITE, which
161 // means we need to keep retrying with *the same exact data* until it
162 // succeeds. Afterwards it will be cleared.
163 Buffer pending_data_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200164 SSL* ssl_;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700165 // Holds the SSL context, which may be shared if an session cache is provided.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200166 SSL_CTX* ssl_ctx_;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700167 // Hostname of server that is being connected, used for SNI.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200168 std::string ssl_host_name_;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700169 // Set the adapter to DTLS or TLS mode before creating the context.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200170 SSLMode ssl_mode_;
Sergey Silkin9c147dd2018-09-12 10:45:38 +0000171 // If true, the server certificate need not match the configured hostname.
172 bool ignore_bad_cert_;
173 // List of protocols to be used in the TLS ALPN extension.
174 std::vector<std::string> alpn_protocols_;
175 // List of elliptic curves to be used in the TLS elliptic curves extension.
176 std::vector<std::string> elliptic_curves_;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700177 // Holds the result of the call to run of the ssl_cert_verify_->Verify()
178 bool custom_cert_verifier_status_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200179};
180
Benjamin Wright19aab2e2018-04-05 15:39:06 -0700181// The OpenSSLAdapterFactory is responsbile for creating multiple new
182// OpenSSLAdapters with a shared SSL_CTX and a shared SSL_SESSION cache. The
183// SSL_SESSION cache allows existing SSL_SESSIONS to be reused instead of
184// recreating them leading to a significant performance improvement.
Justin Uberti1d445502017-08-14 17:04:34 -0700185class OpenSSLAdapterFactory : public SSLAdapterFactory {
186 public:
187 OpenSSLAdapterFactory();
188 ~OpenSSLAdapterFactory() override;
Benjamin Wright19aab2e2018-04-05 15:39:06 -0700189 // Set the SSL Mode to use with this factory. This should only be set before
190 // the first adapter is created with the factory. If it is called after it
191 // will DCHECK.
Justin Uberti1d445502017-08-14 17:04:34 -0700192 void SetMode(SSLMode mode) override;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700193 // Set a custom certificate verifier to be passed down to each instance
194 // created with this factory. This should only ever be set before the first
195 // call to the factory and cannot be changed after the fact.
196 void SetCertVerifier(SSLCertificateVerifier* ssl_cert_verifier) override;
Benjamin Wright19aab2e2018-04-05 15:39:06 -0700197 // Constructs a new socket using the shared OpenSSLSessionCache. This means
198 // existing SSLSessions already in the cache will be reused instead of
199 // re-created for improved performance.
Justin Uberti1d445502017-08-14 17:04:34 -0700200 OpenSSLAdapter* CreateAdapter(AsyncSocket* socket) override;
Henrik Kjellanderc0362762017-06-29 08:03:04 +0200201
Justin Uberti1d445502017-08-14 17:04:34 -0700202 private:
Benjamin Wright19aab2e2018-04-05 15:39:06 -0700203 // Holds the SSLMode (DTLS,TLS) that will be used to set the session cache.
204 SSLMode ssl_mode_ = SSL_MODE_TLS;
205 // Holds a cache of existing SSL Sessions.
206 std::unique_ptr<OpenSSLSessionCache> ssl_session_cache_;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700207 // Provides an optional custom callback for verifying SSL certificates, this
208 // in currently only used for TLS-TURN connections.
209 SSLCertificateVerifier* ssl_cert_verifier_ = nullptr;
Benjamin Wright19aab2e2018-04-05 15:39:06 -0700210 // TODO(benwright): Remove this when context is moved to OpenSSLCommon.
211 // Hold a friend class to the OpenSSLAdapter to retrieve the context.
Justin Uberti1d445502017-08-14 17:04:34 -0700212 friend class OpenSSLAdapter;
Justin Uberti1d445502017-08-14 17:04:34 -0700213};
214
Vojin Ilicf11f0e02021-06-30 14:22:11 +0200215// The EarlyExitCatcher is responsible for calling OpenSSLAdapter::Cleanup on
216// destruction. By doing this we have scoped cleanup which can be disabled if
217// there were no errors, aka early exits.
218
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700219std::string TransformAlpnProtocols(const std::vector<std::string>& protos);
220
Justin Uberti1d445502017-08-14 17:04:34 -0700221} // namespace rtc
222
Steve Anton10542f22019-01-11 09:11:00 -0800223#endif // RTC_BASE_OPENSSL_ADAPTER_H_