blob: fb739f4888c85109a1db32b3a3c98fe31da0aa08 [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>
[email protected]536fd0b2013-03-14 17:41:5713#include <openssl/ssl.h>
bnc67da3de2015-01-15 21:02:2614#include <string.h>
[email protected]d518cd92010-09-29 12:27:4415
[email protected]0f7804ec2011-10-07 20:04:1816#include "base/bind.h"
[email protected]f2da6ac2013-02-04 08:22:5317#include "base/callback_helpers.h"
davidben018aad62014-09-12 02:25:1918#include "base/environment.h"
[email protected]3b63f8f42011-03-28 01:54:1519#include "base/memory/singleton.h"
[email protected]835d7c82010-10-14 04:38:3820#include "base/metrics/histogram.h"
vadimtb2a77c762014-11-21 19:49:2221#include "base/profiler/scoped_tracker.h"
davidben018aad62014-09-12 02:25:1922#include "base/strings/string_piece.h"
[email protected]20305ec2011-01-21 04:55:5223#include "base/synchronization/lock.h"
vadimt6b43dec22015-01-06 01:59:5824#include "base/threading/thread_local.h"
[email protected]ee0f2aa82013-10-25 11:59:2625#include "crypto/ec_private_key.h"
[email protected]4b559b4d2011-04-14 17:37:1426#include "crypto/openssl_util.h"
[email protected]cd9b75b2014-07-10 04:39:3827#include "crypto/scoped_openssl_types.h"
[email protected]d518cd92010-09-29 12:27:4428#include "net/base/net_errors.h"
eranm6571b2b2014-12-03 15:53:2329#include "net/cert/cert_policy_enforcer.h"
[email protected]6e7845ae2013-03-29 21:48:1130#include "net/cert/cert_verifier.h"
eranmefbd3132014-10-28 16:35:1631#include "net/cert/ct_ev_whitelist.h"
davidbeneb5f8ef32014-09-04 14:14:3232#include "net/cert/ct_verifier.h"
[email protected]6e7845ae2013-03-29 21:48:1133#include "net/cert/single_request_cert_verifier.h"
34#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"
41#include "net/ssl/ssl_info.h"
[email protected]d518cd92010-09-29 12:27:4442
davidben8ecc3072014-09-03 23:19:0943#if defined(OS_WIN)
44#include "base/win/windows_version.h"
45#endif
46
[email protected]97a854f2014-07-29 07:51:3647#if defined(USE_OPENSSL_CERTS)
48#include "net/ssl/openssl_client_key_store.h"
49#else
50#include "net/ssl/openssl_platform_key.h"
51#endif
52
[email protected]d518cd92010-09-29 12:27:4453namespace net {
54
55namespace {
56
57// Enable this to see logging for state machine state transitions.
58#if 0
[email protected]3b112772010-10-04 10:54:4959#define GotoState(s) do { DVLOG(2) << (void *)this << " " << __FUNCTION__ << \
[email protected]d518cd92010-09-29 12:27:4460 " jump to state " << s; \
61 next_handshake_state_ = s; } while (0)
62#else
63#define GotoState(s) next_handshake_state_ = s
64#endif
65
[email protected]4b768562013-02-16 04:10:0766// This constant can be any non-negative/non-zero value (eg: it does not
67// overlap with any value of the net::Error range, including net::OK).
68const int kNoPendingReadResult = 1;
69
[email protected]168a8412012-06-14 05:05:4970// If a client doesn't have a list of protocols that it supports, but
71// the server supports NPN, choosing "http/1.1" is the best answer.
72const char kDefaultSupportedNPNProtocol[] = "http/1.1";
73
haavardm2d92e722014-12-19 13:45:4474// Default size of the internal BoringSSL buffers.
75const int KDefaultOpenSSLBufferSize = 17 * 1024;
76
[email protected]82c59022014-08-15 09:38:2777void FreeX509Stack(STACK_OF(X509)* ptr) {
78 sk_X509_pop_free(ptr, X509_free);
79}
80
davidbene94fe0962015-02-21 00:51:3381using ScopedX509Stack = crypto::ScopedOpenSSL<STACK_OF(X509), FreeX509Stack>;
[email protected]6bad5052014-07-12 01:25:1382
[email protected]89038152012-09-07 06:30:1783#if OPENSSL_VERSION_NUMBER < 0x1000103fL
84// This method doesn't seem to have made it into the OpenSSL headers.
[email protected]109805a2010-12-07 18:17:0685unsigned long SSL_CIPHER_get_id(const SSL_CIPHER* cipher) { return cipher->id; }
[email protected]89038152012-09-07 06:30:1786#endif
[email protected]109805a2010-12-07 18:17:0687
88// Used for encoding the |connection_status| field of an SSLInfo object.
pkasting6b68a162014-12-01 22:10:2989int EncodeSSLConnectionStatus(uint16 cipher_suite,
[email protected]109805a2010-12-07 18:17:0690 int compression,
91 int version) {
pkasting6b68a162014-12-01 22:10:2992 return cipher_suite |
[email protected]109805a2010-12-07 18:17:0693 ((compression & SSL_CONNECTION_COMPRESSION_MASK) <<
94 SSL_CONNECTION_COMPRESSION_SHIFT) |
95 ((version & SSL_CONNECTION_VERSION_MASK) <<
96 SSL_CONNECTION_VERSION_SHIFT);
97}
98
99// Returns the net SSL version number (see ssl_connection_status_flags.h) for
100// this SSL connection.
101int GetNetSSLVersion(SSL* ssl) {
[email protected]7e5dd49f2010-12-08 18:33:49102 switch (SSL_version(ssl)) {
[email protected]109805a2010-12-07 18:17:06103 case SSL2_VERSION:
104 return SSL_CONNECTION_VERSION_SSL2;
105 case SSL3_VERSION:
106 return SSL_CONNECTION_VERSION_SSL3;
107 case TLS1_VERSION:
108 return SSL_CONNECTION_VERSION_TLS1;
davidben1d094022014-11-05 18:55:47109 case TLS1_1_VERSION:
[email protected]109805a2010-12-07 18:17:06110 return SSL_CONNECTION_VERSION_TLS1_1;
davidben1d094022014-11-05 18:55:47111 case TLS1_2_VERSION:
[email protected]109805a2010-12-07 18:17:06112 return SSL_CONNECTION_VERSION_TLS1_2;
113 default:
114 return SSL_CONNECTION_VERSION_UNKNOWN;
115 }
116}
117
[email protected]6bad5052014-07-12 01:25:13118ScopedX509 OSCertHandleToOpenSSL(
119 X509Certificate::OSCertHandle os_handle) {
120#if defined(USE_OPENSSL_CERTS)
121 return ScopedX509(X509Certificate::DupOSCertHandle(os_handle));
122#else // !defined(USE_OPENSSL_CERTS)
123 std::string der_encoded;
124 if (!X509Certificate::GetDEREncoded(os_handle, &der_encoded))
125 return ScopedX509();
126 const uint8_t* bytes = reinterpret_cast<const uint8_t*>(der_encoded.data());
127 return ScopedX509(d2i_X509(NULL, &bytes, der_encoded.size()));
128#endif // defined(USE_OPENSSL_CERTS)
129}
130
[email protected]82c59022014-08-15 09:38:27131ScopedX509Stack OSCertHandlesToOpenSSL(
132 const X509Certificate::OSCertHandles& os_handles) {
133 ScopedX509Stack stack(sk_X509_new_null());
134 for (size_t i = 0; i < os_handles.size(); i++) {
135 ScopedX509 x509 = OSCertHandleToOpenSSL(os_handles[i]);
136 if (!x509)
137 return ScopedX509Stack();
138 sk_X509_push(stack.get(), x509.release());
139 }
140 return stack.Pass();
141}
142
davidben018aad62014-09-12 02:25:19143int LogErrorCallback(const char* str, size_t len, void* context) {
144 LOG(ERROR) << base::StringPiece(str, len);
145 return 1;
146}
147
davidbend1fb2f12014-11-08 02:51:00148bool IsOCSPStaplingSupported() {
149#if defined(OS_WIN)
150 // CERT_OCSP_RESPONSE_PROP_ID is only implemented on Vista+, but it can be
151 // set on Windows XP without error. There is some overhead from the server
152 // sending the OCSP response if it supports the extension, for the subset of
153 // XP clients who will request it but be unable to use it, but this is an
154 // acceptable trade-off for simplicity of implementation.
155 return true;
156#else
157 return false;
158#endif
159}
160
[email protected]821e3bb2013-11-08 01:06:01161} // namespace
162
163class SSLClientSocketOpenSSL::SSLContext {
[email protected]fbef13932010-11-23 12:38:53164 public:
[email protected]b29af7d2010-12-14 11:52:47165 static SSLContext* GetInstance() { return Singleton<SSLContext>::get(); }
[email protected]fbef13932010-11-23 12:38:53166 SSL_CTX* ssl_ctx() { return ssl_ctx_.get(); }
davidbendafe4e52015-04-08 22:53:52167 SSLClientSessionCacheOpenSSL* session_cache() { return &session_cache_; }
[email protected]fbef13932010-11-23 12:38:53168
[email protected]1279de12013-12-03 15:13:32169 SSLClientSocketOpenSSL* GetClientSocketFromSSL(const SSL* ssl) {
[email protected]fbef13932010-11-23 12:38:53170 DCHECK(ssl);
171 SSLClientSocketOpenSSL* socket = static_cast<SSLClientSocketOpenSSL*>(
172 SSL_get_ex_data(ssl, ssl_socket_data_index_));
173 DCHECK(socket);
174 return socket;
175 }
176
177 bool SetClientSocketForSSL(SSL* ssl, SSLClientSocketOpenSSL* socket) {
178 return SSL_set_ex_data(ssl, ssl_socket_data_index_, socket) != 0;
179 }
180
181 private:
182 friend struct DefaultSingletonTraits<SSLContext>;
183
davidbendafe4e52015-04-08 22:53:52184 SSLContext() : session_cache_(SSLClientSessionCacheOpenSSL::Config()) {
[email protected]4b559b4d2011-04-14 17:37:14185 crypto::EnsureOpenSSLInit();
[email protected]fbef13932010-11-23 12:38:53186 ssl_socket_data_index_ = SSL_get_ex_new_index(0, 0, 0, 0, 0);
187 DCHECK_NE(ssl_socket_data_index_, -1);
188 ssl_ctx_.reset(SSL_CTX_new(SSLv23_client_method()));
[email protected]b051cdb62014-02-28 02:20:16189 SSL_CTX_set_cert_verify_callback(ssl_ctx_.get(), CertVerifyCallback, NULL);
[email protected]82c59022014-08-15 09:38:27190 SSL_CTX_set_cert_cb(ssl_ctx_.get(), ClientCertRequestCallback, NULL);
[email protected]b051cdb62014-02-28 02:20:16191 SSL_CTX_set_verify(ssl_ctx_.get(), SSL_VERIFY_PEER, NULL);
haavardmc80b0ee32015-01-30 09:16:08192 // This stops |SSL_shutdown| from generating the close_notify message, which
193 // is currently not sent on the network.
194 // TODO(haavardm): Remove setting quiet shutdown once 118366 is fixed.
195 SSL_CTX_set_quiet_shutdown(ssl_ctx_.get(), 1);
[email protected]ea4a1c6a2010-12-09 13:33:28196 // TODO(kristianm): Only select this if ssl_config_.next_proto is not empty.
197 // It would be better if the callback were not a global setting,
198 // but that is an OpenSSL issue.
199 SSL_CTX_set_next_proto_select_cb(ssl_ctx_.get(), SelectNextProtoCallback,
200 NULL);
[email protected]edfd0f42014-07-22 18:20:37201 ssl_ctx_->tlsext_channel_id_enabled_new = 1;
davidbendafe4e52015-04-08 22:53:52202 SSL_CTX_set_info_callback(ssl_ctx_.get(), InfoCallback);
203
204 // Disable the internal session cache. Session caching is handled
205 // externally (i.e. by SSLClientSessionCacheOpenSSL).
206 SSL_CTX_set_session_cache_mode(
207 ssl_ctx_.get(), SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_NO_INTERNAL);
davidben018aad62014-09-12 02:25:19208
209 scoped_ptr<base::Environment> env(base::Environment::Create());
210 std::string ssl_keylog_file;
211 if (env->GetVar("SSLKEYLOGFILE", &ssl_keylog_file) &&
212 !ssl_keylog_file.empty()) {
213 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
214 BIO* bio = BIO_new_file(ssl_keylog_file.c_str(), "a");
215 if (!bio) {
216 LOG(ERROR) << "Failed to open " << ssl_keylog_file;
217 ERR_print_errors_cb(&LogErrorCallback, NULL);
218 } else {
219 SSL_CTX_set_keylog_bio(ssl_ctx_.get(), bio);
220 }
221 }
[email protected]fbef13932010-11-23 12:38:53222 }
223
[email protected]82c59022014-08-15 09:38:27224 static int ClientCertRequestCallback(SSL* ssl, void* arg) {
[email protected]b29af7d2010-12-14 11:52:47225 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
[email protected]82c59022014-08-15 09:38:27226 DCHECK(socket);
227 return socket->ClientCertRequestCallback(ssl);
[email protected]718c9672010-12-02 10:04:10228 }
229
[email protected]b051cdb62014-02-28 02:20:16230 static int CertVerifyCallback(X509_STORE_CTX *store_ctx, void *arg) {
231 SSL* ssl = reinterpret_cast<SSL*>(X509_STORE_CTX_get_ex_data(
232 store_ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
233 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
234 CHECK(socket);
235
236 return socket->CertVerifyCallback(store_ctx);
237 }
238
[email protected]ea4a1c6a2010-12-09 13:33:28239 static int SelectNextProtoCallback(SSL* ssl,
240 unsigned char** out, unsigned char* outlen,
241 const unsigned char* in,
242 unsigned int inlen, void* arg) {
[email protected]b29af7d2010-12-14 11:52:47243 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
[email protected]ea4a1c6a2010-12-09 13:33:28244 return socket->SelectNextProtoCallback(out, outlen, in, inlen);
245 }
246
davidbendafe4e52015-04-08 22:53:52247 static void InfoCallback(const SSL* ssl, int type, int val) {
248 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
249 socket->InfoCallback(type, val);
250 }
251
[email protected]fbef13932010-11-23 12:38:53252 // This is the index used with SSL_get_ex_data to retrieve the owner
253 // SSLClientSocketOpenSSL object from an SSL instance.
254 int ssl_socket_data_index_;
255
davidbenc879af02015-02-20 07:57:21256 ScopedSSL_CTX ssl_ctx_;
davidbendafe4e52015-04-08 22:53:52257
258 // TODO(davidben): Use a separate cache per URLRequestContext.
259 // https://crbug.com/458365
260 //
261 // TODO(davidben): Sessions should be invalidated on fatal
262 // alerts. https://crbug.com/466352
263 SSLClientSessionCacheOpenSSL session_cache_;
[email protected]1279de12013-12-03 15:13:32264};
265
[email protected]7f38da8a2014-03-17 16:44:26266// PeerCertificateChain is a helper object which extracts the certificate
267// chain, as given by the server, from an OpenSSL socket and performs the needed
268// resource management. The first element of the chain is the leaf certificate
269// and the other elements are in the order given by the server.
270class SSLClientSocketOpenSSL::PeerCertificateChain {
271 public:
[email protected]76e85392014-03-20 17:54:14272 explicit PeerCertificateChain(STACK_OF(X509)* chain) { Reset(chain); }
[email protected]7f38da8a2014-03-17 16:44:26273 PeerCertificateChain(const PeerCertificateChain& other) { *this = other; }
274 ~PeerCertificateChain() {}
275 PeerCertificateChain& operator=(const PeerCertificateChain& other);
276
[email protected]76e85392014-03-20 17:54:14277 // Resets the PeerCertificateChain to the set of certificates in|chain|,
278 // which may be NULL, indicating to empty the store certificates.
279 // Note: If an error occurs, such as being unable to parse the certificates,
280 // this will behave as if Reset(NULL) was called.
281 void Reset(STACK_OF(X509)* chain);
282
[email protected]7f38da8a2014-03-17 16:44:26283 // Note that when USE_OPENSSL is defined, OSCertHandle is X509*
davidben30798ed82014-09-19 19:28:20284 scoped_refptr<X509Certificate> AsOSChain() const;
[email protected]7f38da8a2014-03-17 16:44:26285
286 size_t size() const {
287 if (!openssl_chain_.get())
288 return 0;
289 return sk_X509_num(openssl_chain_.get());
290 }
291
davidben30798ed82014-09-19 19:28:20292 bool empty() const {
293 return size() == 0;
294 }
295
296 X509* Get(size_t index) const {
[email protected]7f38da8a2014-03-17 16:44:26297 DCHECK_LT(index, size());
298 return sk_X509_value(openssl_chain_.get(), index);
299 }
300
301 private:
[email protected]cd9b75b2014-07-10 04:39:38302 ScopedX509Stack openssl_chain_;
[email protected]7f38da8a2014-03-17 16:44:26303};
304
305SSLClientSocketOpenSSL::PeerCertificateChain&
306SSLClientSocketOpenSSL::PeerCertificateChain::operator=(
307 const PeerCertificateChain& other) {
308 if (this == &other)
309 return *this;
310
[email protected]24176af2014-08-14 09:31:04311 openssl_chain_.reset(X509_chain_up_ref(other.openssl_chain_.get()));
[email protected]7f38da8a2014-03-17 16:44:26312 return *this;
313}
314
[email protected]76e85392014-03-20 17:54:14315void SSLClientSocketOpenSSL::PeerCertificateChain::Reset(
316 STACK_OF(X509)* chain) {
davidben30798ed82014-09-19 19:28:20317 openssl_chain_.reset(chain ? X509_chain_up_ref(chain) : NULL);
[email protected]7f38da8a2014-03-17 16:44:26318}
[email protected]7f38da8a2014-03-17 16:44:26319
davidben30798ed82014-09-19 19:28:20320scoped_refptr<X509Certificate>
321SSLClientSocketOpenSSL::PeerCertificateChain::AsOSChain() const {
322#if defined(USE_OPENSSL_CERTS)
323 // When OSCertHandle is typedef'ed to X509, this implementation does a short
324 // cut to avoid converting back and forth between DER and the X509 struct.
325 X509Certificate::OSCertHandles intermediates;
326 for (size_t i = 1; i < sk_X509_num(openssl_chain_.get()); ++i) {
327 intermediates.push_back(sk_X509_value(openssl_chain_.get(), i));
328 }
[email protected]7f38da8a2014-03-17 16:44:26329
davidben30798ed82014-09-19 19:28:20330 return make_scoped_refptr(X509Certificate::CreateFromHandle(
331 sk_X509_value(openssl_chain_.get(), 0), intermediates));
332#else
333 // DER-encode the chain and convert to a platform certificate handle.
[email protected]7f38da8a2014-03-17 16:44:26334 std::vector<base::StringPiece> der_chain;
[email protected]edfd0f42014-07-22 18:20:37335 for (size_t i = 0; i < sk_X509_num(openssl_chain_.get()); ++i) {
[email protected]7f38da8a2014-03-17 16:44:26336 X509* x = sk_X509_value(openssl_chain_.get(), i);
davidben30798ed82014-09-19 19:28:20337 base::StringPiece der;
338 if (!x509_util::GetDER(x, &der))
339 return NULL;
340 der_chain.push_back(der);
[email protected]7f38da8a2014-03-17 16:44:26341 }
342
davidben30798ed82014-09-19 19:28:20343 return make_scoped_refptr(X509Certificate::CreateFromDERCertChain(der_chain));
344#endif
[email protected]7f38da8a2014-03-17 16:44:26345}
[email protected]7f38da8a2014-03-17 16:44:26346
[email protected]1279de12013-12-03 15:13:32347// static
[email protected]c3456bb2011-12-12 22:22:19348void SSLClientSocket::ClearSessionCache() {
[email protected]821e3bb2013-11-08 01:06:01349 SSLClientSocketOpenSSL::SSLContext* context =
350 SSLClientSocketOpenSSL::SSLContext::GetInstance();
[email protected]c3456bb2011-12-12 22:22:19351 context->session_cache()->Flush();
352}
353
bnc86b734dd2014-12-03 00:33:10354// static
355uint16 SSLClientSocket::GetMaxSupportedSSLVersion() {
356 return SSL_PROTOCOL_VERSION_TLS1_2;
357}
358
[email protected]d518cd92010-09-29 12:27:44359SSLClientSocketOpenSSL::SSLClientSocketOpenSSL(
[email protected]18ccfdb2013-08-15 00:13:44360 scoped_ptr<ClientSocketHandle> transport_socket,
[email protected]055d7f22010-11-15 12:03:12361 const HostPortPair& host_and_port,
[email protected]822581d2010-12-16 17:27:15362 const SSLConfig& ssl_config,
[email protected]feb79bcd2011-07-21 16:55:17363 const SSLClientSocketContext& context)
[email protected]83039bb2011-12-09 18:43:55364 : transport_send_busy_(false),
[email protected]d518cd92010-09-29 12:27:44365 transport_recv_busy_(false),
[email protected]4b768562013-02-16 04:10:07366 pending_read_error_(kNoPendingReadResult),
davidbenb8c23212014-10-28 00:12:16367 pending_read_ssl_error_(SSL_ERROR_NONE),
[email protected]5aea79182014-07-14 20:43:41368 transport_read_error_(OK),
[email protected]3e5c6922014-02-06 02:42:16369 transport_write_error_(OK),
[email protected]7f38da8a2014-03-17 16:44:26370 server_cert_chain_(new PeerCertificateChain(NULL)),
[email protected]64b5c892014-08-08 09:39:26371 completed_connect_(false),
[email protected]0dc88b32014-03-26 20:12:28372 was_ever_used_(false),
[email protected]d518cd92010-09-29 12:27:44373 client_auth_cert_needed_(false),
[email protected]feb79bcd2011-07-21 16:55:17374 cert_verifier_(context.cert_verifier),
davidbeneb5f8ef32014-09-04 14:14:32375 cert_transparency_verifier_(context.cert_transparency_verifier),
[email protected]6b8a3c742014-07-25 00:25:35376 channel_id_service_(context.channel_id_service),
[email protected]d518cd92010-09-29 12:27:44377 ssl_(NULL),
378 transport_bio_(NULL),
[email protected]18ccfdb2013-08-15 00:13:44379 transport_(transport_socket.Pass()),
[email protected]055d7f22010-11-15 12:03:12380 host_and_port_(host_and_port),
[email protected]d518cd92010-09-29 12:27:44381 ssl_config_(ssl_config),
[email protected]c3456bb2011-12-12 22:22:19382 ssl_session_cache_shard_(context.ssl_session_cache_shard),
[email protected]013c17c2012-01-21 19:09:01383 next_handshake_state_(STATE_NONE),
[email protected]ea4a1c6a2010-12-09 13:33:28384 npn_status_(kNextProtoUnsupported),
[email protected]ee0f2aa82013-10-25 11:59:26385 channel_id_xtn_negotiated_(false),
davidbendafe4e52015-04-08 22:53:52386 handshake_completed_(false),
387 certificate_verified_(false),
[email protected]8bd4e7a2014-08-09 14:49:17388 transport_security_state_(context.transport_security_state),
eranm6571b2b2014-12-03 15:53:23389 policy_enforcer_(context.cert_policy_enforcer),
kulkarni.acd7b4462014-08-28 07:41:34390 net_log_(transport_->socket()->NetLog()),
391 weak_factory_(this) {
davidben9bbf3292015-04-24 21:50:06392 DCHECK(cert_verifier_);
[email protected]8e458552014-08-05 00:02:15393}
[email protected]d518cd92010-09-29 12:27:44394
395SSLClientSocketOpenSSL::~SSLClientSocketOpenSSL() {
396 Disconnect();
397}
398
[email protected]b9b651f2013-11-09 04:32:22399void SSLClientSocketOpenSSL::GetSSLCertRequestInfo(
400 SSLCertRequestInfo* cert_request_info) {
[email protected]791879c2013-12-17 07:22:41401 cert_request_info->host_and_port = host_and_port_;
[email protected]b9b651f2013-11-09 04:32:22402 cert_request_info->cert_authorities = cert_authorities_;
[email protected]c0787702014-05-20 21:51:44403 cert_request_info->cert_key_types = cert_key_types_;
[email protected]b9b651f2013-11-09 04:32:22404}
405
406SSLClientSocket::NextProtoStatus SSLClientSocketOpenSSL::GetNextProto(
[email protected]abc44b752014-07-30 03:52:15407 std::string* proto) {
[email protected]b9b651f2013-11-09 04:32:22408 *proto = npn_proto_;
[email protected]b9b651f2013-11-09 04:32:22409 return npn_status_;
410}
411
[email protected]6b8a3c742014-07-25 00:25:35412ChannelIDService*
413SSLClientSocketOpenSSL::GetChannelIDService() const {
414 return channel_id_service_;
[email protected]b9b651f2013-11-09 04:32:22415}
416
417int SSLClientSocketOpenSSL::ExportKeyingMaterial(
418 const base::StringPiece& label,
419 bool has_context, const base::StringPiece& context,
420 unsigned char* out, unsigned int outlen) {
421 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
422
423 int rv = SSL_export_keying_material(
[email protected]c8a80e92014-05-17 16:02:08424 ssl_, out, outlen, label.data(), label.size(),
davidben866c3d4a72015-04-06 21:56:43425 reinterpret_cast<const unsigned char*>(context.data()), context.length(),
426 has_context ? 1 : 0);
[email protected]b9b651f2013-11-09 04:32:22427
428 if (rv != 1) {
429 int ssl_error = SSL_get_error(ssl_, rv);
430 LOG(ERROR) << "Failed to export keying material;"
431 << " returned " << rv
432 << ", SSL error code " << ssl_error;
433 return MapOpenSSLError(ssl_error, err_tracer);
434 }
435 return OK;
436}
437
438int SSLClientSocketOpenSSL::GetTLSUniqueChannelBinding(std::string* out) {
[email protected]c8a80e92014-05-17 16:02:08439 NOTIMPLEMENTED();
[email protected]b9b651f2013-11-09 04:32:22440 return ERR_NOT_IMPLEMENTED;
441}
442
443int SSLClientSocketOpenSSL::Connect(const CompletionCallback& callback) {
[email protected]8bd4e7a2014-08-09 14:49:17444 // It is an error to create an SSLClientSocket whose context has no
445 // TransportSecurityState.
446 DCHECK(transport_security_state_);
447
[email protected]b9b651f2013-11-09 04:32:22448 net_log_.BeginEvent(NetLog::TYPE_SSL_CONNECT);
449
450 // Set up new ssl object.
[email protected]c8a80e92014-05-17 16:02:08451 int rv = Init();
452 if (rv != OK) {
453 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
454 return rv;
[email protected]b9b651f2013-11-09 04:32:22455 }
456
457 // Set SSL to client mode. Handshake happens in the loop below.
458 SSL_set_connect_state(ssl_);
459
460 GotoState(STATE_HANDSHAKE);
[email protected]c8a80e92014-05-17 16:02:08461 rv = DoHandshakeLoop(OK);
[email protected]b9b651f2013-11-09 04:32:22462 if (rv == ERR_IO_PENDING) {
463 user_connect_callback_ = callback;
464 } else {
465 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
466 }
467
468 return rv > OK ? OK : rv;
469}
470
471void SSLClientSocketOpenSSL::Disconnect() {
472 if (ssl_) {
473 // Calling SSL_shutdown prevents the session from being marked as
474 // unresumable.
475 SSL_shutdown(ssl_);
476 SSL_free(ssl_);
477 ssl_ = NULL;
478 }
479 if (transport_bio_) {
480 BIO_free_all(transport_bio_);
481 transport_bio_ = NULL;
482 }
483
484 // Shut down anything that may call us back.
485 verifier_.reset();
486 transport_->socket()->Disconnect();
487
488 // Null all callbacks, delete all buffers.
489 transport_send_busy_ = false;
490 send_buffer_ = NULL;
491 transport_recv_busy_ = false;
[email protected]b9b651f2013-11-09 04:32:22492 recv_buffer_ = NULL;
493
494 user_connect_callback_.Reset();
495 user_read_callback_.Reset();
496 user_write_callback_.Reset();
497 user_read_buf_ = NULL;
498 user_read_buf_len_ = 0;
499 user_write_buf_ = NULL;
500 user_write_buf_len_ = 0;
501
[email protected]3e5c6922014-02-06 02:42:16502 pending_read_error_ = kNoPendingReadResult;
davidbenb8c23212014-10-28 00:12:16503 pending_read_ssl_error_ = SSL_ERROR_NONE;
504 pending_read_error_info_ = OpenSSLErrorInfo();
505
[email protected]5aea79182014-07-14 20:43:41506 transport_read_error_ = OK;
[email protected]3e5c6922014-02-06 02:42:16507 transport_write_error_ = OK;
508
[email protected]b9b651f2013-11-09 04:32:22509 server_cert_verify_result_.Reset();
[email protected]64b5c892014-08-08 09:39:26510 completed_connect_ = false;
[email protected]b9b651f2013-11-09 04:32:22511
512 cert_authorities_.clear();
[email protected]c0787702014-05-20 21:51:44513 cert_key_types_.clear();
[email protected]b9b651f2013-11-09 04:32:22514 client_auth_cert_needed_ = false;
[email protected]faff9852014-06-21 06:13:46515
davidben09c3d072014-08-25 20:33:58516 start_cert_verification_time_ = base::TimeTicks();
517
[email protected]abc44b752014-07-30 03:52:15518 npn_status_ = kNextProtoUnsupported;
519 npn_proto_.clear();
520
[email protected]faff9852014-06-21 06:13:46521 channel_id_xtn_negotiated_ = false;
522 channel_id_request_handle_.Cancel();
[email protected]b9b651f2013-11-09 04:32:22523}
524
525bool SSLClientSocketOpenSSL::IsConnected() const {
526 // If the handshake has not yet completed.
[email protected]64b5c892014-08-08 09:39:26527 if (!completed_connect_)
[email protected]b9b651f2013-11-09 04:32:22528 return false;
529 // If an asynchronous operation is still pending.
530 if (user_read_buf_.get() || user_write_buf_.get())
531 return true;
532
533 return transport_->socket()->IsConnected();
534}
535
536bool SSLClientSocketOpenSSL::IsConnectedAndIdle() const {
537 // If the handshake has not yet completed.
[email protected]64b5c892014-08-08 09:39:26538 if (!completed_connect_)
[email protected]b9b651f2013-11-09 04:32:22539 return false;
540 // If an asynchronous operation is still pending.
541 if (user_read_buf_.get() || user_write_buf_.get())
542 return false;
davidbenfc9a6b82015-04-15 23:47:32543
544 // If there is data read from the network that has not yet been consumed, do
545 // not treat the connection as idle.
546 //
547 // Note that this does not check |BIO_pending|, whether there is ciphertext
548 // that has not yet been flushed to the network. |Write| returns early, so
549 // this can cause race conditions which cause a socket to not be treated
550 // reusable when it should be. See https://crbug.com/466147.
551 if (BIO_wpending(transport_bio_) > 0)
[email protected]b9b651f2013-11-09 04:32:22552 return false;
[email protected]b9b651f2013-11-09 04:32:22553
554 return transport_->socket()->IsConnectedAndIdle();
555}
556
557int SSLClientSocketOpenSSL::GetPeerAddress(IPEndPoint* addressList) const {
558 return transport_->socket()->GetPeerAddress(addressList);
559}
560
561int SSLClientSocketOpenSSL::GetLocalAddress(IPEndPoint* addressList) const {
562 return transport_->socket()->GetLocalAddress(addressList);
563}
564
565const BoundNetLog& SSLClientSocketOpenSSL::NetLog() const {
566 return net_log_;
567}
568
569void SSLClientSocketOpenSSL::SetSubresourceSpeculation() {
570 if (transport_.get() && transport_->socket()) {
571 transport_->socket()->SetSubresourceSpeculation();
572 } else {
573 NOTREACHED();
574 }
575}
576
577void SSLClientSocketOpenSSL::SetOmniboxSpeculation() {
578 if (transport_.get() && transport_->socket()) {
579 transport_->socket()->SetOmniboxSpeculation();
580 } else {
581 NOTREACHED();
582 }
583}
584
585bool SSLClientSocketOpenSSL::WasEverUsed() const {
[email protected]0dc88b32014-03-26 20:12:28586 return was_ever_used_;
[email protected]b9b651f2013-11-09 04:32:22587}
588
589bool SSLClientSocketOpenSSL::UsingTCPFastOpen() const {
590 if (transport_.get() && transport_->socket())
591 return transport_->socket()->UsingTCPFastOpen();
592
593 NOTREACHED();
594 return false;
595}
596
597bool SSLClientSocketOpenSSL::GetSSLInfo(SSLInfo* ssl_info) {
598 ssl_info->Reset();
davidben30798ed82014-09-19 19:28:20599 if (server_cert_chain_->empty())
[email protected]b9b651f2013-11-09 04:32:22600 return false;
601
602 ssl_info->cert = server_cert_verify_result_.verified_cert;
603 ssl_info->cert_status = server_cert_verify_result_.cert_status;
604 ssl_info->is_issued_by_known_root =
605 server_cert_verify_result_.is_issued_by_known_root;
606 ssl_info->public_key_hashes =
607 server_cert_verify_result_.public_key_hashes;
608 ssl_info->client_cert_sent =
609 ssl_config_.send_client_cert && ssl_config_.client_cert.get();
610 ssl_info->channel_id_sent = WasChannelIDSent();
[email protected]8bd4e7a2014-08-09 14:49:17611 ssl_info->pinning_failure_log = pinning_failure_log_;
[email protected]b9b651f2013-11-09 04:32:22612
davidbeneb5f8ef32014-09-04 14:14:32613 AddSCTInfoToSSLInfo(ssl_info);
614
[email protected]b9b651f2013-11-09 04:32:22615 const SSL_CIPHER* cipher = SSL_get_current_cipher(ssl_);
616 CHECK(cipher);
617 ssl_info->security_bits = SSL_CIPHER_get_bits(cipher, NULL);
[email protected]b9b651f2013-11-09 04:32:22618
619 ssl_info->connection_status = EncodeSSLConnectionStatus(
pkasting6b68a162014-12-01 22:10:29620 static_cast<uint16>(SSL_CIPHER_get_id(cipher)), 0 /* no compression */,
[email protected]b9b651f2013-11-09 04:32:22621 GetNetSSLVersion(ssl_));
622
davidben09c3d072014-08-25 20:33:58623 if (!SSL_get_secure_renegotiation_support(ssl_))
[email protected]b9b651f2013-11-09 04:32:22624 ssl_info->connection_status |= SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION;
[email protected]b9b651f2013-11-09 04:32:22625
626 if (ssl_config_.version_fallback)
627 ssl_info->connection_status |= SSL_CONNECTION_VERSION_FALLBACK;
628
629 ssl_info->handshake_type = SSL_session_reused(ssl_) ?
630 SSLInfo::HANDSHAKE_RESUME : SSLInfo::HANDSHAKE_FULL;
631
632 DVLOG(3) << "Encoded connection status: cipher suite = "
633 << SSLConnectionStatusToCipherSuite(ssl_info->connection_status)
634 << " version = "
635 << SSLConnectionStatusToVersion(ssl_info->connection_status);
636 return true;
637}
638
639int SSLClientSocketOpenSSL::Read(IOBuffer* buf,
640 int buf_len,
641 const CompletionCallback& callback) {
642 user_read_buf_ = buf;
643 user_read_buf_len_ = buf_len;
644
davidben1b133ad2014-10-23 04:23:13645 int rv = DoReadLoop();
[email protected]b9b651f2013-11-09 04:32:22646
647 if (rv == ERR_IO_PENDING) {
648 user_read_callback_ = callback;
649 } else {
[email protected]0dc88b32014-03-26 20:12:28650 if (rv > 0)
651 was_ever_used_ = true;
[email protected]b9b651f2013-11-09 04:32:22652 user_read_buf_ = NULL;
653 user_read_buf_len_ = 0;
654 }
655
656 return rv;
657}
658
659int SSLClientSocketOpenSSL::Write(IOBuffer* buf,
660 int buf_len,
661 const CompletionCallback& callback) {
662 user_write_buf_ = buf;
663 user_write_buf_len_ = buf_len;
664
davidben1b133ad2014-10-23 04:23:13665 int rv = DoWriteLoop();
[email protected]b9b651f2013-11-09 04:32:22666
667 if (rv == ERR_IO_PENDING) {
668 user_write_callback_ = callback;
669 } else {
[email protected]0dc88b32014-03-26 20:12:28670 if (rv > 0)
671 was_ever_used_ = true;
[email protected]b9b651f2013-11-09 04:32:22672 user_write_buf_ = NULL;
673 user_write_buf_len_ = 0;
674 }
675
676 return rv;
677}
678
[email protected]28b96d1c2014-04-09 12:21:15679int SSLClientSocketOpenSSL::SetReceiveBufferSize(int32 size) {
[email protected]b9b651f2013-11-09 04:32:22680 return transport_->socket()->SetReceiveBufferSize(size);
681}
682
[email protected]28b96d1c2014-04-09 12:21:15683int SSLClientSocketOpenSSL::SetSendBufferSize(int32 size) {
[email protected]b9b651f2013-11-09 04:32:22684 return transport_->socket()->SetSendBufferSize(size);
685}
686
[email protected]c8a80e92014-05-17 16:02:08687int SSLClientSocketOpenSSL::Init() {
[email protected]9e733f32010-10-04 18:19:08688 DCHECK(!ssl_);
689 DCHECK(!transport_bio_);
690
[email protected]b29af7d2010-12-14 11:52:47691 SSLContext* context = SSLContext::GetInstance();
[email protected]4b559b4d2011-04-14 17:37:14692 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
[email protected]d518cd92010-09-29 12:27:44693
[email protected]fbef13932010-11-23 12:38:53694 ssl_ = SSL_new(context->ssl_ctx());
695 if (!ssl_ || !context->SetClientSocketForSSL(ssl_, this))
[email protected]c8a80e92014-05-17 16:02:08696 return ERR_UNEXPECTED;
[email protected]fbef13932010-11-23 12:38:53697
698 if (!SSL_set_tlsext_host_name(ssl_, host_and_port_.host().c_str()))
[email protected]c8a80e92014-05-17 16:02:08699 return ERR_UNEXPECTED;
[email protected]fbef13932010-11-23 12:38:53700
davidbendafe4e52015-04-08 22:53:52701 SSL_SESSION* session = context->session_cache()->Lookup(GetSessionCacheKey());
702 if (session != nullptr)
703 SSL_set_session(ssl_, session);
[email protected]d518cd92010-09-29 12:27:44704
haavardm2d92e722014-12-19 13:45:44705 send_buffer_ = new GrowableIOBuffer();
706 send_buffer_->SetCapacity(KDefaultOpenSSLBufferSize);
707 recv_buffer_ = new GrowableIOBuffer();
708 recv_buffer_->SetCapacity(KDefaultOpenSSLBufferSize);
709
[email protected]d518cd92010-09-29 12:27:44710 BIO* ssl_bio = NULL;
haavardm2d92e722014-12-19 13:45:44711
712 // SSLClientSocketOpenSSL retains ownership of the BIO buffers.
713 if (!BIO_new_bio_pair_external_buf(
714 &ssl_bio, send_buffer_->capacity(),
715 reinterpret_cast<uint8_t*>(send_buffer_->data()), &transport_bio_,
716 recv_buffer_->capacity(),
717 reinterpret_cast<uint8_t*>(recv_buffer_->data())))
[email protected]c8a80e92014-05-17 16:02:08718 return ERR_UNEXPECTED;
[email protected]d518cd92010-09-29 12:27:44719 DCHECK(ssl_bio);
720 DCHECK(transport_bio_);
721
[email protected]5aea79182014-07-14 20:43:41722 // Install a callback on OpenSSL's end to plumb transport errors through.
rsleevif020edc2015-03-16 19:31:24723 BIO_set_callback(ssl_bio, &SSLClientSocketOpenSSL::BIOCallback);
[email protected]5aea79182014-07-14 20:43:41724 BIO_set_callback_arg(ssl_bio, reinterpret_cast<char*>(this));
725
[email protected]d518cd92010-09-29 12:27:44726 SSL_set_bio(ssl_, ssl_bio, ssl_bio);
727
[email protected]9e733f32010-10-04 18:19:08728 // OpenSSL defaults some options to on, others to off. To avoid ambiguity,
729 // set everything we care about to an absolute value.
[email protected]fb10e2282010-12-01 17:08:48730 SslSetClearMask options;
731 options.ConfigureFlag(SSL_OP_NO_SSLv2, true);
[email protected]80c75f682012-05-26 16:22:17732 bool ssl3_enabled = (ssl_config_.version_min == SSL_PROTOCOL_VERSION_SSL3);
733 options.ConfigureFlag(SSL_OP_NO_SSLv3, !ssl3_enabled);
734 bool tls1_enabled = (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1 &&
735 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1);
736 options.ConfigureFlag(SSL_OP_NO_TLSv1, !tls1_enabled);
[email protected]80c75f682012-05-26 16:22:17737 bool tls1_1_enabled =
738 (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1_1 &&
739 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1_1);
740 options.ConfigureFlag(SSL_OP_NO_TLSv1_1, !tls1_1_enabled);
[email protected]80c75f682012-05-26 16:22:17741 bool tls1_2_enabled =
742 (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1_2 &&
743 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1_2);
744 options.ConfigureFlag(SSL_OP_NO_TLSv1_2, !tls1_2_enabled);
[email protected]fb10e2282010-12-01 17:08:48745
[email protected]d0f00492012-08-03 22:35:13746 options.ConfigureFlag(SSL_OP_NO_COMPRESSION, true);
[email protected]9e733f32010-10-04 18:19:08747
748 // TODO(joth): Set this conditionally, see http://crbug.com/55410
[email protected]fb10e2282010-12-01 17:08:48749 options.ConfigureFlag(SSL_OP_LEGACY_SERVER_CONNECT, true);
[email protected]9e733f32010-10-04 18:19:08750
[email protected]fb10e2282010-12-01 17:08:48751 SSL_set_options(ssl_, options.set_mask);
752 SSL_clear_options(ssl_, options.clear_mask);
[email protected]9e733f32010-10-04 18:19:08753
[email protected]fb10e2282010-12-01 17:08:48754 // Same as above, this time for the SSL mode.
755 SslSetClearMask mode;
[email protected]9e733f32010-10-04 18:19:08756
[email protected]fb10e2282010-12-01 17:08:48757 mode.ConfigureFlag(SSL_MODE_RELEASE_BUFFERS, true);
ishermane5c05e12014-09-09 20:32:15758 mode.ConfigureFlag(SSL_MODE_CBC_RECORD_SPLITTING, true);
[email protected]fb10e2282010-12-01 17:08:48759
davidben818d93b2015-02-19 22:27:32760 mode.ConfigureFlag(SSL_MODE_ENABLE_FALSE_START,
[email protected]b788de02014-04-23 18:06:07761 ssl_config_.false_start_enabled);
762
davidben6b8131c2015-02-25 23:30:14763 mode.ConfigureFlag(SSL_MODE_SEND_FALLBACK_SCSV, ssl_config_.version_fallback);
764
[email protected]fb10e2282010-12-01 17:08:48765 SSL_set_mode(ssl_, mode.set_mask);
766 SSL_clear_mode(ssl_, mode.clear_mask);
[email protected]109805a2010-12-07 18:17:06767
768 // Removing ciphers by ID from OpenSSL is a bit involved as we must use the
769 // textual name with SSL_set_cipher_list because there is no public API to
770 // directly remove a cipher by ID.
771 STACK_OF(SSL_CIPHER)* ciphers = SSL_get_ciphers(ssl_);
772 DCHECK(ciphers);
773 // See SSLConfig::disabled_cipher_suites for description of the suites
[email protected]9b4bc4a92013-08-20 22:59:07774 // disabled by default. Note that !SHA256 and !SHA384 only remove HMAC-SHA256
775 // and HMAC-SHA384 cipher suites, not GCM cipher suites with SHA256 or SHA384
776 // as the handshake hash.
bnc1e757502014-12-13 02:20:16777 std::string command(
778 "DEFAULT:!NULL:!aNULL:!SHA256:!SHA384:!aECDH:!AESGCM+AES256:!aPSK");
[email protected]109805a2010-12-07 18:17:06779 // Walk through all the installed ciphers, seeing if any need to be
780 // appended to the cipher removal |command|.
[email protected]edfd0f42014-07-22 18:20:37781 for (size_t i = 0; i < sk_SSL_CIPHER_num(ciphers); ++i) {
[email protected]109805a2010-12-07 18:17:06782 const SSL_CIPHER* cipher = sk_SSL_CIPHER_value(ciphers, i);
pkasting6b68a162014-12-01 22:10:29783 const uint16 id = static_cast<uint16>(SSL_CIPHER_get_id(cipher));
[email protected]109805a2010-12-07 18:17:06784 // Remove any ciphers with a strength of less than 80 bits. Note the NSS
785 // implementation uses "effective" bits here but OpenSSL does not provide
786 // this detail. This only impacts Triple DES: reports 112 vs. 168 bits,
787 // both of which are greater than 80 anyway.
788 bool disable = SSL_CIPHER_get_bits(cipher, NULL) < 80;
789 if (!disable) {
790 disable = std::find(ssl_config_.disabled_cipher_suites.begin(),
791 ssl_config_.disabled_cipher_suites.end(), id) !=
792 ssl_config_.disabled_cipher_suites.end();
793 }
794 if (disable) {
795 const char* name = SSL_CIPHER_get_name(cipher);
796 DVLOG(3) << "Found cipher to remove: '" << name << "', ID: " << id
797 << " strength: " << SSL_CIPHER_get_bits(cipher, NULL);
798 command.append(":!");
799 command.append(name);
800 }
801 }
davidben8ecc3072014-09-03 23:19:09802
davidbena4c9d062015-04-03 22:34:25803 if (!ssl_config_.enable_deprecated_cipher_suites)
804 command.append(":!RC4");
805
davidben8ecc3072014-09-03 23:19:09806 // Disable ECDSA cipher suites on platforms that do not support ECDSA
807 // signed certificates, as servers may use the presence of such
808 // ciphersuites as a hint to send an ECDSA certificate.
809#if defined(OS_WIN)
810 if (base::win::GetVersion() < base::win::VERSION_VISTA)
811 command.append(":!ECDSA");
812#endif
813
[email protected]109805a2010-12-07 18:17:06814 int rv = SSL_set_cipher_list(ssl_, command.c_str());
815 // If this fails (rv = 0) it means there are no ciphers enabled on this SSL.
816 // This will almost certainly result in the socket failing to complete the
817 // handshake at which point the appropriate error is bubbled up to the client.
818 LOG_IF(WARNING, rv != 1) << "SSL_set_cipher_list('" << command << "') "
819 "returned " << rv;
[email protected]ee0f2aa82013-10-25 11:59:26820
821 // TLS channel ids.
[email protected]6b8a3c742014-07-25 00:25:35822 if (IsChannelIDEnabled(ssl_config_, channel_id_service_)) {
[email protected]ee0f2aa82013-10-25 11:59:26823 SSL_enable_tls_channel_id(ssl_);
824 }
825
[email protected]abc44b752014-07-30 03:52:15826 if (!ssl_config_.next_protos.empty()) {
bnc1e757502014-12-13 02:20:16827 // Get list of ciphers that are enabled.
828 STACK_OF(SSL_CIPHER)* enabled_ciphers = SSL_get_ciphers(ssl_);
829 DCHECK(enabled_ciphers);
830 std::vector<uint16> enabled_ciphers_vector;
831 for (size_t i = 0; i < sk_SSL_CIPHER_num(enabled_ciphers); ++i) {
832 const SSL_CIPHER* cipher = sk_SSL_CIPHER_value(enabled_ciphers, i);
833 const uint16 id = static_cast<uint16>(SSL_CIPHER_get_id(cipher));
834 enabled_ciphers_vector.push_back(id);
835 }
836
[email protected]abc44b752014-07-30 03:52:15837 std::vector<uint8_t> wire_protos =
bnc1e757502014-12-13 02:20:16838 SerializeNextProtos(ssl_config_.next_protos,
839 HasCipherAdequateForHTTP2(enabled_ciphers_vector) &&
840 IsTLSVersionAdequateForHTTP2(ssl_config_));
[email protected]abc44b752014-07-30 03:52:15841 SSL_set_alpn_protos(ssl_, wire_protos.empty() ? NULL : &wire_protos[0],
842 wire_protos.size());
843 }
844
davidbeneb5f8ef32014-09-04 14:14:32845 if (ssl_config_.signed_cert_timestamps_enabled) {
846 SSL_enable_signed_cert_timestamps(ssl_);
847 SSL_enable_ocsp_stapling(ssl_);
848 }
849
davidbend1fb2f12014-11-08 02:51:00850 if (IsOCSPStaplingSupported())
851 SSL_enable_ocsp_stapling(ssl_);
davidbeneb5f8ef32014-09-04 14:14:32852
davidben24463662015-04-09 23:36:48853 // Enable fastradio padding.
854 SSL_enable_fastradio_padding(ssl_,
855 ssl_config_.fastradio_padding_enabled &&
856 ssl_config_.fastradio_padding_eligible);
857
[email protected]c8a80e92014-05-17 16:02:08858 return OK;
[email protected]d518cd92010-09-29 12:27:44859}
860
[email protected]b9b651f2013-11-09 04:32:22861void SSLClientSocketOpenSSL::DoReadCallback(int rv) {
862 // Since Run may result in Read being called, clear |user_read_callback_|
863 // up front.
[email protected]0dc88b32014-03-26 20:12:28864 if (rv > 0)
865 was_ever_used_ = true;
[email protected]b9b651f2013-11-09 04:32:22866 user_read_buf_ = NULL;
867 user_read_buf_len_ = 0;
868 base::ResetAndReturn(&user_read_callback_).Run(rv);
869}
870
871void SSLClientSocketOpenSSL::DoWriteCallback(int rv) {
872 // Since Run may result in Write being called, clear |user_write_callback_|
873 // up front.
[email protected]0dc88b32014-03-26 20:12:28874 if (rv > 0)
875 was_ever_used_ = true;
[email protected]b9b651f2013-11-09 04:32:22876 user_write_buf_ = NULL;
877 user_write_buf_len_ = 0;
878 base::ResetAndReturn(&user_write_callback_).Run(rv);
879}
880
881bool SSLClientSocketOpenSSL::DoTransportIO() {
882 bool network_moved = false;
883 int rv;
884 // Read and write as much data as possible. The loop is necessary because
885 // Write() may return synchronously.
886 do {
887 rv = BufferSend();
888 if (rv != ERR_IO_PENDING && rv != 0)
889 network_moved = true;
890 } while (rv > 0);
[email protected]5aea79182014-07-14 20:43:41891 if (transport_read_error_ == OK && BufferRecv() != ERR_IO_PENDING)
[email protected]b9b651f2013-11-09 04:32:22892 network_moved = true;
893 return network_moved;
894}
895
pkasting379234c2015-04-08 04:42:12896// TODO(cbentzel): Remove including "base/threading/thread_local.h" and
vadimt6b43dec22015-01-06 01:59:58897// g_first_run_completed once crbug.com/424386 is fixed.
898base::LazyInstance<base::ThreadLocalBoolean>::Leaky g_first_run_completed =
899 LAZY_INSTANCE_INITIALIZER;
900
[email protected]b9b651f2013-11-09 04:32:22901int SSLClientSocketOpenSSL::DoHandshake() {
902 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
[email protected]c8a80e92014-05-17 16:02:08903 int net_error = OK;
vadimt5a243282014-12-24 00:26:16904
905 int rv;
906
pkasting379234c2015-04-08 04:42:12907 // TODO(cbentzel): Leave only 1 call to SSL_do_handshake once crbug.com/424386
vadimt5a243282014-12-24 00:26:16908 // is fixed.
909 if (ssl_config_.send_client_cert && ssl_config_.client_cert.get()) {
vadimt5a243282014-12-24 00:26:16910 rv = SSL_do_handshake(ssl_);
911 } else {
vadimt6b43dec22015-01-06 01:59:58912 if (g_first_run_completed.Get().Get()) {
pkasting379234c2015-04-08 04:42:12913 // TODO(cbentzel): Remove ScopedTracker below once crbug.com/424386 is
vadimt6b43dec22015-01-06 01:59:58914 // fixed.
pkasting379234c2015-04-08 04:42:12915 tracked_objects::ScopedTracker tracking_profile(
916 FROM_HERE_WITH_EXPLICIT_FUNCTION("424386 SSL_do_handshake()"));
vadimt5a243282014-12-24 00:26:16917
vadimt6b43dec22015-01-06 01:59:58918 rv = SSL_do_handshake(ssl_);
919 } else {
920 g_first_run_completed.Get().Set(true);
vadimt6b43dec22015-01-06 01:59:58921 rv = SSL_do_handshake(ssl_);
922 }
vadimt5a243282014-12-24 00:26:16923 }
[email protected]b9b651f2013-11-09 04:32:22924
davidben8114f802015-03-25 17:02:34925 if (rv == 1) {
Adam Langley32352ad2014-10-14 22:31:00926 if (ssl_config_.version_fallback &&
927 ssl_config_.version_max < ssl_config_.version_fallback_min) {
928 return ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION;
929 }
930
[email protected]abc44b752014-07-30 03:52:15931 // SSL handshake is completed. If NPN wasn't negotiated, see if ALPN was.
932 if (npn_status_ == kNextProtoUnsupported) {
933 const uint8_t* alpn_proto = NULL;
934 unsigned alpn_len = 0;
935 SSL_get0_alpn_selected(ssl_, &alpn_proto, &alpn_len);
936 if (alpn_len > 0) {
937 npn_proto_.assign(reinterpret_cast<const char*>(alpn_proto), alpn_len);
938 npn_status_ = kNextProtoNegotiated;
bnc0d28ea52014-10-13 15:15:38939 set_negotiation_extension(kExtensionALPN);
[email protected]abc44b752014-07-30 03:52:15940 }
941 }
942
davidben09c3d072014-08-25 20:33:58943 RecordChannelIDSupport(channel_id_service_,
944 channel_id_xtn_negotiated_,
945 ssl_config_.channel_id_enabled,
946 crypto::ECPrivateKey::IsSupported());
947
davidbend1fb2f12014-11-08 02:51:00948 // Only record OCSP histograms if OCSP was requested.
949 if (ssl_config_.signed_cert_timestamps_enabled ||
950 IsOCSPStaplingSupported()) {
davidben54015aa2014-12-02 22:16:23951 const uint8_t* ocsp_response;
davidbend1fb2f12014-11-08 02:51:00952 size_t ocsp_response_len;
953 SSL_get0_ocsp_response(ssl_, &ocsp_response, &ocsp_response_len);
954
955 set_stapled_ocsp_response_received(ocsp_response_len != 0);
956 UMA_HISTOGRAM_BOOLEAN("Net.OCSPResponseStapled", ocsp_response_len != 0);
957 }
davidbeneb5f8ef32014-09-04 14:14:32958
davidben54015aa2014-12-02 22:16:23959 const uint8_t* sct_list;
davidbeneb5f8ef32014-09-04 14:14:32960 size_t sct_list_len;
961 SSL_get0_signed_cert_timestamp_list(ssl_, &sct_list, &sct_list_len);
962 set_signed_cert_timestamps_received(sct_list_len != 0);
963
[email protected]abc44b752014-07-30 03:52:15964 // Verify the certificate.
davidben30798ed82014-09-19 19:28:20965 UpdateServerCert();
[email protected]b9b651f2013-11-09 04:32:22966 GotoState(STATE_VERIFY_CERT);
967 } else {
davidben8114f802015-03-25 17:02:34968 if (client_auth_cert_needed_)
969 return ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
970
[email protected]b9b651f2013-11-09 04:32:22971 int ssl_error = SSL_get_error(ssl_, rv);
972
973 if (ssl_error == SSL_ERROR_WANT_CHANNEL_ID_LOOKUP) {
[email protected]faff9852014-06-21 06:13:46974 // The server supports channel ID. Stop to look one up before returning to
975 // the handshake.
976 channel_id_xtn_negotiated_ = true;
977 GotoState(STATE_CHANNEL_ID_LOOKUP);
978 return OK;
[email protected]b9b651f2013-11-09 04:32:22979 }
980
davidbena4409c62014-08-27 17:05:51981 OpenSSLErrorInfo error_info;
982 net_error = MapOpenSSLErrorWithDetails(ssl_error, err_tracer, &error_info);
[email protected]faff9852014-06-21 06:13:46983
[email protected]b9b651f2013-11-09 04:32:22984 // If not done, stay in this state
985 if (net_error == ERR_IO_PENDING) {
986 GotoState(STATE_HANDSHAKE);
987 } else {
988 LOG(ERROR) << "handshake failed; returned " << rv
989 << ", SSL error code " << ssl_error
990 << ", net_error " << net_error;
991 net_log_.AddEvent(
992 NetLog::TYPE_SSL_HANDSHAKE_ERROR,
davidbena4409c62014-08-27 17:05:51993 CreateNetLogOpenSSLErrorCallback(net_error, ssl_error, error_info));
[email protected]b9b651f2013-11-09 04:32:22994 }
995 }
996 return net_error;
997}
998
[email protected]faff9852014-06-21 06:13:46999int SSLClientSocketOpenSSL::DoChannelIDLookup() {
rch98cf4472015-02-13 00:14:141000 net_log_.AddEvent(NetLog::TYPE_SSL_CHANNEL_ID_REQUESTED);
[email protected]faff9852014-06-21 06:13:461001 GotoState(STATE_CHANNEL_ID_LOOKUP_COMPLETE);
[email protected]6b8a3c742014-07-25 00:25:351002 return channel_id_service_->GetOrCreateChannelID(
[email protected]faff9852014-06-21 06:13:461003 host_and_port_.host(),
1004 &channel_id_private_key_,
1005 &channel_id_cert_,
1006 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete,
1007 base::Unretained(this)),
1008 &channel_id_request_handle_);
1009}
1010
1011int SSLClientSocketOpenSSL::DoChannelIDLookupComplete(int result) {
1012 if (result < 0)
1013 return result;
1014
1015 DCHECK_LT(0u, channel_id_private_key_.size());
1016 // Decode key.
1017 std::vector<uint8> encrypted_private_key_info;
1018 std::vector<uint8> subject_public_key_info;
1019 encrypted_private_key_info.assign(
1020 channel_id_private_key_.data(),
1021 channel_id_private_key_.data() + channel_id_private_key_.size());
1022 subject_public_key_info.assign(
1023 channel_id_cert_.data(),
1024 channel_id_cert_.data() + channel_id_cert_.size());
1025 scoped_ptr<crypto::ECPrivateKey> ec_private_key(
1026 crypto::ECPrivateKey::CreateFromEncryptedPrivateKeyInfo(
[email protected]6b8a3c742014-07-25 00:25:351027 ChannelIDService::kEPKIPassword,
[email protected]faff9852014-06-21 06:13:461028 encrypted_private_key_info,
1029 subject_public_key_info));
1030 if (!ec_private_key) {
1031 LOG(ERROR) << "Failed to import Channel ID.";
1032 return ERR_CHANNEL_ID_IMPORT_FAILED;
1033 }
1034
1035 // Hand the key to OpenSSL. Check for error in case OpenSSL rejects the key
1036 // type.
1037 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1038 int rv = SSL_set1_tls_channel_id(ssl_, ec_private_key->key());
1039 if (!rv) {
1040 LOG(ERROR) << "Failed to set Channel ID.";
1041 int err = SSL_get_error(ssl_, rv);
1042 return MapOpenSSLError(err, err_tracer);
1043 }
1044
1045 // Return to the handshake.
1046 set_channel_id_sent(true);
rch98cf4472015-02-13 00:14:141047 net_log_.AddEvent(NetLog::TYPE_SSL_CHANNEL_ID_PROVIDED);
[email protected]faff9852014-06-21 06:13:461048 GotoState(STATE_HANDSHAKE);
1049 return OK;
1050}
1051
[email protected]b9b651f2013-11-09 04:32:221052int SSLClientSocketOpenSSL::DoVerifyCert(int result) {
davidben30798ed82014-09-19 19:28:201053 DCHECK(!server_cert_chain_->empty());
davidben09c3d072014-08-25 20:33:581054 DCHECK(start_cert_verification_time_.is_null());
davidben30798ed82014-09-19 19:28:201055
[email protected]b9b651f2013-11-09 04:32:221056 GotoState(STATE_VERIFY_CERT_COMPLETE);
1057
davidben30798ed82014-09-19 19:28:201058 // If the certificate is bad and has been previously accepted, use
1059 // the previous status and bypass the error.
1060 base::StringPiece der_cert;
1061 if (!x509_util::GetDER(server_cert_chain_->Get(0), &der_cert)) {
1062 NOTREACHED();
1063 return ERR_CERT_INVALID;
1064 }
[email protected]b9b651f2013-11-09 04:32:221065 CertStatus cert_status;
davidben30798ed82014-09-19 19:28:201066 if (ssl_config_.IsAllowedBadCert(der_cert, &cert_status)) {
[email protected]b9b651f2013-11-09 04:32:221067 VLOG(1) << "Received an expected bad cert with status: " << cert_status;
1068 server_cert_verify_result_.Reset();
1069 server_cert_verify_result_.cert_status = cert_status;
1070 server_cert_verify_result_.verified_cert = server_cert_;
1071 return OK;
1072 }
1073
davidben30798ed82014-09-19 19:28:201074 // When running in a sandbox, it may not be possible to create an
1075 // X509Certificate*, as that may depend on OS functionality blocked
1076 // in the sandbox.
1077 if (!server_cert_.get()) {
1078 server_cert_verify_result_.Reset();
1079 server_cert_verify_result_.cert_status = CERT_STATUS_INVALID;
1080 return ERR_CERT_INVALID;
1081 }
1082
davidben09c3d072014-08-25 20:33:581083 start_cert_verification_time_ = base::TimeTicks::Now();
1084
[email protected]b9b651f2013-11-09 04:32:221085 int flags = 0;
1086 if (ssl_config_.rev_checking_enabled)
1087 flags |= CertVerifier::VERIFY_REV_CHECKING_ENABLED;
1088 if (ssl_config_.verify_ev_cert)
1089 flags |= CertVerifier::VERIFY_EV_CERT;
1090 if (ssl_config_.cert_io_enabled)
1091 flags |= CertVerifier::VERIFY_CERT_IO_ENABLED;
1092 if (ssl_config_.rev_checking_required_local_anchors)
1093 flags |= CertVerifier::VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS;
1094 verifier_.reset(new SingleRequestCertVerifier(cert_verifier_));
1095 return verifier_->Verify(
1096 server_cert_.get(),
1097 host_and_port_.host(),
1098 flags,
[email protected]591cffcd2014-08-18 20:02:301099 // TODO(davidben): Route the CRLSet through SSLConfig so
1100 // SSLClientSocket doesn't depend on SSLConfigService.
1101 SSLConfigService::GetCRLSet().get(),
[email protected]b9b651f2013-11-09 04:32:221102 &server_cert_verify_result_,
1103 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete,
1104 base::Unretained(this)),
1105 net_log_);
1106}
1107
1108int SSLClientSocketOpenSSL::DoVerifyCertComplete(int result) {
1109 verifier_.reset();
1110
davidben09c3d072014-08-25 20:33:581111 if (!start_cert_verification_time_.is_null()) {
1112 base::TimeDelta verify_time =
1113 base::TimeTicks::Now() - start_cert_verification_time_;
1114 if (result == OK) {
1115 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTime", verify_time);
1116 } else {
1117 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTimeError", verify_time);
1118 }
1119 }
1120
davidben85574eb2014-12-12 03:01:571121 if (result == OK) {
davidben85574eb2014-12-12 03:01:571122 if (SSL_session_reused(ssl_)) {
1123 // Record whether or not the server tried to resume a session for a
1124 // different version. See https://crbug.com/441456.
1125 UMA_HISTOGRAM_BOOLEAN(
1126 "Net.SSLSessionVersionMatch",
1127 SSL_version(ssl_) == SSL_get_session(ssl_)->ssl_version);
1128 }
1129 }
1130
[email protected]8bd4e7a2014-08-09 14:49:171131 const CertStatus cert_status = server_cert_verify_result_.cert_status;
1132 if (transport_security_state_ &&
1133 (result == OK ||
1134 (IsCertificateError(result) && IsCertStatusMinorError(cert_status))) &&
1135 !transport_security_state_->CheckPublicKeyPins(
1136 host_and_port_.host(),
[email protected]8bd4e7a2014-08-09 14:49:171137 server_cert_verify_result_.is_issued_by_known_root,
1138 server_cert_verify_result_.public_key_hashes,
1139 &pinning_failure_log_)) {
1140 result = ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN;
1141 }
1142
[email protected]b9b651f2013-11-09 04:32:221143 if (result == OK) {
davidbeneb5f8ef32014-09-04 14:14:321144 // Only check Certificate Transparency if there were no other errors with
1145 // the connection.
1146 VerifyCT();
1147
davidbendafe4e52015-04-08 22:53:521148 DCHECK(!certificate_verified_);
1149 certificate_verified_ = true;
1150 MaybeCacheSession();
[email protected]b9b651f2013-11-09 04:32:221151 } else {
1152 DVLOG(1) << "DoVerifyCertComplete error " << ErrorToString(result)
1153 << " (" << result << ")";
1154 }
1155
[email protected]64b5c892014-08-08 09:39:261156 completed_connect_ = true;
[email protected]b9b651f2013-11-09 04:32:221157 // Exit DoHandshakeLoop and return the result to the caller to Connect.
1158 DCHECK_EQ(STATE_NONE, next_handshake_state_);
1159 return result;
1160}
1161
1162void SSLClientSocketOpenSSL::DoConnectCallback(int rv) {
1163 if (!user_connect_callback_.is_null()) {
1164 CompletionCallback c = user_connect_callback_;
1165 user_connect_callback_.Reset();
1166 c.Run(rv > OK ? OK : rv);
1167 }
1168}
1169
davidben30798ed82014-09-19 19:28:201170void SSLClientSocketOpenSSL::UpdateServerCert() {
[email protected]76e85392014-03-20 17:54:141171 server_cert_chain_->Reset(SSL_get_peer_cert_chain(ssl_));
[email protected]7f38da8a2014-03-17 16:44:261172 server_cert_ = server_cert_chain_->AsOSChain();
davidben30798ed82014-09-19 19:28:201173 if (server_cert_.get()) {
1174 net_log_.AddEvent(
1175 NetLog::TYPE_SSL_CERTIFICATES_RECEIVED,
1176 base::Bind(&NetLogX509CertificateCallback,
1177 base::Unretained(server_cert_.get())));
davidbend1fb2f12014-11-08 02:51:001178
1179 // TODO(rsleevi): Plumb an OCSP response into the Mac system library and
1180 // update IsOCSPStaplingSupported for Mac. https://crbug.com/430714
1181 if (IsOCSPStaplingSupported()) {
1182#if defined(OS_WIN)
davidben54015aa2014-12-02 22:16:231183 const uint8_t* ocsp_response_raw;
davidbend1fb2f12014-11-08 02:51:001184 size_t ocsp_response_len;
1185 SSL_get0_ocsp_response(ssl_, &ocsp_response_raw, &ocsp_response_len);
1186
1187 CRYPT_DATA_BLOB ocsp_response_blob;
1188 ocsp_response_blob.cbData = ocsp_response_len;
davidben54015aa2014-12-02 22:16:231189 ocsp_response_blob.pbData = const_cast<BYTE*>(ocsp_response_raw);
davidbend1fb2f12014-11-08 02:51:001190 BOOL ok = CertSetCertificateContextProperty(
1191 server_cert_->os_cert_handle(),
1192 CERT_OCSP_RESPONSE_PROP_ID,
1193 CERT_SET_PROPERTY_IGNORE_PERSIST_ERROR_FLAG,
1194 &ocsp_response_blob);
1195 if (!ok) {
1196 VLOG(1) << "Failed to set OCSP response property: "
1197 << GetLastError();
1198 }
1199#else
davidben2bcbc6b2015-04-22 02:36:411200 // TODO(davidben): Support OCSP stapling when NSS is the system
1201 // certificate verifier. https://crbug.com/479034.
davidbend1fb2f12014-11-08 02:51:001202 NOTREACHED();
1203#endif
1204 }
davidben30798ed82014-09-19 19:28:201205 }
[email protected]b9b651f2013-11-09 04:32:221206}
1207
davidbeneb5f8ef32014-09-04 14:14:321208void SSLClientSocketOpenSSL::VerifyCT() {
1209 if (!cert_transparency_verifier_)
1210 return;
1211
davidben54015aa2014-12-02 22:16:231212 const uint8_t* ocsp_response_raw;
davidbeneb5f8ef32014-09-04 14:14:321213 size_t ocsp_response_len;
1214 SSL_get0_ocsp_response(ssl_, &ocsp_response_raw, &ocsp_response_len);
1215 std::string ocsp_response;
1216 if (ocsp_response_len > 0) {
1217 ocsp_response.assign(reinterpret_cast<const char*>(ocsp_response_raw),
1218 ocsp_response_len);
1219 }
1220
davidben54015aa2014-12-02 22:16:231221 const uint8_t* sct_list_raw;
davidbeneb5f8ef32014-09-04 14:14:321222 size_t sct_list_len;
1223 SSL_get0_signed_cert_timestamp_list(ssl_, &sct_list_raw, &sct_list_len);
1224 std::string sct_list;
1225 if (sct_list_len > 0)
1226 sct_list.assign(reinterpret_cast<const char*>(sct_list_raw), sct_list_len);
1227
1228 // Note that this is a completely synchronous operation: The CT Log Verifier
1229 // gets all the data it needs for SCT verification and does not do any
1230 // external communication.
eranm6571b2b2014-12-03 15:53:231231 cert_transparency_verifier_->Verify(
1232 server_cert_verify_result_.verified_cert.get(), ocsp_response, sct_list,
1233 &ct_verify_result_, net_log_);
davidbeneb5f8ef32014-09-04 14:14:321234
eranm6571b2b2014-12-03 15:53:231235 if (!policy_enforcer_) {
1236 server_cert_verify_result_.cert_status &= ~CERT_STATUS_IS_EV;
1237 } else {
1238 if (server_cert_verify_result_.cert_status & CERT_STATUS_IS_EV) {
1239 scoped_refptr<ct::EVCertsWhitelist> ev_whitelist =
1240 SSLConfigService::GetEVCertsWhitelist();
1241 if (!policy_enforcer_->DoesConformToCTEVPolicy(
1242 server_cert_verify_result_.verified_cert.get(),
eranm18a019272014-12-18 08:43:231243 ev_whitelist.get(), ct_verify_result_, net_log_)) {
eranm6571b2b2014-12-03 15:53:231244 // TODO(eranm): Log via the BoundNetLog, see crbug.com/437766
1245 VLOG(1) << "EV certificate for "
1246 << server_cert_verify_result_.verified_cert->subject()
1247 .GetDisplayName()
1248 << " does not conform to CT policy, removing EV status.";
1249 server_cert_verify_result_.cert_status &= ~CERT_STATUS_IS_EV;
1250 }
1251 }
1252 }
davidbeneb5f8ef32014-09-04 14:14:321253}
1254
[email protected]b9b651f2013-11-09 04:32:221255void SSLClientSocketOpenSSL::OnHandshakeIOComplete(int result) {
1256 int rv = DoHandshakeLoop(result);
1257 if (rv != ERR_IO_PENDING) {
1258 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
1259 DoConnectCallback(rv);
1260 }
1261}
1262
1263void SSLClientSocketOpenSSL::OnSendComplete(int result) {
1264 if (next_handshake_state_ == STATE_HANDSHAKE) {
1265 // In handshake phase.
1266 OnHandshakeIOComplete(result);
1267 return;
1268 }
1269
1270 // OnSendComplete may need to call DoPayloadRead while the renegotiation
1271 // handshake is in progress.
1272 int rv_read = ERR_IO_PENDING;
1273 int rv_write = ERR_IO_PENDING;
1274 bool network_moved;
1275 do {
1276 if (user_read_buf_.get())
1277 rv_read = DoPayloadRead();
1278 if (user_write_buf_.get())
1279 rv_write = DoPayloadWrite();
1280 network_moved = DoTransportIO();
1281 } while (rv_read == ERR_IO_PENDING && rv_write == ERR_IO_PENDING &&
1282 (user_read_buf_.get() || user_write_buf_.get()) && network_moved);
1283
1284 // Performing the Read callback may cause |this| to be deleted. If this
1285 // happens, the Write callback should not be invoked. Guard against this by
1286 // holding a WeakPtr to |this| and ensuring it's still valid.
1287 base::WeakPtr<SSLClientSocketOpenSSL> guard(weak_factory_.GetWeakPtr());
1288 if (user_read_buf_.get() && rv_read != ERR_IO_PENDING)
1289 DoReadCallback(rv_read);
1290
1291 if (!guard.get())
1292 return;
1293
1294 if (user_write_buf_.get() && rv_write != ERR_IO_PENDING)
1295 DoWriteCallback(rv_write);
1296}
1297
1298void SSLClientSocketOpenSSL::OnRecvComplete(int result) {
1299 if (next_handshake_state_ == STATE_HANDSHAKE) {
1300 // In handshake phase.
1301 OnHandshakeIOComplete(result);
1302 return;
1303 }
1304
1305 // Network layer received some data, check if client requested to read
1306 // decrypted data.
1307 if (!user_read_buf_.get())
1308 return;
1309
davidben1b133ad2014-10-23 04:23:131310 int rv = DoReadLoop();
[email protected]b9b651f2013-11-09 04:32:221311 if (rv != ERR_IO_PENDING)
1312 DoReadCallback(rv);
1313}
1314
1315int SSLClientSocketOpenSSL::DoHandshakeLoop(int last_io_result) {
1316 int rv = last_io_result;
1317 do {
1318 // Default to STATE_NONE for next state.
1319 // (This is a quirk carried over from the windows
1320 // implementation. It makes reading the logs a bit harder.)
1321 // State handlers can and often do call GotoState just
1322 // to stay in the current state.
1323 State state = next_handshake_state_;
1324 GotoState(STATE_NONE);
1325 switch (state) {
1326 case STATE_HANDSHAKE:
1327 rv = DoHandshake();
1328 break;
[email protected]faff9852014-06-21 06:13:461329 case STATE_CHANNEL_ID_LOOKUP:
1330 DCHECK_EQ(OK, rv);
1331 rv = DoChannelIDLookup();
1332 break;
1333 case STATE_CHANNEL_ID_LOOKUP_COMPLETE:
1334 rv = DoChannelIDLookupComplete(rv);
1335 break;
[email protected]b9b651f2013-11-09 04:32:221336 case STATE_VERIFY_CERT:
[email protected]faff9852014-06-21 06:13:461337 DCHECK_EQ(OK, rv);
[email protected]b9b651f2013-11-09 04:32:221338 rv = DoVerifyCert(rv);
1339 break;
1340 case STATE_VERIFY_CERT_COMPLETE:
1341 rv = DoVerifyCertComplete(rv);
1342 break;
1343 case STATE_NONE:
1344 default:
1345 rv = ERR_UNEXPECTED;
1346 NOTREACHED() << "unexpected state" << state;
1347 break;
1348 }
1349
1350 bool network_moved = DoTransportIO();
1351 if (network_moved && next_handshake_state_ == STATE_HANDSHAKE) {
1352 // In general we exit the loop if rv is ERR_IO_PENDING. In this
1353 // special case we keep looping even if rv is ERR_IO_PENDING because
1354 // the transport IO may allow DoHandshake to make progress.
1355 rv = OK; // This causes us to stay in the loop.
1356 }
1357 } while (rv != ERR_IO_PENDING && next_handshake_state_ != STATE_NONE);
1358 return rv;
1359}
1360
davidben1b133ad2014-10-23 04:23:131361int SSLClientSocketOpenSSL::DoReadLoop() {
[email protected]b9b651f2013-11-09 04:32:221362 bool network_moved;
1363 int rv;
1364 do {
1365 rv = DoPayloadRead();
1366 network_moved = DoTransportIO();
1367 } while (rv == ERR_IO_PENDING && network_moved);
1368
1369 return rv;
1370}
1371
davidben1b133ad2014-10-23 04:23:131372int SSLClientSocketOpenSSL::DoWriteLoop() {
[email protected]b9b651f2013-11-09 04:32:221373 bool network_moved;
1374 int rv;
1375 do {
1376 rv = DoPayloadWrite();
1377 network_moved = DoTransportIO();
1378 } while (rv == ERR_IO_PENDING && network_moved);
1379
1380 return rv;
1381}
1382
1383int SSLClientSocketOpenSSL::DoPayloadRead() {
1384 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1385
davidben7e555daf2015-03-25 17:03:291386 DCHECK_LT(0, user_read_buf_len_);
1387 DCHECK(user_read_buf_.get());
1388
[email protected]b9b651f2013-11-09 04:32:221389 int rv;
1390 if (pending_read_error_ != kNoPendingReadResult) {
1391 rv = pending_read_error_;
1392 pending_read_error_ = kNoPendingReadResult;
1393 if (rv == 0) {
1394 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED,
1395 rv, user_read_buf_->data());
davidbenb8c23212014-10-28 00:12:161396 } else {
1397 net_log_.AddEvent(
1398 NetLog::TYPE_SSL_READ_ERROR,
1399 CreateNetLogOpenSSLErrorCallback(rv, pending_read_ssl_error_,
1400 pending_read_error_info_));
[email protected]b9b651f2013-11-09 04:32:221401 }
davidbenb8c23212014-10-28 00:12:161402 pending_read_ssl_error_ = SSL_ERROR_NONE;
1403 pending_read_error_info_ = OpenSSLErrorInfo();
[email protected]b9b651f2013-11-09 04:32:221404 return rv;
1405 }
1406
1407 int total_bytes_read = 0;
davidben7e555daf2015-03-25 17:03:291408 int ssl_ret;
[email protected]b9b651f2013-11-09 04:32:221409 do {
davidben7e555daf2015-03-25 17:03:291410 ssl_ret = SSL_read(ssl_, user_read_buf_->data() + total_bytes_read,
1411 user_read_buf_len_ - total_bytes_read);
1412 if (ssl_ret > 0)
1413 total_bytes_read += ssl_ret;
1414 } while (total_bytes_read < user_read_buf_len_ && ssl_ret > 0);
[email protected]b9b651f2013-11-09 04:32:221415
davidben7e555daf2015-03-25 17:03:291416 // Although only the final SSL_read call may have failed, the failure needs to
1417 // processed immediately, while the information still available in OpenSSL's
1418 // error queue.
1419 if (client_auth_cert_needed_) {
1420 pending_read_error_ = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
1421 } else if (ssl_ret <= 0) {
1422 // A zero return from SSL_read may mean any of:
1423 // - The underlying BIO_read returned 0.
1424 // - The peer sent a close_notify.
1425 // - Any arbitrary error. https://crbug.com/466303
[email protected]b9b651f2013-11-09 04:32:221426 //
davidben7e555daf2015-03-25 17:03:291427 // TransportReadComplete converts the first to an ERR_CONNECTION_CLOSED
1428 // error, so it does not occur. The second and third are distinguished by
1429 // SSL_ERROR_ZERO_RETURN.
1430 pending_read_ssl_error_ = SSL_get_error(ssl_, ssl_ret);
1431 if (pending_read_ssl_error_ == SSL_ERROR_ZERO_RETURN) {
1432 pending_read_error_ = 0;
1433 } else {
1434 pending_read_error_ = MapOpenSSLErrorWithDetails(
1435 pending_read_ssl_error_, err_tracer, &pending_read_error_info_);
[email protected]b9b651f2013-11-09 04:32:221436 }
1437
davidben7e555daf2015-03-25 17:03:291438 // Many servers do not reliably send a close_notify alert when shutting down
1439 // a connection, and instead terminate the TCP connection. This is reported
1440 // as ERR_CONNECTION_CLOSED. Because of this, map the unclean shutdown to a
1441 // graceful EOF, instead of treating it as an error as it should be.
1442 if (pending_read_error_ == ERR_CONNECTION_CLOSED)
1443 pending_read_error_ = 0;
1444 }
davidbenbe6ce7ec2014-10-20 19:15:561445
davidben7e555daf2015-03-25 17:03:291446 if (total_bytes_read > 0) {
1447 // Return any bytes read to the caller. The error will be deferred to the
1448 // next call of DoPayloadRead.
1449 rv = total_bytes_read;
davidbenbe6ce7ec2014-10-20 19:15:561450
davidben7e555daf2015-03-25 17:03:291451 // Do not treat insufficient data as an error to return in the next call to
1452 // DoPayloadRead() - instead, let the call fall through to check SSL_read()
1453 // again. This is because DoTransportIO() may complete in between the next
1454 // call to DoPayloadRead(), and thus it is important to check SSL_read() on
1455 // subsequent invocations to see if a complete record may now be read.
1456 if (pending_read_error_ == ERR_IO_PENDING)
1457 pending_read_error_ = kNoPendingReadResult;
1458 } else {
1459 // No bytes were returned. Return the pending read error immediately.
1460 DCHECK_NE(kNoPendingReadResult, pending_read_error_);
1461 rv = pending_read_error_;
1462 pending_read_error_ = kNoPendingReadResult;
[email protected]b9b651f2013-11-09 04:32:221463 }
1464
1465 if (rv >= 0) {
1466 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, rv,
1467 user_read_buf_->data());
davidbenb8c23212014-10-28 00:12:161468 } else if (rv != ERR_IO_PENDING) {
1469 net_log_.AddEvent(
1470 NetLog::TYPE_SSL_READ_ERROR,
1471 CreateNetLogOpenSSLErrorCallback(rv, pending_read_ssl_error_,
1472 pending_read_error_info_));
1473 pending_read_ssl_error_ = SSL_ERROR_NONE;
1474 pending_read_error_info_ = OpenSSLErrorInfo();
[email protected]b9b651f2013-11-09 04:32:221475 }
1476 return rv;
1477}
1478
1479int SSLClientSocketOpenSSL::DoPayloadWrite() {
1480 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1481 int rv = SSL_write(ssl_, user_write_buf_->data(), user_write_buf_len_);
rsleevif020edc2015-03-16 19:31:241482
[email protected]b9b651f2013-11-09 04:32:221483 if (rv >= 0) {
1484 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_SENT, rv,
1485 user_write_buf_->data());
1486 return rv;
1487 }
1488
davidbenb8c23212014-10-28 00:12:161489 int ssl_error = SSL_get_error(ssl_, rv);
1490 OpenSSLErrorInfo error_info;
1491 int net_error = MapOpenSSLErrorWithDetails(ssl_error, err_tracer,
1492 &error_info);
1493
1494 if (net_error != ERR_IO_PENDING) {
1495 net_log_.AddEvent(
1496 NetLog::TYPE_SSL_WRITE_ERROR,
1497 CreateNetLogOpenSSLErrorCallback(net_error, ssl_error, error_info));
1498 }
1499 return net_error;
[email protected]b9b651f2013-11-09 04:32:221500}
1501
1502int SSLClientSocketOpenSSL::BufferSend(void) {
1503 if (transport_send_busy_)
1504 return ERR_IO_PENDING;
1505
haavardm2d92e722014-12-19 13:45:441506 size_t buffer_read_offset;
1507 uint8_t* read_buf;
1508 size_t max_read;
1509 int status = BIO_zero_copy_get_read_buf(transport_bio_, &read_buf,
1510 &buffer_read_offset, &max_read);
1511 DCHECK_EQ(status, 1); // Should never fail.
1512 if (!max_read)
1513 return 0; // Nothing pending in the OpenSSL write BIO.
1514 CHECK_EQ(read_buf, reinterpret_cast<uint8_t*>(send_buffer_->StartOfBuffer()));
1515 CHECK_LT(buffer_read_offset, static_cast<size_t>(send_buffer_->capacity()));
1516 send_buffer_->set_offset(buffer_read_offset);
[email protected]b9b651f2013-11-09 04:32:221517
1518 int rv = transport_->socket()->Write(
haavardm2d92e722014-12-19 13:45:441519 send_buffer_.get(), max_read,
[email protected]b9b651f2013-11-09 04:32:221520 base::Bind(&SSLClientSocketOpenSSL::BufferSendComplete,
1521 base::Unretained(this)));
1522 if (rv == ERR_IO_PENDING) {
1523 transport_send_busy_ = true;
1524 } else {
1525 TransportWriteComplete(rv);
1526 }
1527 return rv;
1528}
1529
1530int SSLClientSocketOpenSSL::BufferRecv(void) {
1531 if (transport_recv_busy_)
1532 return ERR_IO_PENDING;
1533
1534 // Determine how much was requested from |transport_bio_| that was not
1535 // actually available.
1536 size_t requested = BIO_ctrl_get_read_request(transport_bio_);
1537 if (requested == 0) {
1538 // This is not a perfect match of error codes, as no operation is
1539 // actually pending. However, returning 0 would be interpreted as
1540 // a possible sign of EOF, which is also an inappropriate match.
1541 return ERR_IO_PENDING;
1542 }
1543
1544 // Known Issue: While only reading |requested| data is the more correct
1545 // implementation, it has the downside of resulting in frequent reads:
1546 // One read for the SSL record header (~5 bytes) and one read for the SSL
1547 // record body. Rather than issuing these reads to the underlying socket
1548 // (and constantly allocating new IOBuffers), a single Read() request to
1549 // fill |transport_bio_| is issued. As long as an SSL client socket cannot
1550 // be gracefully shutdown (via SSL close alerts) and re-used for non-SSL
1551 // traffic, this over-subscribed Read()ing will not cause issues.
haavardm2d92e722014-12-19 13:45:441552
1553 size_t buffer_write_offset;
1554 uint8_t* write_buf;
1555 size_t max_write;
1556 int status = BIO_zero_copy_get_write_buf(transport_bio_, &write_buf,
1557 &buffer_write_offset, &max_write);
1558 DCHECK_EQ(status, 1); // Should never fail.
[email protected]b9b651f2013-11-09 04:32:221559 if (!max_write)
1560 return ERR_IO_PENDING;
1561
haavardm2d92e722014-12-19 13:45:441562 CHECK_EQ(write_buf,
1563 reinterpret_cast<uint8_t*>(recv_buffer_->StartOfBuffer()));
1564 CHECK_LT(buffer_write_offset, static_cast<size_t>(recv_buffer_->capacity()));
1565
1566 recv_buffer_->set_offset(buffer_write_offset);
[email protected]b9b651f2013-11-09 04:32:221567 int rv = transport_->socket()->Read(
1568 recv_buffer_.get(),
1569 max_write,
1570 base::Bind(&SSLClientSocketOpenSSL::BufferRecvComplete,
1571 base::Unretained(this)));
1572 if (rv == ERR_IO_PENDING) {
1573 transport_recv_busy_ = true;
1574 } else {
[email protected]3e5c6922014-02-06 02:42:161575 rv = TransportReadComplete(rv);
[email protected]b9b651f2013-11-09 04:32:221576 }
1577 return rv;
1578}
1579
1580void SSLClientSocketOpenSSL::BufferSendComplete(int result) {
[email protected]b9b651f2013-11-09 04:32:221581 TransportWriteComplete(result);
1582 OnSendComplete(result);
1583}
1584
1585void SSLClientSocketOpenSSL::BufferRecvComplete(int result) {
[email protected]3e5c6922014-02-06 02:42:161586 result = TransportReadComplete(result);
[email protected]b9b651f2013-11-09 04:32:221587 OnRecvComplete(result);
1588}
1589
1590void SSLClientSocketOpenSSL::TransportWriteComplete(int result) {
1591 DCHECK(ERR_IO_PENDING != result);
haavardm2d92e722014-12-19 13:45:441592 int bytes_written = 0;
[email protected]b9b651f2013-11-09 04:32:221593 if (result < 0) {
[email protected]5aea79182014-07-14 20:43:411594 // Record the error. Save it to be reported in a future read or write on
1595 // transport_bio_'s peer.
[email protected]3e5c6922014-02-06 02:42:161596 transport_write_error_ = result;
[email protected]b9b651f2013-11-09 04:32:221597 } else {
haavardm2d92e722014-12-19 13:45:441598 bytes_written = result;
[email protected]b9b651f2013-11-09 04:32:221599 }
haavardm2d92e722014-12-19 13:45:441600 DCHECK_GE(send_buffer_->RemainingCapacity(), bytes_written);
1601 int ret = BIO_zero_copy_get_read_buf_done(transport_bio_, bytes_written);
1602 DCHECK_EQ(1, ret);
1603 transport_send_busy_ = false;
[email protected]b9b651f2013-11-09 04:32:221604}
1605
[email protected]3e5c6922014-02-06 02:42:161606int SSLClientSocketOpenSSL::TransportReadComplete(int result) {
[email protected]b9b651f2013-11-09 04:32:221607 DCHECK(ERR_IO_PENDING != result);
[email protected]5aea79182014-07-14 20:43:411608 // If an EOF, canonicalize to ERR_CONNECTION_CLOSED here so MapOpenSSLError
1609 // does not report success.
1610 if (result == 0)
1611 result = ERR_CONNECTION_CLOSED;
haavardm2d92e722014-12-19 13:45:441612 int bytes_read = 0;
[email protected]5aea79182014-07-14 20:43:411613 if (result < 0) {
[email protected]b9b651f2013-11-09 04:32:221614 DVLOG(1) << "TransportReadComplete result " << result;
[email protected]5aea79182014-07-14 20:43:411615 // Received an error. Save it to be reported in a future read on
1616 // transport_bio_'s peer.
1617 transport_read_error_ = result;
[email protected]b9b651f2013-11-09 04:32:221618 } else {
haavardm2d92e722014-12-19 13:45:441619 bytes_read = result;
[email protected]b9b651f2013-11-09 04:32:221620 }
haavardm2d92e722014-12-19 13:45:441621 DCHECK_GE(recv_buffer_->RemainingCapacity(), bytes_read);
1622 int ret = BIO_zero_copy_get_write_buf_done(transport_bio_, bytes_read);
1623 DCHECK_EQ(1, ret);
[email protected]b9b651f2013-11-09 04:32:221624 transport_recv_busy_ = false;
[email protected]3e5c6922014-02-06 02:42:161625 return result;
[email protected]b9b651f2013-11-09 04:32:221626}
1627
[email protected]82c59022014-08-15 09:38:271628int SSLClientSocketOpenSSL::ClientCertRequestCallback(SSL* ssl) {
[email protected]5ac981e182010-12-06 17:56:271629 DVLOG(3) << "OpenSSL ClientCertRequestCallback called";
1630 DCHECK(ssl == ssl_);
[email protected]82c59022014-08-15 09:38:271631
davidbenaf42cbe2014-11-13 03:27:461632 net_log_.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED);
1633
[email protected]82c59022014-08-15 09:38:271634 // Clear any currently configured certificates.
1635 SSL_certs_clear(ssl_);
[email protected]97a854f2014-07-29 07:51:361636
1637#if defined(OS_IOS)
1638 // TODO(droger): Support client auth on iOS. See http://crbug.com/145954).
1639 LOG(WARNING) << "Client auth is not supported";
1640#else // !defined(OS_IOS)
[email protected]5ac981e182010-12-06 17:56:271641 if (!ssl_config_.send_client_cert) {
[email protected]515adc22013-01-09 16:01:231642 // First pass: we know that a client certificate is needed, but we do not
1643 // have one at hand.
[email protected]5ac981e182010-12-06 17:56:271644 client_auth_cert_needed_ = true;
[email protected]515adc22013-01-09 16:01:231645 STACK_OF(X509_NAME) *authorities = SSL_get_client_CA_list(ssl);
[email protected]edfd0f42014-07-22 18:20:371646 for (size_t i = 0; i < sk_X509_NAME_num(authorities); i++) {
[email protected]515adc22013-01-09 16:01:231647 X509_NAME *ca_name = (X509_NAME *)sk_X509_NAME_value(authorities, i);
1648 unsigned char* str = NULL;
1649 int length = i2d_X509_NAME(ca_name, &str);
1650 cert_authorities_.push_back(std::string(
1651 reinterpret_cast<const char*>(str),
1652 static_cast<size_t>(length)));
1653 OPENSSL_free(str);
1654 }
1655
[email protected]c0787702014-05-20 21:51:441656 const unsigned char* client_cert_types;
[email protected]e7e883e2014-07-25 06:03:081657 size_t num_client_cert_types =
1658 SSL_get0_certificate_types(ssl, &client_cert_types);
[email protected]c0787702014-05-20 21:51:441659 for (size_t i = 0; i < num_client_cert_types; i++) {
1660 cert_key_types_.push_back(
1661 static_cast<SSLClientCertType>(client_cert_types[i]));
1662 }
1663
[email protected]5ac981e182010-12-06 17:56:271664 return -1; // Suspends handshake.
1665 }
1666
1667 // Second pass: a client certificate should have been selected.
[email protected]13914c92013-06-13 22:42:421668 if (ssl_config_.client_cert.get()) {
[email protected]6bad5052014-07-12 01:25:131669 ScopedX509 leaf_x509 =
1670 OSCertHandleToOpenSSL(ssl_config_.client_cert->os_cert_handle());
1671 if (!leaf_x509) {
1672 LOG(WARNING) << "Failed to import certificate";
1673 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT);
1674 return -1;
1675 }
1676
[email protected]82c59022014-08-15 09:38:271677 ScopedX509Stack chain = OSCertHandlesToOpenSSL(
1678 ssl_config_.client_cert->GetIntermediateCertificates());
1679 if (!chain) {
1680 LOG(WARNING) << "Failed to import intermediate certificates";
1681 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT);
1682 return -1;
1683 }
1684
[email protected]97a854f2014-07-29 07:51:361685 // TODO(davidben): With Linux client auth support, this should be
1686 // conditioned on OS_ANDROID and then, with https://crbug.com/394131,
1687 // removed altogether. OpenSSLClientKeyStore is mostly an artifact of the
1688 // net/ client auth API lacking a private key handle.
[email protected]c0787702014-05-20 21:51:441689#if defined(USE_OPENSSL_CERTS)
[email protected]97a854f2014-07-29 07:51:361690 crypto::ScopedEVP_PKEY privkey =
1691 OpenSSLClientKeyStore::GetInstance()->FetchClientCertPrivateKey(
1692 ssl_config_.client_cert.get());
1693#else // !defined(USE_OPENSSL_CERTS)
1694 crypto::ScopedEVP_PKEY privkey =
1695 FetchClientCertPrivateKey(ssl_config_.client_cert.get());
1696#endif // defined(USE_OPENSSL_CERTS)
1697 if (!privkey) {
[email protected]6bad5052014-07-12 01:25:131698 // Could not find the private key. Fail the handshake and surface an
1699 // appropriate error to the caller.
1700 LOG(WARNING) << "Client cert found without private key";
1701 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY);
1702 return -1;
[email protected]0c6523f2010-12-10 10:56:241703 }
[email protected]6bad5052014-07-12 01:25:131704
[email protected]82c59022014-08-15 09:38:271705 if (!SSL_use_certificate(ssl_, leaf_x509.get()) ||
1706 !SSL_use_PrivateKey(ssl_, privkey.get()) ||
1707 !SSL_set1_chain(ssl_, chain.get())) {
1708 LOG(WARNING) << "Failed to set client certificate";
1709 return -1;
1710 }
davidbenaf42cbe2014-11-13 03:27:461711
1712 int cert_count = 1 + sk_X509_num(chain.get());
1713 net_log_.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED,
1714 NetLog::IntegerCallback("cert_count", cert_count));
[email protected]6bad5052014-07-12 01:25:131715 return 1;
[email protected]c0787702014-05-20 21:51:441716 }
[email protected]97a854f2014-07-29 07:51:361717#endif // defined(OS_IOS)
[email protected]5ac981e182010-12-06 17:56:271718
1719 // Send no client certificate.
davidbenaf42cbe2014-11-13 03:27:461720 net_log_.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED,
1721 NetLog::IntegerCallback("cert_count", 0));
[email protected]82c59022014-08-15 09:38:271722 return 1;
[email protected]5ac981e182010-12-06 17:56:271723}
1724
[email protected]b051cdb62014-02-28 02:20:161725int SSLClientSocketOpenSSL::CertVerifyCallback(X509_STORE_CTX* store_ctx) {
[email protected]64b5c892014-08-08 09:39:261726 if (!completed_connect_) {
[email protected]b051cdb62014-02-28 02:20:161727 // If the first handshake hasn't completed then we accept any certificates
1728 // because we verify after the handshake.
1729 return 1;
1730 }
1731
davidben30798ed82014-09-19 19:28:201732 // Disallow the server certificate to change in a renegotiation.
1733 if (server_cert_chain_->empty()) {
[email protected]76e85392014-03-20 17:54:141734 LOG(ERROR) << "Received invalid certificate chain between handshakes";
davidben30798ed82014-09-19 19:28:201735 return 0;
1736 }
1737 base::StringPiece old_der, new_der;
1738 if (store_ctx->cert == NULL ||
1739 !x509_util::GetDER(server_cert_chain_->Get(0), &old_der) ||
1740 !x509_util::GetDER(store_ctx->cert, &new_der)) {
1741 LOG(ERROR) << "Failed to encode certificates";
1742 return 0;
1743 }
1744 if (old_der != new_der) {
[email protected]76e85392014-03-20 17:54:141745 LOG(ERROR) << "Server certificate changed between handshakes";
davidben30798ed82014-09-19 19:28:201746 return 0;
1747 }
1748
1749 return 1;
[email protected]b051cdb62014-02-28 02:20:161750}
1751
[email protected]ae7c9f42011-11-21 11:41:161752// SelectNextProtoCallback is called by OpenSSL during the handshake. If the
1753// server supports NPN, selects a protocol from the list that the server
1754// provides. According to third_party/openssl/openssl/ssl/ssl_lib.c, the
1755// callback can assume that |in| is syntactically valid.
[email protected]ea4a1c6a2010-12-09 13:33:281756int SSLClientSocketOpenSSL::SelectNextProtoCallback(unsigned char** out,
1757 unsigned char* outlen,
1758 const unsigned char* in,
1759 unsigned int inlen) {
[email protected]ea4a1c6a2010-12-09 13:33:281760 if (ssl_config_.next_protos.empty()) {
[email protected]168a8412012-06-14 05:05:491761 *out = reinterpret_cast<uint8*>(
1762 const_cast<char*>(kDefaultSupportedNPNProtocol));
1763 *outlen = arraysize(kDefaultSupportedNPNProtocol) - 1;
1764 npn_status_ = kNextProtoUnsupported;
[email protected]ea4a1c6a2010-12-09 13:33:281765 return SSL_TLSEXT_ERR_OK;
1766 }
1767
[email protected]ae7c9f42011-11-21 11:41:161768 // Assume there's no overlap between our protocols and the server's list.
[email protected]168a8412012-06-14 05:05:491769 npn_status_ = kNextProtoNoOverlap;
[email protected]ae7c9f42011-11-21 11:41:161770
1771 // For each protocol in server preference order, see if we support it.
1772 for (unsigned int i = 0; i < inlen; i += in[i] + 1) {
bnc0d23cf42014-12-11 14:09:461773 for (NextProto next_proto : ssl_config_.next_protos) {
1774 const std::string proto = NextProtoToString(next_proto);
1775 if (in[i] == proto.size() &&
1776 memcmp(&in[i + 1], proto.data(), in[i]) == 0) {
[email protected]168a8412012-06-14 05:05:491777 // We found a match.
[email protected]ae7c9f42011-11-21 11:41:161778 *out = const_cast<unsigned char*>(in) + i + 1;
1779 *outlen = in[i];
[email protected]168a8412012-06-14 05:05:491780 npn_status_ = kNextProtoNegotiated;
[email protected]ae7c9f42011-11-21 11:41:161781 break;
1782 }
1783 }
[email protected]168a8412012-06-14 05:05:491784 if (npn_status_ == kNextProtoNegotiated)
[email protected]ae7c9f42011-11-21 11:41:161785 break;
1786 }
[email protected]ea4a1c6a2010-12-09 13:33:281787
[email protected]168a8412012-06-14 05:05:491788 // If we didn't find a protocol, we select the first one from our list.
1789 if (npn_status_ == kNextProtoNoOverlap) {
bnc67da3de2015-01-15 21:02:261790 // NextProtoToString returns a pointer to a static string.
1791 const char* proto = NextProtoToString(ssl_config_.next_protos[0]);
1792 *out = reinterpret_cast<unsigned char*>(const_cast<char*>(proto));
1793 *outlen = strlen(proto);
[email protected]168a8412012-06-14 05:05:491794 }
1795
[email protected]ea4a1c6a2010-12-09 13:33:281796 npn_proto_.assign(reinterpret_cast<const char*>(*out), *outlen);
[email protected]32e1dee2010-12-09 18:36:241797 DVLOG(2) << "next protocol: '" << npn_proto_ << "' status: " << npn_status_;
bnc0d28ea52014-10-13 15:15:381798 set_negotiation_extension(kExtensionNPN);
[email protected]ea4a1c6a2010-12-09 13:33:281799 return SSL_TLSEXT_ERR_OK;
1800}
1801
[email protected]5aea79182014-07-14 20:43:411802long SSLClientSocketOpenSSL::MaybeReplayTransportError(
1803 BIO *bio,
1804 int cmd,
1805 const char *argp, int argi, long argl,
1806 long retvalue) {
1807 if (cmd == (BIO_CB_READ|BIO_CB_RETURN) && retvalue <= 0) {
1808 // If there is no more data in the buffer, report any pending errors that
1809 // were observed. Note that both the readbuf and the writebuf are checked
1810 // for errors, since the application may have encountered a socket error
1811 // while writing that would otherwise not be reported until the application
1812 // attempted to write again - which it may never do. See
1813 // https://crbug.com/249848.
1814 if (transport_read_error_ != OK) {
1815 OpenSSLPutNetError(FROM_HERE, transport_read_error_);
1816 return -1;
1817 }
1818 if (transport_write_error_ != OK) {
1819 OpenSSLPutNetError(FROM_HERE, transport_write_error_);
1820 return -1;
1821 }
1822 } else if (cmd == BIO_CB_WRITE) {
1823 // Because of the write buffer, this reports a failure from the previous
1824 // write payload. If the current payload fails to write, the error will be
1825 // reported in a future write or read to |bio|.
1826 if (transport_write_error_ != OK) {
1827 OpenSSLPutNetError(FROM_HERE, transport_write_error_);
1828 return -1;
1829 }
1830 }
1831 return retvalue;
1832}
1833
1834// static
1835long SSLClientSocketOpenSSL::BIOCallback(
1836 BIO *bio,
1837 int cmd,
1838 const char *argp, int argi, long argl,
1839 long retvalue) {
1840 SSLClientSocketOpenSSL* socket = reinterpret_cast<SSLClientSocketOpenSSL*>(
1841 BIO_get_callback_arg(bio));
1842 CHECK(socket);
1843 return socket->MaybeReplayTransportError(
1844 bio, cmd, argp, argi, argl, retvalue);
1845}
1846
davidbendafe4e52015-04-08 22:53:521847void SSLClientSocketOpenSSL::MaybeCacheSession() {
1848 // Only cache the session once both the handshake has completed and the
1849 // certificate has been verified.
1850 if (!handshake_completed_ || !certificate_verified_ ||
1851 SSL_session_reused(ssl_)) {
1852 return;
1853 }
1854
1855 SSLContext::GetInstance()->session_cache()->Insert(GetSessionCacheKey(),
1856 SSL_get_session(ssl_));
1857}
1858
1859void SSLClientSocketOpenSSL::InfoCallback(int type, int val) {
1860 // Note that SSL_CB_HANDSHAKE_DONE may be signaled multiple times if the
1861 // socket renegotiates.
1862 if (type != SSL_CB_HANDSHAKE_DONE || handshake_completed_)
1863 return;
1864
1865 handshake_completed_ = true;
1866 MaybeCacheSession();
1867}
1868
davidbeneb5f8ef32014-09-04 14:14:321869void SSLClientSocketOpenSSL::AddSCTInfoToSSLInfo(SSLInfo* ssl_info) const {
1870 for (ct::SCTList::const_iterator iter =
1871 ct_verify_result_.verified_scts.begin();
1872 iter != ct_verify_result_.verified_scts.end(); ++iter) {
1873 ssl_info->signed_certificate_timestamps.push_back(
1874 SignedCertificateTimestampAndStatus(*iter, ct::SCT_STATUS_OK));
1875 }
1876 for (ct::SCTList::const_iterator iter =
1877 ct_verify_result_.invalid_scts.begin();
1878 iter != ct_verify_result_.invalid_scts.end(); ++iter) {
1879 ssl_info->signed_certificate_timestamps.push_back(
1880 SignedCertificateTimestampAndStatus(*iter, ct::SCT_STATUS_INVALID));
1881 }
1882 for (ct::SCTList::const_iterator iter =
1883 ct_verify_result_.unknown_logs_scts.begin();
1884 iter != ct_verify_result_.unknown_logs_scts.end(); ++iter) {
1885 ssl_info->signed_certificate_timestamps.push_back(
1886 SignedCertificateTimestampAndStatus(*iter,
1887 ct::SCT_STATUS_LOG_UNKNOWN));
1888 }
1889}
1890
rsleevif020edc2015-03-16 19:31:241891std::string SSLClientSocketOpenSSL::GetSessionCacheKey() const {
1892 std::string result = host_and_port_.ToString();
1893 result.append("/");
1894 result.append(ssl_session_cache_shard_);
1895
1896 // Shard the session cache based on maximum protocol version. This causes
1897 // fallback connections to use a separate session cache.
1898 result.append("/");
1899 switch (ssl_config_.version_max) {
1900 case SSL_PROTOCOL_VERSION_SSL3:
1901 result.append("ssl3");
1902 break;
1903 case SSL_PROTOCOL_VERSION_TLS1:
1904 result.append("tls1");
1905 break;
1906 case SSL_PROTOCOL_VERSION_TLS1_1:
1907 result.append("tls1.1");
1908 break;
1909 case SSL_PROTOCOL_VERSION_TLS1_2:
1910 result.append("tls1.2");
1911 break;
1912 default:
1913 NOTREACHED();
1914 }
1915
davidbena4c9d062015-04-03 22:34:251916 result.append("/");
1917 if (ssl_config_.enable_deprecated_cipher_suites)
1918 result.append("deprecated");
1919
rsleevif020edc2015-03-16 19:31:241920 return result;
1921}
1922
[email protected]7f38da8a2014-03-17 16:44:261923scoped_refptr<X509Certificate>
1924SSLClientSocketOpenSSL::GetUnverifiedServerCertificateChain() const {
1925 return server_cert_;
1926}
1927
[email protected]7e5dd49f2010-12-08 18:33:491928} // namespace net