blob: 34ddeb8d929b3dfc8788485e5048007caf28752e [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"
davidbenc879af02015-02-20 07:57:2138#include "net/ssl/scoped_openssl_types.h"
[email protected]536fd0b2013-03-14 17:41:5739#include "net/ssl/ssl_cert_request_info.h"
40#include "net/ssl/ssl_connection_status_flags.h"
41#include "net/ssl/ssl_info.h"
[email protected]d518cd92010-09-29 12:27:4442
davidben8ecc3072014-09-03 23:19:0943#if defined(OS_WIN)
44#include "base/win/windows_version.h"
45#endif
46
[email protected]97a854f2014-07-29 07:51:3647#if defined(USE_OPENSSL_CERTS)
48#include "net/ssl/openssl_client_key_store.h"
49#else
50#include "net/ssl/openssl_platform_key.h"
51#endif
52
[email protected]d518cd92010-09-29 12:27:4453namespace net {
54
55namespace {
56
57// Enable this to see logging for state machine state transitions.
58#if 0
[email protected]3b112772010-10-04 10:54:4959#define GotoState(s) do { DVLOG(2) << (void *)this << " " << __FUNCTION__ << \
[email protected]d518cd92010-09-29 12:27:4460 " jump to state " << s; \
61 next_handshake_state_ = s; } while (0)
62#else
63#define GotoState(s) next_handshake_state_ = s
64#endif
65
[email protected]4b768562013-02-16 04:10:0766// This constant can be any non-negative/non-zero value (eg: it does not
67// overlap with any value of the net::Error range, including net::OK).
68const int kNoPendingReadResult = 1;
69
[email protected]168a8412012-06-14 05:05:4970// If a client doesn't have a list of protocols that it supports, but
71// the server supports NPN, choosing "http/1.1" is the best answer.
72const char kDefaultSupportedNPNProtocol[] = "http/1.1";
73
haavardm2d92e722014-12-19 13:45:4474// Default size of the internal BoringSSL buffers.
75const int KDefaultOpenSSLBufferSize = 17 * 1024;
76
[email protected]82c59022014-08-15 09:38:2777void FreeX509Stack(STACK_OF(X509)* ptr) {
78 sk_X509_pop_free(ptr, X509_free);
79}
80
davidbene94fe0962015-02-21 00:51:3381using ScopedX509Stack = crypto::ScopedOpenSSL<STACK_OF(X509), FreeX509Stack>;
[email protected]6bad5052014-07-12 01:25:1382
[email protected]89038152012-09-07 06:30:1783#if OPENSSL_VERSION_NUMBER < 0x1000103fL
84// This method doesn't seem to have made it into the OpenSSL headers.
[email protected]109805a2010-12-07 18:17:0685unsigned long SSL_CIPHER_get_id(const SSL_CIPHER* cipher) { return cipher->id; }
[email protected]89038152012-09-07 06:30:1786#endif
[email protected]109805a2010-12-07 18:17:0687
88// Used for encoding the |connection_status| field of an SSLInfo object.
pkasting6b68a162014-12-01 22:10:2989int EncodeSSLConnectionStatus(uint16 cipher_suite,
[email protected]109805a2010-12-07 18:17:0690 int compression,
91 int version) {
pkasting6b68a162014-12-01 22:10:2992 return cipher_suite |
[email protected]109805a2010-12-07 18:17:0693 ((compression & SSL_CONNECTION_COMPRESSION_MASK) <<
94 SSL_CONNECTION_COMPRESSION_SHIFT) |
95 ((version & SSL_CONNECTION_VERSION_MASK) <<
96 SSL_CONNECTION_VERSION_SHIFT);
97}
98
99// Returns the net SSL version number (see ssl_connection_status_flags.h) for
100// this SSL connection.
101int GetNetSSLVersion(SSL* ssl) {
[email protected]7e5dd49f2010-12-08 18:33:49102 switch (SSL_version(ssl)) {
[email protected]109805a2010-12-07 18:17:06103 case SSL2_VERSION:
104 return SSL_CONNECTION_VERSION_SSL2;
105 case SSL3_VERSION:
106 return SSL_CONNECTION_VERSION_SSL3;
107 case TLS1_VERSION:
108 return SSL_CONNECTION_VERSION_TLS1;
davidben1d094022014-11-05 18:55:47109 case TLS1_1_VERSION:
[email protected]109805a2010-12-07 18:17:06110 return SSL_CONNECTION_VERSION_TLS1_1;
davidben1d094022014-11-05 18:55:47111 case TLS1_2_VERSION:
[email protected]109805a2010-12-07 18:17:06112 return SSL_CONNECTION_VERSION_TLS1_2;
113 default:
114 return SSL_CONNECTION_VERSION_UNKNOWN;
115 }
116}
117
[email protected]6bad5052014-07-12 01:25:13118ScopedX509 OSCertHandleToOpenSSL(
119 X509Certificate::OSCertHandle os_handle) {
120#if defined(USE_OPENSSL_CERTS)
121 return ScopedX509(X509Certificate::DupOSCertHandle(os_handle));
122#else // !defined(USE_OPENSSL_CERTS)
123 std::string der_encoded;
124 if (!X509Certificate::GetDEREncoded(os_handle, &der_encoded))
125 return ScopedX509();
126 const uint8_t* bytes = reinterpret_cast<const uint8_t*>(der_encoded.data());
127 return ScopedX509(d2i_X509(NULL, &bytes, der_encoded.size()));
128#endif // defined(USE_OPENSSL_CERTS)
129}
130
[email protected]82c59022014-08-15 09:38:27131ScopedX509Stack OSCertHandlesToOpenSSL(
132 const X509Certificate::OSCertHandles& os_handles) {
133 ScopedX509Stack stack(sk_X509_new_null());
134 for (size_t i = 0; i < os_handles.size(); i++) {
135 ScopedX509 x509 = OSCertHandleToOpenSSL(os_handles[i]);
136 if (!x509)
137 return ScopedX509Stack();
138 sk_X509_push(stack.get(), x509.release());
139 }
140 return stack.Pass();
141}
142
davidben018aad62014-09-12 02:25:19143int LogErrorCallback(const char* str, size_t len, void* context) {
144 LOG(ERROR) << base::StringPiece(str, len);
145 return 1;
146}
147
davidbend1fb2f12014-11-08 02:51:00148bool IsOCSPStaplingSupported() {
149#if defined(OS_WIN)
150 // CERT_OCSP_RESPONSE_PROP_ID is only implemented on Vista+, but it can be
151 // set on Windows XP without error. There is some overhead from the server
152 // sending the OCSP response if it supports the extension, for the subset of
153 // XP clients who will request it but be unable to use it, but this is an
154 // acceptable trade-off for simplicity of implementation.
155 return true;
156#else
157 return false;
158#endif
159}
160
[email protected]821e3bb2013-11-08 01:06:01161} // namespace
162
163class SSLClientSocketOpenSSL::SSLContext {
[email protected]fbef13932010-11-23 12:38:53164 public:
[email protected]b29af7d2010-12-14 11:52:47165 static SSLContext* GetInstance() { return Singleton<SSLContext>::get(); }
[email protected]fbef13932010-11-23 12:38:53166 SSL_CTX* ssl_ctx() { return ssl_ctx_.get(); }
[email protected]1279de12013-12-03 15:13:32167 SSLSessionCacheOpenSSL* session_cache() { return &session_cache_; }
[email protected]fbef13932010-11-23 12:38:53168
[email protected]1279de12013-12-03 15:13:32169 SSLClientSocketOpenSSL* GetClientSocketFromSSL(const SSL* ssl) {
[email protected]fbef13932010-11-23 12:38:53170 DCHECK(ssl);
171 SSLClientSocketOpenSSL* socket = static_cast<SSLClientSocketOpenSSL*>(
172 SSL_get_ex_data(ssl, ssl_socket_data_index_));
173 DCHECK(socket);
174 return socket;
175 }
176
177 bool SetClientSocketForSSL(SSL* ssl, SSLClientSocketOpenSSL* socket) {
178 return SSL_set_ex_data(ssl, ssl_socket_data_index_, socket) != 0;
179 }
180
181 private:
182 friend struct DefaultSingletonTraits<SSLContext>;
183
184 SSLContext() {
[email protected]4b559b4d2011-04-14 17:37:14185 crypto::EnsureOpenSSLInit();
[email protected]fbef13932010-11-23 12:38:53186 ssl_socket_data_index_ = SSL_get_ex_new_index(0, 0, 0, 0, 0);
187 DCHECK_NE(ssl_socket_data_index_, -1);
188 ssl_ctx_.reset(SSL_CTX_new(SSLv23_client_method()));
[email protected]1279de12013-12-03 15:13:32189 session_cache_.Reset(ssl_ctx_.get(), kDefaultSessionCacheConfig);
[email protected]b051cdb62014-02-28 02:20:16190 SSL_CTX_set_cert_verify_callback(ssl_ctx_.get(), CertVerifyCallback, NULL);
[email protected]82c59022014-08-15 09:38:27191 SSL_CTX_set_cert_cb(ssl_ctx_.get(), ClientCertRequestCallback, NULL);
[email protected]b051cdb62014-02-28 02:20:16192 SSL_CTX_set_verify(ssl_ctx_.get(), SSL_VERIFY_PEER, NULL);
haavardmc80b0ee32015-01-30 09:16:08193 // This stops |SSL_shutdown| from generating the close_notify message, which
194 // is currently not sent on the network.
195 // TODO(haavardm): Remove setting quiet shutdown once 118366 is fixed.
196 SSL_CTX_set_quiet_shutdown(ssl_ctx_.get(), 1);
[email protected]ea4a1c6a2010-12-09 13:33:28197 // TODO(kristianm): Only select this if ssl_config_.next_proto is not empty.
198 // It would be better if the callback were not a global setting,
199 // but that is an OpenSSL issue.
200 SSL_CTX_set_next_proto_select_cb(ssl_ctx_.get(), SelectNextProtoCallback,
201 NULL);
[email protected]edfd0f42014-07-22 18:20:37202 ssl_ctx_->tlsext_channel_id_enabled_new = 1;
davidben018aad62014-09-12 02:25:19203
204 scoped_ptr<base::Environment> env(base::Environment::Create());
205 std::string ssl_keylog_file;
206 if (env->GetVar("SSLKEYLOGFILE", &ssl_keylog_file) &&
207 !ssl_keylog_file.empty()) {
208 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
209 BIO* bio = BIO_new_file(ssl_keylog_file.c_str(), "a");
210 if (!bio) {
211 LOG(ERROR) << "Failed to open " << ssl_keylog_file;
212 ERR_print_errors_cb(&LogErrorCallback, NULL);
213 } else {
214 SSL_CTX_set_keylog_bio(ssl_ctx_.get(), bio);
215 }
216 }
[email protected]fbef13932010-11-23 12:38:53217 }
218
[email protected]1279de12013-12-03 15:13:32219 static std::string GetSessionCacheKey(const SSL* ssl) {
220 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
rsleevif020edc2015-03-16 19:31:24221 CHECK(socket);
[email protected]8e458552014-08-05 00:02:15222 return socket->GetSessionCacheKey();
[email protected]fbef13932010-11-23 12:38:53223 }
224
[email protected]1279de12013-12-03 15:13:32225 static SSLSessionCacheOpenSSL::Config kDefaultSessionCacheConfig;
[email protected]fbef13932010-11-23 12:38:53226
[email protected]82c59022014-08-15 09:38:27227 static int ClientCertRequestCallback(SSL* ssl, void* arg) {
[email protected]b29af7d2010-12-14 11:52:47228 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
[email protected]82c59022014-08-15 09:38:27229 DCHECK(socket);
230 return socket->ClientCertRequestCallback(ssl);
[email protected]718c9672010-12-02 10:04:10231 }
232
[email protected]b051cdb62014-02-28 02:20:16233 static int CertVerifyCallback(X509_STORE_CTX *store_ctx, void *arg) {
234 SSL* ssl = reinterpret_cast<SSL*>(X509_STORE_CTX_get_ex_data(
235 store_ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
236 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
237 CHECK(socket);
238
239 return socket->CertVerifyCallback(store_ctx);
240 }
241
[email protected]ea4a1c6a2010-12-09 13:33:28242 static int SelectNextProtoCallback(SSL* ssl,
243 unsigned char** out, unsigned char* outlen,
244 const unsigned char* in,
245 unsigned int inlen, void* arg) {
[email protected]b29af7d2010-12-14 11:52:47246 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
[email protected]ea4a1c6a2010-12-09 13:33:28247 return socket->SelectNextProtoCallback(out, outlen, in, inlen);
248 }
249
[email protected]fbef13932010-11-23 12:38:53250 // This is the index used with SSL_get_ex_data to retrieve the owner
251 // SSLClientSocketOpenSSL object from an SSL instance.
252 int ssl_socket_data_index_;
253
davidbenc879af02015-02-20 07:57:21254 ScopedSSL_CTX ssl_ctx_;
[email protected]1279de12013-12-03 15:13:32255 // |session_cache_| must be destroyed before |ssl_ctx_|.
256 SSLSessionCacheOpenSSL session_cache_;
257};
258
[email protected]7f38da8a2014-03-17 16:44:26259// PeerCertificateChain is a helper object which extracts the certificate
260// chain, as given by the server, from an OpenSSL socket and performs the needed
261// resource management. The first element of the chain is the leaf certificate
262// and the other elements are in the order given by the server.
263class SSLClientSocketOpenSSL::PeerCertificateChain {
264 public:
[email protected]76e85392014-03-20 17:54:14265 explicit PeerCertificateChain(STACK_OF(X509)* chain) { Reset(chain); }
[email protected]7f38da8a2014-03-17 16:44:26266 PeerCertificateChain(const PeerCertificateChain& other) { *this = other; }
267 ~PeerCertificateChain() {}
268 PeerCertificateChain& operator=(const PeerCertificateChain& other);
269
[email protected]76e85392014-03-20 17:54:14270 // Resets the PeerCertificateChain to the set of certificates in|chain|,
271 // which may be NULL, indicating to empty the store certificates.
272 // Note: If an error occurs, such as being unable to parse the certificates,
273 // this will behave as if Reset(NULL) was called.
274 void Reset(STACK_OF(X509)* chain);
275
[email protected]7f38da8a2014-03-17 16:44:26276 // Note that when USE_OPENSSL is defined, OSCertHandle is X509*
davidben30798ed82014-09-19 19:28:20277 scoped_refptr<X509Certificate> AsOSChain() const;
[email protected]7f38da8a2014-03-17 16:44:26278
279 size_t size() const {
280 if (!openssl_chain_.get())
281 return 0;
282 return sk_X509_num(openssl_chain_.get());
283 }
284
davidben30798ed82014-09-19 19:28:20285 bool empty() const {
286 return size() == 0;
287 }
288
289 X509* Get(size_t index) const {
[email protected]7f38da8a2014-03-17 16:44:26290 DCHECK_LT(index, size());
291 return sk_X509_value(openssl_chain_.get(), index);
292 }
293
294 private:
[email protected]cd9b75b2014-07-10 04:39:38295 ScopedX509Stack openssl_chain_;
[email protected]7f38da8a2014-03-17 16:44:26296};
297
298SSLClientSocketOpenSSL::PeerCertificateChain&
299SSLClientSocketOpenSSL::PeerCertificateChain::operator=(
300 const PeerCertificateChain& other) {
301 if (this == &other)
302 return *this;
303
[email protected]24176af2014-08-14 09:31:04304 openssl_chain_.reset(X509_chain_up_ref(other.openssl_chain_.get()));
[email protected]7f38da8a2014-03-17 16:44:26305 return *this;
306}
307
[email protected]76e85392014-03-20 17:54:14308void SSLClientSocketOpenSSL::PeerCertificateChain::Reset(
309 STACK_OF(X509)* chain) {
davidben30798ed82014-09-19 19:28:20310 openssl_chain_.reset(chain ? X509_chain_up_ref(chain) : NULL);
[email protected]7f38da8a2014-03-17 16:44:26311}
[email protected]7f38da8a2014-03-17 16:44:26312
davidben30798ed82014-09-19 19:28:20313scoped_refptr<X509Certificate>
314SSLClientSocketOpenSSL::PeerCertificateChain::AsOSChain() const {
315#if defined(USE_OPENSSL_CERTS)
316 // When OSCertHandle is typedef'ed to X509, this implementation does a short
317 // cut to avoid converting back and forth between DER and the X509 struct.
318 X509Certificate::OSCertHandles intermediates;
319 for (size_t i = 1; i < sk_X509_num(openssl_chain_.get()); ++i) {
320 intermediates.push_back(sk_X509_value(openssl_chain_.get(), i));
321 }
[email protected]7f38da8a2014-03-17 16:44:26322
davidben30798ed82014-09-19 19:28:20323 return make_scoped_refptr(X509Certificate::CreateFromHandle(
324 sk_X509_value(openssl_chain_.get(), 0), intermediates));
325#else
326 // DER-encode the chain and convert to a platform certificate handle.
[email protected]7f38da8a2014-03-17 16:44:26327 std::vector<base::StringPiece> der_chain;
[email protected]edfd0f42014-07-22 18:20:37328 for (size_t i = 0; i < sk_X509_num(openssl_chain_.get()); ++i) {
[email protected]7f38da8a2014-03-17 16:44:26329 X509* x = sk_X509_value(openssl_chain_.get(), i);
davidben30798ed82014-09-19 19:28:20330 base::StringPiece der;
331 if (!x509_util::GetDER(x, &der))
332 return NULL;
333 der_chain.push_back(der);
[email protected]7f38da8a2014-03-17 16:44:26334 }
335
davidben30798ed82014-09-19 19:28:20336 return make_scoped_refptr(X509Certificate::CreateFromDERCertChain(der_chain));
337#endif
[email protected]7f38da8a2014-03-17 16:44:26338}
[email protected]7f38da8a2014-03-17 16:44:26339
[email protected]1279de12013-12-03 15:13:32340// static
341SSLSessionCacheOpenSSL::Config
342 SSLClientSocketOpenSSL::SSLContext::kDefaultSessionCacheConfig = {
343 &GetSessionCacheKey, // key_func
344 1024, // max_entries
345 256, // expiration_check_count
346 60 * 60, // timeout_seconds
[email protected]fbef13932010-11-23 12:38:53347};
[email protected]313834722010-11-17 09:57:18348
[email protected]c3456bb2011-12-12 22:22:19349// static
350void SSLClientSocket::ClearSessionCache() {
[email protected]821e3bb2013-11-08 01:06:01351 SSLClientSocketOpenSSL::SSLContext* context =
352 SSLClientSocketOpenSSL::SSLContext::GetInstance();
[email protected]c3456bb2011-12-12 22:22:19353 context->session_cache()->Flush();
354}
355
bnc86b734dd2014-12-03 00:33:10356// static
357uint16 SSLClientSocket::GetMaxSupportedSSLVersion() {
358 return SSL_PROTOCOL_VERSION_TLS1_2;
359}
360
[email protected]d518cd92010-09-29 12:27:44361SSLClientSocketOpenSSL::SSLClientSocketOpenSSL(
[email protected]18ccfdb2013-08-15 00:13:44362 scoped_ptr<ClientSocketHandle> transport_socket,
[email protected]055d7f22010-11-15 12:03:12363 const HostPortPair& host_and_port,
[email protected]822581d2010-12-16 17:27:15364 const SSLConfig& ssl_config,
[email protected]feb79bcd2011-07-21 16:55:17365 const SSLClientSocketContext& context)
[email protected]83039bb2011-12-09 18:43:55366 : transport_send_busy_(false),
[email protected]d518cd92010-09-29 12:27:44367 transport_recv_busy_(false),
[email protected]4b768562013-02-16 04:10:07368 pending_read_error_(kNoPendingReadResult),
davidbenb8c23212014-10-28 00:12:16369 pending_read_ssl_error_(SSL_ERROR_NONE),
[email protected]5aea79182014-07-14 20:43:41370 transport_read_error_(OK),
[email protected]3e5c6922014-02-06 02:42:16371 transport_write_error_(OK),
[email protected]7f38da8a2014-03-17 16:44:26372 server_cert_chain_(new PeerCertificateChain(NULL)),
[email protected]64b5c892014-08-08 09:39:26373 completed_connect_(false),
[email protected]0dc88b32014-03-26 20:12:28374 was_ever_used_(false),
[email protected]d518cd92010-09-29 12:27:44375 client_auth_cert_needed_(false),
[email protected]feb79bcd2011-07-21 16:55:17376 cert_verifier_(context.cert_verifier),
davidbeneb5f8ef32014-09-04 14:14:32377 cert_transparency_verifier_(context.cert_transparency_verifier),
[email protected]6b8a3c742014-07-25 00:25:35378 channel_id_service_(context.channel_id_service),
[email protected]d518cd92010-09-29 12:27:44379 ssl_(NULL),
380 transport_bio_(NULL),
[email protected]18ccfdb2013-08-15 00:13:44381 transport_(transport_socket.Pass()),
[email protected]055d7f22010-11-15 12:03:12382 host_and_port_(host_and_port),
[email protected]d518cd92010-09-29 12:27:44383 ssl_config_(ssl_config),
[email protected]c3456bb2011-12-12 22:22:19384 ssl_session_cache_shard_(context.ssl_session_cache_shard),
[email protected]fbef13932010-11-23 12:38:53385 trying_cached_session_(false),
[email protected]013c17c2012-01-21 19:09:01386 next_handshake_state_(STATE_NONE),
[email protected]ea4a1c6a2010-12-09 13:33:28387 npn_status_(kNextProtoUnsupported),
[email protected]ee0f2aa82013-10-25 11:59:26388 channel_id_xtn_negotiated_(false),
[email protected]8bd4e7a2014-08-09 14:49:17389 transport_security_state_(context.transport_security_state),
eranm6571b2b2014-12-03 15:53:23390 policy_enforcer_(context.cert_policy_enforcer),
kulkarni.acd7b4462014-08-28 07:41:34391 net_log_(transport_->socket()->NetLog()),
392 weak_factory_(this) {
[email protected]8e458552014-08-05 00:02:15393}
[email protected]d518cd92010-09-29 12:27:44394
395SSLClientSocketOpenSSL::~SSLClientSocketOpenSSL() {
396 Disconnect();
397}
398
[email protected]b9b651f2013-11-09 04:32:22399void SSLClientSocketOpenSSL::GetSSLCertRequestInfo(
400 SSLCertRequestInfo* cert_request_info) {
[email protected]791879c2013-12-17 07:22:41401 cert_request_info->host_and_port = host_and_port_;
[email protected]b9b651f2013-11-09 04:32:22402 cert_request_info->cert_authorities = cert_authorities_;
[email protected]c0787702014-05-20 21:51:44403 cert_request_info->cert_key_types = cert_key_types_;
[email protected]b9b651f2013-11-09 04:32:22404}
405
406SSLClientSocket::NextProtoStatus SSLClientSocketOpenSSL::GetNextProto(
[email protected]abc44b752014-07-30 03:52:15407 std::string* proto) {
[email protected]b9b651f2013-11-09 04:32:22408 *proto = npn_proto_;
[email protected]b9b651f2013-11-09 04:32:22409 return npn_status_;
410}
411
[email protected]6b8a3c742014-07-25 00:25:35412ChannelIDService*
413SSLClientSocketOpenSSL::GetChannelIDService() const {
414 return channel_id_service_;
[email protected]b9b651f2013-11-09 04:32:22415}
416
417int SSLClientSocketOpenSSL::ExportKeyingMaterial(
418 const base::StringPiece& label,
419 bool has_context, const base::StringPiece& context,
420 unsigned char* out, unsigned int outlen) {
421 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
422
423 int rv = SSL_export_keying_material(
[email protected]c8a80e92014-05-17 16:02:08424 ssl_, out, outlen, label.data(), label.size(),
425 reinterpret_cast<const unsigned char*>(context.data()),
426 context.length(), context.length() > 0);
[email protected]b9b651f2013-11-09 04:32:22427
428 if (rv != 1) {
429 int ssl_error = SSL_get_error(ssl_, rv);
430 LOG(ERROR) << "Failed to export keying material;"
431 << " returned " << rv
432 << ", SSL error code " << ssl_error;
433 return MapOpenSSLError(ssl_error, err_tracer);
434 }
435 return OK;
436}
437
438int SSLClientSocketOpenSSL::GetTLSUniqueChannelBinding(std::string* out) {
[email protected]c8a80e92014-05-17 16:02:08439 NOTIMPLEMENTED();
[email protected]b9b651f2013-11-09 04:32:22440 return ERR_NOT_IMPLEMENTED;
441}
442
443int SSLClientSocketOpenSSL::Connect(const CompletionCallback& callback) {
[email protected]8bd4e7a2014-08-09 14:49:17444 // It is an error to create an SSLClientSocket whose context has no
445 // TransportSecurityState.
446 DCHECK(transport_security_state_);
447
[email protected]b9b651f2013-11-09 04:32:22448 net_log_.BeginEvent(NetLog::TYPE_SSL_CONNECT);
449
450 // Set up new ssl object.
[email protected]c8a80e92014-05-17 16:02:08451 int rv = Init();
452 if (rv != OK) {
453 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
454 return rv;
[email protected]b9b651f2013-11-09 04:32:22455 }
456
457 // Set SSL to client mode. Handshake happens in the loop below.
458 SSL_set_connect_state(ssl_);
459
jeremyim8d44fadd2015-02-10 19:18:15460 // Enable fastradio padding.
461 SSL_enable_fastradio_padding(ssl_,
462 ssl_config_.fastradio_padding_enabled &&
463 ssl_config_.fastradio_padding_eligible);
464
[email protected]b9b651f2013-11-09 04:32:22465 GotoState(STATE_HANDSHAKE);
[email protected]c8a80e92014-05-17 16:02:08466 rv = DoHandshakeLoop(OK);
[email protected]b9b651f2013-11-09 04:32:22467 if (rv == ERR_IO_PENDING) {
468 user_connect_callback_ = callback;
469 } else {
470 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
471 }
472
473 return rv > OK ? OK : rv;
474}
475
476void SSLClientSocketOpenSSL::Disconnect() {
477 if (ssl_) {
478 // Calling SSL_shutdown prevents the session from being marked as
479 // unresumable.
480 SSL_shutdown(ssl_);
481 SSL_free(ssl_);
482 ssl_ = NULL;
483 }
484 if (transport_bio_) {
485 BIO_free_all(transport_bio_);
486 transport_bio_ = NULL;
487 }
488
489 // Shut down anything that may call us back.
490 verifier_.reset();
491 transport_->socket()->Disconnect();
492
493 // Null all callbacks, delete all buffers.
494 transport_send_busy_ = false;
495 send_buffer_ = NULL;
496 transport_recv_busy_ = false;
[email protected]b9b651f2013-11-09 04:32:22497 recv_buffer_ = NULL;
498
499 user_connect_callback_.Reset();
500 user_read_callback_.Reset();
501 user_write_callback_.Reset();
502 user_read_buf_ = NULL;
503 user_read_buf_len_ = 0;
504 user_write_buf_ = NULL;
505 user_write_buf_len_ = 0;
506
[email protected]3e5c6922014-02-06 02:42:16507 pending_read_error_ = kNoPendingReadResult;
davidbenb8c23212014-10-28 00:12:16508 pending_read_ssl_error_ = SSL_ERROR_NONE;
509 pending_read_error_info_ = OpenSSLErrorInfo();
510
[email protected]5aea79182014-07-14 20:43:41511 transport_read_error_ = OK;
[email protected]3e5c6922014-02-06 02:42:16512 transport_write_error_ = OK;
513
[email protected]b9b651f2013-11-09 04:32:22514 server_cert_verify_result_.Reset();
[email protected]64b5c892014-08-08 09:39:26515 completed_connect_ = false;
[email protected]b9b651f2013-11-09 04:32:22516
517 cert_authorities_.clear();
[email protected]c0787702014-05-20 21:51:44518 cert_key_types_.clear();
[email protected]b9b651f2013-11-09 04:32:22519 client_auth_cert_needed_ = false;
[email protected]faff9852014-06-21 06:13:46520
davidben09c3d072014-08-25 20:33:58521 start_cert_verification_time_ = base::TimeTicks();
522
[email protected]abc44b752014-07-30 03:52:15523 npn_status_ = kNextProtoUnsupported;
524 npn_proto_.clear();
525
[email protected]faff9852014-06-21 06:13:46526 channel_id_xtn_negotiated_ = false;
527 channel_id_request_handle_.Cancel();
[email protected]b9b651f2013-11-09 04:32:22528}
529
530bool SSLClientSocketOpenSSL::IsConnected() const {
531 // If the handshake has not yet completed.
[email protected]64b5c892014-08-08 09:39:26532 if (!completed_connect_)
[email protected]b9b651f2013-11-09 04:32:22533 return false;
534 // If an asynchronous operation is still pending.
535 if (user_read_buf_.get() || user_write_buf_.get())
536 return true;
537
538 return transport_->socket()->IsConnected();
539}
540
541bool SSLClientSocketOpenSSL::IsConnectedAndIdle() const {
542 // If the handshake has not yet completed.
[email protected]64b5c892014-08-08 09:39:26543 if (!completed_connect_)
[email protected]b9b651f2013-11-09 04:32:22544 return false;
545 // If an asynchronous operation is still pending.
546 if (user_read_buf_.get() || user_write_buf_.get())
547 return false;
548 // If there is data waiting to be sent, or data read from the network that
549 // has not yet been consumed.
[email protected]edfd0f42014-07-22 18:20:37550 if (BIO_pending(transport_bio_) > 0 ||
551 BIO_wpending(transport_bio_) > 0) {
[email protected]b9b651f2013-11-09 04:32:22552 return false;
553 }
554
555 return transport_->socket()->IsConnectedAndIdle();
556}
557
558int SSLClientSocketOpenSSL::GetPeerAddress(IPEndPoint* addressList) const {
559 return transport_->socket()->GetPeerAddress(addressList);
560}
561
562int SSLClientSocketOpenSSL::GetLocalAddress(IPEndPoint* addressList) const {
563 return transport_->socket()->GetLocalAddress(addressList);
564}
565
566const BoundNetLog& SSLClientSocketOpenSSL::NetLog() const {
567 return net_log_;
568}
569
570void SSLClientSocketOpenSSL::SetSubresourceSpeculation() {
571 if (transport_.get() && transport_->socket()) {
572 transport_->socket()->SetSubresourceSpeculation();
573 } else {
574 NOTREACHED();
575 }
576}
577
578void SSLClientSocketOpenSSL::SetOmniboxSpeculation() {
579 if (transport_.get() && transport_->socket()) {
580 transport_->socket()->SetOmniboxSpeculation();
581 } else {
582 NOTREACHED();
583 }
584}
585
586bool SSLClientSocketOpenSSL::WasEverUsed() const {
[email protected]0dc88b32014-03-26 20:12:28587 return was_ever_used_;
[email protected]b9b651f2013-11-09 04:32:22588}
589
590bool SSLClientSocketOpenSSL::UsingTCPFastOpen() const {
591 if (transport_.get() && transport_->socket())
592 return transport_->socket()->UsingTCPFastOpen();
593
594 NOTREACHED();
595 return false;
596}
597
598bool SSLClientSocketOpenSSL::GetSSLInfo(SSLInfo* ssl_info) {
599 ssl_info->Reset();
davidben30798ed82014-09-19 19:28:20600 if (server_cert_chain_->empty())
[email protected]b9b651f2013-11-09 04:32:22601 return false;
602
603 ssl_info->cert = server_cert_verify_result_.verified_cert;
604 ssl_info->cert_status = server_cert_verify_result_.cert_status;
605 ssl_info->is_issued_by_known_root =
606 server_cert_verify_result_.is_issued_by_known_root;
607 ssl_info->public_key_hashes =
608 server_cert_verify_result_.public_key_hashes;
609 ssl_info->client_cert_sent =
610 ssl_config_.send_client_cert && ssl_config_.client_cert.get();
611 ssl_info->channel_id_sent = WasChannelIDSent();
[email protected]8bd4e7a2014-08-09 14:49:17612 ssl_info->pinning_failure_log = pinning_failure_log_;
[email protected]b9b651f2013-11-09 04:32:22613
davidbeneb5f8ef32014-09-04 14:14:32614 AddSCTInfoToSSLInfo(ssl_info);
615
[email protected]b9b651f2013-11-09 04:32:22616 const SSL_CIPHER* cipher = SSL_get_current_cipher(ssl_);
617 CHECK(cipher);
618 ssl_info->security_bits = SSL_CIPHER_get_bits(cipher, NULL);
[email protected]b9b651f2013-11-09 04:32:22619
620 ssl_info->connection_status = EncodeSSLConnectionStatus(
pkasting6b68a162014-12-01 22:10:29621 static_cast<uint16>(SSL_CIPHER_get_id(cipher)), 0 /* no compression */,
[email protected]b9b651f2013-11-09 04:32:22622 GetNetSSLVersion(ssl_));
623
davidben09c3d072014-08-25 20:33:58624 if (!SSL_get_secure_renegotiation_support(ssl_))
[email protected]b9b651f2013-11-09 04:32:22625 ssl_info->connection_status |= SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION;
[email protected]b9b651f2013-11-09 04:32:22626
627 if (ssl_config_.version_fallback)
628 ssl_info->connection_status |= SSL_CONNECTION_VERSION_FALLBACK;
629
630 ssl_info->handshake_type = SSL_session_reused(ssl_) ?
631 SSLInfo::HANDSHAKE_RESUME : SSLInfo::HANDSHAKE_FULL;
632
633 DVLOG(3) << "Encoded connection status: cipher suite = "
634 << SSLConnectionStatusToCipherSuite(ssl_info->connection_status)
635 << " version = "
636 << SSLConnectionStatusToVersion(ssl_info->connection_status);
637 return true;
638}
639
640int SSLClientSocketOpenSSL::Read(IOBuffer* buf,
641 int buf_len,
642 const CompletionCallback& callback) {
643 user_read_buf_ = buf;
644 user_read_buf_len_ = buf_len;
645
davidben1b133ad2014-10-23 04:23:13646 int rv = DoReadLoop();
[email protected]b9b651f2013-11-09 04:32:22647
648 if (rv == ERR_IO_PENDING) {
649 user_read_callback_ = callback;
650 } else {
[email protected]0dc88b32014-03-26 20:12:28651 if (rv > 0)
652 was_ever_used_ = true;
[email protected]b9b651f2013-11-09 04:32:22653 user_read_buf_ = NULL;
654 user_read_buf_len_ = 0;
655 }
656
657 return rv;
658}
659
660int SSLClientSocketOpenSSL::Write(IOBuffer* buf,
661 int buf_len,
662 const CompletionCallback& callback) {
663 user_write_buf_ = buf;
664 user_write_buf_len_ = buf_len;
665
davidben1b133ad2014-10-23 04:23:13666 int rv = DoWriteLoop();
[email protected]b9b651f2013-11-09 04:32:22667
668 if (rv == ERR_IO_PENDING) {
669 user_write_callback_ = callback;
670 } else {
[email protected]0dc88b32014-03-26 20:12:28671 if (rv > 0)
672 was_ever_used_ = true;
[email protected]b9b651f2013-11-09 04:32:22673 user_write_buf_ = NULL;
674 user_write_buf_len_ = 0;
675 }
676
677 return rv;
678}
679
[email protected]28b96d1c2014-04-09 12:21:15680int SSLClientSocketOpenSSL::SetReceiveBufferSize(int32 size) {
[email protected]b9b651f2013-11-09 04:32:22681 return transport_->socket()->SetReceiveBufferSize(size);
682}
683
[email protected]28b96d1c2014-04-09 12:21:15684int SSLClientSocketOpenSSL::SetSendBufferSize(int32 size) {
[email protected]b9b651f2013-11-09 04:32:22685 return transport_->socket()->SetSendBufferSize(size);
686}
687
[email protected]c8a80e92014-05-17 16:02:08688int SSLClientSocketOpenSSL::Init() {
[email protected]9e733f32010-10-04 18:19:08689 DCHECK(!ssl_);
690 DCHECK(!transport_bio_);
691
[email protected]b29af7d2010-12-14 11:52:47692 SSLContext* context = SSLContext::GetInstance();
[email protected]4b559b4d2011-04-14 17:37:14693 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
[email protected]d518cd92010-09-29 12:27:44694
[email protected]fbef13932010-11-23 12:38:53695 ssl_ = SSL_new(context->ssl_ctx());
696 if (!ssl_ || !context->SetClientSocketForSSL(ssl_, this))
[email protected]c8a80e92014-05-17 16:02:08697 return ERR_UNEXPECTED;
[email protected]fbef13932010-11-23 12:38:53698
699 if (!SSL_set_tlsext_host_name(ssl_, host_and_port_.host().c_str()))
[email protected]c8a80e92014-05-17 16:02:08700 return ERR_UNEXPECTED;
[email protected]fbef13932010-11-23 12:38:53701
[email protected]1279de12013-12-03 15:13:32702 trying_cached_session_ = context->session_cache()->SetSSLSessionWithKey(
[email protected]8e458552014-08-05 00:02:15703 ssl_, GetSessionCacheKey());
[email protected]d518cd92010-09-29 12:27:44704
haavardm2d92e722014-12-19 13:45:44705 send_buffer_ = new GrowableIOBuffer();
706 send_buffer_->SetCapacity(KDefaultOpenSSLBufferSize);
707 recv_buffer_ = new GrowableIOBuffer();
708 recv_buffer_->SetCapacity(KDefaultOpenSSLBufferSize);
709
[email protected]d518cd92010-09-29 12:27:44710 BIO* ssl_bio = NULL;
haavardm2d92e722014-12-19 13:45:44711
712 // SSLClientSocketOpenSSL retains ownership of the BIO buffers.
713 if (!BIO_new_bio_pair_external_buf(
714 &ssl_bio, send_buffer_->capacity(),
715 reinterpret_cast<uint8_t*>(send_buffer_->data()), &transport_bio_,
716 recv_buffer_->capacity(),
717 reinterpret_cast<uint8_t*>(recv_buffer_->data())))
[email protected]c8a80e92014-05-17 16:02:08718 return ERR_UNEXPECTED;
[email protected]d518cd92010-09-29 12:27:44719 DCHECK(ssl_bio);
720 DCHECK(transport_bio_);
721
[email protected]5aea79182014-07-14 20:43:41722 // Install a callback on OpenSSL's end to plumb transport errors through.
rsleevif020edc2015-03-16 19:31:24723 BIO_set_callback(ssl_bio, &SSLClientSocketOpenSSL::BIOCallback);
[email protected]5aea79182014-07-14 20:43:41724 BIO_set_callback_arg(ssl_bio, reinterpret_cast<char*>(this));
725
[email protected]d518cd92010-09-29 12:27:44726 SSL_set_bio(ssl_, ssl_bio, ssl_bio);
727
[email protected]9e733f32010-10-04 18:19:08728 // OpenSSL defaults some options to on, others to off. To avoid ambiguity,
729 // set everything we care about to an absolute value.
[email protected]fb10e2282010-12-01 17:08:48730 SslSetClearMask options;
731 options.ConfigureFlag(SSL_OP_NO_SSLv2, true);
[email protected]80c75f682012-05-26 16:22:17732 bool ssl3_enabled = (ssl_config_.version_min == SSL_PROTOCOL_VERSION_SSL3);
733 options.ConfigureFlag(SSL_OP_NO_SSLv3, !ssl3_enabled);
734 bool tls1_enabled = (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1 &&
735 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1);
736 options.ConfigureFlag(SSL_OP_NO_TLSv1, !tls1_enabled);
[email protected]80c75f682012-05-26 16:22:17737 bool tls1_1_enabled =
738 (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1_1 &&
739 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1_1);
740 options.ConfigureFlag(SSL_OP_NO_TLSv1_1, !tls1_1_enabled);
[email protected]80c75f682012-05-26 16:22:17741 bool tls1_2_enabled =
742 (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1_2 &&
743 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1_2);
744 options.ConfigureFlag(SSL_OP_NO_TLSv1_2, !tls1_2_enabled);
[email protected]fb10e2282010-12-01 17:08:48745
[email protected]d0f00492012-08-03 22:35:13746 options.ConfigureFlag(SSL_OP_NO_COMPRESSION, true);
[email protected]9e733f32010-10-04 18:19:08747
748 // TODO(joth): Set this conditionally, see http://crbug.com/55410
[email protected]fb10e2282010-12-01 17:08:48749 options.ConfigureFlag(SSL_OP_LEGACY_SERVER_CONNECT, true);
[email protected]9e733f32010-10-04 18:19:08750
[email protected]fb10e2282010-12-01 17:08:48751 SSL_set_options(ssl_, options.set_mask);
752 SSL_clear_options(ssl_, options.clear_mask);
[email protected]9e733f32010-10-04 18:19:08753
[email protected]fb10e2282010-12-01 17:08:48754 // Same as above, this time for the SSL mode.
755 SslSetClearMask mode;
[email protected]9e733f32010-10-04 18:19:08756
[email protected]fb10e2282010-12-01 17:08:48757 mode.ConfigureFlag(SSL_MODE_RELEASE_BUFFERS, true);
ishermane5c05e12014-09-09 20:32:15758 mode.ConfigureFlag(SSL_MODE_CBC_RECORD_SPLITTING, true);
[email protected]fb10e2282010-12-01 17:08:48759
davidben818d93b2015-02-19 22:27:32760 mode.ConfigureFlag(SSL_MODE_ENABLE_FALSE_START,
[email protected]b788de02014-04-23 18:06:07761 ssl_config_.false_start_enabled);
762
davidben6b8131c2015-02-25 23:30:14763 mode.ConfigureFlag(SSL_MODE_SEND_FALLBACK_SCSV, ssl_config_.version_fallback);
764
[email protected]fb10e2282010-12-01 17:08:48765 SSL_set_mode(ssl_, mode.set_mask);
766 SSL_clear_mode(ssl_, mode.clear_mask);
[email protected]109805a2010-12-07 18:17:06767
768 // Removing ciphers by ID from OpenSSL is a bit involved as we must use the
769 // textual name with SSL_set_cipher_list because there is no public API to
770 // directly remove a cipher by ID.
771 STACK_OF(SSL_CIPHER)* ciphers = SSL_get_ciphers(ssl_);
772 DCHECK(ciphers);
773 // See SSLConfig::disabled_cipher_suites for description of the suites
[email protected]9b4bc4a92013-08-20 22:59:07774 // disabled by default. Note that !SHA256 and !SHA384 only remove HMAC-SHA256
775 // and HMAC-SHA384 cipher suites, not GCM cipher suites with SHA256 or SHA384
776 // as the handshake hash.
bnc1e757502014-12-13 02:20:16777 std::string command(
778 "DEFAULT:!NULL:!aNULL:!SHA256:!SHA384:!aECDH:!AESGCM+AES256:!aPSK");
[email protected]109805a2010-12-07 18:17:06779 // Walk through all the installed ciphers, seeing if any need to be
780 // appended to the cipher removal |command|.
[email protected]edfd0f42014-07-22 18:20:37781 for (size_t i = 0; i < sk_SSL_CIPHER_num(ciphers); ++i) {
[email protected]109805a2010-12-07 18:17:06782 const SSL_CIPHER* cipher = sk_SSL_CIPHER_value(ciphers, i);
pkasting6b68a162014-12-01 22:10:29783 const uint16 id = static_cast<uint16>(SSL_CIPHER_get_id(cipher));
[email protected]109805a2010-12-07 18:17:06784 // Remove any ciphers with a strength of less than 80 bits. Note the NSS
785 // implementation uses "effective" bits here but OpenSSL does not provide
786 // this detail. This only impacts Triple DES: reports 112 vs. 168 bits,
787 // both of which are greater than 80 anyway.
788 bool disable = SSL_CIPHER_get_bits(cipher, NULL) < 80;
789 if (!disable) {
790 disable = std::find(ssl_config_.disabled_cipher_suites.begin(),
791 ssl_config_.disabled_cipher_suites.end(), id) !=
792 ssl_config_.disabled_cipher_suites.end();
793 }
794 if (disable) {
795 const char* name = SSL_CIPHER_get_name(cipher);
796 DVLOG(3) << "Found cipher to remove: '" << name << "', ID: " << id
797 << " strength: " << SSL_CIPHER_get_bits(cipher, NULL);
798 command.append(":!");
799 command.append(name);
800 }
801 }
davidben8ecc3072014-09-03 23:19:09802
803 // Disable ECDSA cipher suites on platforms that do not support ECDSA
804 // signed certificates, as servers may use the presence of such
805 // ciphersuites as a hint to send an ECDSA certificate.
806#if defined(OS_WIN)
807 if (base::win::GetVersion() < base::win::VERSION_VISTA)
808 command.append(":!ECDSA");
809#endif
810
[email protected]109805a2010-12-07 18:17:06811 int rv = SSL_set_cipher_list(ssl_, command.c_str());
812 // If this fails (rv = 0) it means there are no ciphers enabled on this SSL.
813 // This will almost certainly result in the socket failing to complete the
814 // handshake at which point the appropriate error is bubbled up to the client.
815 LOG_IF(WARNING, rv != 1) << "SSL_set_cipher_list('" << command << "') "
816 "returned " << rv;
[email protected]ee0f2aa82013-10-25 11:59:26817
818 // TLS channel ids.
[email protected]6b8a3c742014-07-25 00:25:35819 if (IsChannelIDEnabled(ssl_config_, channel_id_service_)) {
[email protected]ee0f2aa82013-10-25 11:59:26820 SSL_enable_tls_channel_id(ssl_);
821 }
822
[email protected]abc44b752014-07-30 03:52:15823 if (!ssl_config_.next_protos.empty()) {
bnc1e757502014-12-13 02:20:16824 // Get list of ciphers that are enabled.
825 STACK_OF(SSL_CIPHER)* enabled_ciphers = SSL_get_ciphers(ssl_);
826 DCHECK(enabled_ciphers);
827 std::vector<uint16> enabled_ciphers_vector;
828 for (size_t i = 0; i < sk_SSL_CIPHER_num(enabled_ciphers); ++i) {
829 const SSL_CIPHER* cipher = sk_SSL_CIPHER_value(enabled_ciphers, i);
830 const uint16 id = static_cast<uint16>(SSL_CIPHER_get_id(cipher));
831 enabled_ciphers_vector.push_back(id);
832 }
833
[email protected]abc44b752014-07-30 03:52:15834 std::vector<uint8_t> wire_protos =
bnc1e757502014-12-13 02:20:16835 SerializeNextProtos(ssl_config_.next_protos,
836 HasCipherAdequateForHTTP2(enabled_ciphers_vector) &&
837 IsTLSVersionAdequateForHTTP2(ssl_config_));
[email protected]abc44b752014-07-30 03:52:15838 SSL_set_alpn_protos(ssl_, wire_protos.empty() ? NULL : &wire_protos[0],
839 wire_protos.size());
840 }
841
davidbeneb5f8ef32014-09-04 14:14:32842 if (ssl_config_.signed_cert_timestamps_enabled) {
843 SSL_enable_signed_cert_timestamps(ssl_);
844 SSL_enable_ocsp_stapling(ssl_);
845 }
846
davidbend1fb2f12014-11-08 02:51:00847 if (IsOCSPStaplingSupported())
848 SSL_enable_ocsp_stapling(ssl_);
davidbeneb5f8ef32014-09-04 14:14:32849
[email protected]c8a80e92014-05-17 16:02:08850 return OK;
[email protected]d518cd92010-09-29 12:27:44851}
852
[email protected]b9b651f2013-11-09 04:32:22853void SSLClientSocketOpenSSL::DoReadCallback(int rv) {
854 // Since Run may result in Read being called, clear |user_read_callback_|
855 // up front.
[email protected]0dc88b32014-03-26 20:12:28856 if (rv > 0)
857 was_ever_used_ = true;
[email protected]b9b651f2013-11-09 04:32:22858 user_read_buf_ = NULL;
859 user_read_buf_len_ = 0;
860 base::ResetAndReturn(&user_read_callback_).Run(rv);
861}
862
863void SSLClientSocketOpenSSL::DoWriteCallback(int rv) {
864 // Since Run may result in Write being called, clear |user_write_callback_|
865 // up front.
[email protected]0dc88b32014-03-26 20:12:28866 if (rv > 0)
867 was_ever_used_ = true;
[email protected]b9b651f2013-11-09 04:32:22868 user_write_buf_ = NULL;
869 user_write_buf_len_ = 0;
870 base::ResetAndReturn(&user_write_callback_).Run(rv);
871}
872
873bool SSLClientSocketOpenSSL::DoTransportIO() {
874 bool network_moved = false;
875 int rv;
876 // Read and write as much data as possible. The loop is necessary because
877 // Write() may return synchronously.
878 do {
879 rv = BufferSend();
880 if (rv != ERR_IO_PENDING && rv != 0)
881 network_moved = true;
882 } while (rv > 0);
[email protected]5aea79182014-07-14 20:43:41883 if (transport_read_error_ == OK && BufferRecv() != ERR_IO_PENDING)
[email protected]b9b651f2013-11-09 04:32:22884 network_moved = true;
885 return network_moved;
886}
887
vadimt6b43dec22015-01-06 01:59:58888// TODO(vadimt): Remove including "base/threading/thread_local.h" and
889// g_first_run_completed once crbug.com/424386 is fixed.
890base::LazyInstance<base::ThreadLocalBoolean>::Leaky g_first_run_completed =
891 LAZY_INSTANCE_INITIALIZER;
892
[email protected]b9b651f2013-11-09 04:32:22893int SSLClientSocketOpenSSL::DoHandshake() {
894 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
[email protected]c8a80e92014-05-17 16:02:08895 int net_error = OK;
vadimt5a243282014-12-24 00:26:16896
897 int rv;
898
899 // TODO(vadimt): Leave only 1 call to SSL_do_handshake once crbug.com/424386
900 // is fixed.
901 if (ssl_config_.send_client_cert && ssl_config_.client_cert.get()) {
902 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
903 tracked_objects::ScopedTracker tracking_profile1(
904 FROM_HERE_WITH_EXPLICIT_FUNCTION("424386 DoHandshake_WithCert"));
905
906 rv = SSL_do_handshake(ssl_);
907 } else {
vadimt6b43dec22015-01-06 01:59:58908 if (g_first_run_completed.Get().Get()) {
909 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is
910 // fixed.
911 tracked_objects::ScopedTracker tracking_profile1(
912 FROM_HERE_WITH_EXPLICIT_FUNCTION(
913 "424386 DoHandshake_WithoutCert Not First"));
vadimt5a243282014-12-24 00:26:16914
vadimt6b43dec22015-01-06 01:59:58915 rv = SSL_do_handshake(ssl_);
916 } else {
917 g_first_run_completed.Get().Set(true);
918
919 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is
920 // fixed.
921 tracked_objects::ScopedTracker tracking_profile1(
922 FROM_HERE_WITH_EXPLICIT_FUNCTION(
923 "424386 DoHandshake_WithoutCert First"));
924
925 rv = SSL_do_handshake(ssl_);
926 }
vadimt5a243282014-12-24 00:26:16927 }
[email protected]b9b651f2013-11-09 04:32:22928
davidben8114f802015-03-25 17:02:34929 if (rv == 1) {
vadimtc4e29112014-12-18 01:44:21930 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
931 tracked_objects::ScopedTracker tracking_profile3(
932 FROM_HERE_WITH_EXPLICIT_FUNCTION(
933 "424386 SSLClientSocketOpenSSL::DoHandshake3"));
934
[email protected]b9b651f2013-11-09 04:32:22935 if (trying_cached_session_ && logging::DEBUG_MODE) {
936 DVLOG(2) << "Result of session reuse for " << host_and_port_.ToString()
937 << " is: " << (SSL_session_reused(ssl_) ? "Success" : "Fail");
938 }
[email protected]abc44b752014-07-30 03:52:15939
Adam Langley32352ad2014-10-14 22:31:00940 if (ssl_config_.version_fallback &&
941 ssl_config_.version_max < ssl_config_.version_fallback_min) {
942 return ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION;
943 }
944
[email protected]abc44b752014-07-30 03:52:15945 // SSL handshake is completed. If NPN wasn't negotiated, see if ALPN was.
946 if (npn_status_ == kNextProtoUnsupported) {
947 const uint8_t* alpn_proto = NULL;
948 unsigned alpn_len = 0;
949 SSL_get0_alpn_selected(ssl_, &alpn_proto, &alpn_len);
950 if (alpn_len > 0) {
951 npn_proto_.assign(reinterpret_cast<const char*>(alpn_proto), alpn_len);
952 npn_status_ = kNextProtoNegotiated;
bnc0d28ea52014-10-13 15:15:38953 set_negotiation_extension(kExtensionALPN);
[email protected]abc44b752014-07-30 03:52:15954 }
955 }
956
davidben09c3d072014-08-25 20:33:58957 RecordChannelIDSupport(channel_id_service_,
958 channel_id_xtn_negotiated_,
959 ssl_config_.channel_id_enabled,
960 crypto::ECPrivateKey::IsSupported());
961
davidbend1fb2f12014-11-08 02:51:00962 // Only record OCSP histograms if OCSP was requested.
963 if (ssl_config_.signed_cert_timestamps_enabled ||
964 IsOCSPStaplingSupported()) {
davidben54015aa2014-12-02 22:16:23965 const uint8_t* ocsp_response;
davidbend1fb2f12014-11-08 02:51:00966 size_t ocsp_response_len;
967 SSL_get0_ocsp_response(ssl_, &ocsp_response, &ocsp_response_len);
968
969 set_stapled_ocsp_response_received(ocsp_response_len != 0);
970 UMA_HISTOGRAM_BOOLEAN("Net.OCSPResponseStapled", ocsp_response_len != 0);
971 }
davidbeneb5f8ef32014-09-04 14:14:32972
davidben54015aa2014-12-02 22:16:23973 const uint8_t* sct_list;
davidbeneb5f8ef32014-09-04 14:14:32974 size_t sct_list_len;
975 SSL_get0_signed_cert_timestamp_list(ssl_, &sct_list, &sct_list_len);
976 set_signed_cert_timestamps_received(sct_list_len != 0);
977
[email protected]abc44b752014-07-30 03:52:15978 // Verify the certificate.
davidben30798ed82014-09-19 19:28:20979 UpdateServerCert();
[email protected]b9b651f2013-11-09 04:32:22980 GotoState(STATE_VERIFY_CERT);
981 } else {
vadimtc4e29112014-12-18 01:44:21982 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
983 tracked_objects::ScopedTracker tracking_profile4(
984 FROM_HERE_WITH_EXPLICIT_FUNCTION(
985 "424386 SSLClientSocketOpenSSL::DoHandshake4"));
986
davidben8114f802015-03-25 17:02:34987 if (client_auth_cert_needed_)
988 return ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
989
[email protected]b9b651f2013-11-09 04:32:22990 int ssl_error = SSL_get_error(ssl_, rv);
991
992 if (ssl_error == SSL_ERROR_WANT_CHANNEL_ID_LOOKUP) {
[email protected]faff9852014-06-21 06:13:46993 // The server supports channel ID. Stop to look one up before returning to
994 // the handshake.
995 channel_id_xtn_negotiated_ = true;
996 GotoState(STATE_CHANNEL_ID_LOOKUP);
997 return OK;
[email protected]b9b651f2013-11-09 04:32:22998 }
999
davidbena4409c62014-08-27 17:05:511000 OpenSSLErrorInfo error_info;
1001 net_error = MapOpenSSLErrorWithDetails(ssl_error, err_tracer, &error_info);
[email protected]faff9852014-06-21 06:13:461002
[email protected]b9b651f2013-11-09 04:32:221003 // If not done, stay in this state
1004 if (net_error == ERR_IO_PENDING) {
1005 GotoState(STATE_HANDSHAKE);
1006 } else {
1007 LOG(ERROR) << "handshake failed; returned " << rv
1008 << ", SSL error code " << ssl_error
1009 << ", net_error " << net_error;
1010 net_log_.AddEvent(
1011 NetLog::TYPE_SSL_HANDSHAKE_ERROR,
davidbena4409c62014-08-27 17:05:511012 CreateNetLogOpenSSLErrorCallback(net_error, ssl_error, error_info));
[email protected]b9b651f2013-11-09 04:32:221013 }
1014 }
1015 return net_error;
1016}
1017
[email protected]faff9852014-06-21 06:13:461018int SSLClientSocketOpenSSL::DoChannelIDLookup() {
rch98cf4472015-02-13 00:14:141019 net_log_.AddEvent(NetLog::TYPE_SSL_CHANNEL_ID_REQUESTED);
[email protected]faff9852014-06-21 06:13:461020 GotoState(STATE_CHANNEL_ID_LOOKUP_COMPLETE);
[email protected]6b8a3c742014-07-25 00:25:351021 return channel_id_service_->GetOrCreateChannelID(
[email protected]faff9852014-06-21 06:13:461022 host_and_port_.host(),
1023 &channel_id_private_key_,
1024 &channel_id_cert_,
1025 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete,
1026 base::Unretained(this)),
1027 &channel_id_request_handle_);
1028}
1029
1030int SSLClientSocketOpenSSL::DoChannelIDLookupComplete(int result) {
1031 if (result < 0)
1032 return result;
1033
1034 DCHECK_LT(0u, channel_id_private_key_.size());
1035 // Decode key.
1036 std::vector<uint8> encrypted_private_key_info;
1037 std::vector<uint8> subject_public_key_info;
1038 encrypted_private_key_info.assign(
1039 channel_id_private_key_.data(),
1040 channel_id_private_key_.data() + channel_id_private_key_.size());
1041 subject_public_key_info.assign(
1042 channel_id_cert_.data(),
1043 channel_id_cert_.data() + channel_id_cert_.size());
1044 scoped_ptr<crypto::ECPrivateKey> ec_private_key(
1045 crypto::ECPrivateKey::CreateFromEncryptedPrivateKeyInfo(
[email protected]6b8a3c742014-07-25 00:25:351046 ChannelIDService::kEPKIPassword,
[email protected]faff9852014-06-21 06:13:461047 encrypted_private_key_info,
1048 subject_public_key_info));
1049 if (!ec_private_key) {
1050 LOG(ERROR) << "Failed to import Channel ID.";
1051 return ERR_CHANNEL_ID_IMPORT_FAILED;
1052 }
1053
1054 // Hand the key to OpenSSL. Check for error in case OpenSSL rejects the key
1055 // type.
1056 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1057 int rv = SSL_set1_tls_channel_id(ssl_, ec_private_key->key());
1058 if (!rv) {
1059 LOG(ERROR) << "Failed to set Channel ID.";
1060 int err = SSL_get_error(ssl_, rv);
1061 return MapOpenSSLError(err, err_tracer);
1062 }
1063
1064 // Return to the handshake.
1065 set_channel_id_sent(true);
rch98cf4472015-02-13 00:14:141066 net_log_.AddEvent(NetLog::TYPE_SSL_CHANNEL_ID_PROVIDED);
[email protected]faff9852014-06-21 06:13:461067 GotoState(STATE_HANDSHAKE);
1068 return OK;
1069}
1070
[email protected]b9b651f2013-11-09 04:32:221071int SSLClientSocketOpenSSL::DoVerifyCert(int result) {
davidben30798ed82014-09-19 19:28:201072 DCHECK(!server_cert_chain_->empty());
davidben09c3d072014-08-25 20:33:581073 DCHECK(start_cert_verification_time_.is_null());
davidben30798ed82014-09-19 19:28:201074
[email protected]b9b651f2013-11-09 04:32:221075 GotoState(STATE_VERIFY_CERT_COMPLETE);
1076
davidben30798ed82014-09-19 19:28:201077 // If the certificate is bad and has been previously accepted, use
1078 // the previous status and bypass the error.
1079 base::StringPiece der_cert;
1080 if (!x509_util::GetDER(server_cert_chain_->Get(0), &der_cert)) {
1081 NOTREACHED();
1082 return ERR_CERT_INVALID;
1083 }
[email protected]b9b651f2013-11-09 04:32:221084 CertStatus cert_status;
davidben30798ed82014-09-19 19:28:201085 if (ssl_config_.IsAllowedBadCert(der_cert, &cert_status)) {
[email protected]b9b651f2013-11-09 04:32:221086 VLOG(1) << "Received an expected bad cert with status: " << cert_status;
1087 server_cert_verify_result_.Reset();
1088 server_cert_verify_result_.cert_status = cert_status;
1089 server_cert_verify_result_.verified_cert = server_cert_;
1090 return OK;
1091 }
1092
davidben30798ed82014-09-19 19:28:201093 // When running in a sandbox, it may not be possible to create an
1094 // X509Certificate*, as that may depend on OS functionality blocked
1095 // in the sandbox.
1096 if (!server_cert_.get()) {
1097 server_cert_verify_result_.Reset();
1098 server_cert_verify_result_.cert_status = CERT_STATUS_INVALID;
1099 return ERR_CERT_INVALID;
1100 }
1101
davidben09c3d072014-08-25 20:33:581102 start_cert_verification_time_ = base::TimeTicks::Now();
1103
[email protected]b9b651f2013-11-09 04:32:221104 int flags = 0;
1105 if (ssl_config_.rev_checking_enabled)
1106 flags |= CertVerifier::VERIFY_REV_CHECKING_ENABLED;
1107 if (ssl_config_.verify_ev_cert)
1108 flags |= CertVerifier::VERIFY_EV_CERT;
1109 if (ssl_config_.cert_io_enabled)
1110 flags |= CertVerifier::VERIFY_CERT_IO_ENABLED;
1111 if (ssl_config_.rev_checking_required_local_anchors)
1112 flags |= CertVerifier::VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS;
1113 verifier_.reset(new SingleRequestCertVerifier(cert_verifier_));
1114 return verifier_->Verify(
1115 server_cert_.get(),
1116 host_and_port_.host(),
1117 flags,
[email protected]591cffcd2014-08-18 20:02:301118 // TODO(davidben): Route the CRLSet through SSLConfig so
1119 // SSLClientSocket doesn't depend on SSLConfigService.
1120 SSLConfigService::GetCRLSet().get(),
[email protected]b9b651f2013-11-09 04:32:221121 &server_cert_verify_result_,
1122 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete,
1123 base::Unretained(this)),
1124 net_log_);
1125}
1126
1127int SSLClientSocketOpenSSL::DoVerifyCertComplete(int result) {
1128 verifier_.reset();
1129
davidben09c3d072014-08-25 20:33:581130 if (!start_cert_verification_time_.is_null()) {
1131 base::TimeDelta verify_time =
1132 base::TimeTicks::Now() - start_cert_verification_time_;
1133 if (result == OK) {
1134 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTime", verify_time);
1135 } else {
1136 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTimeError", verify_time);
1137 }
1138 }
1139
davidben85574eb2014-12-12 03:01:571140 if (result == OK) {
davidben85574eb2014-12-12 03:01:571141 if (SSL_session_reused(ssl_)) {
1142 // Record whether or not the server tried to resume a session for a
1143 // different version. See https://crbug.com/441456.
1144 UMA_HISTOGRAM_BOOLEAN(
1145 "Net.SSLSessionVersionMatch",
1146 SSL_version(ssl_) == SSL_get_session(ssl_)->ssl_version);
1147 }
1148 }
1149
[email protected]8bd4e7a2014-08-09 14:49:171150 const CertStatus cert_status = server_cert_verify_result_.cert_status;
1151 if (transport_security_state_ &&
1152 (result == OK ||
1153 (IsCertificateError(result) && IsCertStatusMinorError(cert_status))) &&
1154 !transport_security_state_->CheckPublicKeyPins(
1155 host_and_port_.host(),
[email protected]8bd4e7a2014-08-09 14:49:171156 server_cert_verify_result_.is_issued_by_known_root,
1157 server_cert_verify_result_.public_key_hashes,
1158 &pinning_failure_log_)) {
1159 result = ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN;
1160 }
1161
[email protected]b9b651f2013-11-09 04:32:221162 if (result == OK) {
davidbeneb5f8ef32014-09-04 14:14:321163 // Only check Certificate Transparency if there were no other errors with
1164 // the connection.
1165 VerifyCT();
1166
[email protected]b9b651f2013-11-09 04:32:221167 // TODO(joth): Work out if we need to remember the intermediate CA certs
1168 // when the server sends them to us, and do so here.
[email protected]a8fed1742013-12-27 02:14:241169 SSLContext::GetInstance()->session_cache()->MarkSSLSessionAsGood(ssl_);
[email protected]b9b651f2013-11-09 04:32:221170 } else {
1171 DVLOG(1) << "DoVerifyCertComplete error " << ErrorToString(result)
1172 << " (" << result << ")";
1173 }
1174
[email protected]64b5c892014-08-08 09:39:261175 completed_connect_ = true;
[email protected]b9b651f2013-11-09 04:32:221176 // Exit DoHandshakeLoop and return the result to the caller to Connect.
1177 DCHECK_EQ(STATE_NONE, next_handshake_state_);
1178 return result;
1179}
1180
1181void SSLClientSocketOpenSSL::DoConnectCallback(int rv) {
1182 if (!user_connect_callback_.is_null()) {
1183 CompletionCallback c = user_connect_callback_;
1184 user_connect_callback_.Reset();
1185 c.Run(rv > OK ? OK : rv);
1186 }
1187}
1188
davidben30798ed82014-09-19 19:28:201189void SSLClientSocketOpenSSL::UpdateServerCert() {
vadimtc4e29112014-12-18 01:44:211190 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1191 tracked_objects::ScopedTracker tracking_profile(
1192 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1193 "424386 SSLClientSocketOpenSSL::UpdateServerCert"));
1194
[email protected]76e85392014-03-20 17:54:141195 server_cert_chain_->Reset(SSL_get_peer_cert_chain(ssl_));
vadimt5a243282014-12-24 00:26:161196
1197 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1198 tracked_objects::ScopedTracker tracking_profile1(
1199 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1200 "424386 SSLClientSocketOpenSSL::UpdateServerCert1"));
[email protected]7f38da8a2014-03-17 16:44:261201 server_cert_ = server_cert_chain_->AsOSChain();
[email protected]76e85392014-03-20 17:54:141202
davidben30798ed82014-09-19 19:28:201203 if (server_cert_.get()) {
1204 net_log_.AddEvent(
1205 NetLog::TYPE_SSL_CERTIFICATES_RECEIVED,
1206 base::Bind(&NetLogX509CertificateCallback,
1207 base::Unretained(server_cert_.get())));
davidbend1fb2f12014-11-08 02:51:001208
1209 // TODO(rsleevi): Plumb an OCSP response into the Mac system library and
1210 // update IsOCSPStaplingSupported for Mac. https://crbug.com/430714
1211 if (IsOCSPStaplingSupported()) {
1212#if defined(OS_WIN)
vadimt5a243282014-12-24 00:26:161213 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is
1214 // fixed.
1215 tracked_objects::ScopedTracker tracking_profile2(
1216 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1217 "424386 SSLClientSocketOpenSSL::UpdateServerCert2"));
1218
davidben54015aa2014-12-02 22:16:231219 const uint8_t* ocsp_response_raw;
davidbend1fb2f12014-11-08 02:51:001220 size_t ocsp_response_len;
1221 SSL_get0_ocsp_response(ssl_, &ocsp_response_raw, &ocsp_response_len);
1222
1223 CRYPT_DATA_BLOB ocsp_response_blob;
1224 ocsp_response_blob.cbData = ocsp_response_len;
davidben54015aa2014-12-02 22:16:231225 ocsp_response_blob.pbData = const_cast<BYTE*>(ocsp_response_raw);
davidbend1fb2f12014-11-08 02:51:001226 BOOL ok = CertSetCertificateContextProperty(
1227 server_cert_->os_cert_handle(),
1228 CERT_OCSP_RESPONSE_PROP_ID,
1229 CERT_SET_PROPERTY_IGNORE_PERSIST_ERROR_FLAG,
1230 &ocsp_response_blob);
1231 if (!ok) {
1232 VLOG(1) << "Failed to set OCSP response property: "
1233 << GetLastError();
1234 }
1235#else
1236 NOTREACHED();
1237#endif
1238 }
davidben30798ed82014-09-19 19:28:201239 }
[email protected]b9b651f2013-11-09 04:32:221240}
1241
davidbeneb5f8ef32014-09-04 14:14:321242void SSLClientSocketOpenSSL::VerifyCT() {
1243 if (!cert_transparency_verifier_)
1244 return;
1245
davidben54015aa2014-12-02 22:16:231246 const uint8_t* ocsp_response_raw;
davidbeneb5f8ef32014-09-04 14:14:321247 size_t ocsp_response_len;
1248 SSL_get0_ocsp_response(ssl_, &ocsp_response_raw, &ocsp_response_len);
1249 std::string ocsp_response;
1250 if (ocsp_response_len > 0) {
1251 ocsp_response.assign(reinterpret_cast<const char*>(ocsp_response_raw),
1252 ocsp_response_len);
1253 }
1254
davidben54015aa2014-12-02 22:16:231255 const uint8_t* sct_list_raw;
davidbeneb5f8ef32014-09-04 14:14:321256 size_t sct_list_len;
1257 SSL_get0_signed_cert_timestamp_list(ssl_, &sct_list_raw, &sct_list_len);
1258 std::string sct_list;
1259 if (sct_list_len > 0)
1260 sct_list.assign(reinterpret_cast<const char*>(sct_list_raw), sct_list_len);
1261
1262 // Note that this is a completely synchronous operation: The CT Log Verifier
1263 // gets all the data it needs for SCT verification and does not do any
1264 // external communication.
eranm6571b2b2014-12-03 15:53:231265 cert_transparency_verifier_->Verify(
1266 server_cert_verify_result_.verified_cert.get(), ocsp_response, sct_list,
1267 &ct_verify_result_, net_log_);
davidbeneb5f8ef32014-09-04 14:14:321268
eranm6571b2b2014-12-03 15:53:231269 if (!policy_enforcer_) {
1270 server_cert_verify_result_.cert_status &= ~CERT_STATUS_IS_EV;
1271 } else {
1272 if (server_cert_verify_result_.cert_status & CERT_STATUS_IS_EV) {
1273 scoped_refptr<ct::EVCertsWhitelist> ev_whitelist =
1274 SSLConfigService::GetEVCertsWhitelist();
1275 if (!policy_enforcer_->DoesConformToCTEVPolicy(
1276 server_cert_verify_result_.verified_cert.get(),
eranm18a019272014-12-18 08:43:231277 ev_whitelist.get(), ct_verify_result_, net_log_)) {
eranm6571b2b2014-12-03 15:53:231278 // TODO(eranm): Log via the BoundNetLog, see crbug.com/437766
1279 VLOG(1) << "EV certificate for "
1280 << server_cert_verify_result_.verified_cert->subject()
1281 .GetDisplayName()
1282 << " does not conform to CT policy, removing EV status.";
1283 server_cert_verify_result_.cert_status &= ~CERT_STATUS_IS_EV;
1284 }
1285 }
1286 }
davidbeneb5f8ef32014-09-04 14:14:321287}
1288
[email protected]b9b651f2013-11-09 04:32:221289void SSLClientSocketOpenSSL::OnHandshakeIOComplete(int result) {
1290 int rv = DoHandshakeLoop(result);
1291 if (rv != ERR_IO_PENDING) {
1292 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
1293 DoConnectCallback(rv);
1294 }
1295}
1296
1297void SSLClientSocketOpenSSL::OnSendComplete(int result) {
1298 if (next_handshake_state_ == STATE_HANDSHAKE) {
1299 // In handshake phase.
1300 OnHandshakeIOComplete(result);
1301 return;
1302 }
1303
1304 // OnSendComplete may need to call DoPayloadRead while the renegotiation
1305 // handshake is in progress.
1306 int rv_read = ERR_IO_PENDING;
1307 int rv_write = ERR_IO_PENDING;
1308 bool network_moved;
1309 do {
1310 if (user_read_buf_.get())
1311 rv_read = DoPayloadRead();
1312 if (user_write_buf_.get())
1313 rv_write = DoPayloadWrite();
1314 network_moved = DoTransportIO();
1315 } while (rv_read == ERR_IO_PENDING && rv_write == ERR_IO_PENDING &&
1316 (user_read_buf_.get() || user_write_buf_.get()) && network_moved);
1317
1318 // Performing the Read callback may cause |this| to be deleted. If this
1319 // happens, the Write callback should not be invoked. Guard against this by
1320 // holding a WeakPtr to |this| and ensuring it's still valid.
1321 base::WeakPtr<SSLClientSocketOpenSSL> guard(weak_factory_.GetWeakPtr());
1322 if (user_read_buf_.get() && rv_read != ERR_IO_PENDING)
1323 DoReadCallback(rv_read);
1324
1325 if (!guard.get())
1326 return;
1327
1328 if (user_write_buf_.get() && rv_write != ERR_IO_PENDING)
1329 DoWriteCallback(rv_write);
1330}
1331
1332void SSLClientSocketOpenSSL::OnRecvComplete(int result) {
1333 if (next_handshake_state_ == STATE_HANDSHAKE) {
1334 // In handshake phase.
1335 OnHandshakeIOComplete(result);
1336 return;
1337 }
1338
1339 // Network layer received some data, check if client requested to read
1340 // decrypted data.
1341 if (!user_read_buf_.get())
1342 return;
1343
davidben1b133ad2014-10-23 04:23:131344 int rv = DoReadLoop();
[email protected]b9b651f2013-11-09 04:32:221345 if (rv != ERR_IO_PENDING)
1346 DoReadCallback(rv);
1347}
1348
1349int SSLClientSocketOpenSSL::DoHandshakeLoop(int last_io_result) {
1350 int rv = last_io_result;
1351 do {
1352 // Default to STATE_NONE for next state.
1353 // (This is a quirk carried over from the windows
1354 // implementation. It makes reading the logs a bit harder.)
1355 // State handlers can and often do call GotoState just
1356 // to stay in the current state.
1357 State state = next_handshake_state_;
1358 GotoState(STATE_NONE);
1359 switch (state) {
1360 case STATE_HANDSHAKE:
1361 rv = DoHandshake();
1362 break;
[email protected]faff9852014-06-21 06:13:461363 case STATE_CHANNEL_ID_LOOKUP:
1364 DCHECK_EQ(OK, rv);
1365 rv = DoChannelIDLookup();
1366 break;
1367 case STATE_CHANNEL_ID_LOOKUP_COMPLETE:
1368 rv = DoChannelIDLookupComplete(rv);
1369 break;
[email protected]b9b651f2013-11-09 04:32:221370 case STATE_VERIFY_CERT:
[email protected]faff9852014-06-21 06:13:461371 DCHECK_EQ(OK, rv);
[email protected]b9b651f2013-11-09 04:32:221372 rv = DoVerifyCert(rv);
1373 break;
1374 case STATE_VERIFY_CERT_COMPLETE:
1375 rv = DoVerifyCertComplete(rv);
1376 break;
1377 case STATE_NONE:
1378 default:
1379 rv = ERR_UNEXPECTED;
1380 NOTREACHED() << "unexpected state" << state;
1381 break;
1382 }
1383
1384 bool network_moved = DoTransportIO();
1385 if (network_moved && next_handshake_state_ == STATE_HANDSHAKE) {
1386 // In general we exit the loop if rv is ERR_IO_PENDING. In this
1387 // special case we keep looping even if rv is ERR_IO_PENDING because
1388 // the transport IO may allow DoHandshake to make progress.
1389 rv = OK; // This causes us to stay in the loop.
1390 }
1391 } while (rv != ERR_IO_PENDING && next_handshake_state_ != STATE_NONE);
1392 return rv;
1393}
1394
davidben1b133ad2014-10-23 04:23:131395int SSLClientSocketOpenSSL::DoReadLoop() {
[email protected]b9b651f2013-11-09 04:32:221396 bool network_moved;
1397 int rv;
1398 do {
1399 rv = DoPayloadRead();
1400 network_moved = DoTransportIO();
1401 } while (rv == ERR_IO_PENDING && network_moved);
1402
1403 return rv;
1404}
1405
davidben1b133ad2014-10-23 04:23:131406int SSLClientSocketOpenSSL::DoWriteLoop() {
[email protected]b9b651f2013-11-09 04:32:221407 bool network_moved;
1408 int rv;
1409 do {
1410 rv = DoPayloadWrite();
1411 network_moved = DoTransportIO();
1412 } while (rv == ERR_IO_PENDING && network_moved);
1413
1414 return rv;
1415}
1416
1417int SSLClientSocketOpenSSL::DoPayloadRead() {
1418 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1419
davidben7e555daf2015-03-25 17:03:291420 DCHECK_LT(0, user_read_buf_len_);
1421 DCHECK(user_read_buf_.get());
1422
[email protected]b9b651f2013-11-09 04:32:221423 int rv;
1424 if (pending_read_error_ != kNoPendingReadResult) {
1425 rv = pending_read_error_;
1426 pending_read_error_ = kNoPendingReadResult;
1427 if (rv == 0) {
1428 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED,
1429 rv, user_read_buf_->data());
davidbenb8c23212014-10-28 00:12:161430 } else {
1431 net_log_.AddEvent(
1432 NetLog::TYPE_SSL_READ_ERROR,
1433 CreateNetLogOpenSSLErrorCallback(rv, pending_read_ssl_error_,
1434 pending_read_error_info_));
[email protected]b9b651f2013-11-09 04:32:221435 }
davidbenb8c23212014-10-28 00:12:161436 pending_read_ssl_error_ = SSL_ERROR_NONE;
1437 pending_read_error_info_ = OpenSSLErrorInfo();
[email protected]b9b651f2013-11-09 04:32:221438 return rv;
1439 }
1440
1441 int total_bytes_read = 0;
davidben7e555daf2015-03-25 17:03:291442 int ssl_ret;
[email protected]b9b651f2013-11-09 04:32:221443 do {
davidben7e555daf2015-03-25 17:03:291444 ssl_ret = SSL_read(ssl_, user_read_buf_->data() + total_bytes_read,
1445 user_read_buf_len_ - total_bytes_read);
1446 if (ssl_ret > 0)
1447 total_bytes_read += ssl_ret;
1448 } while (total_bytes_read < user_read_buf_len_ && ssl_ret > 0);
[email protected]b9b651f2013-11-09 04:32:221449
davidben7e555daf2015-03-25 17:03:291450 // Although only the final SSL_read call may have failed, the failure needs to
1451 // processed immediately, while the information still available in OpenSSL's
1452 // error queue.
1453 if (client_auth_cert_needed_) {
1454 pending_read_error_ = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
1455 } else if (ssl_ret <= 0) {
1456 // A zero return from SSL_read may mean any of:
1457 // - The underlying BIO_read returned 0.
1458 // - The peer sent a close_notify.
1459 // - Any arbitrary error. https://crbug.com/466303
[email protected]b9b651f2013-11-09 04:32:221460 //
davidben7e555daf2015-03-25 17:03:291461 // TransportReadComplete converts the first to an ERR_CONNECTION_CLOSED
1462 // error, so it does not occur. The second and third are distinguished by
1463 // SSL_ERROR_ZERO_RETURN.
1464 pending_read_ssl_error_ = SSL_get_error(ssl_, ssl_ret);
1465 if (pending_read_ssl_error_ == SSL_ERROR_ZERO_RETURN) {
1466 pending_read_error_ = 0;
1467 } else {
1468 pending_read_error_ = MapOpenSSLErrorWithDetails(
1469 pending_read_ssl_error_, err_tracer, &pending_read_error_info_);
[email protected]b9b651f2013-11-09 04:32:221470 }
1471
davidben7e555daf2015-03-25 17:03:291472 // Many servers do not reliably send a close_notify alert when shutting down
1473 // a connection, and instead terminate the TCP connection. This is reported
1474 // as ERR_CONNECTION_CLOSED. Because of this, map the unclean shutdown to a
1475 // graceful EOF, instead of treating it as an error as it should be.
1476 if (pending_read_error_ == ERR_CONNECTION_CLOSED)
1477 pending_read_error_ = 0;
1478 }
davidbenbe6ce7ec2014-10-20 19:15:561479
davidben7e555daf2015-03-25 17:03:291480 if (total_bytes_read > 0) {
1481 // Return any bytes read to the caller. The error will be deferred to the
1482 // next call of DoPayloadRead.
1483 rv = total_bytes_read;
davidbenbe6ce7ec2014-10-20 19:15:561484
davidben7e555daf2015-03-25 17:03:291485 // Do not treat insufficient data as an error to return in the next call to
1486 // DoPayloadRead() - instead, let the call fall through to check SSL_read()
1487 // again. This is because DoTransportIO() may complete in between the next
1488 // call to DoPayloadRead(), and thus it is important to check SSL_read() on
1489 // subsequent invocations to see if a complete record may now be read.
1490 if (pending_read_error_ == ERR_IO_PENDING)
1491 pending_read_error_ = kNoPendingReadResult;
1492 } else {
1493 // No bytes were returned. Return the pending read error immediately.
1494 DCHECK_NE(kNoPendingReadResult, pending_read_error_);
1495 rv = pending_read_error_;
1496 pending_read_error_ = kNoPendingReadResult;
[email protected]b9b651f2013-11-09 04:32:221497 }
1498
1499 if (rv >= 0) {
1500 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, rv,
1501 user_read_buf_->data());
davidbenb8c23212014-10-28 00:12:161502 } else if (rv != ERR_IO_PENDING) {
1503 net_log_.AddEvent(
1504 NetLog::TYPE_SSL_READ_ERROR,
1505 CreateNetLogOpenSSLErrorCallback(rv, pending_read_ssl_error_,
1506 pending_read_error_info_));
1507 pending_read_ssl_error_ = SSL_ERROR_NONE;
1508 pending_read_error_info_ = OpenSSLErrorInfo();
[email protected]b9b651f2013-11-09 04:32:221509 }
1510 return rv;
1511}
1512
1513int SSLClientSocketOpenSSL::DoPayloadWrite() {
1514 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1515 int rv = SSL_write(ssl_, user_write_buf_->data(), user_write_buf_len_);
rsleevif020edc2015-03-16 19:31:241516
[email protected]b9b651f2013-11-09 04:32:221517 if (rv >= 0) {
1518 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_SENT, rv,
1519 user_write_buf_->data());
1520 return rv;
1521 }
1522
davidbenb8c23212014-10-28 00:12:161523 int ssl_error = SSL_get_error(ssl_, rv);
1524 OpenSSLErrorInfo error_info;
1525 int net_error = MapOpenSSLErrorWithDetails(ssl_error, err_tracer,
1526 &error_info);
1527
1528 if (net_error != ERR_IO_PENDING) {
1529 net_log_.AddEvent(
1530 NetLog::TYPE_SSL_WRITE_ERROR,
1531 CreateNetLogOpenSSLErrorCallback(net_error, ssl_error, error_info));
1532 }
1533 return net_error;
[email protected]b9b651f2013-11-09 04:32:221534}
1535
1536int SSLClientSocketOpenSSL::BufferSend(void) {
1537 if (transport_send_busy_)
1538 return ERR_IO_PENDING;
1539
haavardm2d92e722014-12-19 13:45:441540 size_t buffer_read_offset;
1541 uint8_t* read_buf;
1542 size_t max_read;
1543 int status = BIO_zero_copy_get_read_buf(transport_bio_, &read_buf,
1544 &buffer_read_offset, &max_read);
1545 DCHECK_EQ(status, 1); // Should never fail.
1546 if (!max_read)
1547 return 0; // Nothing pending in the OpenSSL write BIO.
1548 CHECK_EQ(read_buf, reinterpret_cast<uint8_t*>(send_buffer_->StartOfBuffer()));
1549 CHECK_LT(buffer_read_offset, static_cast<size_t>(send_buffer_->capacity()));
1550 send_buffer_->set_offset(buffer_read_offset);
[email protected]b9b651f2013-11-09 04:32:221551
1552 int rv = transport_->socket()->Write(
haavardm2d92e722014-12-19 13:45:441553 send_buffer_.get(), max_read,
[email protected]b9b651f2013-11-09 04:32:221554 base::Bind(&SSLClientSocketOpenSSL::BufferSendComplete,
1555 base::Unretained(this)));
1556 if (rv == ERR_IO_PENDING) {
1557 transport_send_busy_ = true;
1558 } else {
1559 TransportWriteComplete(rv);
1560 }
1561 return rv;
1562}
1563
1564int SSLClientSocketOpenSSL::BufferRecv(void) {
1565 if (transport_recv_busy_)
1566 return ERR_IO_PENDING;
1567
1568 // Determine how much was requested from |transport_bio_| that was not
1569 // actually available.
1570 size_t requested = BIO_ctrl_get_read_request(transport_bio_);
1571 if (requested == 0) {
1572 // This is not a perfect match of error codes, as no operation is
1573 // actually pending. However, returning 0 would be interpreted as
1574 // a possible sign of EOF, which is also an inappropriate match.
1575 return ERR_IO_PENDING;
1576 }
1577
1578 // Known Issue: While only reading |requested| data is the more correct
1579 // implementation, it has the downside of resulting in frequent reads:
1580 // One read for the SSL record header (~5 bytes) and one read for the SSL
1581 // record body. Rather than issuing these reads to the underlying socket
1582 // (and constantly allocating new IOBuffers), a single Read() request to
1583 // fill |transport_bio_| is issued. As long as an SSL client socket cannot
1584 // be gracefully shutdown (via SSL close alerts) and re-used for non-SSL
1585 // traffic, this over-subscribed Read()ing will not cause issues.
haavardm2d92e722014-12-19 13:45:441586
1587 size_t buffer_write_offset;
1588 uint8_t* write_buf;
1589 size_t max_write;
1590 int status = BIO_zero_copy_get_write_buf(transport_bio_, &write_buf,
1591 &buffer_write_offset, &max_write);
1592 DCHECK_EQ(status, 1); // Should never fail.
[email protected]b9b651f2013-11-09 04:32:221593 if (!max_write)
1594 return ERR_IO_PENDING;
1595
haavardm2d92e722014-12-19 13:45:441596 CHECK_EQ(write_buf,
1597 reinterpret_cast<uint8_t*>(recv_buffer_->StartOfBuffer()));
1598 CHECK_LT(buffer_write_offset, static_cast<size_t>(recv_buffer_->capacity()));
1599
1600 recv_buffer_->set_offset(buffer_write_offset);
[email protected]b9b651f2013-11-09 04:32:221601 int rv = transport_->socket()->Read(
1602 recv_buffer_.get(),
1603 max_write,
1604 base::Bind(&SSLClientSocketOpenSSL::BufferRecvComplete,
1605 base::Unretained(this)));
1606 if (rv == ERR_IO_PENDING) {
1607 transport_recv_busy_ = true;
1608 } else {
[email protected]3e5c6922014-02-06 02:42:161609 rv = TransportReadComplete(rv);
[email protected]b9b651f2013-11-09 04:32:221610 }
1611 return rv;
1612}
1613
1614void SSLClientSocketOpenSSL::BufferSendComplete(int result) {
[email protected]b9b651f2013-11-09 04:32:221615 TransportWriteComplete(result);
1616 OnSendComplete(result);
1617}
1618
1619void SSLClientSocketOpenSSL::BufferRecvComplete(int result) {
[email protected]3e5c6922014-02-06 02:42:161620 result = TransportReadComplete(result);
[email protected]b9b651f2013-11-09 04:32:221621 OnRecvComplete(result);
1622}
1623
1624void SSLClientSocketOpenSSL::TransportWriteComplete(int result) {
1625 DCHECK(ERR_IO_PENDING != result);
haavardm2d92e722014-12-19 13:45:441626 int bytes_written = 0;
[email protected]b9b651f2013-11-09 04:32:221627 if (result < 0) {
[email protected]5aea79182014-07-14 20:43:411628 // Record the error. Save it to be reported in a future read or write on
1629 // transport_bio_'s peer.
[email protected]3e5c6922014-02-06 02:42:161630 transport_write_error_ = result;
[email protected]b9b651f2013-11-09 04:32:221631 } else {
haavardm2d92e722014-12-19 13:45:441632 bytes_written = result;
[email protected]b9b651f2013-11-09 04:32:221633 }
haavardm2d92e722014-12-19 13:45:441634 DCHECK_GE(send_buffer_->RemainingCapacity(), bytes_written);
1635 int ret = BIO_zero_copy_get_read_buf_done(transport_bio_, bytes_written);
1636 DCHECK_EQ(1, ret);
1637 transport_send_busy_ = false;
[email protected]b9b651f2013-11-09 04:32:221638}
1639
[email protected]3e5c6922014-02-06 02:42:161640int SSLClientSocketOpenSSL::TransportReadComplete(int result) {
[email protected]b9b651f2013-11-09 04:32:221641 DCHECK(ERR_IO_PENDING != result);
[email protected]5aea79182014-07-14 20:43:411642 // If an EOF, canonicalize to ERR_CONNECTION_CLOSED here so MapOpenSSLError
1643 // does not report success.
1644 if (result == 0)
1645 result = ERR_CONNECTION_CLOSED;
haavardm2d92e722014-12-19 13:45:441646 int bytes_read = 0;
[email protected]5aea79182014-07-14 20:43:411647 if (result < 0) {
[email protected]b9b651f2013-11-09 04:32:221648 DVLOG(1) << "TransportReadComplete result " << result;
[email protected]5aea79182014-07-14 20:43:411649 // Received an error. Save it to be reported in a future read on
1650 // transport_bio_'s peer.
1651 transport_read_error_ = result;
[email protected]b9b651f2013-11-09 04:32:221652 } else {
haavardm2d92e722014-12-19 13:45:441653 bytes_read = result;
[email protected]b9b651f2013-11-09 04:32:221654 }
haavardm2d92e722014-12-19 13:45:441655 DCHECK_GE(recv_buffer_->RemainingCapacity(), bytes_read);
1656 int ret = BIO_zero_copy_get_write_buf_done(transport_bio_, bytes_read);
1657 DCHECK_EQ(1, ret);
[email protected]b9b651f2013-11-09 04:32:221658 transport_recv_busy_ = false;
[email protected]3e5c6922014-02-06 02:42:161659 return result;
[email protected]b9b651f2013-11-09 04:32:221660}
1661
[email protected]82c59022014-08-15 09:38:271662int SSLClientSocketOpenSSL::ClientCertRequestCallback(SSL* ssl) {
vadimtb2a77c762014-11-21 19:49:221663 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1664 tracked_objects::ScopedTracker tracking_profile(
1665 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1666 "424386 SSLClientSocketOpenSSL::ClientCertRequestCallback"));
1667
[email protected]5ac981e182010-12-06 17:56:271668 DVLOG(3) << "OpenSSL ClientCertRequestCallback called";
1669 DCHECK(ssl == ssl_);
[email protected]82c59022014-08-15 09:38:271670
davidbenaf42cbe2014-11-13 03:27:461671 net_log_.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED);
1672
[email protected]82c59022014-08-15 09:38:271673 // Clear any currently configured certificates.
1674 SSL_certs_clear(ssl_);
[email protected]97a854f2014-07-29 07:51:361675
1676#if defined(OS_IOS)
1677 // TODO(droger): Support client auth on iOS. See http://crbug.com/145954).
1678 LOG(WARNING) << "Client auth is not supported";
1679#else // !defined(OS_IOS)
[email protected]5ac981e182010-12-06 17:56:271680 if (!ssl_config_.send_client_cert) {
[email protected]515adc22013-01-09 16:01:231681 // First pass: we know that a client certificate is needed, but we do not
1682 // have one at hand.
[email protected]5ac981e182010-12-06 17:56:271683 client_auth_cert_needed_ = true;
[email protected]515adc22013-01-09 16:01:231684 STACK_OF(X509_NAME) *authorities = SSL_get_client_CA_list(ssl);
[email protected]edfd0f42014-07-22 18:20:371685 for (size_t i = 0; i < sk_X509_NAME_num(authorities); i++) {
[email protected]515adc22013-01-09 16:01:231686 X509_NAME *ca_name = (X509_NAME *)sk_X509_NAME_value(authorities, i);
1687 unsigned char* str = NULL;
1688 int length = i2d_X509_NAME(ca_name, &str);
1689 cert_authorities_.push_back(std::string(
1690 reinterpret_cast<const char*>(str),
1691 static_cast<size_t>(length)));
1692 OPENSSL_free(str);
1693 }
1694
[email protected]c0787702014-05-20 21:51:441695 const unsigned char* client_cert_types;
[email protected]e7e883e2014-07-25 06:03:081696 size_t num_client_cert_types =
1697 SSL_get0_certificate_types(ssl, &client_cert_types);
[email protected]c0787702014-05-20 21:51:441698 for (size_t i = 0; i < num_client_cert_types; i++) {
1699 cert_key_types_.push_back(
1700 static_cast<SSLClientCertType>(client_cert_types[i]));
1701 }
1702
[email protected]5ac981e182010-12-06 17:56:271703 return -1; // Suspends handshake.
1704 }
1705
1706 // Second pass: a client certificate should have been selected.
[email protected]13914c92013-06-13 22:42:421707 if (ssl_config_.client_cert.get()) {
[email protected]6bad5052014-07-12 01:25:131708 ScopedX509 leaf_x509 =
1709 OSCertHandleToOpenSSL(ssl_config_.client_cert->os_cert_handle());
1710 if (!leaf_x509) {
1711 LOG(WARNING) << "Failed to import certificate";
1712 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT);
1713 return -1;
1714 }
1715
[email protected]82c59022014-08-15 09:38:271716 ScopedX509Stack chain = OSCertHandlesToOpenSSL(
1717 ssl_config_.client_cert->GetIntermediateCertificates());
1718 if (!chain) {
1719 LOG(WARNING) << "Failed to import intermediate certificates";
1720 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT);
1721 return -1;
1722 }
1723
[email protected]97a854f2014-07-29 07:51:361724 // TODO(davidben): With Linux client auth support, this should be
1725 // conditioned on OS_ANDROID and then, with https://crbug.com/394131,
1726 // removed altogether. OpenSSLClientKeyStore is mostly an artifact of the
1727 // net/ client auth API lacking a private key handle.
[email protected]c0787702014-05-20 21:51:441728#if defined(USE_OPENSSL_CERTS)
[email protected]97a854f2014-07-29 07:51:361729 crypto::ScopedEVP_PKEY privkey =
1730 OpenSSLClientKeyStore::GetInstance()->FetchClientCertPrivateKey(
1731 ssl_config_.client_cert.get());
1732#else // !defined(USE_OPENSSL_CERTS)
1733 crypto::ScopedEVP_PKEY privkey =
1734 FetchClientCertPrivateKey(ssl_config_.client_cert.get());
1735#endif // defined(USE_OPENSSL_CERTS)
1736 if (!privkey) {
[email protected]6bad5052014-07-12 01:25:131737 // Could not find the private key. Fail the handshake and surface an
1738 // appropriate error to the caller.
1739 LOG(WARNING) << "Client cert found without private key";
1740 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY);
1741 return -1;
[email protected]0c6523f2010-12-10 10:56:241742 }
[email protected]6bad5052014-07-12 01:25:131743
[email protected]82c59022014-08-15 09:38:271744 if (!SSL_use_certificate(ssl_, leaf_x509.get()) ||
1745 !SSL_use_PrivateKey(ssl_, privkey.get()) ||
1746 !SSL_set1_chain(ssl_, chain.get())) {
1747 LOG(WARNING) << "Failed to set client certificate";
1748 return -1;
1749 }
davidbenaf42cbe2014-11-13 03:27:461750
1751 int cert_count = 1 + sk_X509_num(chain.get());
1752 net_log_.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED,
1753 NetLog::IntegerCallback("cert_count", cert_count));
[email protected]6bad5052014-07-12 01:25:131754 return 1;
[email protected]c0787702014-05-20 21:51:441755 }
[email protected]97a854f2014-07-29 07:51:361756#endif // defined(OS_IOS)
[email protected]5ac981e182010-12-06 17:56:271757
1758 // Send no client certificate.
davidbenaf42cbe2014-11-13 03:27:461759 net_log_.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED,
1760 NetLog::IntegerCallback("cert_count", 0));
[email protected]82c59022014-08-15 09:38:271761 return 1;
[email protected]5ac981e182010-12-06 17:56:271762}
1763
[email protected]b051cdb62014-02-28 02:20:161764int SSLClientSocketOpenSSL::CertVerifyCallback(X509_STORE_CTX* store_ctx) {
vadimtb2a77c762014-11-21 19:49:221765 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1766 tracked_objects::ScopedTracker tracking_profile(
1767 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1768 "424386 SSLClientSocketOpenSSL::CertVerifyCallback"));
1769
[email protected]64b5c892014-08-08 09:39:261770 if (!completed_connect_) {
[email protected]b051cdb62014-02-28 02:20:161771 // If the first handshake hasn't completed then we accept any certificates
1772 // because we verify after the handshake.
1773 return 1;
1774 }
1775
davidben30798ed82014-09-19 19:28:201776 // Disallow the server certificate to change in a renegotiation.
1777 if (server_cert_chain_->empty()) {
[email protected]76e85392014-03-20 17:54:141778 LOG(ERROR) << "Received invalid certificate chain between handshakes";
davidben30798ed82014-09-19 19:28:201779 return 0;
1780 }
1781 base::StringPiece old_der, new_der;
1782 if (store_ctx->cert == NULL ||
1783 !x509_util::GetDER(server_cert_chain_->Get(0), &old_der) ||
1784 !x509_util::GetDER(store_ctx->cert, &new_der)) {
1785 LOG(ERROR) << "Failed to encode certificates";
1786 return 0;
1787 }
1788 if (old_der != new_der) {
[email protected]76e85392014-03-20 17:54:141789 LOG(ERROR) << "Server certificate changed between handshakes";
davidben30798ed82014-09-19 19:28:201790 return 0;
1791 }
1792
1793 return 1;
[email protected]b051cdb62014-02-28 02:20:161794}
1795
[email protected]ae7c9f42011-11-21 11:41:161796// SelectNextProtoCallback is called by OpenSSL during the handshake. If the
1797// server supports NPN, selects a protocol from the list that the server
1798// provides. According to third_party/openssl/openssl/ssl/ssl_lib.c, the
1799// callback can assume that |in| is syntactically valid.
[email protected]ea4a1c6a2010-12-09 13:33:281800int SSLClientSocketOpenSSL::SelectNextProtoCallback(unsigned char** out,
1801 unsigned char* outlen,
1802 const unsigned char* in,
1803 unsigned int inlen) {
vadimtb2a77c762014-11-21 19:49:221804 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1805 tracked_objects::ScopedTracker tracking_profile(
1806 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1807 "424386 SSLClientSocketOpenSSL::SelectNextProtoCallback"));
1808
[email protected]ea4a1c6a2010-12-09 13:33:281809 if (ssl_config_.next_protos.empty()) {
[email protected]168a8412012-06-14 05:05:491810 *out = reinterpret_cast<uint8*>(
1811 const_cast<char*>(kDefaultSupportedNPNProtocol));
1812 *outlen = arraysize(kDefaultSupportedNPNProtocol) - 1;
1813 npn_status_ = kNextProtoUnsupported;
[email protected]ea4a1c6a2010-12-09 13:33:281814 return SSL_TLSEXT_ERR_OK;
1815 }
1816
[email protected]ae7c9f42011-11-21 11:41:161817 // Assume there's no overlap between our protocols and the server's list.
[email protected]168a8412012-06-14 05:05:491818 npn_status_ = kNextProtoNoOverlap;
[email protected]ae7c9f42011-11-21 11:41:161819
1820 // For each protocol in server preference order, see if we support it.
1821 for (unsigned int i = 0; i < inlen; i += in[i] + 1) {
bnc0d23cf42014-12-11 14:09:461822 for (NextProto next_proto : ssl_config_.next_protos) {
1823 const std::string proto = NextProtoToString(next_proto);
1824 if (in[i] == proto.size() &&
1825 memcmp(&in[i + 1], proto.data(), in[i]) == 0) {
[email protected]168a8412012-06-14 05:05:491826 // We found a match.
[email protected]ae7c9f42011-11-21 11:41:161827 *out = const_cast<unsigned char*>(in) + i + 1;
1828 *outlen = in[i];
[email protected]168a8412012-06-14 05:05:491829 npn_status_ = kNextProtoNegotiated;
[email protected]ae7c9f42011-11-21 11:41:161830 break;
1831 }
1832 }
[email protected]168a8412012-06-14 05:05:491833 if (npn_status_ == kNextProtoNegotiated)
[email protected]ae7c9f42011-11-21 11:41:161834 break;
1835 }
[email protected]ea4a1c6a2010-12-09 13:33:281836
[email protected]168a8412012-06-14 05:05:491837 // If we didn't find a protocol, we select the first one from our list.
1838 if (npn_status_ == kNextProtoNoOverlap) {
bnc67da3de2015-01-15 21:02:261839 // NextProtoToString returns a pointer to a static string.
1840 const char* proto = NextProtoToString(ssl_config_.next_protos[0]);
1841 *out = reinterpret_cast<unsigned char*>(const_cast<char*>(proto));
1842 *outlen = strlen(proto);
[email protected]168a8412012-06-14 05:05:491843 }
1844
[email protected]ea4a1c6a2010-12-09 13:33:281845 npn_proto_.assign(reinterpret_cast<const char*>(*out), *outlen);
[email protected]32e1dee2010-12-09 18:36:241846 DVLOG(2) << "next protocol: '" << npn_proto_ << "' status: " << npn_status_;
bnc0d28ea52014-10-13 15:15:381847 set_negotiation_extension(kExtensionNPN);
[email protected]ea4a1c6a2010-12-09 13:33:281848 return SSL_TLSEXT_ERR_OK;
1849}
1850
[email protected]5aea79182014-07-14 20:43:411851long SSLClientSocketOpenSSL::MaybeReplayTransportError(
1852 BIO *bio,
1853 int cmd,
1854 const char *argp, int argi, long argl,
1855 long retvalue) {
1856 if (cmd == (BIO_CB_READ|BIO_CB_RETURN) && retvalue <= 0) {
1857 // If there is no more data in the buffer, report any pending errors that
1858 // were observed. Note that both the readbuf and the writebuf are checked
1859 // for errors, since the application may have encountered a socket error
1860 // while writing that would otherwise not be reported until the application
1861 // attempted to write again - which it may never do. See
1862 // https://crbug.com/249848.
1863 if (transport_read_error_ != OK) {
1864 OpenSSLPutNetError(FROM_HERE, transport_read_error_);
1865 return -1;
1866 }
1867 if (transport_write_error_ != OK) {
1868 OpenSSLPutNetError(FROM_HERE, transport_write_error_);
1869 return -1;
1870 }
1871 } else if (cmd == BIO_CB_WRITE) {
1872 // Because of the write buffer, this reports a failure from the previous
1873 // write payload. If the current payload fails to write, the error will be
1874 // reported in a future write or read to |bio|.
1875 if (transport_write_error_ != OK) {
1876 OpenSSLPutNetError(FROM_HERE, transport_write_error_);
1877 return -1;
1878 }
1879 }
1880 return retvalue;
1881}
1882
1883// static
1884long SSLClientSocketOpenSSL::BIOCallback(
1885 BIO *bio,
1886 int cmd,
1887 const char *argp, int argi, long argl,
1888 long retvalue) {
vadimta1d0d9762014-12-18 00:23:341889 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1890 tracked_objects::ScopedTracker tracking_profile(
1891 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1892 "424386 SSLClientSocketOpenSSL::BIOCallback"));
1893
[email protected]5aea79182014-07-14 20:43:411894 SSLClientSocketOpenSSL* socket = reinterpret_cast<SSLClientSocketOpenSSL*>(
1895 BIO_get_callback_arg(bio));
1896 CHECK(socket);
1897 return socket->MaybeReplayTransportError(
1898 bio, cmd, argp, argi, argl, retvalue);
1899}
1900
davidbeneb5f8ef32014-09-04 14:14:321901void SSLClientSocketOpenSSL::AddSCTInfoToSSLInfo(SSLInfo* ssl_info) const {
1902 for (ct::SCTList::const_iterator iter =
1903 ct_verify_result_.verified_scts.begin();
1904 iter != ct_verify_result_.verified_scts.end(); ++iter) {
1905 ssl_info->signed_certificate_timestamps.push_back(
1906 SignedCertificateTimestampAndStatus(*iter, ct::SCT_STATUS_OK));
1907 }
1908 for (ct::SCTList::const_iterator iter =
1909 ct_verify_result_.invalid_scts.begin();
1910 iter != ct_verify_result_.invalid_scts.end(); ++iter) {
1911 ssl_info->signed_certificate_timestamps.push_back(
1912 SignedCertificateTimestampAndStatus(*iter, ct::SCT_STATUS_INVALID));
1913 }
1914 for (ct::SCTList::const_iterator iter =
1915 ct_verify_result_.unknown_logs_scts.begin();
1916 iter != ct_verify_result_.unknown_logs_scts.end(); ++iter) {
1917 ssl_info->signed_certificate_timestamps.push_back(
1918 SignedCertificateTimestampAndStatus(*iter,
1919 ct::SCT_STATUS_LOG_UNKNOWN));
1920 }
1921}
1922
rsleevif020edc2015-03-16 19:31:241923std::string SSLClientSocketOpenSSL::GetSessionCacheKey() const {
1924 std::string result = host_and_port_.ToString();
1925 result.append("/");
1926 result.append(ssl_session_cache_shard_);
1927
1928 // Shard the session cache based on maximum protocol version. This causes
1929 // fallback connections to use a separate session cache.
1930 result.append("/");
1931 switch (ssl_config_.version_max) {
1932 case SSL_PROTOCOL_VERSION_SSL3:
1933 result.append("ssl3");
1934 break;
1935 case SSL_PROTOCOL_VERSION_TLS1:
1936 result.append("tls1");
1937 break;
1938 case SSL_PROTOCOL_VERSION_TLS1_1:
1939 result.append("tls1.1");
1940 break;
1941 case SSL_PROTOCOL_VERSION_TLS1_2:
1942 result.append("tls1.2");
1943 break;
1944 default:
1945 NOTREACHED();
1946 }
1947
1948 return result;
1949}
1950
[email protected]7f38da8a2014-03-17 16:44:261951scoped_refptr<X509Certificate>
1952SSLClientSocketOpenSSL::GetUnverifiedServerCertificateChain() const {
1953 return server_cert_;
1954}
1955
[email protected]7e5dd49f2010-12-08 18:33:491956} // namespace net