1 /*
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 
11 #ifndef RTC_BASE_OPENSSL_ADAPTER_H_
12 #define RTC_BASE_OPENSSL_ADAPTER_H_
13 
14 #include <stddef.h>
15 #include <stdint.h>
16 
17 #include <memory>
18 #include <string>
19 #include <vector>
20 
21 #include "rtc_base/async_socket.h"
22 #include "rtc_base/buffer.h"
23 #include "rtc_base/message_handler.h"
24 #include "rtc_base/openssl_identity.h"
25 #include "rtc_base/openssl_session_cache.h"
26 #include "rtc_base/socket.h"
27 #include "rtc_base/socket_address.h"
28 #include "rtc_base/ssl_adapter.h"
29 #include "rtc_base/ssl_certificate.h"
30 #include "rtc_base/ssl_identity.h"
31 #include "rtc_base/ssl_stream_adapter.h"
32 
33 namespace rtc {
34 
35 class OpenSSLAdapter final : public SSLAdapter, public MessageHandler {
36  public:
37   static bool InitializeSSL();
38   static bool CleanupSSL();
39 
40   // Creating an OpenSSLAdapter requires a socket to bind to, an optional
41   // session cache if you wish to improve performance by caching sessions for
42   // hostnames you have previously connected to and an optional
43   // SSLCertificateVerifier which can override any existing trusted roots to
44   // validate a peer certificate. The cache and verifier are effectively
45   // immutable after the the SSL connection starts.
46   explicit OpenSSLAdapter(AsyncSocket* socket,
47                           OpenSSLSessionCache* ssl_session_cache = nullptr,
48                           SSLCertificateVerifier* ssl_cert_verifier = nullptr);
49   ~OpenSSLAdapter() override;
50 
51   void SetIgnoreBadCert(bool ignore) override;
52   void SetAlpnProtocols(const std::vector<std::string>& protos) override;
53   void SetEllipticCurves(const std::vector<std::string>& curves) override;
54   void SetMode(SSLMode mode) override;
55   void SetCertVerifier(SSLCertificateVerifier* ssl_cert_verifier) override;
56   void SetIdentity(SSLIdentity* identity) override;
57   void SetIdentity(std::unique_ptr<SSLIdentity> identity) override;
58   void SetRole(SSLRole role) override;
59   AsyncSocket* Accept(SocketAddress* paddr) override;
60   int StartSSL(const char* hostname, bool restartable) override;
61   int Send(const void* pv, size_t cb) override;
62   int SendTo(const void* pv, size_t cb, const SocketAddress& addr) override;
63   int Recv(void* pv, size_t cb, int64_t* timestamp) override;
64   int RecvFrom(void* pv,
65                size_t cb,
66                SocketAddress* paddr,
67                int64_t* timestamp) override;
68   int Close() override;
69   // Note that the socket returns ST_CONNECTING while SSL is being negotiated.
70   ConnState GetState() const override;
71   bool IsResumedSession() override;
72   // Creates a new SSL_CTX object, configured for client-to-server usage
73   // with SSLMode |mode|, and if |enable_cache| is true, with support for
74   // storing successful sessions so that they can be later resumed.
75   // OpenSSLAdapterFactory will call this method to create its own internal
76   // SSL_CTX, and OpenSSLAdapter will also call this when used without a
77   // factory.
78   static SSL_CTX* CreateContext(SSLMode mode, bool enable_cache);
79 
80  protected:
81   void OnConnectEvent(AsyncSocket* socket) override;
82   void OnReadEvent(AsyncSocket* socket) override;
83   void OnWriteEvent(AsyncSocket* socket) override;
84   void OnCloseEvent(AsyncSocket* socket, int err) override;
85 
86  private:
87   enum SSLState {
88     SSL_NONE,
89     SSL_WAIT,
90     SSL_CONNECTING,
91     SSL_CONNECTED,
92     SSL_ERROR
93   };
94 
95   enum { MSG_TIMEOUT };
96 
97   int BeginSSL();
98   int ContinueSSL();
99   void Error(const char* context, int err, bool signal = true);
100   void Cleanup();
101 
102   // Return value and arguments have the same meanings as for Send; |error| is
103   // an output parameter filled with the result of SSL_get_error.
104   int DoSslWrite(const void* pv, size_t cb, int* error);
105   void OnMessage(Message* msg) override;
106   bool SSLPostConnectionCheck(SSL* ssl, const std::string& host);
107 
108 #if !defined(NDEBUG)
109   // In debug builds, logs info about the state of the SSL connection.
110   static void SSLInfoCallback(const SSL* ssl, int where, int ret);
111 #endif
112   static int SSLVerifyCallback(int ok, X509_STORE_CTX* store);
113   friend class OpenSSLStreamAdapter;  // for custom_verify_callback_;
114 
115   // If the SSL_CTX was created with |enable_cache| set to true, this callback
116   // will be called when a SSL session has been successfully established,
117   // to allow its SSL_SESSION* to be cached for later resumption.
118   static int NewSSLSessionCallback(SSL* ssl, SSL_SESSION* session);
119 
120   // Optional SSL Shared session cache to improve performance.
121   OpenSSLSessionCache* ssl_session_cache_ = nullptr;
122   // Optional SSL Certificate verifier which can be set by a third party.
123   SSLCertificateVerifier* ssl_cert_verifier_ = nullptr;
124   // The current connection state of the (d)TLS connection.
125   SSLState state_;
126   std::unique_ptr<OpenSSLIdentity> identity_;
127   // Indicates whethere this is a client or a server.
128   SSLRole role_;
129   bool ssl_read_needs_write_;
130   bool ssl_write_needs_read_;
131   // If true, socket will retain SSL configuration after Close.
132   // TODO(juberti): Remove this unused flag.
133   bool restartable_;
134   // This buffer is used if SSL_write fails with SSL_ERROR_WANT_WRITE, which
135   // means we need to keep retrying with *the same exact data* until it
136   // succeeds. Afterwards it will be cleared.
137   Buffer pending_data_;
138   SSL* ssl_;
139   // Holds the SSL context, which may be shared if an session cache is provided.
140   SSL_CTX* ssl_ctx_;
141   // Hostname of server that is being connected, used for SNI.
142   std::string ssl_host_name_;
143   // Set the adapter to DTLS or TLS mode before creating the context.
144   SSLMode ssl_mode_;
145   // If true, the server certificate need not match the configured hostname.
146   bool ignore_bad_cert_;
147   // List of protocols to be used in the TLS ALPN extension.
148   std::vector<std::string> alpn_protocols_;
149   // List of elliptic curves to be used in the TLS elliptic curves extension.
150   std::vector<std::string> elliptic_curves_;
151   // Holds the result of the call to run of the ssl_cert_verify_->Verify()
152   bool custom_cert_verifier_status_;
153 };
154 
155 // The OpenSSLAdapterFactory is responsbile for creating multiple new
156 // OpenSSLAdapters with a shared SSL_CTX and a shared SSL_SESSION cache. The
157 // SSL_SESSION cache allows existing SSL_SESSIONS to be reused instead of
158 // recreating them leading to a significant performance improvement.
159 class OpenSSLAdapterFactory : public SSLAdapterFactory {
160  public:
161   OpenSSLAdapterFactory();
162   ~OpenSSLAdapterFactory() override;
163   // Set the SSL Mode to use with this factory. This should only be set before
164   // the first adapter is created with the factory. If it is called after it
165   // will DCHECK.
166   void SetMode(SSLMode mode) override;
167   // Set a custom certificate verifier to be passed down to each instance
168   // created with this factory. This should only ever be set before the first
169   // call to the factory and cannot be changed after the fact.
170   void SetCertVerifier(SSLCertificateVerifier* ssl_cert_verifier) override;
171   // Constructs a new socket using the shared OpenSSLSessionCache. This means
172   // existing SSLSessions already in the cache will be reused instead of
173   // re-created for improved performance.
174   OpenSSLAdapter* CreateAdapter(AsyncSocket* socket) override;
175 
176  private:
177   // Holds the SSLMode (DTLS,TLS) that will be used to set the session cache.
178   SSLMode ssl_mode_ = SSL_MODE_TLS;
179   // Holds a cache of existing SSL Sessions.
180   std::unique_ptr<OpenSSLSessionCache> ssl_session_cache_;
181   // Provides an optional custom callback for verifying SSL certificates, this
182   // in currently only used for TLS-TURN connections.
183   SSLCertificateVerifier* ssl_cert_verifier_ = nullptr;
184   // TODO(benwright): Remove this when context is moved to OpenSSLCommon.
185   // Hold a friend class to the OpenSSLAdapter to retrieve the context.
186   friend class OpenSSLAdapter;
187 };
188 
189 std::string TransformAlpnProtocols(const std::vector<std::string>& protos);
190 
191 }  // namespace rtc
192 
193 #endif  // RTC_BASE_OPENSSL_ADAPTER_H_
194