xref: /aosp_15_r20/external/cronet/net/socket/ssl_client_socket.h (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef NET_SOCKET_SSL_CLIENT_SOCKET_H_
6 #define NET_SOCKET_SSL_CLIENT_SOCKET_H_
7 
8 #include <stdint.h>
9 
10 #include <memory>
11 #include <vector>
12 
13 #include "base/containers/flat_set.h"
14 #include "base/gtest_prod_util.h"
15 #include "base/memory/raw_ptr.h"
16 #include "base/observer_list.h"
17 #include "net/base/net_export.h"
18 #include "net/cert/cert_database.h"
19 #include "net/cert/cert_verifier.h"
20 #include "net/socket/ssl_socket.h"
21 #include "net/ssl/ssl_client_auth_cache.h"
22 #include "net/ssl/ssl_config_service.h"
23 
24 namespace net {
25 
26 class HostPortPair;
27 class SCTAuditingDelegate;
28 class SSLClientSessionCache;
29 struct SSLConfig;
30 class SSLKeyLogger;
31 class StreamSocket;
32 class TransportSecurityState;
33 
34 // A client socket that uses SSL as the transport layer.
35 //
36 // NOTE: The SSL handshake occurs within the Connect method after a TCP
37 // connection is established.  If a SSL error occurs during the handshake,
38 // Connect will fail.
39 //
40 class NET_EXPORT SSLClientSocket : public SSLSocket {
41  public:
42   SSLClientSocket();
43 
44   // Called in response to |ERR_ECH_NOT_NEGOTIATED| in Connect(), to determine
45   // how to retry the connection, up to some limit. If this method returns a
46   // non-empty string, it is the serialized updated ECHConfigList provided by
47   // the server. The connection can be retried with the new value. If it returns
48   // an empty string, the server has indicated ECH has been disabled. The
49   // connection can be retried with ECH disabled.
50   virtual std::vector<uint8_t> GetECHRetryConfigs() = 0;
51 
52   // Log SSL key material to |logger|. Must be called before any
53   // SSLClientSockets are created.
54   //
55   // TODO(davidben): Switch this to a parameter on the SSLClientSocketContext
56   // once https://crbug.com/458365 is resolved.
57   static void SetSSLKeyLogger(std::unique_ptr<SSLKeyLogger> logger);
58 
59  protected:
set_signed_cert_timestamps_received(bool signed_cert_timestamps_received)60   void set_signed_cert_timestamps_received(
61       bool signed_cert_timestamps_received) {
62     signed_cert_timestamps_received_ = signed_cert_timestamps_received;
63   }
64 
set_stapled_ocsp_response_received(bool stapled_ocsp_response_received)65   void set_stapled_ocsp_response_received(bool stapled_ocsp_response_received) {
66     stapled_ocsp_response_received_ = stapled_ocsp_response_received;
67   }
68 
69   // Serialize |next_protos| in the wire format for ALPN: protocols are listed
70   // in order, each prefixed by a one-byte length.
71   static std::vector<uint8_t> SerializeNextProtos(
72       const NextProtoVector& next_protos);
73 
74  private:
75   FRIEND_TEST_ALL_PREFIXES(SSLClientSocket, SerializeNextProtos);
76   // For signed_cert_timestamps_received_ and stapled_ocsp_response_received_.
77   FRIEND_TEST_ALL_PREFIXES(SSLClientSocketVersionTest,
78                            ConnectSignedCertTimestampsTLSExtension);
79   FRIEND_TEST_ALL_PREFIXES(SSLClientSocketVersionTest,
80                            ConnectSignedCertTimestampsEnablesOCSP);
81 
82   // True if SCTs were received via a TLS extension.
83   bool signed_cert_timestamps_received_ = false;
84   // True if a stapled OCSP response was received.
85   bool stapled_ocsp_response_received_ = false;
86 };
87 
88 // Shared state and configuration across multiple SSLClientSockets.
89 class NET_EXPORT SSLClientContext : public SSLConfigService::Observer,
90                                     public CertVerifier::Observer,
91                                     public CertDatabase::Observer {
92  public:
93   enum class SSLConfigChangeType {
94     kSSLConfigChanged,
95     kCertDatabaseChanged,
96     kCertVerifierChanged,
97   };
98 
99   class NET_EXPORT Observer : public base::CheckedObserver {
100    public:
101     // Called when SSL configuration for all hosts changed. Newly-created
102     // SSLClientSockets will pick up the new configuration. Note that changes
103     // which only apply to one server will result in a call to
104     // OnSSLConfigForServersChanged() instead.
105     virtual void OnSSLConfigChanged(SSLConfigChangeType change_type) = 0;
106     // Called when SSL configuration for |servers| changed. Newly-created
107     // SSLClientSockets to any server in |servers| will pick up the new
108     // configuration.
109     virtual void OnSSLConfigForServersChanged(
110         const base::flat_set<HostPortPair>& servers) = 0;
111   };
112 
113   // Creates a new SSLClientContext with the specified parameters. The
114   // SSLClientContext may not outlive the input parameters.
115   //
116   // |ssl_config_service| may be null to always use the default
117   // SSLContextConfig. |ssl_client_session_cache| may be null to disable session
118   // caching. |sct_auditing_delegate| may be null to disable SCT auditing.
119   SSLClientContext(SSLConfigService* ssl_config_service,
120                    CertVerifier* cert_verifier,
121                    TransportSecurityState* transport_security_state,
122                    SSLClientSessionCache* ssl_client_session_cache,
123                    SCTAuditingDelegate* sct_auditing_delegate);
124 
125   SSLClientContext(const SSLClientContext&) = delete;
126   SSLClientContext& operator=(const SSLClientContext&) = delete;
127 
128   ~SSLClientContext() override;
129 
config()130   const SSLContextConfig& config() { return config_; }
131 
ssl_config_service()132   SSLConfigService* ssl_config_service() { return ssl_config_service_; }
cert_verifier()133   CertVerifier* cert_verifier() { return cert_verifier_; }
transport_security_state()134   TransportSecurityState* transport_security_state() {
135     return transport_security_state_;
136   }
ssl_client_session_cache()137   SSLClientSessionCache* ssl_client_session_cache() {
138     return ssl_client_session_cache_;
139   }
sct_auditing_delegate()140   SCTAuditingDelegate* sct_auditing_delegate() {
141     return sct_auditing_delegate_;
142   }
143 
144   // Creates a new SSLClientSocket which can then be used to establish an SSL
145   // connection to |host_and_port| over the already-connected |stream_socket|.
146   std::unique_ptr<SSLClientSocket> CreateSSLClientSocket(
147       std::unique_ptr<StreamSocket> stream_socket,
148       const HostPortPair& host_and_port,
149       const SSLConfig& ssl_config);
150 
151   // Looks up the client certificate preference for |server|. If one is found,
152   // returns true and sets |client_cert| and |private_key| to the certificate
153   // and key. Note these may be null if the preference is to continue with no
154   // client certificate. Returns false if no preferences are configured,
155   // which means client certificate requests should be reported as
156   // ERR_SSL_CLIENT_AUTH_CERT_NEEDED.
157   bool GetClientCertificate(const HostPortPair& server,
158                             scoped_refptr<X509Certificate>* client_cert,
159                             scoped_refptr<SSLPrivateKey>* private_key);
160 
161   // Configures all subsequent connections to |server| to authenticate with
162   // |client_cert| and |private_key| when requested. If there is already a
163   // client certificate for |server|, it will be overwritten. |client_cert| and
164   // |private_key| may be null to indicate that no client certificate should be
165   // sent to |server|.
166   //
167   // Note this method will synchronously call OnSSLConfigForServersChanged() on
168   // observers.
169   void SetClientCertificate(const HostPortPair& server,
170                             scoped_refptr<X509Certificate> client_cert,
171                             scoped_refptr<SSLPrivateKey> private_key);
172 
173   // Clears a client certificate preference for |server| set by
174   // SetClientCertificate(). Returns true if one was removed and false
175   // otherwise.
176   //
177   // Note this method will synchronously call OnSSLConfigForServersChanged() on
178   // observers.
179   bool ClearClientCertificate(const HostPortPair& server);
180 
181   // Clears a client certificate preference for |host| set by
182   // SetClientCertificate() if |certificate| doesn't match the cached
183   // certificate.
184   //
185   // Note this method will synchronously call OnSSLConfigForServersChanged() on
186   // observers.
187   void ClearClientCertificateIfNeeded(
188       const net::HostPortPair& host,
189       const scoped_refptr<net::X509Certificate>& certificate);
190 
191   // Clears a client certificate preference, set by SetClientCertificate(),
192   // for all hosts whose cached certificate matches |certificate|.
193   //
194   // Note this method will synchronously call OnSSLConfigForServersChanged() on
195   // observers.
196   void ClearMatchingClientCertificate(
197       const scoped_refptr<net::X509Certificate>& certificate);
198 
GetClientCertificateCachedServersForTesting()199   base::flat_set<HostPortPair> GetClientCertificateCachedServersForTesting()
200       const {
201     return ssl_client_auth_cache_.GetCachedServers();
202   }
203 
204   // Add an observer to be notified when configuration has changed.
205   // RemoveObserver() must be called before |observer| is destroyed.
206   void AddObserver(Observer* observer);
207 
208   // Remove an observer added with AddObserver().
209   void RemoveObserver(Observer* observer);
210 
211   // SSLConfigService::Observer:
212   void OnSSLContextConfigChanged() override;
213 
214   // CertVerifier::Observer:
215   void OnCertVerifierChanged() override;
216 
217   // CertDatabase::Observer:
218   void OnTrustStoreChanged() override;
219   void OnClientCertStoreChanged() override;
220 
221  private:
222   void NotifySSLConfigChanged(SSLConfigChangeType change_type);
223   void NotifySSLConfigForServersChanged(
224       const base::flat_set<HostPortPair>& servers);
225 
226   SSLContextConfig config_;
227 
228   raw_ptr<SSLConfigService> ssl_config_service_;
229   raw_ptr<CertVerifier> cert_verifier_;
230   raw_ptr<TransportSecurityState> transport_security_state_;
231   raw_ptr<SSLClientSessionCache> ssl_client_session_cache_;
232   raw_ptr<SCTAuditingDelegate> sct_auditing_delegate_;
233 
234   SSLClientAuthCache ssl_client_auth_cache_;
235 
236   base::ObserverList<Observer, true /* check_empty */> observers_;
237 };
238 
239 }  // namespace net
240 
241 #endif  // NET_SOCKET_SSL_CLIENT_SOCKET_H_
242