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