blob: 119392c87cf1ed103b8cab8bd6634d9e9b6c0e54 [file] [log] [blame]
[email protected]013c17c2012-01-21 19:09:011// Copyright (c) 2012 The Chromium Authors. All rights reserved.
[email protected]d518cd92010-09-29 12:27:442// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5// OpenSSL binding for SSLClientSocket. The class layout and general principle
6// of operation is derived from SSLClientSocketNSS.
7
8#include "net/socket/ssl_client_socket_openssl.h"
9
[email protected]edfd0f42014-07-22 18:20:3710#include <errno.h>
davidben018aad62014-09-12 02:25:1911#include <openssl/bio.h>
[email protected]d518cd92010-09-29 12:27:4412#include <openssl/err.h>
davidben121e9c962015-05-01 00:40:4913#include <openssl/mem.h>
[email protected]536fd0b2013-03-14 17:41:5714#include <openssl/ssl.h>
bnc67da3de2015-01-15 21:02:2615#include <string.h>
[email protected]d518cd92010-09-29 12:27:4416
[email protected]0f7804ec2011-10-07 20:04:1817#include "base/bind.h"
[email protected]f2da6ac2013-02-04 08:22:5318#include "base/callback_helpers.h"
davidben018aad62014-09-12 02:25:1919#include "base/environment.h"
[email protected]3b63f8f42011-03-28 01:54:1520#include "base/memory/singleton.h"
[email protected]835d7c82010-10-14 04:38:3821#include "base/metrics/histogram.h"
vadimtb2a77c762014-11-21 19:49:2222#include "base/profiler/scoped_tracker.h"
davidben018aad62014-09-12 02:25:1923#include "base/strings/string_piece.h"
[email protected]20305ec2011-01-21 04:55:5224#include "base/synchronization/lock.h"
vadimt6b43dec22015-01-06 01:59:5825#include "base/threading/thread_local.h"
[email protected]ee0f2aa82013-10-25 11:59:2626#include "crypto/ec_private_key.h"
[email protected]4b559b4d2011-04-14 17:37:1427#include "crypto/openssl_util.h"
[email protected]cd9b75b2014-07-10 04:39:3828#include "crypto/scoped_openssl_types.h"
[email protected]d518cd92010-09-29 12:27:4429#include "net/base/net_errors.h"
eranm6571b2b2014-12-03 15:53:2330#include "net/cert/cert_policy_enforcer.h"
[email protected]6e7845ae2013-03-29 21:48:1131#include "net/cert/cert_verifier.h"
eranmefbd3132014-10-28 16:35:1632#include "net/cert/ct_ev_whitelist.h"
davidbeneb5f8ef32014-09-04 14:14:3233#include "net/cert/ct_verifier.h"
[email protected]6e7845ae2013-03-29 21:48:1134#include "net/cert/single_request_cert_verifier.h"
35#include "net/cert/x509_certificate_net_log_param.h"
davidben30798ed82014-09-19 19:28:2036#include "net/cert/x509_util_openssl.h"
[email protected]8bd4e7a2014-08-09 14:49:1737#include "net/http/transport_security_state.h"
davidbenc879af02015-02-20 07:57:2138#include "net/ssl/scoped_openssl_types.h"
[email protected]536fd0b2013-03-14 17:41:5739#include "net/ssl/ssl_cert_request_info.h"
davidbendafe4e52015-04-08 22:53:5240#include "net/ssl/ssl_client_session_cache_openssl.h"
[email protected]536fd0b2013-03-14 17:41:5741#include "net/ssl/ssl_connection_status_flags.h"
42#include "net/ssl/ssl_info.h"
[email protected]d518cd92010-09-29 12:27:4443
davidben8ecc3072014-09-03 23:19:0944#if defined(OS_WIN)
45#include "base/win/windows_version.h"
46#endif
47
[email protected]97a854f2014-07-29 07:51:3648#if defined(USE_OPENSSL_CERTS)
49#include "net/ssl/openssl_client_key_store.h"
50#else
51#include "net/ssl/openssl_platform_key.h"
52#endif
53
[email protected]d518cd92010-09-29 12:27:4454namespace net {
55
56namespace {
57
58// Enable this to see logging for state machine state transitions.
59#if 0
[email protected]3b112772010-10-04 10:54:4960#define GotoState(s) do { DVLOG(2) << (void *)this << " " << __FUNCTION__ << \
[email protected]d518cd92010-09-29 12:27:4461 " jump to state " << s; \
62 next_handshake_state_ = s; } while (0)
63#else
64#define GotoState(s) next_handshake_state_ = s
65#endif
66
[email protected]4b768562013-02-16 04:10:0767// This constant can be any non-negative/non-zero value (eg: it does not
68// overlap with any value of the net::Error range, including net::OK).
69const int kNoPendingReadResult = 1;
70
[email protected]168a8412012-06-14 05:05:4971// If a client doesn't have a list of protocols that it supports, but
72// the server supports NPN, choosing "http/1.1" is the best answer.
73const char kDefaultSupportedNPNProtocol[] = "http/1.1";
74
haavardm2d92e722014-12-19 13:45:4475// Default size of the internal BoringSSL buffers.
76const int KDefaultOpenSSLBufferSize = 17 * 1024;
77
[email protected]82c59022014-08-15 09:38:2778void FreeX509Stack(STACK_OF(X509)* ptr) {
79 sk_X509_pop_free(ptr, X509_free);
80}
81
davidbene94fe0962015-02-21 00:51:3382using ScopedX509Stack = crypto::ScopedOpenSSL<STACK_OF(X509), FreeX509Stack>;
[email protected]6bad5052014-07-12 01:25:1383
[email protected]89038152012-09-07 06:30:1784#if OPENSSL_VERSION_NUMBER < 0x1000103fL
85// This method doesn't seem to have made it into the OpenSSL headers.
[email protected]109805a2010-12-07 18:17:0686unsigned long SSL_CIPHER_get_id(const SSL_CIPHER* cipher) { return cipher->id; }
[email protected]89038152012-09-07 06:30:1787#endif
[email protected]109805a2010-12-07 18:17:0688
89// Used for encoding the |connection_status| field of an SSLInfo object.
pkasting6b68a162014-12-01 22:10:2990int EncodeSSLConnectionStatus(uint16 cipher_suite,
[email protected]109805a2010-12-07 18:17:0691 int compression,
92 int version) {
pkasting6b68a162014-12-01 22:10:2993 return cipher_suite |
[email protected]109805a2010-12-07 18:17:0694 ((compression & SSL_CONNECTION_COMPRESSION_MASK) <<
95 SSL_CONNECTION_COMPRESSION_SHIFT) |
96 ((version & SSL_CONNECTION_VERSION_MASK) <<
97 SSL_CONNECTION_VERSION_SHIFT);
98}
99
100// Returns the net SSL version number (see ssl_connection_status_flags.h) for
101// this SSL connection.
102int GetNetSSLVersion(SSL* ssl) {
[email protected]7e5dd49f2010-12-08 18:33:49103 switch (SSL_version(ssl)) {
[email protected]109805a2010-12-07 18:17:06104 case SSL2_VERSION:
105 return SSL_CONNECTION_VERSION_SSL2;
106 case SSL3_VERSION:
107 return SSL_CONNECTION_VERSION_SSL3;
108 case TLS1_VERSION:
109 return SSL_CONNECTION_VERSION_TLS1;
davidben1d094022014-11-05 18:55:47110 case TLS1_1_VERSION:
[email protected]109805a2010-12-07 18:17:06111 return SSL_CONNECTION_VERSION_TLS1_1;
davidben1d094022014-11-05 18:55:47112 case TLS1_2_VERSION:
[email protected]109805a2010-12-07 18:17:06113 return SSL_CONNECTION_VERSION_TLS1_2;
114 default:
115 return SSL_CONNECTION_VERSION_UNKNOWN;
116 }
117}
118
[email protected]6bad5052014-07-12 01:25:13119ScopedX509 OSCertHandleToOpenSSL(
120 X509Certificate::OSCertHandle os_handle) {
121#if defined(USE_OPENSSL_CERTS)
122 return ScopedX509(X509Certificate::DupOSCertHandle(os_handle));
123#else // !defined(USE_OPENSSL_CERTS)
124 std::string der_encoded;
125 if (!X509Certificate::GetDEREncoded(os_handle, &der_encoded))
126 return ScopedX509();
127 const uint8_t* bytes = reinterpret_cast<const uint8_t*>(der_encoded.data());
128 return ScopedX509(d2i_X509(NULL, &bytes, der_encoded.size()));
129#endif // defined(USE_OPENSSL_CERTS)
130}
131
[email protected]82c59022014-08-15 09:38:27132ScopedX509Stack OSCertHandlesToOpenSSL(
133 const X509Certificate::OSCertHandles& os_handles) {
134 ScopedX509Stack stack(sk_X509_new_null());
135 for (size_t i = 0; i < os_handles.size(); i++) {
136 ScopedX509 x509 = OSCertHandleToOpenSSL(os_handles[i]);
137 if (!x509)
138 return ScopedX509Stack();
139 sk_X509_push(stack.get(), x509.release());
140 }
141 return stack.Pass();
142}
143
davidben018aad62014-09-12 02:25:19144int LogErrorCallback(const char* str, size_t len, void* context) {
145 LOG(ERROR) << base::StringPiece(str, len);
146 return 1;
147}
148
[email protected]821e3bb2013-11-08 01:06:01149} // namespace
150
151class SSLClientSocketOpenSSL::SSLContext {
[email protected]fbef13932010-11-23 12:38:53152 public:
[email protected]b29af7d2010-12-14 11:52:47153 static SSLContext* GetInstance() { return Singleton<SSLContext>::get(); }
[email protected]fbef13932010-11-23 12:38:53154 SSL_CTX* ssl_ctx() { return ssl_ctx_.get(); }
davidbendafe4e52015-04-08 22:53:52155 SSLClientSessionCacheOpenSSL* session_cache() { return &session_cache_; }
[email protected]fbef13932010-11-23 12:38:53156
[email protected]1279de12013-12-03 15:13:32157 SSLClientSocketOpenSSL* GetClientSocketFromSSL(const SSL* ssl) {
[email protected]fbef13932010-11-23 12:38:53158 DCHECK(ssl);
159 SSLClientSocketOpenSSL* socket = static_cast<SSLClientSocketOpenSSL*>(
160 SSL_get_ex_data(ssl, ssl_socket_data_index_));
161 DCHECK(socket);
162 return socket;
163 }
164
165 bool SetClientSocketForSSL(SSL* ssl, SSLClientSocketOpenSSL* socket) {
166 return SSL_set_ex_data(ssl, ssl_socket_data_index_, socket) != 0;
167 }
168
169 private:
170 friend struct DefaultSingletonTraits<SSLContext>;
171
davidbendafe4e52015-04-08 22:53:52172 SSLContext() : session_cache_(SSLClientSessionCacheOpenSSL::Config()) {
[email protected]4b559b4d2011-04-14 17:37:14173 crypto::EnsureOpenSSLInit();
[email protected]fbef13932010-11-23 12:38:53174 ssl_socket_data_index_ = SSL_get_ex_new_index(0, 0, 0, 0, 0);
175 DCHECK_NE(ssl_socket_data_index_, -1);
176 ssl_ctx_.reset(SSL_CTX_new(SSLv23_client_method()));
[email protected]b051cdb62014-02-28 02:20:16177 SSL_CTX_set_cert_verify_callback(ssl_ctx_.get(), CertVerifyCallback, NULL);
[email protected]82c59022014-08-15 09:38:27178 SSL_CTX_set_cert_cb(ssl_ctx_.get(), ClientCertRequestCallback, NULL);
[email protected]b051cdb62014-02-28 02:20:16179 SSL_CTX_set_verify(ssl_ctx_.get(), SSL_VERIFY_PEER, NULL);
haavardmc80b0ee32015-01-30 09:16:08180 // This stops |SSL_shutdown| from generating the close_notify message, which
181 // is currently not sent on the network.
182 // TODO(haavardm): Remove setting quiet shutdown once 118366 is fixed.
183 SSL_CTX_set_quiet_shutdown(ssl_ctx_.get(), 1);
[email protected]ea4a1c6a2010-12-09 13:33:28184 // TODO(kristianm): Only select this if ssl_config_.next_proto is not empty.
185 // It would be better if the callback were not a global setting,
186 // but that is an OpenSSL issue.
187 SSL_CTX_set_next_proto_select_cb(ssl_ctx_.get(), SelectNextProtoCallback,
188 NULL);
[email protected]edfd0f42014-07-22 18:20:37189 ssl_ctx_->tlsext_channel_id_enabled_new = 1;
davidbendafe4e52015-04-08 22:53:52190 SSL_CTX_set_info_callback(ssl_ctx_.get(), InfoCallback);
191
192 // Disable the internal session cache. Session caching is handled
193 // externally (i.e. by SSLClientSessionCacheOpenSSL).
194 SSL_CTX_set_session_cache_mode(
195 ssl_ctx_.get(), SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_NO_INTERNAL);
davidben018aad62014-09-12 02:25:19196
197 scoped_ptr<base::Environment> env(base::Environment::Create());
198 std::string ssl_keylog_file;
199 if (env->GetVar("SSLKEYLOGFILE", &ssl_keylog_file) &&
200 !ssl_keylog_file.empty()) {
201 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
202 BIO* bio = BIO_new_file(ssl_keylog_file.c_str(), "a");
203 if (!bio) {
204 LOG(ERROR) << "Failed to open " << ssl_keylog_file;
205 ERR_print_errors_cb(&LogErrorCallback, NULL);
206 } else {
207 SSL_CTX_set_keylog_bio(ssl_ctx_.get(), bio);
208 }
209 }
[email protected]fbef13932010-11-23 12:38:53210 }
211
[email protected]82c59022014-08-15 09:38:27212 static int ClientCertRequestCallback(SSL* ssl, void* arg) {
[email protected]b29af7d2010-12-14 11:52:47213 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
[email protected]82c59022014-08-15 09:38:27214 DCHECK(socket);
215 return socket->ClientCertRequestCallback(ssl);
[email protected]718c9672010-12-02 10:04:10216 }
217
[email protected]b051cdb62014-02-28 02:20:16218 static int CertVerifyCallback(X509_STORE_CTX *store_ctx, void *arg) {
219 SSL* ssl = reinterpret_cast<SSL*>(X509_STORE_CTX_get_ex_data(
220 store_ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
221 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
222 CHECK(socket);
223
224 return socket->CertVerifyCallback(store_ctx);
225 }
226
[email protected]ea4a1c6a2010-12-09 13:33:28227 static int SelectNextProtoCallback(SSL* ssl,
228 unsigned char** out, unsigned char* outlen,
229 const unsigned char* in,
230 unsigned int inlen, void* arg) {
[email protected]b29af7d2010-12-14 11:52:47231 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
[email protected]ea4a1c6a2010-12-09 13:33:28232 return socket->SelectNextProtoCallback(out, outlen, in, inlen);
233 }
234
davidbendafe4e52015-04-08 22:53:52235 static void InfoCallback(const SSL* ssl, int type, int val) {
236 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
237 socket->InfoCallback(type, val);
238 }
239
[email protected]fbef13932010-11-23 12:38:53240 // This is the index used with SSL_get_ex_data to retrieve the owner
241 // SSLClientSocketOpenSSL object from an SSL instance.
242 int ssl_socket_data_index_;
243
davidbenc879af02015-02-20 07:57:21244 ScopedSSL_CTX ssl_ctx_;
davidbendafe4e52015-04-08 22:53:52245
246 // TODO(davidben): Use a separate cache per URLRequestContext.
247 // https://crbug.com/458365
248 //
249 // TODO(davidben): Sessions should be invalidated on fatal
250 // alerts. https://crbug.com/466352
251 SSLClientSessionCacheOpenSSL session_cache_;
[email protected]1279de12013-12-03 15:13:32252};
253
[email protected]7f38da8a2014-03-17 16:44:26254// PeerCertificateChain is a helper object which extracts the certificate
255// chain, as given by the server, from an OpenSSL socket and performs the needed
256// resource management. The first element of the chain is the leaf certificate
257// and the other elements are in the order given by the server.
258class SSLClientSocketOpenSSL::PeerCertificateChain {
259 public:
[email protected]76e85392014-03-20 17:54:14260 explicit PeerCertificateChain(STACK_OF(X509)* chain) { Reset(chain); }
[email protected]7f38da8a2014-03-17 16:44:26261 PeerCertificateChain(const PeerCertificateChain& other) { *this = other; }
262 ~PeerCertificateChain() {}
263 PeerCertificateChain& operator=(const PeerCertificateChain& other);
264
[email protected]76e85392014-03-20 17:54:14265 // Resets the PeerCertificateChain to the set of certificates in|chain|,
266 // which may be NULL, indicating to empty the store certificates.
267 // Note: If an error occurs, such as being unable to parse the certificates,
268 // this will behave as if Reset(NULL) was called.
269 void Reset(STACK_OF(X509)* chain);
270
[email protected]7f38da8a2014-03-17 16:44:26271 // Note that when USE_OPENSSL is defined, OSCertHandle is X509*
davidben30798ed82014-09-19 19:28:20272 scoped_refptr<X509Certificate> AsOSChain() const;
[email protected]7f38da8a2014-03-17 16:44:26273
274 size_t size() const {
275 if (!openssl_chain_.get())
276 return 0;
277 return sk_X509_num(openssl_chain_.get());
278 }
279
davidben30798ed82014-09-19 19:28:20280 bool empty() const {
281 return size() == 0;
282 }
283
284 X509* Get(size_t index) const {
[email protected]7f38da8a2014-03-17 16:44:26285 DCHECK_LT(index, size());
286 return sk_X509_value(openssl_chain_.get(), index);
287 }
288
289 private:
[email protected]cd9b75b2014-07-10 04:39:38290 ScopedX509Stack openssl_chain_;
[email protected]7f38da8a2014-03-17 16:44:26291};
292
293SSLClientSocketOpenSSL::PeerCertificateChain&
294SSLClientSocketOpenSSL::PeerCertificateChain::operator=(
295 const PeerCertificateChain& other) {
296 if (this == &other)
297 return *this;
298
[email protected]24176af2014-08-14 09:31:04299 openssl_chain_.reset(X509_chain_up_ref(other.openssl_chain_.get()));
[email protected]7f38da8a2014-03-17 16:44:26300 return *this;
301}
302
[email protected]76e85392014-03-20 17:54:14303void SSLClientSocketOpenSSL::PeerCertificateChain::Reset(
304 STACK_OF(X509)* chain) {
davidben30798ed82014-09-19 19:28:20305 openssl_chain_.reset(chain ? X509_chain_up_ref(chain) : NULL);
[email protected]7f38da8a2014-03-17 16:44:26306}
[email protected]7f38da8a2014-03-17 16:44:26307
davidben30798ed82014-09-19 19:28:20308scoped_refptr<X509Certificate>
309SSLClientSocketOpenSSL::PeerCertificateChain::AsOSChain() const {
310#if defined(USE_OPENSSL_CERTS)
311 // When OSCertHandle is typedef'ed to X509, this implementation does a short
312 // cut to avoid converting back and forth between DER and the X509 struct.
313 X509Certificate::OSCertHandles intermediates;
314 for (size_t i = 1; i < sk_X509_num(openssl_chain_.get()); ++i) {
315 intermediates.push_back(sk_X509_value(openssl_chain_.get(), i));
316 }
[email protected]7f38da8a2014-03-17 16:44:26317
davidben30798ed82014-09-19 19:28:20318 return make_scoped_refptr(X509Certificate::CreateFromHandle(
319 sk_X509_value(openssl_chain_.get(), 0), intermediates));
320#else
321 // DER-encode the chain and convert to a platform certificate handle.
[email protected]7f38da8a2014-03-17 16:44:26322 std::vector<base::StringPiece> der_chain;
[email protected]edfd0f42014-07-22 18:20:37323 for (size_t i = 0; i < sk_X509_num(openssl_chain_.get()); ++i) {
[email protected]7f38da8a2014-03-17 16:44:26324 X509* x = sk_X509_value(openssl_chain_.get(), i);
davidben30798ed82014-09-19 19:28:20325 base::StringPiece der;
326 if (!x509_util::GetDER(x, &der))
327 return NULL;
328 der_chain.push_back(der);
[email protected]7f38da8a2014-03-17 16:44:26329 }
330
davidben30798ed82014-09-19 19:28:20331 return make_scoped_refptr(X509Certificate::CreateFromDERCertChain(der_chain));
332#endif
[email protected]7f38da8a2014-03-17 16:44:26333}
[email protected]7f38da8a2014-03-17 16:44:26334
[email protected]1279de12013-12-03 15:13:32335// static
[email protected]c3456bb2011-12-12 22:22:19336void SSLClientSocket::ClearSessionCache() {
[email protected]821e3bb2013-11-08 01:06:01337 SSLClientSocketOpenSSL::SSLContext* context =
338 SSLClientSocketOpenSSL::SSLContext::GetInstance();
[email protected]c3456bb2011-12-12 22:22:19339 context->session_cache()->Flush();
340}
341
bnc86b734dd2014-12-03 00:33:10342// static
343uint16 SSLClientSocket::GetMaxSupportedSSLVersion() {
344 return SSL_PROTOCOL_VERSION_TLS1_2;
345}
346
[email protected]d518cd92010-09-29 12:27:44347SSLClientSocketOpenSSL::SSLClientSocketOpenSSL(
[email protected]18ccfdb2013-08-15 00:13:44348 scoped_ptr<ClientSocketHandle> transport_socket,
[email protected]055d7f22010-11-15 12:03:12349 const HostPortPair& host_and_port,
[email protected]822581d2010-12-16 17:27:15350 const SSLConfig& ssl_config,
[email protected]feb79bcd2011-07-21 16:55:17351 const SSLClientSocketContext& context)
[email protected]83039bb2011-12-09 18:43:55352 : transport_send_busy_(false),
[email protected]d518cd92010-09-29 12:27:44353 transport_recv_busy_(false),
[email protected]4b768562013-02-16 04:10:07354 pending_read_error_(kNoPendingReadResult),
davidbenb8c23212014-10-28 00:12:16355 pending_read_ssl_error_(SSL_ERROR_NONE),
[email protected]5aea79182014-07-14 20:43:41356 transport_read_error_(OK),
[email protected]3e5c6922014-02-06 02:42:16357 transport_write_error_(OK),
[email protected]7f38da8a2014-03-17 16:44:26358 server_cert_chain_(new PeerCertificateChain(NULL)),
[email protected]64b5c892014-08-08 09:39:26359 completed_connect_(false),
[email protected]0dc88b32014-03-26 20:12:28360 was_ever_used_(false),
[email protected]d518cd92010-09-29 12:27:44361 client_auth_cert_needed_(false),
[email protected]feb79bcd2011-07-21 16:55:17362 cert_verifier_(context.cert_verifier),
davidbeneb5f8ef32014-09-04 14:14:32363 cert_transparency_verifier_(context.cert_transparency_verifier),
[email protected]6b8a3c742014-07-25 00:25:35364 channel_id_service_(context.channel_id_service),
[email protected]d518cd92010-09-29 12:27:44365 ssl_(NULL),
366 transport_bio_(NULL),
[email protected]18ccfdb2013-08-15 00:13:44367 transport_(transport_socket.Pass()),
[email protected]055d7f22010-11-15 12:03:12368 host_and_port_(host_and_port),
[email protected]d518cd92010-09-29 12:27:44369 ssl_config_(ssl_config),
[email protected]c3456bb2011-12-12 22:22:19370 ssl_session_cache_shard_(context.ssl_session_cache_shard),
[email protected]013c17c2012-01-21 19:09:01371 next_handshake_state_(STATE_NONE),
[email protected]ea4a1c6a2010-12-09 13:33:28372 npn_status_(kNextProtoUnsupported),
davidben52053b382015-04-27 19:22:29373 channel_id_sent_(false),
davidbendafe4e52015-04-08 22:53:52374 handshake_completed_(false),
375 certificate_verified_(false),
[email protected]8bd4e7a2014-08-09 14:49:17376 transport_security_state_(context.transport_security_state),
eranm6571b2b2014-12-03 15:53:23377 policy_enforcer_(context.cert_policy_enforcer),
kulkarni.acd7b4462014-08-28 07:41:34378 net_log_(transport_->socket()->NetLog()),
379 weak_factory_(this) {
davidben9bbf3292015-04-24 21:50:06380 DCHECK(cert_verifier_);
[email protected]8e458552014-08-05 00:02:15381}
[email protected]d518cd92010-09-29 12:27:44382
383SSLClientSocketOpenSSL::~SSLClientSocketOpenSSL() {
384 Disconnect();
385}
386
[email protected]b9b651f2013-11-09 04:32:22387void SSLClientSocketOpenSSL::GetSSLCertRequestInfo(
388 SSLCertRequestInfo* cert_request_info) {
[email protected]791879c2013-12-17 07:22:41389 cert_request_info->host_and_port = host_and_port_;
[email protected]b9b651f2013-11-09 04:32:22390 cert_request_info->cert_authorities = cert_authorities_;
[email protected]c0787702014-05-20 21:51:44391 cert_request_info->cert_key_types = cert_key_types_;
[email protected]b9b651f2013-11-09 04:32:22392}
393
394SSLClientSocket::NextProtoStatus SSLClientSocketOpenSSL::GetNextProto(
davidben6974bf72015-04-27 17:52:48395 std::string* proto) const {
[email protected]b9b651f2013-11-09 04:32:22396 *proto = npn_proto_;
[email protected]b9b651f2013-11-09 04:32:22397 return npn_status_;
398}
399
[email protected]6b8a3c742014-07-25 00:25:35400ChannelIDService*
401SSLClientSocketOpenSSL::GetChannelIDService() const {
402 return channel_id_service_;
[email protected]b9b651f2013-11-09 04:32:22403}
404
405int SSLClientSocketOpenSSL::ExportKeyingMaterial(
406 const base::StringPiece& label,
407 bool has_context, const base::StringPiece& context,
408 unsigned char* out, unsigned int outlen) {
davidben86935f72015-05-06 22:24:49409 if (!IsConnected())
410 return ERR_SOCKET_NOT_CONNECTED;
411
[email protected]b9b651f2013-11-09 04:32:22412 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
413
414 int rv = SSL_export_keying_material(
[email protected]c8a80e92014-05-17 16:02:08415 ssl_, out, outlen, label.data(), label.size(),
davidben866c3d4a72015-04-06 21:56:43416 reinterpret_cast<const unsigned char*>(context.data()), context.length(),
417 has_context ? 1 : 0);
[email protected]b9b651f2013-11-09 04:32:22418
419 if (rv != 1) {
420 int ssl_error = SSL_get_error(ssl_, rv);
421 LOG(ERROR) << "Failed to export keying material;"
422 << " returned " << rv
423 << ", SSL error code " << ssl_error;
424 return MapOpenSSLError(ssl_error, err_tracer);
425 }
426 return OK;
427}
428
429int SSLClientSocketOpenSSL::GetTLSUniqueChannelBinding(std::string* out) {
[email protected]c8a80e92014-05-17 16:02:08430 NOTIMPLEMENTED();
[email protected]b9b651f2013-11-09 04:32:22431 return ERR_NOT_IMPLEMENTED;
432}
433
434int SSLClientSocketOpenSSL::Connect(const CompletionCallback& callback) {
[email protected]8bd4e7a2014-08-09 14:49:17435 // It is an error to create an SSLClientSocket whose context has no
436 // TransportSecurityState.
437 DCHECK(transport_security_state_);
438
[email protected]b9b651f2013-11-09 04:32:22439 net_log_.BeginEvent(NetLog::TYPE_SSL_CONNECT);
440
441 // Set up new ssl object.
[email protected]c8a80e92014-05-17 16:02:08442 int rv = Init();
443 if (rv != OK) {
444 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
445 return rv;
[email protected]b9b651f2013-11-09 04:32:22446 }
447
448 // Set SSL to client mode. Handshake happens in the loop below.
449 SSL_set_connect_state(ssl_);
450
451 GotoState(STATE_HANDSHAKE);
[email protected]c8a80e92014-05-17 16:02:08452 rv = DoHandshakeLoop(OK);
[email protected]b9b651f2013-11-09 04:32:22453 if (rv == ERR_IO_PENDING) {
454 user_connect_callback_ = callback;
455 } else {
456 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
457 }
458
459 return rv > OK ? OK : rv;
460}
461
462void SSLClientSocketOpenSSL::Disconnect() {
463 if (ssl_) {
464 // Calling SSL_shutdown prevents the session from being marked as
465 // unresumable.
466 SSL_shutdown(ssl_);
467 SSL_free(ssl_);
468 ssl_ = NULL;
469 }
470 if (transport_bio_) {
471 BIO_free_all(transport_bio_);
472 transport_bio_ = NULL;
473 }
474
475 // Shut down anything that may call us back.
476 verifier_.reset();
477 transport_->socket()->Disconnect();
478
479 // Null all callbacks, delete all buffers.
480 transport_send_busy_ = false;
481 send_buffer_ = NULL;
482 transport_recv_busy_ = false;
[email protected]b9b651f2013-11-09 04:32:22483 recv_buffer_ = NULL;
484
485 user_connect_callback_.Reset();
486 user_read_callback_.Reset();
487 user_write_callback_.Reset();
488 user_read_buf_ = NULL;
489 user_read_buf_len_ = 0;
490 user_write_buf_ = NULL;
491 user_write_buf_len_ = 0;
492
[email protected]3e5c6922014-02-06 02:42:16493 pending_read_error_ = kNoPendingReadResult;
davidbenb8c23212014-10-28 00:12:16494 pending_read_ssl_error_ = SSL_ERROR_NONE;
495 pending_read_error_info_ = OpenSSLErrorInfo();
496
[email protected]5aea79182014-07-14 20:43:41497 transport_read_error_ = OK;
[email protected]3e5c6922014-02-06 02:42:16498 transport_write_error_ = OK;
499
[email protected]b9b651f2013-11-09 04:32:22500 server_cert_verify_result_.Reset();
[email protected]64b5c892014-08-08 09:39:26501 completed_connect_ = false;
[email protected]b9b651f2013-11-09 04:32:22502
503 cert_authorities_.clear();
[email protected]c0787702014-05-20 21:51:44504 cert_key_types_.clear();
[email protected]b9b651f2013-11-09 04:32:22505 client_auth_cert_needed_ = false;
[email protected]faff9852014-06-21 06:13:46506
davidben09c3d072014-08-25 20:33:58507 start_cert_verification_time_ = base::TimeTicks();
508
[email protected]abc44b752014-07-30 03:52:15509 npn_status_ = kNextProtoUnsupported;
510 npn_proto_.clear();
511
davidben52053b382015-04-27 19:22:29512 channel_id_sent_ = false;
[email protected]faff9852014-06-21 06:13:46513 channel_id_request_handle_.Cancel();
[email protected]b9b651f2013-11-09 04:32:22514}
515
516bool SSLClientSocketOpenSSL::IsConnected() const {
517 // If the handshake has not yet completed.
[email protected]64b5c892014-08-08 09:39:26518 if (!completed_connect_)
[email protected]b9b651f2013-11-09 04:32:22519 return false;
520 // If an asynchronous operation is still pending.
521 if (user_read_buf_.get() || user_write_buf_.get())
522 return true;
523
524 return transport_->socket()->IsConnected();
525}
526
527bool SSLClientSocketOpenSSL::IsConnectedAndIdle() const {
528 // If the handshake has not yet completed.
[email protected]64b5c892014-08-08 09:39:26529 if (!completed_connect_)
[email protected]b9b651f2013-11-09 04:32:22530 return false;
531 // If an asynchronous operation is still pending.
532 if (user_read_buf_.get() || user_write_buf_.get())
533 return false;
davidbenfc9a6b82015-04-15 23:47:32534
535 // If there is data read from the network that has not yet been consumed, do
536 // not treat the connection as idle.
537 //
538 // Note that this does not check |BIO_pending|, whether there is ciphertext
539 // that has not yet been flushed to the network. |Write| returns early, so
540 // this can cause race conditions which cause a socket to not be treated
541 // reusable when it should be. See https://crbug.com/466147.
542 if (BIO_wpending(transport_bio_) > 0)
[email protected]b9b651f2013-11-09 04:32:22543 return false;
[email protected]b9b651f2013-11-09 04:32:22544
545 return transport_->socket()->IsConnectedAndIdle();
546}
547
548int SSLClientSocketOpenSSL::GetPeerAddress(IPEndPoint* addressList) const {
549 return transport_->socket()->GetPeerAddress(addressList);
550}
551
552int SSLClientSocketOpenSSL::GetLocalAddress(IPEndPoint* addressList) const {
553 return transport_->socket()->GetLocalAddress(addressList);
554}
555
556const BoundNetLog& SSLClientSocketOpenSSL::NetLog() const {
557 return net_log_;
558}
559
560void SSLClientSocketOpenSSL::SetSubresourceSpeculation() {
561 if (transport_.get() && transport_->socket()) {
562 transport_->socket()->SetSubresourceSpeculation();
563 } else {
564 NOTREACHED();
565 }
566}
567
568void SSLClientSocketOpenSSL::SetOmniboxSpeculation() {
569 if (transport_.get() && transport_->socket()) {
570 transport_->socket()->SetOmniboxSpeculation();
571 } else {
572 NOTREACHED();
573 }
574}
575
576bool SSLClientSocketOpenSSL::WasEverUsed() const {
[email protected]0dc88b32014-03-26 20:12:28577 return was_ever_used_;
[email protected]b9b651f2013-11-09 04:32:22578}
579
580bool SSLClientSocketOpenSSL::UsingTCPFastOpen() const {
581 if (transport_.get() && transport_->socket())
582 return transport_->socket()->UsingTCPFastOpen();
583
584 NOTREACHED();
585 return false;
586}
587
588bool SSLClientSocketOpenSSL::GetSSLInfo(SSLInfo* ssl_info) {
589 ssl_info->Reset();
davidben30798ed82014-09-19 19:28:20590 if (server_cert_chain_->empty())
[email protected]b9b651f2013-11-09 04:32:22591 return false;
592
593 ssl_info->cert = server_cert_verify_result_.verified_cert;
594 ssl_info->cert_status = server_cert_verify_result_.cert_status;
595 ssl_info->is_issued_by_known_root =
596 server_cert_verify_result_.is_issued_by_known_root;
597 ssl_info->public_key_hashes =
598 server_cert_verify_result_.public_key_hashes;
599 ssl_info->client_cert_sent =
600 ssl_config_.send_client_cert && ssl_config_.client_cert.get();
davidben52053b382015-04-27 19:22:29601 ssl_info->channel_id_sent = channel_id_sent_;
[email protected]8bd4e7a2014-08-09 14:49:17602 ssl_info->pinning_failure_log = pinning_failure_log_;
[email protected]b9b651f2013-11-09 04:32:22603
davidbeneb5f8ef32014-09-04 14:14:32604 AddSCTInfoToSSLInfo(ssl_info);
605
[email protected]b9b651f2013-11-09 04:32:22606 const SSL_CIPHER* cipher = SSL_get_current_cipher(ssl_);
607 CHECK(cipher);
608 ssl_info->security_bits = SSL_CIPHER_get_bits(cipher, NULL);
[email protected]b9b651f2013-11-09 04:32:22609
610 ssl_info->connection_status = EncodeSSLConnectionStatus(
pkasting6b68a162014-12-01 22:10:29611 static_cast<uint16>(SSL_CIPHER_get_id(cipher)), 0 /* no compression */,
[email protected]b9b651f2013-11-09 04:32:22612 GetNetSSLVersion(ssl_));
613
davidben09c3d072014-08-25 20:33:58614 if (!SSL_get_secure_renegotiation_support(ssl_))
[email protected]b9b651f2013-11-09 04:32:22615 ssl_info->connection_status |= SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION;
[email protected]b9b651f2013-11-09 04:32:22616
617 if (ssl_config_.version_fallback)
618 ssl_info->connection_status |= SSL_CONNECTION_VERSION_FALLBACK;
619
620 ssl_info->handshake_type = SSL_session_reused(ssl_) ?
621 SSLInfo::HANDSHAKE_RESUME : SSLInfo::HANDSHAKE_FULL;
622
623 DVLOG(3) << "Encoded connection status: cipher suite = "
624 << SSLConnectionStatusToCipherSuite(ssl_info->connection_status)
625 << " version = "
626 << SSLConnectionStatusToVersion(ssl_info->connection_status);
627 return true;
628}
629
630int SSLClientSocketOpenSSL::Read(IOBuffer* buf,
631 int buf_len,
632 const CompletionCallback& callback) {
633 user_read_buf_ = buf;
634 user_read_buf_len_ = buf_len;
635
davidben1b133ad2014-10-23 04:23:13636 int rv = DoReadLoop();
[email protected]b9b651f2013-11-09 04:32:22637
638 if (rv == ERR_IO_PENDING) {
639 user_read_callback_ = callback;
640 } else {
[email protected]0dc88b32014-03-26 20:12:28641 if (rv > 0)
642 was_ever_used_ = true;
[email protected]b9b651f2013-11-09 04:32:22643 user_read_buf_ = NULL;
644 user_read_buf_len_ = 0;
645 }
646
647 return rv;
648}
649
650int SSLClientSocketOpenSSL::Write(IOBuffer* buf,
651 int buf_len,
652 const CompletionCallback& callback) {
653 user_write_buf_ = buf;
654 user_write_buf_len_ = buf_len;
655
davidben1b133ad2014-10-23 04:23:13656 int rv = DoWriteLoop();
[email protected]b9b651f2013-11-09 04:32:22657
658 if (rv == ERR_IO_PENDING) {
659 user_write_callback_ = callback;
660 } else {
[email protected]0dc88b32014-03-26 20:12:28661 if (rv > 0)
662 was_ever_used_ = true;
[email protected]b9b651f2013-11-09 04:32:22663 user_write_buf_ = NULL;
664 user_write_buf_len_ = 0;
665 }
666
667 return rv;
668}
669
[email protected]28b96d1c2014-04-09 12:21:15670int SSLClientSocketOpenSSL::SetReceiveBufferSize(int32 size) {
[email protected]b9b651f2013-11-09 04:32:22671 return transport_->socket()->SetReceiveBufferSize(size);
672}
673
[email protected]28b96d1c2014-04-09 12:21:15674int SSLClientSocketOpenSSL::SetSendBufferSize(int32 size) {
[email protected]b9b651f2013-11-09 04:32:22675 return transport_->socket()->SetSendBufferSize(size);
676}
677
[email protected]c8a80e92014-05-17 16:02:08678int SSLClientSocketOpenSSL::Init() {
[email protected]9e733f32010-10-04 18:19:08679 DCHECK(!ssl_);
680 DCHECK(!transport_bio_);
681
[email protected]b29af7d2010-12-14 11:52:47682 SSLContext* context = SSLContext::GetInstance();
[email protected]4b559b4d2011-04-14 17:37:14683 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
[email protected]d518cd92010-09-29 12:27:44684
[email protected]fbef13932010-11-23 12:38:53685 ssl_ = SSL_new(context->ssl_ctx());
686 if (!ssl_ || !context->SetClientSocketForSSL(ssl_, this))
[email protected]c8a80e92014-05-17 16:02:08687 return ERR_UNEXPECTED;
[email protected]fbef13932010-11-23 12:38:53688
689 if (!SSL_set_tlsext_host_name(ssl_, host_and_port_.host().c_str()))
[email protected]c8a80e92014-05-17 16:02:08690 return ERR_UNEXPECTED;
[email protected]fbef13932010-11-23 12:38:53691
davidbendafe4e52015-04-08 22:53:52692 SSL_SESSION* session = context->session_cache()->Lookup(GetSessionCacheKey());
693 if (session != nullptr)
694 SSL_set_session(ssl_, session);
[email protected]d518cd92010-09-29 12:27:44695
haavardm2d92e722014-12-19 13:45:44696 send_buffer_ = new GrowableIOBuffer();
697 send_buffer_->SetCapacity(KDefaultOpenSSLBufferSize);
698 recv_buffer_ = new GrowableIOBuffer();
699 recv_buffer_->SetCapacity(KDefaultOpenSSLBufferSize);
700
[email protected]d518cd92010-09-29 12:27:44701 BIO* ssl_bio = NULL;
haavardm2d92e722014-12-19 13:45:44702
703 // SSLClientSocketOpenSSL retains ownership of the BIO buffers.
704 if (!BIO_new_bio_pair_external_buf(
705 &ssl_bio, send_buffer_->capacity(),
706 reinterpret_cast<uint8_t*>(send_buffer_->data()), &transport_bio_,
707 recv_buffer_->capacity(),
708 reinterpret_cast<uint8_t*>(recv_buffer_->data())))
[email protected]c8a80e92014-05-17 16:02:08709 return ERR_UNEXPECTED;
[email protected]d518cd92010-09-29 12:27:44710 DCHECK(ssl_bio);
711 DCHECK(transport_bio_);
712
[email protected]5aea79182014-07-14 20:43:41713 // Install a callback on OpenSSL's end to plumb transport errors through.
rsleevif020edc2015-03-16 19:31:24714 BIO_set_callback(ssl_bio, &SSLClientSocketOpenSSL::BIOCallback);
[email protected]5aea79182014-07-14 20:43:41715 BIO_set_callback_arg(ssl_bio, reinterpret_cast<char*>(this));
716
[email protected]d518cd92010-09-29 12:27:44717 SSL_set_bio(ssl_, ssl_bio, ssl_bio);
718
[email protected]9e733f32010-10-04 18:19:08719 // OpenSSL defaults some options to on, others to off. To avoid ambiguity,
720 // set everything we care about to an absolute value.
[email protected]fb10e2282010-12-01 17:08:48721 SslSetClearMask options;
722 options.ConfigureFlag(SSL_OP_NO_SSLv2, true);
[email protected]80c75f682012-05-26 16:22:17723 bool ssl3_enabled = (ssl_config_.version_min == SSL_PROTOCOL_VERSION_SSL3);
724 options.ConfigureFlag(SSL_OP_NO_SSLv3, !ssl3_enabled);
725 bool tls1_enabled = (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1 &&
726 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1);
727 options.ConfigureFlag(SSL_OP_NO_TLSv1, !tls1_enabled);
[email protected]80c75f682012-05-26 16:22:17728 bool tls1_1_enabled =
729 (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1_1 &&
730 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1_1);
731 options.ConfigureFlag(SSL_OP_NO_TLSv1_1, !tls1_1_enabled);
[email protected]80c75f682012-05-26 16:22:17732 bool tls1_2_enabled =
733 (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1_2 &&
734 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1_2);
735 options.ConfigureFlag(SSL_OP_NO_TLSv1_2, !tls1_2_enabled);
[email protected]fb10e2282010-12-01 17:08:48736
[email protected]d0f00492012-08-03 22:35:13737 options.ConfigureFlag(SSL_OP_NO_COMPRESSION, true);
[email protected]9e733f32010-10-04 18:19:08738
739 // TODO(joth): Set this conditionally, see http://crbug.com/55410
[email protected]fb10e2282010-12-01 17:08:48740 options.ConfigureFlag(SSL_OP_LEGACY_SERVER_CONNECT, true);
[email protected]9e733f32010-10-04 18:19:08741
[email protected]fb10e2282010-12-01 17:08:48742 SSL_set_options(ssl_, options.set_mask);
743 SSL_clear_options(ssl_, options.clear_mask);
[email protected]9e733f32010-10-04 18:19:08744
[email protected]fb10e2282010-12-01 17:08:48745 // Same as above, this time for the SSL mode.
746 SslSetClearMask mode;
[email protected]9e733f32010-10-04 18:19:08747
[email protected]fb10e2282010-12-01 17:08:48748 mode.ConfigureFlag(SSL_MODE_RELEASE_BUFFERS, true);
ishermane5c05e12014-09-09 20:32:15749 mode.ConfigureFlag(SSL_MODE_CBC_RECORD_SPLITTING, true);
[email protected]fb10e2282010-12-01 17:08:48750
davidben818d93b2015-02-19 22:27:32751 mode.ConfigureFlag(SSL_MODE_ENABLE_FALSE_START,
[email protected]b788de02014-04-23 18:06:07752 ssl_config_.false_start_enabled);
753
davidben6b8131c2015-02-25 23:30:14754 mode.ConfigureFlag(SSL_MODE_SEND_FALLBACK_SCSV, ssl_config_.version_fallback);
755
[email protected]fb10e2282010-12-01 17:08:48756 SSL_set_mode(ssl_, mode.set_mask);
757 SSL_clear_mode(ssl_, mode.clear_mask);
[email protected]109805a2010-12-07 18:17:06758
759 // Removing ciphers by ID from OpenSSL is a bit involved as we must use the
760 // textual name with SSL_set_cipher_list because there is no public API to
761 // directly remove a cipher by ID.
762 STACK_OF(SSL_CIPHER)* ciphers = SSL_get_ciphers(ssl_);
763 DCHECK(ciphers);
764 // See SSLConfig::disabled_cipher_suites for description of the suites
[email protected]9b4bc4a92013-08-20 22:59:07765 // disabled by default. Note that !SHA256 and !SHA384 only remove HMAC-SHA256
766 // and HMAC-SHA384 cipher suites, not GCM cipher suites with SHA256 or SHA384
767 // as the handshake hash.
bnc1e757502014-12-13 02:20:16768 std::string command(
769 "DEFAULT:!NULL:!aNULL:!SHA256:!SHA384:!aECDH:!AESGCM+AES256:!aPSK");
[email protected]109805a2010-12-07 18:17:06770 // Walk through all the installed ciphers, seeing if any need to be
771 // appended to the cipher removal |command|.
[email protected]edfd0f42014-07-22 18:20:37772 for (size_t i = 0; i < sk_SSL_CIPHER_num(ciphers); ++i) {
[email protected]109805a2010-12-07 18:17:06773 const SSL_CIPHER* cipher = sk_SSL_CIPHER_value(ciphers, i);
pkasting6b68a162014-12-01 22:10:29774 const uint16 id = static_cast<uint16>(SSL_CIPHER_get_id(cipher));
[email protected]109805a2010-12-07 18:17:06775 // Remove any ciphers with a strength of less than 80 bits. Note the NSS
776 // implementation uses "effective" bits here but OpenSSL does not provide
777 // this detail. This only impacts Triple DES: reports 112 vs. 168 bits,
778 // both of which are greater than 80 anyway.
779 bool disable = SSL_CIPHER_get_bits(cipher, NULL) < 80;
780 if (!disable) {
781 disable = std::find(ssl_config_.disabled_cipher_suites.begin(),
782 ssl_config_.disabled_cipher_suites.end(), id) !=
783 ssl_config_.disabled_cipher_suites.end();
784 }
785 if (disable) {
786 const char* name = SSL_CIPHER_get_name(cipher);
787 DVLOG(3) << "Found cipher to remove: '" << name << "', ID: " << id
788 << " strength: " << SSL_CIPHER_get_bits(cipher, NULL);
789 command.append(":!");
790 command.append(name);
791 }
792 }
davidben8ecc3072014-09-03 23:19:09793
davidbena4c9d062015-04-03 22:34:25794 if (!ssl_config_.enable_deprecated_cipher_suites)
795 command.append(":!RC4");
796
davidben8ecc3072014-09-03 23:19:09797 // Disable ECDSA cipher suites on platforms that do not support ECDSA
798 // signed certificates, as servers may use the presence of such
799 // ciphersuites as a hint to send an ECDSA certificate.
800#if defined(OS_WIN)
801 if (base::win::GetVersion() < base::win::VERSION_VISTA)
802 command.append(":!ECDSA");
803#endif
804
[email protected]109805a2010-12-07 18:17:06805 int rv = SSL_set_cipher_list(ssl_, command.c_str());
806 // If this fails (rv = 0) it means there are no ciphers enabled on this SSL.
807 // This will almost certainly result in the socket failing to complete the
808 // handshake at which point the appropriate error is bubbled up to the client.
809 LOG_IF(WARNING, rv != 1) << "SSL_set_cipher_list('" << command << "') "
810 "returned " << rv;
[email protected]ee0f2aa82013-10-25 11:59:26811
812 // TLS channel ids.
[email protected]6b8a3c742014-07-25 00:25:35813 if (IsChannelIDEnabled(ssl_config_, channel_id_service_)) {
[email protected]ee0f2aa82013-10-25 11:59:26814 SSL_enable_tls_channel_id(ssl_);
815 }
816
[email protected]abc44b752014-07-30 03:52:15817 if (!ssl_config_.next_protos.empty()) {
bnc1e757502014-12-13 02:20:16818 // Get list of ciphers that are enabled.
819 STACK_OF(SSL_CIPHER)* enabled_ciphers = SSL_get_ciphers(ssl_);
820 DCHECK(enabled_ciphers);
821 std::vector<uint16> enabled_ciphers_vector;
822 for (size_t i = 0; i < sk_SSL_CIPHER_num(enabled_ciphers); ++i) {
823 const SSL_CIPHER* cipher = sk_SSL_CIPHER_value(enabled_ciphers, i);
824 const uint16 id = static_cast<uint16>(SSL_CIPHER_get_id(cipher));
825 enabled_ciphers_vector.push_back(id);
826 }
827
[email protected]abc44b752014-07-30 03:52:15828 std::vector<uint8_t> wire_protos =
bnc1e757502014-12-13 02:20:16829 SerializeNextProtos(ssl_config_.next_protos,
830 HasCipherAdequateForHTTP2(enabled_ciphers_vector) &&
831 IsTLSVersionAdequateForHTTP2(ssl_config_));
[email protected]abc44b752014-07-30 03:52:15832 SSL_set_alpn_protos(ssl_, wire_protos.empty() ? NULL : &wire_protos[0],
833 wire_protos.size());
834 }
835
davidbeneb5f8ef32014-09-04 14:14:32836 if (ssl_config_.signed_cert_timestamps_enabled) {
837 SSL_enable_signed_cert_timestamps(ssl_);
838 SSL_enable_ocsp_stapling(ssl_);
839 }
840
davidben15f57132015-04-27 18:08:36841 if (cert_verifier_->SupportsOCSPStapling())
davidbend1fb2f12014-11-08 02:51:00842 SSL_enable_ocsp_stapling(ssl_);
davidbeneb5f8ef32014-09-04 14:14:32843
davidben24463662015-04-09 23:36:48844 // Enable fastradio padding.
845 SSL_enable_fastradio_padding(ssl_,
846 ssl_config_.fastradio_padding_enabled &&
847 ssl_config_.fastradio_padding_eligible);
848
[email protected]c8a80e92014-05-17 16:02:08849 return OK;
[email protected]d518cd92010-09-29 12:27:44850}
851
[email protected]b9b651f2013-11-09 04:32:22852void SSLClientSocketOpenSSL::DoReadCallback(int rv) {
853 // Since Run may result in Read being called, clear |user_read_callback_|
854 // up front.
[email protected]0dc88b32014-03-26 20:12:28855 if (rv > 0)
856 was_ever_used_ = true;
[email protected]b9b651f2013-11-09 04:32:22857 user_read_buf_ = NULL;
858 user_read_buf_len_ = 0;
859 base::ResetAndReturn(&user_read_callback_).Run(rv);
860}
861
862void SSLClientSocketOpenSSL::DoWriteCallback(int rv) {
863 // Since Run may result in Write being called, clear |user_write_callback_|
864 // up front.
[email protected]0dc88b32014-03-26 20:12:28865 if (rv > 0)
866 was_ever_used_ = true;
[email protected]b9b651f2013-11-09 04:32:22867 user_write_buf_ = NULL;
868 user_write_buf_len_ = 0;
869 base::ResetAndReturn(&user_write_callback_).Run(rv);
870}
871
872bool SSLClientSocketOpenSSL::DoTransportIO() {
873 bool network_moved = false;
874 int rv;
875 // Read and write as much data as possible. The loop is necessary because
876 // Write() may return synchronously.
877 do {
878 rv = BufferSend();
879 if (rv != ERR_IO_PENDING && rv != 0)
880 network_moved = true;
881 } while (rv > 0);
[email protected]5aea79182014-07-14 20:43:41882 if (transport_read_error_ == OK && BufferRecv() != ERR_IO_PENDING)
[email protected]b9b651f2013-11-09 04:32:22883 network_moved = true;
884 return network_moved;
885}
886
pkasting379234c2015-04-08 04:42:12887// TODO(cbentzel): Remove including "base/threading/thread_local.h" and
vadimt6b43dec22015-01-06 01:59:58888// g_first_run_completed once crbug.com/424386 is fixed.
889base::LazyInstance<base::ThreadLocalBoolean>::Leaky g_first_run_completed =
890 LAZY_INSTANCE_INITIALIZER;
891
[email protected]b9b651f2013-11-09 04:32:22892int SSLClientSocketOpenSSL::DoHandshake() {
893 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
[email protected]c8a80e92014-05-17 16:02:08894 int net_error = OK;
vadimt5a243282014-12-24 00:26:16895
896 int rv;
897
pkasting379234c2015-04-08 04:42:12898 // TODO(cbentzel): Leave only 1 call to SSL_do_handshake once crbug.com/424386
vadimt5a243282014-12-24 00:26:16899 // is fixed.
900 if (ssl_config_.send_client_cert && ssl_config_.client_cert.get()) {
vadimt5a243282014-12-24 00:26:16901 rv = SSL_do_handshake(ssl_);
902 } else {
vadimt6b43dec22015-01-06 01:59:58903 if (g_first_run_completed.Get().Get()) {
pkasting379234c2015-04-08 04:42:12904 // TODO(cbentzel): Remove ScopedTracker below once crbug.com/424386 is
vadimt6b43dec22015-01-06 01:59:58905 // fixed.
pkasting379234c2015-04-08 04:42:12906 tracked_objects::ScopedTracker tracking_profile(
907 FROM_HERE_WITH_EXPLICIT_FUNCTION("424386 SSL_do_handshake()"));
vadimt5a243282014-12-24 00:26:16908
vadimt6b43dec22015-01-06 01:59:58909 rv = SSL_do_handshake(ssl_);
910 } else {
911 g_first_run_completed.Get().Set(true);
vadimt6b43dec22015-01-06 01:59:58912 rv = SSL_do_handshake(ssl_);
913 }
vadimt5a243282014-12-24 00:26:16914 }
[email protected]b9b651f2013-11-09 04:32:22915
davidben8114f802015-03-25 17:02:34916 if (rv == 1) {
Adam Langley32352ad2014-10-14 22:31:00917 if (ssl_config_.version_fallback &&
918 ssl_config_.version_max < ssl_config_.version_fallback_min) {
919 return ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION;
920 }
921
[email protected]abc44b752014-07-30 03:52:15922 // SSL handshake is completed. If NPN wasn't negotiated, see if ALPN was.
923 if (npn_status_ == kNextProtoUnsupported) {
924 const uint8_t* alpn_proto = NULL;
925 unsigned alpn_len = 0;
926 SSL_get0_alpn_selected(ssl_, &alpn_proto, &alpn_len);
927 if (alpn_len > 0) {
928 npn_proto_.assign(reinterpret_cast<const char*>(alpn_proto), alpn_len);
929 npn_status_ = kNextProtoNegotiated;
bnc0d28ea52014-10-13 15:15:38930 set_negotiation_extension(kExtensionALPN);
[email protected]abc44b752014-07-30 03:52:15931 }
932 }
933
davidben6974bf72015-04-27 17:52:48934 RecordNegotiationExtension();
davidben52053b382015-04-27 19:22:29935 RecordChannelIDSupport(channel_id_service_, channel_id_sent_,
davidben09c3d072014-08-25 20:33:58936 ssl_config_.channel_id_enabled,
937 crypto::ECPrivateKey::IsSupported());
938
davidbend1fb2f12014-11-08 02:51:00939 // Only record OCSP histograms if OCSP was requested.
940 if (ssl_config_.signed_cert_timestamps_enabled ||
davidben15f57132015-04-27 18:08:36941 cert_verifier_->SupportsOCSPStapling()) {
davidben54015aa2014-12-02 22:16:23942 const uint8_t* ocsp_response;
davidbend1fb2f12014-11-08 02:51:00943 size_t ocsp_response_len;
944 SSL_get0_ocsp_response(ssl_, &ocsp_response, &ocsp_response_len);
945
946 set_stapled_ocsp_response_received(ocsp_response_len != 0);
947 UMA_HISTOGRAM_BOOLEAN("Net.OCSPResponseStapled", ocsp_response_len != 0);
948 }
davidbeneb5f8ef32014-09-04 14:14:32949
davidben54015aa2014-12-02 22:16:23950 const uint8_t* sct_list;
davidbeneb5f8ef32014-09-04 14:14:32951 size_t sct_list_len;
952 SSL_get0_signed_cert_timestamp_list(ssl_, &sct_list, &sct_list_len);
953 set_signed_cert_timestamps_received(sct_list_len != 0);
954
[email protected]abc44b752014-07-30 03:52:15955 // Verify the certificate.
davidben30798ed82014-09-19 19:28:20956 UpdateServerCert();
[email protected]b9b651f2013-11-09 04:32:22957 GotoState(STATE_VERIFY_CERT);
958 } else {
davidben8114f802015-03-25 17:02:34959 if (client_auth_cert_needed_)
960 return ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
961
[email protected]b9b651f2013-11-09 04:32:22962 int ssl_error = SSL_get_error(ssl_, rv);
963
964 if (ssl_error == SSL_ERROR_WANT_CHANNEL_ID_LOOKUP) {
[email protected]faff9852014-06-21 06:13:46965 // The server supports channel ID. Stop to look one up before returning to
966 // the handshake.
[email protected]faff9852014-06-21 06:13:46967 GotoState(STATE_CHANNEL_ID_LOOKUP);
968 return OK;
[email protected]b9b651f2013-11-09 04:32:22969 }
970
davidbena4409c62014-08-27 17:05:51971 OpenSSLErrorInfo error_info;
972 net_error = MapOpenSSLErrorWithDetails(ssl_error, err_tracer, &error_info);
[email protected]faff9852014-06-21 06:13:46973
[email protected]b9b651f2013-11-09 04:32:22974 // If not done, stay in this state
975 if (net_error == ERR_IO_PENDING) {
976 GotoState(STATE_HANDSHAKE);
977 } else {
978 LOG(ERROR) << "handshake failed; returned " << rv
979 << ", SSL error code " << ssl_error
980 << ", net_error " << net_error;
981 net_log_.AddEvent(
982 NetLog::TYPE_SSL_HANDSHAKE_ERROR,
davidbena4409c62014-08-27 17:05:51983 CreateNetLogOpenSSLErrorCallback(net_error, ssl_error, error_info));
[email protected]b9b651f2013-11-09 04:32:22984 }
985 }
986 return net_error;
987}
988
[email protected]faff9852014-06-21 06:13:46989int SSLClientSocketOpenSSL::DoChannelIDLookup() {
rch98cf4472015-02-13 00:14:14990 net_log_.AddEvent(NetLog::TYPE_SSL_CHANNEL_ID_REQUESTED);
[email protected]faff9852014-06-21 06:13:46991 GotoState(STATE_CHANNEL_ID_LOOKUP_COMPLETE);
[email protected]6b8a3c742014-07-25 00:25:35992 return channel_id_service_->GetOrCreateChannelID(
[email protected]faff9852014-06-21 06:13:46993 host_and_port_.host(),
994 &channel_id_private_key_,
995 &channel_id_cert_,
996 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete,
997 base::Unretained(this)),
998 &channel_id_request_handle_);
999}
1000
1001int SSLClientSocketOpenSSL::DoChannelIDLookupComplete(int result) {
1002 if (result < 0)
1003 return result;
1004
1005 DCHECK_LT(0u, channel_id_private_key_.size());
1006 // Decode key.
1007 std::vector<uint8> encrypted_private_key_info;
1008 std::vector<uint8> subject_public_key_info;
1009 encrypted_private_key_info.assign(
1010 channel_id_private_key_.data(),
1011 channel_id_private_key_.data() + channel_id_private_key_.size());
1012 subject_public_key_info.assign(
1013 channel_id_cert_.data(),
1014 channel_id_cert_.data() + channel_id_cert_.size());
1015 scoped_ptr<crypto::ECPrivateKey> ec_private_key(
1016 crypto::ECPrivateKey::CreateFromEncryptedPrivateKeyInfo(
[email protected]6b8a3c742014-07-25 00:25:351017 ChannelIDService::kEPKIPassword,
[email protected]faff9852014-06-21 06:13:461018 encrypted_private_key_info,
1019 subject_public_key_info));
1020 if (!ec_private_key) {
1021 LOG(ERROR) << "Failed to import Channel ID.";
1022 return ERR_CHANNEL_ID_IMPORT_FAILED;
1023 }
1024
1025 // Hand the key to OpenSSL. Check for error in case OpenSSL rejects the key
1026 // type.
1027 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1028 int rv = SSL_set1_tls_channel_id(ssl_, ec_private_key->key());
1029 if (!rv) {
1030 LOG(ERROR) << "Failed to set Channel ID.";
1031 int err = SSL_get_error(ssl_, rv);
1032 return MapOpenSSLError(err, err_tracer);
1033 }
1034
1035 // Return to the handshake.
davidben52053b382015-04-27 19:22:291036 channel_id_sent_ = true;
rch98cf4472015-02-13 00:14:141037 net_log_.AddEvent(NetLog::TYPE_SSL_CHANNEL_ID_PROVIDED);
[email protected]faff9852014-06-21 06:13:461038 GotoState(STATE_HANDSHAKE);
1039 return OK;
1040}
1041
[email protected]b9b651f2013-11-09 04:32:221042int SSLClientSocketOpenSSL::DoVerifyCert(int result) {
davidben30798ed82014-09-19 19:28:201043 DCHECK(!server_cert_chain_->empty());
davidben09c3d072014-08-25 20:33:581044 DCHECK(start_cert_verification_time_.is_null());
davidben30798ed82014-09-19 19:28:201045
[email protected]b9b651f2013-11-09 04:32:221046 GotoState(STATE_VERIFY_CERT_COMPLETE);
1047
davidben30798ed82014-09-19 19:28:201048 // If the certificate is bad and has been previously accepted, use
1049 // the previous status and bypass the error.
1050 base::StringPiece der_cert;
1051 if (!x509_util::GetDER(server_cert_chain_->Get(0), &der_cert)) {
1052 NOTREACHED();
1053 return ERR_CERT_INVALID;
1054 }
[email protected]b9b651f2013-11-09 04:32:221055 CertStatus cert_status;
davidben30798ed82014-09-19 19:28:201056 if (ssl_config_.IsAllowedBadCert(der_cert, &cert_status)) {
[email protected]b9b651f2013-11-09 04:32:221057 VLOG(1) << "Received an expected bad cert with status: " << cert_status;
1058 server_cert_verify_result_.Reset();
1059 server_cert_verify_result_.cert_status = cert_status;
1060 server_cert_verify_result_.verified_cert = server_cert_;
1061 return OK;
1062 }
1063
davidben30798ed82014-09-19 19:28:201064 // When running in a sandbox, it may not be possible to create an
1065 // X509Certificate*, as that may depend on OS functionality blocked
1066 // in the sandbox.
1067 if (!server_cert_.get()) {
1068 server_cert_verify_result_.Reset();
1069 server_cert_verify_result_.cert_status = CERT_STATUS_INVALID;
1070 return ERR_CERT_INVALID;
1071 }
1072
davidben15f57132015-04-27 18:08:361073 std::string ocsp_response;
1074 if (cert_verifier_->SupportsOCSPStapling()) {
1075 const uint8_t* ocsp_response_raw;
1076 size_t ocsp_response_len;
1077 SSL_get0_ocsp_response(ssl_, &ocsp_response_raw, &ocsp_response_len);
1078 ocsp_response.assign(reinterpret_cast<const char*>(ocsp_response_raw),
1079 ocsp_response_len);
1080 }
1081
davidben09c3d072014-08-25 20:33:581082 start_cert_verification_time_ = base::TimeTicks::Now();
1083
[email protected]b9b651f2013-11-09 04:32:221084 int flags = 0;
1085 if (ssl_config_.rev_checking_enabled)
1086 flags |= CertVerifier::VERIFY_REV_CHECKING_ENABLED;
1087 if (ssl_config_.verify_ev_cert)
1088 flags |= CertVerifier::VERIFY_EV_CERT;
1089 if (ssl_config_.cert_io_enabled)
1090 flags |= CertVerifier::VERIFY_CERT_IO_ENABLED;
1091 if (ssl_config_.rev_checking_required_local_anchors)
1092 flags |= CertVerifier::VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS;
1093 verifier_.reset(new SingleRequestCertVerifier(cert_verifier_));
1094 return verifier_->Verify(
davidben15f57132015-04-27 18:08:361095 server_cert_.get(), host_and_port_.host(), ocsp_response, flags,
[email protected]591cffcd2014-08-18 20:02:301096 // TODO(davidben): Route the CRLSet through SSLConfig so
1097 // SSLClientSocket doesn't depend on SSLConfigService.
davidben15f57132015-04-27 18:08:361098 SSLConfigService::GetCRLSet().get(), &server_cert_verify_result_,
[email protected]b9b651f2013-11-09 04:32:221099 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete,
1100 base::Unretained(this)),
1101 net_log_);
1102}
1103
1104int SSLClientSocketOpenSSL::DoVerifyCertComplete(int result) {
1105 verifier_.reset();
1106
davidben09c3d072014-08-25 20:33:581107 if (!start_cert_verification_time_.is_null()) {
1108 base::TimeDelta verify_time =
1109 base::TimeTicks::Now() - start_cert_verification_time_;
1110 if (result == OK) {
1111 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTime", verify_time);
1112 } else {
1113 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTimeError", verify_time);
1114 }
1115 }
1116
davidben85574eb2014-12-12 03:01:571117 if (result == OK) {
davidben85574eb2014-12-12 03:01:571118 if (SSL_session_reused(ssl_)) {
1119 // Record whether or not the server tried to resume a session for a
1120 // different version. See https://crbug.com/441456.
1121 UMA_HISTOGRAM_BOOLEAN(
1122 "Net.SSLSessionVersionMatch",
1123 SSL_version(ssl_) == SSL_get_session(ssl_)->ssl_version);
1124 }
1125 }
1126
[email protected]8bd4e7a2014-08-09 14:49:171127 const CertStatus cert_status = server_cert_verify_result_.cert_status;
1128 if (transport_security_state_ &&
1129 (result == OK ||
1130 (IsCertificateError(result) && IsCertStatusMinorError(cert_status))) &&
1131 !transport_security_state_->CheckPublicKeyPins(
1132 host_and_port_.host(),
[email protected]8bd4e7a2014-08-09 14:49:171133 server_cert_verify_result_.is_issued_by_known_root,
1134 server_cert_verify_result_.public_key_hashes,
1135 &pinning_failure_log_)) {
1136 result = ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN;
1137 }
1138
[email protected]b9b651f2013-11-09 04:32:221139 if (result == OK) {
davidbeneb5f8ef32014-09-04 14:14:321140 // Only check Certificate Transparency if there were no other errors with
1141 // the connection.
1142 VerifyCT();
1143
davidbendafe4e52015-04-08 22:53:521144 DCHECK(!certificate_verified_);
1145 certificate_verified_ = true;
1146 MaybeCacheSession();
[email protected]b9b651f2013-11-09 04:32:221147 } else {
1148 DVLOG(1) << "DoVerifyCertComplete error " << ErrorToString(result)
1149 << " (" << result << ")";
1150 }
1151
[email protected]64b5c892014-08-08 09:39:261152 completed_connect_ = true;
[email protected]b9b651f2013-11-09 04:32:221153 // Exit DoHandshakeLoop and return the result to the caller to Connect.
1154 DCHECK_EQ(STATE_NONE, next_handshake_state_);
1155 return result;
1156}
1157
1158void SSLClientSocketOpenSSL::DoConnectCallback(int rv) {
1159 if (!user_connect_callback_.is_null()) {
1160 CompletionCallback c = user_connect_callback_;
1161 user_connect_callback_.Reset();
1162 c.Run(rv > OK ? OK : rv);
1163 }
1164}
1165
davidben30798ed82014-09-19 19:28:201166void SSLClientSocketOpenSSL::UpdateServerCert() {
[email protected]76e85392014-03-20 17:54:141167 server_cert_chain_->Reset(SSL_get_peer_cert_chain(ssl_));
[email protected]7f38da8a2014-03-17 16:44:261168 server_cert_ = server_cert_chain_->AsOSChain();
davidben30798ed82014-09-19 19:28:201169 if (server_cert_.get()) {
1170 net_log_.AddEvent(
1171 NetLog::TYPE_SSL_CERTIFICATES_RECEIVED,
1172 base::Bind(&NetLogX509CertificateCallback,
1173 base::Unretained(server_cert_.get())));
1174 }
[email protected]b9b651f2013-11-09 04:32:221175}
1176
davidbeneb5f8ef32014-09-04 14:14:321177void SSLClientSocketOpenSSL::VerifyCT() {
1178 if (!cert_transparency_verifier_)
1179 return;
1180
davidben54015aa2014-12-02 22:16:231181 const uint8_t* ocsp_response_raw;
davidbeneb5f8ef32014-09-04 14:14:321182 size_t ocsp_response_len;
1183 SSL_get0_ocsp_response(ssl_, &ocsp_response_raw, &ocsp_response_len);
1184 std::string ocsp_response;
1185 if (ocsp_response_len > 0) {
1186 ocsp_response.assign(reinterpret_cast<const char*>(ocsp_response_raw),
1187 ocsp_response_len);
1188 }
1189
davidben54015aa2014-12-02 22:16:231190 const uint8_t* sct_list_raw;
davidbeneb5f8ef32014-09-04 14:14:321191 size_t sct_list_len;
1192 SSL_get0_signed_cert_timestamp_list(ssl_, &sct_list_raw, &sct_list_len);
1193 std::string sct_list;
1194 if (sct_list_len > 0)
1195 sct_list.assign(reinterpret_cast<const char*>(sct_list_raw), sct_list_len);
1196
1197 // Note that this is a completely synchronous operation: The CT Log Verifier
1198 // gets all the data it needs for SCT verification and does not do any
1199 // external communication.
eranm6571b2b2014-12-03 15:53:231200 cert_transparency_verifier_->Verify(
1201 server_cert_verify_result_.verified_cert.get(), ocsp_response, sct_list,
1202 &ct_verify_result_, net_log_);
davidbeneb5f8ef32014-09-04 14:14:321203
eranm6571b2b2014-12-03 15:53:231204 if (!policy_enforcer_) {
1205 server_cert_verify_result_.cert_status &= ~CERT_STATUS_IS_EV;
1206 } else {
1207 if (server_cert_verify_result_.cert_status & CERT_STATUS_IS_EV) {
1208 scoped_refptr<ct::EVCertsWhitelist> ev_whitelist =
1209 SSLConfigService::GetEVCertsWhitelist();
1210 if (!policy_enforcer_->DoesConformToCTEVPolicy(
1211 server_cert_verify_result_.verified_cert.get(),
eranm18a019272014-12-18 08:43:231212 ev_whitelist.get(), ct_verify_result_, net_log_)) {
eranm6571b2b2014-12-03 15:53:231213 // TODO(eranm): Log via the BoundNetLog, see crbug.com/437766
1214 VLOG(1) << "EV certificate for "
1215 << server_cert_verify_result_.verified_cert->subject()
1216 .GetDisplayName()
1217 << " does not conform to CT policy, removing EV status.";
1218 server_cert_verify_result_.cert_status &= ~CERT_STATUS_IS_EV;
1219 }
1220 }
1221 }
davidbeneb5f8ef32014-09-04 14:14:321222}
1223
[email protected]b9b651f2013-11-09 04:32:221224void SSLClientSocketOpenSSL::OnHandshakeIOComplete(int result) {
1225 int rv = DoHandshakeLoop(result);
1226 if (rv != ERR_IO_PENDING) {
1227 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
1228 DoConnectCallback(rv);
1229 }
1230}
1231
1232void SSLClientSocketOpenSSL::OnSendComplete(int result) {
1233 if (next_handshake_state_ == STATE_HANDSHAKE) {
1234 // In handshake phase.
1235 OnHandshakeIOComplete(result);
1236 return;
1237 }
1238
1239 // OnSendComplete may need to call DoPayloadRead while the renegotiation
1240 // handshake is in progress.
1241 int rv_read = ERR_IO_PENDING;
1242 int rv_write = ERR_IO_PENDING;
1243 bool network_moved;
1244 do {
1245 if (user_read_buf_.get())
1246 rv_read = DoPayloadRead();
1247 if (user_write_buf_.get())
1248 rv_write = DoPayloadWrite();
1249 network_moved = DoTransportIO();
1250 } while (rv_read == ERR_IO_PENDING && rv_write == ERR_IO_PENDING &&
1251 (user_read_buf_.get() || user_write_buf_.get()) && network_moved);
1252
1253 // Performing the Read callback may cause |this| to be deleted. If this
1254 // happens, the Write callback should not be invoked. Guard against this by
1255 // holding a WeakPtr to |this| and ensuring it's still valid.
1256 base::WeakPtr<SSLClientSocketOpenSSL> guard(weak_factory_.GetWeakPtr());
1257 if (user_read_buf_.get() && rv_read != ERR_IO_PENDING)
1258 DoReadCallback(rv_read);
1259
1260 if (!guard.get())
1261 return;
1262
1263 if (user_write_buf_.get() && rv_write != ERR_IO_PENDING)
1264 DoWriteCallback(rv_write);
1265}
1266
1267void SSLClientSocketOpenSSL::OnRecvComplete(int result) {
1268 if (next_handshake_state_ == STATE_HANDSHAKE) {
1269 // In handshake phase.
1270 OnHandshakeIOComplete(result);
1271 return;
1272 }
1273
1274 // Network layer received some data, check if client requested to read
1275 // decrypted data.
1276 if (!user_read_buf_.get())
1277 return;
1278
davidben1b133ad2014-10-23 04:23:131279 int rv = DoReadLoop();
[email protected]b9b651f2013-11-09 04:32:221280 if (rv != ERR_IO_PENDING)
1281 DoReadCallback(rv);
1282}
1283
1284int SSLClientSocketOpenSSL::DoHandshakeLoop(int last_io_result) {
1285 int rv = last_io_result;
1286 do {
1287 // Default to STATE_NONE for next state.
1288 // (This is a quirk carried over from the windows
1289 // implementation. It makes reading the logs a bit harder.)
1290 // State handlers can and often do call GotoState just
1291 // to stay in the current state.
1292 State state = next_handshake_state_;
1293 GotoState(STATE_NONE);
1294 switch (state) {
1295 case STATE_HANDSHAKE:
1296 rv = DoHandshake();
1297 break;
[email protected]faff9852014-06-21 06:13:461298 case STATE_CHANNEL_ID_LOOKUP:
1299 DCHECK_EQ(OK, rv);
1300 rv = DoChannelIDLookup();
1301 break;
1302 case STATE_CHANNEL_ID_LOOKUP_COMPLETE:
1303 rv = DoChannelIDLookupComplete(rv);
1304 break;
[email protected]b9b651f2013-11-09 04:32:221305 case STATE_VERIFY_CERT:
[email protected]faff9852014-06-21 06:13:461306 DCHECK_EQ(OK, rv);
[email protected]b9b651f2013-11-09 04:32:221307 rv = DoVerifyCert(rv);
1308 break;
1309 case STATE_VERIFY_CERT_COMPLETE:
1310 rv = DoVerifyCertComplete(rv);
1311 break;
1312 case STATE_NONE:
1313 default:
1314 rv = ERR_UNEXPECTED;
1315 NOTREACHED() << "unexpected state" << state;
1316 break;
1317 }
1318
1319 bool network_moved = DoTransportIO();
1320 if (network_moved && next_handshake_state_ == STATE_HANDSHAKE) {
1321 // In general we exit the loop if rv is ERR_IO_PENDING. In this
1322 // special case we keep looping even if rv is ERR_IO_PENDING because
1323 // the transport IO may allow DoHandshake to make progress.
1324 rv = OK; // This causes us to stay in the loop.
1325 }
1326 } while (rv != ERR_IO_PENDING && next_handshake_state_ != STATE_NONE);
1327 return rv;
1328}
1329
davidben1b133ad2014-10-23 04:23:131330int SSLClientSocketOpenSSL::DoReadLoop() {
[email protected]b9b651f2013-11-09 04:32:221331 bool network_moved;
1332 int rv;
1333 do {
1334 rv = DoPayloadRead();
1335 network_moved = DoTransportIO();
1336 } while (rv == ERR_IO_PENDING && network_moved);
1337
1338 return rv;
1339}
1340
davidben1b133ad2014-10-23 04:23:131341int SSLClientSocketOpenSSL::DoWriteLoop() {
[email protected]b9b651f2013-11-09 04:32:221342 bool network_moved;
1343 int rv;
1344 do {
1345 rv = DoPayloadWrite();
1346 network_moved = DoTransportIO();
1347 } while (rv == ERR_IO_PENDING && network_moved);
1348
1349 return rv;
1350}
1351
1352int SSLClientSocketOpenSSL::DoPayloadRead() {
1353 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1354
davidben7e555daf2015-03-25 17:03:291355 DCHECK_LT(0, user_read_buf_len_);
1356 DCHECK(user_read_buf_.get());
1357
[email protected]b9b651f2013-11-09 04:32:221358 int rv;
1359 if (pending_read_error_ != kNoPendingReadResult) {
1360 rv = pending_read_error_;
1361 pending_read_error_ = kNoPendingReadResult;
1362 if (rv == 0) {
1363 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED,
1364 rv, user_read_buf_->data());
davidbenb8c23212014-10-28 00:12:161365 } else {
1366 net_log_.AddEvent(
1367 NetLog::TYPE_SSL_READ_ERROR,
1368 CreateNetLogOpenSSLErrorCallback(rv, pending_read_ssl_error_,
1369 pending_read_error_info_));
[email protected]b9b651f2013-11-09 04:32:221370 }
davidbenb8c23212014-10-28 00:12:161371 pending_read_ssl_error_ = SSL_ERROR_NONE;
1372 pending_read_error_info_ = OpenSSLErrorInfo();
[email protected]b9b651f2013-11-09 04:32:221373 return rv;
1374 }
1375
1376 int total_bytes_read = 0;
davidben7e555daf2015-03-25 17:03:291377 int ssl_ret;
[email protected]b9b651f2013-11-09 04:32:221378 do {
davidben7e555daf2015-03-25 17:03:291379 ssl_ret = SSL_read(ssl_, user_read_buf_->data() + total_bytes_read,
1380 user_read_buf_len_ - total_bytes_read);
1381 if (ssl_ret > 0)
1382 total_bytes_read += ssl_ret;
1383 } while (total_bytes_read < user_read_buf_len_ && ssl_ret > 0);
[email protected]b9b651f2013-11-09 04:32:221384
davidben7e555daf2015-03-25 17:03:291385 // Although only the final SSL_read call may have failed, the failure needs to
1386 // processed immediately, while the information still available in OpenSSL's
1387 // error queue.
1388 if (client_auth_cert_needed_) {
1389 pending_read_error_ = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
1390 } else if (ssl_ret <= 0) {
1391 // A zero return from SSL_read may mean any of:
1392 // - The underlying BIO_read returned 0.
1393 // - The peer sent a close_notify.
1394 // - Any arbitrary error. https://crbug.com/466303
[email protected]b9b651f2013-11-09 04:32:221395 //
davidben7e555daf2015-03-25 17:03:291396 // TransportReadComplete converts the first to an ERR_CONNECTION_CLOSED
1397 // error, so it does not occur. The second and third are distinguished by
1398 // SSL_ERROR_ZERO_RETURN.
1399 pending_read_ssl_error_ = SSL_get_error(ssl_, ssl_ret);
1400 if (pending_read_ssl_error_ == SSL_ERROR_ZERO_RETURN) {
1401 pending_read_error_ = 0;
1402 } else {
1403 pending_read_error_ = MapOpenSSLErrorWithDetails(
1404 pending_read_ssl_error_, err_tracer, &pending_read_error_info_);
[email protected]b9b651f2013-11-09 04:32:221405 }
1406
davidben7e555daf2015-03-25 17:03:291407 // Many servers do not reliably send a close_notify alert when shutting down
1408 // a connection, and instead terminate the TCP connection. This is reported
1409 // as ERR_CONNECTION_CLOSED. Because of this, map the unclean shutdown to a
1410 // graceful EOF, instead of treating it as an error as it should be.
1411 if (pending_read_error_ == ERR_CONNECTION_CLOSED)
1412 pending_read_error_ = 0;
1413 }
davidbenbe6ce7ec2014-10-20 19:15:561414
davidben7e555daf2015-03-25 17:03:291415 if (total_bytes_read > 0) {
1416 // Return any bytes read to the caller. The error will be deferred to the
1417 // next call of DoPayloadRead.
1418 rv = total_bytes_read;
davidbenbe6ce7ec2014-10-20 19:15:561419
davidben7e555daf2015-03-25 17:03:291420 // Do not treat insufficient data as an error to return in the next call to
1421 // DoPayloadRead() - instead, let the call fall through to check SSL_read()
1422 // again. This is because DoTransportIO() may complete in between the next
1423 // call to DoPayloadRead(), and thus it is important to check SSL_read() on
1424 // subsequent invocations to see if a complete record may now be read.
1425 if (pending_read_error_ == ERR_IO_PENDING)
1426 pending_read_error_ = kNoPendingReadResult;
1427 } else {
1428 // No bytes were returned. Return the pending read error immediately.
1429 DCHECK_NE(kNoPendingReadResult, pending_read_error_);
1430 rv = pending_read_error_;
1431 pending_read_error_ = kNoPendingReadResult;
[email protected]b9b651f2013-11-09 04:32:221432 }
1433
1434 if (rv >= 0) {
1435 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, rv,
1436 user_read_buf_->data());
davidbenb8c23212014-10-28 00:12:161437 } else if (rv != ERR_IO_PENDING) {
1438 net_log_.AddEvent(
1439 NetLog::TYPE_SSL_READ_ERROR,
1440 CreateNetLogOpenSSLErrorCallback(rv, pending_read_ssl_error_,
1441 pending_read_error_info_));
1442 pending_read_ssl_error_ = SSL_ERROR_NONE;
1443 pending_read_error_info_ = OpenSSLErrorInfo();
[email protected]b9b651f2013-11-09 04:32:221444 }
1445 return rv;
1446}
1447
1448int SSLClientSocketOpenSSL::DoPayloadWrite() {
1449 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1450 int rv = SSL_write(ssl_, user_write_buf_->data(), user_write_buf_len_);
rsleevif020edc2015-03-16 19:31:241451
[email protected]b9b651f2013-11-09 04:32:221452 if (rv >= 0) {
1453 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_SENT, rv,
1454 user_write_buf_->data());
1455 return rv;
1456 }
1457
davidbenb8c23212014-10-28 00:12:161458 int ssl_error = SSL_get_error(ssl_, rv);
1459 OpenSSLErrorInfo error_info;
1460 int net_error = MapOpenSSLErrorWithDetails(ssl_error, err_tracer,
1461 &error_info);
1462
1463 if (net_error != ERR_IO_PENDING) {
1464 net_log_.AddEvent(
1465 NetLog::TYPE_SSL_WRITE_ERROR,
1466 CreateNetLogOpenSSLErrorCallback(net_error, ssl_error, error_info));
1467 }
1468 return net_error;
[email protected]b9b651f2013-11-09 04:32:221469}
1470
1471int SSLClientSocketOpenSSL::BufferSend(void) {
1472 if (transport_send_busy_)
1473 return ERR_IO_PENDING;
1474
haavardm2d92e722014-12-19 13:45:441475 size_t buffer_read_offset;
1476 uint8_t* read_buf;
1477 size_t max_read;
1478 int status = BIO_zero_copy_get_read_buf(transport_bio_, &read_buf,
1479 &buffer_read_offset, &max_read);
1480 DCHECK_EQ(status, 1); // Should never fail.
1481 if (!max_read)
1482 return 0; // Nothing pending in the OpenSSL write BIO.
1483 CHECK_EQ(read_buf, reinterpret_cast<uint8_t*>(send_buffer_->StartOfBuffer()));
1484 CHECK_LT(buffer_read_offset, static_cast<size_t>(send_buffer_->capacity()));
1485 send_buffer_->set_offset(buffer_read_offset);
[email protected]b9b651f2013-11-09 04:32:221486
1487 int rv = transport_->socket()->Write(
haavardm2d92e722014-12-19 13:45:441488 send_buffer_.get(), max_read,
[email protected]b9b651f2013-11-09 04:32:221489 base::Bind(&SSLClientSocketOpenSSL::BufferSendComplete,
1490 base::Unretained(this)));
1491 if (rv == ERR_IO_PENDING) {
1492 transport_send_busy_ = true;
1493 } else {
1494 TransportWriteComplete(rv);
1495 }
1496 return rv;
1497}
1498
1499int SSLClientSocketOpenSSL::BufferRecv(void) {
1500 if (transport_recv_busy_)
1501 return ERR_IO_PENDING;
1502
1503 // Determine how much was requested from |transport_bio_| that was not
1504 // actually available.
1505 size_t requested = BIO_ctrl_get_read_request(transport_bio_);
1506 if (requested == 0) {
1507 // This is not a perfect match of error codes, as no operation is
1508 // actually pending. However, returning 0 would be interpreted as
1509 // a possible sign of EOF, which is also an inappropriate match.
1510 return ERR_IO_PENDING;
1511 }
1512
1513 // Known Issue: While only reading |requested| data is the more correct
1514 // implementation, it has the downside of resulting in frequent reads:
1515 // One read for the SSL record header (~5 bytes) and one read for the SSL
1516 // record body. Rather than issuing these reads to the underlying socket
1517 // (and constantly allocating new IOBuffers), a single Read() request to
1518 // fill |transport_bio_| is issued. As long as an SSL client socket cannot
1519 // be gracefully shutdown (via SSL close alerts) and re-used for non-SSL
1520 // traffic, this over-subscribed Read()ing will not cause issues.
haavardm2d92e722014-12-19 13:45:441521
1522 size_t buffer_write_offset;
1523 uint8_t* write_buf;
1524 size_t max_write;
1525 int status = BIO_zero_copy_get_write_buf(transport_bio_, &write_buf,
1526 &buffer_write_offset, &max_write);
1527 DCHECK_EQ(status, 1); // Should never fail.
[email protected]b9b651f2013-11-09 04:32:221528 if (!max_write)
1529 return ERR_IO_PENDING;
1530
haavardm2d92e722014-12-19 13:45:441531 CHECK_EQ(write_buf,
1532 reinterpret_cast<uint8_t*>(recv_buffer_->StartOfBuffer()));
1533 CHECK_LT(buffer_write_offset, static_cast<size_t>(recv_buffer_->capacity()));
1534
1535 recv_buffer_->set_offset(buffer_write_offset);
[email protected]b9b651f2013-11-09 04:32:221536 int rv = transport_->socket()->Read(
1537 recv_buffer_.get(),
1538 max_write,
1539 base::Bind(&SSLClientSocketOpenSSL::BufferRecvComplete,
1540 base::Unretained(this)));
1541 if (rv == ERR_IO_PENDING) {
1542 transport_recv_busy_ = true;
1543 } else {
[email protected]3e5c6922014-02-06 02:42:161544 rv = TransportReadComplete(rv);
[email protected]b9b651f2013-11-09 04:32:221545 }
1546 return rv;
1547}
1548
1549void SSLClientSocketOpenSSL::BufferSendComplete(int result) {
[email protected]b9b651f2013-11-09 04:32:221550 TransportWriteComplete(result);
1551 OnSendComplete(result);
1552}
1553
1554void SSLClientSocketOpenSSL::BufferRecvComplete(int result) {
[email protected]3e5c6922014-02-06 02:42:161555 result = TransportReadComplete(result);
[email protected]b9b651f2013-11-09 04:32:221556 OnRecvComplete(result);
1557}
1558
1559void SSLClientSocketOpenSSL::TransportWriteComplete(int result) {
1560 DCHECK(ERR_IO_PENDING != result);
haavardm2d92e722014-12-19 13:45:441561 int bytes_written = 0;
[email protected]b9b651f2013-11-09 04:32:221562 if (result < 0) {
[email protected]5aea79182014-07-14 20:43:411563 // Record the error. Save it to be reported in a future read or write on
1564 // transport_bio_'s peer.
[email protected]3e5c6922014-02-06 02:42:161565 transport_write_error_ = result;
[email protected]b9b651f2013-11-09 04:32:221566 } else {
haavardm2d92e722014-12-19 13:45:441567 bytes_written = result;
[email protected]b9b651f2013-11-09 04:32:221568 }
haavardm2d92e722014-12-19 13:45:441569 DCHECK_GE(send_buffer_->RemainingCapacity(), bytes_written);
1570 int ret = BIO_zero_copy_get_read_buf_done(transport_bio_, bytes_written);
1571 DCHECK_EQ(1, ret);
1572 transport_send_busy_ = false;
[email protected]b9b651f2013-11-09 04:32:221573}
1574
[email protected]3e5c6922014-02-06 02:42:161575int SSLClientSocketOpenSSL::TransportReadComplete(int result) {
[email protected]b9b651f2013-11-09 04:32:221576 DCHECK(ERR_IO_PENDING != result);
[email protected]5aea79182014-07-14 20:43:411577 // If an EOF, canonicalize to ERR_CONNECTION_CLOSED here so MapOpenSSLError
1578 // does not report success.
1579 if (result == 0)
1580 result = ERR_CONNECTION_CLOSED;
haavardm2d92e722014-12-19 13:45:441581 int bytes_read = 0;
[email protected]5aea79182014-07-14 20:43:411582 if (result < 0) {
[email protected]b9b651f2013-11-09 04:32:221583 DVLOG(1) << "TransportReadComplete result " << result;
[email protected]5aea79182014-07-14 20:43:411584 // Received an error. Save it to be reported in a future read on
1585 // transport_bio_'s peer.
1586 transport_read_error_ = result;
[email protected]b9b651f2013-11-09 04:32:221587 } else {
haavardm2d92e722014-12-19 13:45:441588 bytes_read = result;
[email protected]b9b651f2013-11-09 04:32:221589 }
haavardm2d92e722014-12-19 13:45:441590 DCHECK_GE(recv_buffer_->RemainingCapacity(), bytes_read);
1591 int ret = BIO_zero_copy_get_write_buf_done(transport_bio_, bytes_read);
1592 DCHECK_EQ(1, ret);
[email protected]b9b651f2013-11-09 04:32:221593 transport_recv_busy_ = false;
[email protected]3e5c6922014-02-06 02:42:161594 return result;
[email protected]b9b651f2013-11-09 04:32:221595}
1596
[email protected]82c59022014-08-15 09:38:271597int SSLClientSocketOpenSSL::ClientCertRequestCallback(SSL* ssl) {
[email protected]5ac981e182010-12-06 17:56:271598 DVLOG(3) << "OpenSSL ClientCertRequestCallback called";
1599 DCHECK(ssl == ssl_);
[email protected]82c59022014-08-15 09:38:271600
davidbenaf42cbe2014-11-13 03:27:461601 net_log_.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED);
1602
[email protected]82c59022014-08-15 09:38:271603 // Clear any currently configured certificates.
1604 SSL_certs_clear(ssl_);
[email protected]97a854f2014-07-29 07:51:361605
1606#if defined(OS_IOS)
1607 // TODO(droger): Support client auth on iOS. See http://crbug.com/145954).
1608 LOG(WARNING) << "Client auth is not supported";
1609#else // !defined(OS_IOS)
[email protected]5ac981e182010-12-06 17:56:271610 if (!ssl_config_.send_client_cert) {
[email protected]515adc22013-01-09 16:01:231611 // First pass: we know that a client certificate is needed, but we do not
1612 // have one at hand.
[email protected]5ac981e182010-12-06 17:56:271613 client_auth_cert_needed_ = true;
[email protected]515adc22013-01-09 16:01:231614 STACK_OF(X509_NAME) *authorities = SSL_get_client_CA_list(ssl);
[email protected]edfd0f42014-07-22 18:20:371615 for (size_t i = 0; i < sk_X509_NAME_num(authorities); i++) {
[email protected]515adc22013-01-09 16:01:231616 X509_NAME *ca_name = (X509_NAME *)sk_X509_NAME_value(authorities, i);
1617 unsigned char* str = NULL;
1618 int length = i2d_X509_NAME(ca_name, &str);
1619 cert_authorities_.push_back(std::string(
1620 reinterpret_cast<const char*>(str),
1621 static_cast<size_t>(length)));
1622 OPENSSL_free(str);
1623 }
1624
[email protected]c0787702014-05-20 21:51:441625 const unsigned char* client_cert_types;
[email protected]e7e883e2014-07-25 06:03:081626 size_t num_client_cert_types =
1627 SSL_get0_certificate_types(ssl, &client_cert_types);
[email protected]c0787702014-05-20 21:51:441628 for (size_t i = 0; i < num_client_cert_types; i++) {
1629 cert_key_types_.push_back(
1630 static_cast<SSLClientCertType>(client_cert_types[i]));
1631 }
1632
[email protected]5ac981e182010-12-06 17:56:271633 return -1; // Suspends handshake.
1634 }
1635
1636 // Second pass: a client certificate should have been selected.
[email protected]13914c92013-06-13 22:42:421637 if (ssl_config_.client_cert.get()) {
[email protected]6bad5052014-07-12 01:25:131638 ScopedX509 leaf_x509 =
1639 OSCertHandleToOpenSSL(ssl_config_.client_cert->os_cert_handle());
1640 if (!leaf_x509) {
1641 LOG(WARNING) << "Failed to import certificate";
1642 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT);
1643 return -1;
1644 }
1645
[email protected]82c59022014-08-15 09:38:271646 ScopedX509Stack chain = OSCertHandlesToOpenSSL(
1647 ssl_config_.client_cert->GetIntermediateCertificates());
1648 if (!chain) {
1649 LOG(WARNING) << "Failed to import intermediate certificates";
1650 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT);
1651 return -1;
1652 }
1653
[email protected]97a854f2014-07-29 07:51:361654 // TODO(davidben): With Linux client auth support, this should be
1655 // conditioned on OS_ANDROID and then, with https://crbug.com/394131,
1656 // removed altogether. OpenSSLClientKeyStore is mostly an artifact of the
1657 // net/ client auth API lacking a private key handle.
[email protected]c0787702014-05-20 21:51:441658#if defined(USE_OPENSSL_CERTS)
[email protected]97a854f2014-07-29 07:51:361659 crypto::ScopedEVP_PKEY privkey =
1660 OpenSSLClientKeyStore::GetInstance()->FetchClientCertPrivateKey(
1661 ssl_config_.client_cert.get());
1662#else // !defined(USE_OPENSSL_CERTS)
1663 crypto::ScopedEVP_PKEY privkey =
1664 FetchClientCertPrivateKey(ssl_config_.client_cert.get());
1665#endif // defined(USE_OPENSSL_CERTS)
1666 if (!privkey) {
[email protected]6bad5052014-07-12 01:25:131667 // Could not find the private key. Fail the handshake and surface an
1668 // appropriate error to the caller.
1669 LOG(WARNING) << "Client cert found without private key";
1670 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY);
1671 return -1;
[email protected]0c6523f2010-12-10 10:56:241672 }
[email protected]6bad5052014-07-12 01:25:131673
[email protected]82c59022014-08-15 09:38:271674 if (!SSL_use_certificate(ssl_, leaf_x509.get()) ||
1675 !SSL_use_PrivateKey(ssl_, privkey.get()) ||
1676 !SSL_set1_chain(ssl_, chain.get())) {
1677 LOG(WARNING) << "Failed to set client certificate";
1678 return -1;
1679 }
davidbenaf42cbe2014-11-13 03:27:461680
1681 int cert_count = 1 + sk_X509_num(chain.get());
1682 net_log_.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED,
1683 NetLog::IntegerCallback("cert_count", cert_count));
[email protected]6bad5052014-07-12 01:25:131684 return 1;
[email protected]c0787702014-05-20 21:51:441685 }
[email protected]97a854f2014-07-29 07:51:361686#endif // defined(OS_IOS)
[email protected]5ac981e182010-12-06 17:56:271687
1688 // Send no client certificate.
davidbenaf42cbe2014-11-13 03:27:461689 net_log_.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED,
1690 NetLog::IntegerCallback("cert_count", 0));
[email protected]82c59022014-08-15 09:38:271691 return 1;
[email protected]5ac981e182010-12-06 17:56:271692}
1693
[email protected]b051cdb62014-02-28 02:20:161694int SSLClientSocketOpenSSL::CertVerifyCallback(X509_STORE_CTX* store_ctx) {
[email protected]64b5c892014-08-08 09:39:261695 if (!completed_connect_) {
[email protected]b051cdb62014-02-28 02:20:161696 // If the first handshake hasn't completed then we accept any certificates
1697 // because we verify after the handshake.
1698 return 1;
1699 }
1700
davidben30798ed82014-09-19 19:28:201701 // Disallow the server certificate to change in a renegotiation.
1702 if (server_cert_chain_->empty()) {
[email protected]76e85392014-03-20 17:54:141703 LOG(ERROR) << "Received invalid certificate chain between handshakes";
davidben30798ed82014-09-19 19:28:201704 return 0;
1705 }
1706 base::StringPiece old_der, new_der;
1707 if (store_ctx->cert == NULL ||
1708 !x509_util::GetDER(server_cert_chain_->Get(0), &old_der) ||
1709 !x509_util::GetDER(store_ctx->cert, &new_der)) {
1710 LOG(ERROR) << "Failed to encode certificates";
1711 return 0;
1712 }
1713 if (old_der != new_der) {
[email protected]76e85392014-03-20 17:54:141714 LOG(ERROR) << "Server certificate changed between handshakes";
davidben30798ed82014-09-19 19:28:201715 return 0;
1716 }
1717
1718 return 1;
[email protected]b051cdb62014-02-28 02:20:161719}
1720
[email protected]ae7c9f42011-11-21 11:41:161721// SelectNextProtoCallback is called by OpenSSL during the handshake. If the
1722// server supports NPN, selects a protocol from the list that the server
1723// provides. According to third_party/openssl/openssl/ssl/ssl_lib.c, the
1724// callback can assume that |in| is syntactically valid.
[email protected]ea4a1c6a2010-12-09 13:33:281725int SSLClientSocketOpenSSL::SelectNextProtoCallback(unsigned char** out,
1726 unsigned char* outlen,
1727 const unsigned char* in,
1728 unsigned int inlen) {
[email protected]ea4a1c6a2010-12-09 13:33:281729 if (ssl_config_.next_protos.empty()) {
[email protected]168a8412012-06-14 05:05:491730 *out = reinterpret_cast<uint8*>(
1731 const_cast<char*>(kDefaultSupportedNPNProtocol));
1732 *outlen = arraysize(kDefaultSupportedNPNProtocol) - 1;
1733 npn_status_ = kNextProtoUnsupported;
[email protected]ea4a1c6a2010-12-09 13:33:281734 return SSL_TLSEXT_ERR_OK;
1735 }
1736
[email protected]ae7c9f42011-11-21 11:41:161737 // Assume there's no overlap between our protocols and the server's list.
[email protected]168a8412012-06-14 05:05:491738 npn_status_ = kNextProtoNoOverlap;
[email protected]ae7c9f42011-11-21 11:41:161739
1740 // For each protocol in server preference order, see if we support it.
1741 for (unsigned int i = 0; i < inlen; i += in[i] + 1) {
bnc0d23cf42014-12-11 14:09:461742 for (NextProto next_proto : ssl_config_.next_protos) {
1743 const std::string proto = NextProtoToString(next_proto);
1744 if (in[i] == proto.size() &&
1745 memcmp(&in[i + 1], proto.data(), in[i]) == 0) {
[email protected]168a8412012-06-14 05:05:491746 // We found a match.
[email protected]ae7c9f42011-11-21 11:41:161747 *out = const_cast<unsigned char*>(in) + i + 1;
1748 *outlen = in[i];
[email protected]168a8412012-06-14 05:05:491749 npn_status_ = kNextProtoNegotiated;
[email protected]ae7c9f42011-11-21 11:41:161750 break;
1751 }
1752 }
[email protected]168a8412012-06-14 05:05:491753 if (npn_status_ == kNextProtoNegotiated)
[email protected]ae7c9f42011-11-21 11:41:161754 break;
1755 }
[email protected]ea4a1c6a2010-12-09 13:33:281756
[email protected]168a8412012-06-14 05:05:491757 // If we didn't find a protocol, we select the first one from our list.
1758 if (npn_status_ == kNextProtoNoOverlap) {
bnc67da3de2015-01-15 21:02:261759 // NextProtoToString returns a pointer to a static string.
1760 const char* proto = NextProtoToString(ssl_config_.next_protos[0]);
1761 *out = reinterpret_cast<unsigned char*>(const_cast<char*>(proto));
1762 *outlen = strlen(proto);
[email protected]168a8412012-06-14 05:05:491763 }
1764
[email protected]ea4a1c6a2010-12-09 13:33:281765 npn_proto_.assign(reinterpret_cast<const char*>(*out), *outlen);
[email protected]32e1dee2010-12-09 18:36:241766 DVLOG(2) << "next protocol: '" << npn_proto_ << "' status: " << npn_status_;
bnc0d28ea52014-10-13 15:15:381767 set_negotiation_extension(kExtensionNPN);
[email protected]ea4a1c6a2010-12-09 13:33:281768 return SSL_TLSEXT_ERR_OK;
1769}
1770
[email protected]5aea79182014-07-14 20:43:411771long SSLClientSocketOpenSSL::MaybeReplayTransportError(
1772 BIO *bio,
1773 int cmd,
1774 const char *argp, int argi, long argl,
1775 long retvalue) {
1776 if (cmd == (BIO_CB_READ|BIO_CB_RETURN) && retvalue <= 0) {
1777 // If there is no more data in the buffer, report any pending errors that
1778 // were observed. Note that both the readbuf and the writebuf are checked
1779 // for errors, since the application may have encountered a socket error
1780 // while writing that would otherwise not be reported until the application
1781 // attempted to write again - which it may never do. See
1782 // https://crbug.com/249848.
1783 if (transport_read_error_ != OK) {
1784 OpenSSLPutNetError(FROM_HERE, transport_read_error_);
1785 return -1;
1786 }
1787 if (transport_write_error_ != OK) {
1788 OpenSSLPutNetError(FROM_HERE, transport_write_error_);
1789 return -1;
1790 }
1791 } else if (cmd == BIO_CB_WRITE) {
1792 // Because of the write buffer, this reports a failure from the previous
1793 // write payload. If the current payload fails to write, the error will be
1794 // reported in a future write or read to |bio|.
1795 if (transport_write_error_ != OK) {
1796 OpenSSLPutNetError(FROM_HERE, transport_write_error_);
1797 return -1;
1798 }
1799 }
1800 return retvalue;
1801}
1802
1803// static
1804long SSLClientSocketOpenSSL::BIOCallback(
1805 BIO *bio,
1806 int cmd,
1807 const char *argp, int argi, long argl,
1808 long retvalue) {
1809 SSLClientSocketOpenSSL* socket = reinterpret_cast<SSLClientSocketOpenSSL*>(
1810 BIO_get_callback_arg(bio));
1811 CHECK(socket);
1812 return socket->MaybeReplayTransportError(
1813 bio, cmd, argp, argi, argl, retvalue);
1814}
1815
davidbendafe4e52015-04-08 22:53:521816void SSLClientSocketOpenSSL::MaybeCacheSession() {
1817 // Only cache the session once both the handshake has completed and the
1818 // certificate has been verified.
1819 if (!handshake_completed_ || !certificate_verified_ ||
1820 SSL_session_reused(ssl_)) {
1821 return;
1822 }
1823
1824 SSLContext::GetInstance()->session_cache()->Insert(GetSessionCacheKey(),
1825 SSL_get_session(ssl_));
1826}
1827
1828void SSLClientSocketOpenSSL::InfoCallback(int type, int val) {
1829 // Note that SSL_CB_HANDSHAKE_DONE may be signaled multiple times if the
1830 // socket renegotiates.
1831 if (type != SSL_CB_HANDSHAKE_DONE || handshake_completed_)
1832 return;
1833
1834 handshake_completed_ = true;
1835 MaybeCacheSession();
1836}
1837
davidbeneb5f8ef32014-09-04 14:14:321838void SSLClientSocketOpenSSL::AddSCTInfoToSSLInfo(SSLInfo* ssl_info) const {
1839 for (ct::SCTList::const_iterator iter =
1840 ct_verify_result_.verified_scts.begin();
1841 iter != ct_verify_result_.verified_scts.end(); ++iter) {
1842 ssl_info->signed_certificate_timestamps.push_back(
1843 SignedCertificateTimestampAndStatus(*iter, ct::SCT_STATUS_OK));
1844 }
1845 for (ct::SCTList::const_iterator iter =
1846 ct_verify_result_.invalid_scts.begin();
1847 iter != ct_verify_result_.invalid_scts.end(); ++iter) {
1848 ssl_info->signed_certificate_timestamps.push_back(
1849 SignedCertificateTimestampAndStatus(*iter, ct::SCT_STATUS_INVALID));
1850 }
1851 for (ct::SCTList::const_iterator iter =
1852 ct_verify_result_.unknown_logs_scts.begin();
1853 iter != ct_verify_result_.unknown_logs_scts.end(); ++iter) {
1854 ssl_info->signed_certificate_timestamps.push_back(
1855 SignedCertificateTimestampAndStatus(*iter,
1856 ct::SCT_STATUS_LOG_UNKNOWN));
1857 }
1858}
1859
rsleevif020edc2015-03-16 19:31:241860std::string SSLClientSocketOpenSSL::GetSessionCacheKey() const {
1861 std::string result = host_and_port_.ToString();
1862 result.append("/");
1863 result.append(ssl_session_cache_shard_);
1864
1865 // Shard the session cache based on maximum protocol version. This causes
1866 // fallback connections to use a separate session cache.
1867 result.append("/");
1868 switch (ssl_config_.version_max) {
1869 case SSL_PROTOCOL_VERSION_SSL3:
1870 result.append("ssl3");
1871 break;
1872 case SSL_PROTOCOL_VERSION_TLS1:
1873 result.append("tls1");
1874 break;
1875 case SSL_PROTOCOL_VERSION_TLS1_1:
1876 result.append("tls1.1");
1877 break;
1878 case SSL_PROTOCOL_VERSION_TLS1_2:
1879 result.append("tls1.2");
1880 break;
1881 default:
1882 NOTREACHED();
1883 }
1884
davidbena4c9d062015-04-03 22:34:251885 result.append("/");
1886 if (ssl_config_.enable_deprecated_cipher_suites)
1887 result.append("deprecated");
1888
rsleevif020edc2015-03-16 19:31:241889 return result;
1890}
1891
[email protected]7f38da8a2014-03-17 16:44:261892scoped_refptr<X509Certificate>
1893SSLClientSocketOpenSSL::GetUnverifiedServerCertificateChain() const {
1894 return server_cert_;
1895}
1896
[email protected]7e5dd49f2010-12-08 18:33:491897} // namespace net