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_
8 #include <openssl/base.h>
9 #include <openssl/ssl.h>
14 #include "base/compiler_specific.h"
15 #include "base/memory/scoped_ptr.h"
16 #include "base/memory/weak_ptr.h"
17 #include "net/base/completion_callback.h"
18 #include "net/base/io_buffer.h"
19 #include "net/cert/cert_verifier.h"
20 #include "net/cert/cert_verify_result.h"
21 #include "net/cert/ct_verify_result.h"
22 #include "net/socket/client_socket_handle.h"
23 #include "net/socket/ssl_client_socket.h"
24 #include "net/ssl/channel_id_service.h"
25 #include "net/ssl/openssl_ssl_util.h"
26 #include "net/ssl/ssl_client_cert_type.h"
27 #include "net/ssl/ssl_config_service.h"
28 #include "net/ssl/ssl_failure_state.h"
34 class SSLCertRequestInfo
;
38 // An SSL client socket implemented with OpenSSL.
39 class SSLClientSocketOpenSSL
: public SSLClientSocket
{
41 // Takes ownership of the transport_socket, which may already be connected.
42 // The given hostname will be compared with the name(s) in the server's
43 // certificate during the SSL handshake. ssl_config specifies the SSL
45 SSLClientSocketOpenSSL(scoped_ptr
<ClientSocketHandle
> transport_socket
,
46 const HostPortPair
& host_and_port
,
47 const SSLConfig
& ssl_config
,
48 const SSLClientSocketContext
& context
);
49 ~SSLClientSocketOpenSSL() override
;
51 const HostPortPair
& host_and_port() const { return host_and_port_
; }
52 const std::string
& ssl_session_cache_shard() const {
53 return ssl_session_cache_shard_
;
56 // SSLClientSocket implementation.
57 void GetSSLCertRequestInfo(SSLCertRequestInfo
* cert_request_info
) override
;
58 NextProtoStatus
GetNextProto(std::string
* proto
) const override
;
59 ChannelIDService
* GetChannelIDService() const override
;
60 SSLFailureState
GetSSLFailureState() const override
;
62 // SSLSocket implementation.
63 int ExportKeyingMaterial(const base::StringPiece
& label
,
65 const base::StringPiece
& context
,
67 unsigned int outlen
) override
;
68 int GetTLSUniqueChannelBinding(std::string
* out
) override
;
70 // StreamSocket implementation.
71 int Connect(const CompletionCallback
& callback
) override
;
72 void Disconnect() override
;
73 bool IsConnected() const override
;
74 bool IsConnectedAndIdle() const override
;
75 int GetPeerAddress(IPEndPoint
* address
) const override
;
76 int GetLocalAddress(IPEndPoint
* address
) const override
;
77 const BoundNetLog
& NetLog() const override
;
78 void SetSubresourceSpeculation() override
;
79 void SetOmniboxSpeculation() override
;
80 bool WasEverUsed() const override
;
81 bool UsingTCPFastOpen() const override
;
82 bool GetSSLInfo(SSLInfo
* ssl_info
) override
;
83 void GetConnectionAttempts(ConnectionAttempts
* out
) const override
;
84 void ClearConnectionAttempts() override
{}
85 void AddConnectionAttempts(const ConnectionAttempts
& attempts
) override
{}
87 // Socket implementation.
88 int Read(IOBuffer
* buf
,
90 const CompletionCallback
& callback
) override
;
91 int Write(IOBuffer
* buf
,
93 const CompletionCallback
& callback
) override
;
94 int SetReceiveBufferSize(int32 size
) override
;
95 int SetSendBufferSize(int32 size
) override
;
98 class PeerCertificateChain
;
100 friend class SSLClientSocket
;
101 friend class SSLContext
;
104 void DoReadCallback(int result
);
105 void DoWriteCallback(int result
);
107 bool DoTransportIO();
109 int DoHandshakeComplete(int result
);
110 int DoChannelIDLookup();
111 int DoChannelIDLookupComplete(int result
);
112 int DoVerifyCert(int result
);
113 int DoVerifyCertComplete(int result
);
114 void DoConnectCallback(int result
);
115 void UpdateServerCert();
118 void OnHandshakeIOComplete(int result
);
119 void OnSendComplete(int result
);
120 void OnRecvComplete(int result
);
122 int DoHandshakeLoop(int last_io_result
);
126 int DoPayloadWrite();
128 // Called when an asynchronous event completes which may have blocked the
129 // pending Read or Write calls, if any. Retries both state machines and, if
130 // complete, runs the respective callbacks.
131 void PumpReadWriteEvents();
135 void BufferSendComplete(int result
);
136 void BufferRecvComplete(int result
);
137 void TransportWriteComplete(int result
);
138 int TransportReadComplete(int result
);
140 // Callback from the SSL layer that indicates the remote server is requesting
141 // a certificate for this client.
142 int ClientCertRequestCallback(SSL
* ssl
);
144 // CertVerifyCallback is called to verify the server's certificates. We do
145 // verification after the handshake so this function only enforces that the
146 // certificates don't change during renegotiation.
147 int CertVerifyCallback(X509_STORE_CTX
*store_ctx
);
149 // Callback from the SSL layer to check which NPN protocol we are supporting
150 int SelectNextProtoCallback(unsigned char** out
, unsigned char* outlen
,
151 const unsigned char* in
, unsigned int inlen
);
153 // Called during an operation on |transport_bio_|'s peer. Checks saved
154 // transport error state and, if appropriate, returns an error through
155 // OpenSSL's error system.
156 long MaybeReplayTransportError(BIO
*bio
,
158 const char *argp
, int argi
, long argl
,
161 // Callback from the SSL layer when an operation is performed on
162 // |transport_bio_|'s peer.
163 static long BIOCallback(BIO
*bio
,
165 const char *argp
, int argi
, long argl
,
168 // Called after the initial handshake completes and after the server
169 // certificate has been verified. The order of handshake completion and
170 // certificate verification depends on whether the connection was false
171 // started. After both have happened (thus calling this twice), the session is
172 // safe to cache and will be cached.
173 void MaybeCacheSession();
175 // Called from the SSL layer whenever a new session is established.
176 int NewSessionCallback(SSL_SESSION
* session
);
178 // Adds the SignedCertificateTimestamps from ct_verify_result_ to |ssl_info|.
179 // SCTs are held in three separate vectors in ct_verify_result, each
180 // vetor representing a particular verification state, this method associates
181 // each of the SCTs with the corresponding SCTVerifyStatus as it adds it to
182 // the |ssl_info|.signed_certificate_timestamps list.
183 void AddSCTInfoToSSLInfo(SSLInfo
* ssl_info
) const;
185 // Returns a unique key string for the SSL session cache for
187 std::string
GetSessionCacheKey() const;
189 // Returns true if renegotiations are allowed.
190 bool IsRenegotiationAllowed() const;
192 // Callbacks for operations with the private key.
193 int PrivateKeyTypeCallback();
194 int PrivateKeySupportsDigestCallback(const EVP_MD
* md
);
195 size_t PrivateKeyMaxSignatureLenCallback();
196 ssl_private_key_result_t
PrivateKeySignCallback(uint8_t* out
,
202 ssl_private_key_result_t
PrivateKeySignCompleteCallback(uint8_t* out
,
206 void OnPrivateKeySignComplete(Error error
,
207 const std::vector
<uint8_t>& signature
);
209 bool transport_send_busy_
;
210 bool transport_recv_busy_
;
212 // Buffers which are shared by BoringSSL and SSLClientSocketOpenSSL.
213 // GrowableIOBuffer is used to keep ownership and setting offset.
214 scoped_refptr
<GrowableIOBuffer
> send_buffer_
;
215 scoped_refptr
<GrowableIOBuffer
> recv_buffer_
;
217 CompletionCallback user_connect_callback_
;
218 CompletionCallback user_read_callback_
;
219 CompletionCallback user_write_callback_
;
221 // Used by Read function.
222 scoped_refptr
<IOBuffer
> user_read_buf_
;
223 int user_read_buf_len_
;
225 // Used by Write function.
226 scoped_refptr
<IOBuffer
> user_write_buf_
;
227 int user_write_buf_len_
;
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_
;
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_
;
241 // If there is a pending read result, the OpenSSLErrorInfo associated with it.
242 OpenSSLErrorInfo pending_read_error_info_
;
244 // Used by TransportReadComplete() to signify an error reading from the
245 // transport socket. A value of OK indicates the socket is still
246 // readable. EOFs are mapped to ERR_CONNECTION_CLOSED.
247 int transport_read_error_
;
249 // Used by TransportWriteComplete() and TransportReadComplete() to signify an
250 // error writing to the transport socket. A value of OK indicates no error.
251 int transport_write_error_
;
253 // Set when Connect finishes.
254 scoped_ptr
<PeerCertificateChain
> server_cert_chain_
;
255 scoped_refptr
<X509Certificate
> server_cert_
;
256 CertVerifyResult server_cert_verify_result_
;
257 bool completed_connect_
;
259 // Set when Read() or Write() successfully reads or writes data to or from the
263 // List of DER-encoded X.509 DistinguishedName of certificate authorities
264 // allowed by the server.
265 std::vector
<std::string
> cert_authorities_
;
266 // List of SSLClientCertType values for client certificates allowed by the
268 std::vector
<SSLClientCertType
> cert_key_types_
;
270 CertVerifier
* const cert_verifier_
;
271 scoped_ptr
<CertVerifier::Request
> cert_verifier_request_
;
272 base::TimeTicks start_cert_verification_time_
;
274 // Certificate Transparency: Verifier and result holder.
275 ct::CTVerifyResult ct_verify_result_
;
276 CTVerifier
* cert_transparency_verifier_
;
278 // The service for retrieving Channel ID keys. May be NULL.
279 ChannelIDService
* channel_id_service_
;
285 scoped_ptr
<ClientSocketHandle
> transport_
;
286 const HostPortPair host_and_port_
;
287 SSLConfig ssl_config_
;
288 // ssl_session_cache_shard_ is an opaque string that partitions the SSL
289 // session cache. i.e. sessions created with one value will not attempt to
290 // resume on the socket with a different value.
291 const std::string ssl_session_cache_shard_
;
296 STATE_HANDSHAKE_COMPLETE
,
297 STATE_CHANNEL_ID_LOOKUP
,
298 STATE_CHANNEL_ID_LOOKUP_COMPLETE
,
300 STATE_VERIFY_CERT_COMPLETE
,
302 State next_handshake_state_
;
303 NextProtoStatus npn_status_
;
304 std::string npn_proto_
;
305 // Written by the |channel_id_service_|.
306 scoped_ptr
<crypto::ECPrivateKey
> channel_id_key_
;
307 // True if a channel ID was sent.
308 bool channel_id_sent_
;
309 // True if the current session was newly-established, but the certificate had
310 // not yet been verified externally, so it cannot be inserted into the cache
312 bool session_pending_
;
313 // True if the initial handshake's certificate has been verified.
314 bool certificate_verified_
;
315 // The request handle for |channel_id_service_|.
316 ChannelIDService::Request channel_id_request_
;
317 SSLFailureState ssl_failure_state_
;
319 scoped_ptr
<SSLPrivateKey
> private_key_
;
320 int signature_result_
;
321 std::vector
<uint8_t> signature_
;
323 TransportSecurityState
* transport_security_state_
;
325 CertPolicyEnforcer
* const policy_enforcer_
;
327 // pinning_failure_log contains a message produced by
328 // TransportSecurityState::CheckPublicKeyPins in the event of a
329 // pinning failure. It is a (somewhat) human-readable string.
330 std::string pinning_failure_log_
;
332 BoundNetLog net_log_
;
333 base::WeakPtrFactory
<SSLClientSocketOpenSSL
> weak_factory_
;
338 #endif // NET_SOCKET_SSL_CLIENT_SOCKET_OPENSSL_H_