blob: 391999fd99f65d6d7af4519a149abb5a799a9370 [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"
[email protected]1279de12013-12-03 15:13:3237#include "net/socket/ssl_session_cache_openssl.h"
[email protected]536fd0b2013-03-14 17:41:5738#include "net/ssl/ssl_cert_request_info.h"
39#include "net/ssl/ssl_connection_status_flags.h"
40#include "net/ssl/ssl_info.h"
[email protected]d518cd92010-09-29 12:27:4441
davidben8ecc3072014-09-03 23:19:0942#if defined(OS_WIN)
43#include "base/win/windows_version.h"
44#endif
45
[email protected]97a854f2014-07-29 07:51:3646#if defined(USE_OPENSSL_CERTS)
47#include "net/ssl/openssl_client_key_store.h"
48#else
49#include "net/ssl/openssl_platform_key.h"
50#endif
51
[email protected]d518cd92010-09-29 12:27:4452namespace net {
53
54namespace {
55
56// Enable this to see logging for state machine state transitions.
57#if 0
[email protected]3b112772010-10-04 10:54:4958#define GotoState(s) do { DVLOG(2) << (void *)this << " " << __FUNCTION__ << \
[email protected]d518cd92010-09-29 12:27:4459 " jump to state " << s; \
60 next_handshake_state_ = s; } while (0)
61#else
62#define GotoState(s) next_handshake_state_ = s
63#endif
64
[email protected]4b768562013-02-16 04:10:0765// This constant can be any non-negative/non-zero value (eg: it does not
66// overlap with any value of the net::Error range, including net::OK).
67const int kNoPendingReadResult = 1;
68
[email protected]168a8412012-06-14 05:05:4969// If a client doesn't have a list of protocols that it supports, but
70// the server supports NPN, choosing "http/1.1" is the best answer.
71const char kDefaultSupportedNPNProtocol[] = "http/1.1";
72
haavardm2d92e722014-12-19 13:45:4473// Default size of the internal BoringSSL buffers.
74const int KDefaultOpenSSLBufferSize = 17 * 1024;
75
[email protected]82c59022014-08-15 09:38:2776void FreeX509Stack(STACK_OF(X509)* ptr) {
77 sk_X509_pop_free(ptr, X509_free);
78}
79
[email protected]6bad5052014-07-12 01:25:1380typedef crypto::ScopedOpenSSL<X509, X509_free>::Type ScopedX509;
[email protected]82c59022014-08-15 09:38:2781typedef crypto::ScopedOpenSSL<STACK_OF(X509), FreeX509Stack>::Type
82 ScopedX509Stack;
[email protected]6bad5052014-07-12 01:25:1383
[email protected]89038152012-09-07 06:30:1784#if OPENSSL_VERSION_NUMBER < 0x1000103fL
85// This method doesn't seem to have made it into the OpenSSL headers.
[email protected]109805a2010-12-07 18:17:0686unsigned long SSL_CIPHER_get_id(const SSL_CIPHER* cipher) { return cipher->id; }
[email protected]89038152012-09-07 06:30:1787#endif
[email protected]109805a2010-12-07 18:17:0688
89// Used for encoding the |connection_status| field of an SSLInfo object.
pkasting6b68a162014-12-01 22:10:2990int EncodeSSLConnectionStatus(uint16 cipher_suite,
[email protected]109805a2010-12-07 18:17:0691 int compression,
92 int version) {
pkasting6b68a162014-12-01 22:10:2993 return cipher_suite |
[email protected]109805a2010-12-07 18:17:0694 ((compression & SSL_CONNECTION_COMPRESSION_MASK) <<
95 SSL_CONNECTION_COMPRESSION_SHIFT) |
96 ((version & SSL_CONNECTION_VERSION_MASK) <<
97 SSL_CONNECTION_VERSION_SHIFT);
98}
99
100// Returns the net SSL version number (see ssl_connection_status_flags.h) for
101// this SSL connection.
102int GetNetSSLVersion(SSL* ssl) {
[email protected]7e5dd49f2010-12-08 18:33:49103 switch (SSL_version(ssl)) {
[email protected]109805a2010-12-07 18:17:06104 case SSL2_VERSION:
105 return SSL_CONNECTION_VERSION_SSL2;
106 case SSL3_VERSION:
107 return SSL_CONNECTION_VERSION_SSL3;
108 case TLS1_VERSION:
109 return SSL_CONNECTION_VERSION_TLS1;
davidben1d094022014-11-05 18:55:47110 case TLS1_1_VERSION:
[email protected]109805a2010-12-07 18:17:06111 return SSL_CONNECTION_VERSION_TLS1_1;
davidben1d094022014-11-05 18:55:47112 case TLS1_2_VERSION:
[email protected]109805a2010-12-07 18:17:06113 return SSL_CONNECTION_VERSION_TLS1_2;
114 default:
115 return SSL_CONNECTION_VERSION_UNKNOWN;
116 }
117}
118
[email protected]6bad5052014-07-12 01:25:13119ScopedX509 OSCertHandleToOpenSSL(
120 X509Certificate::OSCertHandle os_handle) {
121#if defined(USE_OPENSSL_CERTS)
122 return ScopedX509(X509Certificate::DupOSCertHandle(os_handle));
123#else // !defined(USE_OPENSSL_CERTS)
124 std::string der_encoded;
125 if (!X509Certificate::GetDEREncoded(os_handle, &der_encoded))
126 return ScopedX509();
127 const uint8_t* bytes = reinterpret_cast<const uint8_t*>(der_encoded.data());
128 return ScopedX509(d2i_X509(NULL, &bytes, der_encoded.size()));
129#endif // defined(USE_OPENSSL_CERTS)
130}
131
[email protected]82c59022014-08-15 09:38:27132ScopedX509Stack OSCertHandlesToOpenSSL(
133 const X509Certificate::OSCertHandles& os_handles) {
134 ScopedX509Stack stack(sk_X509_new_null());
135 for (size_t i = 0; i < os_handles.size(); i++) {
136 ScopedX509 x509 = OSCertHandleToOpenSSL(os_handles[i]);
137 if (!x509)
138 return ScopedX509Stack();
139 sk_X509_push(stack.get(), x509.release());
140 }
141 return stack.Pass();
142}
143
davidben018aad62014-09-12 02:25:19144int LogErrorCallback(const char* str, size_t len, void* context) {
145 LOG(ERROR) << base::StringPiece(str, len);
146 return 1;
147}
148
davidbend1fb2f12014-11-08 02:51:00149bool IsOCSPStaplingSupported() {
150#if defined(OS_WIN)
151 // CERT_OCSP_RESPONSE_PROP_ID is only implemented on Vista+, but it can be
152 // set on Windows XP without error. There is some overhead from the server
153 // sending the OCSP response if it supports the extension, for the subset of
154 // XP clients who will request it but be unable to use it, but this is an
155 // acceptable trade-off for simplicity of implementation.
156 return true;
157#else
158 return false;
159#endif
160}
161
[email protected]821e3bb2013-11-08 01:06:01162} // namespace
163
164class SSLClientSocketOpenSSL::SSLContext {
[email protected]fbef13932010-11-23 12:38:53165 public:
[email protected]b29af7d2010-12-14 11:52:47166 static SSLContext* GetInstance() { return Singleton<SSLContext>::get(); }
[email protected]fbef13932010-11-23 12:38:53167 SSL_CTX* ssl_ctx() { return ssl_ctx_.get(); }
[email protected]1279de12013-12-03 15:13:32168 SSLSessionCacheOpenSSL* session_cache() { return &session_cache_; }
[email protected]fbef13932010-11-23 12:38:53169
[email protected]1279de12013-12-03 15:13:32170 SSLClientSocketOpenSSL* GetClientSocketFromSSL(const SSL* ssl) {
[email protected]fbef13932010-11-23 12:38:53171 DCHECK(ssl);
172 SSLClientSocketOpenSSL* socket = static_cast<SSLClientSocketOpenSSL*>(
173 SSL_get_ex_data(ssl, ssl_socket_data_index_));
174 DCHECK(socket);
175 return socket;
176 }
177
178 bool SetClientSocketForSSL(SSL* ssl, SSLClientSocketOpenSSL* socket) {
179 return SSL_set_ex_data(ssl, ssl_socket_data_index_, socket) != 0;
180 }
181
182 private:
183 friend struct DefaultSingletonTraits<SSLContext>;
184
185 SSLContext() {
[email protected]4b559b4d2011-04-14 17:37:14186 crypto::EnsureOpenSSLInit();
[email protected]fbef13932010-11-23 12:38:53187 ssl_socket_data_index_ = SSL_get_ex_new_index(0, 0, 0, 0, 0);
188 DCHECK_NE(ssl_socket_data_index_, -1);
189 ssl_ctx_.reset(SSL_CTX_new(SSLv23_client_method()));
[email protected]1279de12013-12-03 15:13:32190 session_cache_.Reset(ssl_ctx_.get(), kDefaultSessionCacheConfig);
[email protected]b051cdb62014-02-28 02:20:16191 SSL_CTX_set_cert_verify_callback(ssl_ctx_.get(), CertVerifyCallback, NULL);
[email protected]82c59022014-08-15 09:38:27192 SSL_CTX_set_cert_cb(ssl_ctx_.get(), ClientCertRequestCallback, NULL);
[email protected]b051cdb62014-02-28 02:20:16193 SSL_CTX_set_verify(ssl_ctx_.get(), SSL_VERIFY_PEER, NULL);
haavardmc80b0ee32015-01-30 09:16:08194 // This stops |SSL_shutdown| from generating the close_notify message, which
195 // is currently not sent on the network.
196 // TODO(haavardm): Remove setting quiet shutdown once 118366 is fixed.
197 SSL_CTX_set_quiet_shutdown(ssl_ctx_.get(), 1);
[email protected]ea4a1c6a2010-12-09 13:33:28198 // TODO(kristianm): Only select this if ssl_config_.next_proto is not empty.
199 // It would be better if the callback were not a global setting,
200 // but that is an OpenSSL issue.
201 SSL_CTX_set_next_proto_select_cb(ssl_ctx_.get(), SelectNextProtoCallback,
202 NULL);
[email protected]edfd0f42014-07-22 18:20:37203 ssl_ctx_->tlsext_channel_id_enabled_new = 1;
davidben018aad62014-09-12 02:25:19204
205 scoped_ptr<base::Environment> env(base::Environment::Create());
206 std::string ssl_keylog_file;
207 if (env->GetVar("SSLKEYLOGFILE", &ssl_keylog_file) &&
208 !ssl_keylog_file.empty()) {
209 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
210 BIO* bio = BIO_new_file(ssl_keylog_file.c_str(), "a");
211 if (!bio) {
212 LOG(ERROR) << "Failed to open " << ssl_keylog_file;
213 ERR_print_errors_cb(&LogErrorCallback, NULL);
214 } else {
215 SSL_CTX_set_keylog_bio(ssl_ctx_.get(), bio);
216 }
217 }
[email protected]fbef13932010-11-23 12:38:53218 }
219
[email protected]1279de12013-12-03 15:13:32220 static std::string GetSessionCacheKey(const SSL* ssl) {
221 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
222 DCHECK(socket);
[email protected]8e458552014-08-05 00:02:15223 return socket->GetSessionCacheKey();
[email protected]fbef13932010-11-23 12:38:53224 }
225
[email protected]1279de12013-12-03 15:13:32226 static SSLSessionCacheOpenSSL::Config kDefaultSessionCacheConfig;
[email protected]fbef13932010-11-23 12:38:53227
[email protected]82c59022014-08-15 09:38:27228 static int ClientCertRequestCallback(SSL* ssl, void* arg) {
[email protected]b29af7d2010-12-14 11:52:47229 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
[email protected]82c59022014-08-15 09:38:27230 DCHECK(socket);
231 return socket->ClientCertRequestCallback(ssl);
[email protected]718c9672010-12-02 10:04:10232 }
233
[email protected]b051cdb62014-02-28 02:20:16234 static int CertVerifyCallback(X509_STORE_CTX *store_ctx, void *arg) {
235 SSL* ssl = reinterpret_cast<SSL*>(X509_STORE_CTX_get_ex_data(
236 store_ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
237 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
238 CHECK(socket);
239
240 return socket->CertVerifyCallback(store_ctx);
241 }
242
[email protected]ea4a1c6a2010-12-09 13:33:28243 static int SelectNextProtoCallback(SSL* ssl,
244 unsigned char** out, unsigned char* outlen,
245 const unsigned char* in,
246 unsigned int inlen, void* arg) {
[email protected]b29af7d2010-12-14 11:52:47247 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
[email protected]ea4a1c6a2010-12-09 13:33:28248 return socket->SelectNextProtoCallback(out, outlen, in, inlen);
249 }
250
[email protected]fbef13932010-11-23 12:38:53251 // This is the index used with SSL_get_ex_data to retrieve the owner
252 // SSLClientSocketOpenSSL object from an SSL instance.
253 int ssl_socket_data_index_;
254
[email protected]cd9b75b2014-07-10 04:39:38255 crypto::ScopedOpenSSL<SSL_CTX, SSL_CTX_free>::Type ssl_ctx_;
[email protected]1279de12013-12-03 15:13:32256 // |session_cache_| must be destroyed before |ssl_ctx_|.
257 SSLSessionCacheOpenSSL session_cache_;
258};
259
[email protected]7f38da8a2014-03-17 16:44:26260// PeerCertificateChain is a helper object which extracts the certificate
261// chain, as given by the server, from an OpenSSL socket and performs the needed
262// resource management. The first element of the chain is the leaf certificate
263// and the other elements are in the order given by the server.
264class SSLClientSocketOpenSSL::PeerCertificateChain {
265 public:
[email protected]76e85392014-03-20 17:54:14266 explicit PeerCertificateChain(STACK_OF(X509)* chain) { Reset(chain); }
[email protected]7f38da8a2014-03-17 16:44:26267 PeerCertificateChain(const PeerCertificateChain& other) { *this = other; }
268 ~PeerCertificateChain() {}
269 PeerCertificateChain& operator=(const PeerCertificateChain& other);
270
[email protected]76e85392014-03-20 17:54:14271 // Resets the PeerCertificateChain to the set of certificates in|chain|,
272 // which may be NULL, indicating to empty the store certificates.
273 // Note: If an error occurs, such as being unable to parse the certificates,
274 // this will behave as if Reset(NULL) was called.
275 void Reset(STACK_OF(X509)* chain);
276
[email protected]7f38da8a2014-03-17 16:44:26277 // Note that when USE_OPENSSL is defined, OSCertHandle is X509*
davidben30798ed82014-09-19 19:28:20278 scoped_refptr<X509Certificate> AsOSChain() const;
[email protected]7f38da8a2014-03-17 16:44:26279
280 size_t size() const {
281 if (!openssl_chain_.get())
282 return 0;
283 return sk_X509_num(openssl_chain_.get());
284 }
285
davidben30798ed82014-09-19 19:28:20286 bool empty() const {
287 return size() == 0;
288 }
289
290 X509* Get(size_t index) const {
[email protected]7f38da8a2014-03-17 16:44:26291 DCHECK_LT(index, size());
292 return sk_X509_value(openssl_chain_.get(), index);
293 }
294
295 private:
[email protected]cd9b75b2014-07-10 04:39:38296 ScopedX509Stack openssl_chain_;
[email protected]7f38da8a2014-03-17 16:44:26297};
298
299SSLClientSocketOpenSSL::PeerCertificateChain&
300SSLClientSocketOpenSSL::PeerCertificateChain::operator=(
301 const PeerCertificateChain& other) {
302 if (this == &other)
303 return *this;
304
[email protected]24176af2014-08-14 09:31:04305 openssl_chain_.reset(X509_chain_up_ref(other.openssl_chain_.get()));
[email protected]7f38da8a2014-03-17 16:44:26306 return *this;
307}
308
[email protected]76e85392014-03-20 17:54:14309void SSLClientSocketOpenSSL::PeerCertificateChain::Reset(
310 STACK_OF(X509)* chain) {
davidben30798ed82014-09-19 19:28:20311 openssl_chain_.reset(chain ? X509_chain_up_ref(chain) : NULL);
[email protected]7f38da8a2014-03-17 16:44:26312}
[email protected]7f38da8a2014-03-17 16:44:26313
davidben30798ed82014-09-19 19:28:20314scoped_refptr<X509Certificate>
315SSLClientSocketOpenSSL::PeerCertificateChain::AsOSChain() const {
316#if defined(USE_OPENSSL_CERTS)
317 // When OSCertHandle is typedef'ed to X509, this implementation does a short
318 // cut to avoid converting back and forth between DER and the X509 struct.
319 X509Certificate::OSCertHandles intermediates;
320 for (size_t i = 1; i < sk_X509_num(openssl_chain_.get()); ++i) {
321 intermediates.push_back(sk_X509_value(openssl_chain_.get(), i));
322 }
[email protected]7f38da8a2014-03-17 16:44:26323
davidben30798ed82014-09-19 19:28:20324 return make_scoped_refptr(X509Certificate::CreateFromHandle(
325 sk_X509_value(openssl_chain_.get(), 0), intermediates));
326#else
327 // DER-encode the chain and convert to a platform certificate handle.
[email protected]7f38da8a2014-03-17 16:44:26328 std::vector<base::StringPiece> der_chain;
[email protected]edfd0f42014-07-22 18:20:37329 for (size_t i = 0; i < sk_X509_num(openssl_chain_.get()); ++i) {
[email protected]7f38da8a2014-03-17 16:44:26330 X509* x = sk_X509_value(openssl_chain_.get(), i);
davidben30798ed82014-09-19 19:28:20331 base::StringPiece der;
332 if (!x509_util::GetDER(x, &der))
333 return NULL;
334 der_chain.push_back(der);
[email protected]7f38da8a2014-03-17 16:44:26335 }
336
davidben30798ed82014-09-19 19:28:20337 return make_scoped_refptr(X509Certificate::CreateFromDERCertChain(der_chain));
338#endif
[email protected]7f38da8a2014-03-17 16:44:26339}
[email protected]7f38da8a2014-03-17 16:44:26340
[email protected]1279de12013-12-03 15:13:32341// static
342SSLSessionCacheOpenSSL::Config
343 SSLClientSocketOpenSSL::SSLContext::kDefaultSessionCacheConfig = {
344 &GetSessionCacheKey, // key_func
345 1024, // max_entries
346 256, // expiration_check_count
347 60 * 60, // timeout_seconds
[email protected]fbef13932010-11-23 12:38:53348};
[email protected]313834722010-11-17 09:57:18349
[email protected]c3456bb2011-12-12 22:22:19350// static
351void SSLClientSocket::ClearSessionCache() {
[email protected]821e3bb2013-11-08 01:06:01352 SSLClientSocketOpenSSL::SSLContext* context =
353 SSLClientSocketOpenSSL::SSLContext::GetInstance();
[email protected]c3456bb2011-12-12 22:22:19354 context->session_cache()->Flush();
355}
356
bnc86b734dd2014-12-03 00:33:10357// static
358uint16 SSLClientSocket::GetMaxSupportedSSLVersion() {
359 return SSL_PROTOCOL_VERSION_TLS1_2;
360}
361
[email protected]d518cd92010-09-29 12:27:44362SSLClientSocketOpenSSL::SSLClientSocketOpenSSL(
[email protected]18ccfdb2013-08-15 00:13:44363 scoped_ptr<ClientSocketHandle> transport_socket,
[email protected]055d7f22010-11-15 12:03:12364 const HostPortPair& host_and_port,
[email protected]822581d2010-12-16 17:27:15365 const SSLConfig& ssl_config,
[email protected]feb79bcd2011-07-21 16:55:17366 const SSLClientSocketContext& context)
[email protected]83039bb2011-12-09 18:43:55367 : transport_send_busy_(false),
[email protected]d518cd92010-09-29 12:27:44368 transport_recv_busy_(false),
[email protected]4b768562013-02-16 04:10:07369 pending_read_error_(kNoPendingReadResult),
davidbenb8c23212014-10-28 00:12:16370 pending_read_ssl_error_(SSL_ERROR_NONE),
[email protected]5aea79182014-07-14 20:43:41371 transport_read_error_(OK),
[email protected]3e5c6922014-02-06 02:42:16372 transport_write_error_(OK),
[email protected]7f38da8a2014-03-17 16:44:26373 server_cert_chain_(new PeerCertificateChain(NULL)),
[email protected]64b5c892014-08-08 09:39:26374 completed_connect_(false),
[email protected]0dc88b32014-03-26 20:12:28375 was_ever_used_(false),
[email protected]d518cd92010-09-29 12:27:44376 client_auth_cert_needed_(false),
[email protected]feb79bcd2011-07-21 16:55:17377 cert_verifier_(context.cert_verifier),
davidbeneb5f8ef32014-09-04 14:14:32378 cert_transparency_verifier_(context.cert_transparency_verifier),
[email protected]6b8a3c742014-07-25 00:25:35379 channel_id_service_(context.channel_id_service),
[email protected]d518cd92010-09-29 12:27:44380 ssl_(NULL),
381 transport_bio_(NULL),
[email protected]18ccfdb2013-08-15 00:13:44382 transport_(transport_socket.Pass()),
[email protected]055d7f22010-11-15 12:03:12383 host_and_port_(host_and_port),
[email protected]d518cd92010-09-29 12:27:44384 ssl_config_(ssl_config),
[email protected]c3456bb2011-12-12 22:22:19385 ssl_session_cache_shard_(context.ssl_session_cache_shard),
[email protected]fbef13932010-11-23 12:38:53386 trying_cached_session_(false),
[email protected]013c17c2012-01-21 19:09:01387 next_handshake_state_(STATE_NONE),
[email protected]ea4a1c6a2010-12-09 13:33:28388 npn_status_(kNextProtoUnsupported),
[email protected]ee0f2aa82013-10-25 11:59:26389 channel_id_xtn_negotiated_(false),
[email protected]64b5c892014-08-08 09:39:26390 handshake_succeeded_(false),
[email protected]e4738ba52014-08-07 10:07:22391 marked_session_as_good_(false),
[email protected]8bd4e7a2014-08-09 14:49:17392 transport_security_state_(context.transport_security_state),
eranm6571b2b2014-12-03 15:53:23393 policy_enforcer_(context.cert_policy_enforcer),
kulkarni.acd7b4462014-08-28 07:41:34394 net_log_(transport_->socket()->NetLog()),
395 weak_factory_(this) {
[email protected]8e458552014-08-05 00:02:15396}
[email protected]d518cd92010-09-29 12:27:44397
398SSLClientSocketOpenSSL::~SSLClientSocketOpenSSL() {
399 Disconnect();
400}
401
[email protected]cffd7f92014-08-21 21:30:50402std::string SSLClientSocketOpenSSL::GetSessionCacheKey() const {
403 std::string result = host_and_port_.ToString();
404 result.append("/");
405 result.append(ssl_session_cache_shard_);
406 return result;
407}
408
[email protected]8e458552014-08-05 00:02:15409bool SSLClientSocketOpenSSL::InSessionCache() const {
410 SSLContext* context = SSLContext::GetInstance();
411 std::string cache_key = GetSessionCacheKey();
412 return context->session_cache()->SSLSessionIsInCache(cache_key);
413}
414
415void SSLClientSocketOpenSSL::SetHandshakeCompletionCallback(
416 const base::Closure& callback) {
417 handshake_completion_callback_ = callback;
418}
419
[email protected]b9b651f2013-11-09 04:32:22420void SSLClientSocketOpenSSL::GetSSLCertRequestInfo(
421 SSLCertRequestInfo* cert_request_info) {
[email protected]791879c2013-12-17 07:22:41422 cert_request_info->host_and_port = host_and_port_;
[email protected]b9b651f2013-11-09 04:32:22423 cert_request_info->cert_authorities = cert_authorities_;
[email protected]c0787702014-05-20 21:51:44424 cert_request_info->cert_key_types = cert_key_types_;
[email protected]b9b651f2013-11-09 04:32:22425}
426
427SSLClientSocket::NextProtoStatus SSLClientSocketOpenSSL::GetNextProto(
[email protected]abc44b752014-07-30 03:52:15428 std::string* proto) {
[email protected]b9b651f2013-11-09 04:32:22429 *proto = npn_proto_;
[email protected]b9b651f2013-11-09 04:32:22430 return npn_status_;
431}
432
[email protected]6b8a3c742014-07-25 00:25:35433ChannelIDService*
434SSLClientSocketOpenSSL::GetChannelIDService() const {
435 return channel_id_service_;
[email protected]b9b651f2013-11-09 04:32:22436}
437
438int SSLClientSocketOpenSSL::ExportKeyingMaterial(
439 const base::StringPiece& label,
440 bool has_context, const base::StringPiece& context,
441 unsigned char* out, unsigned int outlen) {
442 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
443
444 int rv = SSL_export_keying_material(
[email protected]c8a80e92014-05-17 16:02:08445 ssl_, out, outlen, label.data(), label.size(),
446 reinterpret_cast<const unsigned char*>(context.data()),
447 context.length(), context.length() > 0);
[email protected]b9b651f2013-11-09 04:32:22448
449 if (rv != 1) {
450 int ssl_error = SSL_get_error(ssl_, rv);
451 LOG(ERROR) << "Failed to export keying material;"
452 << " returned " << rv
453 << ", SSL error code " << ssl_error;
454 return MapOpenSSLError(ssl_error, err_tracer);
455 }
456 return OK;
457}
458
459int SSLClientSocketOpenSSL::GetTLSUniqueChannelBinding(std::string* out) {
[email protected]c8a80e92014-05-17 16:02:08460 NOTIMPLEMENTED();
[email protected]b9b651f2013-11-09 04:32:22461 return ERR_NOT_IMPLEMENTED;
462}
463
464int SSLClientSocketOpenSSL::Connect(const CompletionCallback& callback) {
[email protected]8bd4e7a2014-08-09 14:49:17465 // It is an error to create an SSLClientSocket whose context has no
466 // TransportSecurityState.
467 DCHECK(transport_security_state_);
468
[email protected]b9b651f2013-11-09 04:32:22469 net_log_.BeginEvent(NetLog::TYPE_SSL_CONNECT);
470
471 // Set up new ssl object.
[email protected]c8a80e92014-05-17 16:02:08472 int rv = Init();
473 if (rv != OK) {
474 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
475 return rv;
[email protected]b9b651f2013-11-09 04:32:22476 }
477
478 // Set SSL to client mode. Handshake happens in the loop below.
479 SSL_set_connect_state(ssl_);
480
jeremyim8d44fadd2015-02-10 19:18:15481 // Enable fastradio padding.
482 SSL_enable_fastradio_padding(ssl_,
483 ssl_config_.fastradio_padding_enabled &&
484 ssl_config_.fastradio_padding_eligible);
485
[email protected]b9b651f2013-11-09 04:32:22486 GotoState(STATE_HANDSHAKE);
[email protected]c8a80e92014-05-17 16:02:08487 rv = DoHandshakeLoop(OK);
[email protected]b9b651f2013-11-09 04:32:22488 if (rv == ERR_IO_PENDING) {
489 user_connect_callback_ = callback;
490 } else {
491 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
[email protected]8e458552014-08-05 00:02:15492 if (rv < OK)
493 OnHandshakeCompletion();
[email protected]b9b651f2013-11-09 04:32:22494 }
495
496 return rv > OK ? OK : rv;
497}
498
499void SSLClientSocketOpenSSL::Disconnect() {
[email protected]8e458552014-08-05 00:02:15500 // If a handshake was pending (Connect() had been called), notify interested
501 // parties that it's been aborted now. If the handshake had already
502 // completed, this is a no-op.
503 OnHandshakeCompletion();
[email protected]b9b651f2013-11-09 04:32:22504 if (ssl_) {
505 // Calling SSL_shutdown prevents the session from being marked as
506 // unresumable.
507 SSL_shutdown(ssl_);
508 SSL_free(ssl_);
509 ssl_ = NULL;
510 }
511 if (transport_bio_) {
512 BIO_free_all(transport_bio_);
513 transport_bio_ = NULL;
514 }
515
516 // Shut down anything that may call us back.
517 verifier_.reset();
518 transport_->socket()->Disconnect();
519
520 // Null all callbacks, delete all buffers.
521 transport_send_busy_ = false;
522 send_buffer_ = NULL;
523 transport_recv_busy_ = false;
[email protected]b9b651f2013-11-09 04:32:22524 recv_buffer_ = NULL;
525
526 user_connect_callback_.Reset();
527 user_read_callback_.Reset();
528 user_write_callback_.Reset();
529 user_read_buf_ = NULL;
530 user_read_buf_len_ = 0;
531 user_write_buf_ = NULL;
532 user_write_buf_len_ = 0;
533
[email protected]3e5c6922014-02-06 02:42:16534 pending_read_error_ = kNoPendingReadResult;
davidbenb8c23212014-10-28 00:12:16535 pending_read_ssl_error_ = SSL_ERROR_NONE;
536 pending_read_error_info_ = OpenSSLErrorInfo();
537
[email protected]5aea79182014-07-14 20:43:41538 transport_read_error_ = OK;
[email protected]3e5c6922014-02-06 02:42:16539 transport_write_error_ = OK;
540
[email protected]b9b651f2013-11-09 04:32:22541 server_cert_verify_result_.Reset();
[email protected]64b5c892014-08-08 09:39:26542 completed_connect_ = false;
[email protected]b9b651f2013-11-09 04:32:22543
544 cert_authorities_.clear();
[email protected]c0787702014-05-20 21:51:44545 cert_key_types_.clear();
[email protected]b9b651f2013-11-09 04:32:22546 client_auth_cert_needed_ = false;
[email protected]faff9852014-06-21 06:13:46547
davidben09c3d072014-08-25 20:33:58548 start_cert_verification_time_ = base::TimeTicks();
549
[email protected]abc44b752014-07-30 03:52:15550 npn_status_ = kNextProtoUnsupported;
551 npn_proto_.clear();
552
[email protected]faff9852014-06-21 06:13:46553 channel_id_xtn_negotiated_ = false;
554 channel_id_request_handle_.Cancel();
[email protected]b9b651f2013-11-09 04:32:22555}
556
557bool SSLClientSocketOpenSSL::IsConnected() const {
558 // If the handshake has not yet completed.
[email protected]64b5c892014-08-08 09:39:26559 if (!completed_connect_)
[email protected]b9b651f2013-11-09 04:32:22560 return false;
561 // If an asynchronous operation is still pending.
562 if (user_read_buf_.get() || user_write_buf_.get())
563 return true;
564
565 return transport_->socket()->IsConnected();
566}
567
568bool SSLClientSocketOpenSSL::IsConnectedAndIdle() const {
569 // If the handshake has not yet completed.
[email protected]64b5c892014-08-08 09:39:26570 if (!completed_connect_)
[email protected]b9b651f2013-11-09 04:32:22571 return false;
572 // If an asynchronous operation is still pending.
573 if (user_read_buf_.get() || user_write_buf_.get())
574 return false;
575 // If there is data waiting to be sent, or data read from the network that
576 // has not yet been consumed.
[email protected]edfd0f42014-07-22 18:20:37577 if (BIO_pending(transport_bio_) > 0 ||
578 BIO_wpending(transport_bio_) > 0) {
[email protected]b9b651f2013-11-09 04:32:22579 return false;
580 }
581
582 return transport_->socket()->IsConnectedAndIdle();
583}
584
585int SSLClientSocketOpenSSL::GetPeerAddress(IPEndPoint* addressList) const {
586 return transport_->socket()->GetPeerAddress(addressList);
587}
588
589int SSLClientSocketOpenSSL::GetLocalAddress(IPEndPoint* addressList) const {
590 return transport_->socket()->GetLocalAddress(addressList);
591}
592
593const BoundNetLog& SSLClientSocketOpenSSL::NetLog() const {
594 return net_log_;
595}
596
597void SSLClientSocketOpenSSL::SetSubresourceSpeculation() {
598 if (transport_.get() && transport_->socket()) {
599 transport_->socket()->SetSubresourceSpeculation();
600 } else {
601 NOTREACHED();
602 }
603}
604
605void SSLClientSocketOpenSSL::SetOmniboxSpeculation() {
606 if (transport_.get() && transport_->socket()) {
607 transport_->socket()->SetOmniboxSpeculation();
608 } else {
609 NOTREACHED();
610 }
611}
612
613bool SSLClientSocketOpenSSL::WasEverUsed() const {
[email protected]0dc88b32014-03-26 20:12:28614 return was_ever_used_;
[email protected]b9b651f2013-11-09 04:32:22615}
616
617bool SSLClientSocketOpenSSL::UsingTCPFastOpen() const {
618 if (transport_.get() && transport_->socket())
619 return transport_->socket()->UsingTCPFastOpen();
620
621 NOTREACHED();
622 return false;
623}
624
625bool SSLClientSocketOpenSSL::GetSSLInfo(SSLInfo* ssl_info) {
626 ssl_info->Reset();
davidben30798ed82014-09-19 19:28:20627 if (server_cert_chain_->empty())
[email protected]b9b651f2013-11-09 04:32:22628 return false;
629
630 ssl_info->cert = server_cert_verify_result_.verified_cert;
631 ssl_info->cert_status = server_cert_verify_result_.cert_status;
632 ssl_info->is_issued_by_known_root =
633 server_cert_verify_result_.is_issued_by_known_root;
634 ssl_info->public_key_hashes =
635 server_cert_verify_result_.public_key_hashes;
636 ssl_info->client_cert_sent =
637 ssl_config_.send_client_cert && ssl_config_.client_cert.get();
638 ssl_info->channel_id_sent = WasChannelIDSent();
[email protected]8bd4e7a2014-08-09 14:49:17639 ssl_info->pinning_failure_log = pinning_failure_log_;
[email protected]b9b651f2013-11-09 04:32:22640
davidbeneb5f8ef32014-09-04 14:14:32641 AddSCTInfoToSSLInfo(ssl_info);
642
[email protected]b9b651f2013-11-09 04:32:22643 const SSL_CIPHER* cipher = SSL_get_current_cipher(ssl_);
644 CHECK(cipher);
645 ssl_info->security_bits = SSL_CIPHER_get_bits(cipher, NULL);
[email protected]b9b651f2013-11-09 04:32:22646
647 ssl_info->connection_status = EncodeSSLConnectionStatus(
pkasting6b68a162014-12-01 22:10:29648 static_cast<uint16>(SSL_CIPHER_get_id(cipher)), 0 /* no compression */,
[email protected]b9b651f2013-11-09 04:32:22649 GetNetSSLVersion(ssl_));
650
davidben09c3d072014-08-25 20:33:58651 if (!SSL_get_secure_renegotiation_support(ssl_))
[email protected]b9b651f2013-11-09 04:32:22652 ssl_info->connection_status |= SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION;
[email protected]b9b651f2013-11-09 04:32:22653
654 if (ssl_config_.version_fallback)
655 ssl_info->connection_status |= SSL_CONNECTION_VERSION_FALLBACK;
656
657 ssl_info->handshake_type = SSL_session_reused(ssl_) ?
658 SSLInfo::HANDSHAKE_RESUME : SSLInfo::HANDSHAKE_FULL;
659
660 DVLOG(3) << "Encoded connection status: cipher suite = "
661 << SSLConnectionStatusToCipherSuite(ssl_info->connection_status)
662 << " version = "
663 << SSLConnectionStatusToVersion(ssl_info->connection_status);
664 return true;
665}
666
667int SSLClientSocketOpenSSL::Read(IOBuffer* buf,
668 int buf_len,
669 const CompletionCallback& callback) {
670 user_read_buf_ = buf;
671 user_read_buf_len_ = buf_len;
672
davidben1b133ad2014-10-23 04:23:13673 int rv = DoReadLoop();
[email protected]b9b651f2013-11-09 04:32:22674
675 if (rv == ERR_IO_PENDING) {
676 user_read_callback_ = callback;
677 } else {
[email protected]0dc88b32014-03-26 20:12:28678 if (rv > 0)
679 was_ever_used_ = true;
[email protected]b9b651f2013-11-09 04:32:22680 user_read_buf_ = NULL;
681 user_read_buf_len_ = 0;
[email protected]8e458552014-08-05 00:02:15682 if (rv <= 0) {
683 // Failure of a read attempt may indicate a failed false start
684 // connection.
685 OnHandshakeCompletion();
686 }
[email protected]b9b651f2013-11-09 04:32:22687 }
688
689 return rv;
690}
691
692int SSLClientSocketOpenSSL::Write(IOBuffer* buf,
693 int buf_len,
694 const CompletionCallback& callback) {
695 user_write_buf_ = buf;
696 user_write_buf_len_ = buf_len;
697
davidben1b133ad2014-10-23 04:23:13698 int rv = DoWriteLoop();
[email protected]b9b651f2013-11-09 04:32:22699
700 if (rv == ERR_IO_PENDING) {
701 user_write_callback_ = callback;
702 } else {
[email protected]0dc88b32014-03-26 20:12:28703 if (rv > 0)
704 was_ever_used_ = true;
[email protected]b9b651f2013-11-09 04:32:22705 user_write_buf_ = NULL;
706 user_write_buf_len_ = 0;
[email protected]8e458552014-08-05 00:02:15707 if (rv < 0) {
708 // Failure of a write attempt may indicate a failed false start
709 // connection.
710 OnHandshakeCompletion();
711 }
[email protected]b9b651f2013-11-09 04:32:22712 }
713
714 return rv;
715}
716
[email protected]28b96d1c2014-04-09 12:21:15717int SSLClientSocketOpenSSL::SetReceiveBufferSize(int32 size) {
[email protected]b9b651f2013-11-09 04:32:22718 return transport_->socket()->SetReceiveBufferSize(size);
719}
720
[email protected]28b96d1c2014-04-09 12:21:15721int SSLClientSocketOpenSSL::SetSendBufferSize(int32 size) {
[email protected]b9b651f2013-11-09 04:32:22722 return transport_->socket()->SetSendBufferSize(size);
723}
724
[email protected]c8a80e92014-05-17 16:02:08725int SSLClientSocketOpenSSL::Init() {
[email protected]9e733f32010-10-04 18:19:08726 DCHECK(!ssl_);
727 DCHECK(!transport_bio_);
728
[email protected]b29af7d2010-12-14 11:52:47729 SSLContext* context = SSLContext::GetInstance();
[email protected]4b559b4d2011-04-14 17:37:14730 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
[email protected]d518cd92010-09-29 12:27:44731
[email protected]fbef13932010-11-23 12:38:53732 ssl_ = SSL_new(context->ssl_ctx());
733 if (!ssl_ || !context->SetClientSocketForSSL(ssl_, this))
[email protected]c8a80e92014-05-17 16:02:08734 return ERR_UNEXPECTED;
[email protected]fbef13932010-11-23 12:38:53735
736 if (!SSL_set_tlsext_host_name(ssl_, host_and_port_.host().c_str()))
[email protected]c8a80e92014-05-17 16:02:08737 return ERR_UNEXPECTED;
[email protected]fbef13932010-11-23 12:38:53738
[email protected]e4738ba52014-08-07 10:07:22739 // Set an OpenSSL callback to monitor this SSL*'s connection.
740 SSL_set_info_callback(ssl_, &InfoCallback);
741
[email protected]1279de12013-12-03 15:13:32742 trying_cached_session_ = context->session_cache()->SetSSLSessionWithKey(
[email protected]8e458552014-08-05 00:02:15743 ssl_, GetSessionCacheKey());
[email protected]d518cd92010-09-29 12:27:44744
haavardm2d92e722014-12-19 13:45:44745 send_buffer_ = new GrowableIOBuffer();
746 send_buffer_->SetCapacity(KDefaultOpenSSLBufferSize);
747 recv_buffer_ = new GrowableIOBuffer();
748 recv_buffer_->SetCapacity(KDefaultOpenSSLBufferSize);
749
[email protected]d518cd92010-09-29 12:27:44750 BIO* ssl_bio = NULL;
haavardm2d92e722014-12-19 13:45:44751
752 // SSLClientSocketOpenSSL retains ownership of the BIO buffers.
753 if (!BIO_new_bio_pair_external_buf(
754 &ssl_bio, send_buffer_->capacity(),
755 reinterpret_cast<uint8_t*>(send_buffer_->data()), &transport_bio_,
756 recv_buffer_->capacity(),
757 reinterpret_cast<uint8_t*>(recv_buffer_->data())))
[email protected]c8a80e92014-05-17 16:02:08758 return ERR_UNEXPECTED;
[email protected]d518cd92010-09-29 12:27:44759 DCHECK(ssl_bio);
760 DCHECK(transport_bio_);
761
[email protected]5aea79182014-07-14 20:43:41762 // Install a callback on OpenSSL's end to plumb transport errors through.
[email protected]64b5c892014-08-08 09:39:26763 BIO_set_callback(ssl_bio, BIOCallback);
[email protected]5aea79182014-07-14 20:43:41764 BIO_set_callback_arg(ssl_bio, reinterpret_cast<char*>(this));
765
[email protected]d518cd92010-09-29 12:27:44766 SSL_set_bio(ssl_, ssl_bio, ssl_bio);
767
[email protected]9e733f32010-10-04 18:19:08768 // OpenSSL defaults some options to on, others to off. To avoid ambiguity,
769 // set everything we care about to an absolute value.
[email protected]fb10e2282010-12-01 17:08:48770 SslSetClearMask options;
771 options.ConfigureFlag(SSL_OP_NO_SSLv2, true);
[email protected]80c75f682012-05-26 16:22:17772 bool ssl3_enabled = (ssl_config_.version_min == SSL_PROTOCOL_VERSION_SSL3);
773 options.ConfigureFlag(SSL_OP_NO_SSLv3, !ssl3_enabled);
774 bool tls1_enabled = (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1 &&
775 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1);
776 options.ConfigureFlag(SSL_OP_NO_TLSv1, !tls1_enabled);
[email protected]80c75f682012-05-26 16:22:17777 bool tls1_1_enabled =
778 (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1_1 &&
779 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1_1);
780 options.ConfigureFlag(SSL_OP_NO_TLSv1_1, !tls1_1_enabled);
[email protected]80c75f682012-05-26 16:22:17781 bool tls1_2_enabled =
782 (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1_2 &&
783 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1_2);
784 options.ConfigureFlag(SSL_OP_NO_TLSv1_2, !tls1_2_enabled);
[email protected]fb10e2282010-12-01 17:08:48785
[email protected]d0f00492012-08-03 22:35:13786 options.ConfigureFlag(SSL_OP_NO_COMPRESSION, true);
[email protected]9e733f32010-10-04 18:19:08787
788 // TODO(joth): Set this conditionally, see http://crbug.com/55410
[email protected]fb10e2282010-12-01 17:08:48789 options.ConfigureFlag(SSL_OP_LEGACY_SERVER_CONNECT, true);
[email protected]9e733f32010-10-04 18:19:08790
[email protected]fb10e2282010-12-01 17:08:48791 SSL_set_options(ssl_, options.set_mask);
792 SSL_clear_options(ssl_, options.clear_mask);
[email protected]9e733f32010-10-04 18:19:08793
[email protected]fb10e2282010-12-01 17:08:48794 // Same as above, this time for the SSL mode.
795 SslSetClearMask mode;
[email protected]9e733f32010-10-04 18:19:08796
[email protected]fb10e2282010-12-01 17:08:48797 mode.ConfigureFlag(SSL_MODE_RELEASE_BUFFERS, true);
ishermane5c05e12014-09-09 20:32:15798 mode.ConfigureFlag(SSL_MODE_CBC_RECORD_SPLITTING, true);
[email protected]fb10e2282010-12-01 17:08:48799
[email protected]b788de02014-04-23 18:06:07800 mode.ConfigureFlag(SSL_MODE_HANDSHAKE_CUTTHROUGH,
801 ssl_config_.false_start_enabled);
802
[email protected]fb10e2282010-12-01 17:08:48803 SSL_set_mode(ssl_, mode.set_mask);
804 SSL_clear_mode(ssl_, mode.clear_mask);
[email protected]109805a2010-12-07 18:17:06805
806 // Removing ciphers by ID from OpenSSL is a bit involved as we must use the
807 // textual name with SSL_set_cipher_list because there is no public API to
808 // directly remove a cipher by ID.
809 STACK_OF(SSL_CIPHER)* ciphers = SSL_get_ciphers(ssl_);
810 DCHECK(ciphers);
811 // See SSLConfig::disabled_cipher_suites for description of the suites
[email protected]9b4bc4a92013-08-20 22:59:07812 // disabled by default. Note that !SHA256 and !SHA384 only remove HMAC-SHA256
813 // and HMAC-SHA384 cipher suites, not GCM cipher suites with SHA256 or SHA384
814 // as the handshake hash.
bnc1e757502014-12-13 02:20:16815 std::string command(
816 "DEFAULT:!NULL:!aNULL:!SHA256:!SHA384:!aECDH:!AESGCM+AES256:!aPSK");
[email protected]109805a2010-12-07 18:17:06817 // Walk through all the installed ciphers, seeing if any need to be
818 // appended to the cipher removal |command|.
[email protected]edfd0f42014-07-22 18:20:37819 for (size_t i = 0; i < sk_SSL_CIPHER_num(ciphers); ++i) {
[email protected]109805a2010-12-07 18:17:06820 const SSL_CIPHER* cipher = sk_SSL_CIPHER_value(ciphers, i);
pkasting6b68a162014-12-01 22:10:29821 const uint16 id = static_cast<uint16>(SSL_CIPHER_get_id(cipher));
[email protected]109805a2010-12-07 18:17:06822 // Remove any ciphers with a strength of less than 80 bits. Note the NSS
823 // implementation uses "effective" bits here but OpenSSL does not provide
824 // this detail. This only impacts Triple DES: reports 112 vs. 168 bits,
825 // both of which are greater than 80 anyway.
826 bool disable = SSL_CIPHER_get_bits(cipher, NULL) < 80;
827 if (!disable) {
828 disable = std::find(ssl_config_.disabled_cipher_suites.begin(),
829 ssl_config_.disabled_cipher_suites.end(), id) !=
830 ssl_config_.disabled_cipher_suites.end();
831 }
832 if (disable) {
833 const char* name = SSL_CIPHER_get_name(cipher);
834 DVLOG(3) << "Found cipher to remove: '" << name << "', ID: " << id
835 << " strength: " << SSL_CIPHER_get_bits(cipher, NULL);
836 command.append(":!");
837 command.append(name);
838 }
839 }
davidben8ecc3072014-09-03 23:19:09840
841 // Disable ECDSA cipher suites on platforms that do not support ECDSA
842 // signed certificates, as servers may use the presence of such
843 // ciphersuites as a hint to send an ECDSA certificate.
844#if defined(OS_WIN)
845 if (base::win::GetVersion() < base::win::VERSION_VISTA)
846 command.append(":!ECDSA");
847#endif
848
[email protected]109805a2010-12-07 18:17:06849 int rv = SSL_set_cipher_list(ssl_, command.c_str());
850 // If this fails (rv = 0) it means there are no ciphers enabled on this SSL.
851 // This will almost certainly result in the socket failing to complete the
852 // handshake at which point the appropriate error is bubbled up to the client.
853 LOG_IF(WARNING, rv != 1) << "SSL_set_cipher_list('" << command << "') "
854 "returned " << rv;
[email protected]ee0f2aa82013-10-25 11:59:26855
[email protected]0d0a6872014-07-26 18:05:11856 if (ssl_config_.version_fallback)
857 SSL_enable_fallback_scsv(ssl_);
858
[email protected]ee0f2aa82013-10-25 11:59:26859 // TLS channel ids.
[email protected]6b8a3c742014-07-25 00:25:35860 if (IsChannelIDEnabled(ssl_config_, channel_id_service_)) {
[email protected]ee0f2aa82013-10-25 11:59:26861 SSL_enable_tls_channel_id(ssl_);
862 }
863
[email protected]abc44b752014-07-30 03:52:15864 if (!ssl_config_.next_protos.empty()) {
bnc1e757502014-12-13 02:20:16865 // Get list of ciphers that are enabled.
866 STACK_OF(SSL_CIPHER)* enabled_ciphers = SSL_get_ciphers(ssl_);
867 DCHECK(enabled_ciphers);
868 std::vector<uint16> enabled_ciphers_vector;
869 for (size_t i = 0; i < sk_SSL_CIPHER_num(enabled_ciphers); ++i) {
870 const SSL_CIPHER* cipher = sk_SSL_CIPHER_value(enabled_ciphers, i);
871 const uint16 id = static_cast<uint16>(SSL_CIPHER_get_id(cipher));
872 enabled_ciphers_vector.push_back(id);
873 }
874
[email protected]abc44b752014-07-30 03:52:15875 std::vector<uint8_t> wire_protos =
bnc1e757502014-12-13 02:20:16876 SerializeNextProtos(ssl_config_.next_protos,
877 HasCipherAdequateForHTTP2(enabled_ciphers_vector) &&
878 IsTLSVersionAdequateForHTTP2(ssl_config_));
[email protected]abc44b752014-07-30 03:52:15879 SSL_set_alpn_protos(ssl_, wire_protos.empty() ? NULL : &wire_protos[0],
880 wire_protos.size());
881 }
882
davidbeneb5f8ef32014-09-04 14:14:32883 if (ssl_config_.signed_cert_timestamps_enabled) {
884 SSL_enable_signed_cert_timestamps(ssl_);
885 SSL_enable_ocsp_stapling(ssl_);
886 }
887
davidbend1fb2f12014-11-08 02:51:00888 if (IsOCSPStaplingSupported())
889 SSL_enable_ocsp_stapling(ssl_);
davidbeneb5f8ef32014-09-04 14:14:32890
[email protected]c8a80e92014-05-17 16:02:08891 return OK;
[email protected]d518cd92010-09-29 12:27:44892}
893
[email protected]b9b651f2013-11-09 04:32:22894void SSLClientSocketOpenSSL::DoReadCallback(int rv) {
895 // Since Run may result in Read being called, clear |user_read_callback_|
896 // up front.
[email protected]0dc88b32014-03-26 20:12:28897 if (rv > 0)
898 was_ever_used_ = true;
[email protected]b9b651f2013-11-09 04:32:22899 user_read_buf_ = NULL;
900 user_read_buf_len_ = 0;
[email protected]8e458552014-08-05 00:02:15901 if (rv <= 0) {
902 // Failure of a read attempt may indicate a failed false start
903 // connection.
904 OnHandshakeCompletion();
905 }
[email protected]b9b651f2013-11-09 04:32:22906 base::ResetAndReturn(&user_read_callback_).Run(rv);
907}
908
909void SSLClientSocketOpenSSL::DoWriteCallback(int rv) {
910 // Since Run may result in Write being called, clear |user_write_callback_|
911 // up front.
[email protected]0dc88b32014-03-26 20:12:28912 if (rv > 0)
913 was_ever_used_ = true;
[email protected]b9b651f2013-11-09 04:32:22914 user_write_buf_ = NULL;
915 user_write_buf_len_ = 0;
[email protected]8e458552014-08-05 00:02:15916 if (rv < 0) {
917 // Failure of a write attempt may indicate a failed false start
918 // connection.
919 OnHandshakeCompletion();
920 }
[email protected]b9b651f2013-11-09 04:32:22921 base::ResetAndReturn(&user_write_callback_).Run(rv);
922}
923
[email protected]8e458552014-08-05 00:02:15924void SSLClientSocketOpenSSL::OnHandshakeCompletion() {
925 if (!handshake_completion_callback_.is_null())
926 base::ResetAndReturn(&handshake_completion_callback_).Run();
927}
928
[email protected]b9b651f2013-11-09 04:32:22929bool SSLClientSocketOpenSSL::DoTransportIO() {
930 bool network_moved = false;
931 int rv;
932 // Read and write as much data as possible. The loop is necessary because
933 // Write() may return synchronously.
934 do {
935 rv = BufferSend();
936 if (rv != ERR_IO_PENDING && rv != 0)
937 network_moved = true;
938 } while (rv > 0);
[email protected]5aea79182014-07-14 20:43:41939 if (transport_read_error_ == OK && BufferRecv() != ERR_IO_PENDING)
[email protected]b9b651f2013-11-09 04:32:22940 network_moved = true;
941 return network_moved;
942}
943
vadimt6b43dec22015-01-06 01:59:58944// TODO(vadimt): Remove including "base/threading/thread_local.h" and
945// g_first_run_completed once crbug.com/424386 is fixed.
946base::LazyInstance<base::ThreadLocalBoolean>::Leaky g_first_run_completed =
947 LAZY_INSTANCE_INITIALIZER;
948
[email protected]b9b651f2013-11-09 04:32:22949int SSLClientSocketOpenSSL::DoHandshake() {
950 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
[email protected]c8a80e92014-05-17 16:02:08951 int net_error = OK;
vadimt5a243282014-12-24 00:26:16952
953 int rv;
954
955 // TODO(vadimt): Leave only 1 call to SSL_do_handshake once crbug.com/424386
956 // is fixed.
957 if (ssl_config_.send_client_cert && ssl_config_.client_cert.get()) {
958 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
959 tracked_objects::ScopedTracker tracking_profile1(
960 FROM_HERE_WITH_EXPLICIT_FUNCTION("424386 DoHandshake_WithCert"));
961
962 rv = SSL_do_handshake(ssl_);
963 } else {
vadimt6b43dec22015-01-06 01:59:58964 if (g_first_run_completed.Get().Get()) {
965 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is
966 // fixed.
967 tracked_objects::ScopedTracker tracking_profile1(
968 FROM_HERE_WITH_EXPLICIT_FUNCTION(
969 "424386 DoHandshake_WithoutCert Not First"));
vadimt5a243282014-12-24 00:26:16970
vadimt6b43dec22015-01-06 01:59:58971 rv = SSL_do_handshake(ssl_);
972 } else {
973 g_first_run_completed.Get().Set(true);
974
975 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is
976 // fixed.
977 tracked_objects::ScopedTracker tracking_profile1(
978 FROM_HERE_WITH_EXPLICIT_FUNCTION(
979 "424386 DoHandshake_WithoutCert First"));
980
981 rv = SSL_do_handshake(ssl_);
982 }
vadimt5a243282014-12-24 00:26:16983 }
[email protected]b9b651f2013-11-09 04:32:22984
985 if (client_auth_cert_needed_) {
vadimtc4e29112014-12-18 01:44:21986 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
987 tracked_objects::ScopedTracker tracking_profile2(
988 FROM_HERE_WITH_EXPLICIT_FUNCTION(
989 "424386 SSLClientSocketOpenSSL::DoHandshake2"));
990
[email protected]b9b651f2013-11-09 04:32:22991 net_error = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
992 // If the handshake already succeeded (because the server requests but
993 // doesn't require a client cert), we need to invalidate the SSL session
994 // so that we won't try to resume the non-client-authenticated session in
995 // the next handshake. This will cause the server to ask for a client
996 // cert again.
997 if (rv == 1) {
998 // Remove from session cache but don't clear this connection.
999 SSL_SESSION* session = SSL_get_session(ssl_);
1000 if (session) {
1001 int rv = SSL_CTX_remove_session(SSL_get_SSL_CTX(ssl_), session);
1002 LOG_IF(WARNING, !rv) << "Couldn't invalidate SSL session: " << session;
1003 }
1004 }
1005 } else if (rv == 1) {
vadimtc4e29112014-12-18 01:44:211006 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1007 tracked_objects::ScopedTracker tracking_profile3(
1008 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1009 "424386 SSLClientSocketOpenSSL::DoHandshake3"));
1010
[email protected]b9b651f2013-11-09 04:32:221011 if (trying_cached_session_ && logging::DEBUG_MODE) {
1012 DVLOG(2) << "Result of session reuse for " << host_and_port_.ToString()
1013 << " is: " << (SSL_session_reused(ssl_) ? "Success" : "Fail");
1014 }
[email protected]abc44b752014-07-30 03:52:151015
Adam Langley32352ad2014-10-14 22:31:001016 if (ssl_config_.version_fallback &&
1017 ssl_config_.version_max < ssl_config_.version_fallback_min) {
1018 return ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION;
1019 }
1020
[email protected]abc44b752014-07-30 03:52:151021 // SSL handshake is completed. If NPN wasn't negotiated, see if ALPN was.
1022 if (npn_status_ == kNextProtoUnsupported) {
1023 const uint8_t* alpn_proto = NULL;
1024 unsigned alpn_len = 0;
1025 SSL_get0_alpn_selected(ssl_, &alpn_proto, &alpn_len);
1026 if (alpn_len > 0) {
1027 npn_proto_.assign(reinterpret_cast<const char*>(alpn_proto), alpn_len);
1028 npn_status_ = kNextProtoNegotiated;
bnc0d28ea52014-10-13 15:15:381029 set_negotiation_extension(kExtensionALPN);
[email protected]abc44b752014-07-30 03:52:151030 }
1031 }
1032
davidben09c3d072014-08-25 20:33:581033 RecordChannelIDSupport(channel_id_service_,
1034 channel_id_xtn_negotiated_,
1035 ssl_config_.channel_id_enabled,
1036 crypto::ECPrivateKey::IsSupported());
1037
davidbend1fb2f12014-11-08 02:51:001038 // Only record OCSP histograms if OCSP was requested.
1039 if (ssl_config_.signed_cert_timestamps_enabled ||
1040 IsOCSPStaplingSupported()) {
davidben54015aa2014-12-02 22:16:231041 const uint8_t* ocsp_response;
davidbend1fb2f12014-11-08 02:51:001042 size_t ocsp_response_len;
1043 SSL_get0_ocsp_response(ssl_, &ocsp_response, &ocsp_response_len);
1044
1045 set_stapled_ocsp_response_received(ocsp_response_len != 0);
1046 UMA_HISTOGRAM_BOOLEAN("Net.OCSPResponseStapled", ocsp_response_len != 0);
1047 }
davidbeneb5f8ef32014-09-04 14:14:321048
davidben54015aa2014-12-02 22:16:231049 const uint8_t* sct_list;
davidbeneb5f8ef32014-09-04 14:14:321050 size_t sct_list_len;
1051 SSL_get0_signed_cert_timestamp_list(ssl_, &sct_list, &sct_list_len);
1052 set_signed_cert_timestamps_received(sct_list_len != 0);
1053
[email protected]abc44b752014-07-30 03:52:151054 // Verify the certificate.
davidben30798ed82014-09-19 19:28:201055 UpdateServerCert();
[email protected]b9b651f2013-11-09 04:32:221056 GotoState(STATE_VERIFY_CERT);
1057 } else {
vadimtc4e29112014-12-18 01:44:211058 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1059 tracked_objects::ScopedTracker tracking_profile4(
1060 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1061 "424386 SSLClientSocketOpenSSL::DoHandshake4"));
1062
[email protected]b9b651f2013-11-09 04:32:221063 int ssl_error = SSL_get_error(ssl_, rv);
1064
1065 if (ssl_error == SSL_ERROR_WANT_CHANNEL_ID_LOOKUP) {
[email protected]faff9852014-06-21 06:13:461066 // The server supports channel ID. Stop to look one up before returning to
1067 // the handshake.
1068 channel_id_xtn_negotiated_ = true;
1069 GotoState(STATE_CHANNEL_ID_LOOKUP);
1070 return OK;
[email protected]b9b651f2013-11-09 04:32:221071 }
1072
davidbena4409c62014-08-27 17:05:511073 OpenSSLErrorInfo error_info;
1074 net_error = MapOpenSSLErrorWithDetails(ssl_error, err_tracer, &error_info);
[email protected]faff9852014-06-21 06:13:461075
[email protected]b9b651f2013-11-09 04:32:221076 // If not done, stay in this state
1077 if (net_error == ERR_IO_PENDING) {
1078 GotoState(STATE_HANDSHAKE);
1079 } else {
1080 LOG(ERROR) << "handshake failed; returned " << rv
1081 << ", SSL error code " << ssl_error
1082 << ", net_error " << net_error;
1083 net_log_.AddEvent(
1084 NetLog::TYPE_SSL_HANDSHAKE_ERROR,
davidbena4409c62014-08-27 17:05:511085 CreateNetLogOpenSSLErrorCallback(net_error, ssl_error, error_info));
[email protected]b9b651f2013-11-09 04:32:221086 }
1087 }
1088 return net_error;
1089}
1090
[email protected]faff9852014-06-21 06:13:461091int SSLClientSocketOpenSSL::DoChannelIDLookup() {
1092 GotoState(STATE_CHANNEL_ID_LOOKUP_COMPLETE);
[email protected]6b8a3c742014-07-25 00:25:351093 return channel_id_service_->GetOrCreateChannelID(
[email protected]faff9852014-06-21 06:13:461094 host_and_port_.host(),
1095 &channel_id_private_key_,
1096 &channel_id_cert_,
1097 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete,
1098 base::Unretained(this)),
1099 &channel_id_request_handle_);
1100}
1101
1102int SSLClientSocketOpenSSL::DoChannelIDLookupComplete(int result) {
1103 if (result < 0)
1104 return result;
1105
1106 DCHECK_LT(0u, channel_id_private_key_.size());
1107 // Decode key.
1108 std::vector<uint8> encrypted_private_key_info;
1109 std::vector<uint8> subject_public_key_info;
1110 encrypted_private_key_info.assign(
1111 channel_id_private_key_.data(),
1112 channel_id_private_key_.data() + channel_id_private_key_.size());
1113 subject_public_key_info.assign(
1114 channel_id_cert_.data(),
1115 channel_id_cert_.data() + channel_id_cert_.size());
1116 scoped_ptr<crypto::ECPrivateKey> ec_private_key(
1117 crypto::ECPrivateKey::CreateFromEncryptedPrivateKeyInfo(
[email protected]6b8a3c742014-07-25 00:25:351118 ChannelIDService::kEPKIPassword,
[email protected]faff9852014-06-21 06:13:461119 encrypted_private_key_info,
1120 subject_public_key_info));
1121 if (!ec_private_key) {
1122 LOG(ERROR) << "Failed to import Channel ID.";
1123 return ERR_CHANNEL_ID_IMPORT_FAILED;
1124 }
1125
1126 // Hand the key to OpenSSL. Check for error in case OpenSSL rejects the key
1127 // type.
1128 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1129 int rv = SSL_set1_tls_channel_id(ssl_, ec_private_key->key());
1130 if (!rv) {
1131 LOG(ERROR) << "Failed to set Channel ID.";
1132 int err = SSL_get_error(ssl_, rv);
1133 return MapOpenSSLError(err, err_tracer);
1134 }
1135
1136 // Return to the handshake.
1137 set_channel_id_sent(true);
1138 GotoState(STATE_HANDSHAKE);
1139 return OK;
1140}
1141
[email protected]b9b651f2013-11-09 04:32:221142int SSLClientSocketOpenSSL::DoVerifyCert(int result) {
davidben30798ed82014-09-19 19:28:201143 DCHECK(!server_cert_chain_->empty());
davidben09c3d072014-08-25 20:33:581144 DCHECK(start_cert_verification_time_.is_null());
davidben30798ed82014-09-19 19:28:201145
[email protected]b9b651f2013-11-09 04:32:221146 GotoState(STATE_VERIFY_CERT_COMPLETE);
1147
davidben30798ed82014-09-19 19:28:201148 // If the certificate is bad and has been previously accepted, use
1149 // the previous status and bypass the error.
1150 base::StringPiece der_cert;
1151 if (!x509_util::GetDER(server_cert_chain_->Get(0), &der_cert)) {
1152 NOTREACHED();
1153 return ERR_CERT_INVALID;
1154 }
[email protected]b9b651f2013-11-09 04:32:221155 CertStatus cert_status;
davidben30798ed82014-09-19 19:28:201156 if (ssl_config_.IsAllowedBadCert(der_cert, &cert_status)) {
[email protected]b9b651f2013-11-09 04:32:221157 VLOG(1) << "Received an expected bad cert with status: " << cert_status;
1158 server_cert_verify_result_.Reset();
1159 server_cert_verify_result_.cert_status = cert_status;
1160 server_cert_verify_result_.verified_cert = server_cert_;
1161 return OK;
1162 }
1163
davidben30798ed82014-09-19 19:28:201164 // When running in a sandbox, it may not be possible to create an
1165 // X509Certificate*, as that may depend on OS functionality blocked
1166 // in the sandbox.
1167 if (!server_cert_.get()) {
1168 server_cert_verify_result_.Reset();
1169 server_cert_verify_result_.cert_status = CERT_STATUS_INVALID;
1170 return ERR_CERT_INVALID;
1171 }
1172
davidben09c3d072014-08-25 20:33:581173 start_cert_verification_time_ = base::TimeTicks::Now();
1174
[email protected]b9b651f2013-11-09 04:32:221175 int flags = 0;
1176 if (ssl_config_.rev_checking_enabled)
1177 flags |= CertVerifier::VERIFY_REV_CHECKING_ENABLED;
1178 if (ssl_config_.verify_ev_cert)
1179 flags |= CertVerifier::VERIFY_EV_CERT;
1180 if (ssl_config_.cert_io_enabled)
1181 flags |= CertVerifier::VERIFY_CERT_IO_ENABLED;
1182 if (ssl_config_.rev_checking_required_local_anchors)
1183 flags |= CertVerifier::VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS;
1184 verifier_.reset(new SingleRequestCertVerifier(cert_verifier_));
1185 return verifier_->Verify(
1186 server_cert_.get(),
1187 host_and_port_.host(),
1188 flags,
[email protected]591cffcd2014-08-18 20:02:301189 // TODO(davidben): Route the CRLSet through SSLConfig so
1190 // SSLClientSocket doesn't depend on SSLConfigService.
1191 SSLConfigService::GetCRLSet().get(),
[email protected]b9b651f2013-11-09 04:32:221192 &server_cert_verify_result_,
1193 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete,
1194 base::Unretained(this)),
1195 net_log_);
1196}
1197
1198int SSLClientSocketOpenSSL::DoVerifyCertComplete(int result) {
1199 verifier_.reset();
1200
davidben09c3d072014-08-25 20:33:581201 if (!start_cert_verification_time_.is_null()) {
1202 base::TimeDelta verify_time =
1203 base::TimeTicks::Now() - start_cert_verification_time_;
1204 if (result == OK) {
1205 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTime", verify_time);
1206 } else {
1207 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTimeError", verify_time);
1208 }
1209 }
1210
davidben85574eb2014-12-12 03:01:571211 if (result == OK) {
davidben7c7ab602014-11-05 22:27:441212 RecordConnectionTypeMetrics(GetNetSSLVersion(ssl_));
1213
davidben85574eb2014-12-12 03:01:571214 if (SSL_session_reused(ssl_)) {
1215 // Record whether or not the server tried to resume a session for a
1216 // different version. See https://crbug.com/441456.
1217 UMA_HISTOGRAM_BOOLEAN(
1218 "Net.SSLSessionVersionMatch",
1219 SSL_version(ssl_) == SSL_get_session(ssl_)->ssl_version);
1220 }
1221 }
1222
[email protected]8bd4e7a2014-08-09 14:49:171223 const CertStatus cert_status = server_cert_verify_result_.cert_status;
1224 if (transport_security_state_ &&
1225 (result == OK ||
1226 (IsCertificateError(result) && IsCertStatusMinorError(cert_status))) &&
1227 !transport_security_state_->CheckPublicKeyPins(
1228 host_and_port_.host(),
[email protected]8bd4e7a2014-08-09 14:49:171229 server_cert_verify_result_.is_issued_by_known_root,
1230 server_cert_verify_result_.public_key_hashes,
1231 &pinning_failure_log_)) {
1232 result = ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN;
1233 }
1234
[email protected]b9b651f2013-11-09 04:32:221235 if (result == OK) {
davidbeneb5f8ef32014-09-04 14:14:321236 // Only check Certificate Transparency if there were no other errors with
1237 // the connection.
1238 VerifyCT();
1239
[email protected]b9b651f2013-11-09 04:32:221240 // TODO(joth): Work out if we need to remember the intermediate CA certs
1241 // when the server sends them to us, and do so here.
[email protected]a8fed1742013-12-27 02:14:241242 SSLContext::GetInstance()->session_cache()->MarkSSLSessionAsGood(ssl_);
[email protected]e4738ba52014-08-07 10:07:221243 marked_session_as_good_ = true;
1244 CheckIfHandshakeFinished();
[email protected]b9b651f2013-11-09 04:32:221245 } else {
1246 DVLOG(1) << "DoVerifyCertComplete error " << ErrorToString(result)
1247 << " (" << result << ")";
1248 }
1249
[email protected]64b5c892014-08-08 09:39:261250 completed_connect_ = true;
[email protected]8bd4e7a2014-08-09 14:49:171251
[email protected]b9b651f2013-11-09 04:32:221252 // Exit DoHandshakeLoop and return the result to the caller to Connect.
1253 DCHECK_EQ(STATE_NONE, next_handshake_state_);
1254 return result;
1255}
1256
1257void SSLClientSocketOpenSSL::DoConnectCallback(int rv) {
[email protected]8e458552014-08-05 00:02:151258 if (rv < OK)
1259 OnHandshakeCompletion();
[email protected]b9b651f2013-11-09 04:32:221260 if (!user_connect_callback_.is_null()) {
1261 CompletionCallback c = user_connect_callback_;
1262 user_connect_callback_.Reset();
1263 c.Run(rv > OK ? OK : rv);
1264 }
1265}
1266
davidben30798ed82014-09-19 19:28:201267void SSLClientSocketOpenSSL::UpdateServerCert() {
vadimtc4e29112014-12-18 01:44:211268 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1269 tracked_objects::ScopedTracker tracking_profile(
1270 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1271 "424386 SSLClientSocketOpenSSL::UpdateServerCert"));
1272
[email protected]76e85392014-03-20 17:54:141273 server_cert_chain_->Reset(SSL_get_peer_cert_chain(ssl_));
vadimt5a243282014-12-24 00:26:161274
1275 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1276 tracked_objects::ScopedTracker tracking_profile1(
1277 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1278 "424386 SSLClientSocketOpenSSL::UpdateServerCert1"));
[email protected]7f38da8a2014-03-17 16:44:261279 server_cert_ = server_cert_chain_->AsOSChain();
[email protected]76e85392014-03-20 17:54:141280
davidben30798ed82014-09-19 19:28:201281 if (server_cert_.get()) {
1282 net_log_.AddEvent(
1283 NetLog::TYPE_SSL_CERTIFICATES_RECEIVED,
1284 base::Bind(&NetLogX509CertificateCallback,
1285 base::Unretained(server_cert_.get())));
davidbend1fb2f12014-11-08 02:51:001286
1287 // TODO(rsleevi): Plumb an OCSP response into the Mac system library and
1288 // update IsOCSPStaplingSupported for Mac. https://crbug.com/430714
1289 if (IsOCSPStaplingSupported()) {
1290#if defined(OS_WIN)
vadimt5a243282014-12-24 00:26:161291 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is
1292 // fixed.
1293 tracked_objects::ScopedTracker tracking_profile2(
1294 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1295 "424386 SSLClientSocketOpenSSL::UpdateServerCert2"));
1296
davidben54015aa2014-12-02 22:16:231297 const uint8_t* ocsp_response_raw;
davidbend1fb2f12014-11-08 02:51:001298 size_t ocsp_response_len;
1299 SSL_get0_ocsp_response(ssl_, &ocsp_response_raw, &ocsp_response_len);
1300
1301 CRYPT_DATA_BLOB ocsp_response_blob;
1302 ocsp_response_blob.cbData = ocsp_response_len;
davidben54015aa2014-12-02 22:16:231303 ocsp_response_blob.pbData = const_cast<BYTE*>(ocsp_response_raw);
davidbend1fb2f12014-11-08 02:51:001304 BOOL ok = CertSetCertificateContextProperty(
1305 server_cert_->os_cert_handle(),
1306 CERT_OCSP_RESPONSE_PROP_ID,
1307 CERT_SET_PROPERTY_IGNORE_PERSIST_ERROR_FLAG,
1308 &ocsp_response_blob);
1309 if (!ok) {
1310 VLOG(1) << "Failed to set OCSP response property: "
1311 << GetLastError();
1312 }
1313#else
1314 NOTREACHED();
1315#endif
1316 }
davidben30798ed82014-09-19 19:28:201317 }
[email protected]b9b651f2013-11-09 04:32:221318}
1319
davidbeneb5f8ef32014-09-04 14:14:321320void SSLClientSocketOpenSSL::VerifyCT() {
1321 if (!cert_transparency_verifier_)
1322 return;
1323
davidben54015aa2014-12-02 22:16:231324 const uint8_t* ocsp_response_raw;
davidbeneb5f8ef32014-09-04 14:14:321325 size_t ocsp_response_len;
1326 SSL_get0_ocsp_response(ssl_, &ocsp_response_raw, &ocsp_response_len);
1327 std::string ocsp_response;
1328 if (ocsp_response_len > 0) {
1329 ocsp_response.assign(reinterpret_cast<const char*>(ocsp_response_raw),
1330 ocsp_response_len);
1331 }
1332
davidben54015aa2014-12-02 22:16:231333 const uint8_t* sct_list_raw;
davidbeneb5f8ef32014-09-04 14:14:321334 size_t sct_list_len;
1335 SSL_get0_signed_cert_timestamp_list(ssl_, &sct_list_raw, &sct_list_len);
1336 std::string sct_list;
1337 if (sct_list_len > 0)
1338 sct_list.assign(reinterpret_cast<const char*>(sct_list_raw), sct_list_len);
1339
1340 // Note that this is a completely synchronous operation: The CT Log Verifier
1341 // gets all the data it needs for SCT verification and does not do any
1342 // external communication.
eranm6571b2b2014-12-03 15:53:231343 cert_transparency_verifier_->Verify(
1344 server_cert_verify_result_.verified_cert.get(), ocsp_response, sct_list,
1345 &ct_verify_result_, net_log_);
davidbeneb5f8ef32014-09-04 14:14:321346
eranm6571b2b2014-12-03 15:53:231347 if (!policy_enforcer_) {
1348 server_cert_verify_result_.cert_status &= ~CERT_STATUS_IS_EV;
1349 } else {
1350 if (server_cert_verify_result_.cert_status & CERT_STATUS_IS_EV) {
1351 scoped_refptr<ct::EVCertsWhitelist> ev_whitelist =
1352 SSLConfigService::GetEVCertsWhitelist();
1353 if (!policy_enforcer_->DoesConformToCTEVPolicy(
1354 server_cert_verify_result_.verified_cert.get(),
eranm18a019272014-12-18 08:43:231355 ev_whitelist.get(), ct_verify_result_, net_log_)) {
eranm6571b2b2014-12-03 15:53:231356 // TODO(eranm): Log via the BoundNetLog, see crbug.com/437766
1357 VLOG(1) << "EV certificate for "
1358 << server_cert_verify_result_.verified_cert->subject()
1359 .GetDisplayName()
1360 << " does not conform to CT policy, removing EV status.";
1361 server_cert_verify_result_.cert_status &= ~CERT_STATUS_IS_EV;
1362 }
1363 }
1364 }
davidbeneb5f8ef32014-09-04 14:14:321365}
1366
[email protected]b9b651f2013-11-09 04:32:221367void SSLClientSocketOpenSSL::OnHandshakeIOComplete(int result) {
1368 int rv = DoHandshakeLoop(result);
1369 if (rv != ERR_IO_PENDING) {
1370 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
1371 DoConnectCallback(rv);
1372 }
1373}
1374
1375void SSLClientSocketOpenSSL::OnSendComplete(int result) {
1376 if (next_handshake_state_ == STATE_HANDSHAKE) {
1377 // In handshake phase.
1378 OnHandshakeIOComplete(result);
1379 return;
1380 }
1381
1382 // OnSendComplete may need to call DoPayloadRead while the renegotiation
1383 // handshake is in progress.
1384 int rv_read = ERR_IO_PENDING;
1385 int rv_write = ERR_IO_PENDING;
1386 bool network_moved;
1387 do {
1388 if (user_read_buf_.get())
1389 rv_read = DoPayloadRead();
1390 if (user_write_buf_.get())
1391 rv_write = DoPayloadWrite();
1392 network_moved = DoTransportIO();
1393 } while (rv_read == ERR_IO_PENDING && rv_write == ERR_IO_PENDING &&
1394 (user_read_buf_.get() || user_write_buf_.get()) && network_moved);
1395
1396 // Performing the Read callback may cause |this| to be deleted. If this
1397 // happens, the Write callback should not be invoked. Guard against this by
1398 // holding a WeakPtr to |this| and ensuring it's still valid.
1399 base::WeakPtr<SSLClientSocketOpenSSL> guard(weak_factory_.GetWeakPtr());
1400 if (user_read_buf_.get() && rv_read != ERR_IO_PENDING)
1401 DoReadCallback(rv_read);
1402
1403 if (!guard.get())
1404 return;
1405
1406 if (user_write_buf_.get() && rv_write != ERR_IO_PENDING)
1407 DoWriteCallback(rv_write);
1408}
1409
1410void SSLClientSocketOpenSSL::OnRecvComplete(int result) {
1411 if (next_handshake_state_ == STATE_HANDSHAKE) {
1412 // In handshake phase.
1413 OnHandshakeIOComplete(result);
1414 return;
1415 }
1416
1417 // Network layer received some data, check if client requested to read
1418 // decrypted data.
1419 if (!user_read_buf_.get())
1420 return;
1421
davidben1b133ad2014-10-23 04:23:131422 int rv = DoReadLoop();
[email protected]b9b651f2013-11-09 04:32:221423 if (rv != ERR_IO_PENDING)
1424 DoReadCallback(rv);
1425}
1426
1427int SSLClientSocketOpenSSL::DoHandshakeLoop(int last_io_result) {
1428 int rv = last_io_result;
1429 do {
1430 // Default to STATE_NONE for next state.
1431 // (This is a quirk carried over from the windows
1432 // implementation. It makes reading the logs a bit harder.)
1433 // State handlers can and often do call GotoState just
1434 // to stay in the current state.
1435 State state = next_handshake_state_;
1436 GotoState(STATE_NONE);
1437 switch (state) {
1438 case STATE_HANDSHAKE:
1439 rv = DoHandshake();
1440 break;
[email protected]faff9852014-06-21 06:13:461441 case STATE_CHANNEL_ID_LOOKUP:
1442 DCHECK_EQ(OK, rv);
1443 rv = DoChannelIDLookup();
1444 break;
1445 case STATE_CHANNEL_ID_LOOKUP_COMPLETE:
1446 rv = DoChannelIDLookupComplete(rv);
1447 break;
[email protected]b9b651f2013-11-09 04:32:221448 case STATE_VERIFY_CERT:
[email protected]faff9852014-06-21 06:13:461449 DCHECK_EQ(OK, rv);
[email protected]b9b651f2013-11-09 04:32:221450 rv = DoVerifyCert(rv);
1451 break;
1452 case STATE_VERIFY_CERT_COMPLETE:
1453 rv = DoVerifyCertComplete(rv);
1454 break;
1455 case STATE_NONE:
1456 default:
1457 rv = ERR_UNEXPECTED;
1458 NOTREACHED() << "unexpected state" << state;
1459 break;
1460 }
1461
1462 bool network_moved = DoTransportIO();
1463 if (network_moved && next_handshake_state_ == STATE_HANDSHAKE) {
1464 // In general we exit the loop if rv is ERR_IO_PENDING. In this
1465 // special case we keep looping even if rv is ERR_IO_PENDING because
1466 // the transport IO may allow DoHandshake to make progress.
1467 rv = OK; // This causes us to stay in the loop.
1468 }
1469 } while (rv != ERR_IO_PENDING && next_handshake_state_ != STATE_NONE);
[email protected]8e458552014-08-05 00:02:151470
[email protected]b9b651f2013-11-09 04:32:221471 return rv;
1472}
1473
davidben1b133ad2014-10-23 04:23:131474int SSLClientSocketOpenSSL::DoReadLoop() {
[email protected]b9b651f2013-11-09 04:32:221475 bool network_moved;
1476 int rv;
1477 do {
1478 rv = DoPayloadRead();
1479 network_moved = DoTransportIO();
1480 } while (rv == ERR_IO_PENDING && network_moved);
1481
1482 return rv;
1483}
1484
davidben1b133ad2014-10-23 04:23:131485int SSLClientSocketOpenSSL::DoWriteLoop() {
[email protected]b9b651f2013-11-09 04:32:221486 bool network_moved;
1487 int rv;
1488 do {
1489 rv = DoPayloadWrite();
1490 network_moved = DoTransportIO();
1491 } while (rv == ERR_IO_PENDING && network_moved);
1492
1493 return rv;
1494}
1495
1496int SSLClientSocketOpenSSL::DoPayloadRead() {
1497 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1498
1499 int rv;
1500 if (pending_read_error_ != kNoPendingReadResult) {
1501 rv = pending_read_error_;
1502 pending_read_error_ = kNoPendingReadResult;
1503 if (rv == 0) {
1504 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED,
1505 rv, user_read_buf_->data());
davidbenb8c23212014-10-28 00:12:161506 } else {
1507 net_log_.AddEvent(
1508 NetLog::TYPE_SSL_READ_ERROR,
1509 CreateNetLogOpenSSLErrorCallback(rv, pending_read_ssl_error_,
1510 pending_read_error_info_));
[email protected]b9b651f2013-11-09 04:32:221511 }
davidbenb8c23212014-10-28 00:12:161512 pending_read_ssl_error_ = SSL_ERROR_NONE;
1513 pending_read_error_info_ = OpenSSLErrorInfo();
[email protected]b9b651f2013-11-09 04:32:221514 return rv;
1515 }
1516
1517 int total_bytes_read = 0;
1518 do {
1519 rv = SSL_read(ssl_, user_read_buf_->data() + total_bytes_read,
1520 user_read_buf_len_ - total_bytes_read);
1521 if (rv > 0)
1522 total_bytes_read += rv;
1523 } while (total_bytes_read < user_read_buf_len_ && rv > 0);
1524
1525 if (total_bytes_read == user_read_buf_len_) {
1526 rv = total_bytes_read;
1527 } else {
1528 // Otherwise, an error occurred (rv <= 0). The error needs to be handled
1529 // immediately, while the OpenSSL errors are still available in
1530 // thread-local storage. However, the handled/remapped error code should
1531 // only be returned if no application data was already read; if it was, the
1532 // error code should be deferred until the next call of DoPayloadRead.
1533 //
1534 // If no data was read, |*next_result| will point to the return value of
1535 // this function. If at least some data was read, |*next_result| will point
1536 // to |pending_read_error_|, to be returned in a future call to
1537 // DoPayloadRead() (e.g.: after the current data is handled).
1538 int *next_result = &rv;
1539 if (total_bytes_read > 0) {
1540 pending_read_error_ = rv;
1541 rv = total_bytes_read;
1542 next_result = &pending_read_error_;
1543 }
1544
1545 if (client_auth_cert_needed_) {
1546 *next_result = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
1547 } else if (*next_result < 0) {
davidbenb8c23212014-10-28 00:12:161548 pending_read_ssl_error_ = SSL_get_error(ssl_, *next_result);
1549 *next_result = MapOpenSSLErrorWithDetails(pending_read_ssl_error_,
1550 err_tracer,
1551 &pending_read_error_info_);
davidbenbe6ce7ec2014-10-20 19:15:561552
1553 // Many servers do not reliably send a close_notify alert when shutting
1554 // down a connection, and instead terminate the TCP connection. This is
1555 // reported as ERR_CONNECTION_CLOSED. Because of this, map the unclean
1556 // shutdown to a graceful EOF, instead of treating it as an error as it
1557 // should be.
1558 if (*next_result == ERR_CONNECTION_CLOSED)
1559 *next_result = 0;
1560
[email protected]b9b651f2013-11-09 04:32:221561 if (rv > 0 && *next_result == ERR_IO_PENDING) {
1562 // If at least some data was read from SSL_read(), do not treat
1563 // insufficient data as an error to return in the next call to
1564 // DoPayloadRead() - instead, let the call fall through to check
1565 // SSL_read() again. This is because DoTransportIO() may complete
1566 // in between the next call to DoPayloadRead(), and thus it is
1567 // important to check SSL_read() on subsequent invocations to see
1568 // if a complete record may now be read.
1569 *next_result = kNoPendingReadResult;
1570 }
1571 }
1572 }
1573
1574 if (rv >= 0) {
1575 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, rv,
1576 user_read_buf_->data());
davidbenb8c23212014-10-28 00:12:161577 } else if (rv != ERR_IO_PENDING) {
1578 net_log_.AddEvent(
1579 NetLog::TYPE_SSL_READ_ERROR,
1580 CreateNetLogOpenSSLErrorCallback(rv, pending_read_ssl_error_,
1581 pending_read_error_info_));
1582 pending_read_ssl_error_ = SSL_ERROR_NONE;
1583 pending_read_error_info_ = OpenSSLErrorInfo();
[email protected]b9b651f2013-11-09 04:32:221584 }
1585 return rv;
1586}
1587
1588int SSLClientSocketOpenSSL::DoPayloadWrite() {
1589 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1590 int rv = SSL_write(ssl_, user_write_buf_->data(), user_write_buf_len_);
[email protected]b9b651f2013-11-09 04:32:221591 if (rv >= 0) {
1592 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_SENT, rv,
1593 user_write_buf_->data());
1594 return rv;
1595 }
1596
davidbenb8c23212014-10-28 00:12:161597 int ssl_error = SSL_get_error(ssl_, rv);
1598 OpenSSLErrorInfo error_info;
1599 int net_error = MapOpenSSLErrorWithDetails(ssl_error, err_tracer,
1600 &error_info);
1601
1602 if (net_error != ERR_IO_PENDING) {
1603 net_log_.AddEvent(
1604 NetLog::TYPE_SSL_WRITE_ERROR,
1605 CreateNetLogOpenSSLErrorCallback(net_error, ssl_error, error_info));
1606 }
1607 return net_error;
[email protected]b9b651f2013-11-09 04:32:221608}
1609
1610int SSLClientSocketOpenSSL::BufferSend(void) {
1611 if (transport_send_busy_)
1612 return ERR_IO_PENDING;
1613
haavardm2d92e722014-12-19 13:45:441614 size_t buffer_read_offset;
1615 uint8_t* read_buf;
1616 size_t max_read;
1617 int status = BIO_zero_copy_get_read_buf(transport_bio_, &read_buf,
1618 &buffer_read_offset, &max_read);
1619 DCHECK_EQ(status, 1); // Should never fail.
1620 if (!max_read)
1621 return 0; // Nothing pending in the OpenSSL write BIO.
1622 CHECK_EQ(read_buf, reinterpret_cast<uint8_t*>(send_buffer_->StartOfBuffer()));
1623 CHECK_LT(buffer_read_offset, static_cast<size_t>(send_buffer_->capacity()));
1624 send_buffer_->set_offset(buffer_read_offset);
[email protected]b9b651f2013-11-09 04:32:221625
1626 int rv = transport_->socket()->Write(
haavardm2d92e722014-12-19 13:45:441627 send_buffer_.get(), max_read,
[email protected]b9b651f2013-11-09 04:32:221628 base::Bind(&SSLClientSocketOpenSSL::BufferSendComplete,
1629 base::Unretained(this)));
1630 if (rv == ERR_IO_PENDING) {
1631 transport_send_busy_ = true;
1632 } else {
1633 TransportWriteComplete(rv);
1634 }
1635 return rv;
1636}
1637
1638int SSLClientSocketOpenSSL::BufferRecv(void) {
1639 if (transport_recv_busy_)
1640 return ERR_IO_PENDING;
1641
1642 // Determine how much was requested from |transport_bio_| that was not
1643 // actually available.
1644 size_t requested = BIO_ctrl_get_read_request(transport_bio_);
1645 if (requested == 0) {
1646 // This is not a perfect match of error codes, as no operation is
1647 // actually pending. However, returning 0 would be interpreted as
1648 // a possible sign of EOF, which is also an inappropriate match.
1649 return ERR_IO_PENDING;
1650 }
1651
1652 // Known Issue: While only reading |requested| data is the more correct
1653 // implementation, it has the downside of resulting in frequent reads:
1654 // One read for the SSL record header (~5 bytes) and one read for the SSL
1655 // record body. Rather than issuing these reads to the underlying socket
1656 // (and constantly allocating new IOBuffers), a single Read() request to
1657 // fill |transport_bio_| is issued. As long as an SSL client socket cannot
1658 // be gracefully shutdown (via SSL close alerts) and re-used for non-SSL
1659 // traffic, this over-subscribed Read()ing will not cause issues.
haavardm2d92e722014-12-19 13:45:441660
1661 size_t buffer_write_offset;
1662 uint8_t* write_buf;
1663 size_t max_write;
1664 int status = BIO_zero_copy_get_write_buf(transport_bio_, &write_buf,
1665 &buffer_write_offset, &max_write);
1666 DCHECK_EQ(status, 1); // Should never fail.
[email protected]b9b651f2013-11-09 04:32:221667 if (!max_write)
1668 return ERR_IO_PENDING;
1669
haavardm2d92e722014-12-19 13:45:441670 CHECK_EQ(write_buf,
1671 reinterpret_cast<uint8_t*>(recv_buffer_->StartOfBuffer()));
1672 CHECK_LT(buffer_write_offset, static_cast<size_t>(recv_buffer_->capacity()));
1673
1674 recv_buffer_->set_offset(buffer_write_offset);
[email protected]b9b651f2013-11-09 04:32:221675 int rv = transport_->socket()->Read(
1676 recv_buffer_.get(),
1677 max_write,
1678 base::Bind(&SSLClientSocketOpenSSL::BufferRecvComplete,
1679 base::Unretained(this)));
1680 if (rv == ERR_IO_PENDING) {
1681 transport_recv_busy_ = true;
1682 } else {
[email protected]3e5c6922014-02-06 02:42:161683 rv = TransportReadComplete(rv);
[email protected]b9b651f2013-11-09 04:32:221684 }
1685 return rv;
1686}
1687
1688void SSLClientSocketOpenSSL::BufferSendComplete(int result) {
[email protected]b9b651f2013-11-09 04:32:221689 TransportWriteComplete(result);
1690 OnSendComplete(result);
1691}
1692
1693void SSLClientSocketOpenSSL::BufferRecvComplete(int result) {
[email protected]3e5c6922014-02-06 02:42:161694 result = TransportReadComplete(result);
[email protected]b9b651f2013-11-09 04:32:221695 OnRecvComplete(result);
1696}
1697
1698void SSLClientSocketOpenSSL::TransportWriteComplete(int result) {
1699 DCHECK(ERR_IO_PENDING != result);
haavardm2d92e722014-12-19 13:45:441700 int bytes_written = 0;
[email protected]b9b651f2013-11-09 04:32:221701 if (result < 0) {
[email protected]5aea79182014-07-14 20:43:411702 // Record the error. Save it to be reported in a future read or write on
1703 // transport_bio_'s peer.
[email protected]3e5c6922014-02-06 02:42:161704 transport_write_error_ = result;
[email protected]b9b651f2013-11-09 04:32:221705 } else {
haavardm2d92e722014-12-19 13:45:441706 bytes_written = result;
[email protected]b9b651f2013-11-09 04:32:221707 }
haavardm2d92e722014-12-19 13:45:441708 DCHECK_GE(send_buffer_->RemainingCapacity(), bytes_written);
1709 int ret = BIO_zero_copy_get_read_buf_done(transport_bio_, bytes_written);
1710 DCHECK_EQ(1, ret);
1711 transport_send_busy_ = false;
[email protected]b9b651f2013-11-09 04:32:221712}
1713
[email protected]3e5c6922014-02-06 02:42:161714int SSLClientSocketOpenSSL::TransportReadComplete(int result) {
[email protected]b9b651f2013-11-09 04:32:221715 DCHECK(ERR_IO_PENDING != result);
[email protected]5aea79182014-07-14 20:43:411716 // If an EOF, canonicalize to ERR_CONNECTION_CLOSED here so MapOpenSSLError
1717 // does not report success.
1718 if (result == 0)
1719 result = ERR_CONNECTION_CLOSED;
haavardm2d92e722014-12-19 13:45:441720 int bytes_read = 0;
[email protected]5aea79182014-07-14 20:43:411721 if (result < 0) {
[email protected]b9b651f2013-11-09 04:32:221722 DVLOG(1) << "TransportReadComplete result " << result;
[email protected]5aea79182014-07-14 20:43:411723 // Received an error. Save it to be reported in a future read on
1724 // transport_bio_'s peer.
1725 transport_read_error_ = result;
[email protected]b9b651f2013-11-09 04:32:221726 } else {
haavardm2d92e722014-12-19 13:45:441727 bytes_read = result;
[email protected]b9b651f2013-11-09 04:32:221728 }
haavardm2d92e722014-12-19 13:45:441729 DCHECK_GE(recv_buffer_->RemainingCapacity(), bytes_read);
1730 int ret = BIO_zero_copy_get_write_buf_done(transport_bio_, bytes_read);
1731 DCHECK_EQ(1, ret);
[email protected]b9b651f2013-11-09 04:32:221732 transport_recv_busy_ = false;
[email protected]3e5c6922014-02-06 02:42:161733 return result;
[email protected]b9b651f2013-11-09 04:32:221734}
1735
[email protected]82c59022014-08-15 09:38:271736int SSLClientSocketOpenSSL::ClientCertRequestCallback(SSL* ssl) {
vadimtb2a77c762014-11-21 19:49:221737 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1738 tracked_objects::ScopedTracker tracking_profile(
1739 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1740 "424386 SSLClientSocketOpenSSL::ClientCertRequestCallback"));
1741
[email protected]5ac981e182010-12-06 17:56:271742 DVLOG(3) << "OpenSSL ClientCertRequestCallback called";
1743 DCHECK(ssl == ssl_);
[email protected]82c59022014-08-15 09:38:271744
davidbenaf42cbe2014-11-13 03:27:461745 net_log_.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED);
1746
[email protected]82c59022014-08-15 09:38:271747 // Clear any currently configured certificates.
1748 SSL_certs_clear(ssl_);
[email protected]97a854f2014-07-29 07:51:361749
1750#if defined(OS_IOS)
1751 // TODO(droger): Support client auth on iOS. See http://crbug.com/145954).
1752 LOG(WARNING) << "Client auth is not supported";
1753#else // !defined(OS_IOS)
[email protected]5ac981e182010-12-06 17:56:271754 if (!ssl_config_.send_client_cert) {
[email protected]515adc22013-01-09 16:01:231755 // First pass: we know that a client certificate is needed, but we do not
1756 // have one at hand.
[email protected]5ac981e182010-12-06 17:56:271757 client_auth_cert_needed_ = true;
[email protected]515adc22013-01-09 16:01:231758 STACK_OF(X509_NAME) *authorities = SSL_get_client_CA_list(ssl);
[email protected]edfd0f42014-07-22 18:20:371759 for (size_t i = 0; i < sk_X509_NAME_num(authorities); i++) {
[email protected]515adc22013-01-09 16:01:231760 X509_NAME *ca_name = (X509_NAME *)sk_X509_NAME_value(authorities, i);
1761 unsigned char* str = NULL;
1762 int length = i2d_X509_NAME(ca_name, &str);
1763 cert_authorities_.push_back(std::string(
1764 reinterpret_cast<const char*>(str),
1765 static_cast<size_t>(length)));
1766 OPENSSL_free(str);
1767 }
1768
[email protected]c0787702014-05-20 21:51:441769 const unsigned char* client_cert_types;
[email protected]e7e883e2014-07-25 06:03:081770 size_t num_client_cert_types =
1771 SSL_get0_certificate_types(ssl, &client_cert_types);
[email protected]c0787702014-05-20 21:51:441772 for (size_t i = 0; i < num_client_cert_types; i++) {
1773 cert_key_types_.push_back(
1774 static_cast<SSLClientCertType>(client_cert_types[i]));
1775 }
1776
[email protected]5ac981e182010-12-06 17:56:271777 return -1; // Suspends handshake.
1778 }
1779
1780 // Second pass: a client certificate should have been selected.
[email protected]13914c92013-06-13 22:42:421781 if (ssl_config_.client_cert.get()) {
[email protected]6bad5052014-07-12 01:25:131782 ScopedX509 leaf_x509 =
1783 OSCertHandleToOpenSSL(ssl_config_.client_cert->os_cert_handle());
1784 if (!leaf_x509) {
1785 LOG(WARNING) << "Failed to import certificate";
1786 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT);
1787 return -1;
1788 }
1789
[email protected]82c59022014-08-15 09:38:271790 ScopedX509Stack chain = OSCertHandlesToOpenSSL(
1791 ssl_config_.client_cert->GetIntermediateCertificates());
1792 if (!chain) {
1793 LOG(WARNING) << "Failed to import intermediate certificates";
1794 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT);
1795 return -1;
1796 }
1797
[email protected]97a854f2014-07-29 07:51:361798 // TODO(davidben): With Linux client auth support, this should be
1799 // conditioned on OS_ANDROID and then, with https://crbug.com/394131,
1800 // removed altogether. OpenSSLClientKeyStore is mostly an artifact of the
1801 // net/ client auth API lacking a private key handle.
[email protected]c0787702014-05-20 21:51:441802#if defined(USE_OPENSSL_CERTS)
[email protected]97a854f2014-07-29 07:51:361803 crypto::ScopedEVP_PKEY privkey =
1804 OpenSSLClientKeyStore::GetInstance()->FetchClientCertPrivateKey(
1805 ssl_config_.client_cert.get());
1806#else // !defined(USE_OPENSSL_CERTS)
1807 crypto::ScopedEVP_PKEY privkey =
1808 FetchClientCertPrivateKey(ssl_config_.client_cert.get());
1809#endif // defined(USE_OPENSSL_CERTS)
1810 if (!privkey) {
[email protected]6bad5052014-07-12 01:25:131811 // Could not find the private key. Fail the handshake and surface an
1812 // appropriate error to the caller.
1813 LOG(WARNING) << "Client cert found without private key";
1814 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY);
1815 return -1;
[email protected]0c6523f2010-12-10 10:56:241816 }
[email protected]6bad5052014-07-12 01:25:131817
[email protected]82c59022014-08-15 09:38:271818 if (!SSL_use_certificate(ssl_, leaf_x509.get()) ||
1819 !SSL_use_PrivateKey(ssl_, privkey.get()) ||
1820 !SSL_set1_chain(ssl_, chain.get())) {
1821 LOG(WARNING) << "Failed to set client certificate";
1822 return -1;
1823 }
davidbenaf42cbe2014-11-13 03:27:461824
1825 int cert_count = 1 + sk_X509_num(chain.get());
1826 net_log_.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED,
1827 NetLog::IntegerCallback("cert_count", cert_count));
[email protected]6bad5052014-07-12 01:25:131828 return 1;
[email protected]c0787702014-05-20 21:51:441829 }
[email protected]97a854f2014-07-29 07:51:361830#endif // defined(OS_IOS)
[email protected]5ac981e182010-12-06 17:56:271831
1832 // Send no client certificate.
davidbenaf42cbe2014-11-13 03:27:461833 net_log_.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED,
1834 NetLog::IntegerCallback("cert_count", 0));
[email protected]82c59022014-08-15 09:38:271835 return 1;
[email protected]5ac981e182010-12-06 17:56:271836}
1837
[email protected]b051cdb62014-02-28 02:20:161838int SSLClientSocketOpenSSL::CertVerifyCallback(X509_STORE_CTX* store_ctx) {
vadimtb2a77c762014-11-21 19:49:221839 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1840 tracked_objects::ScopedTracker tracking_profile(
1841 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1842 "424386 SSLClientSocketOpenSSL::CertVerifyCallback"));
1843
[email protected]64b5c892014-08-08 09:39:261844 if (!completed_connect_) {
[email protected]b051cdb62014-02-28 02:20:161845 // If the first handshake hasn't completed then we accept any certificates
1846 // because we verify after the handshake.
1847 return 1;
1848 }
1849
davidben30798ed82014-09-19 19:28:201850 // Disallow the server certificate to change in a renegotiation.
1851 if (server_cert_chain_->empty()) {
[email protected]76e85392014-03-20 17:54:141852 LOG(ERROR) << "Received invalid certificate chain between handshakes";
davidben30798ed82014-09-19 19:28:201853 return 0;
1854 }
1855 base::StringPiece old_der, new_der;
1856 if (store_ctx->cert == NULL ||
1857 !x509_util::GetDER(server_cert_chain_->Get(0), &old_der) ||
1858 !x509_util::GetDER(store_ctx->cert, &new_der)) {
1859 LOG(ERROR) << "Failed to encode certificates";
1860 return 0;
1861 }
1862 if (old_der != new_der) {
[email protected]76e85392014-03-20 17:54:141863 LOG(ERROR) << "Server certificate changed between handshakes";
davidben30798ed82014-09-19 19:28:201864 return 0;
1865 }
1866
1867 return 1;
[email protected]b051cdb62014-02-28 02:20:161868}
1869
[email protected]ae7c9f42011-11-21 11:41:161870// SelectNextProtoCallback is called by OpenSSL during the handshake. If the
1871// server supports NPN, selects a protocol from the list that the server
1872// provides. According to third_party/openssl/openssl/ssl/ssl_lib.c, the
1873// callback can assume that |in| is syntactically valid.
[email protected]ea4a1c6a2010-12-09 13:33:281874int SSLClientSocketOpenSSL::SelectNextProtoCallback(unsigned char** out,
1875 unsigned char* outlen,
1876 const unsigned char* in,
1877 unsigned int inlen) {
vadimtb2a77c762014-11-21 19:49:221878 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1879 tracked_objects::ScopedTracker tracking_profile(
1880 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1881 "424386 SSLClientSocketOpenSSL::SelectNextProtoCallback"));
1882
[email protected]ea4a1c6a2010-12-09 13:33:281883 if (ssl_config_.next_protos.empty()) {
[email protected]168a8412012-06-14 05:05:491884 *out = reinterpret_cast<uint8*>(
1885 const_cast<char*>(kDefaultSupportedNPNProtocol));
1886 *outlen = arraysize(kDefaultSupportedNPNProtocol) - 1;
1887 npn_status_ = kNextProtoUnsupported;
[email protected]ea4a1c6a2010-12-09 13:33:281888 return SSL_TLSEXT_ERR_OK;
1889 }
1890
[email protected]ae7c9f42011-11-21 11:41:161891 // Assume there's no overlap between our protocols and the server's list.
[email protected]168a8412012-06-14 05:05:491892 npn_status_ = kNextProtoNoOverlap;
[email protected]ae7c9f42011-11-21 11:41:161893
1894 // For each protocol in server preference order, see if we support it.
1895 for (unsigned int i = 0; i < inlen; i += in[i] + 1) {
bnc0d23cf42014-12-11 14:09:461896 for (NextProto next_proto : ssl_config_.next_protos) {
1897 const std::string proto = NextProtoToString(next_proto);
1898 if (in[i] == proto.size() &&
1899 memcmp(&in[i + 1], proto.data(), in[i]) == 0) {
[email protected]168a8412012-06-14 05:05:491900 // We found a match.
[email protected]ae7c9f42011-11-21 11:41:161901 *out = const_cast<unsigned char*>(in) + i + 1;
1902 *outlen = in[i];
[email protected]168a8412012-06-14 05:05:491903 npn_status_ = kNextProtoNegotiated;
[email protected]ae7c9f42011-11-21 11:41:161904 break;
1905 }
1906 }
[email protected]168a8412012-06-14 05:05:491907 if (npn_status_ == kNextProtoNegotiated)
[email protected]ae7c9f42011-11-21 11:41:161908 break;
1909 }
[email protected]ea4a1c6a2010-12-09 13:33:281910
[email protected]168a8412012-06-14 05:05:491911 // If we didn't find a protocol, we select the first one from our list.
1912 if (npn_status_ == kNextProtoNoOverlap) {
bnc67da3de2015-01-15 21:02:261913 // NextProtoToString returns a pointer to a static string.
1914 const char* proto = NextProtoToString(ssl_config_.next_protos[0]);
1915 *out = reinterpret_cast<unsigned char*>(const_cast<char*>(proto));
1916 *outlen = strlen(proto);
[email protected]168a8412012-06-14 05:05:491917 }
1918
[email protected]ea4a1c6a2010-12-09 13:33:281919 npn_proto_.assign(reinterpret_cast<const char*>(*out), *outlen);
[email protected]32e1dee2010-12-09 18:36:241920 DVLOG(2) << "next protocol: '" << npn_proto_ << "' status: " << npn_status_;
bnc0d28ea52014-10-13 15:15:381921 set_negotiation_extension(kExtensionNPN);
[email protected]ea4a1c6a2010-12-09 13:33:281922 return SSL_TLSEXT_ERR_OK;
1923}
1924
[email protected]5aea79182014-07-14 20:43:411925long SSLClientSocketOpenSSL::MaybeReplayTransportError(
1926 BIO *bio,
1927 int cmd,
1928 const char *argp, int argi, long argl,
1929 long retvalue) {
1930 if (cmd == (BIO_CB_READ|BIO_CB_RETURN) && retvalue <= 0) {
1931 // If there is no more data in the buffer, report any pending errors that
1932 // were observed. Note that both the readbuf and the writebuf are checked
1933 // for errors, since the application may have encountered a socket error
1934 // while writing that would otherwise not be reported until the application
1935 // attempted to write again - which it may never do. See
1936 // https://crbug.com/249848.
1937 if (transport_read_error_ != OK) {
1938 OpenSSLPutNetError(FROM_HERE, transport_read_error_);
1939 return -1;
1940 }
1941 if (transport_write_error_ != OK) {
1942 OpenSSLPutNetError(FROM_HERE, transport_write_error_);
1943 return -1;
1944 }
1945 } else if (cmd == BIO_CB_WRITE) {
1946 // Because of the write buffer, this reports a failure from the previous
1947 // write payload. If the current payload fails to write, the error will be
1948 // reported in a future write or read to |bio|.
1949 if (transport_write_error_ != OK) {
1950 OpenSSLPutNetError(FROM_HERE, transport_write_error_);
1951 return -1;
1952 }
1953 }
1954 return retvalue;
1955}
1956
1957// static
1958long SSLClientSocketOpenSSL::BIOCallback(
1959 BIO *bio,
1960 int cmd,
1961 const char *argp, int argi, long argl,
1962 long retvalue) {
vadimta1d0d9762014-12-18 00:23:341963 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1964 tracked_objects::ScopedTracker tracking_profile(
1965 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1966 "424386 SSLClientSocketOpenSSL::BIOCallback"));
1967
[email protected]5aea79182014-07-14 20:43:411968 SSLClientSocketOpenSSL* socket = reinterpret_cast<SSLClientSocketOpenSSL*>(
1969 BIO_get_callback_arg(bio));
1970 CHECK(socket);
1971 return socket->MaybeReplayTransportError(
1972 bio, cmd, argp, argi, argl, retvalue);
1973}
1974
[email protected]64b5c892014-08-08 09:39:261975// static
1976void SSLClientSocketOpenSSL::InfoCallback(const SSL* ssl,
1977 int type,
1978 int /*val*/) {
vadimta1d0d9762014-12-18 00:23:341979 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1980 tracked_objects::ScopedTracker tracking_profile(
1981 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1982 "424386 SSLClientSocketOpenSSL::InfoCallback"));
1983
[email protected]64b5c892014-08-08 09:39:261984 if (type == SSL_CB_HANDSHAKE_DONE) {
1985 SSLClientSocketOpenSSL* ssl_socket =
1986 SSLContext::GetInstance()->GetClientSocketFromSSL(ssl);
1987 ssl_socket->handshake_succeeded_ = true;
1988 ssl_socket->CheckIfHandshakeFinished();
1989 }
1990}
1991
1992// Determines if both the handshake and certificate verification have completed
1993// successfully, and calls the handshake completion callback if that is the
1994// case.
1995//
1996// CheckIfHandshakeFinished is called twice per connection: once after
1997// MarkSSLSessionAsGood, when the certificate has been verified, and
1998// once via an OpenSSL callback when the handshake has completed. On the
1999// second call, when the certificate has been verified and the handshake
2000// has completed, the connection's handshake completion callback is run.
2001void SSLClientSocketOpenSSL::CheckIfHandshakeFinished() {
2002 if (handshake_succeeded_ && marked_session_as_good_)
2003 OnHandshakeCompletion();
2004}
2005
davidbeneb5f8ef32014-09-04 14:14:322006void SSLClientSocketOpenSSL::AddSCTInfoToSSLInfo(SSLInfo* ssl_info) const {
2007 for (ct::SCTList::const_iterator iter =
2008 ct_verify_result_.verified_scts.begin();
2009 iter != ct_verify_result_.verified_scts.end(); ++iter) {
2010 ssl_info->signed_certificate_timestamps.push_back(
2011 SignedCertificateTimestampAndStatus(*iter, ct::SCT_STATUS_OK));
2012 }
2013 for (ct::SCTList::const_iterator iter =
2014 ct_verify_result_.invalid_scts.begin();
2015 iter != ct_verify_result_.invalid_scts.end(); ++iter) {
2016 ssl_info->signed_certificate_timestamps.push_back(
2017 SignedCertificateTimestampAndStatus(*iter, ct::SCT_STATUS_INVALID));
2018 }
2019 for (ct::SCTList::const_iterator iter =
2020 ct_verify_result_.unknown_logs_scts.begin();
2021 iter != ct_verify_result_.unknown_logs_scts.end(); ++iter) {
2022 ssl_info->signed_certificate_timestamps.push_back(
2023 SignedCertificateTimestampAndStatus(*iter,
2024 ct::SCT_STATUS_LOG_UNKNOWN));
2025 }
2026}
2027
[email protected]7f38da8a2014-03-17 16:44:262028scoped_refptr<X509Certificate>
2029SSLClientSocketOpenSSL::GetUnverifiedServerCertificateChain() const {
2030 return server_cert_;
2031}
2032
[email protected]7e5dd49f2010-12-08 18:33:492033} // namespace net