blob: d286ff2b94c5a4e0baf08985e11977abad1f30d4 [file] [log] [blame]
[email protected]013c17c2012-01-21 19:09:011// Copyright (c) 2012 The Chromium Authors. All rights reserved.
[email protected]d518cd92010-09-29 12:27:442// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5// OpenSSL binding for SSLClientSocket. The class layout and general principle
6// of operation is derived from SSLClientSocketNSS.
7
8#include "net/socket/ssl_client_socket_openssl.h"
9
[email protected]edfd0f42014-07-22 18:20:3710#include <errno.h>
davidben018aad62014-09-12 02:25:1911#include <openssl/bio.h>
[email protected]d518cd92010-09-29 12:27:4412#include <openssl/err.h>
davidben121e9c962015-05-01 00:40:4913#include <openssl/mem.h>
[email protected]536fd0b2013-03-14 17:41:5714#include <openssl/ssl.h>
bnc67da3de2015-01-15 21:02:2615#include <string.h>
[email protected]d518cd92010-09-29 12:27:4416
[email protected]0f7804ec2011-10-07 20:04:1817#include "base/bind.h"
[email protected]f2da6ac2013-02-04 08:22:5318#include "base/callback_helpers.h"
davidben018aad62014-09-12 02:25:1919#include "base/environment.h"
[email protected]3b63f8f42011-03-28 01:54:1520#include "base/memory/singleton.h"
[email protected]835d7c82010-10-14 04:38:3821#include "base/metrics/histogram.h"
vadimtb2a77c762014-11-21 19:49:2222#include "base/profiler/scoped_tracker.h"
davidben018aad62014-09-12 02:25:1923#include "base/strings/string_piece.h"
[email protected]20305ec2011-01-21 04:55:5224#include "base/synchronization/lock.h"
vadimt6b43dec22015-01-06 01:59:5825#include "base/threading/thread_local.h"
estade5e5529d2015-05-21 20:59:1126#include "base/values.h"
[email protected]ee0f2aa82013-10-25 11:59:2627#include "crypto/ec_private_key.h"
[email protected]4b559b4d2011-04-14 17:37:1428#include "crypto/openssl_util.h"
[email protected]cd9b75b2014-07-10 04:39:3829#include "crypto/scoped_openssl_types.h"
[email protected]d518cd92010-09-29 12:27:4430#include "net/base/net_errors.h"
eranm6571b2b2014-12-03 15:53:2331#include "net/cert/cert_policy_enforcer.h"
[email protected]6e7845ae2013-03-29 21:48:1132#include "net/cert/cert_verifier.h"
eranmefbd3132014-10-28 16:35:1633#include "net/cert/ct_ev_whitelist.h"
davidbeneb5f8ef32014-09-04 14:14:3234#include "net/cert/ct_verifier.h"
[email protected]6e7845ae2013-03-29 21:48:1135#include "net/cert/x509_certificate_net_log_param.h"
davidben30798ed82014-09-19 19:28:2036#include "net/cert/x509_util_openssl.h"
[email protected]8bd4e7a2014-08-09 14:49:1737#include "net/http/transport_security_state.h"
davidbenc879af02015-02-20 07:57:2138#include "net/ssl/scoped_openssl_types.h"
[email protected]536fd0b2013-03-14 17:41:5739#include "net/ssl/ssl_cert_request_info.h"
davidbendafe4e52015-04-08 22:53:5240#include "net/ssl/ssl_client_session_cache_openssl.h"
[email protected]536fd0b2013-03-14 17:41:5741#include "net/ssl/ssl_connection_status_flags.h"
davidbenf2eaaf92015-05-15 22:18:4242#include "net/ssl/ssl_failure_state.h"
[email protected]536fd0b2013-03-14 17:41:5743#include "net/ssl/ssl_info.h"
[email protected]d518cd92010-09-29 12:27:4444
davidben8ecc3072014-09-03 23:19:0945#if defined(OS_WIN)
46#include "base/win/windows_version.h"
47#endif
48
[email protected]97a854f2014-07-29 07:51:3649#if defined(USE_OPENSSL_CERTS)
50#include "net/ssl/openssl_client_key_store.h"
51#else
52#include "net/ssl/openssl_platform_key.h"
53#endif
54
[email protected]d518cd92010-09-29 12:27:4455namespace net {
56
57namespace {
58
59// Enable this to see logging for state machine state transitions.
60#if 0
[email protected]3b112772010-10-04 10:54:4961#define GotoState(s) do { DVLOG(2) << (void *)this << " " << __FUNCTION__ << \
[email protected]d518cd92010-09-29 12:27:4462 " jump to state " << s; \
63 next_handshake_state_ = s; } while (0)
64#else
65#define GotoState(s) next_handshake_state_ = s
66#endif
67
[email protected]4b768562013-02-16 04:10:0768// This constant can be any non-negative/non-zero value (eg: it does not
69// overlap with any value of the net::Error range, including net::OK).
70const int kNoPendingReadResult = 1;
71
[email protected]168a8412012-06-14 05:05:4972// If a client doesn't have a list of protocols that it supports, but
73// the server supports NPN, choosing "http/1.1" is the best answer.
74const char kDefaultSupportedNPNProtocol[] = "http/1.1";
75
haavardm2d92e722014-12-19 13:45:4476// Default size of the internal BoringSSL buffers.
77const int KDefaultOpenSSLBufferSize = 17 * 1024;
78
[email protected]82c59022014-08-15 09:38:2779void FreeX509Stack(STACK_OF(X509)* ptr) {
80 sk_X509_pop_free(ptr, X509_free);
81}
82
davidbene94fe0962015-02-21 00:51:3383using ScopedX509Stack = crypto::ScopedOpenSSL<STACK_OF(X509), FreeX509Stack>;
[email protected]6bad5052014-07-12 01:25:1384
[email protected]89038152012-09-07 06:30:1785#if OPENSSL_VERSION_NUMBER < 0x1000103fL
86// This method doesn't seem to have made it into the OpenSSL headers.
[email protected]109805a2010-12-07 18:17:0687unsigned long SSL_CIPHER_get_id(const SSL_CIPHER* cipher) { return cipher->id; }
[email protected]89038152012-09-07 06:30:1788#endif
[email protected]109805a2010-12-07 18:17:0689
90// Used for encoding the |connection_status| field of an SSLInfo object.
pkasting6b68a162014-12-01 22:10:2991int EncodeSSLConnectionStatus(uint16 cipher_suite,
[email protected]109805a2010-12-07 18:17:0692 int compression,
93 int version) {
pkasting6b68a162014-12-01 22:10:2994 return cipher_suite |
[email protected]109805a2010-12-07 18:17:0695 ((compression & SSL_CONNECTION_COMPRESSION_MASK) <<
96 SSL_CONNECTION_COMPRESSION_SHIFT) |
97 ((version & SSL_CONNECTION_VERSION_MASK) <<
98 SSL_CONNECTION_VERSION_SHIFT);
99}
100
101// Returns the net SSL version number (see ssl_connection_status_flags.h) for
102// this SSL connection.
103int GetNetSSLVersion(SSL* ssl) {
[email protected]7e5dd49f2010-12-08 18:33:49104 switch (SSL_version(ssl)) {
[email protected]109805a2010-12-07 18:17:06105 case TLS1_VERSION:
106 return SSL_CONNECTION_VERSION_TLS1;
davidben1d094022014-11-05 18:55:47107 case TLS1_1_VERSION:
[email protected]109805a2010-12-07 18:17:06108 return SSL_CONNECTION_VERSION_TLS1_1;
davidben1d094022014-11-05 18:55:47109 case TLS1_2_VERSION:
[email protected]109805a2010-12-07 18:17:06110 return SSL_CONNECTION_VERSION_TLS1_2;
111 default:
davidbenb937d6c2015-05-14 04:53:42112 NOTREACHED();
[email protected]109805a2010-12-07 18:17:06113 return SSL_CONNECTION_VERSION_UNKNOWN;
114 }
115}
116
[email protected]6bad5052014-07-12 01:25:13117ScopedX509 OSCertHandleToOpenSSL(
118 X509Certificate::OSCertHandle os_handle) {
119#if defined(USE_OPENSSL_CERTS)
120 return ScopedX509(X509Certificate::DupOSCertHandle(os_handle));
121#else // !defined(USE_OPENSSL_CERTS)
122 std::string der_encoded;
123 if (!X509Certificate::GetDEREncoded(os_handle, &der_encoded))
124 return ScopedX509();
125 const uint8_t* bytes = reinterpret_cast<const uint8_t*>(der_encoded.data());
126 return ScopedX509(d2i_X509(NULL, &bytes, der_encoded.size()));
127#endif // defined(USE_OPENSSL_CERTS)
128}
129
[email protected]82c59022014-08-15 09:38:27130ScopedX509Stack OSCertHandlesToOpenSSL(
131 const X509Certificate::OSCertHandles& os_handles) {
132 ScopedX509Stack stack(sk_X509_new_null());
133 for (size_t i = 0; i < os_handles.size(); i++) {
134 ScopedX509 x509 = OSCertHandleToOpenSSL(os_handles[i]);
135 if (!x509)
136 return ScopedX509Stack();
137 sk_X509_push(stack.get(), x509.release());
138 }
139 return stack.Pass();
140}
141
davidben018aad62014-09-12 02:25:19142int LogErrorCallback(const char* str, size_t len, void* context) {
143 LOG(ERROR) << base::StringPiece(str, len);
144 return 1;
145}
146
[email protected]821e3bb2013-11-08 01:06:01147} // namespace
148
149class SSLClientSocketOpenSSL::SSLContext {
[email protected]fbef13932010-11-23 12:38:53150 public:
[email protected]b29af7d2010-12-14 11:52:47151 static SSLContext* GetInstance() { return Singleton<SSLContext>::get(); }
[email protected]fbef13932010-11-23 12:38:53152 SSL_CTX* ssl_ctx() { return ssl_ctx_.get(); }
davidbendafe4e52015-04-08 22:53:52153 SSLClientSessionCacheOpenSSL* session_cache() { return &session_cache_; }
[email protected]fbef13932010-11-23 12:38:53154
[email protected]1279de12013-12-03 15:13:32155 SSLClientSocketOpenSSL* GetClientSocketFromSSL(const SSL* ssl) {
[email protected]fbef13932010-11-23 12:38:53156 DCHECK(ssl);
157 SSLClientSocketOpenSSL* socket = static_cast<SSLClientSocketOpenSSL*>(
158 SSL_get_ex_data(ssl, ssl_socket_data_index_));
159 DCHECK(socket);
160 return socket;
161 }
162
163 bool SetClientSocketForSSL(SSL* ssl, SSLClientSocketOpenSSL* socket) {
164 return SSL_set_ex_data(ssl, ssl_socket_data_index_, socket) != 0;
165 }
166
167 private:
168 friend struct DefaultSingletonTraits<SSLContext>;
169
davidbendafe4e52015-04-08 22:53:52170 SSLContext() : session_cache_(SSLClientSessionCacheOpenSSL::Config()) {
[email protected]4b559b4d2011-04-14 17:37:14171 crypto::EnsureOpenSSLInit();
[email protected]fbef13932010-11-23 12:38:53172 ssl_socket_data_index_ = SSL_get_ex_new_index(0, 0, 0, 0, 0);
173 DCHECK_NE(ssl_socket_data_index_, -1);
174 ssl_ctx_.reset(SSL_CTX_new(SSLv23_client_method()));
[email protected]b051cdb62014-02-28 02:20:16175 SSL_CTX_set_cert_verify_callback(ssl_ctx_.get(), CertVerifyCallback, NULL);
[email protected]82c59022014-08-15 09:38:27176 SSL_CTX_set_cert_cb(ssl_ctx_.get(), ClientCertRequestCallback, NULL);
[email protected]b051cdb62014-02-28 02:20:16177 SSL_CTX_set_verify(ssl_ctx_.get(), SSL_VERIFY_PEER, NULL);
haavardmc80b0ee32015-01-30 09:16:08178 // This stops |SSL_shutdown| from generating the close_notify message, which
179 // is currently not sent on the network.
180 // TODO(haavardm): Remove setting quiet shutdown once 118366 is fixed.
181 SSL_CTX_set_quiet_shutdown(ssl_ctx_.get(), 1);
[email protected]ea4a1c6a2010-12-09 13:33:28182 // TODO(kristianm): Only select this if ssl_config_.next_proto is not empty.
183 // It would be better if the callback were not a global setting,
184 // but that is an OpenSSL issue.
185 SSL_CTX_set_next_proto_select_cb(ssl_ctx_.get(), SelectNextProtoCallback,
186 NULL);
[email protected]edfd0f42014-07-22 18:20:37187 ssl_ctx_->tlsext_channel_id_enabled_new = 1;
davidbendafe4e52015-04-08 22:53:52188 SSL_CTX_set_info_callback(ssl_ctx_.get(), InfoCallback);
189
190 // Disable the internal session cache. Session caching is handled
191 // externally (i.e. by SSLClientSessionCacheOpenSSL).
192 SSL_CTX_set_session_cache_mode(
193 ssl_ctx_.get(), SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_NO_INTERNAL);
davidben018aad62014-09-12 02:25:19194
195 scoped_ptr<base::Environment> env(base::Environment::Create());
196 std::string ssl_keylog_file;
197 if (env->GetVar("SSLKEYLOGFILE", &ssl_keylog_file) &&
198 !ssl_keylog_file.empty()) {
199 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
200 BIO* bio = BIO_new_file(ssl_keylog_file.c_str(), "a");
201 if (!bio) {
202 LOG(ERROR) << "Failed to open " << ssl_keylog_file;
203 ERR_print_errors_cb(&LogErrorCallback, NULL);
204 } else {
205 SSL_CTX_set_keylog_bio(ssl_ctx_.get(), bio);
206 }
207 }
[email protected]fbef13932010-11-23 12:38:53208 }
209
[email protected]82c59022014-08-15 09:38:27210 static int ClientCertRequestCallback(SSL* ssl, void* arg) {
[email protected]b29af7d2010-12-14 11:52:47211 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
[email protected]82c59022014-08-15 09:38:27212 DCHECK(socket);
213 return socket->ClientCertRequestCallback(ssl);
[email protected]718c9672010-12-02 10:04:10214 }
215
[email protected]b051cdb62014-02-28 02:20:16216 static int CertVerifyCallback(X509_STORE_CTX *store_ctx, void *arg) {
217 SSL* ssl = reinterpret_cast<SSL*>(X509_STORE_CTX_get_ex_data(
218 store_ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
219 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
220 CHECK(socket);
221
222 return socket->CertVerifyCallback(store_ctx);
223 }
224
[email protected]ea4a1c6a2010-12-09 13:33:28225 static int SelectNextProtoCallback(SSL* ssl,
226 unsigned char** out, unsigned char* outlen,
227 const unsigned char* in,
228 unsigned int inlen, void* arg) {
[email protected]b29af7d2010-12-14 11:52:47229 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
[email protected]ea4a1c6a2010-12-09 13:33:28230 return socket->SelectNextProtoCallback(out, outlen, in, inlen);
231 }
232
davidbendafe4e52015-04-08 22:53:52233 static void InfoCallback(const SSL* ssl, int type, int val) {
234 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
235 socket->InfoCallback(type, val);
236 }
237
[email protected]fbef13932010-11-23 12:38:53238 // This is the index used with SSL_get_ex_data to retrieve the owner
239 // SSLClientSocketOpenSSL object from an SSL instance.
240 int ssl_socket_data_index_;
241
davidbenc879af02015-02-20 07:57:21242 ScopedSSL_CTX ssl_ctx_;
davidbendafe4e52015-04-08 22:53:52243
244 // TODO(davidben): Use a separate cache per URLRequestContext.
245 // https://crbug.com/458365
246 //
247 // TODO(davidben): Sessions should be invalidated on fatal
248 // alerts. https://crbug.com/466352
249 SSLClientSessionCacheOpenSSL session_cache_;
[email protected]1279de12013-12-03 15:13:32250};
251
[email protected]7f38da8a2014-03-17 16:44:26252// PeerCertificateChain is a helper object which extracts the certificate
253// chain, as given by the server, from an OpenSSL socket and performs the needed
254// resource management. The first element of the chain is the leaf certificate
255// and the other elements are in the order given by the server.
256class SSLClientSocketOpenSSL::PeerCertificateChain {
257 public:
[email protected]76e85392014-03-20 17:54:14258 explicit PeerCertificateChain(STACK_OF(X509)* chain) { Reset(chain); }
[email protected]7f38da8a2014-03-17 16:44:26259 PeerCertificateChain(const PeerCertificateChain& other) { *this = other; }
260 ~PeerCertificateChain() {}
261 PeerCertificateChain& operator=(const PeerCertificateChain& other);
262
[email protected]76e85392014-03-20 17:54:14263 // Resets the PeerCertificateChain to the set of certificates in|chain|,
264 // which may be NULL, indicating to empty the store certificates.
265 // Note: If an error occurs, such as being unable to parse the certificates,
266 // this will behave as if Reset(NULL) was called.
267 void Reset(STACK_OF(X509)* chain);
268
[email protected]7f38da8a2014-03-17 16:44:26269 // Note that when USE_OPENSSL is defined, OSCertHandle is X509*
davidben30798ed82014-09-19 19:28:20270 scoped_refptr<X509Certificate> AsOSChain() const;
[email protected]7f38da8a2014-03-17 16:44:26271
272 size_t size() const {
273 if (!openssl_chain_.get())
274 return 0;
275 return sk_X509_num(openssl_chain_.get());
276 }
277
davidben30798ed82014-09-19 19:28:20278 bool empty() const {
279 return size() == 0;
280 }
281
282 X509* Get(size_t index) const {
[email protected]7f38da8a2014-03-17 16:44:26283 DCHECK_LT(index, size());
284 return sk_X509_value(openssl_chain_.get(), index);
285 }
286
287 private:
[email protected]cd9b75b2014-07-10 04:39:38288 ScopedX509Stack openssl_chain_;
[email protected]7f38da8a2014-03-17 16:44:26289};
290
291SSLClientSocketOpenSSL::PeerCertificateChain&
292SSLClientSocketOpenSSL::PeerCertificateChain::operator=(
293 const PeerCertificateChain& other) {
294 if (this == &other)
295 return *this;
296
[email protected]24176af2014-08-14 09:31:04297 openssl_chain_.reset(X509_chain_up_ref(other.openssl_chain_.get()));
[email protected]7f38da8a2014-03-17 16:44:26298 return *this;
299}
300
[email protected]76e85392014-03-20 17:54:14301void SSLClientSocketOpenSSL::PeerCertificateChain::Reset(
302 STACK_OF(X509)* chain) {
davidben30798ed82014-09-19 19:28:20303 openssl_chain_.reset(chain ? X509_chain_up_ref(chain) : NULL);
[email protected]7f38da8a2014-03-17 16:44:26304}
[email protected]7f38da8a2014-03-17 16:44:26305
davidben30798ed82014-09-19 19:28:20306scoped_refptr<X509Certificate>
307SSLClientSocketOpenSSL::PeerCertificateChain::AsOSChain() const {
308#if defined(USE_OPENSSL_CERTS)
309 // When OSCertHandle is typedef'ed to X509, this implementation does a short
310 // cut to avoid converting back and forth between DER and the X509 struct.
311 X509Certificate::OSCertHandles intermediates;
312 for (size_t i = 1; i < sk_X509_num(openssl_chain_.get()); ++i) {
313 intermediates.push_back(sk_X509_value(openssl_chain_.get(), i));
314 }
[email protected]7f38da8a2014-03-17 16:44:26315
davidben30798ed82014-09-19 19:28:20316 return make_scoped_refptr(X509Certificate::CreateFromHandle(
317 sk_X509_value(openssl_chain_.get(), 0), intermediates));
318#else
319 // DER-encode the chain and convert to a platform certificate handle.
[email protected]7f38da8a2014-03-17 16:44:26320 std::vector<base::StringPiece> der_chain;
[email protected]edfd0f42014-07-22 18:20:37321 for (size_t i = 0; i < sk_X509_num(openssl_chain_.get()); ++i) {
[email protected]7f38da8a2014-03-17 16:44:26322 X509* x = sk_X509_value(openssl_chain_.get(), i);
davidben30798ed82014-09-19 19:28:20323 base::StringPiece der;
324 if (!x509_util::GetDER(x, &der))
325 return NULL;
326 der_chain.push_back(der);
[email protected]7f38da8a2014-03-17 16:44:26327 }
328
davidben30798ed82014-09-19 19:28:20329 return make_scoped_refptr(X509Certificate::CreateFromDERCertChain(der_chain));
330#endif
[email protected]7f38da8a2014-03-17 16:44:26331}
[email protected]7f38da8a2014-03-17 16:44:26332
[email protected]1279de12013-12-03 15:13:32333// static
[email protected]c3456bb2011-12-12 22:22:19334void SSLClientSocket::ClearSessionCache() {
[email protected]821e3bb2013-11-08 01:06:01335 SSLClientSocketOpenSSL::SSLContext* context =
336 SSLClientSocketOpenSSL::SSLContext::GetInstance();
[email protected]c3456bb2011-12-12 22:22:19337 context->session_cache()->Flush();
338}
339
bnc86b734dd2014-12-03 00:33:10340// static
341uint16 SSLClientSocket::GetMaxSupportedSSLVersion() {
342 return SSL_PROTOCOL_VERSION_TLS1_2;
343}
344
[email protected]d518cd92010-09-29 12:27:44345SSLClientSocketOpenSSL::SSLClientSocketOpenSSL(
[email protected]18ccfdb2013-08-15 00:13:44346 scoped_ptr<ClientSocketHandle> transport_socket,
[email protected]055d7f22010-11-15 12:03:12347 const HostPortPair& host_and_port,
[email protected]822581d2010-12-16 17:27:15348 const SSLConfig& ssl_config,
[email protected]feb79bcd2011-07-21 16:55:17349 const SSLClientSocketContext& context)
[email protected]83039bb2011-12-09 18:43:55350 : transport_send_busy_(false),
[email protected]d518cd92010-09-29 12:27:44351 transport_recv_busy_(false),
[email protected]4b768562013-02-16 04:10:07352 pending_read_error_(kNoPendingReadResult),
davidbenb8c23212014-10-28 00:12:16353 pending_read_ssl_error_(SSL_ERROR_NONE),
[email protected]5aea79182014-07-14 20:43:41354 transport_read_error_(OK),
[email protected]3e5c6922014-02-06 02:42:16355 transport_write_error_(OK),
[email protected]7f38da8a2014-03-17 16:44:26356 server_cert_chain_(new PeerCertificateChain(NULL)),
[email protected]64b5c892014-08-08 09:39:26357 completed_connect_(false),
[email protected]0dc88b32014-03-26 20:12:28358 was_ever_used_(false),
[email protected]feb79bcd2011-07-21 16:55:17359 cert_verifier_(context.cert_verifier),
davidbeneb5f8ef32014-09-04 14:14:32360 cert_transparency_verifier_(context.cert_transparency_verifier),
[email protected]6b8a3c742014-07-25 00:25:35361 channel_id_service_(context.channel_id_service),
[email protected]d518cd92010-09-29 12:27:44362 ssl_(NULL),
363 transport_bio_(NULL),
[email protected]18ccfdb2013-08-15 00:13:44364 transport_(transport_socket.Pass()),
[email protected]055d7f22010-11-15 12:03:12365 host_and_port_(host_and_port),
[email protected]d518cd92010-09-29 12:27:44366 ssl_config_(ssl_config),
[email protected]c3456bb2011-12-12 22:22:19367 ssl_session_cache_shard_(context.ssl_session_cache_shard),
[email protected]013c17c2012-01-21 19:09:01368 next_handshake_state_(STATE_NONE),
[email protected]ea4a1c6a2010-12-09 13:33:28369 npn_status_(kNextProtoUnsupported),
davidben52053b382015-04-27 19:22:29370 channel_id_sent_(false),
davidbendafe4e52015-04-08 22:53:52371 handshake_completed_(false),
372 certificate_verified_(false),
davidbenf2eaaf92015-05-15 22:18:42373 ssl_failure_state_(SSL_FAILURE_NONE),
[email protected]8bd4e7a2014-08-09 14:49:17374 transport_security_state_(context.transport_security_state),
eranm6571b2b2014-12-03 15:53:23375 policy_enforcer_(context.cert_policy_enforcer),
kulkarni.acd7b4462014-08-28 07:41:34376 net_log_(transport_->socket()->NetLog()),
377 weak_factory_(this) {
davidben9bbf3292015-04-24 21:50:06378 DCHECK(cert_verifier_);
[email protected]8e458552014-08-05 00:02:15379}
[email protected]d518cd92010-09-29 12:27:44380
381SSLClientSocketOpenSSL::~SSLClientSocketOpenSSL() {
382 Disconnect();
383}
384
[email protected]b9b651f2013-11-09 04:32:22385void SSLClientSocketOpenSSL::GetSSLCertRequestInfo(
386 SSLCertRequestInfo* cert_request_info) {
[email protected]791879c2013-12-17 07:22:41387 cert_request_info->host_and_port = host_and_port_;
[email protected]b9b651f2013-11-09 04:32:22388 cert_request_info->cert_authorities = cert_authorities_;
[email protected]c0787702014-05-20 21:51:44389 cert_request_info->cert_key_types = cert_key_types_;
[email protected]b9b651f2013-11-09 04:32:22390}
391
392SSLClientSocket::NextProtoStatus SSLClientSocketOpenSSL::GetNextProto(
davidben6974bf72015-04-27 17:52:48393 std::string* proto) const {
[email protected]b9b651f2013-11-09 04:32:22394 *proto = npn_proto_;
[email protected]b9b651f2013-11-09 04:32:22395 return npn_status_;
396}
397
[email protected]6b8a3c742014-07-25 00:25:35398ChannelIDService*
399SSLClientSocketOpenSSL::GetChannelIDService() const {
400 return channel_id_service_;
[email protected]b9b651f2013-11-09 04:32:22401}
402
davidbenf2eaaf92015-05-15 22:18:42403SSLFailureState SSLClientSocketOpenSSL::GetSSLFailureState() const {
404 return ssl_failure_state_;
405}
406
[email protected]b9b651f2013-11-09 04:32:22407int SSLClientSocketOpenSSL::ExportKeyingMaterial(
408 const base::StringPiece& label,
409 bool has_context, const base::StringPiece& context,
410 unsigned char* out, unsigned int outlen) {
davidben86935f72015-05-06 22:24:49411 if (!IsConnected())
412 return ERR_SOCKET_NOT_CONNECTED;
413
[email protected]b9b651f2013-11-09 04:32:22414 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
415
416 int rv = SSL_export_keying_material(
[email protected]c8a80e92014-05-17 16:02:08417 ssl_, out, outlen, label.data(), label.size(),
davidben866c3d4a72015-04-06 21:56:43418 reinterpret_cast<const unsigned char*>(context.data()), context.length(),
419 has_context ? 1 : 0);
[email protected]b9b651f2013-11-09 04:32:22420
421 if (rv != 1) {
422 int ssl_error = SSL_get_error(ssl_, rv);
423 LOG(ERROR) << "Failed to export keying material;"
424 << " returned " << rv
425 << ", SSL error code " << ssl_error;
426 return MapOpenSSLError(ssl_error, err_tracer);
427 }
428 return OK;
429}
430
431int SSLClientSocketOpenSSL::GetTLSUniqueChannelBinding(std::string* out) {
[email protected]c8a80e92014-05-17 16:02:08432 NOTIMPLEMENTED();
[email protected]b9b651f2013-11-09 04:32:22433 return ERR_NOT_IMPLEMENTED;
434}
435
436int SSLClientSocketOpenSSL::Connect(const CompletionCallback& callback) {
[email protected]8bd4e7a2014-08-09 14:49:17437 // It is an error to create an SSLClientSocket whose context has no
438 // TransportSecurityState.
439 DCHECK(transport_security_state_);
440
[email protected]b9b651f2013-11-09 04:32:22441 net_log_.BeginEvent(NetLog::TYPE_SSL_CONNECT);
442
443 // Set up new ssl object.
[email protected]c8a80e92014-05-17 16:02:08444 int rv = Init();
445 if (rv != OK) {
446 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
447 return rv;
[email protected]b9b651f2013-11-09 04:32:22448 }
449
450 // Set SSL to client mode. Handshake happens in the loop below.
451 SSL_set_connect_state(ssl_);
452
453 GotoState(STATE_HANDSHAKE);
[email protected]c8a80e92014-05-17 16:02:08454 rv = DoHandshakeLoop(OK);
[email protected]b9b651f2013-11-09 04:32:22455 if (rv == ERR_IO_PENDING) {
456 user_connect_callback_ = callback;
457 } else {
458 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
459 }
460
461 return rv > OK ? OK : rv;
462}
463
464void SSLClientSocketOpenSSL::Disconnect() {
465 if (ssl_) {
466 // Calling SSL_shutdown prevents the session from being marked as
467 // unresumable.
468 SSL_shutdown(ssl_);
469 SSL_free(ssl_);
470 ssl_ = NULL;
471 }
472 if (transport_bio_) {
473 BIO_free_all(transport_bio_);
474 transport_bio_ = NULL;
475 }
476
477 // Shut down anything that may call us back.
eroman7f9236a2015-05-11 21:23:43478 cert_verifier_request_.reset();
[email protected]b9b651f2013-11-09 04:32:22479 transport_->socket()->Disconnect();
480
481 // Null all callbacks, delete all buffers.
482 transport_send_busy_ = false;
483 send_buffer_ = NULL;
484 transport_recv_busy_ = false;
[email protected]b9b651f2013-11-09 04:32:22485 recv_buffer_ = NULL;
486
487 user_connect_callback_.Reset();
488 user_read_callback_.Reset();
489 user_write_callback_.Reset();
490 user_read_buf_ = NULL;
491 user_read_buf_len_ = 0;
492 user_write_buf_ = NULL;
493 user_write_buf_len_ = 0;
494
[email protected]3e5c6922014-02-06 02:42:16495 pending_read_error_ = kNoPendingReadResult;
davidbenb8c23212014-10-28 00:12:16496 pending_read_ssl_error_ = SSL_ERROR_NONE;
497 pending_read_error_info_ = OpenSSLErrorInfo();
498
[email protected]5aea79182014-07-14 20:43:41499 transport_read_error_ = OK;
[email protected]3e5c6922014-02-06 02:42:16500 transport_write_error_ = OK;
501
[email protected]b9b651f2013-11-09 04:32:22502 server_cert_verify_result_.Reset();
[email protected]64b5c892014-08-08 09:39:26503 completed_connect_ = false;
[email protected]b9b651f2013-11-09 04:32:22504
505 cert_authorities_.clear();
[email protected]c0787702014-05-20 21:51:44506 cert_key_types_.clear();
[email protected]faff9852014-06-21 06:13:46507
davidben09c3d072014-08-25 20:33:58508 start_cert_verification_time_ = base::TimeTicks();
509
[email protected]abc44b752014-07-30 03:52:15510 npn_status_ = kNextProtoUnsupported;
511 npn_proto_.clear();
512
davidben52053b382015-04-27 19:22:29513 channel_id_sent_ = false;
davidbenf2eaaf92015-05-15 22:18:42514 handshake_completed_ = false;
515 certificate_verified_ = false;
[email protected]faff9852014-06-21 06:13:46516 channel_id_request_handle_.Cancel();
davidbenf2eaaf92015-05-15 22:18:42517 ssl_failure_state_ = SSL_FAILURE_NONE;
[email protected]b9b651f2013-11-09 04:32:22518}
519
520bool SSLClientSocketOpenSSL::IsConnected() const {
521 // If the handshake has not yet completed.
[email protected]64b5c892014-08-08 09:39:26522 if (!completed_connect_)
[email protected]b9b651f2013-11-09 04:32:22523 return false;
524 // If an asynchronous operation is still pending.
525 if (user_read_buf_.get() || user_write_buf_.get())
526 return true;
527
528 return transport_->socket()->IsConnected();
529}
530
531bool SSLClientSocketOpenSSL::IsConnectedAndIdle() const {
532 // If the handshake has not yet completed.
[email protected]64b5c892014-08-08 09:39:26533 if (!completed_connect_)
[email protected]b9b651f2013-11-09 04:32:22534 return false;
535 // If an asynchronous operation is still pending.
536 if (user_read_buf_.get() || user_write_buf_.get())
537 return false;
davidbenfc9a6b82015-04-15 23:47:32538
539 // If there is data read from the network that has not yet been consumed, do
540 // not treat the connection as idle.
541 //
542 // Note that this does not check |BIO_pending|, whether there is ciphertext
543 // that has not yet been flushed to the network. |Write| returns early, so
544 // this can cause race conditions which cause a socket to not be treated
545 // reusable when it should be. See https://crbug.com/466147.
546 if (BIO_wpending(transport_bio_) > 0)
[email protected]b9b651f2013-11-09 04:32:22547 return false;
[email protected]b9b651f2013-11-09 04:32:22548
549 return transport_->socket()->IsConnectedAndIdle();
550}
551
552int SSLClientSocketOpenSSL::GetPeerAddress(IPEndPoint* addressList) const {
553 return transport_->socket()->GetPeerAddress(addressList);
554}
555
556int SSLClientSocketOpenSSL::GetLocalAddress(IPEndPoint* addressList) const {
557 return transport_->socket()->GetLocalAddress(addressList);
558}
559
560const BoundNetLog& SSLClientSocketOpenSSL::NetLog() const {
561 return net_log_;
562}
563
564void SSLClientSocketOpenSSL::SetSubresourceSpeculation() {
565 if (transport_.get() && transport_->socket()) {
566 transport_->socket()->SetSubresourceSpeculation();
567 } else {
568 NOTREACHED();
569 }
570}
571
572void SSLClientSocketOpenSSL::SetOmniboxSpeculation() {
573 if (transport_.get() && transport_->socket()) {
574 transport_->socket()->SetOmniboxSpeculation();
575 } else {
576 NOTREACHED();
577 }
578}
579
580bool SSLClientSocketOpenSSL::WasEverUsed() const {
[email protected]0dc88b32014-03-26 20:12:28581 return was_ever_used_;
[email protected]b9b651f2013-11-09 04:32:22582}
583
584bool SSLClientSocketOpenSSL::UsingTCPFastOpen() const {
585 if (transport_.get() && transport_->socket())
586 return transport_->socket()->UsingTCPFastOpen();
587
588 NOTREACHED();
589 return false;
590}
591
592bool SSLClientSocketOpenSSL::GetSSLInfo(SSLInfo* ssl_info) {
593 ssl_info->Reset();
davidben30798ed82014-09-19 19:28:20594 if (server_cert_chain_->empty())
[email protected]b9b651f2013-11-09 04:32:22595 return false;
596
597 ssl_info->cert = server_cert_verify_result_.verified_cert;
598 ssl_info->cert_status = server_cert_verify_result_.cert_status;
599 ssl_info->is_issued_by_known_root =
600 server_cert_verify_result_.is_issued_by_known_root;
601 ssl_info->public_key_hashes =
602 server_cert_verify_result_.public_key_hashes;
603 ssl_info->client_cert_sent =
604 ssl_config_.send_client_cert && ssl_config_.client_cert.get();
davidben52053b382015-04-27 19:22:29605 ssl_info->channel_id_sent = channel_id_sent_;
[email protected]8bd4e7a2014-08-09 14:49:17606 ssl_info->pinning_failure_log = pinning_failure_log_;
[email protected]b9b651f2013-11-09 04:32:22607
davidbeneb5f8ef32014-09-04 14:14:32608 AddSCTInfoToSSLInfo(ssl_info);
609
[email protected]b9b651f2013-11-09 04:32:22610 const SSL_CIPHER* cipher = SSL_get_current_cipher(ssl_);
611 CHECK(cipher);
612 ssl_info->security_bits = SSL_CIPHER_get_bits(cipher, NULL);
[email protected]b9b651f2013-11-09 04:32:22613
614 ssl_info->connection_status = EncodeSSLConnectionStatus(
pkasting6b68a162014-12-01 22:10:29615 static_cast<uint16>(SSL_CIPHER_get_id(cipher)), 0 /* no compression */,
[email protected]b9b651f2013-11-09 04:32:22616 GetNetSSLVersion(ssl_));
617
davidben09c3d072014-08-25 20:33:58618 if (!SSL_get_secure_renegotiation_support(ssl_))
[email protected]b9b651f2013-11-09 04:32:22619 ssl_info->connection_status |= SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION;
[email protected]b9b651f2013-11-09 04:32:22620
621 if (ssl_config_.version_fallback)
622 ssl_info->connection_status |= SSL_CONNECTION_VERSION_FALLBACK;
623
624 ssl_info->handshake_type = SSL_session_reused(ssl_) ?
625 SSLInfo::HANDSHAKE_RESUME : SSLInfo::HANDSHAKE_FULL;
626
627 DVLOG(3) << "Encoded connection status: cipher suite = "
628 << SSLConnectionStatusToCipherSuite(ssl_info->connection_status)
629 << " version = "
630 << SSLConnectionStatusToVersion(ssl_info->connection_status);
631 return true;
632}
633
ttuttle23fdb7b2015-05-15 01:28:03634void SSLClientSocketOpenSSL::GetConnectionAttempts(
635 ConnectionAttempts* out) const {
636 out->clear();
637}
638
[email protected]b9b651f2013-11-09 04:32:22639int SSLClientSocketOpenSSL::Read(IOBuffer* buf,
640 int buf_len,
641 const CompletionCallback& callback) {
642 user_read_buf_ = buf;
643 user_read_buf_len_ = buf_len;
644
davidben1b133ad2014-10-23 04:23:13645 int rv = DoReadLoop();
[email protected]b9b651f2013-11-09 04:32:22646
647 if (rv == ERR_IO_PENDING) {
648 user_read_callback_ = callback;
649 } else {
[email protected]0dc88b32014-03-26 20:12:28650 if (rv > 0)
651 was_ever_used_ = true;
[email protected]b9b651f2013-11-09 04:32:22652 user_read_buf_ = NULL;
653 user_read_buf_len_ = 0;
654 }
655
656 return rv;
657}
658
659int SSLClientSocketOpenSSL::Write(IOBuffer* buf,
660 int buf_len,
661 const CompletionCallback& callback) {
662 user_write_buf_ = buf;
663 user_write_buf_len_ = buf_len;
664
davidben1b133ad2014-10-23 04:23:13665 int rv = DoWriteLoop();
[email protected]b9b651f2013-11-09 04:32:22666
667 if (rv == ERR_IO_PENDING) {
668 user_write_callback_ = callback;
669 } else {
[email protected]0dc88b32014-03-26 20:12:28670 if (rv > 0)
671 was_ever_used_ = true;
[email protected]b9b651f2013-11-09 04:32:22672 user_write_buf_ = NULL;
673 user_write_buf_len_ = 0;
674 }
675
676 return rv;
677}
678
[email protected]28b96d1c2014-04-09 12:21:15679int SSLClientSocketOpenSSL::SetReceiveBufferSize(int32 size) {
[email protected]b9b651f2013-11-09 04:32:22680 return transport_->socket()->SetReceiveBufferSize(size);
681}
682
[email protected]28b96d1c2014-04-09 12:21:15683int SSLClientSocketOpenSSL::SetSendBufferSize(int32 size) {
[email protected]b9b651f2013-11-09 04:32:22684 return transport_->socket()->SetSendBufferSize(size);
685}
686
[email protected]c8a80e92014-05-17 16:02:08687int SSLClientSocketOpenSSL::Init() {
[email protected]9e733f32010-10-04 18:19:08688 DCHECK(!ssl_);
689 DCHECK(!transport_bio_);
690
[email protected]b29af7d2010-12-14 11:52:47691 SSLContext* context = SSLContext::GetInstance();
[email protected]4b559b4d2011-04-14 17:37:14692 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
[email protected]d518cd92010-09-29 12:27:44693
[email protected]fbef13932010-11-23 12:38:53694 ssl_ = SSL_new(context->ssl_ctx());
695 if (!ssl_ || !context->SetClientSocketForSSL(ssl_, this))
[email protected]c8a80e92014-05-17 16:02:08696 return ERR_UNEXPECTED;
[email protected]fbef13932010-11-23 12:38:53697
698 if (!SSL_set_tlsext_host_name(ssl_, host_and_port_.host().c_str()))
[email protected]c8a80e92014-05-17 16:02:08699 return ERR_UNEXPECTED;
[email protected]fbef13932010-11-23 12:38:53700
davidbendafe4e52015-04-08 22:53:52701 SSL_SESSION* session = context->session_cache()->Lookup(GetSessionCacheKey());
702 if (session != nullptr)
703 SSL_set_session(ssl_, session);
[email protected]d518cd92010-09-29 12:27:44704
haavardm2d92e722014-12-19 13:45:44705 send_buffer_ = new GrowableIOBuffer();
706 send_buffer_->SetCapacity(KDefaultOpenSSLBufferSize);
707 recv_buffer_ = new GrowableIOBuffer();
708 recv_buffer_->SetCapacity(KDefaultOpenSSLBufferSize);
709
[email protected]d518cd92010-09-29 12:27:44710 BIO* ssl_bio = NULL;
haavardm2d92e722014-12-19 13:45:44711
712 // SSLClientSocketOpenSSL retains ownership of the BIO buffers.
713 if (!BIO_new_bio_pair_external_buf(
714 &ssl_bio, send_buffer_->capacity(),
715 reinterpret_cast<uint8_t*>(send_buffer_->data()), &transport_bio_,
716 recv_buffer_->capacity(),
717 reinterpret_cast<uint8_t*>(recv_buffer_->data())))
[email protected]c8a80e92014-05-17 16:02:08718 return ERR_UNEXPECTED;
[email protected]d518cd92010-09-29 12:27:44719 DCHECK(ssl_bio);
720 DCHECK(transport_bio_);
721
[email protected]5aea79182014-07-14 20:43:41722 // Install a callback on OpenSSL's end to plumb transport errors through.
rsleevif020edc2015-03-16 19:31:24723 BIO_set_callback(ssl_bio, &SSLClientSocketOpenSSL::BIOCallback);
[email protected]5aea79182014-07-14 20:43:41724 BIO_set_callback_arg(ssl_bio, reinterpret_cast<char*>(this));
725
[email protected]d518cd92010-09-29 12:27:44726 SSL_set_bio(ssl_, ssl_bio, ssl_bio);
727
davidbenb937d6c2015-05-14 04:53:42728 DCHECK_LT(SSL3_VERSION, ssl_config_.version_min);
729 DCHECK_LT(SSL3_VERSION, ssl_config_.version_max);
730 SSL_set_min_version(ssl_, ssl_config_.version_min);
731 SSL_set_max_version(ssl_, ssl_config_.version_max);
732
[email protected]9e733f32010-10-04 18:19:08733 // OpenSSL defaults some options to on, others to off. To avoid ambiguity,
734 // set everything we care about to an absolute value.
[email protected]fb10e2282010-12-01 17:08:48735 SslSetClearMask options;
[email protected]d0f00492012-08-03 22:35:13736 options.ConfigureFlag(SSL_OP_NO_COMPRESSION, true);
[email protected]9e733f32010-10-04 18:19:08737
738 // TODO(joth): Set this conditionally, see http://crbug.com/55410
[email protected]fb10e2282010-12-01 17:08:48739 options.ConfigureFlag(SSL_OP_LEGACY_SERVER_CONNECT, true);
[email protected]9e733f32010-10-04 18:19:08740
[email protected]fb10e2282010-12-01 17:08:48741 SSL_set_options(ssl_, options.set_mask);
742 SSL_clear_options(ssl_, options.clear_mask);
[email protected]9e733f32010-10-04 18:19:08743
[email protected]fb10e2282010-12-01 17:08:48744 // Same as above, this time for the SSL mode.
745 SslSetClearMask mode;
[email protected]9e733f32010-10-04 18:19:08746
[email protected]fb10e2282010-12-01 17:08:48747 mode.ConfigureFlag(SSL_MODE_RELEASE_BUFFERS, true);
ishermane5c05e12014-09-09 20:32:15748 mode.ConfigureFlag(SSL_MODE_CBC_RECORD_SPLITTING, true);
[email protected]fb10e2282010-12-01 17:08:48749
davidben818d93b2015-02-19 22:27:32750 mode.ConfigureFlag(SSL_MODE_ENABLE_FALSE_START,
[email protected]b788de02014-04-23 18:06:07751 ssl_config_.false_start_enabled);
752
davidben6b8131c2015-02-25 23:30:14753 mode.ConfigureFlag(SSL_MODE_SEND_FALLBACK_SCSV, ssl_config_.version_fallback);
754
[email protected]fb10e2282010-12-01 17:08:48755 SSL_set_mode(ssl_, mode.set_mask);
756 SSL_clear_mode(ssl_, mode.clear_mask);
[email protected]109805a2010-12-07 18:17:06757
758 // Removing ciphers by ID from OpenSSL is a bit involved as we must use the
759 // textual name with SSL_set_cipher_list because there is no public API to
760 // directly remove a cipher by ID.
761 STACK_OF(SSL_CIPHER)* ciphers = SSL_get_ciphers(ssl_);
762 DCHECK(ciphers);
763 // See SSLConfig::disabled_cipher_suites for description of the suites
[email protected]9b4bc4a92013-08-20 22:59:07764 // disabled by default. Note that !SHA256 and !SHA384 only remove HMAC-SHA256
765 // and HMAC-SHA384 cipher suites, not GCM cipher suites with SHA256 or SHA384
766 // as the handshake hash.
bnc1e757502014-12-13 02:20:16767 std::string command(
768 "DEFAULT:!NULL:!aNULL:!SHA256:!SHA384:!aECDH:!AESGCM+AES256:!aPSK");
[email protected]109805a2010-12-07 18:17:06769 // Walk through all the installed ciphers, seeing if any need to be
770 // appended to the cipher removal |command|.
[email protected]edfd0f42014-07-22 18:20:37771 for (size_t i = 0; i < sk_SSL_CIPHER_num(ciphers); ++i) {
[email protected]109805a2010-12-07 18:17:06772 const SSL_CIPHER* cipher = sk_SSL_CIPHER_value(ciphers, i);
pkasting6b68a162014-12-01 22:10:29773 const uint16 id = static_cast<uint16>(SSL_CIPHER_get_id(cipher));
[email protected]109805a2010-12-07 18:17:06774 // Remove any ciphers with a strength of less than 80 bits. Note the NSS
775 // implementation uses "effective" bits here but OpenSSL does not provide
776 // this detail. This only impacts Triple DES: reports 112 vs. 168 bits,
777 // both of which are greater than 80 anyway.
778 bool disable = SSL_CIPHER_get_bits(cipher, NULL) < 80;
779 if (!disable) {
780 disable = std::find(ssl_config_.disabled_cipher_suites.begin(),
781 ssl_config_.disabled_cipher_suites.end(), id) !=
782 ssl_config_.disabled_cipher_suites.end();
783 }
784 if (disable) {
785 const char* name = SSL_CIPHER_get_name(cipher);
786 DVLOG(3) << "Found cipher to remove: '" << name << "', ID: " << id
787 << " strength: " << SSL_CIPHER_get_bits(cipher, NULL);
788 command.append(":!");
789 command.append(name);
790 }
791 }
davidben8ecc3072014-09-03 23:19:09792
davidbena4c9d062015-04-03 22:34:25793 if (!ssl_config_.enable_deprecated_cipher_suites)
794 command.append(":!RC4");
795
davidben8ecc3072014-09-03 23:19:09796 // Disable ECDSA cipher suites on platforms that do not support ECDSA
797 // signed certificates, as servers may use the presence of such
798 // ciphersuites as a hint to send an ECDSA certificate.
799#if defined(OS_WIN)
800 if (base::win::GetVersion() < base::win::VERSION_VISTA)
801 command.append(":!ECDSA");
802#endif
803
[email protected]109805a2010-12-07 18:17:06804 int rv = SSL_set_cipher_list(ssl_, command.c_str());
805 // If this fails (rv = 0) it means there are no ciphers enabled on this SSL.
806 // This will almost certainly result in the socket failing to complete the
807 // handshake at which point the appropriate error is bubbled up to the client.
808 LOG_IF(WARNING, rv != 1) << "SSL_set_cipher_list('" << command << "') "
809 "returned " << rv;
[email protected]ee0f2aa82013-10-25 11:59:26810
811 // TLS channel ids.
[email protected]6b8a3c742014-07-25 00:25:35812 if (IsChannelIDEnabled(ssl_config_, channel_id_service_)) {
[email protected]ee0f2aa82013-10-25 11:59:26813 SSL_enable_tls_channel_id(ssl_);
814 }
815
[email protected]abc44b752014-07-30 03:52:15816 if (!ssl_config_.next_protos.empty()) {
bnc1e757502014-12-13 02:20:16817 // Get list of ciphers that are enabled.
818 STACK_OF(SSL_CIPHER)* enabled_ciphers = SSL_get_ciphers(ssl_);
819 DCHECK(enabled_ciphers);
820 std::vector<uint16> enabled_ciphers_vector;
821 for (size_t i = 0; i < sk_SSL_CIPHER_num(enabled_ciphers); ++i) {
822 const SSL_CIPHER* cipher = sk_SSL_CIPHER_value(enabled_ciphers, i);
823 const uint16 id = static_cast<uint16>(SSL_CIPHER_get_id(cipher));
824 enabled_ciphers_vector.push_back(id);
825 }
826
[email protected]abc44b752014-07-30 03:52:15827 std::vector<uint8_t> wire_protos =
bnc1e757502014-12-13 02:20:16828 SerializeNextProtos(ssl_config_.next_protos,
829 HasCipherAdequateForHTTP2(enabled_ciphers_vector) &&
830 IsTLSVersionAdequateForHTTP2(ssl_config_));
[email protected]abc44b752014-07-30 03:52:15831 SSL_set_alpn_protos(ssl_, wire_protos.empty() ? NULL : &wire_protos[0],
832 wire_protos.size());
833 }
834
davidbeneb5f8ef32014-09-04 14:14:32835 if (ssl_config_.signed_cert_timestamps_enabled) {
836 SSL_enable_signed_cert_timestamps(ssl_);
837 SSL_enable_ocsp_stapling(ssl_);
838 }
839
davidben15f57132015-04-27 18:08:36840 if (cert_verifier_->SupportsOCSPStapling())
davidbend1fb2f12014-11-08 02:51:00841 SSL_enable_ocsp_stapling(ssl_);
davidbeneb5f8ef32014-09-04 14:14:32842
davidben24463662015-04-09 23:36:48843 // Enable fastradio padding.
844 SSL_enable_fastradio_padding(ssl_,
845 ssl_config_.fastradio_padding_enabled &&
846 ssl_config_.fastradio_padding_eligible);
847
davidben421116c2015-05-12 19:56:51848 // By default, renegotiations are rejected. After the initial handshake
849 // completes, some application protocols may re-enable it.
850 SSL_set_reject_peer_renegotiations(ssl_, 1);
851
[email protected]c8a80e92014-05-17 16:02:08852 return OK;
[email protected]d518cd92010-09-29 12:27:44853}
854
[email protected]b9b651f2013-11-09 04:32:22855void SSLClientSocketOpenSSL::DoReadCallback(int rv) {
856 // Since Run may result in Read being called, clear |user_read_callback_|
857 // up front.
[email protected]0dc88b32014-03-26 20:12:28858 if (rv > 0)
859 was_ever_used_ = true;
[email protected]b9b651f2013-11-09 04:32:22860 user_read_buf_ = NULL;
861 user_read_buf_len_ = 0;
862 base::ResetAndReturn(&user_read_callback_).Run(rv);
863}
864
865void SSLClientSocketOpenSSL::DoWriteCallback(int rv) {
866 // Since Run may result in Write being called, clear |user_write_callback_|
867 // up front.
[email protected]0dc88b32014-03-26 20:12:28868 if (rv > 0)
869 was_ever_used_ = true;
[email protected]b9b651f2013-11-09 04:32:22870 user_write_buf_ = NULL;
871 user_write_buf_len_ = 0;
872 base::ResetAndReturn(&user_write_callback_).Run(rv);
873}
874
875bool SSLClientSocketOpenSSL::DoTransportIO() {
876 bool network_moved = false;
877 int rv;
878 // Read and write as much data as possible. The loop is necessary because
879 // Write() may return synchronously.
880 do {
881 rv = BufferSend();
882 if (rv != ERR_IO_PENDING && rv != 0)
883 network_moved = true;
884 } while (rv > 0);
[email protected]5aea79182014-07-14 20:43:41885 if (transport_read_error_ == OK && BufferRecv() != ERR_IO_PENDING)
[email protected]b9b651f2013-11-09 04:32:22886 network_moved = true;
887 return network_moved;
888}
889
pkasting379234c2015-04-08 04:42:12890// TODO(cbentzel): Remove including "base/threading/thread_local.h" and
vadimt6b43dec22015-01-06 01:59:58891// g_first_run_completed once crbug.com/424386 is fixed.
892base::LazyInstance<base::ThreadLocalBoolean>::Leaky g_first_run_completed =
893 LAZY_INSTANCE_INITIALIZER;
894
[email protected]b9b651f2013-11-09 04:32:22895int SSLClientSocketOpenSSL::DoHandshake() {
896 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
vadimt5a243282014-12-24 00:26:16897
898 int rv;
899
pkasting379234c2015-04-08 04:42:12900 // TODO(cbentzel): Leave only 1 call to SSL_do_handshake once crbug.com/424386
vadimt5a243282014-12-24 00:26:16901 // is fixed.
902 if (ssl_config_.send_client_cert && ssl_config_.client_cert.get()) {
vadimt5a243282014-12-24 00:26:16903 rv = SSL_do_handshake(ssl_);
904 } else {
vadimt6b43dec22015-01-06 01:59:58905 if (g_first_run_completed.Get().Get()) {
pkasting379234c2015-04-08 04:42:12906 // TODO(cbentzel): Remove ScopedTracker below once crbug.com/424386 is
vadimt6b43dec22015-01-06 01:59:58907 // fixed.
pkasting379234c2015-04-08 04:42:12908 tracked_objects::ScopedTracker tracking_profile(
909 FROM_HERE_WITH_EXPLICIT_FUNCTION("424386 SSL_do_handshake()"));
vadimt5a243282014-12-24 00:26:16910
vadimt6b43dec22015-01-06 01:59:58911 rv = SSL_do_handshake(ssl_);
912 } else {
913 g_first_run_completed.Get().Set(true);
vadimt6b43dec22015-01-06 01:59:58914 rv = SSL_do_handshake(ssl_);
915 }
vadimt5a243282014-12-24 00:26:16916 }
[email protected]b9b651f2013-11-09 04:32:22917
davidbenc4212c02015-05-12 22:30:18918 int net_error = OK;
919 if (rv <= 0) {
[email protected]b9b651f2013-11-09 04:32:22920 int ssl_error = SSL_get_error(ssl_, rv);
[email protected]b9b651f2013-11-09 04:32:22921 if (ssl_error == SSL_ERROR_WANT_CHANNEL_ID_LOOKUP) {
[email protected]faff9852014-06-21 06:13:46922 // The server supports channel ID. Stop to look one up before returning to
923 // the handshake.
[email protected]faff9852014-06-21 06:13:46924 GotoState(STATE_CHANNEL_ID_LOOKUP);
925 return OK;
[email protected]b9b651f2013-11-09 04:32:22926 }
davidbenced4aa9b2015-05-12 21:22:35927 if (ssl_error == SSL_ERROR_WANT_X509_LOOKUP &&
928 !ssl_config_.send_client_cert) {
929 return ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
930 }
[email protected]b9b651f2013-11-09 04:32:22931
davidbena4409c62014-08-27 17:05:51932 OpenSSLErrorInfo error_info;
933 net_error = MapOpenSSLErrorWithDetails(ssl_error, err_tracer, &error_info);
[email protected]b9b651f2013-11-09 04:32:22934 if (net_error == ERR_IO_PENDING) {
davidbenc4212c02015-05-12 22:30:18935 // If not done, stay in this state
[email protected]b9b651f2013-11-09 04:32:22936 GotoState(STATE_HANDSHAKE);
davidbenc4212c02015-05-12 22:30:18937 return ERR_IO_PENDING;
938 }
939
940 LOG(ERROR) << "handshake failed; returned " << rv << ", SSL error code "
941 << ssl_error << ", net_error " << net_error;
942 net_log_.AddEvent(
943 NetLog::TYPE_SSL_HANDSHAKE_ERROR,
944 CreateNetLogOpenSSLErrorCallback(net_error, ssl_error, error_info));
davidbenf2eaaf92015-05-15 22:18:42945
946 // Classify the handshake failure. This is used to determine causes of the
947 // TLS version fallback.
948
949 // |cipher| is the current outgoing cipher suite, so it is non-null iff
950 // ChangeCipherSpec was sent.
951 const SSL_CIPHER* cipher = SSL_get_current_cipher(ssl_);
952 if (SSL_get_state(ssl_) == SSL3_ST_CR_SRVR_HELLO_A) {
953 ssl_failure_state_ = SSL_FAILURE_CLIENT_HELLO;
954 } else if (cipher && (SSL_CIPHER_get_id(cipher) ==
955 TLS1_CK_DHE_RSA_WITH_AES_128_GCM_SHA256 ||
956 SSL_CIPHER_get_id(cipher) ==
957 TLS1_CK_RSA_WITH_AES_128_GCM_SHA256)) {
958 ssl_failure_state_ = SSL_FAILURE_BUGGY_GCM;
959 } else if (cipher && ssl_config_.send_client_cert) {
960 ssl_failure_state_ = SSL_FAILURE_CLIENT_AUTH;
961 } else if (ERR_GET_LIB(error_info.error_code) == ERR_LIB_SSL &&
962 ERR_GET_REASON(error_info.error_code) ==
963 SSL_R_OLD_SESSION_VERSION_NOT_RETURNED) {
964 ssl_failure_state_ = SSL_FAILURE_SESSION_MISMATCH;
965 } else if (cipher && npn_status_ != kNextProtoUnsupported) {
966 ssl_failure_state_ = SSL_FAILURE_NEXT_PROTO;
967 } else {
968 ssl_failure_state_ = SSL_FAILURE_UNKNOWN;
969 }
davidbenc4212c02015-05-12 22:30:18970 }
971
972 GotoState(STATE_HANDSHAKE_COMPLETE);
973 return net_error;
974}
975
976int SSLClientSocketOpenSSL::DoHandshakeComplete(int result) {
977 if (result < 0)
978 return result;
979
980 if (ssl_config_.version_fallback &&
981 ssl_config_.version_max < ssl_config_.version_fallback_min) {
982 return ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION;
983 }
984
985 // SSL handshake is completed. If NPN wasn't negotiated, see if ALPN was.
986 if (npn_status_ == kNextProtoUnsupported) {
987 const uint8_t* alpn_proto = NULL;
988 unsigned alpn_len = 0;
989 SSL_get0_alpn_selected(ssl_, &alpn_proto, &alpn_len);
990 if (alpn_len > 0) {
991 npn_proto_.assign(reinterpret_cast<const char*>(alpn_proto), alpn_len);
992 npn_status_ = kNextProtoNegotiated;
993 set_negotiation_extension(kExtensionALPN);
[email protected]b9b651f2013-11-09 04:32:22994 }
995 }
davidbenc4212c02015-05-12 22:30:18996
997 RecordNegotiationExtension();
998 RecordChannelIDSupport(channel_id_service_, channel_id_sent_,
999 ssl_config_.channel_id_enabled,
1000 crypto::ECPrivateKey::IsSupported());
1001
1002 // Only record OCSP histograms if OCSP was requested.
1003 if (ssl_config_.signed_cert_timestamps_enabled ||
1004 cert_verifier_->SupportsOCSPStapling()) {
1005 const uint8_t* ocsp_response;
1006 size_t ocsp_response_len;
1007 SSL_get0_ocsp_response(ssl_, &ocsp_response, &ocsp_response_len);
1008
1009 set_stapled_ocsp_response_received(ocsp_response_len != 0);
1010 UMA_HISTOGRAM_BOOLEAN("Net.OCSPResponseStapled", ocsp_response_len != 0);
1011 }
1012
1013 const uint8_t* sct_list;
1014 size_t sct_list_len;
1015 SSL_get0_signed_cert_timestamp_list(ssl_, &sct_list, &sct_list_len);
1016 set_signed_cert_timestamps_received(sct_list_len != 0);
1017
1018 if (IsRenegotiationAllowed())
1019 SSL_set_reject_peer_renegotiations(ssl_, 0);
1020
1021 // Verify the certificate.
1022 UpdateServerCert();
1023 GotoState(STATE_VERIFY_CERT);
1024 return OK;
[email protected]b9b651f2013-11-09 04:32:221025}
1026
[email protected]faff9852014-06-21 06:13:461027int SSLClientSocketOpenSSL::DoChannelIDLookup() {
rch98cf4472015-02-13 00:14:141028 net_log_.AddEvent(NetLog::TYPE_SSL_CHANNEL_ID_REQUESTED);
[email protected]faff9852014-06-21 06:13:461029 GotoState(STATE_CHANNEL_ID_LOOKUP_COMPLETE);
[email protected]6b8a3c742014-07-25 00:25:351030 return channel_id_service_->GetOrCreateChannelID(
[email protected]faff9852014-06-21 06:13:461031 host_and_port_.host(),
1032 &channel_id_private_key_,
1033 &channel_id_cert_,
1034 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete,
1035 base::Unretained(this)),
1036 &channel_id_request_handle_);
1037}
1038
1039int SSLClientSocketOpenSSL::DoChannelIDLookupComplete(int result) {
1040 if (result < 0)
1041 return result;
1042
1043 DCHECK_LT(0u, channel_id_private_key_.size());
1044 // Decode key.
1045 std::vector<uint8> encrypted_private_key_info;
1046 std::vector<uint8> subject_public_key_info;
1047 encrypted_private_key_info.assign(
1048 channel_id_private_key_.data(),
1049 channel_id_private_key_.data() + channel_id_private_key_.size());
1050 subject_public_key_info.assign(
1051 channel_id_cert_.data(),
1052 channel_id_cert_.data() + channel_id_cert_.size());
1053 scoped_ptr<crypto::ECPrivateKey> ec_private_key(
1054 crypto::ECPrivateKey::CreateFromEncryptedPrivateKeyInfo(
[email protected]6b8a3c742014-07-25 00:25:351055 ChannelIDService::kEPKIPassword,
[email protected]faff9852014-06-21 06:13:461056 encrypted_private_key_info,
1057 subject_public_key_info));
1058 if (!ec_private_key) {
1059 LOG(ERROR) << "Failed to import Channel ID.";
1060 return ERR_CHANNEL_ID_IMPORT_FAILED;
1061 }
1062
1063 // Hand the key to OpenSSL. Check for error in case OpenSSL rejects the key
1064 // type.
1065 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1066 int rv = SSL_set1_tls_channel_id(ssl_, ec_private_key->key());
1067 if (!rv) {
1068 LOG(ERROR) << "Failed to set Channel ID.";
1069 int err = SSL_get_error(ssl_, rv);
1070 return MapOpenSSLError(err, err_tracer);
1071 }
1072
1073 // Return to the handshake.
davidben52053b382015-04-27 19:22:291074 channel_id_sent_ = true;
rch98cf4472015-02-13 00:14:141075 net_log_.AddEvent(NetLog::TYPE_SSL_CHANNEL_ID_PROVIDED);
[email protected]faff9852014-06-21 06:13:461076 GotoState(STATE_HANDSHAKE);
1077 return OK;
1078}
1079
[email protected]b9b651f2013-11-09 04:32:221080int SSLClientSocketOpenSSL::DoVerifyCert(int result) {
davidben30798ed82014-09-19 19:28:201081 DCHECK(!server_cert_chain_->empty());
davidben09c3d072014-08-25 20:33:581082 DCHECK(start_cert_verification_time_.is_null());
davidben30798ed82014-09-19 19:28:201083
[email protected]b9b651f2013-11-09 04:32:221084 GotoState(STATE_VERIFY_CERT_COMPLETE);
1085
davidben30798ed82014-09-19 19:28:201086 // If the certificate is bad and has been previously accepted, use
1087 // the previous status and bypass the error.
1088 base::StringPiece der_cert;
1089 if (!x509_util::GetDER(server_cert_chain_->Get(0), &der_cert)) {
1090 NOTREACHED();
1091 return ERR_CERT_INVALID;
1092 }
[email protected]b9b651f2013-11-09 04:32:221093 CertStatus cert_status;
davidben30798ed82014-09-19 19:28:201094 if (ssl_config_.IsAllowedBadCert(der_cert, &cert_status)) {
[email protected]b9b651f2013-11-09 04:32:221095 VLOG(1) << "Received an expected bad cert with status: " << cert_status;
1096 server_cert_verify_result_.Reset();
1097 server_cert_verify_result_.cert_status = cert_status;
1098 server_cert_verify_result_.verified_cert = server_cert_;
1099 return OK;
1100 }
1101
davidben30798ed82014-09-19 19:28:201102 // When running in a sandbox, it may not be possible to create an
1103 // X509Certificate*, as that may depend on OS functionality blocked
1104 // in the sandbox.
1105 if (!server_cert_.get()) {
1106 server_cert_verify_result_.Reset();
1107 server_cert_verify_result_.cert_status = CERT_STATUS_INVALID;
1108 return ERR_CERT_INVALID;
1109 }
1110
davidben15f57132015-04-27 18:08:361111 std::string ocsp_response;
1112 if (cert_verifier_->SupportsOCSPStapling()) {
1113 const uint8_t* ocsp_response_raw;
1114 size_t ocsp_response_len;
1115 SSL_get0_ocsp_response(ssl_, &ocsp_response_raw, &ocsp_response_len);
1116 ocsp_response.assign(reinterpret_cast<const char*>(ocsp_response_raw),
1117 ocsp_response_len);
1118 }
1119
davidben09c3d072014-08-25 20:33:581120 start_cert_verification_time_ = base::TimeTicks::Now();
1121
[email protected]b9b651f2013-11-09 04:32:221122 int flags = 0;
1123 if (ssl_config_.rev_checking_enabled)
1124 flags |= CertVerifier::VERIFY_REV_CHECKING_ENABLED;
1125 if (ssl_config_.verify_ev_cert)
1126 flags |= CertVerifier::VERIFY_EV_CERT;
1127 if (ssl_config_.cert_io_enabled)
1128 flags |= CertVerifier::VERIFY_CERT_IO_ENABLED;
1129 if (ssl_config_.rev_checking_required_local_anchors)
1130 flags |= CertVerifier::VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS;
eroman7f9236a2015-05-11 21:23:431131 return cert_verifier_->Verify(
davidben15f57132015-04-27 18:08:361132 server_cert_.get(), host_and_port_.host(), ocsp_response, flags,
[email protected]591cffcd2014-08-18 20:02:301133 // TODO(davidben): Route the CRLSet through SSLConfig so
1134 // SSLClientSocket doesn't depend on SSLConfigService.
davidben15f57132015-04-27 18:08:361135 SSLConfigService::GetCRLSet().get(), &server_cert_verify_result_,
[email protected]b9b651f2013-11-09 04:32:221136 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete,
1137 base::Unretained(this)),
eroman7f9236a2015-05-11 21:23:431138 &cert_verifier_request_, net_log_);
[email protected]b9b651f2013-11-09 04:32:221139}
1140
1141int SSLClientSocketOpenSSL::DoVerifyCertComplete(int result) {
eroman7f9236a2015-05-11 21:23:431142 cert_verifier_request_.reset();
[email protected]b9b651f2013-11-09 04:32:221143
davidben09c3d072014-08-25 20:33:581144 if (!start_cert_verification_time_.is_null()) {
1145 base::TimeDelta verify_time =
1146 base::TimeTicks::Now() - start_cert_verification_time_;
1147 if (result == OK) {
1148 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTime", verify_time);
1149 } else {
1150 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTimeError", verify_time);
1151 }
1152 }
1153
davidben85574eb2014-12-12 03:01:571154 if (result == OK) {
davidben85574eb2014-12-12 03:01:571155 if (SSL_session_reused(ssl_)) {
1156 // Record whether or not the server tried to resume a session for a
1157 // different version. See https://crbug.com/441456.
1158 UMA_HISTOGRAM_BOOLEAN(
1159 "Net.SSLSessionVersionMatch",
1160 SSL_version(ssl_) == SSL_get_session(ssl_)->ssl_version);
1161 }
1162 }
1163
[email protected]8bd4e7a2014-08-09 14:49:171164 const CertStatus cert_status = server_cert_verify_result_.cert_status;
1165 if (transport_security_state_ &&
1166 (result == OK ||
1167 (IsCertificateError(result) && IsCertStatusMinorError(cert_status))) &&
1168 !transport_security_state_->CheckPublicKeyPins(
1169 host_and_port_.host(),
[email protected]8bd4e7a2014-08-09 14:49:171170 server_cert_verify_result_.is_issued_by_known_root,
1171 server_cert_verify_result_.public_key_hashes,
1172 &pinning_failure_log_)) {
1173 result = ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN;
1174 }
1175
[email protected]b9b651f2013-11-09 04:32:221176 if (result == OK) {
davidbeneb5f8ef32014-09-04 14:14:321177 // Only check Certificate Transparency if there were no other errors with
1178 // the connection.
1179 VerifyCT();
1180
davidbendafe4e52015-04-08 22:53:521181 DCHECK(!certificate_verified_);
1182 certificate_verified_ = true;
1183 MaybeCacheSession();
[email protected]b9b651f2013-11-09 04:32:221184 } else {
1185 DVLOG(1) << "DoVerifyCertComplete error " << ErrorToString(result)
1186 << " (" << result << ")";
1187 }
1188
[email protected]64b5c892014-08-08 09:39:261189 completed_connect_ = true;
[email protected]b9b651f2013-11-09 04:32:221190 // Exit DoHandshakeLoop and return the result to the caller to Connect.
1191 DCHECK_EQ(STATE_NONE, next_handshake_state_);
1192 return result;
1193}
1194
1195void SSLClientSocketOpenSSL::DoConnectCallback(int rv) {
1196 if (!user_connect_callback_.is_null()) {
1197 CompletionCallback c = user_connect_callback_;
1198 user_connect_callback_.Reset();
1199 c.Run(rv > OK ? OK : rv);
1200 }
1201}
1202
davidben30798ed82014-09-19 19:28:201203void SSLClientSocketOpenSSL::UpdateServerCert() {
[email protected]76e85392014-03-20 17:54:141204 server_cert_chain_->Reset(SSL_get_peer_cert_chain(ssl_));
[email protected]7f38da8a2014-03-17 16:44:261205 server_cert_ = server_cert_chain_->AsOSChain();
davidben30798ed82014-09-19 19:28:201206 if (server_cert_.get()) {
1207 net_log_.AddEvent(
1208 NetLog::TYPE_SSL_CERTIFICATES_RECEIVED,
1209 base::Bind(&NetLogX509CertificateCallback,
1210 base::Unretained(server_cert_.get())));
1211 }
[email protected]b9b651f2013-11-09 04:32:221212}
1213
davidbeneb5f8ef32014-09-04 14:14:321214void SSLClientSocketOpenSSL::VerifyCT() {
1215 if (!cert_transparency_verifier_)
1216 return;
1217
davidben54015aa2014-12-02 22:16:231218 const uint8_t* ocsp_response_raw;
davidbeneb5f8ef32014-09-04 14:14:321219 size_t ocsp_response_len;
1220 SSL_get0_ocsp_response(ssl_, &ocsp_response_raw, &ocsp_response_len);
1221 std::string ocsp_response;
1222 if (ocsp_response_len > 0) {
1223 ocsp_response.assign(reinterpret_cast<const char*>(ocsp_response_raw),
1224 ocsp_response_len);
1225 }
1226
davidben54015aa2014-12-02 22:16:231227 const uint8_t* sct_list_raw;
davidbeneb5f8ef32014-09-04 14:14:321228 size_t sct_list_len;
1229 SSL_get0_signed_cert_timestamp_list(ssl_, &sct_list_raw, &sct_list_len);
1230 std::string sct_list;
1231 if (sct_list_len > 0)
1232 sct_list.assign(reinterpret_cast<const char*>(sct_list_raw), sct_list_len);
1233
1234 // Note that this is a completely synchronous operation: The CT Log Verifier
1235 // gets all the data it needs for SCT verification and does not do any
1236 // external communication.
eranm6571b2b2014-12-03 15:53:231237 cert_transparency_verifier_->Verify(
1238 server_cert_verify_result_.verified_cert.get(), ocsp_response, sct_list,
1239 &ct_verify_result_, net_log_);
davidbeneb5f8ef32014-09-04 14:14:321240
eranm6571b2b2014-12-03 15:53:231241 if (!policy_enforcer_) {
1242 server_cert_verify_result_.cert_status &= ~CERT_STATUS_IS_EV;
1243 } else {
1244 if (server_cert_verify_result_.cert_status & CERT_STATUS_IS_EV) {
1245 scoped_refptr<ct::EVCertsWhitelist> ev_whitelist =
1246 SSLConfigService::GetEVCertsWhitelist();
1247 if (!policy_enforcer_->DoesConformToCTEVPolicy(
1248 server_cert_verify_result_.verified_cert.get(),
eranm18a019272014-12-18 08:43:231249 ev_whitelist.get(), ct_verify_result_, net_log_)) {
eranm6571b2b2014-12-03 15:53:231250 // TODO(eranm): Log via the BoundNetLog, see crbug.com/437766
1251 VLOG(1) << "EV certificate for "
1252 << server_cert_verify_result_.verified_cert->subject()
1253 .GetDisplayName()
1254 << " does not conform to CT policy, removing EV status.";
1255 server_cert_verify_result_.cert_status &= ~CERT_STATUS_IS_EV;
1256 }
1257 }
1258 }
davidbeneb5f8ef32014-09-04 14:14:321259}
1260
[email protected]b9b651f2013-11-09 04:32:221261void SSLClientSocketOpenSSL::OnHandshakeIOComplete(int result) {
1262 int rv = DoHandshakeLoop(result);
1263 if (rv != ERR_IO_PENDING) {
1264 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
1265 DoConnectCallback(rv);
1266 }
1267}
1268
1269void SSLClientSocketOpenSSL::OnSendComplete(int result) {
1270 if (next_handshake_state_ == STATE_HANDSHAKE) {
1271 // In handshake phase.
1272 OnHandshakeIOComplete(result);
1273 return;
1274 }
1275
1276 // OnSendComplete may need to call DoPayloadRead while the renegotiation
1277 // handshake is in progress.
1278 int rv_read = ERR_IO_PENDING;
1279 int rv_write = ERR_IO_PENDING;
1280 bool network_moved;
1281 do {
1282 if (user_read_buf_.get())
1283 rv_read = DoPayloadRead();
1284 if (user_write_buf_.get())
1285 rv_write = DoPayloadWrite();
1286 network_moved = DoTransportIO();
1287 } while (rv_read == ERR_IO_PENDING && rv_write == ERR_IO_PENDING &&
1288 (user_read_buf_.get() || user_write_buf_.get()) && network_moved);
1289
1290 // Performing the Read callback may cause |this| to be deleted. If this
1291 // happens, the Write callback should not be invoked. Guard against this by
1292 // holding a WeakPtr to |this| and ensuring it's still valid.
1293 base::WeakPtr<SSLClientSocketOpenSSL> guard(weak_factory_.GetWeakPtr());
1294 if (user_read_buf_.get() && rv_read != ERR_IO_PENDING)
1295 DoReadCallback(rv_read);
1296
1297 if (!guard.get())
1298 return;
1299
1300 if (user_write_buf_.get() && rv_write != ERR_IO_PENDING)
1301 DoWriteCallback(rv_write);
1302}
1303
1304void SSLClientSocketOpenSSL::OnRecvComplete(int result) {
1305 if (next_handshake_state_ == STATE_HANDSHAKE) {
1306 // In handshake phase.
1307 OnHandshakeIOComplete(result);
1308 return;
1309 }
1310
1311 // Network layer received some data, check if client requested to read
1312 // decrypted data.
1313 if (!user_read_buf_.get())
1314 return;
1315
davidben1b133ad2014-10-23 04:23:131316 int rv = DoReadLoop();
[email protected]b9b651f2013-11-09 04:32:221317 if (rv != ERR_IO_PENDING)
1318 DoReadCallback(rv);
1319}
1320
1321int SSLClientSocketOpenSSL::DoHandshakeLoop(int last_io_result) {
1322 int rv = last_io_result;
1323 do {
1324 // Default to STATE_NONE for next state.
1325 // (This is a quirk carried over from the windows
1326 // implementation. It makes reading the logs a bit harder.)
1327 // State handlers can and often do call GotoState just
1328 // to stay in the current state.
1329 State state = next_handshake_state_;
1330 GotoState(STATE_NONE);
1331 switch (state) {
1332 case STATE_HANDSHAKE:
1333 rv = DoHandshake();
1334 break;
davidbenc4212c02015-05-12 22:30:181335 case STATE_HANDSHAKE_COMPLETE:
1336 rv = DoHandshakeComplete(rv);
1337 break;
[email protected]faff9852014-06-21 06:13:461338 case STATE_CHANNEL_ID_LOOKUP:
1339 DCHECK_EQ(OK, rv);
1340 rv = DoChannelIDLookup();
1341 break;
1342 case STATE_CHANNEL_ID_LOOKUP_COMPLETE:
1343 rv = DoChannelIDLookupComplete(rv);
1344 break;
[email protected]b9b651f2013-11-09 04:32:221345 case STATE_VERIFY_CERT:
[email protected]faff9852014-06-21 06:13:461346 DCHECK_EQ(OK, rv);
[email protected]b9b651f2013-11-09 04:32:221347 rv = DoVerifyCert(rv);
1348 break;
1349 case STATE_VERIFY_CERT_COMPLETE:
1350 rv = DoVerifyCertComplete(rv);
1351 break;
1352 case STATE_NONE:
1353 default:
1354 rv = ERR_UNEXPECTED;
1355 NOTREACHED() << "unexpected state" << state;
1356 break;
1357 }
1358
1359 bool network_moved = DoTransportIO();
1360 if (network_moved && next_handshake_state_ == STATE_HANDSHAKE) {
1361 // In general we exit the loop if rv is ERR_IO_PENDING. In this
1362 // special case we keep looping even if rv is ERR_IO_PENDING because
1363 // the transport IO may allow DoHandshake to make progress.
1364 rv = OK; // This causes us to stay in the loop.
1365 }
1366 } while (rv != ERR_IO_PENDING && next_handshake_state_ != STATE_NONE);
1367 return rv;
1368}
1369
davidben1b133ad2014-10-23 04:23:131370int SSLClientSocketOpenSSL::DoReadLoop() {
[email protected]b9b651f2013-11-09 04:32:221371 bool network_moved;
1372 int rv;
1373 do {
1374 rv = DoPayloadRead();
1375 network_moved = DoTransportIO();
1376 } while (rv == ERR_IO_PENDING && network_moved);
1377
1378 return rv;
1379}
1380
davidben1b133ad2014-10-23 04:23:131381int SSLClientSocketOpenSSL::DoWriteLoop() {
[email protected]b9b651f2013-11-09 04:32:221382 bool network_moved;
1383 int rv;
1384 do {
1385 rv = DoPayloadWrite();
1386 network_moved = DoTransportIO();
1387 } while (rv == ERR_IO_PENDING && network_moved);
1388
1389 return rv;
1390}
1391
1392int SSLClientSocketOpenSSL::DoPayloadRead() {
1393 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1394
davidben7e555daf2015-03-25 17:03:291395 DCHECK_LT(0, user_read_buf_len_);
1396 DCHECK(user_read_buf_.get());
1397
[email protected]b9b651f2013-11-09 04:32:221398 int rv;
1399 if (pending_read_error_ != kNoPendingReadResult) {
1400 rv = pending_read_error_;
1401 pending_read_error_ = kNoPendingReadResult;
1402 if (rv == 0) {
1403 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED,
1404 rv, user_read_buf_->data());
davidbenb8c23212014-10-28 00:12:161405 } else {
1406 net_log_.AddEvent(
1407 NetLog::TYPE_SSL_READ_ERROR,
1408 CreateNetLogOpenSSLErrorCallback(rv, pending_read_ssl_error_,
1409 pending_read_error_info_));
[email protected]b9b651f2013-11-09 04:32:221410 }
davidbenb8c23212014-10-28 00:12:161411 pending_read_ssl_error_ = SSL_ERROR_NONE;
1412 pending_read_error_info_ = OpenSSLErrorInfo();
[email protected]b9b651f2013-11-09 04:32:221413 return rv;
1414 }
1415
1416 int total_bytes_read = 0;
davidben7e555daf2015-03-25 17:03:291417 int ssl_ret;
[email protected]b9b651f2013-11-09 04:32:221418 do {
davidben7e555daf2015-03-25 17:03:291419 ssl_ret = SSL_read(ssl_, user_read_buf_->data() + total_bytes_read,
1420 user_read_buf_len_ - total_bytes_read);
1421 if (ssl_ret > 0)
1422 total_bytes_read += ssl_ret;
1423 } while (total_bytes_read < user_read_buf_len_ && ssl_ret > 0);
[email protected]b9b651f2013-11-09 04:32:221424
davidben7e555daf2015-03-25 17:03:291425 // Although only the final SSL_read call may have failed, the failure needs to
1426 // processed immediately, while the information still available in OpenSSL's
1427 // error queue.
davidbenced4aa9b2015-05-12 21:22:351428 if (ssl_ret <= 0) {
davidben7e555daf2015-03-25 17:03:291429 // A zero return from SSL_read may mean any of:
1430 // - The underlying BIO_read returned 0.
1431 // - The peer sent a close_notify.
1432 // - Any arbitrary error. https://crbug.com/466303
[email protected]b9b651f2013-11-09 04:32:221433 //
davidben7e555daf2015-03-25 17:03:291434 // TransportReadComplete converts the first to an ERR_CONNECTION_CLOSED
1435 // error, so it does not occur. The second and third are distinguished by
1436 // SSL_ERROR_ZERO_RETURN.
1437 pending_read_ssl_error_ = SSL_get_error(ssl_, ssl_ret);
1438 if (pending_read_ssl_error_ == SSL_ERROR_ZERO_RETURN) {
1439 pending_read_error_ = 0;
davidbenced4aa9b2015-05-12 21:22:351440 } else if (pending_read_ssl_error_ == SSL_ERROR_WANT_X509_LOOKUP &&
1441 !ssl_config_.send_client_cert) {
1442 pending_read_error_ = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
davidben7e555daf2015-03-25 17:03:291443 } else {
1444 pending_read_error_ = MapOpenSSLErrorWithDetails(
1445 pending_read_ssl_error_, err_tracer, &pending_read_error_info_);
[email protected]b9b651f2013-11-09 04:32:221446 }
1447
davidben7e555daf2015-03-25 17:03:291448 // Many servers do not reliably send a close_notify alert when shutting down
1449 // a connection, and instead terminate the TCP connection. This is reported
1450 // as ERR_CONNECTION_CLOSED. Because of this, map the unclean shutdown to a
1451 // graceful EOF, instead of treating it as an error as it should be.
1452 if (pending_read_error_ == ERR_CONNECTION_CLOSED)
1453 pending_read_error_ = 0;
1454 }
davidbenbe6ce7ec2014-10-20 19:15:561455
davidben7e555daf2015-03-25 17:03:291456 if (total_bytes_read > 0) {
1457 // Return any bytes read to the caller. The error will be deferred to the
1458 // next call of DoPayloadRead.
1459 rv = total_bytes_read;
davidbenbe6ce7ec2014-10-20 19:15:561460
davidben7e555daf2015-03-25 17:03:291461 // Do not treat insufficient data as an error to return in the next call to
1462 // DoPayloadRead() - instead, let the call fall through to check SSL_read()
1463 // again. This is because DoTransportIO() may complete in between the next
1464 // call to DoPayloadRead(), and thus it is important to check SSL_read() on
1465 // subsequent invocations to see if a complete record may now be read.
1466 if (pending_read_error_ == ERR_IO_PENDING)
1467 pending_read_error_ = kNoPendingReadResult;
1468 } else {
1469 // No bytes were returned. Return the pending read error immediately.
1470 DCHECK_NE(kNoPendingReadResult, pending_read_error_);
1471 rv = pending_read_error_;
1472 pending_read_error_ = kNoPendingReadResult;
[email protected]b9b651f2013-11-09 04:32:221473 }
1474
1475 if (rv >= 0) {
1476 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, rv,
1477 user_read_buf_->data());
davidbenb8c23212014-10-28 00:12:161478 } else if (rv != ERR_IO_PENDING) {
1479 net_log_.AddEvent(
1480 NetLog::TYPE_SSL_READ_ERROR,
1481 CreateNetLogOpenSSLErrorCallback(rv, pending_read_ssl_error_,
1482 pending_read_error_info_));
1483 pending_read_ssl_error_ = SSL_ERROR_NONE;
1484 pending_read_error_info_ = OpenSSLErrorInfo();
[email protected]b9b651f2013-11-09 04:32:221485 }
1486 return rv;
1487}
1488
1489int SSLClientSocketOpenSSL::DoPayloadWrite() {
1490 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1491 int rv = SSL_write(ssl_, user_write_buf_->data(), user_write_buf_len_);
rsleevif020edc2015-03-16 19:31:241492
[email protected]b9b651f2013-11-09 04:32:221493 if (rv >= 0) {
1494 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_SENT, rv,
1495 user_write_buf_->data());
1496 return rv;
1497 }
1498
davidbenb8c23212014-10-28 00:12:161499 int ssl_error = SSL_get_error(ssl_, rv);
1500 OpenSSLErrorInfo error_info;
1501 int net_error = MapOpenSSLErrorWithDetails(ssl_error, err_tracer,
1502 &error_info);
1503
1504 if (net_error != ERR_IO_PENDING) {
1505 net_log_.AddEvent(
1506 NetLog::TYPE_SSL_WRITE_ERROR,
1507 CreateNetLogOpenSSLErrorCallback(net_error, ssl_error, error_info));
1508 }
1509 return net_error;
[email protected]b9b651f2013-11-09 04:32:221510}
1511
1512int SSLClientSocketOpenSSL::BufferSend(void) {
1513 if (transport_send_busy_)
1514 return ERR_IO_PENDING;
1515
haavardm2d92e722014-12-19 13:45:441516 size_t buffer_read_offset;
1517 uint8_t* read_buf;
1518 size_t max_read;
1519 int status = BIO_zero_copy_get_read_buf(transport_bio_, &read_buf,
1520 &buffer_read_offset, &max_read);
1521 DCHECK_EQ(status, 1); // Should never fail.
1522 if (!max_read)
1523 return 0; // Nothing pending in the OpenSSL write BIO.
1524 CHECK_EQ(read_buf, reinterpret_cast<uint8_t*>(send_buffer_->StartOfBuffer()));
1525 CHECK_LT(buffer_read_offset, static_cast<size_t>(send_buffer_->capacity()));
1526 send_buffer_->set_offset(buffer_read_offset);
[email protected]b9b651f2013-11-09 04:32:221527
1528 int rv = transport_->socket()->Write(
haavardm2d92e722014-12-19 13:45:441529 send_buffer_.get(), max_read,
[email protected]b9b651f2013-11-09 04:32:221530 base::Bind(&SSLClientSocketOpenSSL::BufferSendComplete,
1531 base::Unretained(this)));
1532 if (rv == ERR_IO_PENDING) {
1533 transport_send_busy_ = true;
1534 } else {
1535 TransportWriteComplete(rv);
1536 }
1537 return rv;
1538}
1539
1540int SSLClientSocketOpenSSL::BufferRecv(void) {
1541 if (transport_recv_busy_)
1542 return ERR_IO_PENDING;
1543
1544 // Determine how much was requested from |transport_bio_| that was not
1545 // actually available.
1546 size_t requested = BIO_ctrl_get_read_request(transport_bio_);
1547 if (requested == 0) {
1548 // This is not a perfect match of error codes, as no operation is
1549 // actually pending. However, returning 0 would be interpreted as
1550 // a possible sign of EOF, which is also an inappropriate match.
1551 return ERR_IO_PENDING;
1552 }
1553
1554 // Known Issue: While only reading |requested| data is the more correct
1555 // implementation, it has the downside of resulting in frequent reads:
1556 // One read for the SSL record header (~5 bytes) and one read for the SSL
1557 // record body. Rather than issuing these reads to the underlying socket
1558 // (and constantly allocating new IOBuffers), a single Read() request to
1559 // fill |transport_bio_| is issued. As long as an SSL client socket cannot
1560 // be gracefully shutdown (via SSL close alerts) and re-used for non-SSL
1561 // traffic, this over-subscribed Read()ing will not cause issues.
haavardm2d92e722014-12-19 13:45:441562
1563 size_t buffer_write_offset;
1564 uint8_t* write_buf;
1565 size_t max_write;
1566 int status = BIO_zero_copy_get_write_buf(transport_bio_, &write_buf,
1567 &buffer_write_offset, &max_write);
1568 DCHECK_EQ(status, 1); // Should never fail.
[email protected]b9b651f2013-11-09 04:32:221569 if (!max_write)
1570 return ERR_IO_PENDING;
1571
haavardm2d92e722014-12-19 13:45:441572 CHECK_EQ(write_buf,
1573 reinterpret_cast<uint8_t*>(recv_buffer_->StartOfBuffer()));
1574 CHECK_LT(buffer_write_offset, static_cast<size_t>(recv_buffer_->capacity()));
1575
1576 recv_buffer_->set_offset(buffer_write_offset);
[email protected]b9b651f2013-11-09 04:32:221577 int rv = transport_->socket()->Read(
1578 recv_buffer_.get(),
1579 max_write,
1580 base::Bind(&SSLClientSocketOpenSSL::BufferRecvComplete,
1581 base::Unretained(this)));
1582 if (rv == ERR_IO_PENDING) {
1583 transport_recv_busy_ = true;
1584 } else {
[email protected]3e5c6922014-02-06 02:42:161585 rv = TransportReadComplete(rv);
[email protected]b9b651f2013-11-09 04:32:221586 }
1587 return rv;
1588}
1589
1590void SSLClientSocketOpenSSL::BufferSendComplete(int result) {
[email protected]b9b651f2013-11-09 04:32:221591 TransportWriteComplete(result);
1592 OnSendComplete(result);
1593}
1594
1595void SSLClientSocketOpenSSL::BufferRecvComplete(int result) {
[email protected]3e5c6922014-02-06 02:42:161596 result = TransportReadComplete(result);
[email protected]b9b651f2013-11-09 04:32:221597 OnRecvComplete(result);
1598}
1599
1600void SSLClientSocketOpenSSL::TransportWriteComplete(int result) {
1601 DCHECK(ERR_IO_PENDING != result);
haavardm2d92e722014-12-19 13:45:441602 int bytes_written = 0;
[email protected]b9b651f2013-11-09 04:32:221603 if (result < 0) {
[email protected]5aea79182014-07-14 20:43:411604 // Record the error. Save it to be reported in a future read or write on
1605 // transport_bio_'s peer.
[email protected]3e5c6922014-02-06 02:42:161606 transport_write_error_ = result;
[email protected]b9b651f2013-11-09 04:32:221607 } else {
haavardm2d92e722014-12-19 13:45:441608 bytes_written = result;
[email protected]b9b651f2013-11-09 04:32:221609 }
haavardm2d92e722014-12-19 13:45:441610 DCHECK_GE(send_buffer_->RemainingCapacity(), bytes_written);
1611 int ret = BIO_zero_copy_get_read_buf_done(transport_bio_, bytes_written);
1612 DCHECK_EQ(1, ret);
1613 transport_send_busy_ = false;
[email protected]b9b651f2013-11-09 04:32:221614}
1615
[email protected]3e5c6922014-02-06 02:42:161616int SSLClientSocketOpenSSL::TransportReadComplete(int result) {
[email protected]b9b651f2013-11-09 04:32:221617 DCHECK(ERR_IO_PENDING != result);
[email protected]5aea79182014-07-14 20:43:411618 // If an EOF, canonicalize to ERR_CONNECTION_CLOSED here so MapOpenSSLError
1619 // does not report success.
1620 if (result == 0)
1621 result = ERR_CONNECTION_CLOSED;
haavardm2d92e722014-12-19 13:45:441622 int bytes_read = 0;
[email protected]5aea79182014-07-14 20:43:411623 if (result < 0) {
[email protected]b9b651f2013-11-09 04:32:221624 DVLOG(1) << "TransportReadComplete result " << result;
[email protected]5aea79182014-07-14 20:43:411625 // Received an error. Save it to be reported in a future read on
1626 // transport_bio_'s peer.
1627 transport_read_error_ = result;
[email protected]b9b651f2013-11-09 04:32:221628 } else {
haavardm2d92e722014-12-19 13:45:441629 bytes_read = result;
[email protected]b9b651f2013-11-09 04:32:221630 }
haavardm2d92e722014-12-19 13:45:441631 DCHECK_GE(recv_buffer_->RemainingCapacity(), bytes_read);
1632 int ret = BIO_zero_copy_get_write_buf_done(transport_bio_, bytes_read);
1633 DCHECK_EQ(1, ret);
[email protected]b9b651f2013-11-09 04:32:221634 transport_recv_busy_ = false;
[email protected]3e5c6922014-02-06 02:42:161635 return result;
[email protected]b9b651f2013-11-09 04:32:221636}
1637
[email protected]82c59022014-08-15 09:38:271638int SSLClientSocketOpenSSL::ClientCertRequestCallback(SSL* ssl) {
[email protected]5ac981e182010-12-06 17:56:271639 DVLOG(3) << "OpenSSL ClientCertRequestCallback called";
1640 DCHECK(ssl == ssl_);
[email protected]82c59022014-08-15 09:38:271641
davidbenaf42cbe2014-11-13 03:27:461642 net_log_.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED);
1643
[email protected]82c59022014-08-15 09:38:271644 // Clear any currently configured certificates.
1645 SSL_certs_clear(ssl_);
[email protected]97a854f2014-07-29 07:51:361646
1647#if defined(OS_IOS)
1648 // TODO(droger): Support client auth on iOS. See http://crbug.com/145954).
1649 LOG(WARNING) << "Client auth is not supported";
1650#else // !defined(OS_IOS)
[email protected]5ac981e182010-12-06 17:56:271651 if (!ssl_config_.send_client_cert) {
[email protected]515adc22013-01-09 16:01:231652 // First pass: we know that a client certificate is needed, but we do not
1653 // have one at hand.
[email protected]515adc22013-01-09 16:01:231654 STACK_OF(X509_NAME) *authorities = SSL_get_client_CA_list(ssl);
[email protected]edfd0f42014-07-22 18:20:371655 for (size_t i = 0; i < sk_X509_NAME_num(authorities); i++) {
[email protected]515adc22013-01-09 16:01:231656 X509_NAME *ca_name = (X509_NAME *)sk_X509_NAME_value(authorities, i);
1657 unsigned char* str = NULL;
1658 int length = i2d_X509_NAME(ca_name, &str);
1659 cert_authorities_.push_back(std::string(
1660 reinterpret_cast<const char*>(str),
1661 static_cast<size_t>(length)));
1662 OPENSSL_free(str);
1663 }
1664
[email protected]c0787702014-05-20 21:51:441665 const unsigned char* client_cert_types;
[email protected]e7e883e2014-07-25 06:03:081666 size_t num_client_cert_types =
1667 SSL_get0_certificate_types(ssl, &client_cert_types);
[email protected]c0787702014-05-20 21:51:441668 for (size_t i = 0; i < num_client_cert_types; i++) {
1669 cert_key_types_.push_back(
1670 static_cast<SSLClientCertType>(client_cert_types[i]));
1671 }
1672
davidbenced4aa9b2015-05-12 21:22:351673 // Suspends handshake. SSL_get_error will return SSL_ERROR_WANT_X509_LOOKUP.
1674 return -1;
[email protected]5ac981e182010-12-06 17:56:271675 }
1676
1677 // Second pass: a client certificate should have been selected.
[email protected]13914c92013-06-13 22:42:421678 if (ssl_config_.client_cert.get()) {
[email protected]6bad5052014-07-12 01:25:131679 ScopedX509 leaf_x509 =
1680 OSCertHandleToOpenSSL(ssl_config_.client_cert->os_cert_handle());
1681 if (!leaf_x509) {
1682 LOG(WARNING) << "Failed to import certificate";
1683 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT);
1684 return -1;
1685 }
1686
[email protected]82c59022014-08-15 09:38:271687 ScopedX509Stack chain = OSCertHandlesToOpenSSL(
1688 ssl_config_.client_cert->GetIntermediateCertificates());
1689 if (!chain) {
1690 LOG(WARNING) << "Failed to import intermediate certificates";
1691 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT);
1692 return -1;
1693 }
1694
[email protected]97a854f2014-07-29 07:51:361695 // TODO(davidben): With Linux client auth support, this should be
1696 // conditioned on OS_ANDROID and then, with https://crbug.com/394131,
1697 // removed altogether. OpenSSLClientKeyStore is mostly an artifact of the
1698 // net/ client auth API lacking a private key handle.
[email protected]c0787702014-05-20 21:51:441699#if defined(USE_OPENSSL_CERTS)
[email protected]97a854f2014-07-29 07:51:361700 crypto::ScopedEVP_PKEY privkey =
1701 OpenSSLClientKeyStore::GetInstance()->FetchClientCertPrivateKey(
1702 ssl_config_.client_cert.get());
1703#else // !defined(USE_OPENSSL_CERTS)
1704 crypto::ScopedEVP_PKEY privkey =
1705 FetchClientCertPrivateKey(ssl_config_.client_cert.get());
1706#endif // defined(USE_OPENSSL_CERTS)
1707 if (!privkey) {
[email protected]6bad5052014-07-12 01:25:131708 // Could not find the private key. Fail the handshake and surface an
1709 // appropriate error to the caller.
1710 LOG(WARNING) << "Client cert found without private key";
1711 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY);
1712 return -1;
[email protected]0c6523f2010-12-10 10:56:241713 }
[email protected]6bad5052014-07-12 01:25:131714
[email protected]82c59022014-08-15 09:38:271715 if (!SSL_use_certificate(ssl_, leaf_x509.get()) ||
1716 !SSL_use_PrivateKey(ssl_, privkey.get()) ||
1717 !SSL_set1_chain(ssl_, chain.get())) {
1718 LOG(WARNING) << "Failed to set client certificate";
1719 return -1;
1720 }
davidbenaf42cbe2014-11-13 03:27:461721
1722 int cert_count = 1 + sk_X509_num(chain.get());
1723 net_log_.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED,
1724 NetLog::IntegerCallback("cert_count", cert_count));
[email protected]6bad5052014-07-12 01:25:131725 return 1;
[email protected]c0787702014-05-20 21:51:441726 }
[email protected]97a854f2014-07-29 07:51:361727#endif // defined(OS_IOS)
[email protected]5ac981e182010-12-06 17:56:271728
1729 // Send no client certificate.
davidbenaf42cbe2014-11-13 03:27:461730 net_log_.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED,
1731 NetLog::IntegerCallback("cert_count", 0));
[email protected]82c59022014-08-15 09:38:271732 return 1;
[email protected]5ac981e182010-12-06 17:56:271733}
1734
[email protected]b051cdb62014-02-28 02:20:161735int SSLClientSocketOpenSSL::CertVerifyCallback(X509_STORE_CTX* store_ctx) {
[email protected]64b5c892014-08-08 09:39:261736 if (!completed_connect_) {
[email protected]b051cdb62014-02-28 02:20:161737 // If the first handshake hasn't completed then we accept any certificates
1738 // because we verify after the handshake.
1739 return 1;
1740 }
1741
davidben30798ed82014-09-19 19:28:201742 // Disallow the server certificate to change in a renegotiation.
1743 if (server_cert_chain_->empty()) {
[email protected]76e85392014-03-20 17:54:141744 LOG(ERROR) << "Received invalid certificate chain between handshakes";
davidben30798ed82014-09-19 19:28:201745 return 0;
1746 }
1747 base::StringPiece old_der, new_der;
1748 if (store_ctx->cert == NULL ||
1749 !x509_util::GetDER(server_cert_chain_->Get(0), &old_der) ||
1750 !x509_util::GetDER(store_ctx->cert, &new_der)) {
1751 LOG(ERROR) << "Failed to encode certificates";
1752 return 0;
1753 }
1754 if (old_der != new_der) {
[email protected]76e85392014-03-20 17:54:141755 LOG(ERROR) << "Server certificate changed between handshakes";
davidben30798ed82014-09-19 19:28:201756 return 0;
1757 }
1758
1759 return 1;
[email protected]b051cdb62014-02-28 02:20:161760}
1761
[email protected]ae7c9f42011-11-21 11:41:161762// SelectNextProtoCallback is called by OpenSSL during the handshake. If the
1763// server supports NPN, selects a protocol from the list that the server
1764// provides. According to third_party/openssl/openssl/ssl/ssl_lib.c, the
1765// callback can assume that |in| is syntactically valid.
[email protected]ea4a1c6a2010-12-09 13:33:281766int SSLClientSocketOpenSSL::SelectNextProtoCallback(unsigned char** out,
1767 unsigned char* outlen,
1768 const unsigned char* in,
1769 unsigned int inlen) {
[email protected]ea4a1c6a2010-12-09 13:33:281770 if (ssl_config_.next_protos.empty()) {
[email protected]168a8412012-06-14 05:05:491771 *out = reinterpret_cast<uint8*>(
1772 const_cast<char*>(kDefaultSupportedNPNProtocol));
1773 *outlen = arraysize(kDefaultSupportedNPNProtocol) - 1;
1774 npn_status_ = kNextProtoUnsupported;
[email protected]ea4a1c6a2010-12-09 13:33:281775 return SSL_TLSEXT_ERR_OK;
1776 }
1777
[email protected]ae7c9f42011-11-21 11:41:161778 // Assume there's no overlap between our protocols and the server's list.
[email protected]168a8412012-06-14 05:05:491779 npn_status_ = kNextProtoNoOverlap;
[email protected]ae7c9f42011-11-21 11:41:161780
1781 // For each protocol in server preference order, see if we support it.
1782 for (unsigned int i = 0; i < inlen; i += in[i] + 1) {
bnc0d23cf42014-12-11 14:09:461783 for (NextProto next_proto : ssl_config_.next_protos) {
1784 const std::string proto = NextProtoToString(next_proto);
1785 if (in[i] == proto.size() &&
1786 memcmp(&in[i + 1], proto.data(), in[i]) == 0) {
[email protected]168a8412012-06-14 05:05:491787 // We found a match.
[email protected]ae7c9f42011-11-21 11:41:161788 *out = const_cast<unsigned char*>(in) + i + 1;
1789 *outlen = in[i];
[email protected]168a8412012-06-14 05:05:491790 npn_status_ = kNextProtoNegotiated;
[email protected]ae7c9f42011-11-21 11:41:161791 break;
1792 }
1793 }
[email protected]168a8412012-06-14 05:05:491794 if (npn_status_ == kNextProtoNegotiated)
[email protected]ae7c9f42011-11-21 11:41:161795 break;
1796 }
[email protected]ea4a1c6a2010-12-09 13:33:281797
[email protected]168a8412012-06-14 05:05:491798 // If we didn't find a protocol, we select the first one from our list.
1799 if (npn_status_ == kNextProtoNoOverlap) {
bnc67da3de2015-01-15 21:02:261800 // NextProtoToString returns a pointer to a static string.
1801 const char* proto = NextProtoToString(ssl_config_.next_protos[0]);
1802 *out = reinterpret_cast<unsigned char*>(const_cast<char*>(proto));
1803 *outlen = strlen(proto);
[email protected]168a8412012-06-14 05:05:491804 }
1805
[email protected]ea4a1c6a2010-12-09 13:33:281806 npn_proto_.assign(reinterpret_cast<const char*>(*out), *outlen);
[email protected]32e1dee2010-12-09 18:36:241807 DVLOG(2) << "next protocol: '" << npn_proto_ << "' status: " << npn_status_;
bnc0d28ea52014-10-13 15:15:381808 set_negotiation_extension(kExtensionNPN);
[email protected]ea4a1c6a2010-12-09 13:33:281809 return SSL_TLSEXT_ERR_OK;
1810}
1811
[email protected]5aea79182014-07-14 20:43:411812long SSLClientSocketOpenSSL::MaybeReplayTransportError(
1813 BIO *bio,
1814 int cmd,
1815 const char *argp, int argi, long argl,
1816 long retvalue) {
1817 if (cmd == (BIO_CB_READ|BIO_CB_RETURN) && retvalue <= 0) {
1818 // If there is no more data in the buffer, report any pending errors that
1819 // were observed. Note that both the readbuf and the writebuf are checked
1820 // for errors, since the application may have encountered a socket error
1821 // while writing that would otherwise not be reported until the application
1822 // attempted to write again - which it may never do. See
1823 // https://crbug.com/249848.
1824 if (transport_read_error_ != OK) {
1825 OpenSSLPutNetError(FROM_HERE, transport_read_error_);
1826 return -1;
1827 }
1828 if (transport_write_error_ != OK) {
1829 OpenSSLPutNetError(FROM_HERE, transport_write_error_);
1830 return -1;
1831 }
1832 } else if (cmd == BIO_CB_WRITE) {
1833 // Because of the write buffer, this reports a failure from the previous
1834 // write payload. If the current payload fails to write, the error will be
1835 // reported in a future write or read to |bio|.
1836 if (transport_write_error_ != OK) {
1837 OpenSSLPutNetError(FROM_HERE, transport_write_error_);
1838 return -1;
1839 }
1840 }
1841 return retvalue;
1842}
1843
1844// static
1845long SSLClientSocketOpenSSL::BIOCallback(
1846 BIO *bio,
1847 int cmd,
1848 const char *argp, int argi, long argl,
1849 long retvalue) {
1850 SSLClientSocketOpenSSL* socket = reinterpret_cast<SSLClientSocketOpenSSL*>(
1851 BIO_get_callback_arg(bio));
1852 CHECK(socket);
1853 return socket->MaybeReplayTransportError(
1854 bio, cmd, argp, argi, argl, retvalue);
1855}
1856
davidbendafe4e52015-04-08 22:53:521857void SSLClientSocketOpenSSL::MaybeCacheSession() {
1858 // Only cache the session once both the handshake has completed and the
1859 // certificate has been verified.
1860 if (!handshake_completed_ || !certificate_verified_ ||
1861 SSL_session_reused(ssl_)) {
1862 return;
1863 }
1864
1865 SSLContext::GetInstance()->session_cache()->Insert(GetSessionCacheKey(),
1866 SSL_get_session(ssl_));
1867}
1868
1869void SSLClientSocketOpenSSL::InfoCallback(int type, int val) {
1870 // Note that SSL_CB_HANDSHAKE_DONE may be signaled multiple times if the
1871 // socket renegotiates.
1872 if (type != SSL_CB_HANDSHAKE_DONE || handshake_completed_)
1873 return;
1874
1875 handshake_completed_ = true;
1876 MaybeCacheSession();
1877}
1878
davidbeneb5f8ef32014-09-04 14:14:321879void SSLClientSocketOpenSSL::AddSCTInfoToSSLInfo(SSLInfo* ssl_info) const {
1880 for (ct::SCTList::const_iterator iter =
1881 ct_verify_result_.verified_scts.begin();
1882 iter != ct_verify_result_.verified_scts.end(); ++iter) {
1883 ssl_info->signed_certificate_timestamps.push_back(
1884 SignedCertificateTimestampAndStatus(*iter, ct::SCT_STATUS_OK));
1885 }
1886 for (ct::SCTList::const_iterator iter =
1887 ct_verify_result_.invalid_scts.begin();
1888 iter != ct_verify_result_.invalid_scts.end(); ++iter) {
1889 ssl_info->signed_certificate_timestamps.push_back(
1890 SignedCertificateTimestampAndStatus(*iter, ct::SCT_STATUS_INVALID));
1891 }
1892 for (ct::SCTList::const_iterator iter =
1893 ct_verify_result_.unknown_logs_scts.begin();
1894 iter != ct_verify_result_.unknown_logs_scts.end(); ++iter) {
1895 ssl_info->signed_certificate_timestamps.push_back(
1896 SignedCertificateTimestampAndStatus(*iter,
1897 ct::SCT_STATUS_LOG_UNKNOWN));
1898 }
1899}
1900
rsleevif020edc2015-03-16 19:31:241901std::string SSLClientSocketOpenSSL::GetSessionCacheKey() const {
1902 std::string result = host_and_port_.ToString();
1903 result.append("/");
1904 result.append(ssl_session_cache_shard_);
1905
1906 // Shard the session cache based on maximum protocol version. This causes
1907 // fallback connections to use a separate session cache.
1908 result.append("/");
1909 switch (ssl_config_.version_max) {
rsleevif020edc2015-03-16 19:31:241910 case SSL_PROTOCOL_VERSION_TLS1:
1911 result.append("tls1");
1912 break;
1913 case SSL_PROTOCOL_VERSION_TLS1_1:
1914 result.append("tls1.1");
1915 break;
1916 case SSL_PROTOCOL_VERSION_TLS1_2:
1917 result.append("tls1.2");
1918 break;
1919 default:
1920 NOTREACHED();
1921 }
1922
davidbena4c9d062015-04-03 22:34:251923 result.append("/");
1924 if (ssl_config_.enable_deprecated_cipher_suites)
1925 result.append("deprecated");
1926
rsleevif020edc2015-03-16 19:31:241927 return result;
1928}
1929
davidben421116c2015-05-12 19:56:511930bool SSLClientSocketOpenSSL::IsRenegotiationAllowed() const {
1931 if (npn_status_ == kNextProtoUnsupported)
1932 return ssl_config_.renego_allowed_default;
1933
1934 NextProto next_proto = NextProtoFromString(npn_proto_);
1935 for (NextProto allowed : ssl_config_.renego_allowed_for_protos) {
1936 if (next_proto == allowed)
1937 return true;
1938 }
1939 return false;
1940}
1941
[email protected]7f38da8a2014-03-17 16:44:261942scoped_refptr<X509Certificate>
1943SSLClientSocketOpenSSL::GetUnverifiedServerCertificateChain() const {
1944 return server_cert_;
1945}
1946
[email protected]7e5dd49f2010-12-08 18:33:491947} // namespace net