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