• 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_IMPL_H_
6 #define NET_SOCKET_SSL_CLIENT_SOCKET_IMPL_H_
7 
8 #include <stddef.h>
9 #include <stdint.h>
10 
11 #include <memory>
12 #include <string>
13 #include <vector>
14 
15 #include "base/compiler_specific.h"
16 #include "base/containers/lru_cache.h"
17 #include "base/memory/raw_ptr.h"
18 #include "base/memory/scoped_refptr.h"
19 #include "base/memory/weak_ptr.h"
20 #include "net/base/completion_once_callback.h"
21 #include "net/base/host_port_pair.h"
22 #include "net/base/io_buffer.h"
23 #include "net/cert/cert_verifier.h"
24 #include "net/cert/cert_verify_result.h"
25 #include "net/log/net_log_with_source.h"
26 #include "net/socket/next_proto.h"
27 #include "net/socket/socket_bio_adapter.h"
28 #include "net/socket/ssl_client_socket.h"
29 #include "net/socket/stream_socket.h"
30 #include "net/ssl/openssl_ssl_util.h"
31 #include "net/ssl/ssl_client_session_cache.h"
32 #include "net/ssl/ssl_config.h"
33 #include "net/traffic_annotation/network_traffic_annotation.h"
34 #include "third_party/abseil-cpp/absl/types/optional.h"
35 #include "third_party/boringssl/src/include/openssl/base.h"
36 #include "third_party/boringssl/src/include/openssl/ssl.h"
37 
38 namespace crypto {
39 class OpenSSLErrStackTracer;
40 }
41 
42 namespace net {
43 
44 class SSLCertRequestInfo;
45 class SSLInfo;
46 class SSLPrivateKey;
47 class SSLKeyLogger;
48 class X509Certificate;
49 
50 class SSLClientSocketImpl : public SSLClientSocket,
51                             public SocketBIOAdapter::Delegate {
52  public:
53   // Takes ownership of |stream_socket|, which may already be connected.
54   // The given hostname will be compared with the name(s) in the server's
55   // certificate during the SSL handshake.  |ssl_config| specifies the SSL
56   // settings. The resulting socket may not outlive |context|.
57   SSLClientSocketImpl(SSLClientContext* context,
58                       std::unique_ptr<StreamSocket> stream_socket,
59                       const HostPortPair& host_and_port,
60                       const SSLConfig& ssl_config);
61 
62   SSLClientSocketImpl(const SSLClientSocketImpl&) = delete;
63   SSLClientSocketImpl& operator=(const SSLClientSocketImpl&) = delete;
64 
65   ~SSLClientSocketImpl() override;
66 
host_and_port()67   const HostPortPair& host_and_port() const { return host_and_port_; }
68 
69   // Log SSL key material to |logger|. Must be called before any
70   // SSLClientSockets are created.
71   static void SetSSLKeyLogger(std::unique_ptr<SSLKeyLogger> logger);
72 
73   // SSLClientSocket implementation.
74   std::vector<uint8_t> GetECHRetryConfigs() override;
75 
76   // SSLSocket implementation.
77   int ExportKeyingMaterial(base::StringPiece label,
78                            bool has_context,
79                            base::StringPiece context,
80                            unsigned char* out,
81                            unsigned int outlen) override;
82 
83   // StreamSocket implementation.
84   int Connect(CompletionOnceCallback callback) override;
85   void Disconnect() override;
86   int ConfirmHandshake(CompletionOnceCallback callback) override;
87   bool IsConnected() const override;
88   bool IsConnectedAndIdle() const override;
89   int GetPeerAddress(IPEndPoint* address) const override;
90   int GetLocalAddress(IPEndPoint* address) const override;
91   const NetLogWithSource& NetLog() const override;
92   bool WasEverUsed() const override;
93   NextProto GetNegotiatedProtocol() const override;
94   absl::optional<base::StringPiece> GetPeerApplicationSettings() const override;
95   bool GetSSLInfo(SSLInfo* ssl_info) override;
96   int64_t GetTotalReceivedBytes() const override;
97   void GetSSLCertRequestInfo(
98       SSLCertRequestInfo* cert_request_info) const override;
99 
100   void ApplySocketTag(const SocketTag& tag) override;
101 
102   // Socket implementation.
103   int Read(IOBuffer* buf,
104            int buf_len,
105            CompletionOnceCallback callback) override;
106   int ReadIfReady(IOBuffer* buf,
107                   int buf_len,
108                   CompletionOnceCallback callback) override;
109   int CancelReadIfReady() override;
110   int Write(IOBuffer* buf,
111             int buf_len,
112             CompletionOnceCallback callback,
113             const NetworkTrafficAnnotationTag& traffic_annotation) override;
114   int SetReceiveBufferSize(int32_t size) override;
115   int SetSendBufferSize(int32_t size) override;
116 
117   // SocketBIOAdapter implementation:
118   void OnReadReady() override;
119   void OnWriteReady() override;
120 
121  private:
122   class PeerCertificateChain;
123   class SSLContext;
124   friend class SSLClientSocket;
125   friend class SSLContext;
126 
127   int Init();
128   void DoReadCallback(int result);
129   void DoWriteCallback(int result);
130 
131   int DoHandshake();
132   int DoHandshakeComplete(int result);
133   void DoConnectCallback(int result);
134 
135   void OnVerifyComplete(int result);
136   void OnHandshakeIOComplete(int result);
137 
138   int DoHandshakeLoop(int last_io_result);
139   int DoPayloadRead(IOBuffer* buf, int buf_len);
140   int DoPayloadWrite();
141   void DoPeek();
142 
143   // Called when an asynchronous event completes which may have blocked the
144   // pending Connect, Read or Write calls, if any. Retries all state machines
145   // and, if complete, runs the respective callbacks.
146   void RetryAllOperations();
147 
148   // Callback from the SSL layer when a certificate needs to be verified. This
149   // is called when establishing new (fresh) connections and when evaluating
150   // whether an existing session can be resumed.
151   static ssl_verify_result_t VerifyCertCallback(SSL* ssl, uint8_t* out_alert);
152   ssl_verify_result_t VerifyCert();
153   ssl_verify_result_t HandleVerifyResult();
154   int CheckCTCompliance();
155 
156   // Callback from the SSL layer that indicates the remote server is requesting
157   // a certificate for this client.
158   int ClientCertRequestCallback(SSL* ssl);
159 
160   // Called from the SSL layer whenever a new session is established.
161   int NewSessionCallback(SSL_SESSION* session);
162 
163   // Returns a session cache key for this socket.
164   SSLClientSessionCache::Key GetSessionCacheKey(
165       absl::optional<IPAddress> dest_ip_addr) const;
166 
167   // Returns true if renegotiations are allowed.
168   bool IsRenegotiationAllowed() const;
169 
170   // Returns true when we should be using the ssl_client_session_cache_
171   bool IsCachingEnabled() const;
172 
173   // Callbacks for operations with the private key.
174   ssl_private_key_result_t PrivateKeySignCallback(uint8_t* out,
175                                                   size_t* out_len,
176                                                   size_t max_out,
177                                                   uint16_t algorithm,
178                                                   const uint8_t* in,
179                                                   size_t in_len);
180   ssl_private_key_result_t PrivateKeyCompleteCallback(uint8_t* out,
181                                                       size_t* out_len,
182                                                       size_t max_out);
183 
184   void OnPrivateKeyComplete(Error error, const std::vector<uint8_t>& signature);
185 
186   // Called whenever BoringSSL processes a protocol message.
187   void MessageCallback(int is_write,
188                        int content_type,
189                        const void* buf,
190                        size_t len);
191 
192   void LogConnectEndEvent(int rv);
193 
194   // Record whether ALPN was used, and if so, the negotiated protocol,
195   // in a UMA histogram.
196   void RecordNegotiatedProtocol() const;
197 
198   // Returns the net error corresponding to the most recent OpenSSL
199   // error. ssl_error is the output of SSL_get_error.
200   int MapLastOpenSSLError(int ssl_error,
201                           const crypto::OpenSSLErrStackTracer& tracer,
202                           OpenSSLErrorInfo* info);
203 
204   // Wraps SSL_get0_ech_name_override. See documentation for that function.
205   base::StringPiece GetECHNameOverride() const;
206 
207   // Returns true if |cert| is one of the certs in |allowed_bad_certs|.
208   // The expected cert status is written to |cert_status|. |*cert_status| can
209   // be nullptr if user doesn't care about the cert status. This method checks
210   // handshake state, so it may only be called during certificate verification.
211   bool IsAllowedBadCert(X509Certificate* cert, CertStatus* cert_status) const;
212 
213   CompletionOnceCallback user_connect_callback_;
214   CompletionOnceCallback user_read_callback_;
215   CompletionOnceCallback user_write_callback_;
216 
217   // Used by Read function.
218   scoped_refptr<IOBuffer> user_read_buf_;
219   int user_read_buf_len_;
220 
221   // Used by Write function.
222   scoped_refptr<IOBuffer> user_write_buf_;
223   int user_write_buf_len_;
224   bool first_post_handshake_write_ = true;
225 
226   // True if we've already handled the result of our attempt to use early data.
227   bool handled_early_data_result_ = false;
228 
229   // Used by DoPayloadRead() when attempting to fill the caller's buffer with
230   // as much data as possible without blocking.
231   // If DoPayloadRead() encounters an error after having read some data, stores
232   // the result to return on the *next* call to DoPayloadRead().  A value > 0
233   // indicates there is no pending result, otherwise 0 indicates EOF and < 0
234   // indicates an error.
235   int pending_read_error_;
236 
237   // If there is a pending read result, the OpenSSL result code (output of
238   // SSL_get_error) associated with it.
239   int pending_read_ssl_error_ = SSL_ERROR_NONE;
240 
241   // If there is a pending read result, the OpenSSLErrorInfo associated with it.
242   OpenSSLErrorInfo pending_read_error_info_;
243 
244   // Set when Connect finishes.
245   scoped_refptr<X509Certificate> server_cert_;
246   CertVerifyResult server_cert_verify_result_;
247   bool completed_connect_ = false;
248 
249   // Set when Read() or Write() successfully reads or writes data to or from the
250   // network.
251   bool was_ever_used_ = false;
252 
253   const raw_ptr<SSLClientContext> context_;
254 
255   std::unique_ptr<CertVerifier::Request> cert_verifier_request_;
256 
257   // Result from Cert Verifier.
258   int cert_verification_result_;
259 
260   // OpenSSL stuff
261   bssl::UniquePtr<SSL> ssl_;
262 
263   std::unique_ptr<StreamSocket> stream_socket_;
264   std::unique_ptr<SocketBIOAdapter> transport_adapter_;
265   const HostPortPair host_and_port_;
266   SSLConfig ssl_config_;
267 
268   enum State {
269     STATE_NONE,
270     STATE_HANDSHAKE,
271     STATE_HANDSHAKE_COMPLETE,
272   };
273   State next_handshake_state_ = STATE_NONE;
274 
275   // True if we are currently confirming the handshake.
276   bool in_confirm_handshake_ = false;
277 
278   // True if the post-handshake SSL_peek has completed.
279   bool peek_complete_ = false;
280 
281   // True if the socket has been disconnected.
282   bool disconnected_ = false;
283 
284   // True if certificate verification used an ECH name override.
285   bool used_ech_name_override_ = false;
286 
287   NextProto negotiated_protocol_ = kProtoUnknown;
288 
289   // Set to true if a CertificateRequest was received.
290   bool certificate_requested_ = false;
291 
292   int signature_result_;
293   std::vector<uint8_t> signature_;
294 
295   // pinning_failure_log contains a message produced by
296   // TransportSecurityState::CheckPublicKeyPins in the event of a
297   // pinning failure. It is a (somewhat) human-readable string.
298   std::string pinning_failure_log_;
299 
300   // True if PKP is bypassed due to a local trust anchor.
301   bool pkp_bypassed_ = false;
302 
303   // True if there was a certificate error which should be treated as fatal,
304   // and false otherwise.
305   bool is_fatal_cert_error_ = false;
306 
307   // True if the socket should respond to client certificate requests with
308   // |client_cert_| and |client_private_key_|, which may be null to continue
309   // with no certificate. If false, client certificate requests will result in
310   // ERR_SSL_CLIENT_AUTH_CERT_NEEDED.
311   bool send_client_cert_;
312   scoped_refptr<X509Certificate> client_cert_;
313   scoped_refptr<SSLPrivateKey> client_private_key_;
314 
315   NetLogWithSource net_log_;
316   base::WeakPtrFactory<SSLClientSocketImpl> weak_factory_{this};
317 };
318 
319 }  // namespace net
320 
321 #endif  // NET_SOCKET_SSL_CLIENT_SOCKET_IMPL_H_
322