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.
5 #ifndef NET_SOCKET_SSL_CLIENT_SOCKET_OPENSSL_H_
6 #define NET_SOCKET_SSL_CLIENT_SOCKET_OPENSSL_H_
10 #include "base/compiler_specific.h"
11 #include "base/memory/scoped_ptr.h"
12 #include "base/memory/weak_ptr.h"
13 #include "net/base/completion_callback.h"
14 #include "net/base/io_buffer.h"
15 #include "net/cert/cert_verify_result.h"
16 #include "net/cert/ct_verify_result.h"
17 #include "net/socket/client_socket_handle.h"
18 #include "net/socket/ssl_client_socket.h"
19 #include "net/ssl/channel_id_service.h"
20 #include "net/ssl/openssl_ssl_util.h"
21 #include "net/ssl/ssl_client_cert_type.h"
22 #include "net/ssl/ssl_config_service.h"
24 // Avoid including misc OpenSSL headers, i.e.:
26 typedef struct bio_st BIO
;
28 typedef struct evp_pkey_st EVP_PKEY
;
30 typedef struct ssl_st SSL
;
32 typedef struct x509_st X509
;
33 // <openssl/ossl_type.h>
34 typedef struct x509_store_ctx_st X509_STORE_CTX
;
40 class SingleRequestCertVerifier
;
41 class SSLCertRequestInfo
;
44 // An SSL client socket implemented with OpenSSL.
45 class SSLClientSocketOpenSSL
: public SSLClientSocket
{
47 // Takes ownership of the transport_socket, which may already be connected.
48 // The given hostname will be compared with the name(s) in the server's
49 // certificate during the SSL handshake. ssl_config specifies the SSL
51 SSLClientSocketOpenSSL(scoped_ptr
<ClientSocketHandle
> transport_socket
,
52 const HostPortPair
& host_and_port
,
53 const SSLConfig
& ssl_config
,
54 const SSLClientSocketContext
& context
);
55 ~SSLClientSocketOpenSSL() override
;
57 const HostPortPair
& host_and_port() const { return host_and_port_
; }
58 const std::string
& ssl_session_cache_shard() const {
59 return ssl_session_cache_shard_
;
62 // SSLClientSocket implementation.
63 void GetSSLCertRequestInfo(SSLCertRequestInfo
* cert_request_info
) override
;
64 NextProtoStatus
GetNextProto(std::string
* proto
) override
;
65 ChannelIDService
* GetChannelIDService() const override
;
67 // SSLSocket implementation.
68 int ExportKeyingMaterial(const base::StringPiece
& label
,
70 const base::StringPiece
& context
,
72 unsigned int outlen
) override
;
73 int GetTLSUniqueChannelBinding(std::string
* out
) override
;
75 // StreamSocket implementation.
76 int Connect(const CompletionCallback
& callback
) override
;
77 void Disconnect() override
;
78 bool IsConnected() const override
;
79 bool IsConnectedAndIdle() const override
;
80 int GetPeerAddress(IPEndPoint
* address
) const override
;
81 int GetLocalAddress(IPEndPoint
* address
) const override
;
82 const BoundNetLog
& NetLog() const override
;
83 void SetSubresourceSpeculation() override
;
84 void SetOmniboxSpeculation() override
;
85 bool WasEverUsed() const override
;
86 bool UsingTCPFastOpen() const override
;
87 bool GetSSLInfo(SSLInfo
* ssl_info
) override
;
89 // Socket implementation.
90 int Read(IOBuffer
* buf
,
92 const CompletionCallback
& callback
) override
;
93 int Write(IOBuffer
* buf
,
95 const CompletionCallback
& callback
) override
;
96 int SetReceiveBufferSize(int32 size
) override
;
97 int SetSendBufferSize(int32 size
) override
;
100 // SSLClientSocket implementation.
101 scoped_refptr
<X509Certificate
> GetUnverifiedServerCertificateChain()
105 class PeerCertificateChain
;
107 friend class SSLClientSocket
;
108 friend class SSLContext
;
111 void DoReadCallback(int result
);
112 void DoWriteCallback(int result
);
114 bool DoTransportIO();
116 int DoChannelIDLookup();
117 int DoChannelIDLookupComplete(int result
);
118 int DoVerifyCert(int result
);
119 int DoVerifyCertComplete(int result
);
120 void DoConnectCallback(int result
);
121 void UpdateServerCert();
124 void OnHandshakeIOComplete(int result
);
125 void OnSendComplete(int result
);
126 void OnRecvComplete(int result
);
128 int DoHandshakeLoop(int last_io_result
);
132 int DoPayloadWrite();
136 void BufferSendComplete(int result
);
137 void BufferRecvComplete(int result
);
138 void TransportWriteComplete(int result
);
139 int TransportReadComplete(int result
);
141 // Callback from the SSL layer that indicates the remote server is requesting
142 // a certificate for this client.
143 int ClientCertRequestCallback(SSL
* ssl
);
145 // CertVerifyCallback is called to verify the server's certificates. We do
146 // verification after the handshake so this function only enforces that the
147 // certificates don't change during renegotiation.
148 int CertVerifyCallback(X509_STORE_CTX
*store_ctx
);
150 // Callback from the SSL layer to check which NPN protocol we are supporting
151 int SelectNextProtoCallback(unsigned char** out
, unsigned char* outlen
,
152 const unsigned char* in
, unsigned int inlen
);
154 // Called during an operation on |transport_bio_|'s peer. Checks saved
155 // transport error state and, if appropriate, returns an error through
156 // OpenSSL's error system.
157 long MaybeReplayTransportError(BIO
*bio
,
159 const char *argp
, int argi
, long argl
,
162 // Callback from the SSL layer when an operation is performed on
163 // |transport_bio_|'s peer.
164 static long BIOCallback(BIO
*bio
,
166 const char *argp
, int argi
, long argl
,
169 // Called after the initial handshake completes and after the server
170 // certificate has been verified. The order of handshake completion and
171 // certificate verification depends on whether the connection was false
172 // started. After both have happened (thus calling this twice), the session is
173 // safe to cache and will be cached.
174 void MaybeCacheSession();
176 // Callback from the SSL layer when the internal state machine progresses. It
177 // is used to listen for when the handshake completes entirely; |Connect| may
178 // return early if false starting.
179 void InfoCallback(int type
, int val
);
181 // Adds the SignedCertificateTimestamps from ct_verify_result_ to |ssl_info|.
182 // SCTs are held in three separate vectors in ct_verify_result, each
183 // vetor representing a particular verification state, this method associates
184 // each of the SCTs with the corresponding SCTVerifyStatus as it adds it to
185 // the |ssl_info|.signed_certificate_timestamps list.
186 void AddSCTInfoToSSLInfo(SSLInfo
* ssl_info
) const;
188 // Returns a unique key string for the SSL session cache for
190 std::string
GetSessionCacheKey() const;
192 bool transport_send_busy_
;
193 bool transport_recv_busy_
;
195 // Buffers which are shared by BoringSSL and SSLClientSocketOpenSSL.
196 // GrowableIOBuffer is used to keep ownership and setting offset.
197 scoped_refptr
<GrowableIOBuffer
> send_buffer_
;
198 scoped_refptr
<GrowableIOBuffer
> recv_buffer_
;
200 CompletionCallback user_connect_callback_
;
201 CompletionCallback user_read_callback_
;
202 CompletionCallback user_write_callback_
;
204 // Used by Read function.
205 scoped_refptr
<IOBuffer
> user_read_buf_
;
206 int user_read_buf_len_
;
208 // Used by Write function.
209 scoped_refptr
<IOBuffer
> user_write_buf_
;
210 int user_write_buf_len_
;
212 // Used by DoPayloadRead() when attempting to fill the caller's buffer with
213 // as much data as possible without blocking.
214 // If DoPayloadRead() encounters an error after having read some data, stores
215 // the result to return on the *next* call to DoPayloadRead(). A value > 0
216 // indicates there is no pending result, otherwise 0 indicates EOF and < 0
217 // indicates an error.
218 int pending_read_error_
;
220 // If there is a pending read result, the OpenSSL result code (output of
221 // SSL_get_error) associated with it.
222 int pending_read_ssl_error_
;
224 // If there is a pending read result, the OpenSSLErrorInfo associated with it.
225 OpenSSLErrorInfo pending_read_error_info_
;
227 // Used by TransportReadComplete() to signify an error reading from the
228 // transport socket. A value of OK indicates the socket is still
229 // readable. EOFs are mapped to ERR_CONNECTION_CLOSED.
230 int transport_read_error_
;
232 // Used by TransportWriteComplete() and TransportReadComplete() to signify an
233 // error writing to the transport socket. A value of OK indicates no error.
234 int transport_write_error_
;
236 // Set when Connect finishes.
237 scoped_ptr
<PeerCertificateChain
> server_cert_chain_
;
238 scoped_refptr
<X509Certificate
> server_cert_
;
239 CertVerifyResult server_cert_verify_result_
;
240 bool completed_connect_
;
242 // Set when Read() or Write() successfully reads or writes data to or from the
246 // Stores client authentication information between ClientAuthHandler and
247 // GetSSLCertRequestInfo calls.
248 bool client_auth_cert_needed_
;
249 // List of DER-encoded X.509 DistinguishedName of certificate authorities
250 // allowed by the server.
251 std::vector
<std::string
> cert_authorities_
;
252 // List of SSLClientCertType values for client certificates allowed by the
254 std::vector
<SSLClientCertType
> cert_key_types_
;
256 CertVerifier
* const cert_verifier_
;
257 scoped_ptr
<SingleRequestCertVerifier
> verifier_
;
258 base::TimeTicks start_cert_verification_time_
;
260 // Certificate Transparency: Verifier and result holder.
261 ct::CTVerifyResult ct_verify_result_
;
262 CTVerifier
* cert_transparency_verifier_
;
264 // The service for retrieving Channel ID keys. May be NULL.
265 ChannelIDService
* channel_id_service_
;
271 scoped_ptr
<ClientSocketHandle
> transport_
;
272 const HostPortPair host_and_port_
;
273 SSLConfig ssl_config_
;
274 // ssl_session_cache_shard_ is an opaque string that partitions the SSL
275 // session cache. i.e. sessions created with one value will not attempt to
276 // resume on the socket with a different value.
277 const std::string ssl_session_cache_shard_
;
282 STATE_CHANNEL_ID_LOOKUP
,
283 STATE_CHANNEL_ID_LOOKUP_COMPLETE
,
285 STATE_VERIFY_CERT_COMPLETE
,
287 State next_handshake_state_
;
288 NextProtoStatus npn_status_
;
289 std::string npn_proto_
;
290 // Written by the |channel_id_service_|.
291 std::string channel_id_private_key_
;
292 std::string channel_id_cert_
;
293 // True if channel ID extension was negotiated.
294 bool channel_id_xtn_negotiated_
;
295 // True if the initial handshake has completed.
296 bool handshake_completed_
;
297 // True if the initial handshake's certificate has been verified.
298 bool certificate_verified_
;
299 // The request handle for |channel_id_service_|.
300 ChannelIDService::RequestHandle channel_id_request_handle_
;
302 TransportSecurityState
* transport_security_state_
;
304 CertPolicyEnforcer
* const policy_enforcer_
;
306 // pinning_failure_log contains a message produced by
307 // TransportSecurityState::CheckPublicKeyPins in the event of a
308 // pinning failure. It is a (somewhat) human-readable string.
309 std::string pinning_failure_log_
;
311 BoundNetLog net_log_
;
312 base::WeakPtrFactory
<SSLClientSocketOpenSSL
> weak_factory_
;
317 #endif // NET_SOCKET_SSL_CLIENT_SOCKET_OPENSSL_H_