blob: d06f5ac48a67fd0e282b820a0269ed53e78aef18 [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;
nharper75ade892015-06-10 19:05:35516 channel_id_request_.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(
nharper2e171cf2015-06-01 20:29:231031 host_and_port_.host(), &channel_id_key_,
[email protected]faff9852014-06-21 06:13:461032 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete,
1033 base::Unretained(this)),
nharper75ade892015-06-10 19:05:351034 &channel_id_request_);
[email protected]faff9852014-06-21 06:13:461035}
1036
1037int SSLClientSocketOpenSSL::DoChannelIDLookupComplete(int result) {
1038 if (result < 0)
1039 return result;
1040
nharper2e171cf2015-06-01 20:29:231041 if (!channel_id_key_) {
[email protected]faff9852014-06-21 06:13:461042 LOG(ERROR) << "Failed to import Channel ID.";
1043 return ERR_CHANNEL_ID_IMPORT_FAILED;
1044 }
1045
1046 // Hand the key to OpenSSL. Check for error in case OpenSSL rejects the key
1047 // type.
1048 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
nharper2e171cf2015-06-01 20:29:231049 int rv = SSL_set1_tls_channel_id(ssl_, channel_id_key_->key());
[email protected]faff9852014-06-21 06:13:461050 if (!rv) {
1051 LOG(ERROR) << "Failed to set Channel ID.";
1052 int err = SSL_get_error(ssl_, rv);
1053 return MapOpenSSLError(err, err_tracer);
1054 }
1055
1056 // Return to the handshake.
davidben52053b382015-04-27 19:22:291057 channel_id_sent_ = true;
rch98cf4472015-02-13 00:14:141058 net_log_.AddEvent(NetLog::TYPE_SSL_CHANNEL_ID_PROVIDED);
[email protected]faff9852014-06-21 06:13:461059 GotoState(STATE_HANDSHAKE);
1060 return OK;
1061}
1062
[email protected]b9b651f2013-11-09 04:32:221063int SSLClientSocketOpenSSL::DoVerifyCert(int result) {
davidben30798ed82014-09-19 19:28:201064 DCHECK(!server_cert_chain_->empty());
davidben09c3d072014-08-25 20:33:581065 DCHECK(start_cert_verification_time_.is_null());
davidben30798ed82014-09-19 19:28:201066
[email protected]b9b651f2013-11-09 04:32:221067 GotoState(STATE_VERIFY_CERT_COMPLETE);
1068
davidben30798ed82014-09-19 19:28:201069 // If the certificate is bad and has been previously accepted, use
1070 // the previous status and bypass the error.
1071 base::StringPiece der_cert;
1072 if (!x509_util::GetDER(server_cert_chain_->Get(0), &der_cert)) {
1073 NOTREACHED();
1074 return ERR_CERT_INVALID;
1075 }
[email protected]b9b651f2013-11-09 04:32:221076 CertStatus cert_status;
davidben30798ed82014-09-19 19:28:201077 if (ssl_config_.IsAllowedBadCert(der_cert, &cert_status)) {
[email protected]b9b651f2013-11-09 04:32:221078 VLOG(1) << "Received an expected bad cert with status: " << cert_status;
1079 server_cert_verify_result_.Reset();
1080 server_cert_verify_result_.cert_status = cert_status;
1081 server_cert_verify_result_.verified_cert = server_cert_;
1082 return OK;
1083 }
1084
davidben30798ed82014-09-19 19:28:201085 // When running in a sandbox, it may not be possible to create an
1086 // X509Certificate*, as that may depend on OS functionality blocked
1087 // in the sandbox.
1088 if (!server_cert_.get()) {
1089 server_cert_verify_result_.Reset();
1090 server_cert_verify_result_.cert_status = CERT_STATUS_INVALID;
1091 return ERR_CERT_INVALID;
1092 }
1093
davidben15f57132015-04-27 18:08:361094 std::string ocsp_response;
1095 if (cert_verifier_->SupportsOCSPStapling()) {
1096 const uint8_t* ocsp_response_raw;
1097 size_t ocsp_response_len;
1098 SSL_get0_ocsp_response(ssl_, &ocsp_response_raw, &ocsp_response_len);
1099 ocsp_response.assign(reinterpret_cast<const char*>(ocsp_response_raw),
1100 ocsp_response_len);
1101 }
1102
davidben09c3d072014-08-25 20:33:581103 start_cert_verification_time_ = base::TimeTicks::Now();
1104
[email protected]b9b651f2013-11-09 04:32:221105 int flags = 0;
1106 if (ssl_config_.rev_checking_enabled)
1107 flags |= CertVerifier::VERIFY_REV_CHECKING_ENABLED;
1108 if (ssl_config_.verify_ev_cert)
1109 flags |= CertVerifier::VERIFY_EV_CERT;
1110 if (ssl_config_.cert_io_enabled)
1111 flags |= CertVerifier::VERIFY_CERT_IO_ENABLED;
1112 if (ssl_config_.rev_checking_required_local_anchors)
1113 flags |= CertVerifier::VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS;
eroman7f9236a2015-05-11 21:23:431114 return cert_verifier_->Verify(
davidben15f57132015-04-27 18:08:361115 server_cert_.get(), host_and_port_.host(), ocsp_response, flags,
[email protected]591cffcd2014-08-18 20:02:301116 // TODO(davidben): Route the CRLSet through SSLConfig so
1117 // SSLClientSocket doesn't depend on SSLConfigService.
davidben15f57132015-04-27 18:08:361118 SSLConfigService::GetCRLSet().get(), &server_cert_verify_result_,
[email protected]b9b651f2013-11-09 04:32:221119 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete,
1120 base::Unretained(this)),
eroman7f9236a2015-05-11 21:23:431121 &cert_verifier_request_, net_log_);
[email protected]b9b651f2013-11-09 04:32:221122}
1123
1124int SSLClientSocketOpenSSL::DoVerifyCertComplete(int result) {
eroman7f9236a2015-05-11 21:23:431125 cert_verifier_request_.reset();
[email protected]b9b651f2013-11-09 04:32:221126
davidben09c3d072014-08-25 20:33:581127 if (!start_cert_verification_time_.is_null()) {
1128 base::TimeDelta verify_time =
1129 base::TimeTicks::Now() - start_cert_verification_time_;
1130 if (result == OK) {
1131 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTime", verify_time);
1132 } else {
1133 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTimeError", verify_time);
1134 }
1135 }
1136
davidben85574eb2014-12-12 03:01:571137 if (result == OK) {
davidben85574eb2014-12-12 03:01:571138 if (SSL_session_reused(ssl_)) {
1139 // Record whether or not the server tried to resume a session for a
1140 // different version. See https://crbug.com/441456.
1141 UMA_HISTOGRAM_BOOLEAN(
1142 "Net.SSLSessionVersionMatch",
1143 SSL_version(ssl_) == SSL_get_session(ssl_)->ssl_version);
1144 }
1145 }
1146
[email protected]8bd4e7a2014-08-09 14:49:171147 const CertStatus cert_status = server_cert_verify_result_.cert_status;
1148 if (transport_security_state_ &&
1149 (result == OK ||
1150 (IsCertificateError(result) && IsCertStatusMinorError(cert_status))) &&
1151 !transport_security_state_->CheckPublicKeyPins(
1152 host_and_port_.host(),
[email protected]8bd4e7a2014-08-09 14:49:171153 server_cert_verify_result_.is_issued_by_known_root,
1154 server_cert_verify_result_.public_key_hashes,
1155 &pinning_failure_log_)) {
1156 result = ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN;
1157 }
1158
[email protected]b9b651f2013-11-09 04:32:221159 if (result == OK) {
davidbeneb5f8ef32014-09-04 14:14:321160 // Only check Certificate Transparency if there were no other errors with
1161 // the connection.
1162 VerifyCT();
1163
davidbendafe4e52015-04-08 22:53:521164 DCHECK(!certificate_verified_);
1165 certificate_verified_ = true;
1166 MaybeCacheSession();
[email protected]b9b651f2013-11-09 04:32:221167 } else {
1168 DVLOG(1) << "DoVerifyCertComplete error " << ErrorToString(result)
1169 << " (" << result << ")";
1170 }
1171
[email protected]64b5c892014-08-08 09:39:261172 completed_connect_ = true;
[email protected]b9b651f2013-11-09 04:32:221173 // Exit DoHandshakeLoop and return the result to the caller to Connect.
1174 DCHECK_EQ(STATE_NONE, next_handshake_state_);
1175 return result;
1176}
1177
1178void SSLClientSocketOpenSSL::DoConnectCallback(int rv) {
1179 if (!user_connect_callback_.is_null()) {
1180 CompletionCallback c = user_connect_callback_;
1181 user_connect_callback_.Reset();
1182 c.Run(rv > OK ? OK : rv);
1183 }
1184}
1185
davidben30798ed82014-09-19 19:28:201186void SSLClientSocketOpenSSL::UpdateServerCert() {
[email protected]76e85392014-03-20 17:54:141187 server_cert_chain_->Reset(SSL_get_peer_cert_chain(ssl_));
[email protected]7f38da8a2014-03-17 16:44:261188 server_cert_ = server_cert_chain_->AsOSChain();
davidben30798ed82014-09-19 19:28:201189 if (server_cert_.get()) {
1190 net_log_.AddEvent(
1191 NetLog::TYPE_SSL_CERTIFICATES_RECEIVED,
1192 base::Bind(&NetLogX509CertificateCallback,
1193 base::Unretained(server_cert_.get())));
1194 }
[email protected]b9b651f2013-11-09 04:32:221195}
1196
davidbeneb5f8ef32014-09-04 14:14:321197void SSLClientSocketOpenSSL::VerifyCT() {
1198 if (!cert_transparency_verifier_)
1199 return;
1200
davidben54015aa2014-12-02 22:16:231201 const uint8_t* ocsp_response_raw;
davidbeneb5f8ef32014-09-04 14:14:321202 size_t ocsp_response_len;
1203 SSL_get0_ocsp_response(ssl_, &ocsp_response_raw, &ocsp_response_len);
1204 std::string ocsp_response;
1205 if (ocsp_response_len > 0) {
1206 ocsp_response.assign(reinterpret_cast<const char*>(ocsp_response_raw),
1207 ocsp_response_len);
1208 }
1209
davidben54015aa2014-12-02 22:16:231210 const uint8_t* sct_list_raw;
davidbeneb5f8ef32014-09-04 14:14:321211 size_t sct_list_len;
1212 SSL_get0_signed_cert_timestamp_list(ssl_, &sct_list_raw, &sct_list_len);
1213 std::string sct_list;
1214 if (sct_list_len > 0)
1215 sct_list.assign(reinterpret_cast<const char*>(sct_list_raw), sct_list_len);
1216
1217 // Note that this is a completely synchronous operation: The CT Log Verifier
1218 // gets all the data it needs for SCT verification and does not do any
1219 // external communication.
eranm6571b2b2014-12-03 15:53:231220 cert_transparency_verifier_->Verify(
1221 server_cert_verify_result_.verified_cert.get(), ocsp_response, sct_list,
1222 &ct_verify_result_, net_log_);
davidbeneb5f8ef32014-09-04 14:14:321223
eranm6571b2b2014-12-03 15:53:231224 if (!policy_enforcer_) {
1225 server_cert_verify_result_.cert_status &= ~CERT_STATUS_IS_EV;
1226 } else {
1227 if (server_cert_verify_result_.cert_status & CERT_STATUS_IS_EV) {
1228 scoped_refptr<ct::EVCertsWhitelist> ev_whitelist =
1229 SSLConfigService::GetEVCertsWhitelist();
1230 if (!policy_enforcer_->DoesConformToCTEVPolicy(
1231 server_cert_verify_result_.verified_cert.get(),
eranm18a019272014-12-18 08:43:231232 ev_whitelist.get(), ct_verify_result_, net_log_)) {
eranm6571b2b2014-12-03 15:53:231233 // TODO(eranm): Log via the BoundNetLog, see crbug.com/437766
1234 VLOG(1) << "EV certificate for "
1235 << server_cert_verify_result_.verified_cert->subject()
1236 .GetDisplayName()
1237 << " does not conform to CT policy, removing EV status.";
1238 server_cert_verify_result_.cert_status &= ~CERT_STATUS_IS_EV;
1239 }
1240 }
1241 }
davidbeneb5f8ef32014-09-04 14:14:321242}
1243
[email protected]b9b651f2013-11-09 04:32:221244void SSLClientSocketOpenSSL::OnHandshakeIOComplete(int result) {
1245 int rv = DoHandshakeLoop(result);
1246 if (rv != ERR_IO_PENDING) {
1247 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
1248 DoConnectCallback(rv);
1249 }
1250}
1251
1252void SSLClientSocketOpenSSL::OnSendComplete(int result) {
1253 if (next_handshake_state_ == STATE_HANDSHAKE) {
1254 // In handshake phase.
1255 OnHandshakeIOComplete(result);
1256 return;
1257 }
1258
1259 // OnSendComplete may need to call DoPayloadRead while the renegotiation
1260 // handshake is in progress.
1261 int rv_read = ERR_IO_PENDING;
1262 int rv_write = ERR_IO_PENDING;
1263 bool network_moved;
1264 do {
1265 if (user_read_buf_.get())
1266 rv_read = DoPayloadRead();
1267 if (user_write_buf_.get())
1268 rv_write = DoPayloadWrite();
1269 network_moved = DoTransportIO();
1270 } while (rv_read == ERR_IO_PENDING && rv_write == ERR_IO_PENDING &&
1271 (user_read_buf_.get() || user_write_buf_.get()) && network_moved);
1272
1273 // Performing the Read callback may cause |this| to be deleted. If this
1274 // happens, the Write callback should not be invoked. Guard against this by
1275 // holding a WeakPtr to |this| and ensuring it's still valid.
1276 base::WeakPtr<SSLClientSocketOpenSSL> guard(weak_factory_.GetWeakPtr());
1277 if (user_read_buf_.get() && rv_read != ERR_IO_PENDING)
1278 DoReadCallback(rv_read);
1279
1280 if (!guard.get())
1281 return;
1282
1283 if (user_write_buf_.get() && rv_write != ERR_IO_PENDING)
1284 DoWriteCallback(rv_write);
1285}
1286
1287void SSLClientSocketOpenSSL::OnRecvComplete(int result) {
1288 if (next_handshake_state_ == STATE_HANDSHAKE) {
1289 // In handshake phase.
1290 OnHandshakeIOComplete(result);
1291 return;
1292 }
1293
1294 // Network layer received some data, check if client requested to read
1295 // decrypted data.
1296 if (!user_read_buf_.get())
1297 return;
1298
davidben1b133ad2014-10-23 04:23:131299 int rv = DoReadLoop();
[email protected]b9b651f2013-11-09 04:32:221300 if (rv != ERR_IO_PENDING)
1301 DoReadCallback(rv);
1302}
1303
1304int SSLClientSocketOpenSSL::DoHandshakeLoop(int last_io_result) {
1305 int rv = last_io_result;
1306 do {
1307 // Default to STATE_NONE for next state.
1308 // (This is a quirk carried over from the windows
1309 // implementation. It makes reading the logs a bit harder.)
1310 // State handlers can and often do call GotoState just
1311 // to stay in the current state.
1312 State state = next_handshake_state_;
1313 GotoState(STATE_NONE);
1314 switch (state) {
1315 case STATE_HANDSHAKE:
1316 rv = DoHandshake();
1317 break;
davidbenc4212c02015-05-12 22:30:181318 case STATE_HANDSHAKE_COMPLETE:
1319 rv = DoHandshakeComplete(rv);
1320 break;
[email protected]faff9852014-06-21 06:13:461321 case STATE_CHANNEL_ID_LOOKUP:
1322 DCHECK_EQ(OK, rv);
1323 rv = DoChannelIDLookup();
1324 break;
1325 case STATE_CHANNEL_ID_LOOKUP_COMPLETE:
1326 rv = DoChannelIDLookupComplete(rv);
1327 break;
[email protected]b9b651f2013-11-09 04:32:221328 case STATE_VERIFY_CERT:
[email protected]faff9852014-06-21 06:13:461329 DCHECK_EQ(OK, rv);
[email protected]b9b651f2013-11-09 04:32:221330 rv = DoVerifyCert(rv);
1331 break;
1332 case STATE_VERIFY_CERT_COMPLETE:
1333 rv = DoVerifyCertComplete(rv);
1334 break;
1335 case STATE_NONE:
1336 default:
1337 rv = ERR_UNEXPECTED;
1338 NOTREACHED() << "unexpected state" << state;
1339 break;
1340 }
1341
1342 bool network_moved = DoTransportIO();
1343 if (network_moved && next_handshake_state_ == STATE_HANDSHAKE) {
1344 // In general we exit the loop if rv is ERR_IO_PENDING. In this
1345 // special case we keep looping even if rv is ERR_IO_PENDING because
1346 // the transport IO may allow DoHandshake to make progress.
1347 rv = OK; // This causes us to stay in the loop.
1348 }
1349 } while (rv != ERR_IO_PENDING && next_handshake_state_ != STATE_NONE);
1350 return rv;
1351}
1352
davidben1b133ad2014-10-23 04:23:131353int SSLClientSocketOpenSSL::DoReadLoop() {
[email protected]b9b651f2013-11-09 04:32:221354 bool network_moved;
1355 int rv;
1356 do {
1357 rv = DoPayloadRead();
1358 network_moved = DoTransportIO();
1359 } while (rv == ERR_IO_PENDING && network_moved);
1360
1361 return rv;
1362}
1363
davidben1b133ad2014-10-23 04:23:131364int SSLClientSocketOpenSSL::DoWriteLoop() {
[email protected]b9b651f2013-11-09 04:32:221365 bool network_moved;
1366 int rv;
1367 do {
1368 rv = DoPayloadWrite();
1369 network_moved = DoTransportIO();
1370 } while (rv == ERR_IO_PENDING && network_moved);
1371
1372 return rv;
1373}
1374
1375int SSLClientSocketOpenSSL::DoPayloadRead() {
1376 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1377
davidben7e555daf2015-03-25 17:03:291378 DCHECK_LT(0, user_read_buf_len_);
1379 DCHECK(user_read_buf_.get());
1380
[email protected]b9b651f2013-11-09 04:32:221381 int rv;
1382 if (pending_read_error_ != kNoPendingReadResult) {
1383 rv = pending_read_error_;
1384 pending_read_error_ = kNoPendingReadResult;
1385 if (rv == 0) {
1386 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED,
1387 rv, user_read_buf_->data());
davidbenb8c23212014-10-28 00:12:161388 } else {
1389 net_log_.AddEvent(
1390 NetLog::TYPE_SSL_READ_ERROR,
1391 CreateNetLogOpenSSLErrorCallback(rv, pending_read_ssl_error_,
1392 pending_read_error_info_));
[email protected]b9b651f2013-11-09 04:32:221393 }
davidbenb8c23212014-10-28 00:12:161394 pending_read_ssl_error_ = SSL_ERROR_NONE;
1395 pending_read_error_info_ = OpenSSLErrorInfo();
[email protected]b9b651f2013-11-09 04:32:221396 return rv;
1397 }
1398
1399 int total_bytes_read = 0;
davidben7e555daf2015-03-25 17:03:291400 int ssl_ret;
[email protected]b9b651f2013-11-09 04:32:221401 do {
davidben7e555daf2015-03-25 17:03:291402 ssl_ret = SSL_read(ssl_, user_read_buf_->data() + total_bytes_read,
1403 user_read_buf_len_ - total_bytes_read);
1404 if (ssl_ret > 0)
1405 total_bytes_read += ssl_ret;
1406 } while (total_bytes_read < user_read_buf_len_ && ssl_ret > 0);
[email protected]b9b651f2013-11-09 04:32:221407
davidben7e555daf2015-03-25 17:03:291408 // Although only the final SSL_read call may have failed, the failure needs to
1409 // processed immediately, while the information still available in OpenSSL's
1410 // error queue.
davidbenced4aa9b2015-05-12 21:22:351411 if (ssl_ret <= 0) {
davidben7e555daf2015-03-25 17:03:291412 // A zero return from SSL_read may mean any of:
1413 // - The underlying BIO_read returned 0.
1414 // - The peer sent a close_notify.
1415 // - Any arbitrary error. https://crbug.com/466303
[email protected]b9b651f2013-11-09 04:32:221416 //
davidben7e555daf2015-03-25 17:03:291417 // TransportReadComplete converts the first to an ERR_CONNECTION_CLOSED
1418 // error, so it does not occur. The second and third are distinguished by
1419 // SSL_ERROR_ZERO_RETURN.
1420 pending_read_ssl_error_ = SSL_get_error(ssl_, ssl_ret);
1421 if (pending_read_ssl_error_ == SSL_ERROR_ZERO_RETURN) {
1422 pending_read_error_ = 0;
davidbenced4aa9b2015-05-12 21:22:351423 } else if (pending_read_ssl_error_ == SSL_ERROR_WANT_X509_LOOKUP &&
1424 !ssl_config_.send_client_cert) {
1425 pending_read_error_ = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
davidben7e555daf2015-03-25 17:03:291426 } else {
1427 pending_read_error_ = MapOpenSSLErrorWithDetails(
1428 pending_read_ssl_error_, err_tracer, &pending_read_error_info_);
[email protected]b9b651f2013-11-09 04:32:221429 }
1430
davidben7e555daf2015-03-25 17:03:291431 // Many servers do not reliably send a close_notify alert when shutting down
1432 // a connection, and instead terminate the TCP connection. This is reported
1433 // as ERR_CONNECTION_CLOSED. Because of this, map the unclean shutdown to a
1434 // graceful EOF, instead of treating it as an error as it should be.
1435 if (pending_read_error_ == ERR_CONNECTION_CLOSED)
1436 pending_read_error_ = 0;
1437 }
davidbenbe6ce7ec2014-10-20 19:15:561438
davidben7e555daf2015-03-25 17:03:291439 if (total_bytes_read > 0) {
1440 // Return any bytes read to the caller. The error will be deferred to the
1441 // next call of DoPayloadRead.
1442 rv = total_bytes_read;
davidbenbe6ce7ec2014-10-20 19:15:561443
davidben7e555daf2015-03-25 17:03:291444 // Do not treat insufficient data as an error to return in the next call to
1445 // DoPayloadRead() - instead, let the call fall through to check SSL_read()
1446 // again. This is because DoTransportIO() may complete in between the next
1447 // call to DoPayloadRead(), and thus it is important to check SSL_read() on
1448 // subsequent invocations to see if a complete record may now be read.
1449 if (pending_read_error_ == ERR_IO_PENDING)
1450 pending_read_error_ = kNoPendingReadResult;
1451 } else {
1452 // No bytes were returned. Return the pending read error immediately.
1453 DCHECK_NE(kNoPendingReadResult, pending_read_error_);
1454 rv = pending_read_error_;
1455 pending_read_error_ = kNoPendingReadResult;
[email protected]b9b651f2013-11-09 04:32:221456 }
1457
1458 if (rv >= 0) {
1459 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, rv,
1460 user_read_buf_->data());
davidbenb8c23212014-10-28 00:12:161461 } else if (rv != ERR_IO_PENDING) {
1462 net_log_.AddEvent(
1463 NetLog::TYPE_SSL_READ_ERROR,
1464 CreateNetLogOpenSSLErrorCallback(rv, pending_read_ssl_error_,
1465 pending_read_error_info_));
1466 pending_read_ssl_error_ = SSL_ERROR_NONE;
1467 pending_read_error_info_ = OpenSSLErrorInfo();
[email protected]b9b651f2013-11-09 04:32:221468 }
1469 return rv;
1470}
1471
1472int SSLClientSocketOpenSSL::DoPayloadWrite() {
1473 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1474 int rv = SSL_write(ssl_, user_write_buf_->data(), user_write_buf_len_);
rsleevif020edc2015-03-16 19:31:241475
[email protected]b9b651f2013-11-09 04:32:221476 if (rv >= 0) {
1477 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_SENT, rv,
1478 user_write_buf_->data());
1479 return rv;
1480 }
1481
davidbenb8c23212014-10-28 00:12:161482 int ssl_error = SSL_get_error(ssl_, rv);
1483 OpenSSLErrorInfo error_info;
1484 int net_error = MapOpenSSLErrorWithDetails(ssl_error, err_tracer,
1485 &error_info);
1486
1487 if (net_error != ERR_IO_PENDING) {
1488 net_log_.AddEvent(
1489 NetLog::TYPE_SSL_WRITE_ERROR,
1490 CreateNetLogOpenSSLErrorCallback(net_error, ssl_error, error_info));
1491 }
1492 return net_error;
[email protected]b9b651f2013-11-09 04:32:221493}
1494
1495int SSLClientSocketOpenSSL::BufferSend(void) {
1496 if (transport_send_busy_)
1497 return ERR_IO_PENDING;
1498
haavardm2d92e722014-12-19 13:45:441499 size_t buffer_read_offset;
1500 uint8_t* read_buf;
1501 size_t max_read;
1502 int status = BIO_zero_copy_get_read_buf(transport_bio_, &read_buf,
1503 &buffer_read_offset, &max_read);
1504 DCHECK_EQ(status, 1); // Should never fail.
1505 if (!max_read)
1506 return 0; // Nothing pending in the OpenSSL write BIO.
1507 CHECK_EQ(read_buf, reinterpret_cast<uint8_t*>(send_buffer_->StartOfBuffer()));
1508 CHECK_LT(buffer_read_offset, static_cast<size_t>(send_buffer_->capacity()));
1509 send_buffer_->set_offset(buffer_read_offset);
[email protected]b9b651f2013-11-09 04:32:221510
1511 int rv = transport_->socket()->Write(
haavardm2d92e722014-12-19 13:45:441512 send_buffer_.get(), max_read,
[email protected]b9b651f2013-11-09 04:32:221513 base::Bind(&SSLClientSocketOpenSSL::BufferSendComplete,
1514 base::Unretained(this)));
1515 if (rv == ERR_IO_PENDING) {
1516 transport_send_busy_ = true;
1517 } else {
1518 TransportWriteComplete(rv);
1519 }
1520 return rv;
1521}
1522
1523int SSLClientSocketOpenSSL::BufferRecv(void) {
1524 if (transport_recv_busy_)
1525 return ERR_IO_PENDING;
1526
1527 // Determine how much was requested from |transport_bio_| that was not
1528 // actually available.
1529 size_t requested = BIO_ctrl_get_read_request(transport_bio_);
1530 if (requested == 0) {
1531 // This is not a perfect match of error codes, as no operation is
1532 // actually pending. However, returning 0 would be interpreted as
1533 // a possible sign of EOF, which is also an inappropriate match.
1534 return ERR_IO_PENDING;
1535 }
1536
1537 // Known Issue: While only reading |requested| data is the more correct
1538 // implementation, it has the downside of resulting in frequent reads:
1539 // One read for the SSL record header (~5 bytes) and one read for the SSL
1540 // record body. Rather than issuing these reads to the underlying socket
1541 // (and constantly allocating new IOBuffers), a single Read() request to
1542 // fill |transport_bio_| is issued. As long as an SSL client socket cannot
1543 // be gracefully shutdown (via SSL close alerts) and re-used for non-SSL
1544 // traffic, this over-subscribed Read()ing will not cause issues.
haavardm2d92e722014-12-19 13:45:441545
1546 size_t buffer_write_offset;
1547 uint8_t* write_buf;
1548 size_t max_write;
1549 int status = BIO_zero_copy_get_write_buf(transport_bio_, &write_buf,
1550 &buffer_write_offset, &max_write);
1551 DCHECK_EQ(status, 1); // Should never fail.
[email protected]b9b651f2013-11-09 04:32:221552 if (!max_write)
1553 return ERR_IO_PENDING;
1554
haavardm2d92e722014-12-19 13:45:441555 CHECK_EQ(write_buf,
1556 reinterpret_cast<uint8_t*>(recv_buffer_->StartOfBuffer()));
1557 CHECK_LT(buffer_write_offset, static_cast<size_t>(recv_buffer_->capacity()));
1558
1559 recv_buffer_->set_offset(buffer_write_offset);
[email protected]b9b651f2013-11-09 04:32:221560 int rv = transport_->socket()->Read(
1561 recv_buffer_.get(),
1562 max_write,
1563 base::Bind(&SSLClientSocketOpenSSL::BufferRecvComplete,
1564 base::Unretained(this)));
1565 if (rv == ERR_IO_PENDING) {
1566 transport_recv_busy_ = true;
1567 } else {
[email protected]3e5c6922014-02-06 02:42:161568 rv = TransportReadComplete(rv);
[email protected]b9b651f2013-11-09 04:32:221569 }
1570 return rv;
1571}
1572
1573void SSLClientSocketOpenSSL::BufferSendComplete(int result) {
[email protected]b9b651f2013-11-09 04:32:221574 TransportWriteComplete(result);
1575 OnSendComplete(result);
1576}
1577
1578void SSLClientSocketOpenSSL::BufferRecvComplete(int result) {
[email protected]3e5c6922014-02-06 02:42:161579 result = TransportReadComplete(result);
[email protected]b9b651f2013-11-09 04:32:221580 OnRecvComplete(result);
1581}
1582
1583void SSLClientSocketOpenSSL::TransportWriteComplete(int result) {
1584 DCHECK(ERR_IO_PENDING != result);
haavardm2d92e722014-12-19 13:45:441585 int bytes_written = 0;
[email protected]b9b651f2013-11-09 04:32:221586 if (result < 0) {
[email protected]5aea79182014-07-14 20:43:411587 // Record the error. Save it to be reported in a future read or write on
1588 // transport_bio_'s peer.
[email protected]3e5c6922014-02-06 02:42:161589 transport_write_error_ = result;
[email protected]b9b651f2013-11-09 04:32:221590 } else {
haavardm2d92e722014-12-19 13:45:441591 bytes_written = result;
[email protected]b9b651f2013-11-09 04:32:221592 }
haavardm2d92e722014-12-19 13:45:441593 DCHECK_GE(send_buffer_->RemainingCapacity(), bytes_written);
1594 int ret = BIO_zero_copy_get_read_buf_done(transport_bio_, bytes_written);
1595 DCHECK_EQ(1, ret);
1596 transport_send_busy_ = false;
[email protected]b9b651f2013-11-09 04:32:221597}
1598
[email protected]3e5c6922014-02-06 02:42:161599int SSLClientSocketOpenSSL::TransportReadComplete(int result) {
[email protected]b9b651f2013-11-09 04:32:221600 DCHECK(ERR_IO_PENDING != result);
[email protected]5aea79182014-07-14 20:43:411601 // If an EOF, canonicalize to ERR_CONNECTION_CLOSED here so MapOpenSSLError
1602 // does not report success.
1603 if (result == 0)
1604 result = ERR_CONNECTION_CLOSED;
haavardm2d92e722014-12-19 13:45:441605 int bytes_read = 0;
[email protected]5aea79182014-07-14 20:43:411606 if (result < 0) {
[email protected]b9b651f2013-11-09 04:32:221607 DVLOG(1) << "TransportReadComplete result " << result;
[email protected]5aea79182014-07-14 20:43:411608 // Received an error. Save it to be reported in a future read on
1609 // transport_bio_'s peer.
1610 transport_read_error_ = result;
[email protected]b9b651f2013-11-09 04:32:221611 } else {
haavardm2d92e722014-12-19 13:45:441612 bytes_read = result;
[email protected]b9b651f2013-11-09 04:32:221613 }
haavardm2d92e722014-12-19 13:45:441614 DCHECK_GE(recv_buffer_->RemainingCapacity(), bytes_read);
1615 int ret = BIO_zero_copy_get_write_buf_done(transport_bio_, bytes_read);
1616 DCHECK_EQ(1, ret);
[email protected]b9b651f2013-11-09 04:32:221617 transport_recv_busy_ = false;
[email protected]3e5c6922014-02-06 02:42:161618 return result;
[email protected]b9b651f2013-11-09 04:32:221619}
1620
[email protected]82c59022014-08-15 09:38:271621int SSLClientSocketOpenSSL::ClientCertRequestCallback(SSL* ssl) {
[email protected]5ac981e182010-12-06 17:56:271622 DVLOG(3) << "OpenSSL ClientCertRequestCallback called";
1623 DCHECK(ssl == ssl_);
[email protected]82c59022014-08-15 09:38:271624
davidbenaf42cbe2014-11-13 03:27:461625 net_log_.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED);
1626
[email protected]82c59022014-08-15 09:38:271627 // Clear any currently configured certificates.
1628 SSL_certs_clear(ssl_);
[email protected]97a854f2014-07-29 07:51:361629
1630#if defined(OS_IOS)
1631 // TODO(droger): Support client auth on iOS. See http://crbug.com/145954).
1632 LOG(WARNING) << "Client auth is not supported";
1633#else // !defined(OS_IOS)
[email protected]5ac981e182010-12-06 17:56:271634 if (!ssl_config_.send_client_cert) {
[email protected]515adc22013-01-09 16:01:231635 // First pass: we know that a client certificate is needed, but we do not
1636 // have one at hand.
[email protected]515adc22013-01-09 16:01:231637 STACK_OF(X509_NAME) *authorities = SSL_get_client_CA_list(ssl);
[email protected]edfd0f42014-07-22 18:20:371638 for (size_t i = 0; i < sk_X509_NAME_num(authorities); i++) {
[email protected]515adc22013-01-09 16:01:231639 X509_NAME *ca_name = (X509_NAME *)sk_X509_NAME_value(authorities, i);
1640 unsigned char* str = NULL;
1641 int length = i2d_X509_NAME(ca_name, &str);
1642 cert_authorities_.push_back(std::string(
1643 reinterpret_cast<const char*>(str),
1644 static_cast<size_t>(length)));
1645 OPENSSL_free(str);
1646 }
1647
[email protected]c0787702014-05-20 21:51:441648 const unsigned char* client_cert_types;
[email protected]e7e883e2014-07-25 06:03:081649 size_t num_client_cert_types =
1650 SSL_get0_certificate_types(ssl, &client_cert_types);
[email protected]c0787702014-05-20 21:51:441651 for (size_t i = 0; i < num_client_cert_types; i++) {
1652 cert_key_types_.push_back(
1653 static_cast<SSLClientCertType>(client_cert_types[i]));
1654 }
1655
davidbenced4aa9b2015-05-12 21:22:351656 // Suspends handshake. SSL_get_error will return SSL_ERROR_WANT_X509_LOOKUP.
1657 return -1;
[email protected]5ac981e182010-12-06 17:56:271658 }
1659
1660 // Second pass: a client certificate should have been selected.
[email protected]13914c92013-06-13 22:42:421661 if (ssl_config_.client_cert.get()) {
[email protected]6bad5052014-07-12 01:25:131662 ScopedX509 leaf_x509 =
1663 OSCertHandleToOpenSSL(ssl_config_.client_cert->os_cert_handle());
1664 if (!leaf_x509) {
1665 LOG(WARNING) << "Failed to import certificate";
1666 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT);
1667 return -1;
1668 }
1669
[email protected]82c59022014-08-15 09:38:271670 ScopedX509Stack chain = OSCertHandlesToOpenSSL(
1671 ssl_config_.client_cert->GetIntermediateCertificates());
1672 if (!chain) {
1673 LOG(WARNING) << "Failed to import intermediate certificates";
1674 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT);
1675 return -1;
1676 }
1677
[email protected]97a854f2014-07-29 07:51:361678 // TODO(davidben): With Linux client auth support, this should be
1679 // conditioned on OS_ANDROID and then, with https://crbug.com/394131,
1680 // removed altogether. OpenSSLClientKeyStore is mostly an artifact of the
1681 // net/ client auth API lacking a private key handle.
[email protected]c0787702014-05-20 21:51:441682#if defined(USE_OPENSSL_CERTS)
[email protected]97a854f2014-07-29 07:51:361683 crypto::ScopedEVP_PKEY privkey =
1684 OpenSSLClientKeyStore::GetInstance()->FetchClientCertPrivateKey(
1685 ssl_config_.client_cert.get());
1686#else // !defined(USE_OPENSSL_CERTS)
1687 crypto::ScopedEVP_PKEY privkey =
1688 FetchClientCertPrivateKey(ssl_config_.client_cert.get());
1689#endif // defined(USE_OPENSSL_CERTS)
1690 if (!privkey) {
[email protected]6bad5052014-07-12 01:25:131691 // Could not find the private key. Fail the handshake and surface an
1692 // appropriate error to the caller.
1693 LOG(WARNING) << "Client cert found without private key";
1694 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY);
1695 return -1;
[email protected]0c6523f2010-12-10 10:56:241696 }
[email protected]6bad5052014-07-12 01:25:131697
[email protected]82c59022014-08-15 09:38:271698 if (!SSL_use_certificate(ssl_, leaf_x509.get()) ||
1699 !SSL_use_PrivateKey(ssl_, privkey.get()) ||
1700 !SSL_set1_chain(ssl_, chain.get())) {
1701 LOG(WARNING) << "Failed to set client certificate";
1702 return -1;
1703 }
davidbenaf42cbe2014-11-13 03:27:461704
1705 int cert_count = 1 + sk_X509_num(chain.get());
1706 net_log_.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED,
1707 NetLog::IntegerCallback("cert_count", cert_count));
[email protected]6bad5052014-07-12 01:25:131708 return 1;
[email protected]c0787702014-05-20 21:51:441709 }
[email protected]97a854f2014-07-29 07:51:361710#endif // defined(OS_IOS)
[email protected]5ac981e182010-12-06 17:56:271711
1712 // Send no client certificate.
davidbenaf42cbe2014-11-13 03:27:461713 net_log_.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED,
1714 NetLog::IntegerCallback("cert_count", 0));
[email protected]82c59022014-08-15 09:38:271715 return 1;
[email protected]5ac981e182010-12-06 17:56:271716}
1717
[email protected]b051cdb62014-02-28 02:20:161718int SSLClientSocketOpenSSL::CertVerifyCallback(X509_STORE_CTX* store_ctx) {
[email protected]64b5c892014-08-08 09:39:261719 if (!completed_connect_) {
[email protected]b051cdb62014-02-28 02:20:161720 // If the first handshake hasn't completed then we accept any certificates
1721 // because we verify after the handshake.
1722 return 1;
1723 }
1724
davidben30798ed82014-09-19 19:28:201725 // Disallow the server certificate to change in a renegotiation.
1726 if (server_cert_chain_->empty()) {
[email protected]76e85392014-03-20 17:54:141727 LOG(ERROR) << "Received invalid certificate chain between handshakes";
davidben30798ed82014-09-19 19:28:201728 return 0;
1729 }
1730 base::StringPiece old_der, new_der;
1731 if (store_ctx->cert == NULL ||
1732 !x509_util::GetDER(server_cert_chain_->Get(0), &old_der) ||
1733 !x509_util::GetDER(store_ctx->cert, &new_der)) {
1734 LOG(ERROR) << "Failed to encode certificates";
1735 return 0;
1736 }
1737 if (old_der != new_der) {
[email protected]76e85392014-03-20 17:54:141738 LOG(ERROR) << "Server certificate changed between handshakes";
davidben30798ed82014-09-19 19:28:201739 return 0;
1740 }
1741
1742 return 1;
[email protected]b051cdb62014-02-28 02:20:161743}
1744
[email protected]ae7c9f42011-11-21 11:41:161745// SelectNextProtoCallback is called by OpenSSL during the handshake. If the
1746// server supports NPN, selects a protocol from the list that the server
1747// provides. According to third_party/openssl/openssl/ssl/ssl_lib.c, the
1748// callback can assume that |in| is syntactically valid.
[email protected]ea4a1c6a2010-12-09 13:33:281749int SSLClientSocketOpenSSL::SelectNextProtoCallback(unsigned char** out,
1750 unsigned char* outlen,
1751 const unsigned char* in,
1752 unsigned int inlen) {
[email protected]ea4a1c6a2010-12-09 13:33:281753 if (ssl_config_.next_protos.empty()) {
[email protected]168a8412012-06-14 05:05:491754 *out = reinterpret_cast<uint8*>(
1755 const_cast<char*>(kDefaultSupportedNPNProtocol));
1756 *outlen = arraysize(kDefaultSupportedNPNProtocol) - 1;
1757 npn_status_ = kNextProtoUnsupported;
[email protected]ea4a1c6a2010-12-09 13:33:281758 return SSL_TLSEXT_ERR_OK;
1759 }
1760
[email protected]ae7c9f42011-11-21 11:41:161761 // Assume there's no overlap between our protocols and the server's list.
[email protected]168a8412012-06-14 05:05:491762 npn_status_ = kNextProtoNoOverlap;
[email protected]ae7c9f42011-11-21 11:41:161763
1764 // For each protocol in server preference order, see if we support it.
1765 for (unsigned int i = 0; i < inlen; i += in[i] + 1) {
bnc0d23cf42014-12-11 14:09:461766 for (NextProto next_proto : ssl_config_.next_protos) {
1767 const std::string proto = NextProtoToString(next_proto);
1768 if (in[i] == proto.size() &&
1769 memcmp(&in[i + 1], proto.data(), in[i]) == 0) {
[email protected]168a8412012-06-14 05:05:491770 // We found a match.
[email protected]ae7c9f42011-11-21 11:41:161771 *out = const_cast<unsigned char*>(in) + i + 1;
1772 *outlen = in[i];
[email protected]168a8412012-06-14 05:05:491773 npn_status_ = kNextProtoNegotiated;
[email protected]ae7c9f42011-11-21 11:41:161774 break;
1775 }
1776 }
[email protected]168a8412012-06-14 05:05:491777 if (npn_status_ == kNextProtoNegotiated)
[email protected]ae7c9f42011-11-21 11:41:161778 break;
1779 }
[email protected]ea4a1c6a2010-12-09 13:33:281780
[email protected]168a8412012-06-14 05:05:491781 // If we didn't find a protocol, we select the first one from our list.
1782 if (npn_status_ == kNextProtoNoOverlap) {
bnc67da3de2015-01-15 21:02:261783 // NextProtoToString returns a pointer to a static string.
1784 const char* proto = NextProtoToString(ssl_config_.next_protos[0]);
1785 *out = reinterpret_cast<unsigned char*>(const_cast<char*>(proto));
1786 *outlen = strlen(proto);
[email protected]168a8412012-06-14 05:05:491787 }
1788
[email protected]ea4a1c6a2010-12-09 13:33:281789 npn_proto_.assign(reinterpret_cast<const char*>(*out), *outlen);
[email protected]32e1dee2010-12-09 18:36:241790 DVLOG(2) << "next protocol: '" << npn_proto_ << "' status: " << npn_status_;
bnc0d28ea52014-10-13 15:15:381791 set_negotiation_extension(kExtensionNPN);
[email protected]ea4a1c6a2010-12-09 13:33:281792 return SSL_TLSEXT_ERR_OK;
1793}
1794
[email protected]5aea79182014-07-14 20:43:411795long SSLClientSocketOpenSSL::MaybeReplayTransportError(
1796 BIO *bio,
1797 int cmd,
1798 const char *argp, int argi, long argl,
1799 long retvalue) {
1800 if (cmd == (BIO_CB_READ|BIO_CB_RETURN) && retvalue <= 0) {
1801 // If there is no more data in the buffer, report any pending errors that
1802 // were observed. Note that both the readbuf and the writebuf are checked
1803 // for errors, since the application may have encountered a socket error
1804 // while writing that would otherwise not be reported until the application
1805 // attempted to write again - which it may never do. See
1806 // https://crbug.com/249848.
1807 if (transport_read_error_ != OK) {
1808 OpenSSLPutNetError(FROM_HERE, transport_read_error_);
1809 return -1;
1810 }
1811 if (transport_write_error_ != OK) {
1812 OpenSSLPutNetError(FROM_HERE, transport_write_error_);
1813 return -1;
1814 }
1815 } else if (cmd == BIO_CB_WRITE) {
1816 // Because of the write buffer, this reports a failure from the previous
1817 // write payload. If the current payload fails to write, the error will be
1818 // reported in a future write or read to |bio|.
1819 if (transport_write_error_ != OK) {
1820 OpenSSLPutNetError(FROM_HERE, transport_write_error_);
1821 return -1;
1822 }
1823 }
1824 return retvalue;
1825}
1826
1827// static
1828long SSLClientSocketOpenSSL::BIOCallback(
1829 BIO *bio,
1830 int cmd,
1831 const char *argp, int argi, long argl,
1832 long retvalue) {
1833 SSLClientSocketOpenSSL* socket = reinterpret_cast<SSLClientSocketOpenSSL*>(
1834 BIO_get_callback_arg(bio));
1835 CHECK(socket);
1836 return socket->MaybeReplayTransportError(
1837 bio, cmd, argp, argi, argl, retvalue);
1838}
1839
davidbendafe4e52015-04-08 22:53:521840void SSLClientSocketOpenSSL::MaybeCacheSession() {
1841 // Only cache the session once both the handshake has completed and the
1842 // certificate has been verified.
1843 if (!handshake_completed_ || !certificate_verified_ ||
1844 SSL_session_reused(ssl_)) {
1845 return;
1846 }
1847
1848 SSLContext::GetInstance()->session_cache()->Insert(GetSessionCacheKey(),
1849 SSL_get_session(ssl_));
1850}
1851
1852void SSLClientSocketOpenSSL::InfoCallback(int type, int val) {
1853 // Note that SSL_CB_HANDSHAKE_DONE may be signaled multiple times if the
1854 // socket renegotiates.
1855 if (type != SSL_CB_HANDSHAKE_DONE || handshake_completed_)
1856 return;
1857
1858 handshake_completed_ = true;
1859 MaybeCacheSession();
1860}
1861
davidbeneb5f8ef32014-09-04 14:14:321862void SSLClientSocketOpenSSL::AddSCTInfoToSSLInfo(SSLInfo* ssl_info) const {
1863 for (ct::SCTList::const_iterator iter =
1864 ct_verify_result_.verified_scts.begin();
1865 iter != ct_verify_result_.verified_scts.end(); ++iter) {
1866 ssl_info->signed_certificate_timestamps.push_back(
1867 SignedCertificateTimestampAndStatus(*iter, ct::SCT_STATUS_OK));
1868 }
1869 for (ct::SCTList::const_iterator iter =
1870 ct_verify_result_.invalid_scts.begin();
1871 iter != ct_verify_result_.invalid_scts.end(); ++iter) {
1872 ssl_info->signed_certificate_timestamps.push_back(
1873 SignedCertificateTimestampAndStatus(*iter, ct::SCT_STATUS_INVALID));
1874 }
1875 for (ct::SCTList::const_iterator iter =
1876 ct_verify_result_.unknown_logs_scts.begin();
1877 iter != ct_verify_result_.unknown_logs_scts.end(); ++iter) {
1878 ssl_info->signed_certificate_timestamps.push_back(
1879 SignedCertificateTimestampAndStatus(*iter,
1880 ct::SCT_STATUS_LOG_UNKNOWN));
1881 }
1882}
1883
rsleevif020edc2015-03-16 19:31:241884std::string SSLClientSocketOpenSSL::GetSessionCacheKey() const {
1885 std::string result = host_and_port_.ToString();
1886 result.append("/");
1887 result.append(ssl_session_cache_shard_);
1888
1889 // Shard the session cache based on maximum protocol version. This causes
1890 // fallback connections to use a separate session cache.
1891 result.append("/");
1892 switch (ssl_config_.version_max) {
rsleevif020edc2015-03-16 19:31:241893 case SSL_PROTOCOL_VERSION_TLS1:
1894 result.append("tls1");
1895 break;
1896 case SSL_PROTOCOL_VERSION_TLS1_1:
1897 result.append("tls1.1");
1898 break;
1899 case SSL_PROTOCOL_VERSION_TLS1_2:
1900 result.append("tls1.2");
1901 break;
1902 default:
1903 NOTREACHED();
1904 }
1905
davidbena4c9d062015-04-03 22:34:251906 result.append("/");
1907 if (ssl_config_.enable_deprecated_cipher_suites)
1908 result.append("deprecated");
1909
rsleevif020edc2015-03-16 19:31:241910 return result;
1911}
1912
davidben421116c2015-05-12 19:56:511913bool SSLClientSocketOpenSSL::IsRenegotiationAllowed() const {
1914 if (npn_status_ == kNextProtoUnsupported)
1915 return ssl_config_.renego_allowed_default;
1916
1917 NextProto next_proto = NextProtoFromString(npn_proto_);
1918 for (NextProto allowed : ssl_config_.renego_allowed_for_protos) {
1919 if (next_proto == allowed)
1920 return true;
1921 }
1922 return false;
1923}
1924
[email protected]7f38da8a2014-03-17 16:44:261925scoped_refptr<X509Certificate>
1926SSLClientSocketOpenSSL::GetUnverifiedServerCertificateChain() const {
1927 return server_cert_;
1928}
1929
[email protected]7e5dd49f2010-12-08 18:33:491930} // namespace net