blob: 89d2952875b1b5c6c0a720b3c960e457c44100ed [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/x509_certificate_net_log_param.h"
davidben30798ed82014-09-19 19:28:2035#include "net/cert/x509_util_openssl.h"
[email protected]8bd4e7a2014-08-09 14:49:1736#include "net/http/transport_security_state.h"
davidbenc879af02015-02-20 07:57:2137#include "net/ssl/scoped_openssl_types.h"
[email protected]536fd0b2013-03-14 17:41:5738#include "net/ssl/ssl_cert_request_info.h"
davidbendafe4e52015-04-08 22:53:5239#include "net/ssl/ssl_client_session_cache_openssl.h"
[email protected]536fd0b2013-03-14 17:41:5740#include "net/ssl/ssl_connection_status_flags.h"
davidbenf2eaaf92015-05-15 22:18:4241#include "net/ssl/ssl_failure_state.h"
[email protected]536fd0b2013-03-14 17:41:5742#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 TLS1_VERSION:
105 return SSL_CONNECTION_VERSION_TLS1;
davidben1d094022014-11-05 18:55:47106 case TLS1_1_VERSION:
[email protected]109805a2010-12-07 18:17:06107 return SSL_CONNECTION_VERSION_TLS1_1;
davidben1d094022014-11-05 18:55:47108 case TLS1_2_VERSION:
[email protected]109805a2010-12-07 18:17:06109 return SSL_CONNECTION_VERSION_TLS1_2;
110 default:
davidbenb937d6c2015-05-14 04:53:42111 NOTREACHED();
[email protected]109805a2010-12-07 18:17:06112 return SSL_CONNECTION_VERSION_UNKNOWN;
113 }
114}
115
[email protected]6bad5052014-07-12 01:25:13116ScopedX509 OSCertHandleToOpenSSL(
117 X509Certificate::OSCertHandle os_handle) {
118#if defined(USE_OPENSSL_CERTS)
119 return ScopedX509(X509Certificate::DupOSCertHandle(os_handle));
120#else // !defined(USE_OPENSSL_CERTS)
121 std::string der_encoded;
122 if (!X509Certificate::GetDEREncoded(os_handle, &der_encoded))
123 return ScopedX509();
124 const uint8_t* bytes = reinterpret_cast<const uint8_t*>(der_encoded.data());
125 return ScopedX509(d2i_X509(NULL, &bytes, der_encoded.size()));
126#endif // defined(USE_OPENSSL_CERTS)
127}
128
[email protected]82c59022014-08-15 09:38:27129ScopedX509Stack OSCertHandlesToOpenSSL(
130 const X509Certificate::OSCertHandles& os_handles) {
131 ScopedX509Stack stack(sk_X509_new_null());
132 for (size_t i = 0; i < os_handles.size(); i++) {
133 ScopedX509 x509 = OSCertHandleToOpenSSL(os_handles[i]);
134 if (!x509)
135 return ScopedX509Stack();
136 sk_X509_push(stack.get(), x509.release());
137 }
138 return stack.Pass();
139}
140
davidben018aad62014-09-12 02:25:19141int LogErrorCallback(const char* str, size_t len, void* context) {
142 LOG(ERROR) << base::StringPiece(str, len);
143 return 1;
144}
145
[email protected]821e3bb2013-11-08 01:06:01146} // namespace
147
148class SSLClientSocketOpenSSL::SSLContext {
[email protected]fbef13932010-11-23 12:38:53149 public:
[email protected]b29af7d2010-12-14 11:52:47150 static SSLContext* GetInstance() { return Singleton<SSLContext>::get(); }
[email protected]fbef13932010-11-23 12:38:53151 SSL_CTX* ssl_ctx() { return ssl_ctx_.get(); }
davidbendafe4e52015-04-08 22:53:52152 SSLClientSessionCacheOpenSSL* session_cache() { return &session_cache_; }
[email protected]fbef13932010-11-23 12:38:53153
[email protected]1279de12013-12-03 15:13:32154 SSLClientSocketOpenSSL* GetClientSocketFromSSL(const SSL* ssl) {
[email protected]fbef13932010-11-23 12:38:53155 DCHECK(ssl);
156 SSLClientSocketOpenSSL* socket = static_cast<SSLClientSocketOpenSSL*>(
157 SSL_get_ex_data(ssl, ssl_socket_data_index_));
158 DCHECK(socket);
159 return socket;
160 }
161
162 bool SetClientSocketForSSL(SSL* ssl, SSLClientSocketOpenSSL* socket) {
163 return SSL_set_ex_data(ssl, ssl_socket_data_index_, socket) != 0;
164 }
165
166 private:
167 friend struct DefaultSingletonTraits<SSLContext>;
168
davidbendafe4e52015-04-08 22:53:52169 SSLContext() : session_cache_(SSLClientSessionCacheOpenSSL::Config()) {
[email protected]4b559b4d2011-04-14 17:37:14170 crypto::EnsureOpenSSLInit();
[email protected]fbef13932010-11-23 12:38:53171 ssl_socket_data_index_ = SSL_get_ex_new_index(0, 0, 0, 0, 0);
172 DCHECK_NE(ssl_socket_data_index_, -1);
173 ssl_ctx_.reset(SSL_CTX_new(SSLv23_client_method()));
[email protected]b051cdb62014-02-28 02:20:16174 SSL_CTX_set_cert_verify_callback(ssl_ctx_.get(), CertVerifyCallback, NULL);
[email protected]82c59022014-08-15 09:38:27175 SSL_CTX_set_cert_cb(ssl_ctx_.get(), ClientCertRequestCallback, NULL);
[email protected]b051cdb62014-02-28 02:20:16176 SSL_CTX_set_verify(ssl_ctx_.get(), SSL_VERIFY_PEER, NULL);
haavardmc80b0ee32015-01-30 09:16:08177 // This stops |SSL_shutdown| from generating the close_notify message, which
178 // is currently not sent on the network.
179 // TODO(haavardm): Remove setting quiet shutdown once 118366 is fixed.
180 SSL_CTX_set_quiet_shutdown(ssl_ctx_.get(), 1);
[email protected]ea4a1c6a2010-12-09 13:33:28181 // TODO(kristianm): Only select this if ssl_config_.next_proto is not empty.
182 // It would be better if the callback were not a global setting,
183 // but that is an OpenSSL issue.
184 SSL_CTX_set_next_proto_select_cb(ssl_ctx_.get(), SelectNextProtoCallback,
185 NULL);
[email protected]edfd0f42014-07-22 18:20:37186 ssl_ctx_->tlsext_channel_id_enabled_new = 1;
davidbendafe4e52015-04-08 22:53:52187 SSL_CTX_set_info_callback(ssl_ctx_.get(), InfoCallback);
188
189 // Disable the internal session cache. Session caching is handled
190 // externally (i.e. by SSLClientSessionCacheOpenSSL).
191 SSL_CTX_set_session_cache_mode(
192 ssl_ctx_.get(), SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_NO_INTERNAL);
davidben018aad62014-09-12 02:25:19193
194 scoped_ptr<base::Environment> env(base::Environment::Create());
195 std::string ssl_keylog_file;
196 if (env->GetVar("SSLKEYLOGFILE", &ssl_keylog_file) &&
197 !ssl_keylog_file.empty()) {
198 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
199 BIO* bio = BIO_new_file(ssl_keylog_file.c_str(), "a");
200 if (!bio) {
201 LOG(ERROR) << "Failed to open " << ssl_keylog_file;
202 ERR_print_errors_cb(&LogErrorCallback, NULL);
203 } else {
204 SSL_CTX_set_keylog_bio(ssl_ctx_.get(), bio);
205 }
206 }
[email protected]fbef13932010-11-23 12:38:53207 }
208
[email protected]82c59022014-08-15 09:38:27209 static int ClientCertRequestCallback(SSL* ssl, void* arg) {
[email protected]b29af7d2010-12-14 11:52:47210 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
[email protected]82c59022014-08-15 09:38:27211 DCHECK(socket);
212 return socket->ClientCertRequestCallback(ssl);
[email protected]718c9672010-12-02 10:04:10213 }
214
[email protected]b051cdb62014-02-28 02:20:16215 static int CertVerifyCallback(X509_STORE_CTX *store_ctx, void *arg) {
216 SSL* ssl = reinterpret_cast<SSL*>(X509_STORE_CTX_get_ex_data(
217 store_ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
218 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
219 CHECK(socket);
220
221 return socket->CertVerifyCallback(store_ctx);
222 }
223
[email protected]ea4a1c6a2010-12-09 13:33:28224 static int SelectNextProtoCallback(SSL* ssl,
225 unsigned char** out, unsigned char* outlen,
226 const unsigned char* in,
227 unsigned int inlen, void* arg) {
[email protected]b29af7d2010-12-14 11:52:47228 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
[email protected]ea4a1c6a2010-12-09 13:33:28229 return socket->SelectNextProtoCallback(out, outlen, in, inlen);
230 }
231
davidbendafe4e52015-04-08 22:53:52232 static void InfoCallback(const SSL* ssl, int type, int val) {
233 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
234 socket->InfoCallback(type, val);
235 }
236
[email protected]fbef13932010-11-23 12:38:53237 // This is the index used with SSL_get_ex_data to retrieve the owner
238 // SSLClientSocketOpenSSL object from an SSL instance.
239 int ssl_socket_data_index_;
240
davidbenc879af02015-02-20 07:57:21241 ScopedSSL_CTX ssl_ctx_;
davidbendafe4e52015-04-08 22:53:52242
243 // TODO(davidben): Use a separate cache per URLRequestContext.
244 // https://crbug.com/458365
245 //
246 // TODO(davidben): Sessions should be invalidated on fatal
247 // alerts. https://crbug.com/466352
248 SSLClientSessionCacheOpenSSL session_cache_;
[email protected]1279de12013-12-03 15:13:32249};
250
[email protected]7f38da8a2014-03-17 16:44:26251// PeerCertificateChain is a helper object which extracts the certificate
252// chain, as given by the server, from an OpenSSL socket and performs the needed
253// resource management. The first element of the chain is the leaf certificate
254// and the other elements are in the order given by the server.
255class SSLClientSocketOpenSSL::PeerCertificateChain {
256 public:
[email protected]76e85392014-03-20 17:54:14257 explicit PeerCertificateChain(STACK_OF(X509)* chain) { Reset(chain); }
[email protected]7f38da8a2014-03-17 16:44:26258 PeerCertificateChain(const PeerCertificateChain& other) { *this = other; }
259 ~PeerCertificateChain() {}
260 PeerCertificateChain& operator=(const PeerCertificateChain& other);
261
[email protected]76e85392014-03-20 17:54:14262 // Resets the PeerCertificateChain to the set of certificates in|chain|,
263 // which may be NULL, indicating to empty the store certificates.
264 // Note: If an error occurs, such as being unable to parse the certificates,
265 // this will behave as if Reset(NULL) was called.
266 void Reset(STACK_OF(X509)* chain);
267
[email protected]7f38da8a2014-03-17 16:44:26268 // Note that when USE_OPENSSL is defined, OSCertHandle is X509*
davidben30798ed82014-09-19 19:28:20269 scoped_refptr<X509Certificate> AsOSChain() const;
[email protected]7f38da8a2014-03-17 16:44:26270
271 size_t size() const {
272 if (!openssl_chain_.get())
273 return 0;
274 return sk_X509_num(openssl_chain_.get());
275 }
276
davidben30798ed82014-09-19 19:28:20277 bool empty() const {
278 return size() == 0;
279 }
280
281 X509* Get(size_t index) const {
[email protected]7f38da8a2014-03-17 16:44:26282 DCHECK_LT(index, size());
283 return sk_X509_value(openssl_chain_.get(), index);
284 }
285
286 private:
[email protected]cd9b75b2014-07-10 04:39:38287 ScopedX509Stack openssl_chain_;
[email protected]7f38da8a2014-03-17 16:44:26288};
289
290SSLClientSocketOpenSSL::PeerCertificateChain&
291SSLClientSocketOpenSSL::PeerCertificateChain::operator=(
292 const PeerCertificateChain& other) {
293 if (this == &other)
294 return *this;
295
[email protected]24176af2014-08-14 09:31:04296 openssl_chain_.reset(X509_chain_up_ref(other.openssl_chain_.get()));
[email protected]7f38da8a2014-03-17 16:44:26297 return *this;
298}
299
[email protected]76e85392014-03-20 17:54:14300void SSLClientSocketOpenSSL::PeerCertificateChain::Reset(
301 STACK_OF(X509)* chain) {
davidben30798ed82014-09-19 19:28:20302 openssl_chain_.reset(chain ? X509_chain_up_ref(chain) : NULL);
[email protected]7f38da8a2014-03-17 16:44:26303}
[email protected]7f38da8a2014-03-17 16:44:26304
davidben30798ed82014-09-19 19:28:20305scoped_refptr<X509Certificate>
306SSLClientSocketOpenSSL::PeerCertificateChain::AsOSChain() const {
307#if defined(USE_OPENSSL_CERTS)
308 // When OSCertHandle is typedef'ed to X509, this implementation does a short
309 // cut to avoid converting back and forth between DER and the X509 struct.
310 X509Certificate::OSCertHandles intermediates;
311 for (size_t i = 1; i < sk_X509_num(openssl_chain_.get()); ++i) {
312 intermediates.push_back(sk_X509_value(openssl_chain_.get(), i));
313 }
[email protected]7f38da8a2014-03-17 16:44:26314
davidben30798ed82014-09-19 19:28:20315 return make_scoped_refptr(X509Certificate::CreateFromHandle(
316 sk_X509_value(openssl_chain_.get(), 0), intermediates));
317#else
318 // DER-encode the chain and convert to a platform certificate handle.
[email protected]7f38da8a2014-03-17 16:44:26319 std::vector<base::StringPiece> der_chain;
[email protected]edfd0f42014-07-22 18:20:37320 for (size_t i = 0; i < sk_X509_num(openssl_chain_.get()); ++i) {
[email protected]7f38da8a2014-03-17 16:44:26321 X509* x = sk_X509_value(openssl_chain_.get(), i);
davidben30798ed82014-09-19 19:28:20322 base::StringPiece der;
323 if (!x509_util::GetDER(x, &der))
324 return NULL;
325 der_chain.push_back(der);
[email protected]7f38da8a2014-03-17 16:44:26326 }
327
davidben30798ed82014-09-19 19:28:20328 return make_scoped_refptr(X509Certificate::CreateFromDERCertChain(der_chain));
329#endif
[email protected]7f38da8a2014-03-17 16:44:26330}
[email protected]7f38da8a2014-03-17 16:44:26331
[email protected]1279de12013-12-03 15:13:32332// static
[email protected]c3456bb2011-12-12 22:22:19333void SSLClientSocket::ClearSessionCache() {
[email protected]821e3bb2013-11-08 01:06:01334 SSLClientSocketOpenSSL::SSLContext* context =
335 SSLClientSocketOpenSSL::SSLContext::GetInstance();
[email protected]c3456bb2011-12-12 22:22:19336 context->session_cache()->Flush();
337}
338
bnc86b734dd2014-12-03 00:33:10339// static
340uint16 SSLClientSocket::GetMaxSupportedSSLVersion() {
341 return SSL_PROTOCOL_VERSION_TLS1_2;
342}
343
[email protected]d518cd92010-09-29 12:27:44344SSLClientSocketOpenSSL::SSLClientSocketOpenSSL(
[email protected]18ccfdb2013-08-15 00:13:44345 scoped_ptr<ClientSocketHandle> transport_socket,
[email protected]055d7f22010-11-15 12:03:12346 const HostPortPair& host_and_port,
[email protected]822581d2010-12-16 17:27:15347 const SSLConfig& ssl_config,
[email protected]feb79bcd2011-07-21 16:55:17348 const SSLClientSocketContext& context)
[email protected]83039bb2011-12-09 18:43:55349 : transport_send_busy_(false),
[email protected]d518cd92010-09-29 12:27:44350 transport_recv_busy_(false),
[email protected]4b768562013-02-16 04:10:07351 pending_read_error_(kNoPendingReadResult),
davidbenb8c23212014-10-28 00:12:16352 pending_read_ssl_error_(SSL_ERROR_NONE),
[email protected]5aea79182014-07-14 20:43:41353 transport_read_error_(OK),
[email protected]3e5c6922014-02-06 02:42:16354 transport_write_error_(OK),
[email protected]7f38da8a2014-03-17 16:44:26355 server_cert_chain_(new PeerCertificateChain(NULL)),
[email protected]64b5c892014-08-08 09:39:26356 completed_connect_(false),
[email protected]0dc88b32014-03-26 20:12:28357 was_ever_used_(false),
[email protected]feb79bcd2011-07-21 16:55:17358 cert_verifier_(context.cert_verifier),
davidbeneb5f8ef32014-09-04 14:14:32359 cert_transparency_verifier_(context.cert_transparency_verifier),
[email protected]6b8a3c742014-07-25 00:25:35360 channel_id_service_(context.channel_id_service),
[email protected]d518cd92010-09-29 12:27:44361 ssl_(NULL),
362 transport_bio_(NULL),
[email protected]18ccfdb2013-08-15 00:13:44363 transport_(transport_socket.Pass()),
[email protected]055d7f22010-11-15 12:03:12364 host_and_port_(host_and_port),
[email protected]d518cd92010-09-29 12:27:44365 ssl_config_(ssl_config),
[email protected]c3456bb2011-12-12 22:22:19366 ssl_session_cache_shard_(context.ssl_session_cache_shard),
[email protected]013c17c2012-01-21 19:09:01367 next_handshake_state_(STATE_NONE),
[email protected]ea4a1c6a2010-12-09 13:33:28368 npn_status_(kNextProtoUnsupported),
davidben52053b382015-04-27 19:22:29369 channel_id_sent_(false),
davidbendafe4e52015-04-08 22:53:52370 handshake_completed_(false),
371 certificate_verified_(false),
davidbenf2eaaf92015-05-15 22:18:42372 ssl_failure_state_(SSL_FAILURE_NONE),
[email protected]8bd4e7a2014-08-09 14:49:17373 transport_security_state_(context.transport_security_state),
eranm6571b2b2014-12-03 15:53:23374 policy_enforcer_(context.cert_policy_enforcer),
kulkarni.acd7b4462014-08-28 07:41:34375 net_log_(transport_->socket()->NetLog()),
376 weak_factory_(this) {
davidben9bbf3292015-04-24 21:50:06377 DCHECK(cert_verifier_);
[email protected]8e458552014-08-05 00:02:15378}
[email protected]d518cd92010-09-29 12:27:44379
380SSLClientSocketOpenSSL::~SSLClientSocketOpenSSL() {
381 Disconnect();
382}
383
[email protected]b9b651f2013-11-09 04:32:22384void SSLClientSocketOpenSSL::GetSSLCertRequestInfo(
385 SSLCertRequestInfo* cert_request_info) {
[email protected]791879c2013-12-17 07:22:41386 cert_request_info->host_and_port = host_and_port_;
[email protected]b9b651f2013-11-09 04:32:22387 cert_request_info->cert_authorities = cert_authorities_;
[email protected]c0787702014-05-20 21:51:44388 cert_request_info->cert_key_types = cert_key_types_;
[email protected]b9b651f2013-11-09 04:32:22389}
390
391SSLClientSocket::NextProtoStatus SSLClientSocketOpenSSL::GetNextProto(
davidben6974bf72015-04-27 17:52:48392 std::string* proto) const {
[email protected]b9b651f2013-11-09 04:32:22393 *proto = npn_proto_;
[email protected]b9b651f2013-11-09 04:32:22394 return npn_status_;
395}
396
[email protected]6b8a3c742014-07-25 00:25:35397ChannelIDService*
398SSLClientSocketOpenSSL::GetChannelIDService() const {
399 return channel_id_service_;
[email protected]b9b651f2013-11-09 04:32:22400}
401
davidbenf2eaaf92015-05-15 22:18:42402SSLFailureState SSLClientSocketOpenSSL::GetSSLFailureState() const {
403 return ssl_failure_state_;
404}
405
[email protected]b9b651f2013-11-09 04:32:22406int SSLClientSocketOpenSSL::ExportKeyingMaterial(
407 const base::StringPiece& label,
408 bool has_context, const base::StringPiece& context,
409 unsigned char* out, unsigned int outlen) {
davidben86935f72015-05-06 22:24:49410 if (!IsConnected())
411 return ERR_SOCKET_NOT_CONNECTED;
412
[email protected]b9b651f2013-11-09 04:32:22413 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
414
415 int rv = SSL_export_keying_material(
[email protected]c8a80e92014-05-17 16:02:08416 ssl_, out, outlen, label.data(), label.size(),
davidben866c3d4a72015-04-06 21:56:43417 reinterpret_cast<const unsigned char*>(context.data()), context.length(),
418 has_context ? 1 : 0);
[email protected]b9b651f2013-11-09 04:32:22419
420 if (rv != 1) {
421 int ssl_error = SSL_get_error(ssl_, rv);
422 LOG(ERROR) << "Failed to export keying material;"
423 << " returned " << rv
424 << ", SSL error code " << ssl_error;
425 return MapOpenSSLError(ssl_error, err_tracer);
426 }
427 return OK;
428}
429
430int SSLClientSocketOpenSSL::GetTLSUniqueChannelBinding(std::string* out) {
[email protected]c8a80e92014-05-17 16:02:08431 NOTIMPLEMENTED();
[email protected]b9b651f2013-11-09 04:32:22432 return ERR_NOT_IMPLEMENTED;
433}
434
435int SSLClientSocketOpenSSL::Connect(const CompletionCallback& callback) {
[email protected]8bd4e7a2014-08-09 14:49:17436 // It is an error to create an SSLClientSocket whose context has no
437 // TransportSecurityState.
438 DCHECK(transport_security_state_);
439
[email protected]b9b651f2013-11-09 04:32:22440 net_log_.BeginEvent(NetLog::TYPE_SSL_CONNECT);
441
442 // Set up new ssl object.
[email protected]c8a80e92014-05-17 16:02:08443 int rv = Init();
444 if (rv != OK) {
445 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
446 return rv;
[email protected]b9b651f2013-11-09 04:32:22447 }
448
449 // Set SSL to client mode. Handshake happens in the loop below.
450 SSL_set_connect_state(ssl_);
451
452 GotoState(STATE_HANDSHAKE);
[email protected]c8a80e92014-05-17 16:02:08453 rv = DoHandshakeLoop(OK);
[email protected]b9b651f2013-11-09 04:32:22454 if (rv == ERR_IO_PENDING) {
455 user_connect_callback_ = callback;
456 } else {
457 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
458 }
459
460 return rv > OK ? OK : rv;
461}
462
463void SSLClientSocketOpenSSL::Disconnect() {
464 if (ssl_) {
465 // Calling SSL_shutdown prevents the session from being marked as
466 // unresumable.
467 SSL_shutdown(ssl_);
468 SSL_free(ssl_);
469 ssl_ = NULL;
470 }
471 if (transport_bio_) {
472 BIO_free_all(transport_bio_);
473 transport_bio_ = NULL;
474 }
475
476 // Shut down anything that may call us back.
eroman7f9236a2015-05-11 21:23:43477 cert_verifier_request_.reset();
[email protected]b9b651f2013-11-09 04:32:22478 transport_->socket()->Disconnect();
479
480 // Null all callbacks, delete all buffers.
481 transport_send_busy_ = false;
482 send_buffer_ = NULL;
483 transport_recv_busy_ = false;
[email protected]b9b651f2013-11-09 04:32:22484 recv_buffer_ = NULL;
485
486 user_connect_callback_.Reset();
487 user_read_callback_.Reset();
488 user_write_callback_.Reset();
489 user_read_buf_ = NULL;
490 user_read_buf_len_ = 0;
491 user_write_buf_ = NULL;
492 user_write_buf_len_ = 0;
493
[email protected]3e5c6922014-02-06 02:42:16494 pending_read_error_ = kNoPendingReadResult;
davidbenb8c23212014-10-28 00:12:16495 pending_read_ssl_error_ = SSL_ERROR_NONE;
496 pending_read_error_info_ = OpenSSLErrorInfo();
497
[email protected]5aea79182014-07-14 20:43:41498 transport_read_error_ = OK;
[email protected]3e5c6922014-02-06 02:42:16499 transport_write_error_ = OK;
500
[email protected]b9b651f2013-11-09 04:32:22501 server_cert_verify_result_.Reset();
[email protected]64b5c892014-08-08 09:39:26502 completed_connect_ = false;
[email protected]b9b651f2013-11-09 04:32:22503
504 cert_authorities_.clear();
[email protected]c0787702014-05-20 21:51:44505 cert_key_types_.clear();
[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;
davidbenf2eaaf92015-05-15 22:18:42513 handshake_completed_ = false;
514 certificate_verified_ = false;
[email protected]faff9852014-06-21 06:13:46515 channel_id_request_handle_.Cancel();
davidbenf2eaaf92015-05-15 22:18:42516 ssl_failure_state_ = SSL_FAILURE_NONE;
[email protected]b9b651f2013-11-09 04:32:22517}
518
519bool SSLClientSocketOpenSSL::IsConnected() const {
520 // If the handshake has not yet completed.
[email protected]64b5c892014-08-08 09:39:26521 if (!completed_connect_)
[email protected]b9b651f2013-11-09 04:32:22522 return false;
523 // If an asynchronous operation is still pending.
524 if (user_read_buf_.get() || user_write_buf_.get())
525 return true;
526
527 return transport_->socket()->IsConnected();
528}
529
530bool SSLClientSocketOpenSSL::IsConnectedAndIdle() const {
531 // If the handshake has not yet completed.
[email protected]64b5c892014-08-08 09:39:26532 if (!completed_connect_)
[email protected]b9b651f2013-11-09 04:32:22533 return false;
534 // If an asynchronous operation is still pending.
535 if (user_read_buf_.get() || user_write_buf_.get())
536 return false;
davidbenfc9a6b82015-04-15 23:47:32537
538 // If there is data read from the network that has not yet been consumed, do
539 // not treat the connection as idle.
540 //
541 // Note that this does not check |BIO_pending|, whether there is ciphertext
542 // that has not yet been flushed to the network. |Write| returns early, so
543 // this can cause race conditions which cause a socket to not be treated
544 // reusable when it should be. See https://crbug.com/466147.
545 if (BIO_wpending(transport_bio_) > 0)
[email protected]b9b651f2013-11-09 04:32:22546 return false;
[email protected]b9b651f2013-11-09 04:32:22547
548 return transport_->socket()->IsConnectedAndIdle();
549}
550
551int SSLClientSocketOpenSSL::GetPeerAddress(IPEndPoint* addressList) const {
552 return transport_->socket()->GetPeerAddress(addressList);
553}
554
555int SSLClientSocketOpenSSL::GetLocalAddress(IPEndPoint* addressList) const {
556 return transport_->socket()->GetLocalAddress(addressList);
557}
558
559const BoundNetLog& SSLClientSocketOpenSSL::NetLog() const {
560 return net_log_;
561}
562
563void SSLClientSocketOpenSSL::SetSubresourceSpeculation() {
564 if (transport_.get() && transport_->socket()) {
565 transport_->socket()->SetSubresourceSpeculation();
566 } else {
567 NOTREACHED();
568 }
569}
570
571void SSLClientSocketOpenSSL::SetOmniboxSpeculation() {
572 if (transport_.get() && transport_->socket()) {
573 transport_->socket()->SetOmniboxSpeculation();
574 } else {
575 NOTREACHED();
576 }
577}
578
579bool SSLClientSocketOpenSSL::WasEverUsed() const {
[email protected]0dc88b32014-03-26 20:12:28580 return was_ever_used_;
[email protected]b9b651f2013-11-09 04:32:22581}
582
583bool SSLClientSocketOpenSSL::UsingTCPFastOpen() const {
584 if (transport_.get() && transport_->socket())
585 return transport_->socket()->UsingTCPFastOpen();
586
587 NOTREACHED();
588 return false;
589}
590
591bool SSLClientSocketOpenSSL::GetSSLInfo(SSLInfo* ssl_info) {
592 ssl_info->Reset();
davidben30798ed82014-09-19 19:28:20593 if (server_cert_chain_->empty())
[email protected]b9b651f2013-11-09 04:32:22594 return false;
595
596 ssl_info->cert = server_cert_verify_result_.verified_cert;
597 ssl_info->cert_status = server_cert_verify_result_.cert_status;
598 ssl_info->is_issued_by_known_root =
599 server_cert_verify_result_.is_issued_by_known_root;
600 ssl_info->public_key_hashes =
601 server_cert_verify_result_.public_key_hashes;
602 ssl_info->client_cert_sent =
603 ssl_config_.send_client_cert && ssl_config_.client_cert.get();
davidben52053b382015-04-27 19:22:29604 ssl_info->channel_id_sent = channel_id_sent_;
[email protected]8bd4e7a2014-08-09 14:49:17605 ssl_info->pinning_failure_log = pinning_failure_log_;
[email protected]b9b651f2013-11-09 04:32:22606
davidbeneb5f8ef32014-09-04 14:14:32607 AddSCTInfoToSSLInfo(ssl_info);
608
[email protected]b9b651f2013-11-09 04:32:22609 const SSL_CIPHER* cipher = SSL_get_current_cipher(ssl_);
610 CHECK(cipher);
611 ssl_info->security_bits = SSL_CIPHER_get_bits(cipher, NULL);
[email protected]b9b651f2013-11-09 04:32:22612
613 ssl_info->connection_status = EncodeSSLConnectionStatus(
pkasting6b68a162014-12-01 22:10:29614 static_cast<uint16>(SSL_CIPHER_get_id(cipher)), 0 /* no compression */,
[email protected]b9b651f2013-11-09 04:32:22615 GetNetSSLVersion(ssl_));
616
davidben09c3d072014-08-25 20:33:58617 if (!SSL_get_secure_renegotiation_support(ssl_))
[email protected]b9b651f2013-11-09 04:32:22618 ssl_info->connection_status |= SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION;
[email protected]b9b651f2013-11-09 04:32:22619
620 if (ssl_config_.version_fallback)
621 ssl_info->connection_status |= SSL_CONNECTION_VERSION_FALLBACK;
622
623 ssl_info->handshake_type = SSL_session_reused(ssl_) ?
624 SSLInfo::HANDSHAKE_RESUME : SSLInfo::HANDSHAKE_FULL;
625
626 DVLOG(3) << "Encoded connection status: cipher suite = "
627 << SSLConnectionStatusToCipherSuite(ssl_info->connection_status)
628 << " version = "
629 << SSLConnectionStatusToVersion(ssl_info->connection_status);
630 return true;
631}
632
ttuttle23fdb7b2015-05-15 01:28:03633void SSLClientSocketOpenSSL::GetConnectionAttempts(
634 ConnectionAttempts* out) const {
635 out->clear();
636}
637
[email protected]b9b651f2013-11-09 04:32:22638int SSLClientSocketOpenSSL::Read(IOBuffer* buf,
639 int buf_len,
640 const CompletionCallback& callback) {
641 user_read_buf_ = buf;
642 user_read_buf_len_ = buf_len;
643
davidben1b133ad2014-10-23 04:23:13644 int rv = DoReadLoop();
[email protected]b9b651f2013-11-09 04:32:22645
646 if (rv == ERR_IO_PENDING) {
647 user_read_callback_ = callback;
648 } else {
[email protected]0dc88b32014-03-26 20:12:28649 if (rv > 0)
650 was_ever_used_ = true;
[email protected]b9b651f2013-11-09 04:32:22651 user_read_buf_ = NULL;
652 user_read_buf_len_ = 0;
653 }
654
655 return rv;
656}
657
658int SSLClientSocketOpenSSL::Write(IOBuffer* buf,
659 int buf_len,
660 const CompletionCallback& callback) {
661 user_write_buf_ = buf;
662 user_write_buf_len_ = buf_len;
663
davidben1b133ad2014-10-23 04:23:13664 int rv = DoWriteLoop();
[email protected]b9b651f2013-11-09 04:32:22665
666 if (rv == ERR_IO_PENDING) {
667 user_write_callback_ = callback;
668 } else {
[email protected]0dc88b32014-03-26 20:12:28669 if (rv > 0)
670 was_ever_used_ = true;
[email protected]b9b651f2013-11-09 04:32:22671 user_write_buf_ = NULL;
672 user_write_buf_len_ = 0;
673 }
674
675 return rv;
676}
677
[email protected]28b96d1c2014-04-09 12:21:15678int SSLClientSocketOpenSSL::SetReceiveBufferSize(int32 size) {
[email protected]b9b651f2013-11-09 04:32:22679 return transport_->socket()->SetReceiveBufferSize(size);
680}
681
[email protected]28b96d1c2014-04-09 12:21:15682int SSLClientSocketOpenSSL::SetSendBufferSize(int32 size) {
[email protected]b9b651f2013-11-09 04:32:22683 return transport_->socket()->SetSendBufferSize(size);
684}
685
[email protected]c8a80e92014-05-17 16:02:08686int SSLClientSocketOpenSSL::Init() {
[email protected]9e733f32010-10-04 18:19:08687 DCHECK(!ssl_);
688 DCHECK(!transport_bio_);
689
[email protected]b29af7d2010-12-14 11:52:47690 SSLContext* context = SSLContext::GetInstance();
[email protected]4b559b4d2011-04-14 17:37:14691 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
[email protected]d518cd92010-09-29 12:27:44692
[email protected]fbef13932010-11-23 12:38:53693 ssl_ = SSL_new(context->ssl_ctx());
694 if (!ssl_ || !context->SetClientSocketForSSL(ssl_, this))
[email protected]c8a80e92014-05-17 16:02:08695 return ERR_UNEXPECTED;
[email protected]fbef13932010-11-23 12:38:53696
697 if (!SSL_set_tlsext_host_name(ssl_, host_and_port_.host().c_str()))
[email protected]c8a80e92014-05-17 16:02:08698 return ERR_UNEXPECTED;
[email protected]fbef13932010-11-23 12:38:53699
davidbendafe4e52015-04-08 22:53:52700 SSL_SESSION* session = context->session_cache()->Lookup(GetSessionCacheKey());
701 if (session != nullptr)
702 SSL_set_session(ssl_, session);
[email protected]d518cd92010-09-29 12:27:44703
haavardm2d92e722014-12-19 13:45:44704 send_buffer_ = new GrowableIOBuffer();
705 send_buffer_->SetCapacity(KDefaultOpenSSLBufferSize);
706 recv_buffer_ = new GrowableIOBuffer();
707 recv_buffer_->SetCapacity(KDefaultOpenSSLBufferSize);
708
[email protected]d518cd92010-09-29 12:27:44709 BIO* ssl_bio = NULL;
haavardm2d92e722014-12-19 13:45:44710
711 // SSLClientSocketOpenSSL retains ownership of the BIO buffers.
712 if (!BIO_new_bio_pair_external_buf(
713 &ssl_bio, send_buffer_->capacity(),
714 reinterpret_cast<uint8_t*>(send_buffer_->data()), &transport_bio_,
715 recv_buffer_->capacity(),
716 reinterpret_cast<uint8_t*>(recv_buffer_->data())))
[email protected]c8a80e92014-05-17 16:02:08717 return ERR_UNEXPECTED;
[email protected]d518cd92010-09-29 12:27:44718 DCHECK(ssl_bio);
719 DCHECK(transport_bio_);
720
[email protected]5aea79182014-07-14 20:43:41721 // Install a callback on OpenSSL's end to plumb transport errors through.
rsleevif020edc2015-03-16 19:31:24722 BIO_set_callback(ssl_bio, &SSLClientSocketOpenSSL::BIOCallback);
[email protected]5aea79182014-07-14 20:43:41723 BIO_set_callback_arg(ssl_bio, reinterpret_cast<char*>(this));
724
[email protected]d518cd92010-09-29 12:27:44725 SSL_set_bio(ssl_, ssl_bio, ssl_bio);
726
davidbenb937d6c2015-05-14 04:53:42727 DCHECK_LT(SSL3_VERSION, ssl_config_.version_min);
728 DCHECK_LT(SSL3_VERSION, ssl_config_.version_max);
729 SSL_set_min_version(ssl_, ssl_config_.version_min);
730 SSL_set_max_version(ssl_, ssl_config_.version_max);
731
[email protected]9e733f32010-10-04 18:19:08732 // OpenSSL defaults some options to on, others to off. To avoid ambiguity,
733 // set everything we care about to an absolute value.
[email protected]fb10e2282010-12-01 17:08:48734 SslSetClearMask options;
[email protected]d0f00492012-08-03 22:35:13735 options.ConfigureFlag(SSL_OP_NO_COMPRESSION, true);
[email protected]9e733f32010-10-04 18:19:08736
737 // TODO(joth): Set this conditionally, see http://crbug.com/55410
[email protected]fb10e2282010-12-01 17:08:48738 options.ConfigureFlag(SSL_OP_LEGACY_SERVER_CONNECT, true);
[email protected]9e733f32010-10-04 18:19:08739
[email protected]fb10e2282010-12-01 17:08:48740 SSL_set_options(ssl_, options.set_mask);
741 SSL_clear_options(ssl_, options.clear_mask);
[email protected]9e733f32010-10-04 18:19:08742
[email protected]fb10e2282010-12-01 17:08:48743 // Same as above, this time for the SSL mode.
744 SslSetClearMask mode;
[email protected]9e733f32010-10-04 18:19:08745
[email protected]fb10e2282010-12-01 17:08:48746 mode.ConfigureFlag(SSL_MODE_RELEASE_BUFFERS, true);
ishermane5c05e12014-09-09 20:32:15747 mode.ConfigureFlag(SSL_MODE_CBC_RECORD_SPLITTING, true);
[email protected]fb10e2282010-12-01 17:08:48748
davidben818d93b2015-02-19 22:27:32749 mode.ConfigureFlag(SSL_MODE_ENABLE_FALSE_START,
[email protected]b788de02014-04-23 18:06:07750 ssl_config_.false_start_enabled);
751
davidben6b8131c2015-02-25 23:30:14752 mode.ConfigureFlag(SSL_MODE_SEND_FALLBACK_SCSV, ssl_config_.version_fallback);
753
[email protected]fb10e2282010-12-01 17:08:48754 SSL_set_mode(ssl_, mode.set_mask);
755 SSL_clear_mode(ssl_, mode.clear_mask);
[email protected]109805a2010-12-07 18:17:06756
757 // Removing ciphers by ID from OpenSSL is a bit involved as we must use the
758 // textual name with SSL_set_cipher_list because there is no public API to
759 // directly remove a cipher by ID.
760 STACK_OF(SSL_CIPHER)* ciphers = SSL_get_ciphers(ssl_);
761 DCHECK(ciphers);
762 // See SSLConfig::disabled_cipher_suites for description of the suites
[email protected]9b4bc4a92013-08-20 22:59:07763 // disabled by default. Note that !SHA256 and !SHA384 only remove HMAC-SHA256
764 // and HMAC-SHA384 cipher suites, not GCM cipher suites with SHA256 or SHA384
765 // as the handshake hash.
bnc1e757502014-12-13 02:20:16766 std::string command(
767 "DEFAULT:!NULL:!aNULL:!SHA256:!SHA384:!aECDH:!AESGCM+AES256:!aPSK");
[email protected]109805a2010-12-07 18:17:06768 // Walk through all the installed ciphers, seeing if any need to be
769 // appended to the cipher removal |command|.
[email protected]edfd0f42014-07-22 18:20:37770 for (size_t i = 0; i < sk_SSL_CIPHER_num(ciphers); ++i) {
[email protected]109805a2010-12-07 18:17:06771 const SSL_CIPHER* cipher = sk_SSL_CIPHER_value(ciphers, i);
pkasting6b68a162014-12-01 22:10:29772 const uint16 id = static_cast<uint16>(SSL_CIPHER_get_id(cipher));
[email protected]109805a2010-12-07 18:17:06773 // Remove any ciphers with a strength of less than 80 bits. Note the NSS
774 // implementation uses "effective" bits here but OpenSSL does not provide
775 // this detail. This only impacts Triple DES: reports 112 vs. 168 bits,
776 // both of which are greater than 80 anyway.
777 bool disable = SSL_CIPHER_get_bits(cipher, NULL) < 80;
778 if (!disable) {
779 disable = std::find(ssl_config_.disabled_cipher_suites.begin(),
780 ssl_config_.disabled_cipher_suites.end(), id) !=
781 ssl_config_.disabled_cipher_suites.end();
782 }
783 if (disable) {
784 const char* name = SSL_CIPHER_get_name(cipher);
785 DVLOG(3) << "Found cipher to remove: '" << name << "', ID: " << id
786 << " strength: " << SSL_CIPHER_get_bits(cipher, NULL);
787 command.append(":!");
788 command.append(name);
789 }
790 }
davidben8ecc3072014-09-03 23:19:09791
davidbena4c9d062015-04-03 22:34:25792 if (!ssl_config_.enable_deprecated_cipher_suites)
793 command.append(":!RC4");
794
davidben8ecc3072014-09-03 23:19:09795 // Disable ECDSA cipher suites on platforms that do not support ECDSA
796 // signed certificates, as servers may use the presence of such
797 // ciphersuites as a hint to send an ECDSA certificate.
798#if defined(OS_WIN)
799 if (base::win::GetVersion() < base::win::VERSION_VISTA)
800 command.append(":!ECDSA");
801#endif
802
[email protected]109805a2010-12-07 18:17:06803 int rv = SSL_set_cipher_list(ssl_, command.c_str());
804 // If this fails (rv = 0) it means there are no ciphers enabled on this SSL.
805 // This will almost certainly result in the socket failing to complete the
806 // handshake at which point the appropriate error is bubbled up to the client.
807 LOG_IF(WARNING, rv != 1) << "SSL_set_cipher_list('" << command << "') "
808 "returned " << rv;
[email protected]ee0f2aa82013-10-25 11:59:26809
810 // TLS channel ids.
[email protected]6b8a3c742014-07-25 00:25:35811 if (IsChannelIDEnabled(ssl_config_, channel_id_service_)) {
[email protected]ee0f2aa82013-10-25 11:59:26812 SSL_enable_tls_channel_id(ssl_);
813 }
814
[email protected]abc44b752014-07-30 03:52:15815 if (!ssl_config_.next_protos.empty()) {
bnc1e757502014-12-13 02:20:16816 // Get list of ciphers that are enabled.
817 STACK_OF(SSL_CIPHER)* enabled_ciphers = SSL_get_ciphers(ssl_);
818 DCHECK(enabled_ciphers);
819 std::vector<uint16> enabled_ciphers_vector;
820 for (size_t i = 0; i < sk_SSL_CIPHER_num(enabled_ciphers); ++i) {
821 const SSL_CIPHER* cipher = sk_SSL_CIPHER_value(enabled_ciphers, i);
822 const uint16 id = static_cast<uint16>(SSL_CIPHER_get_id(cipher));
823 enabled_ciphers_vector.push_back(id);
824 }
825
[email protected]abc44b752014-07-30 03:52:15826 std::vector<uint8_t> wire_protos =
bnc1e757502014-12-13 02:20:16827 SerializeNextProtos(ssl_config_.next_protos,
828 HasCipherAdequateForHTTP2(enabled_ciphers_vector) &&
829 IsTLSVersionAdequateForHTTP2(ssl_config_));
[email protected]abc44b752014-07-30 03:52:15830 SSL_set_alpn_protos(ssl_, wire_protos.empty() ? NULL : &wire_protos[0],
831 wire_protos.size());
832 }
833
davidbeneb5f8ef32014-09-04 14:14:32834 if (ssl_config_.signed_cert_timestamps_enabled) {
835 SSL_enable_signed_cert_timestamps(ssl_);
836 SSL_enable_ocsp_stapling(ssl_);
837 }
838
davidben15f57132015-04-27 18:08:36839 if (cert_verifier_->SupportsOCSPStapling())
davidbend1fb2f12014-11-08 02:51:00840 SSL_enable_ocsp_stapling(ssl_);
davidbeneb5f8ef32014-09-04 14:14:32841
davidben24463662015-04-09 23:36:48842 // Enable fastradio padding.
843 SSL_enable_fastradio_padding(ssl_,
844 ssl_config_.fastradio_padding_enabled &&
845 ssl_config_.fastradio_padding_eligible);
846
davidben421116c2015-05-12 19:56:51847 // By default, renegotiations are rejected. After the initial handshake
848 // completes, some application protocols may re-enable it.
849 SSL_set_reject_peer_renegotiations(ssl_, 1);
850
[email protected]c8a80e92014-05-17 16:02:08851 return OK;
[email protected]d518cd92010-09-29 12:27:44852}
853
[email protected]b9b651f2013-11-09 04:32:22854void SSLClientSocketOpenSSL::DoReadCallback(int rv) {
855 // Since Run may result in Read being called, clear |user_read_callback_|
856 // up front.
[email protected]0dc88b32014-03-26 20:12:28857 if (rv > 0)
858 was_ever_used_ = true;
[email protected]b9b651f2013-11-09 04:32:22859 user_read_buf_ = NULL;
860 user_read_buf_len_ = 0;
861 base::ResetAndReturn(&user_read_callback_).Run(rv);
862}
863
864void SSLClientSocketOpenSSL::DoWriteCallback(int rv) {
865 // Since Run may result in Write being called, clear |user_write_callback_|
866 // up front.
[email protected]0dc88b32014-03-26 20:12:28867 if (rv > 0)
868 was_ever_used_ = true;
[email protected]b9b651f2013-11-09 04:32:22869 user_write_buf_ = NULL;
870 user_write_buf_len_ = 0;
871 base::ResetAndReturn(&user_write_callback_).Run(rv);
872}
873
874bool SSLClientSocketOpenSSL::DoTransportIO() {
875 bool network_moved = false;
876 int rv;
877 // Read and write as much data as possible. The loop is necessary because
878 // Write() may return synchronously.
879 do {
880 rv = BufferSend();
881 if (rv != ERR_IO_PENDING && rv != 0)
882 network_moved = true;
883 } while (rv > 0);
[email protected]5aea79182014-07-14 20:43:41884 if (transport_read_error_ == OK && BufferRecv() != ERR_IO_PENDING)
[email protected]b9b651f2013-11-09 04:32:22885 network_moved = true;
886 return network_moved;
887}
888
pkasting379234c2015-04-08 04:42:12889// TODO(cbentzel): Remove including "base/threading/thread_local.h" and
vadimt6b43dec22015-01-06 01:59:58890// g_first_run_completed once crbug.com/424386 is fixed.
891base::LazyInstance<base::ThreadLocalBoolean>::Leaky g_first_run_completed =
892 LAZY_INSTANCE_INITIALIZER;
893
[email protected]b9b651f2013-11-09 04:32:22894int SSLClientSocketOpenSSL::DoHandshake() {
895 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
vadimt5a243282014-12-24 00:26:16896
897 int rv;
898
pkasting379234c2015-04-08 04:42:12899 // TODO(cbentzel): Leave only 1 call to SSL_do_handshake once crbug.com/424386
vadimt5a243282014-12-24 00:26:16900 // is fixed.
901 if (ssl_config_.send_client_cert && ssl_config_.client_cert.get()) {
vadimt5a243282014-12-24 00:26:16902 rv = SSL_do_handshake(ssl_);
903 } else {
vadimt6b43dec22015-01-06 01:59:58904 if (g_first_run_completed.Get().Get()) {
pkasting379234c2015-04-08 04:42:12905 // TODO(cbentzel): Remove ScopedTracker below once crbug.com/424386 is
vadimt6b43dec22015-01-06 01:59:58906 // fixed.
pkasting379234c2015-04-08 04:42:12907 tracked_objects::ScopedTracker tracking_profile(
908 FROM_HERE_WITH_EXPLICIT_FUNCTION("424386 SSL_do_handshake()"));
vadimt5a243282014-12-24 00:26:16909
vadimt6b43dec22015-01-06 01:59:58910 rv = SSL_do_handshake(ssl_);
911 } else {
912 g_first_run_completed.Get().Set(true);
vadimt6b43dec22015-01-06 01:59:58913 rv = SSL_do_handshake(ssl_);
914 }
vadimt5a243282014-12-24 00:26:16915 }
[email protected]b9b651f2013-11-09 04:32:22916
davidbenc4212c02015-05-12 22:30:18917 int net_error = OK;
918 if (rv <= 0) {
[email protected]b9b651f2013-11-09 04:32:22919 int ssl_error = SSL_get_error(ssl_, rv);
[email protected]b9b651f2013-11-09 04:32:22920 if (ssl_error == SSL_ERROR_WANT_CHANNEL_ID_LOOKUP) {
[email protected]faff9852014-06-21 06:13:46921 // The server supports channel ID. Stop to look one up before returning to
922 // the handshake.
[email protected]faff9852014-06-21 06:13:46923 GotoState(STATE_CHANNEL_ID_LOOKUP);
924 return OK;
[email protected]b9b651f2013-11-09 04:32:22925 }
davidbenced4aa9b2015-05-12 21:22:35926 if (ssl_error == SSL_ERROR_WANT_X509_LOOKUP &&
927 !ssl_config_.send_client_cert) {
928 return ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
929 }
[email protected]b9b651f2013-11-09 04:32:22930
davidbena4409c62014-08-27 17:05:51931 OpenSSLErrorInfo error_info;
932 net_error = MapOpenSSLErrorWithDetails(ssl_error, err_tracer, &error_info);
[email protected]b9b651f2013-11-09 04:32:22933 if (net_error == ERR_IO_PENDING) {
davidbenc4212c02015-05-12 22:30:18934 // If not done, stay in this state
[email protected]b9b651f2013-11-09 04:32:22935 GotoState(STATE_HANDSHAKE);
davidbenc4212c02015-05-12 22:30:18936 return ERR_IO_PENDING;
937 }
938
939 LOG(ERROR) << "handshake failed; returned " << rv << ", SSL error code "
940 << ssl_error << ", net_error " << net_error;
941 net_log_.AddEvent(
942 NetLog::TYPE_SSL_HANDSHAKE_ERROR,
943 CreateNetLogOpenSSLErrorCallback(net_error, ssl_error, error_info));
davidbenf2eaaf92015-05-15 22:18:42944
945 // Classify the handshake failure. This is used to determine causes of the
946 // TLS version fallback.
947
948 // |cipher| is the current outgoing cipher suite, so it is non-null iff
949 // ChangeCipherSpec was sent.
950 const SSL_CIPHER* cipher = SSL_get_current_cipher(ssl_);
951 if (SSL_get_state(ssl_) == SSL3_ST_CR_SRVR_HELLO_A) {
952 ssl_failure_state_ = SSL_FAILURE_CLIENT_HELLO;
953 } else if (cipher && (SSL_CIPHER_get_id(cipher) ==
954 TLS1_CK_DHE_RSA_WITH_AES_128_GCM_SHA256 ||
955 SSL_CIPHER_get_id(cipher) ==
956 TLS1_CK_RSA_WITH_AES_128_GCM_SHA256)) {
957 ssl_failure_state_ = SSL_FAILURE_BUGGY_GCM;
958 } else if (cipher && ssl_config_.send_client_cert) {
959 ssl_failure_state_ = SSL_FAILURE_CLIENT_AUTH;
960 } else if (ERR_GET_LIB(error_info.error_code) == ERR_LIB_SSL &&
961 ERR_GET_REASON(error_info.error_code) ==
962 SSL_R_OLD_SESSION_VERSION_NOT_RETURNED) {
963 ssl_failure_state_ = SSL_FAILURE_SESSION_MISMATCH;
964 } else if (cipher && npn_status_ != kNextProtoUnsupported) {
965 ssl_failure_state_ = SSL_FAILURE_NEXT_PROTO;
966 } else {
967 ssl_failure_state_ = SSL_FAILURE_UNKNOWN;
968 }
davidbenc4212c02015-05-12 22:30:18969 }
970
971 GotoState(STATE_HANDSHAKE_COMPLETE);
972 return net_error;
973}
974
975int SSLClientSocketOpenSSL::DoHandshakeComplete(int result) {
976 if (result < 0)
977 return result;
978
979 if (ssl_config_.version_fallback &&
980 ssl_config_.version_max < ssl_config_.version_fallback_min) {
981 return ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION;
982 }
983
984 // SSL handshake is completed. If NPN wasn't negotiated, see if ALPN was.
985 if (npn_status_ == kNextProtoUnsupported) {
986 const uint8_t* alpn_proto = NULL;
987 unsigned alpn_len = 0;
988 SSL_get0_alpn_selected(ssl_, &alpn_proto, &alpn_len);
989 if (alpn_len > 0) {
990 npn_proto_.assign(reinterpret_cast<const char*>(alpn_proto), alpn_len);
991 npn_status_ = kNextProtoNegotiated;
992 set_negotiation_extension(kExtensionALPN);
[email protected]b9b651f2013-11-09 04:32:22993 }
994 }
davidbenc4212c02015-05-12 22:30:18995
996 RecordNegotiationExtension();
997 RecordChannelIDSupport(channel_id_service_, channel_id_sent_,
998 ssl_config_.channel_id_enabled,
999 crypto::ECPrivateKey::IsSupported());
1000
1001 // Only record OCSP histograms if OCSP was requested.
1002 if (ssl_config_.signed_cert_timestamps_enabled ||
1003 cert_verifier_->SupportsOCSPStapling()) {
1004 const uint8_t* ocsp_response;
1005 size_t ocsp_response_len;
1006 SSL_get0_ocsp_response(ssl_, &ocsp_response, &ocsp_response_len);
1007
1008 set_stapled_ocsp_response_received(ocsp_response_len != 0);
1009 UMA_HISTOGRAM_BOOLEAN("Net.OCSPResponseStapled", ocsp_response_len != 0);
1010 }
1011
1012 const uint8_t* sct_list;
1013 size_t sct_list_len;
1014 SSL_get0_signed_cert_timestamp_list(ssl_, &sct_list, &sct_list_len);
1015 set_signed_cert_timestamps_received(sct_list_len != 0);
1016
1017 if (IsRenegotiationAllowed())
1018 SSL_set_reject_peer_renegotiations(ssl_, 0);
1019
1020 // Verify the certificate.
1021 UpdateServerCert();
1022 GotoState(STATE_VERIFY_CERT);
1023 return OK;
[email protected]b9b651f2013-11-09 04:32:221024}
1025
[email protected]faff9852014-06-21 06:13:461026int SSLClientSocketOpenSSL::DoChannelIDLookup() {
rch98cf4472015-02-13 00:14:141027 net_log_.AddEvent(NetLog::TYPE_SSL_CHANNEL_ID_REQUESTED);
[email protected]faff9852014-06-21 06:13:461028 GotoState(STATE_CHANNEL_ID_LOOKUP_COMPLETE);
[email protected]6b8a3c742014-07-25 00:25:351029 return channel_id_service_->GetOrCreateChannelID(
[email protected]faff9852014-06-21 06:13:461030 host_and_port_.host(),
1031 &channel_id_private_key_,
1032 &channel_id_cert_,
1033 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete,
1034 base::Unretained(this)),
1035 &channel_id_request_handle_);
1036}
1037
1038int SSLClientSocketOpenSSL::DoChannelIDLookupComplete(int result) {
1039 if (result < 0)
1040 return result;
1041
1042 DCHECK_LT(0u, channel_id_private_key_.size());
1043 // Decode key.
1044 std::vector<uint8> encrypted_private_key_info;
1045 std::vector<uint8> subject_public_key_info;
1046 encrypted_private_key_info.assign(
1047 channel_id_private_key_.data(),
1048 channel_id_private_key_.data() + channel_id_private_key_.size());
1049 subject_public_key_info.assign(
1050 channel_id_cert_.data(),
1051 channel_id_cert_.data() + channel_id_cert_.size());
1052 scoped_ptr<crypto::ECPrivateKey> ec_private_key(
1053 crypto::ECPrivateKey::CreateFromEncryptedPrivateKeyInfo(
[email protected]6b8a3c742014-07-25 00:25:351054 ChannelIDService::kEPKIPassword,
[email protected]faff9852014-06-21 06:13:461055 encrypted_private_key_info,
1056 subject_public_key_info));
1057 if (!ec_private_key) {
1058 LOG(ERROR) << "Failed to import Channel ID.";
1059 return ERR_CHANNEL_ID_IMPORT_FAILED;
1060 }
1061
1062 // Hand the key to OpenSSL. Check for error in case OpenSSL rejects the key
1063 // type.
1064 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1065 int rv = SSL_set1_tls_channel_id(ssl_, ec_private_key->key());
1066 if (!rv) {
1067 LOG(ERROR) << "Failed to set Channel ID.";
1068 int err = SSL_get_error(ssl_, rv);
1069 return MapOpenSSLError(err, err_tracer);
1070 }
1071
1072 // Return to the handshake.
davidben52053b382015-04-27 19:22:291073 channel_id_sent_ = true;
rch98cf4472015-02-13 00:14:141074 net_log_.AddEvent(NetLog::TYPE_SSL_CHANNEL_ID_PROVIDED);
[email protected]faff9852014-06-21 06:13:461075 GotoState(STATE_HANDSHAKE);
1076 return OK;
1077}
1078
[email protected]b9b651f2013-11-09 04:32:221079int SSLClientSocketOpenSSL::DoVerifyCert(int result) {
davidben30798ed82014-09-19 19:28:201080 DCHECK(!server_cert_chain_->empty());
davidben09c3d072014-08-25 20:33:581081 DCHECK(start_cert_verification_time_.is_null());
davidben30798ed82014-09-19 19:28:201082
[email protected]b9b651f2013-11-09 04:32:221083 GotoState(STATE_VERIFY_CERT_COMPLETE);
1084
davidben30798ed82014-09-19 19:28:201085 // If the certificate is bad and has been previously accepted, use
1086 // the previous status and bypass the error.
1087 base::StringPiece der_cert;
1088 if (!x509_util::GetDER(server_cert_chain_->Get(0), &der_cert)) {
1089 NOTREACHED();
1090 return ERR_CERT_INVALID;
1091 }
[email protected]b9b651f2013-11-09 04:32:221092 CertStatus cert_status;
davidben30798ed82014-09-19 19:28:201093 if (ssl_config_.IsAllowedBadCert(der_cert, &cert_status)) {
[email protected]b9b651f2013-11-09 04:32:221094 VLOG(1) << "Received an expected bad cert with status: " << cert_status;
1095 server_cert_verify_result_.Reset();
1096 server_cert_verify_result_.cert_status = cert_status;
1097 server_cert_verify_result_.verified_cert = server_cert_;
1098 return OK;
1099 }
1100
davidben30798ed82014-09-19 19:28:201101 // When running in a sandbox, it may not be possible to create an
1102 // X509Certificate*, as that may depend on OS functionality blocked
1103 // in the sandbox.
1104 if (!server_cert_.get()) {
1105 server_cert_verify_result_.Reset();
1106 server_cert_verify_result_.cert_status = CERT_STATUS_INVALID;
1107 return ERR_CERT_INVALID;
1108 }
1109
davidben15f57132015-04-27 18:08:361110 std::string ocsp_response;
1111 if (cert_verifier_->SupportsOCSPStapling()) {
1112 const uint8_t* ocsp_response_raw;
1113 size_t ocsp_response_len;
1114 SSL_get0_ocsp_response(ssl_, &ocsp_response_raw, &ocsp_response_len);
1115 ocsp_response.assign(reinterpret_cast<const char*>(ocsp_response_raw),
1116 ocsp_response_len);
1117 }
1118
davidben09c3d072014-08-25 20:33:581119 start_cert_verification_time_ = base::TimeTicks::Now();
1120
[email protected]b9b651f2013-11-09 04:32:221121 int flags = 0;
1122 if (ssl_config_.rev_checking_enabled)
1123 flags |= CertVerifier::VERIFY_REV_CHECKING_ENABLED;
1124 if (ssl_config_.verify_ev_cert)
1125 flags |= CertVerifier::VERIFY_EV_CERT;
1126 if (ssl_config_.cert_io_enabled)
1127 flags |= CertVerifier::VERIFY_CERT_IO_ENABLED;
1128 if (ssl_config_.rev_checking_required_local_anchors)
1129 flags |= CertVerifier::VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS;
eroman7f9236a2015-05-11 21:23:431130 return cert_verifier_->Verify(
davidben15f57132015-04-27 18:08:361131 server_cert_.get(), host_and_port_.host(), ocsp_response, flags,
[email protected]591cffcd2014-08-18 20:02:301132 // TODO(davidben): Route the CRLSet through SSLConfig so
1133 // SSLClientSocket doesn't depend on SSLConfigService.
davidben15f57132015-04-27 18:08:361134 SSLConfigService::GetCRLSet().get(), &server_cert_verify_result_,
[email protected]b9b651f2013-11-09 04:32:221135 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete,
1136 base::Unretained(this)),
eroman7f9236a2015-05-11 21:23:431137 &cert_verifier_request_, net_log_);
[email protected]b9b651f2013-11-09 04:32:221138}
1139
1140int SSLClientSocketOpenSSL::DoVerifyCertComplete(int result) {
eroman7f9236a2015-05-11 21:23:431141 cert_verifier_request_.reset();
[email protected]b9b651f2013-11-09 04:32:221142
davidben09c3d072014-08-25 20:33:581143 if (!start_cert_verification_time_.is_null()) {
1144 base::TimeDelta verify_time =
1145 base::TimeTicks::Now() - start_cert_verification_time_;
1146 if (result == OK) {
1147 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTime", verify_time);
1148 } else {
1149 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTimeError", verify_time);
1150 }
1151 }
1152
davidben85574eb2014-12-12 03:01:571153 if (result == OK) {
davidben85574eb2014-12-12 03:01:571154 if (SSL_session_reused(ssl_)) {
1155 // Record whether or not the server tried to resume a session for a
1156 // different version. See https://crbug.com/441456.
1157 UMA_HISTOGRAM_BOOLEAN(
1158 "Net.SSLSessionVersionMatch",
1159 SSL_version(ssl_) == SSL_get_session(ssl_)->ssl_version);
1160 }
1161 }
1162
[email protected]8bd4e7a2014-08-09 14:49:171163 const CertStatus cert_status = server_cert_verify_result_.cert_status;
1164 if (transport_security_state_ &&
1165 (result == OK ||
1166 (IsCertificateError(result) && IsCertStatusMinorError(cert_status))) &&
1167 !transport_security_state_->CheckPublicKeyPins(
1168 host_and_port_.host(),
[email protected]8bd4e7a2014-08-09 14:49:171169 server_cert_verify_result_.is_issued_by_known_root,
1170 server_cert_verify_result_.public_key_hashes,
1171 &pinning_failure_log_)) {
1172 result = ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN;
1173 }
1174
[email protected]b9b651f2013-11-09 04:32:221175 if (result == OK) {
davidbeneb5f8ef32014-09-04 14:14:321176 // Only check Certificate Transparency if there were no other errors with
1177 // the connection.
1178 VerifyCT();
1179
davidbendafe4e52015-04-08 22:53:521180 DCHECK(!certificate_verified_);
1181 certificate_verified_ = true;
1182 MaybeCacheSession();
[email protected]b9b651f2013-11-09 04:32:221183 } else {
1184 DVLOG(1) << "DoVerifyCertComplete error " << ErrorToString(result)
1185 << " (" << result << ")";
1186 }
1187
[email protected]64b5c892014-08-08 09:39:261188 completed_connect_ = true;
[email protected]b9b651f2013-11-09 04:32:221189 // Exit DoHandshakeLoop and return the result to the caller to Connect.
1190 DCHECK_EQ(STATE_NONE, next_handshake_state_);
1191 return result;
1192}
1193
1194void SSLClientSocketOpenSSL::DoConnectCallback(int rv) {
1195 if (!user_connect_callback_.is_null()) {
1196 CompletionCallback c = user_connect_callback_;
1197 user_connect_callback_.Reset();
1198 c.Run(rv > OK ? OK : rv);
1199 }
1200}
1201
davidben30798ed82014-09-19 19:28:201202void SSLClientSocketOpenSSL::UpdateServerCert() {
[email protected]76e85392014-03-20 17:54:141203 server_cert_chain_->Reset(SSL_get_peer_cert_chain(ssl_));
[email protected]7f38da8a2014-03-17 16:44:261204 server_cert_ = server_cert_chain_->AsOSChain();
davidben30798ed82014-09-19 19:28:201205 if (server_cert_.get()) {
1206 net_log_.AddEvent(
1207 NetLog::TYPE_SSL_CERTIFICATES_RECEIVED,
1208 base::Bind(&NetLogX509CertificateCallback,
1209 base::Unretained(server_cert_.get())));
1210 }
[email protected]b9b651f2013-11-09 04:32:221211}
1212
davidbeneb5f8ef32014-09-04 14:14:321213void SSLClientSocketOpenSSL::VerifyCT() {
1214 if (!cert_transparency_verifier_)
1215 return;
1216
davidben54015aa2014-12-02 22:16:231217 const uint8_t* ocsp_response_raw;
davidbeneb5f8ef32014-09-04 14:14:321218 size_t ocsp_response_len;
1219 SSL_get0_ocsp_response(ssl_, &ocsp_response_raw, &ocsp_response_len);
1220 std::string ocsp_response;
1221 if (ocsp_response_len > 0) {
1222 ocsp_response.assign(reinterpret_cast<const char*>(ocsp_response_raw),
1223 ocsp_response_len);
1224 }
1225
davidben54015aa2014-12-02 22:16:231226 const uint8_t* sct_list_raw;
davidbeneb5f8ef32014-09-04 14:14:321227 size_t sct_list_len;
1228 SSL_get0_signed_cert_timestamp_list(ssl_, &sct_list_raw, &sct_list_len);
1229 std::string sct_list;
1230 if (sct_list_len > 0)
1231 sct_list.assign(reinterpret_cast<const char*>(sct_list_raw), sct_list_len);
1232
1233 // Note that this is a completely synchronous operation: The CT Log Verifier
1234 // gets all the data it needs for SCT verification and does not do any
1235 // external communication.
eranm6571b2b2014-12-03 15:53:231236 cert_transparency_verifier_->Verify(
1237 server_cert_verify_result_.verified_cert.get(), ocsp_response, sct_list,
1238 &ct_verify_result_, net_log_);
davidbeneb5f8ef32014-09-04 14:14:321239
eranm6571b2b2014-12-03 15:53:231240 if (!policy_enforcer_) {
1241 server_cert_verify_result_.cert_status &= ~CERT_STATUS_IS_EV;
1242 } else {
1243 if (server_cert_verify_result_.cert_status & CERT_STATUS_IS_EV) {
1244 scoped_refptr<ct::EVCertsWhitelist> ev_whitelist =
1245 SSLConfigService::GetEVCertsWhitelist();
1246 if (!policy_enforcer_->DoesConformToCTEVPolicy(
1247 server_cert_verify_result_.verified_cert.get(),
eranm18a019272014-12-18 08:43:231248 ev_whitelist.get(), ct_verify_result_, net_log_)) {
eranm6571b2b2014-12-03 15:53:231249 // TODO(eranm): Log via the BoundNetLog, see crbug.com/437766
1250 VLOG(1) << "EV certificate for "
1251 << server_cert_verify_result_.verified_cert->subject()
1252 .GetDisplayName()
1253 << " does not conform to CT policy, removing EV status.";
1254 server_cert_verify_result_.cert_status &= ~CERT_STATUS_IS_EV;
1255 }
1256 }
1257 }
davidbeneb5f8ef32014-09-04 14:14:321258}
1259
[email protected]b9b651f2013-11-09 04:32:221260void SSLClientSocketOpenSSL::OnHandshakeIOComplete(int result) {
1261 int rv = DoHandshakeLoop(result);
1262 if (rv != ERR_IO_PENDING) {
1263 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
1264 DoConnectCallback(rv);
1265 }
1266}
1267
1268void SSLClientSocketOpenSSL::OnSendComplete(int result) {
1269 if (next_handshake_state_ == STATE_HANDSHAKE) {
1270 // In handshake phase.
1271 OnHandshakeIOComplete(result);
1272 return;
1273 }
1274
1275 // OnSendComplete may need to call DoPayloadRead while the renegotiation
1276 // handshake is in progress.
1277 int rv_read = ERR_IO_PENDING;
1278 int rv_write = ERR_IO_PENDING;
1279 bool network_moved;
1280 do {
1281 if (user_read_buf_.get())
1282 rv_read = DoPayloadRead();
1283 if (user_write_buf_.get())
1284 rv_write = DoPayloadWrite();
1285 network_moved = DoTransportIO();
1286 } while (rv_read == ERR_IO_PENDING && rv_write == ERR_IO_PENDING &&
1287 (user_read_buf_.get() || user_write_buf_.get()) && network_moved);
1288
1289 // Performing the Read callback may cause |this| to be deleted. If this
1290 // happens, the Write callback should not be invoked. Guard against this by
1291 // holding a WeakPtr to |this| and ensuring it's still valid.
1292 base::WeakPtr<SSLClientSocketOpenSSL> guard(weak_factory_.GetWeakPtr());
1293 if (user_read_buf_.get() && rv_read != ERR_IO_PENDING)
1294 DoReadCallback(rv_read);
1295
1296 if (!guard.get())
1297 return;
1298
1299 if (user_write_buf_.get() && rv_write != ERR_IO_PENDING)
1300 DoWriteCallback(rv_write);
1301}
1302
1303void SSLClientSocketOpenSSL::OnRecvComplete(int result) {
1304 if (next_handshake_state_ == STATE_HANDSHAKE) {
1305 // In handshake phase.
1306 OnHandshakeIOComplete(result);
1307 return;
1308 }
1309
1310 // Network layer received some data, check if client requested to read
1311 // decrypted data.
1312 if (!user_read_buf_.get())
1313 return;
1314
davidben1b133ad2014-10-23 04:23:131315 int rv = DoReadLoop();
[email protected]b9b651f2013-11-09 04:32:221316 if (rv != ERR_IO_PENDING)
1317 DoReadCallback(rv);
1318}
1319
1320int SSLClientSocketOpenSSL::DoHandshakeLoop(int last_io_result) {
1321 int rv = last_io_result;
1322 do {
1323 // Default to STATE_NONE for next state.
1324 // (This is a quirk carried over from the windows
1325 // implementation. It makes reading the logs a bit harder.)
1326 // State handlers can and often do call GotoState just
1327 // to stay in the current state.
1328 State state = next_handshake_state_;
1329 GotoState(STATE_NONE);
1330 switch (state) {
1331 case STATE_HANDSHAKE:
1332 rv = DoHandshake();
1333 break;
davidbenc4212c02015-05-12 22:30:181334 case STATE_HANDSHAKE_COMPLETE:
1335 rv = DoHandshakeComplete(rv);
1336 break;
[email protected]faff9852014-06-21 06:13:461337 case STATE_CHANNEL_ID_LOOKUP:
1338 DCHECK_EQ(OK, rv);
1339 rv = DoChannelIDLookup();
1340 break;
1341 case STATE_CHANNEL_ID_LOOKUP_COMPLETE:
1342 rv = DoChannelIDLookupComplete(rv);
1343 break;
[email protected]b9b651f2013-11-09 04:32:221344 case STATE_VERIFY_CERT:
[email protected]faff9852014-06-21 06:13:461345 DCHECK_EQ(OK, rv);
[email protected]b9b651f2013-11-09 04:32:221346 rv = DoVerifyCert(rv);
1347 break;
1348 case STATE_VERIFY_CERT_COMPLETE:
1349 rv = DoVerifyCertComplete(rv);
1350 break;
1351 case STATE_NONE:
1352 default:
1353 rv = ERR_UNEXPECTED;
1354 NOTREACHED() << "unexpected state" << state;
1355 break;
1356 }
1357
1358 bool network_moved = DoTransportIO();
1359 if (network_moved && next_handshake_state_ == STATE_HANDSHAKE) {
1360 // In general we exit the loop if rv is ERR_IO_PENDING. In this
1361 // special case we keep looping even if rv is ERR_IO_PENDING because
1362 // the transport IO may allow DoHandshake to make progress.
1363 rv = OK; // This causes us to stay in the loop.
1364 }
1365 } while (rv != ERR_IO_PENDING && next_handshake_state_ != STATE_NONE);
1366 return rv;
1367}
1368
davidben1b133ad2014-10-23 04:23:131369int SSLClientSocketOpenSSL::DoReadLoop() {
[email protected]b9b651f2013-11-09 04:32:221370 bool network_moved;
1371 int rv;
1372 do {
1373 rv = DoPayloadRead();
1374 network_moved = DoTransportIO();
1375 } while (rv == ERR_IO_PENDING && network_moved);
1376
1377 return rv;
1378}
1379
davidben1b133ad2014-10-23 04:23:131380int SSLClientSocketOpenSSL::DoWriteLoop() {
[email protected]b9b651f2013-11-09 04:32:221381 bool network_moved;
1382 int rv;
1383 do {
1384 rv = DoPayloadWrite();
1385 network_moved = DoTransportIO();
1386 } while (rv == ERR_IO_PENDING && network_moved);
1387
1388 return rv;
1389}
1390
1391int SSLClientSocketOpenSSL::DoPayloadRead() {
1392 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1393
davidben7e555daf2015-03-25 17:03:291394 DCHECK_LT(0, user_read_buf_len_);
1395 DCHECK(user_read_buf_.get());
1396
[email protected]b9b651f2013-11-09 04:32:221397 int rv;
1398 if (pending_read_error_ != kNoPendingReadResult) {
1399 rv = pending_read_error_;
1400 pending_read_error_ = kNoPendingReadResult;
1401 if (rv == 0) {
1402 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED,
1403 rv, user_read_buf_->data());
davidbenb8c23212014-10-28 00:12:161404 } else {
1405 net_log_.AddEvent(
1406 NetLog::TYPE_SSL_READ_ERROR,
1407 CreateNetLogOpenSSLErrorCallback(rv, pending_read_ssl_error_,
1408 pending_read_error_info_));
[email protected]b9b651f2013-11-09 04:32:221409 }
davidbenb8c23212014-10-28 00:12:161410 pending_read_ssl_error_ = SSL_ERROR_NONE;
1411 pending_read_error_info_ = OpenSSLErrorInfo();
[email protected]b9b651f2013-11-09 04:32:221412 return rv;
1413 }
1414
1415 int total_bytes_read = 0;
davidben7e555daf2015-03-25 17:03:291416 int ssl_ret;
[email protected]b9b651f2013-11-09 04:32:221417 do {
davidben7e555daf2015-03-25 17:03:291418 ssl_ret = SSL_read(ssl_, user_read_buf_->data() + total_bytes_read,
1419 user_read_buf_len_ - total_bytes_read);
1420 if (ssl_ret > 0)
1421 total_bytes_read += ssl_ret;
1422 } while (total_bytes_read < user_read_buf_len_ && ssl_ret > 0);
[email protected]b9b651f2013-11-09 04:32:221423
davidben7e555daf2015-03-25 17:03:291424 // Although only the final SSL_read call may have failed, the failure needs to
1425 // processed immediately, while the information still available in OpenSSL's
1426 // error queue.
davidbenced4aa9b2015-05-12 21:22:351427 if (ssl_ret <= 0) {
davidben7e555daf2015-03-25 17:03:291428 // A zero return from SSL_read may mean any of:
1429 // - The underlying BIO_read returned 0.
1430 // - The peer sent a close_notify.
1431 // - Any arbitrary error. https://crbug.com/466303
[email protected]b9b651f2013-11-09 04:32:221432 //
davidben7e555daf2015-03-25 17:03:291433 // TransportReadComplete converts the first to an ERR_CONNECTION_CLOSED
1434 // error, so it does not occur. The second and third are distinguished by
1435 // SSL_ERROR_ZERO_RETURN.
1436 pending_read_ssl_error_ = SSL_get_error(ssl_, ssl_ret);
1437 if (pending_read_ssl_error_ == SSL_ERROR_ZERO_RETURN) {
1438 pending_read_error_ = 0;
davidbenced4aa9b2015-05-12 21:22:351439 } else if (pending_read_ssl_error_ == SSL_ERROR_WANT_X509_LOOKUP &&
1440 !ssl_config_.send_client_cert) {
1441 pending_read_error_ = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
davidben7e555daf2015-03-25 17:03:291442 } else {
1443 pending_read_error_ = MapOpenSSLErrorWithDetails(
1444 pending_read_ssl_error_, err_tracer, &pending_read_error_info_);
[email protected]b9b651f2013-11-09 04:32:221445 }
1446
davidben7e555daf2015-03-25 17:03:291447 // Many servers do not reliably send a close_notify alert when shutting down
1448 // a connection, and instead terminate the TCP connection. This is reported
1449 // as ERR_CONNECTION_CLOSED. Because of this, map the unclean shutdown to a
1450 // graceful EOF, instead of treating it as an error as it should be.
1451 if (pending_read_error_ == ERR_CONNECTION_CLOSED)
1452 pending_read_error_ = 0;
1453 }
davidbenbe6ce7ec2014-10-20 19:15:561454
davidben7e555daf2015-03-25 17:03:291455 if (total_bytes_read > 0) {
1456 // Return any bytes read to the caller. The error will be deferred to the
1457 // next call of DoPayloadRead.
1458 rv = total_bytes_read;
davidbenbe6ce7ec2014-10-20 19:15:561459
davidben7e555daf2015-03-25 17:03:291460 // Do not treat insufficient data as an error to return in the next call to
1461 // DoPayloadRead() - instead, let the call fall through to check SSL_read()
1462 // again. This is because DoTransportIO() may complete in between the next
1463 // call to DoPayloadRead(), and thus it is important to check SSL_read() on
1464 // subsequent invocations to see if a complete record may now be read.
1465 if (pending_read_error_ == ERR_IO_PENDING)
1466 pending_read_error_ = kNoPendingReadResult;
1467 } else {
1468 // No bytes were returned. Return the pending read error immediately.
1469 DCHECK_NE(kNoPendingReadResult, pending_read_error_);
1470 rv = pending_read_error_;
1471 pending_read_error_ = kNoPendingReadResult;
[email protected]b9b651f2013-11-09 04:32:221472 }
1473
1474 if (rv >= 0) {
1475 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, rv,
1476 user_read_buf_->data());
davidbenb8c23212014-10-28 00:12:161477 } else if (rv != ERR_IO_PENDING) {
1478 net_log_.AddEvent(
1479 NetLog::TYPE_SSL_READ_ERROR,
1480 CreateNetLogOpenSSLErrorCallback(rv, pending_read_ssl_error_,
1481 pending_read_error_info_));
1482 pending_read_ssl_error_ = SSL_ERROR_NONE;
1483 pending_read_error_info_ = OpenSSLErrorInfo();
[email protected]b9b651f2013-11-09 04:32:221484 }
1485 return rv;
1486}
1487
1488int SSLClientSocketOpenSSL::DoPayloadWrite() {
1489 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1490 int rv = SSL_write(ssl_, user_write_buf_->data(), user_write_buf_len_);
rsleevif020edc2015-03-16 19:31:241491
[email protected]b9b651f2013-11-09 04:32:221492 if (rv >= 0) {
1493 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_SENT, rv,
1494 user_write_buf_->data());
1495 return rv;
1496 }
1497
davidbenb8c23212014-10-28 00:12:161498 int ssl_error = SSL_get_error(ssl_, rv);
1499 OpenSSLErrorInfo error_info;
1500 int net_error = MapOpenSSLErrorWithDetails(ssl_error, err_tracer,
1501 &error_info);
1502
1503 if (net_error != ERR_IO_PENDING) {
1504 net_log_.AddEvent(
1505 NetLog::TYPE_SSL_WRITE_ERROR,
1506 CreateNetLogOpenSSLErrorCallback(net_error, ssl_error, error_info));
1507 }
1508 return net_error;
[email protected]b9b651f2013-11-09 04:32:221509}
1510
1511int SSLClientSocketOpenSSL::BufferSend(void) {
1512 if (transport_send_busy_)
1513 return ERR_IO_PENDING;
1514
haavardm2d92e722014-12-19 13:45:441515 size_t buffer_read_offset;
1516 uint8_t* read_buf;
1517 size_t max_read;
1518 int status = BIO_zero_copy_get_read_buf(transport_bio_, &read_buf,
1519 &buffer_read_offset, &max_read);
1520 DCHECK_EQ(status, 1); // Should never fail.
1521 if (!max_read)
1522 return 0; // Nothing pending in the OpenSSL write BIO.
1523 CHECK_EQ(read_buf, reinterpret_cast<uint8_t*>(send_buffer_->StartOfBuffer()));
1524 CHECK_LT(buffer_read_offset, static_cast<size_t>(send_buffer_->capacity()));
1525 send_buffer_->set_offset(buffer_read_offset);
[email protected]b9b651f2013-11-09 04:32:221526
1527 int rv = transport_->socket()->Write(
haavardm2d92e722014-12-19 13:45:441528 send_buffer_.get(), max_read,
[email protected]b9b651f2013-11-09 04:32:221529 base::Bind(&SSLClientSocketOpenSSL::BufferSendComplete,
1530 base::Unretained(this)));
1531 if (rv == ERR_IO_PENDING) {
1532 transport_send_busy_ = true;
1533 } else {
1534 TransportWriteComplete(rv);
1535 }
1536 return rv;
1537}
1538
1539int SSLClientSocketOpenSSL::BufferRecv(void) {
1540 if (transport_recv_busy_)
1541 return ERR_IO_PENDING;
1542
1543 // Determine how much was requested from |transport_bio_| that was not
1544 // actually available.
1545 size_t requested = BIO_ctrl_get_read_request(transport_bio_);
1546 if (requested == 0) {
1547 // This is not a perfect match of error codes, as no operation is
1548 // actually pending. However, returning 0 would be interpreted as
1549 // a possible sign of EOF, which is also an inappropriate match.
1550 return ERR_IO_PENDING;
1551 }
1552
1553 // Known Issue: While only reading |requested| data is the more correct
1554 // implementation, it has the downside of resulting in frequent reads:
1555 // One read for the SSL record header (~5 bytes) and one read for the SSL
1556 // record body. Rather than issuing these reads to the underlying socket
1557 // (and constantly allocating new IOBuffers), a single Read() request to
1558 // fill |transport_bio_| is issued. As long as an SSL client socket cannot
1559 // be gracefully shutdown (via SSL close alerts) and re-used for non-SSL
1560 // traffic, this over-subscribed Read()ing will not cause issues.
haavardm2d92e722014-12-19 13:45:441561
1562 size_t buffer_write_offset;
1563 uint8_t* write_buf;
1564 size_t max_write;
1565 int status = BIO_zero_copy_get_write_buf(transport_bio_, &write_buf,
1566 &buffer_write_offset, &max_write);
1567 DCHECK_EQ(status, 1); // Should never fail.
[email protected]b9b651f2013-11-09 04:32:221568 if (!max_write)
1569 return ERR_IO_PENDING;
1570
haavardm2d92e722014-12-19 13:45:441571 CHECK_EQ(write_buf,
1572 reinterpret_cast<uint8_t*>(recv_buffer_->StartOfBuffer()));
1573 CHECK_LT(buffer_write_offset, static_cast<size_t>(recv_buffer_->capacity()));
1574
1575 recv_buffer_->set_offset(buffer_write_offset);
[email protected]b9b651f2013-11-09 04:32:221576 int rv = transport_->socket()->Read(
1577 recv_buffer_.get(),
1578 max_write,
1579 base::Bind(&SSLClientSocketOpenSSL::BufferRecvComplete,
1580 base::Unretained(this)));
1581 if (rv == ERR_IO_PENDING) {
1582 transport_recv_busy_ = true;
1583 } else {
[email protected]3e5c6922014-02-06 02:42:161584 rv = TransportReadComplete(rv);
[email protected]b9b651f2013-11-09 04:32:221585 }
1586 return rv;
1587}
1588
1589void SSLClientSocketOpenSSL::BufferSendComplete(int result) {
[email protected]b9b651f2013-11-09 04:32:221590 TransportWriteComplete(result);
1591 OnSendComplete(result);
1592}
1593
1594void SSLClientSocketOpenSSL::BufferRecvComplete(int result) {
[email protected]3e5c6922014-02-06 02:42:161595 result = TransportReadComplete(result);
[email protected]b9b651f2013-11-09 04:32:221596 OnRecvComplete(result);
1597}
1598
1599void SSLClientSocketOpenSSL::TransportWriteComplete(int result) {
1600 DCHECK(ERR_IO_PENDING != result);
haavardm2d92e722014-12-19 13:45:441601 int bytes_written = 0;
[email protected]b9b651f2013-11-09 04:32:221602 if (result < 0) {
[email protected]5aea79182014-07-14 20:43:411603 // Record the error. Save it to be reported in a future read or write on
1604 // transport_bio_'s peer.
[email protected]3e5c6922014-02-06 02:42:161605 transport_write_error_ = result;
[email protected]b9b651f2013-11-09 04:32:221606 } else {
haavardm2d92e722014-12-19 13:45:441607 bytes_written = result;
[email protected]b9b651f2013-11-09 04:32:221608 }
haavardm2d92e722014-12-19 13:45:441609 DCHECK_GE(send_buffer_->RemainingCapacity(), bytes_written);
1610 int ret = BIO_zero_copy_get_read_buf_done(transport_bio_, bytes_written);
1611 DCHECK_EQ(1, ret);
1612 transport_send_busy_ = false;
[email protected]b9b651f2013-11-09 04:32:221613}
1614
[email protected]3e5c6922014-02-06 02:42:161615int SSLClientSocketOpenSSL::TransportReadComplete(int result) {
[email protected]b9b651f2013-11-09 04:32:221616 DCHECK(ERR_IO_PENDING != result);
[email protected]5aea79182014-07-14 20:43:411617 // If an EOF, canonicalize to ERR_CONNECTION_CLOSED here so MapOpenSSLError
1618 // does not report success.
1619 if (result == 0)
1620 result = ERR_CONNECTION_CLOSED;
haavardm2d92e722014-12-19 13:45:441621 int bytes_read = 0;
[email protected]5aea79182014-07-14 20:43:411622 if (result < 0) {
[email protected]b9b651f2013-11-09 04:32:221623 DVLOG(1) << "TransportReadComplete result " << result;
[email protected]5aea79182014-07-14 20:43:411624 // Received an error. Save it to be reported in a future read on
1625 // transport_bio_'s peer.
1626 transport_read_error_ = result;
[email protected]b9b651f2013-11-09 04:32:221627 } else {
haavardm2d92e722014-12-19 13:45:441628 bytes_read = result;
[email protected]b9b651f2013-11-09 04:32:221629 }
haavardm2d92e722014-12-19 13:45:441630 DCHECK_GE(recv_buffer_->RemainingCapacity(), bytes_read);
1631 int ret = BIO_zero_copy_get_write_buf_done(transport_bio_, bytes_read);
1632 DCHECK_EQ(1, ret);
[email protected]b9b651f2013-11-09 04:32:221633 transport_recv_busy_ = false;
[email protected]3e5c6922014-02-06 02:42:161634 return result;
[email protected]b9b651f2013-11-09 04:32:221635}
1636
[email protected]82c59022014-08-15 09:38:271637int SSLClientSocketOpenSSL::ClientCertRequestCallback(SSL* ssl) {
[email protected]5ac981e182010-12-06 17:56:271638 DVLOG(3) << "OpenSSL ClientCertRequestCallback called";
1639 DCHECK(ssl == ssl_);
[email protected]82c59022014-08-15 09:38:271640
davidbenaf42cbe2014-11-13 03:27:461641 net_log_.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED);
1642
[email protected]82c59022014-08-15 09:38:271643 // Clear any currently configured certificates.
1644 SSL_certs_clear(ssl_);
[email protected]97a854f2014-07-29 07:51:361645
1646#if defined(OS_IOS)
1647 // TODO(droger): Support client auth on iOS. See http://crbug.com/145954).
1648 LOG(WARNING) << "Client auth is not supported";
1649#else // !defined(OS_IOS)
[email protected]5ac981e182010-12-06 17:56:271650 if (!ssl_config_.send_client_cert) {
[email protected]515adc22013-01-09 16:01:231651 // First pass: we know that a client certificate is needed, but we do not
1652 // have one at hand.
[email protected]515adc22013-01-09 16:01:231653 STACK_OF(X509_NAME) *authorities = SSL_get_client_CA_list(ssl);
[email protected]edfd0f42014-07-22 18:20:371654 for (size_t i = 0; i < sk_X509_NAME_num(authorities); i++) {
[email protected]515adc22013-01-09 16:01:231655 X509_NAME *ca_name = (X509_NAME *)sk_X509_NAME_value(authorities, i);
1656 unsigned char* str = NULL;
1657 int length = i2d_X509_NAME(ca_name, &str);
1658 cert_authorities_.push_back(std::string(
1659 reinterpret_cast<const char*>(str),
1660 static_cast<size_t>(length)));
1661 OPENSSL_free(str);
1662 }
1663
[email protected]c0787702014-05-20 21:51:441664 const unsigned char* client_cert_types;
[email protected]e7e883e2014-07-25 06:03:081665 size_t num_client_cert_types =
1666 SSL_get0_certificate_types(ssl, &client_cert_types);
[email protected]c0787702014-05-20 21:51:441667 for (size_t i = 0; i < num_client_cert_types; i++) {
1668 cert_key_types_.push_back(
1669 static_cast<SSLClientCertType>(client_cert_types[i]));
1670 }
1671
davidbenced4aa9b2015-05-12 21:22:351672 // Suspends handshake. SSL_get_error will return SSL_ERROR_WANT_X509_LOOKUP.
1673 return -1;
[email protected]5ac981e182010-12-06 17:56:271674 }
1675
1676 // Second pass: a client certificate should have been selected.
[email protected]13914c92013-06-13 22:42:421677 if (ssl_config_.client_cert.get()) {
[email protected]6bad5052014-07-12 01:25:131678 ScopedX509 leaf_x509 =
1679 OSCertHandleToOpenSSL(ssl_config_.client_cert->os_cert_handle());
1680 if (!leaf_x509) {
1681 LOG(WARNING) << "Failed to import certificate";
1682 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT);
1683 return -1;
1684 }
1685
[email protected]82c59022014-08-15 09:38:271686 ScopedX509Stack chain = OSCertHandlesToOpenSSL(
1687 ssl_config_.client_cert->GetIntermediateCertificates());
1688 if (!chain) {
1689 LOG(WARNING) << "Failed to import intermediate certificates";
1690 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT);
1691 return -1;
1692 }
1693
[email protected]97a854f2014-07-29 07:51:361694 // TODO(davidben): With Linux client auth support, this should be
1695 // conditioned on OS_ANDROID and then, with https://crbug.com/394131,
1696 // removed altogether. OpenSSLClientKeyStore is mostly an artifact of the
1697 // net/ client auth API lacking a private key handle.
[email protected]c0787702014-05-20 21:51:441698#if defined(USE_OPENSSL_CERTS)
[email protected]97a854f2014-07-29 07:51:361699 crypto::ScopedEVP_PKEY privkey =
1700 OpenSSLClientKeyStore::GetInstance()->FetchClientCertPrivateKey(
1701 ssl_config_.client_cert.get());
1702#else // !defined(USE_OPENSSL_CERTS)
1703 crypto::ScopedEVP_PKEY privkey =
1704 FetchClientCertPrivateKey(ssl_config_.client_cert.get());
1705#endif // defined(USE_OPENSSL_CERTS)
1706 if (!privkey) {
[email protected]6bad5052014-07-12 01:25:131707 // Could not find the private key. Fail the handshake and surface an
1708 // appropriate error to the caller.
1709 LOG(WARNING) << "Client cert found without private key";
1710 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY);
1711 return -1;
[email protected]0c6523f2010-12-10 10:56:241712 }
[email protected]6bad5052014-07-12 01:25:131713
[email protected]82c59022014-08-15 09:38:271714 if (!SSL_use_certificate(ssl_, leaf_x509.get()) ||
1715 !SSL_use_PrivateKey(ssl_, privkey.get()) ||
1716 !SSL_set1_chain(ssl_, chain.get())) {
1717 LOG(WARNING) << "Failed to set client certificate";
1718 return -1;
1719 }
davidbenaf42cbe2014-11-13 03:27:461720
1721 int cert_count = 1 + sk_X509_num(chain.get());
1722 net_log_.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED,
1723 NetLog::IntegerCallback("cert_count", cert_count));
[email protected]6bad5052014-07-12 01:25:131724 return 1;
[email protected]c0787702014-05-20 21:51:441725 }
[email protected]97a854f2014-07-29 07:51:361726#endif // defined(OS_IOS)
[email protected]5ac981e182010-12-06 17:56:271727
1728 // Send no client certificate.
davidbenaf42cbe2014-11-13 03:27:461729 net_log_.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED,
1730 NetLog::IntegerCallback("cert_count", 0));
[email protected]82c59022014-08-15 09:38:271731 return 1;
[email protected]5ac981e182010-12-06 17:56:271732}
1733
[email protected]b051cdb62014-02-28 02:20:161734int SSLClientSocketOpenSSL::CertVerifyCallback(X509_STORE_CTX* store_ctx) {
[email protected]64b5c892014-08-08 09:39:261735 if (!completed_connect_) {
[email protected]b051cdb62014-02-28 02:20:161736 // If the first handshake hasn't completed then we accept any certificates
1737 // because we verify after the handshake.
1738 return 1;
1739 }
1740
davidben30798ed82014-09-19 19:28:201741 // Disallow the server certificate to change in a renegotiation.
1742 if (server_cert_chain_->empty()) {
[email protected]76e85392014-03-20 17:54:141743 LOG(ERROR) << "Received invalid certificate chain between handshakes";
davidben30798ed82014-09-19 19:28:201744 return 0;
1745 }
1746 base::StringPiece old_der, new_der;
1747 if (store_ctx->cert == NULL ||
1748 !x509_util::GetDER(server_cert_chain_->Get(0), &old_der) ||
1749 !x509_util::GetDER(store_ctx->cert, &new_der)) {
1750 LOG(ERROR) << "Failed to encode certificates";
1751 return 0;
1752 }
1753 if (old_der != new_der) {
[email protected]76e85392014-03-20 17:54:141754 LOG(ERROR) << "Server certificate changed between handshakes";
davidben30798ed82014-09-19 19:28:201755 return 0;
1756 }
1757
1758 return 1;
[email protected]b051cdb62014-02-28 02:20:161759}
1760
[email protected]ae7c9f42011-11-21 11:41:161761// SelectNextProtoCallback is called by OpenSSL during the handshake. If the
1762// server supports NPN, selects a protocol from the list that the server
1763// provides. According to third_party/openssl/openssl/ssl/ssl_lib.c, the
1764// callback can assume that |in| is syntactically valid.
[email protected]ea4a1c6a2010-12-09 13:33:281765int SSLClientSocketOpenSSL::SelectNextProtoCallback(unsigned char** out,
1766 unsigned char* outlen,
1767 const unsigned char* in,
1768 unsigned int inlen) {
[email protected]ea4a1c6a2010-12-09 13:33:281769 if (ssl_config_.next_protos.empty()) {
[email protected]168a8412012-06-14 05:05:491770 *out = reinterpret_cast<uint8*>(
1771 const_cast<char*>(kDefaultSupportedNPNProtocol));
1772 *outlen = arraysize(kDefaultSupportedNPNProtocol) - 1;
1773 npn_status_ = kNextProtoUnsupported;
[email protected]ea4a1c6a2010-12-09 13:33:281774 return SSL_TLSEXT_ERR_OK;
1775 }
1776
[email protected]ae7c9f42011-11-21 11:41:161777 // Assume there's no overlap between our protocols and the server's list.
[email protected]168a8412012-06-14 05:05:491778 npn_status_ = kNextProtoNoOverlap;
[email protected]ae7c9f42011-11-21 11:41:161779
1780 // For each protocol in server preference order, see if we support it.
1781 for (unsigned int i = 0; i < inlen; i += in[i] + 1) {
bnc0d23cf42014-12-11 14:09:461782 for (NextProto next_proto : ssl_config_.next_protos) {
1783 const std::string proto = NextProtoToString(next_proto);
1784 if (in[i] == proto.size() &&
1785 memcmp(&in[i + 1], proto.data(), in[i]) == 0) {
[email protected]168a8412012-06-14 05:05:491786 // We found a match.
[email protected]ae7c9f42011-11-21 11:41:161787 *out = const_cast<unsigned char*>(in) + i + 1;
1788 *outlen = in[i];
[email protected]168a8412012-06-14 05:05:491789 npn_status_ = kNextProtoNegotiated;
[email protected]ae7c9f42011-11-21 11:41:161790 break;
1791 }
1792 }
[email protected]168a8412012-06-14 05:05:491793 if (npn_status_ == kNextProtoNegotiated)
[email protected]ae7c9f42011-11-21 11:41:161794 break;
1795 }
[email protected]ea4a1c6a2010-12-09 13:33:281796
[email protected]168a8412012-06-14 05:05:491797 // If we didn't find a protocol, we select the first one from our list.
1798 if (npn_status_ == kNextProtoNoOverlap) {
bnc67da3de2015-01-15 21:02:261799 // NextProtoToString returns a pointer to a static string.
1800 const char* proto = NextProtoToString(ssl_config_.next_protos[0]);
1801 *out = reinterpret_cast<unsigned char*>(const_cast<char*>(proto));
1802 *outlen = strlen(proto);
[email protected]168a8412012-06-14 05:05:491803 }
1804
[email protected]ea4a1c6a2010-12-09 13:33:281805 npn_proto_.assign(reinterpret_cast<const char*>(*out), *outlen);
[email protected]32e1dee2010-12-09 18:36:241806 DVLOG(2) << "next protocol: '" << npn_proto_ << "' status: " << npn_status_;
bnc0d28ea52014-10-13 15:15:381807 set_negotiation_extension(kExtensionNPN);
[email protected]ea4a1c6a2010-12-09 13:33:281808 return SSL_TLSEXT_ERR_OK;
1809}
1810
[email protected]5aea79182014-07-14 20:43:411811long SSLClientSocketOpenSSL::MaybeReplayTransportError(
1812 BIO *bio,
1813 int cmd,
1814 const char *argp, int argi, long argl,
1815 long retvalue) {
1816 if (cmd == (BIO_CB_READ|BIO_CB_RETURN) && retvalue <= 0) {
1817 // If there is no more data in the buffer, report any pending errors that
1818 // were observed. Note that both the readbuf and the writebuf are checked
1819 // for errors, since the application may have encountered a socket error
1820 // while writing that would otherwise not be reported until the application
1821 // attempted to write again - which it may never do. See
1822 // https://crbug.com/249848.
1823 if (transport_read_error_ != OK) {
1824 OpenSSLPutNetError(FROM_HERE, transport_read_error_);
1825 return -1;
1826 }
1827 if (transport_write_error_ != OK) {
1828 OpenSSLPutNetError(FROM_HERE, transport_write_error_);
1829 return -1;
1830 }
1831 } else if (cmd == BIO_CB_WRITE) {
1832 // Because of the write buffer, this reports a failure from the previous
1833 // write payload. If the current payload fails to write, the error will be
1834 // reported in a future write or read to |bio|.
1835 if (transport_write_error_ != OK) {
1836 OpenSSLPutNetError(FROM_HERE, transport_write_error_);
1837 return -1;
1838 }
1839 }
1840 return retvalue;
1841}
1842
1843// static
1844long SSLClientSocketOpenSSL::BIOCallback(
1845 BIO *bio,
1846 int cmd,
1847 const char *argp, int argi, long argl,
1848 long retvalue) {
1849 SSLClientSocketOpenSSL* socket = reinterpret_cast<SSLClientSocketOpenSSL*>(
1850 BIO_get_callback_arg(bio));
1851 CHECK(socket);
1852 return socket->MaybeReplayTransportError(
1853 bio, cmd, argp, argi, argl, retvalue);
1854}
1855
davidbendafe4e52015-04-08 22:53:521856void SSLClientSocketOpenSSL::MaybeCacheSession() {
1857 // Only cache the session once both the handshake has completed and the
1858 // certificate has been verified.
1859 if (!handshake_completed_ || !certificate_verified_ ||
1860 SSL_session_reused(ssl_)) {
1861 return;
1862 }
1863
1864 SSLContext::GetInstance()->session_cache()->Insert(GetSessionCacheKey(),
1865 SSL_get_session(ssl_));
1866}
1867
1868void SSLClientSocketOpenSSL::InfoCallback(int type, int val) {
1869 // Note that SSL_CB_HANDSHAKE_DONE may be signaled multiple times if the
1870 // socket renegotiates.
1871 if (type != SSL_CB_HANDSHAKE_DONE || handshake_completed_)
1872 return;
1873
1874 handshake_completed_ = true;
1875 MaybeCacheSession();
1876}
1877
davidbeneb5f8ef32014-09-04 14:14:321878void SSLClientSocketOpenSSL::AddSCTInfoToSSLInfo(SSLInfo* ssl_info) const {
1879 for (ct::SCTList::const_iterator iter =
1880 ct_verify_result_.verified_scts.begin();
1881 iter != ct_verify_result_.verified_scts.end(); ++iter) {
1882 ssl_info->signed_certificate_timestamps.push_back(
1883 SignedCertificateTimestampAndStatus(*iter, ct::SCT_STATUS_OK));
1884 }
1885 for (ct::SCTList::const_iterator iter =
1886 ct_verify_result_.invalid_scts.begin();
1887 iter != ct_verify_result_.invalid_scts.end(); ++iter) {
1888 ssl_info->signed_certificate_timestamps.push_back(
1889 SignedCertificateTimestampAndStatus(*iter, ct::SCT_STATUS_INVALID));
1890 }
1891 for (ct::SCTList::const_iterator iter =
1892 ct_verify_result_.unknown_logs_scts.begin();
1893 iter != ct_verify_result_.unknown_logs_scts.end(); ++iter) {
1894 ssl_info->signed_certificate_timestamps.push_back(
1895 SignedCertificateTimestampAndStatus(*iter,
1896 ct::SCT_STATUS_LOG_UNKNOWN));
1897 }
1898}
1899
rsleevif020edc2015-03-16 19:31:241900std::string SSLClientSocketOpenSSL::GetSessionCacheKey() const {
1901 std::string result = host_and_port_.ToString();
1902 result.append("/");
1903 result.append(ssl_session_cache_shard_);
1904
1905 // Shard the session cache based on maximum protocol version. This causes
1906 // fallback connections to use a separate session cache.
1907 result.append("/");
1908 switch (ssl_config_.version_max) {
rsleevif020edc2015-03-16 19:31:241909 case SSL_PROTOCOL_VERSION_TLS1:
1910 result.append("tls1");
1911 break;
1912 case SSL_PROTOCOL_VERSION_TLS1_1:
1913 result.append("tls1.1");
1914 break;
1915 case SSL_PROTOCOL_VERSION_TLS1_2:
1916 result.append("tls1.2");
1917 break;
1918 default:
1919 NOTREACHED();
1920 }
1921
davidbena4c9d062015-04-03 22:34:251922 result.append("/");
1923 if (ssl_config_.enable_deprecated_cipher_suites)
1924 result.append("deprecated");
1925
rsleevif020edc2015-03-16 19:31:241926 return result;
1927}
1928
davidben421116c2015-05-12 19:56:511929bool SSLClientSocketOpenSSL::IsRenegotiationAllowed() const {
1930 if (npn_status_ == kNextProtoUnsupported)
1931 return ssl_config_.renego_allowed_default;
1932
1933 NextProto next_proto = NextProtoFromString(npn_proto_);
1934 for (NextProto allowed : ssl_config_.renego_allowed_for_protos) {
1935 if (next_proto == allowed)
1936 return true;
1937 }
1938 return false;
1939}
1940
[email protected]7f38da8a2014-03-17 16:44:261941scoped_refptr<X509Certificate>
1942SSLClientSocketOpenSSL::GetUnverifiedServerCertificateChain() const {
1943 return server_cert_;
1944}
1945
[email protected]7e5dd49f2010-12-08 18:33:491946} // namespace net