blob: 6433b2311c8e4a6000ac4647708447243931f652 [file] [log] [blame]
[email protected]013c17c2012-01-21 19:09:011// Copyright (c) 2012 The Chromium Authors. All rights reserved.
[email protected]d518cd92010-09-29 12:27:442// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5// OpenSSL binding for SSLClientSocket. The class layout and general principle
6// of operation is derived from SSLClientSocketNSS.
7
8#include "net/socket/ssl_client_socket_openssl.h"
9
[email protected]edfd0f42014-07-22 18:20:3710#include <errno.h>
davidben018aad62014-09-12 02:25:1911#include <openssl/bio.h>
[email protected]d518cd92010-09-29 12:27:4412#include <openssl/err.h>
[email protected]536fd0b2013-03-14 17:41:5713#include <openssl/ssl.h>
[email protected]d518cd92010-09-29 12:27:4414
[email protected]0f7804ec2011-10-07 20:04:1815#include "base/bind.h"
[email protected]f2da6ac2013-02-04 08:22:5316#include "base/callback_helpers.h"
davidben018aad62014-09-12 02:25:1917#include "base/environment.h"
[email protected]3b63f8f42011-03-28 01:54:1518#include "base/memory/singleton.h"
[email protected]835d7c82010-10-14 04:38:3819#include "base/metrics/histogram.h"
vadimtb2a77c762014-11-21 19:49:2220#include "base/profiler/scoped_tracker.h"
davidben018aad62014-09-12 02:25:1921#include "base/strings/string_piece.h"
[email protected]20305ec2011-01-21 04:55:5222#include "base/synchronization/lock.h"
[email protected]ee0f2aa82013-10-25 11:59:2623#include "crypto/ec_private_key.h"
[email protected]4b559b4d2011-04-14 17:37:1424#include "crypto/openssl_util.h"
[email protected]cd9b75b2014-07-10 04:39:3825#include "crypto/scoped_openssl_types.h"
[email protected]d518cd92010-09-29 12:27:4426#include "net/base/net_errors.h"
eranm6571b2b2014-12-03 15:53:2327#include "net/cert/cert_policy_enforcer.h"
[email protected]6e7845ae2013-03-29 21:48:1128#include "net/cert/cert_verifier.h"
eranmefbd3132014-10-28 16:35:1629#include "net/cert/ct_ev_whitelist.h"
davidbeneb5f8ef32014-09-04 14:14:3230#include "net/cert/ct_verifier.h"
[email protected]6e7845ae2013-03-29 21:48:1131#include "net/cert/single_request_cert_verifier.h"
32#include "net/cert/x509_certificate_net_log_param.h"
davidben30798ed82014-09-19 19:28:2033#include "net/cert/x509_util_openssl.h"
[email protected]8bd4e7a2014-08-09 14:49:1734#include "net/http/transport_security_state.h"
[email protected]1279de12013-12-03 15:13:3235#include "net/socket/ssl_session_cache_openssl.h"
[email protected]536fd0b2013-03-14 17:41:5736#include "net/ssl/ssl_cert_request_info.h"
37#include "net/ssl/ssl_connection_status_flags.h"
38#include "net/ssl/ssl_info.h"
[email protected]d518cd92010-09-29 12:27:4439
davidben8ecc3072014-09-03 23:19:0940#if defined(OS_WIN)
41#include "base/win/windows_version.h"
42#endif
43
[email protected]97a854f2014-07-29 07:51:3644#if defined(USE_OPENSSL_CERTS)
45#include "net/ssl/openssl_client_key_store.h"
46#else
47#include "net/ssl/openssl_platform_key.h"
48#endif
49
[email protected]d518cd92010-09-29 12:27:4450namespace net {
51
52namespace {
53
54// Enable this to see logging for state machine state transitions.
55#if 0
[email protected]3b112772010-10-04 10:54:4956#define GotoState(s) do { DVLOG(2) << (void *)this << " " << __FUNCTION__ << \
[email protected]d518cd92010-09-29 12:27:4457 " jump to state " << s; \
58 next_handshake_state_ = s; } while (0)
59#else
60#define GotoState(s) next_handshake_state_ = s
61#endif
62
[email protected]4b768562013-02-16 04:10:0763// This constant can be any non-negative/non-zero value (eg: it does not
64// overlap with any value of the net::Error range, including net::OK).
65const int kNoPendingReadResult = 1;
66
[email protected]168a8412012-06-14 05:05:4967// If a client doesn't have a list of protocols that it supports, but
68// the server supports NPN, choosing "http/1.1" is the best answer.
69const char kDefaultSupportedNPNProtocol[] = "http/1.1";
70
[email protected]82c59022014-08-15 09:38:2771void FreeX509Stack(STACK_OF(X509)* ptr) {
72 sk_X509_pop_free(ptr, X509_free);
73}
74
[email protected]6bad5052014-07-12 01:25:1375typedef crypto::ScopedOpenSSL<X509, X509_free>::Type ScopedX509;
[email protected]82c59022014-08-15 09:38:2776typedef crypto::ScopedOpenSSL<STACK_OF(X509), FreeX509Stack>::Type
77 ScopedX509Stack;
[email protected]6bad5052014-07-12 01:25:1378
[email protected]89038152012-09-07 06:30:1779#if OPENSSL_VERSION_NUMBER < 0x1000103fL
80// This method doesn't seem to have made it into the OpenSSL headers.
[email protected]109805a2010-12-07 18:17:0681unsigned long SSL_CIPHER_get_id(const SSL_CIPHER* cipher) { return cipher->id; }
[email protected]89038152012-09-07 06:30:1782#endif
[email protected]109805a2010-12-07 18:17:0683
84// Used for encoding the |connection_status| field of an SSLInfo object.
pkasting6b68a162014-12-01 22:10:2985int EncodeSSLConnectionStatus(uint16 cipher_suite,
[email protected]109805a2010-12-07 18:17:0686 int compression,
87 int version) {
pkasting6b68a162014-12-01 22:10:2988 return cipher_suite |
[email protected]109805a2010-12-07 18:17:0689 ((compression & SSL_CONNECTION_COMPRESSION_MASK) <<
90 SSL_CONNECTION_COMPRESSION_SHIFT) |
91 ((version & SSL_CONNECTION_VERSION_MASK) <<
92 SSL_CONNECTION_VERSION_SHIFT);
93}
94
95// Returns the net SSL version number (see ssl_connection_status_flags.h) for
96// this SSL connection.
97int GetNetSSLVersion(SSL* ssl) {
[email protected]7e5dd49f2010-12-08 18:33:4998 switch (SSL_version(ssl)) {
[email protected]109805a2010-12-07 18:17:0699 case SSL2_VERSION:
100 return SSL_CONNECTION_VERSION_SSL2;
101 case SSL3_VERSION:
102 return SSL_CONNECTION_VERSION_SSL3;
103 case TLS1_VERSION:
104 return SSL_CONNECTION_VERSION_TLS1;
davidben1d094022014-11-05 18:55:47105 case TLS1_1_VERSION:
[email protected]109805a2010-12-07 18:17:06106 return SSL_CONNECTION_VERSION_TLS1_1;
davidben1d094022014-11-05 18:55:47107 case TLS1_2_VERSION:
[email protected]109805a2010-12-07 18:17:06108 return SSL_CONNECTION_VERSION_TLS1_2;
109 default:
110 return SSL_CONNECTION_VERSION_UNKNOWN;
111 }
112}
113
[email protected]6bad5052014-07-12 01:25:13114ScopedX509 OSCertHandleToOpenSSL(
115 X509Certificate::OSCertHandle os_handle) {
116#if defined(USE_OPENSSL_CERTS)
117 return ScopedX509(X509Certificate::DupOSCertHandle(os_handle));
118#else // !defined(USE_OPENSSL_CERTS)
119 std::string der_encoded;
120 if (!X509Certificate::GetDEREncoded(os_handle, &der_encoded))
121 return ScopedX509();
122 const uint8_t* bytes = reinterpret_cast<const uint8_t*>(der_encoded.data());
123 return ScopedX509(d2i_X509(NULL, &bytes, der_encoded.size()));
124#endif // defined(USE_OPENSSL_CERTS)
125}
126
[email protected]82c59022014-08-15 09:38:27127ScopedX509Stack OSCertHandlesToOpenSSL(
128 const X509Certificate::OSCertHandles& os_handles) {
129 ScopedX509Stack stack(sk_X509_new_null());
130 for (size_t i = 0; i < os_handles.size(); i++) {
131 ScopedX509 x509 = OSCertHandleToOpenSSL(os_handles[i]);
132 if (!x509)
133 return ScopedX509Stack();
134 sk_X509_push(stack.get(), x509.release());
135 }
136 return stack.Pass();
137}
138
davidben018aad62014-09-12 02:25:19139int LogErrorCallback(const char* str, size_t len, void* context) {
140 LOG(ERROR) << base::StringPiece(str, len);
141 return 1;
142}
143
davidbend1fb2f12014-11-08 02:51:00144bool IsOCSPStaplingSupported() {
145#if defined(OS_WIN)
146 // CERT_OCSP_RESPONSE_PROP_ID is only implemented on Vista+, but it can be
147 // set on Windows XP without error. There is some overhead from the server
148 // sending the OCSP response if it supports the extension, for the subset of
149 // XP clients who will request it but be unable to use it, but this is an
150 // acceptable trade-off for simplicity of implementation.
151 return true;
152#else
153 return false;
154#endif
155}
156
[email protected]821e3bb2013-11-08 01:06:01157} // namespace
158
159class SSLClientSocketOpenSSL::SSLContext {
[email protected]fbef13932010-11-23 12:38:53160 public:
[email protected]b29af7d2010-12-14 11:52:47161 static SSLContext* GetInstance() { return Singleton<SSLContext>::get(); }
[email protected]fbef13932010-11-23 12:38:53162 SSL_CTX* ssl_ctx() { return ssl_ctx_.get(); }
[email protected]1279de12013-12-03 15:13:32163 SSLSessionCacheOpenSSL* session_cache() { return &session_cache_; }
[email protected]fbef13932010-11-23 12:38:53164
[email protected]1279de12013-12-03 15:13:32165 SSLClientSocketOpenSSL* GetClientSocketFromSSL(const SSL* ssl) {
[email protected]fbef13932010-11-23 12:38:53166 DCHECK(ssl);
167 SSLClientSocketOpenSSL* socket = static_cast<SSLClientSocketOpenSSL*>(
168 SSL_get_ex_data(ssl, ssl_socket_data_index_));
169 DCHECK(socket);
170 return socket;
171 }
172
173 bool SetClientSocketForSSL(SSL* ssl, SSLClientSocketOpenSSL* socket) {
174 return SSL_set_ex_data(ssl, ssl_socket_data_index_, socket) != 0;
175 }
176
177 private:
178 friend struct DefaultSingletonTraits<SSLContext>;
179
180 SSLContext() {
[email protected]4b559b4d2011-04-14 17:37:14181 crypto::EnsureOpenSSLInit();
[email protected]fbef13932010-11-23 12:38:53182 ssl_socket_data_index_ = SSL_get_ex_new_index(0, 0, 0, 0, 0);
183 DCHECK_NE(ssl_socket_data_index_, -1);
184 ssl_ctx_.reset(SSL_CTX_new(SSLv23_client_method()));
[email protected]1279de12013-12-03 15:13:32185 session_cache_.Reset(ssl_ctx_.get(), kDefaultSessionCacheConfig);
[email protected]b051cdb62014-02-28 02:20:16186 SSL_CTX_set_cert_verify_callback(ssl_ctx_.get(), CertVerifyCallback, NULL);
[email protected]82c59022014-08-15 09:38:27187 SSL_CTX_set_cert_cb(ssl_ctx_.get(), ClientCertRequestCallback, NULL);
[email protected]b051cdb62014-02-28 02:20:16188 SSL_CTX_set_verify(ssl_ctx_.get(), SSL_VERIFY_PEER, NULL);
[email protected]ea4a1c6a2010-12-09 13:33:28189 // TODO(kristianm): Only select this if ssl_config_.next_proto is not empty.
190 // It would be better if the callback were not a global setting,
191 // but that is an OpenSSL issue.
192 SSL_CTX_set_next_proto_select_cb(ssl_ctx_.get(), SelectNextProtoCallback,
193 NULL);
[email protected]edfd0f42014-07-22 18:20:37194 ssl_ctx_->tlsext_channel_id_enabled_new = 1;
davidben018aad62014-09-12 02:25:19195
196 scoped_ptr<base::Environment> env(base::Environment::Create());
197 std::string ssl_keylog_file;
198 if (env->GetVar("SSLKEYLOGFILE", &ssl_keylog_file) &&
199 !ssl_keylog_file.empty()) {
200 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
201 BIO* bio = BIO_new_file(ssl_keylog_file.c_str(), "a");
202 if (!bio) {
203 LOG(ERROR) << "Failed to open " << ssl_keylog_file;
204 ERR_print_errors_cb(&LogErrorCallback, NULL);
205 } else {
206 SSL_CTX_set_keylog_bio(ssl_ctx_.get(), bio);
207 }
208 }
[email protected]fbef13932010-11-23 12:38:53209 }
210
[email protected]1279de12013-12-03 15:13:32211 static std::string GetSessionCacheKey(const SSL* ssl) {
212 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
213 DCHECK(socket);
[email protected]8e458552014-08-05 00:02:15214 return socket->GetSessionCacheKey();
[email protected]fbef13932010-11-23 12:38:53215 }
216
[email protected]1279de12013-12-03 15:13:32217 static SSLSessionCacheOpenSSL::Config kDefaultSessionCacheConfig;
[email protected]fbef13932010-11-23 12:38:53218
[email protected]82c59022014-08-15 09:38:27219 static int ClientCertRequestCallback(SSL* ssl, void* arg) {
[email protected]b29af7d2010-12-14 11:52:47220 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
[email protected]82c59022014-08-15 09:38:27221 DCHECK(socket);
222 return socket->ClientCertRequestCallback(ssl);
[email protected]718c9672010-12-02 10:04:10223 }
224
[email protected]b051cdb62014-02-28 02:20:16225 static int CertVerifyCallback(X509_STORE_CTX *store_ctx, void *arg) {
226 SSL* ssl = reinterpret_cast<SSL*>(X509_STORE_CTX_get_ex_data(
227 store_ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
228 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
229 CHECK(socket);
230
231 return socket->CertVerifyCallback(store_ctx);
232 }
233
[email protected]ea4a1c6a2010-12-09 13:33:28234 static int SelectNextProtoCallback(SSL* ssl,
235 unsigned char** out, unsigned char* outlen,
236 const unsigned char* in,
237 unsigned int inlen, void* arg) {
[email protected]b29af7d2010-12-14 11:52:47238 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
[email protected]ea4a1c6a2010-12-09 13:33:28239 return socket->SelectNextProtoCallback(out, outlen, in, inlen);
240 }
241
[email protected]fbef13932010-11-23 12:38:53242 // This is the index used with SSL_get_ex_data to retrieve the owner
243 // SSLClientSocketOpenSSL object from an SSL instance.
244 int ssl_socket_data_index_;
245
[email protected]cd9b75b2014-07-10 04:39:38246 crypto::ScopedOpenSSL<SSL_CTX, SSL_CTX_free>::Type ssl_ctx_;
[email protected]1279de12013-12-03 15:13:32247 // |session_cache_| must be destroyed before |ssl_ctx_|.
248 SSLSessionCacheOpenSSL session_cache_;
249};
250
[email protected]7f38da8a2014-03-17 16:44:26251// PeerCertificateChain is a helper object which extracts the certificate
252// chain, as given by the server, from an OpenSSL socket and performs the needed
253// resource management. The first element of the chain is the leaf certificate
254// and the other elements are in the order given by the server.
255class SSLClientSocketOpenSSL::PeerCertificateChain {
256 public:
[email protected]76e85392014-03-20 17:54:14257 explicit PeerCertificateChain(STACK_OF(X509)* chain) { Reset(chain); }
[email protected]7f38da8a2014-03-17 16:44:26258 PeerCertificateChain(const PeerCertificateChain& other) { *this = other; }
259 ~PeerCertificateChain() {}
260 PeerCertificateChain& operator=(const PeerCertificateChain& other);
261
[email protected]76e85392014-03-20 17:54:14262 // Resets the PeerCertificateChain to the set of certificates in|chain|,
263 // which may be NULL, indicating to empty the store certificates.
264 // Note: If an error occurs, such as being unable to parse the certificates,
265 // this will behave as if Reset(NULL) was called.
266 void Reset(STACK_OF(X509)* chain);
267
[email protected]7f38da8a2014-03-17 16:44:26268 // Note that when USE_OPENSSL is defined, OSCertHandle is X509*
davidben30798ed82014-09-19 19:28:20269 scoped_refptr<X509Certificate> AsOSChain() const;
[email protected]7f38da8a2014-03-17 16:44:26270
271 size_t size() const {
272 if (!openssl_chain_.get())
273 return 0;
274 return sk_X509_num(openssl_chain_.get());
275 }
276
davidben30798ed82014-09-19 19:28:20277 bool empty() const {
278 return size() == 0;
279 }
280
281 X509* Get(size_t index) const {
[email protected]7f38da8a2014-03-17 16:44:26282 DCHECK_LT(index, size());
283 return sk_X509_value(openssl_chain_.get(), index);
284 }
285
286 private:
[email protected]cd9b75b2014-07-10 04:39:38287 ScopedX509Stack openssl_chain_;
[email protected]7f38da8a2014-03-17 16:44:26288};
289
290SSLClientSocketOpenSSL::PeerCertificateChain&
291SSLClientSocketOpenSSL::PeerCertificateChain::operator=(
292 const PeerCertificateChain& other) {
293 if (this == &other)
294 return *this;
295
[email protected]24176af2014-08-14 09:31:04296 openssl_chain_.reset(X509_chain_up_ref(other.openssl_chain_.get()));
[email protected]7f38da8a2014-03-17 16:44:26297 return *this;
298}
299
[email protected]76e85392014-03-20 17:54:14300void SSLClientSocketOpenSSL::PeerCertificateChain::Reset(
301 STACK_OF(X509)* chain) {
davidben30798ed82014-09-19 19:28:20302 openssl_chain_.reset(chain ? X509_chain_up_ref(chain) : NULL);
[email protected]7f38da8a2014-03-17 16:44:26303}
[email protected]7f38da8a2014-03-17 16:44:26304
davidben30798ed82014-09-19 19:28:20305scoped_refptr<X509Certificate>
306SSLClientSocketOpenSSL::PeerCertificateChain::AsOSChain() const {
307#if defined(USE_OPENSSL_CERTS)
308 // When OSCertHandle is typedef'ed to X509, this implementation does a short
309 // cut to avoid converting back and forth between DER and the X509 struct.
310 X509Certificate::OSCertHandles intermediates;
311 for (size_t i = 1; i < sk_X509_num(openssl_chain_.get()); ++i) {
312 intermediates.push_back(sk_X509_value(openssl_chain_.get(), i));
313 }
[email protected]7f38da8a2014-03-17 16:44:26314
davidben30798ed82014-09-19 19:28:20315 return make_scoped_refptr(X509Certificate::CreateFromHandle(
316 sk_X509_value(openssl_chain_.get(), 0), intermediates));
317#else
318 // DER-encode the chain and convert to a platform certificate handle.
[email protected]7f38da8a2014-03-17 16:44:26319 std::vector<base::StringPiece> der_chain;
[email protected]edfd0f42014-07-22 18:20:37320 for (size_t i = 0; i < sk_X509_num(openssl_chain_.get()); ++i) {
[email protected]7f38da8a2014-03-17 16:44:26321 X509* x = sk_X509_value(openssl_chain_.get(), i);
davidben30798ed82014-09-19 19:28:20322 base::StringPiece der;
323 if (!x509_util::GetDER(x, &der))
324 return NULL;
325 der_chain.push_back(der);
[email protected]7f38da8a2014-03-17 16:44:26326 }
327
davidben30798ed82014-09-19 19:28:20328 return make_scoped_refptr(X509Certificate::CreateFromDERCertChain(der_chain));
329#endif
[email protected]7f38da8a2014-03-17 16:44:26330}
[email protected]7f38da8a2014-03-17 16:44:26331
[email protected]1279de12013-12-03 15:13:32332// static
333SSLSessionCacheOpenSSL::Config
334 SSLClientSocketOpenSSL::SSLContext::kDefaultSessionCacheConfig = {
335 &GetSessionCacheKey, // key_func
336 1024, // max_entries
337 256, // expiration_check_count
338 60 * 60, // timeout_seconds
[email protected]fbef13932010-11-23 12:38:53339};
[email protected]313834722010-11-17 09:57:18340
[email protected]c3456bb2011-12-12 22:22:19341// static
342void SSLClientSocket::ClearSessionCache() {
[email protected]821e3bb2013-11-08 01:06:01343 SSLClientSocketOpenSSL::SSLContext* context =
344 SSLClientSocketOpenSSL::SSLContext::GetInstance();
[email protected]c3456bb2011-12-12 22:22:19345 context->session_cache()->Flush();
346}
347
bnc86b734dd2014-12-03 00:33:10348// static
349uint16 SSLClientSocket::GetMaxSupportedSSLVersion() {
350 return SSL_PROTOCOL_VERSION_TLS1_2;
351}
352
[email protected]d518cd92010-09-29 12:27:44353SSLClientSocketOpenSSL::SSLClientSocketOpenSSL(
[email protected]18ccfdb2013-08-15 00:13:44354 scoped_ptr<ClientSocketHandle> transport_socket,
[email protected]055d7f22010-11-15 12:03:12355 const HostPortPair& host_and_port,
[email protected]822581d2010-12-16 17:27:15356 const SSLConfig& ssl_config,
[email protected]feb79bcd2011-07-21 16:55:17357 const SSLClientSocketContext& context)
[email protected]83039bb2011-12-09 18:43:55358 : transport_send_busy_(false),
[email protected]d518cd92010-09-29 12:27:44359 transport_recv_busy_(false),
[email protected]4b768562013-02-16 04:10:07360 pending_read_error_(kNoPendingReadResult),
davidbenb8c23212014-10-28 00:12:16361 pending_read_ssl_error_(SSL_ERROR_NONE),
[email protected]5aea79182014-07-14 20:43:41362 transport_read_error_(OK),
[email protected]3e5c6922014-02-06 02:42:16363 transport_write_error_(OK),
[email protected]7f38da8a2014-03-17 16:44:26364 server_cert_chain_(new PeerCertificateChain(NULL)),
[email protected]64b5c892014-08-08 09:39:26365 completed_connect_(false),
[email protected]0dc88b32014-03-26 20:12:28366 was_ever_used_(false),
[email protected]d518cd92010-09-29 12:27:44367 client_auth_cert_needed_(false),
[email protected]feb79bcd2011-07-21 16:55:17368 cert_verifier_(context.cert_verifier),
davidbeneb5f8ef32014-09-04 14:14:32369 cert_transparency_verifier_(context.cert_transparency_verifier),
[email protected]6b8a3c742014-07-25 00:25:35370 channel_id_service_(context.channel_id_service),
[email protected]d518cd92010-09-29 12:27:44371 ssl_(NULL),
372 transport_bio_(NULL),
[email protected]18ccfdb2013-08-15 00:13:44373 transport_(transport_socket.Pass()),
[email protected]055d7f22010-11-15 12:03:12374 host_and_port_(host_and_port),
[email protected]d518cd92010-09-29 12:27:44375 ssl_config_(ssl_config),
[email protected]c3456bb2011-12-12 22:22:19376 ssl_session_cache_shard_(context.ssl_session_cache_shard),
[email protected]fbef13932010-11-23 12:38:53377 trying_cached_session_(false),
[email protected]013c17c2012-01-21 19:09:01378 next_handshake_state_(STATE_NONE),
[email protected]ea4a1c6a2010-12-09 13:33:28379 npn_status_(kNextProtoUnsupported),
[email protected]ee0f2aa82013-10-25 11:59:26380 channel_id_xtn_negotiated_(false),
[email protected]64b5c892014-08-08 09:39:26381 handshake_succeeded_(false),
[email protected]e4738ba52014-08-07 10:07:22382 marked_session_as_good_(false),
[email protected]8bd4e7a2014-08-09 14:49:17383 transport_security_state_(context.transport_security_state),
eranm6571b2b2014-12-03 15:53:23384 policy_enforcer_(context.cert_policy_enforcer),
kulkarni.acd7b4462014-08-28 07:41:34385 net_log_(transport_->socket()->NetLog()),
386 weak_factory_(this) {
[email protected]8e458552014-08-05 00:02:15387}
[email protected]d518cd92010-09-29 12:27:44388
389SSLClientSocketOpenSSL::~SSLClientSocketOpenSSL() {
390 Disconnect();
391}
392
[email protected]cffd7f92014-08-21 21:30:50393std::string SSLClientSocketOpenSSL::GetSessionCacheKey() const {
394 std::string result = host_and_port_.ToString();
395 result.append("/");
396 result.append(ssl_session_cache_shard_);
397 return result;
398}
399
[email protected]8e458552014-08-05 00:02:15400bool SSLClientSocketOpenSSL::InSessionCache() const {
401 SSLContext* context = SSLContext::GetInstance();
402 std::string cache_key = GetSessionCacheKey();
403 return context->session_cache()->SSLSessionIsInCache(cache_key);
404}
405
406void SSLClientSocketOpenSSL::SetHandshakeCompletionCallback(
407 const base::Closure& callback) {
408 handshake_completion_callback_ = callback;
409}
410
[email protected]b9b651f2013-11-09 04:32:22411void SSLClientSocketOpenSSL::GetSSLCertRequestInfo(
412 SSLCertRequestInfo* cert_request_info) {
[email protected]791879c2013-12-17 07:22:41413 cert_request_info->host_and_port = host_and_port_;
[email protected]b9b651f2013-11-09 04:32:22414 cert_request_info->cert_authorities = cert_authorities_;
[email protected]c0787702014-05-20 21:51:44415 cert_request_info->cert_key_types = cert_key_types_;
[email protected]b9b651f2013-11-09 04:32:22416}
417
418SSLClientSocket::NextProtoStatus SSLClientSocketOpenSSL::GetNextProto(
[email protected]abc44b752014-07-30 03:52:15419 std::string* proto) {
[email protected]b9b651f2013-11-09 04:32:22420 *proto = npn_proto_;
[email protected]b9b651f2013-11-09 04:32:22421 return npn_status_;
422}
423
[email protected]6b8a3c742014-07-25 00:25:35424ChannelIDService*
425SSLClientSocketOpenSSL::GetChannelIDService() const {
426 return channel_id_service_;
[email protected]b9b651f2013-11-09 04:32:22427}
428
429int SSLClientSocketOpenSSL::ExportKeyingMaterial(
430 const base::StringPiece& label,
431 bool has_context, const base::StringPiece& context,
432 unsigned char* out, unsigned int outlen) {
433 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
434
435 int rv = SSL_export_keying_material(
[email protected]c8a80e92014-05-17 16:02:08436 ssl_, out, outlen, label.data(), label.size(),
437 reinterpret_cast<const unsigned char*>(context.data()),
438 context.length(), context.length() > 0);
[email protected]b9b651f2013-11-09 04:32:22439
440 if (rv != 1) {
441 int ssl_error = SSL_get_error(ssl_, rv);
442 LOG(ERROR) << "Failed to export keying material;"
443 << " returned " << rv
444 << ", SSL error code " << ssl_error;
445 return MapOpenSSLError(ssl_error, err_tracer);
446 }
447 return OK;
448}
449
450int SSLClientSocketOpenSSL::GetTLSUniqueChannelBinding(std::string* out) {
[email protected]c8a80e92014-05-17 16:02:08451 NOTIMPLEMENTED();
[email protected]b9b651f2013-11-09 04:32:22452 return ERR_NOT_IMPLEMENTED;
453}
454
455int SSLClientSocketOpenSSL::Connect(const CompletionCallback& callback) {
[email protected]8bd4e7a2014-08-09 14:49:17456 // It is an error to create an SSLClientSocket whose context has no
457 // TransportSecurityState.
458 DCHECK(transport_security_state_);
459
[email protected]b9b651f2013-11-09 04:32:22460 net_log_.BeginEvent(NetLog::TYPE_SSL_CONNECT);
461
462 // Set up new ssl object.
[email protected]c8a80e92014-05-17 16:02:08463 int rv = Init();
464 if (rv != OK) {
465 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
466 return rv;
[email protected]b9b651f2013-11-09 04:32:22467 }
468
469 // Set SSL to client mode. Handshake happens in the loop below.
470 SSL_set_connect_state(ssl_);
471
472 GotoState(STATE_HANDSHAKE);
[email protected]c8a80e92014-05-17 16:02:08473 rv = DoHandshakeLoop(OK);
[email protected]b9b651f2013-11-09 04:32:22474 if (rv == ERR_IO_PENDING) {
475 user_connect_callback_ = callback;
476 } else {
477 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
[email protected]8e458552014-08-05 00:02:15478 if (rv < OK)
479 OnHandshakeCompletion();
[email protected]b9b651f2013-11-09 04:32:22480 }
481
482 return rv > OK ? OK : rv;
483}
484
485void SSLClientSocketOpenSSL::Disconnect() {
[email protected]8e458552014-08-05 00:02:15486 // If a handshake was pending (Connect() had been called), notify interested
487 // parties that it's been aborted now. If the handshake had already
488 // completed, this is a no-op.
489 OnHandshakeCompletion();
[email protected]b9b651f2013-11-09 04:32:22490 if (ssl_) {
491 // Calling SSL_shutdown prevents the session from being marked as
492 // unresumable.
493 SSL_shutdown(ssl_);
494 SSL_free(ssl_);
495 ssl_ = NULL;
496 }
497 if (transport_bio_) {
498 BIO_free_all(transport_bio_);
499 transport_bio_ = NULL;
500 }
501
502 // Shut down anything that may call us back.
503 verifier_.reset();
504 transport_->socket()->Disconnect();
505
506 // Null all callbacks, delete all buffers.
507 transport_send_busy_ = false;
508 send_buffer_ = NULL;
509 transport_recv_busy_ = false;
[email protected]b9b651f2013-11-09 04:32:22510 recv_buffer_ = NULL;
511
512 user_connect_callback_.Reset();
513 user_read_callback_.Reset();
514 user_write_callback_.Reset();
515 user_read_buf_ = NULL;
516 user_read_buf_len_ = 0;
517 user_write_buf_ = NULL;
518 user_write_buf_len_ = 0;
519
[email protected]3e5c6922014-02-06 02:42:16520 pending_read_error_ = kNoPendingReadResult;
davidbenb8c23212014-10-28 00:12:16521 pending_read_ssl_error_ = SSL_ERROR_NONE;
522 pending_read_error_info_ = OpenSSLErrorInfo();
523
[email protected]5aea79182014-07-14 20:43:41524 transport_read_error_ = OK;
[email protected]3e5c6922014-02-06 02:42:16525 transport_write_error_ = OK;
526
[email protected]b9b651f2013-11-09 04:32:22527 server_cert_verify_result_.Reset();
[email protected]64b5c892014-08-08 09:39:26528 completed_connect_ = false;
[email protected]b9b651f2013-11-09 04:32:22529
530 cert_authorities_.clear();
[email protected]c0787702014-05-20 21:51:44531 cert_key_types_.clear();
[email protected]b9b651f2013-11-09 04:32:22532 client_auth_cert_needed_ = false;
[email protected]faff9852014-06-21 06:13:46533
davidben09c3d072014-08-25 20:33:58534 start_cert_verification_time_ = base::TimeTicks();
535
[email protected]abc44b752014-07-30 03:52:15536 npn_status_ = kNextProtoUnsupported;
537 npn_proto_.clear();
538
[email protected]faff9852014-06-21 06:13:46539 channel_id_xtn_negotiated_ = false;
540 channel_id_request_handle_.Cancel();
[email protected]b9b651f2013-11-09 04:32:22541}
542
543bool SSLClientSocketOpenSSL::IsConnected() const {
544 // If the handshake has not yet completed.
[email protected]64b5c892014-08-08 09:39:26545 if (!completed_connect_)
[email protected]b9b651f2013-11-09 04:32:22546 return false;
547 // If an asynchronous operation is still pending.
548 if (user_read_buf_.get() || user_write_buf_.get())
549 return true;
550
551 return transport_->socket()->IsConnected();
552}
553
554bool SSLClientSocketOpenSSL::IsConnectedAndIdle() const {
555 // If the handshake has not yet completed.
[email protected]64b5c892014-08-08 09:39:26556 if (!completed_connect_)
[email protected]b9b651f2013-11-09 04:32:22557 return false;
558 // If an asynchronous operation is still pending.
559 if (user_read_buf_.get() || user_write_buf_.get())
560 return false;
561 // If there is data waiting to be sent, or data read from the network that
562 // has not yet been consumed.
[email protected]edfd0f42014-07-22 18:20:37563 if (BIO_pending(transport_bio_) > 0 ||
564 BIO_wpending(transport_bio_) > 0) {
[email protected]b9b651f2013-11-09 04:32:22565 return false;
566 }
567
568 return transport_->socket()->IsConnectedAndIdle();
569}
570
571int SSLClientSocketOpenSSL::GetPeerAddress(IPEndPoint* addressList) const {
572 return transport_->socket()->GetPeerAddress(addressList);
573}
574
575int SSLClientSocketOpenSSL::GetLocalAddress(IPEndPoint* addressList) const {
576 return transport_->socket()->GetLocalAddress(addressList);
577}
578
579const BoundNetLog& SSLClientSocketOpenSSL::NetLog() const {
580 return net_log_;
581}
582
583void SSLClientSocketOpenSSL::SetSubresourceSpeculation() {
584 if (transport_.get() && transport_->socket()) {
585 transport_->socket()->SetSubresourceSpeculation();
586 } else {
587 NOTREACHED();
588 }
589}
590
591void SSLClientSocketOpenSSL::SetOmniboxSpeculation() {
592 if (transport_.get() && transport_->socket()) {
593 transport_->socket()->SetOmniboxSpeculation();
594 } else {
595 NOTREACHED();
596 }
597}
598
599bool SSLClientSocketOpenSSL::WasEverUsed() const {
[email protected]0dc88b32014-03-26 20:12:28600 return was_ever_used_;
[email protected]b9b651f2013-11-09 04:32:22601}
602
603bool SSLClientSocketOpenSSL::UsingTCPFastOpen() const {
604 if (transport_.get() && transport_->socket())
605 return transport_->socket()->UsingTCPFastOpen();
606
607 NOTREACHED();
608 return false;
609}
610
611bool SSLClientSocketOpenSSL::GetSSLInfo(SSLInfo* ssl_info) {
612 ssl_info->Reset();
davidben30798ed82014-09-19 19:28:20613 if (server_cert_chain_->empty())
[email protected]b9b651f2013-11-09 04:32:22614 return false;
615
616 ssl_info->cert = server_cert_verify_result_.verified_cert;
617 ssl_info->cert_status = server_cert_verify_result_.cert_status;
618 ssl_info->is_issued_by_known_root =
619 server_cert_verify_result_.is_issued_by_known_root;
620 ssl_info->public_key_hashes =
621 server_cert_verify_result_.public_key_hashes;
622 ssl_info->client_cert_sent =
623 ssl_config_.send_client_cert && ssl_config_.client_cert.get();
624 ssl_info->channel_id_sent = WasChannelIDSent();
[email protected]8bd4e7a2014-08-09 14:49:17625 ssl_info->pinning_failure_log = pinning_failure_log_;
[email protected]b9b651f2013-11-09 04:32:22626
davidbeneb5f8ef32014-09-04 14:14:32627 AddSCTInfoToSSLInfo(ssl_info);
628
[email protected]b9b651f2013-11-09 04:32:22629 const SSL_CIPHER* cipher = SSL_get_current_cipher(ssl_);
630 CHECK(cipher);
631 ssl_info->security_bits = SSL_CIPHER_get_bits(cipher, NULL);
[email protected]b9b651f2013-11-09 04:32:22632
633 ssl_info->connection_status = EncodeSSLConnectionStatus(
pkasting6b68a162014-12-01 22:10:29634 static_cast<uint16>(SSL_CIPHER_get_id(cipher)), 0 /* no compression */,
[email protected]b9b651f2013-11-09 04:32:22635 GetNetSSLVersion(ssl_));
636
davidben09c3d072014-08-25 20:33:58637 if (!SSL_get_secure_renegotiation_support(ssl_))
[email protected]b9b651f2013-11-09 04:32:22638 ssl_info->connection_status |= SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION;
[email protected]b9b651f2013-11-09 04:32:22639
640 if (ssl_config_.version_fallback)
641 ssl_info->connection_status |= SSL_CONNECTION_VERSION_FALLBACK;
642
643 ssl_info->handshake_type = SSL_session_reused(ssl_) ?
644 SSLInfo::HANDSHAKE_RESUME : SSLInfo::HANDSHAKE_FULL;
645
646 DVLOG(3) << "Encoded connection status: cipher suite = "
647 << SSLConnectionStatusToCipherSuite(ssl_info->connection_status)
648 << " version = "
649 << SSLConnectionStatusToVersion(ssl_info->connection_status);
650 return true;
651}
652
653int SSLClientSocketOpenSSL::Read(IOBuffer* buf,
654 int buf_len,
655 const CompletionCallback& callback) {
656 user_read_buf_ = buf;
657 user_read_buf_len_ = buf_len;
658
davidben1b133ad2014-10-23 04:23:13659 int rv = DoReadLoop();
[email protected]b9b651f2013-11-09 04:32:22660
661 if (rv == ERR_IO_PENDING) {
662 user_read_callback_ = callback;
663 } else {
[email protected]0dc88b32014-03-26 20:12:28664 if (rv > 0)
665 was_ever_used_ = true;
[email protected]b9b651f2013-11-09 04:32:22666 user_read_buf_ = NULL;
667 user_read_buf_len_ = 0;
[email protected]8e458552014-08-05 00:02:15668 if (rv <= 0) {
669 // Failure of a read attempt may indicate a failed false start
670 // connection.
671 OnHandshakeCompletion();
672 }
[email protected]b9b651f2013-11-09 04:32:22673 }
674
675 return rv;
676}
677
678int SSLClientSocketOpenSSL::Write(IOBuffer* buf,
679 int buf_len,
680 const CompletionCallback& callback) {
681 user_write_buf_ = buf;
682 user_write_buf_len_ = buf_len;
683
davidben1b133ad2014-10-23 04:23:13684 int rv = DoWriteLoop();
[email protected]b9b651f2013-11-09 04:32:22685
686 if (rv == ERR_IO_PENDING) {
687 user_write_callback_ = callback;
688 } else {
[email protected]0dc88b32014-03-26 20:12:28689 if (rv > 0)
690 was_ever_used_ = true;
[email protected]b9b651f2013-11-09 04:32:22691 user_write_buf_ = NULL;
692 user_write_buf_len_ = 0;
[email protected]8e458552014-08-05 00:02:15693 if (rv < 0) {
694 // Failure of a write attempt may indicate a failed false start
695 // connection.
696 OnHandshakeCompletion();
697 }
[email protected]b9b651f2013-11-09 04:32:22698 }
699
700 return rv;
701}
702
[email protected]28b96d1c2014-04-09 12:21:15703int SSLClientSocketOpenSSL::SetReceiveBufferSize(int32 size) {
[email protected]b9b651f2013-11-09 04:32:22704 return transport_->socket()->SetReceiveBufferSize(size);
705}
706
[email protected]28b96d1c2014-04-09 12:21:15707int SSLClientSocketOpenSSL::SetSendBufferSize(int32 size) {
[email protected]b9b651f2013-11-09 04:32:22708 return transport_->socket()->SetSendBufferSize(size);
709}
710
[email protected]c8a80e92014-05-17 16:02:08711int SSLClientSocketOpenSSL::Init() {
[email protected]9e733f32010-10-04 18:19:08712 DCHECK(!ssl_);
713 DCHECK(!transport_bio_);
714
[email protected]b29af7d2010-12-14 11:52:47715 SSLContext* context = SSLContext::GetInstance();
[email protected]4b559b4d2011-04-14 17:37:14716 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
[email protected]d518cd92010-09-29 12:27:44717
[email protected]fbef13932010-11-23 12:38:53718 ssl_ = SSL_new(context->ssl_ctx());
719 if (!ssl_ || !context->SetClientSocketForSSL(ssl_, this))
[email protected]c8a80e92014-05-17 16:02:08720 return ERR_UNEXPECTED;
[email protected]fbef13932010-11-23 12:38:53721
722 if (!SSL_set_tlsext_host_name(ssl_, host_and_port_.host().c_str()))
[email protected]c8a80e92014-05-17 16:02:08723 return ERR_UNEXPECTED;
[email protected]fbef13932010-11-23 12:38:53724
[email protected]e4738ba52014-08-07 10:07:22725 // Set an OpenSSL callback to monitor this SSL*'s connection.
726 SSL_set_info_callback(ssl_, &InfoCallback);
727
[email protected]1279de12013-12-03 15:13:32728 trying_cached_session_ = context->session_cache()->SetSSLSessionWithKey(
[email protected]8e458552014-08-05 00:02:15729 ssl_, GetSessionCacheKey());
[email protected]d518cd92010-09-29 12:27:44730
731 BIO* ssl_bio = NULL;
[email protected]fbef13932010-11-23 12:38:53732 // 0 => use default buffer sizes.
733 if (!BIO_new_bio_pair(&ssl_bio, 0, &transport_bio_, 0))
[email protected]c8a80e92014-05-17 16:02:08734 return ERR_UNEXPECTED;
[email protected]d518cd92010-09-29 12:27:44735 DCHECK(ssl_bio);
736 DCHECK(transport_bio_);
737
[email protected]5aea79182014-07-14 20:43:41738 // Install a callback on OpenSSL's end to plumb transport errors through.
[email protected]64b5c892014-08-08 09:39:26739 BIO_set_callback(ssl_bio, BIOCallback);
[email protected]5aea79182014-07-14 20:43:41740 BIO_set_callback_arg(ssl_bio, reinterpret_cast<char*>(this));
741
[email protected]d518cd92010-09-29 12:27:44742 SSL_set_bio(ssl_, ssl_bio, ssl_bio);
743
[email protected]9e733f32010-10-04 18:19:08744 // OpenSSL defaults some options to on, others to off. To avoid ambiguity,
745 // set everything we care about to an absolute value.
[email protected]fb10e2282010-12-01 17:08:48746 SslSetClearMask options;
747 options.ConfigureFlag(SSL_OP_NO_SSLv2, true);
[email protected]80c75f682012-05-26 16:22:17748 bool ssl3_enabled = (ssl_config_.version_min == SSL_PROTOCOL_VERSION_SSL3);
749 options.ConfigureFlag(SSL_OP_NO_SSLv3, !ssl3_enabled);
750 bool tls1_enabled = (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1 &&
751 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1);
752 options.ConfigureFlag(SSL_OP_NO_TLSv1, !tls1_enabled);
[email protected]80c75f682012-05-26 16:22:17753 bool tls1_1_enabled =
754 (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1_1 &&
755 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1_1);
756 options.ConfigureFlag(SSL_OP_NO_TLSv1_1, !tls1_1_enabled);
[email protected]80c75f682012-05-26 16:22:17757 bool tls1_2_enabled =
758 (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1_2 &&
759 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1_2);
760 options.ConfigureFlag(SSL_OP_NO_TLSv1_2, !tls1_2_enabled);
[email protected]fb10e2282010-12-01 17:08:48761
[email protected]d0f00492012-08-03 22:35:13762 options.ConfigureFlag(SSL_OP_NO_COMPRESSION, true);
[email protected]9e733f32010-10-04 18:19:08763
764 // TODO(joth): Set this conditionally, see http://crbug.com/55410
[email protected]fb10e2282010-12-01 17:08:48765 options.ConfigureFlag(SSL_OP_LEGACY_SERVER_CONNECT, true);
[email protected]9e733f32010-10-04 18:19:08766
[email protected]fb10e2282010-12-01 17:08:48767 SSL_set_options(ssl_, options.set_mask);
768 SSL_clear_options(ssl_, options.clear_mask);
[email protected]9e733f32010-10-04 18:19:08769
[email protected]fb10e2282010-12-01 17:08:48770 // Same as above, this time for the SSL mode.
771 SslSetClearMask mode;
[email protected]9e733f32010-10-04 18:19:08772
[email protected]fb10e2282010-12-01 17:08:48773 mode.ConfigureFlag(SSL_MODE_RELEASE_BUFFERS, true);
ishermane5c05e12014-09-09 20:32:15774 mode.ConfigureFlag(SSL_MODE_CBC_RECORD_SPLITTING, true);
[email protected]fb10e2282010-12-01 17:08:48775
[email protected]b788de02014-04-23 18:06:07776 mode.ConfigureFlag(SSL_MODE_HANDSHAKE_CUTTHROUGH,
777 ssl_config_.false_start_enabled);
778
[email protected]fb10e2282010-12-01 17:08:48779 SSL_set_mode(ssl_, mode.set_mask);
780 SSL_clear_mode(ssl_, mode.clear_mask);
[email protected]109805a2010-12-07 18:17:06781
782 // Removing ciphers by ID from OpenSSL is a bit involved as we must use the
783 // textual name with SSL_set_cipher_list because there is no public API to
784 // directly remove a cipher by ID.
785 STACK_OF(SSL_CIPHER)* ciphers = SSL_get_ciphers(ssl_);
786 DCHECK(ciphers);
787 // See SSLConfig::disabled_cipher_suites for description of the suites
[email protected]9b4bc4a92013-08-20 22:59:07788 // disabled by default. Note that !SHA256 and !SHA384 only remove HMAC-SHA256
789 // and HMAC-SHA384 cipher suites, not GCM cipher suites with SHA256 or SHA384
790 // as the handshake hash.
791 std::string command("DEFAULT:!NULL:!aNULL:!IDEA:!FZA:!SRP:!SHA256:!SHA384:"
792 "!aECDH:!AESGCM+AES256");
[email protected]109805a2010-12-07 18:17:06793 // Walk through all the installed ciphers, seeing if any need to be
794 // appended to the cipher removal |command|.
[email protected]edfd0f42014-07-22 18:20:37795 for (size_t i = 0; i < sk_SSL_CIPHER_num(ciphers); ++i) {
[email protected]109805a2010-12-07 18:17:06796 const SSL_CIPHER* cipher = sk_SSL_CIPHER_value(ciphers, i);
pkasting6b68a162014-12-01 22:10:29797 const uint16 id = static_cast<uint16>(SSL_CIPHER_get_id(cipher));
[email protected]109805a2010-12-07 18:17:06798 // Remove any ciphers with a strength of less than 80 bits. Note the NSS
799 // implementation uses "effective" bits here but OpenSSL does not provide
800 // this detail. This only impacts Triple DES: reports 112 vs. 168 bits,
801 // both of which are greater than 80 anyway.
802 bool disable = SSL_CIPHER_get_bits(cipher, NULL) < 80;
803 if (!disable) {
804 disable = std::find(ssl_config_.disabled_cipher_suites.begin(),
805 ssl_config_.disabled_cipher_suites.end(), id) !=
806 ssl_config_.disabled_cipher_suites.end();
807 }
808 if (disable) {
809 const char* name = SSL_CIPHER_get_name(cipher);
810 DVLOG(3) << "Found cipher to remove: '" << name << "', ID: " << id
811 << " strength: " << SSL_CIPHER_get_bits(cipher, NULL);
812 command.append(":!");
813 command.append(name);
814 }
815 }
davidben8ecc3072014-09-03 23:19:09816
817 // Disable ECDSA cipher suites on platforms that do not support ECDSA
818 // signed certificates, as servers may use the presence of such
819 // ciphersuites as a hint to send an ECDSA certificate.
820#if defined(OS_WIN)
821 if (base::win::GetVersion() < base::win::VERSION_VISTA)
822 command.append(":!ECDSA");
823#endif
824
[email protected]109805a2010-12-07 18:17:06825 int rv = SSL_set_cipher_list(ssl_, command.c_str());
826 // If this fails (rv = 0) it means there are no ciphers enabled on this SSL.
827 // This will almost certainly result in the socket failing to complete the
828 // handshake at which point the appropriate error is bubbled up to the client.
829 LOG_IF(WARNING, rv != 1) << "SSL_set_cipher_list('" << command << "') "
830 "returned " << rv;
[email protected]ee0f2aa82013-10-25 11:59:26831
[email protected]0d0a6872014-07-26 18:05:11832 if (ssl_config_.version_fallback)
833 SSL_enable_fallback_scsv(ssl_);
834
[email protected]ee0f2aa82013-10-25 11:59:26835 // TLS channel ids.
[email protected]6b8a3c742014-07-25 00:25:35836 if (IsChannelIDEnabled(ssl_config_, channel_id_service_)) {
[email protected]ee0f2aa82013-10-25 11:59:26837 SSL_enable_tls_channel_id(ssl_);
838 }
839
[email protected]abc44b752014-07-30 03:52:15840 if (!ssl_config_.next_protos.empty()) {
841 std::vector<uint8_t> wire_protos =
842 SerializeNextProtos(ssl_config_.next_protos);
843 SSL_set_alpn_protos(ssl_, wire_protos.empty() ? NULL : &wire_protos[0],
844 wire_protos.size());
845 }
846
davidbeneb5f8ef32014-09-04 14:14:32847 if (ssl_config_.signed_cert_timestamps_enabled) {
848 SSL_enable_signed_cert_timestamps(ssl_);
849 SSL_enable_ocsp_stapling(ssl_);
850 }
851
davidbend1fb2f12014-11-08 02:51:00852 if (IsOCSPStaplingSupported())
853 SSL_enable_ocsp_stapling(ssl_);
davidbeneb5f8ef32014-09-04 14:14:32854
[email protected]c8a80e92014-05-17 16:02:08855 return OK;
[email protected]d518cd92010-09-29 12:27:44856}
857
[email protected]b9b651f2013-11-09 04:32:22858void SSLClientSocketOpenSSL::DoReadCallback(int rv) {
859 // Since Run may result in Read being called, clear |user_read_callback_|
860 // up front.
[email protected]0dc88b32014-03-26 20:12:28861 if (rv > 0)
862 was_ever_used_ = true;
[email protected]b9b651f2013-11-09 04:32:22863 user_read_buf_ = NULL;
864 user_read_buf_len_ = 0;
[email protected]8e458552014-08-05 00:02:15865 if (rv <= 0) {
866 // Failure of a read attempt may indicate a failed false start
867 // connection.
868 OnHandshakeCompletion();
869 }
[email protected]b9b651f2013-11-09 04:32:22870 base::ResetAndReturn(&user_read_callback_).Run(rv);
871}
872
873void SSLClientSocketOpenSSL::DoWriteCallback(int rv) {
874 // Since Run may result in Write being called, clear |user_write_callback_|
875 // up front.
[email protected]0dc88b32014-03-26 20:12:28876 if (rv > 0)
877 was_ever_used_ = true;
[email protected]b9b651f2013-11-09 04:32:22878 user_write_buf_ = NULL;
879 user_write_buf_len_ = 0;
[email protected]8e458552014-08-05 00:02:15880 if (rv < 0) {
881 // Failure of a write attempt may indicate a failed false start
882 // connection.
883 OnHandshakeCompletion();
884 }
[email protected]b9b651f2013-11-09 04:32:22885 base::ResetAndReturn(&user_write_callback_).Run(rv);
886}
887
[email protected]8e458552014-08-05 00:02:15888void SSLClientSocketOpenSSL::OnHandshakeCompletion() {
889 if (!handshake_completion_callback_.is_null())
890 base::ResetAndReturn(&handshake_completion_callback_).Run();
891}
892
[email protected]b9b651f2013-11-09 04:32:22893bool SSLClientSocketOpenSSL::DoTransportIO() {
894 bool network_moved = false;
895 int rv;
896 // Read and write as much data as possible. The loop is necessary because
897 // Write() may return synchronously.
898 do {
899 rv = BufferSend();
900 if (rv != ERR_IO_PENDING && rv != 0)
901 network_moved = true;
902 } while (rv > 0);
[email protected]5aea79182014-07-14 20:43:41903 if (transport_read_error_ == OK && BufferRecv() != ERR_IO_PENDING)
[email protected]b9b651f2013-11-09 04:32:22904 network_moved = true;
905 return network_moved;
906}
907
908int SSLClientSocketOpenSSL::DoHandshake() {
vadimtb2a77c762014-11-21 19:49:22909 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
910 tracked_objects::ScopedTracker tracking_profile1(
911 FROM_HERE_WITH_EXPLICIT_FUNCTION(
912 "424386 SSLClientSocketOpenSSL::DoHandshake1"));
913
[email protected]b9b651f2013-11-09 04:32:22914 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
[email protected]c8a80e92014-05-17 16:02:08915 int net_error = OK;
[email protected]b9b651f2013-11-09 04:32:22916 int rv = SSL_do_handshake(ssl_);
917
vadimtb2a77c762014-11-21 19:49:22918 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
919 tracked_objects::ScopedTracker tracking_profile2(
920 FROM_HERE_WITH_EXPLICIT_FUNCTION(
921 "424386 SSLClientSocketOpenSSL::DoHandshake2"));
922
[email protected]b9b651f2013-11-09 04:32:22923 if (client_auth_cert_needed_) {
924 net_error = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
925 // If the handshake already succeeded (because the server requests but
926 // doesn't require a client cert), we need to invalidate the SSL session
927 // so that we won't try to resume the non-client-authenticated session in
928 // the next handshake. This will cause the server to ask for a client
929 // cert again.
930 if (rv == 1) {
931 // Remove from session cache but don't clear this connection.
932 SSL_SESSION* session = SSL_get_session(ssl_);
933 if (session) {
934 int rv = SSL_CTX_remove_session(SSL_get_SSL_CTX(ssl_), session);
935 LOG_IF(WARNING, !rv) << "Couldn't invalidate SSL session: " << session;
936 }
937 }
938 } else if (rv == 1) {
939 if (trying_cached_session_ && logging::DEBUG_MODE) {
940 DVLOG(2) << "Result of session reuse for " << host_and_port_.ToString()
941 << " is: " << (SSL_session_reused(ssl_) ? "Success" : "Fail");
942 }
[email protected]abc44b752014-07-30 03:52:15943
Adam Langley32352ad2014-10-14 22:31:00944 if (ssl_config_.version_fallback &&
945 ssl_config_.version_max < ssl_config_.version_fallback_min) {
946 return ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION;
947 }
948
[email protected]abc44b752014-07-30 03:52:15949 // SSL handshake is completed. If NPN wasn't negotiated, see if ALPN was.
950 if (npn_status_ == kNextProtoUnsupported) {
951 const uint8_t* alpn_proto = NULL;
952 unsigned alpn_len = 0;
953 SSL_get0_alpn_selected(ssl_, &alpn_proto, &alpn_len);
954 if (alpn_len > 0) {
955 npn_proto_.assign(reinterpret_cast<const char*>(alpn_proto), alpn_len);
956 npn_status_ = kNextProtoNegotiated;
bnc0d28ea52014-10-13 15:15:38957 set_negotiation_extension(kExtensionALPN);
[email protected]abc44b752014-07-30 03:52:15958 }
959 }
960
davidben09c3d072014-08-25 20:33:58961 RecordChannelIDSupport(channel_id_service_,
962 channel_id_xtn_negotiated_,
963 ssl_config_.channel_id_enabled,
964 crypto::ECPrivateKey::IsSupported());
965
davidbend1fb2f12014-11-08 02:51:00966 // Only record OCSP histograms if OCSP was requested.
967 if (ssl_config_.signed_cert_timestamps_enabled ||
968 IsOCSPStaplingSupported()) {
davidben54015aa2014-12-02 22:16:23969 const uint8_t* ocsp_response;
davidbend1fb2f12014-11-08 02:51:00970 size_t ocsp_response_len;
971 SSL_get0_ocsp_response(ssl_, &ocsp_response, &ocsp_response_len);
972
973 set_stapled_ocsp_response_received(ocsp_response_len != 0);
974 UMA_HISTOGRAM_BOOLEAN("Net.OCSPResponseStapled", ocsp_response_len != 0);
975 }
davidbeneb5f8ef32014-09-04 14:14:32976
davidben54015aa2014-12-02 22:16:23977 const uint8_t* sct_list;
davidbeneb5f8ef32014-09-04 14:14:32978 size_t sct_list_len;
979 SSL_get0_signed_cert_timestamp_list(ssl_, &sct_list, &sct_list_len);
980 set_signed_cert_timestamps_received(sct_list_len != 0);
981
[email protected]abc44b752014-07-30 03:52:15982 // Verify the certificate.
davidben30798ed82014-09-19 19:28:20983 UpdateServerCert();
[email protected]b9b651f2013-11-09 04:32:22984 GotoState(STATE_VERIFY_CERT);
985 } else {
986 int ssl_error = SSL_get_error(ssl_, rv);
987
988 if (ssl_error == SSL_ERROR_WANT_CHANNEL_ID_LOOKUP) {
[email protected]faff9852014-06-21 06:13:46989 // The server supports channel ID. Stop to look one up before returning to
990 // the handshake.
991 channel_id_xtn_negotiated_ = true;
992 GotoState(STATE_CHANNEL_ID_LOOKUP);
993 return OK;
[email protected]b9b651f2013-11-09 04:32:22994 }
995
davidbena4409c62014-08-27 17:05:51996 OpenSSLErrorInfo error_info;
997 net_error = MapOpenSSLErrorWithDetails(ssl_error, err_tracer, &error_info);
[email protected]faff9852014-06-21 06:13:46998
[email protected]b9b651f2013-11-09 04:32:22999 // If not done, stay in this state
1000 if (net_error == ERR_IO_PENDING) {
1001 GotoState(STATE_HANDSHAKE);
1002 } else {
1003 LOG(ERROR) << "handshake failed; returned " << rv
1004 << ", SSL error code " << ssl_error
1005 << ", net_error " << net_error;
1006 net_log_.AddEvent(
1007 NetLog::TYPE_SSL_HANDSHAKE_ERROR,
davidbena4409c62014-08-27 17:05:511008 CreateNetLogOpenSSLErrorCallback(net_error, ssl_error, error_info));
[email protected]b9b651f2013-11-09 04:32:221009 }
1010 }
1011 return net_error;
1012}
1013
[email protected]faff9852014-06-21 06:13:461014int SSLClientSocketOpenSSL::DoChannelIDLookup() {
1015 GotoState(STATE_CHANNEL_ID_LOOKUP_COMPLETE);
[email protected]6b8a3c742014-07-25 00:25:351016 return channel_id_service_->GetOrCreateChannelID(
[email protected]faff9852014-06-21 06:13:461017 host_and_port_.host(),
1018 &channel_id_private_key_,
1019 &channel_id_cert_,
1020 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete,
1021 base::Unretained(this)),
1022 &channel_id_request_handle_);
1023}
1024
1025int SSLClientSocketOpenSSL::DoChannelIDLookupComplete(int result) {
1026 if (result < 0)
1027 return result;
1028
1029 DCHECK_LT(0u, channel_id_private_key_.size());
1030 // Decode key.
1031 std::vector<uint8> encrypted_private_key_info;
1032 std::vector<uint8> subject_public_key_info;
1033 encrypted_private_key_info.assign(
1034 channel_id_private_key_.data(),
1035 channel_id_private_key_.data() + channel_id_private_key_.size());
1036 subject_public_key_info.assign(
1037 channel_id_cert_.data(),
1038 channel_id_cert_.data() + channel_id_cert_.size());
1039 scoped_ptr<crypto::ECPrivateKey> ec_private_key(
1040 crypto::ECPrivateKey::CreateFromEncryptedPrivateKeyInfo(
[email protected]6b8a3c742014-07-25 00:25:351041 ChannelIDService::kEPKIPassword,
[email protected]faff9852014-06-21 06:13:461042 encrypted_private_key_info,
1043 subject_public_key_info));
1044 if (!ec_private_key) {
1045 LOG(ERROR) << "Failed to import Channel ID.";
1046 return ERR_CHANNEL_ID_IMPORT_FAILED;
1047 }
1048
1049 // Hand the key to OpenSSL. Check for error in case OpenSSL rejects the key
1050 // type.
1051 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1052 int rv = SSL_set1_tls_channel_id(ssl_, ec_private_key->key());
1053 if (!rv) {
1054 LOG(ERROR) << "Failed to set Channel ID.";
1055 int err = SSL_get_error(ssl_, rv);
1056 return MapOpenSSLError(err, err_tracer);
1057 }
1058
1059 // Return to the handshake.
1060 set_channel_id_sent(true);
1061 GotoState(STATE_HANDSHAKE);
1062 return OK;
1063}
1064
[email protected]b9b651f2013-11-09 04:32:221065int SSLClientSocketOpenSSL::DoVerifyCert(int result) {
davidben30798ed82014-09-19 19:28:201066 DCHECK(!server_cert_chain_->empty());
davidben09c3d072014-08-25 20:33:581067 DCHECK(start_cert_verification_time_.is_null());
davidben30798ed82014-09-19 19:28:201068
[email protected]b9b651f2013-11-09 04:32:221069 GotoState(STATE_VERIFY_CERT_COMPLETE);
1070
davidben30798ed82014-09-19 19:28:201071 // If the certificate is bad and has been previously accepted, use
1072 // the previous status and bypass the error.
1073 base::StringPiece der_cert;
1074 if (!x509_util::GetDER(server_cert_chain_->Get(0), &der_cert)) {
1075 NOTREACHED();
1076 return ERR_CERT_INVALID;
1077 }
[email protected]b9b651f2013-11-09 04:32:221078 CertStatus cert_status;
davidben30798ed82014-09-19 19:28:201079 if (ssl_config_.IsAllowedBadCert(der_cert, &cert_status)) {
[email protected]b9b651f2013-11-09 04:32:221080 VLOG(1) << "Received an expected bad cert with status: " << cert_status;
1081 server_cert_verify_result_.Reset();
1082 server_cert_verify_result_.cert_status = cert_status;
1083 server_cert_verify_result_.verified_cert = server_cert_;
1084 return OK;
1085 }
1086
davidben30798ed82014-09-19 19:28:201087 // When running in a sandbox, it may not be possible to create an
1088 // X509Certificate*, as that may depend on OS functionality blocked
1089 // in the sandbox.
1090 if (!server_cert_.get()) {
1091 server_cert_verify_result_.Reset();
1092 server_cert_verify_result_.cert_status = CERT_STATUS_INVALID;
1093 return ERR_CERT_INVALID;
1094 }
1095
davidben09c3d072014-08-25 20:33:581096 start_cert_verification_time_ = base::TimeTicks::Now();
1097
[email protected]b9b651f2013-11-09 04:32:221098 int flags = 0;
1099 if (ssl_config_.rev_checking_enabled)
1100 flags |= CertVerifier::VERIFY_REV_CHECKING_ENABLED;
1101 if (ssl_config_.verify_ev_cert)
1102 flags |= CertVerifier::VERIFY_EV_CERT;
1103 if (ssl_config_.cert_io_enabled)
1104 flags |= CertVerifier::VERIFY_CERT_IO_ENABLED;
1105 if (ssl_config_.rev_checking_required_local_anchors)
1106 flags |= CertVerifier::VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS;
1107 verifier_.reset(new SingleRequestCertVerifier(cert_verifier_));
1108 return verifier_->Verify(
1109 server_cert_.get(),
1110 host_and_port_.host(),
1111 flags,
[email protected]591cffcd2014-08-18 20:02:301112 // TODO(davidben): Route the CRLSet through SSLConfig so
1113 // SSLClientSocket doesn't depend on SSLConfigService.
1114 SSLConfigService::GetCRLSet().get(),
[email protected]b9b651f2013-11-09 04:32:221115 &server_cert_verify_result_,
1116 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete,
1117 base::Unretained(this)),
1118 net_log_);
1119}
1120
1121int SSLClientSocketOpenSSL::DoVerifyCertComplete(int result) {
1122 verifier_.reset();
1123
davidben09c3d072014-08-25 20:33:581124 if (!start_cert_verification_time_.is_null()) {
1125 base::TimeDelta verify_time =
1126 base::TimeTicks::Now() - start_cert_verification_time_;
1127 if (result == OK) {
1128 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTime", verify_time);
1129 } else {
1130 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTimeError", verify_time);
1131 }
1132 }
1133
davidben7c7ab602014-11-05 22:27:441134 if (result == OK)
1135 RecordConnectionTypeMetrics(GetNetSSLVersion(ssl_));
1136
[email protected]8bd4e7a2014-08-09 14:49:171137 const CertStatus cert_status = server_cert_verify_result_.cert_status;
1138 if (transport_security_state_ &&
1139 (result == OK ||
1140 (IsCertificateError(result) && IsCertStatusMinorError(cert_status))) &&
1141 !transport_security_state_->CheckPublicKeyPins(
1142 host_and_port_.host(),
[email protected]8bd4e7a2014-08-09 14:49:171143 server_cert_verify_result_.is_issued_by_known_root,
1144 server_cert_verify_result_.public_key_hashes,
1145 &pinning_failure_log_)) {
1146 result = ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN;
1147 }
1148
[email protected]b9b651f2013-11-09 04:32:221149 if (result == OK) {
davidbeneb5f8ef32014-09-04 14:14:321150 // Only check Certificate Transparency if there were no other errors with
1151 // the connection.
1152 VerifyCT();
1153
[email protected]b9b651f2013-11-09 04:32:221154 // TODO(joth): Work out if we need to remember the intermediate CA certs
1155 // when the server sends them to us, and do so here.
[email protected]a8fed1742013-12-27 02:14:241156 SSLContext::GetInstance()->session_cache()->MarkSSLSessionAsGood(ssl_);
[email protected]e4738ba52014-08-07 10:07:221157 marked_session_as_good_ = true;
1158 CheckIfHandshakeFinished();
[email protected]b9b651f2013-11-09 04:32:221159 } else {
1160 DVLOG(1) << "DoVerifyCertComplete error " << ErrorToString(result)
1161 << " (" << result << ")";
1162 }
1163
[email protected]64b5c892014-08-08 09:39:261164 completed_connect_ = true;
[email protected]8bd4e7a2014-08-09 14:49:171165
[email protected]b9b651f2013-11-09 04:32:221166 // Exit DoHandshakeLoop and return the result to the caller to Connect.
1167 DCHECK_EQ(STATE_NONE, next_handshake_state_);
1168 return result;
1169}
1170
1171void SSLClientSocketOpenSSL::DoConnectCallback(int rv) {
[email protected]8e458552014-08-05 00:02:151172 if (rv < OK)
1173 OnHandshakeCompletion();
[email protected]b9b651f2013-11-09 04:32:221174 if (!user_connect_callback_.is_null()) {
1175 CompletionCallback c = user_connect_callback_;
1176 user_connect_callback_.Reset();
1177 c.Run(rv > OK ? OK : rv);
1178 }
1179}
1180
davidben30798ed82014-09-19 19:28:201181void SSLClientSocketOpenSSL::UpdateServerCert() {
[email protected]76e85392014-03-20 17:54:141182 server_cert_chain_->Reset(SSL_get_peer_cert_chain(ssl_));
[email protected]7f38da8a2014-03-17 16:44:261183 server_cert_ = server_cert_chain_->AsOSChain();
[email protected]76e85392014-03-20 17:54:141184
davidben30798ed82014-09-19 19:28:201185 if (server_cert_.get()) {
1186 net_log_.AddEvent(
1187 NetLog::TYPE_SSL_CERTIFICATES_RECEIVED,
1188 base::Bind(&NetLogX509CertificateCallback,
1189 base::Unretained(server_cert_.get())));
davidbend1fb2f12014-11-08 02:51:001190
1191 // TODO(rsleevi): Plumb an OCSP response into the Mac system library and
1192 // update IsOCSPStaplingSupported for Mac. https://crbug.com/430714
1193 if (IsOCSPStaplingSupported()) {
1194#if defined(OS_WIN)
davidben54015aa2014-12-02 22:16:231195 const uint8_t* ocsp_response_raw;
davidbend1fb2f12014-11-08 02:51:001196 size_t ocsp_response_len;
1197 SSL_get0_ocsp_response(ssl_, &ocsp_response_raw, &ocsp_response_len);
1198
1199 CRYPT_DATA_BLOB ocsp_response_blob;
1200 ocsp_response_blob.cbData = ocsp_response_len;
davidben54015aa2014-12-02 22:16:231201 ocsp_response_blob.pbData = const_cast<BYTE*>(ocsp_response_raw);
davidbend1fb2f12014-11-08 02:51:001202 BOOL ok = CertSetCertificateContextProperty(
1203 server_cert_->os_cert_handle(),
1204 CERT_OCSP_RESPONSE_PROP_ID,
1205 CERT_SET_PROPERTY_IGNORE_PERSIST_ERROR_FLAG,
1206 &ocsp_response_blob);
1207 if (!ok) {
1208 VLOG(1) << "Failed to set OCSP response property: "
1209 << GetLastError();
1210 }
1211#else
1212 NOTREACHED();
1213#endif
1214 }
davidben30798ed82014-09-19 19:28:201215 }
[email protected]b9b651f2013-11-09 04:32:221216}
1217
davidbeneb5f8ef32014-09-04 14:14:321218void SSLClientSocketOpenSSL::VerifyCT() {
1219 if (!cert_transparency_verifier_)
1220 return;
1221
davidben54015aa2014-12-02 22:16:231222 const uint8_t* ocsp_response_raw;
davidbeneb5f8ef32014-09-04 14:14:321223 size_t ocsp_response_len;
1224 SSL_get0_ocsp_response(ssl_, &ocsp_response_raw, &ocsp_response_len);
1225 std::string ocsp_response;
1226 if (ocsp_response_len > 0) {
1227 ocsp_response.assign(reinterpret_cast<const char*>(ocsp_response_raw),
1228 ocsp_response_len);
1229 }
1230
davidben54015aa2014-12-02 22:16:231231 const uint8_t* sct_list_raw;
davidbeneb5f8ef32014-09-04 14:14:321232 size_t sct_list_len;
1233 SSL_get0_signed_cert_timestamp_list(ssl_, &sct_list_raw, &sct_list_len);
1234 std::string sct_list;
1235 if (sct_list_len > 0)
1236 sct_list.assign(reinterpret_cast<const char*>(sct_list_raw), sct_list_len);
1237
1238 // Note that this is a completely synchronous operation: The CT Log Verifier
1239 // gets all the data it needs for SCT verification and does not do any
1240 // external communication.
eranm6571b2b2014-12-03 15:53:231241 cert_transparency_verifier_->Verify(
1242 server_cert_verify_result_.verified_cert.get(), ocsp_response, sct_list,
1243 &ct_verify_result_, net_log_);
davidbeneb5f8ef32014-09-04 14:14:321244
eranm6571b2b2014-12-03 15:53:231245 if (!policy_enforcer_) {
1246 server_cert_verify_result_.cert_status &= ~CERT_STATUS_IS_EV;
1247 } else {
1248 if (server_cert_verify_result_.cert_status & CERT_STATUS_IS_EV) {
1249 scoped_refptr<ct::EVCertsWhitelist> ev_whitelist =
1250 SSLConfigService::GetEVCertsWhitelist();
1251 if (!policy_enforcer_->DoesConformToCTEVPolicy(
1252 server_cert_verify_result_.verified_cert.get(),
1253 ev_whitelist.get(), ct_verify_result_)) {
1254 // TODO(eranm): Log via the BoundNetLog, see crbug.com/437766
1255 VLOG(1) << "EV certificate for "
1256 << server_cert_verify_result_.verified_cert->subject()
1257 .GetDisplayName()
1258 << " does not conform to CT policy, removing EV status.";
1259 server_cert_verify_result_.cert_status &= ~CERT_STATUS_IS_EV;
1260 }
1261 }
1262 }
davidbeneb5f8ef32014-09-04 14:14:321263}
1264
[email protected]b9b651f2013-11-09 04:32:221265void SSLClientSocketOpenSSL::OnHandshakeIOComplete(int result) {
1266 int rv = DoHandshakeLoop(result);
1267 if (rv != ERR_IO_PENDING) {
1268 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
1269 DoConnectCallback(rv);
1270 }
1271}
1272
1273void SSLClientSocketOpenSSL::OnSendComplete(int result) {
1274 if (next_handshake_state_ == STATE_HANDSHAKE) {
1275 // In handshake phase.
1276 OnHandshakeIOComplete(result);
1277 return;
1278 }
1279
1280 // OnSendComplete may need to call DoPayloadRead while the renegotiation
1281 // handshake is in progress.
1282 int rv_read = ERR_IO_PENDING;
1283 int rv_write = ERR_IO_PENDING;
1284 bool network_moved;
1285 do {
1286 if (user_read_buf_.get())
1287 rv_read = DoPayloadRead();
1288 if (user_write_buf_.get())
1289 rv_write = DoPayloadWrite();
1290 network_moved = DoTransportIO();
1291 } while (rv_read == ERR_IO_PENDING && rv_write == ERR_IO_PENDING &&
1292 (user_read_buf_.get() || user_write_buf_.get()) && network_moved);
1293
1294 // Performing the Read callback may cause |this| to be deleted. If this
1295 // happens, the Write callback should not be invoked. Guard against this by
1296 // holding a WeakPtr to |this| and ensuring it's still valid.
1297 base::WeakPtr<SSLClientSocketOpenSSL> guard(weak_factory_.GetWeakPtr());
1298 if (user_read_buf_.get() && rv_read != ERR_IO_PENDING)
1299 DoReadCallback(rv_read);
1300
1301 if (!guard.get())
1302 return;
1303
1304 if (user_write_buf_.get() && rv_write != ERR_IO_PENDING)
1305 DoWriteCallback(rv_write);
1306}
1307
1308void SSLClientSocketOpenSSL::OnRecvComplete(int result) {
1309 if (next_handshake_state_ == STATE_HANDSHAKE) {
1310 // In handshake phase.
1311 OnHandshakeIOComplete(result);
1312 return;
1313 }
1314
1315 // Network layer received some data, check if client requested to read
1316 // decrypted data.
1317 if (!user_read_buf_.get())
1318 return;
1319
davidben1b133ad2014-10-23 04:23:131320 int rv = DoReadLoop();
[email protected]b9b651f2013-11-09 04:32:221321 if (rv != ERR_IO_PENDING)
1322 DoReadCallback(rv);
1323}
1324
1325int SSLClientSocketOpenSSL::DoHandshakeLoop(int last_io_result) {
1326 int rv = last_io_result;
1327 do {
1328 // Default to STATE_NONE for next state.
1329 // (This is a quirk carried over from the windows
1330 // implementation. It makes reading the logs a bit harder.)
1331 // State handlers can and often do call GotoState just
1332 // to stay in the current state.
1333 State state = next_handshake_state_;
1334 GotoState(STATE_NONE);
1335 switch (state) {
1336 case STATE_HANDSHAKE:
1337 rv = DoHandshake();
1338 break;
[email protected]faff9852014-06-21 06:13:461339 case STATE_CHANNEL_ID_LOOKUP:
1340 DCHECK_EQ(OK, rv);
1341 rv = DoChannelIDLookup();
1342 break;
1343 case STATE_CHANNEL_ID_LOOKUP_COMPLETE:
1344 rv = DoChannelIDLookupComplete(rv);
1345 break;
[email protected]b9b651f2013-11-09 04:32:221346 case STATE_VERIFY_CERT:
[email protected]faff9852014-06-21 06:13:461347 DCHECK_EQ(OK, rv);
[email protected]b9b651f2013-11-09 04:32:221348 rv = DoVerifyCert(rv);
1349 break;
1350 case STATE_VERIFY_CERT_COMPLETE:
1351 rv = DoVerifyCertComplete(rv);
1352 break;
1353 case STATE_NONE:
1354 default:
1355 rv = ERR_UNEXPECTED;
1356 NOTREACHED() << "unexpected state" << state;
1357 break;
1358 }
1359
1360 bool network_moved = DoTransportIO();
1361 if (network_moved && next_handshake_state_ == STATE_HANDSHAKE) {
1362 // In general we exit the loop if rv is ERR_IO_PENDING. In this
1363 // special case we keep looping even if rv is ERR_IO_PENDING because
1364 // the transport IO may allow DoHandshake to make progress.
1365 rv = OK; // This causes us to stay in the loop.
1366 }
1367 } while (rv != ERR_IO_PENDING && next_handshake_state_ != STATE_NONE);
[email protected]8e458552014-08-05 00:02:151368
[email protected]b9b651f2013-11-09 04:32:221369 return rv;
1370}
1371
davidben1b133ad2014-10-23 04:23:131372int SSLClientSocketOpenSSL::DoReadLoop() {
[email protected]b9b651f2013-11-09 04:32:221373 bool network_moved;
1374 int rv;
1375 do {
1376 rv = DoPayloadRead();
1377 network_moved = DoTransportIO();
1378 } while (rv == ERR_IO_PENDING && network_moved);
1379
1380 return rv;
1381}
1382
davidben1b133ad2014-10-23 04:23:131383int SSLClientSocketOpenSSL::DoWriteLoop() {
[email protected]b9b651f2013-11-09 04:32:221384 bool network_moved;
1385 int rv;
1386 do {
1387 rv = DoPayloadWrite();
1388 network_moved = DoTransportIO();
1389 } while (rv == ERR_IO_PENDING && network_moved);
1390
1391 return rv;
1392}
1393
1394int SSLClientSocketOpenSSL::DoPayloadRead() {
1395 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1396
1397 int rv;
1398 if (pending_read_error_ != kNoPendingReadResult) {
1399 rv = pending_read_error_;
1400 pending_read_error_ = kNoPendingReadResult;
1401 if (rv == 0) {
1402 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED,
1403 rv, user_read_buf_->data());
davidbenb8c23212014-10-28 00:12:161404 } else {
1405 net_log_.AddEvent(
1406 NetLog::TYPE_SSL_READ_ERROR,
1407 CreateNetLogOpenSSLErrorCallback(rv, pending_read_ssl_error_,
1408 pending_read_error_info_));
[email protected]b9b651f2013-11-09 04:32:221409 }
davidbenb8c23212014-10-28 00:12:161410 pending_read_ssl_error_ = SSL_ERROR_NONE;
1411 pending_read_error_info_ = OpenSSLErrorInfo();
[email protected]b9b651f2013-11-09 04:32:221412 return rv;
1413 }
1414
1415 int total_bytes_read = 0;
1416 do {
1417 rv = SSL_read(ssl_, user_read_buf_->data() + total_bytes_read,
1418 user_read_buf_len_ - total_bytes_read);
1419 if (rv > 0)
1420 total_bytes_read += rv;
1421 } while (total_bytes_read < user_read_buf_len_ && rv > 0);
1422
1423 if (total_bytes_read == user_read_buf_len_) {
1424 rv = total_bytes_read;
1425 } else {
1426 // Otherwise, an error occurred (rv <= 0). The error needs to be handled
1427 // immediately, while the OpenSSL errors are still available in
1428 // thread-local storage. However, the handled/remapped error code should
1429 // only be returned if no application data was already read; if it was, the
1430 // error code should be deferred until the next call of DoPayloadRead.
1431 //
1432 // If no data was read, |*next_result| will point to the return value of
1433 // this function. If at least some data was read, |*next_result| will point
1434 // to |pending_read_error_|, to be returned in a future call to
1435 // DoPayloadRead() (e.g.: after the current data is handled).
1436 int *next_result = &rv;
1437 if (total_bytes_read > 0) {
1438 pending_read_error_ = rv;
1439 rv = total_bytes_read;
1440 next_result = &pending_read_error_;
1441 }
1442
1443 if (client_auth_cert_needed_) {
1444 *next_result = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
1445 } else if (*next_result < 0) {
davidbenb8c23212014-10-28 00:12:161446 pending_read_ssl_error_ = SSL_get_error(ssl_, *next_result);
1447 *next_result = MapOpenSSLErrorWithDetails(pending_read_ssl_error_,
1448 err_tracer,
1449 &pending_read_error_info_);
davidbenbe6ce7ec2014-10-20 19:15:561450
1451 // Many servers do not reliably send a close_notify alert when shutting
1452 // down a connection, and instead terminate the TCP connection. This is
1453 // reported as ERR_CONNECTION_CLOSED. Because of this, map the unclean
1454 // shutdown to a graceful EOF, instead of treating it as an error as it
1455 // should be.
1456 if (*next_result == ERR_CONNECTION_CLOSED)
1457 *next_result = 0;
1458
[email protected]b9b651f2013-11-09 04:32:221459 if (rv > 0 && *next_result == ERR_IO_PENDING) {
1460 // If at least some data was read from SSL_read(), do not treat
1461 // insufficient data as an error to return in the next call to
1462 // DoPayloadRead() - instead, let the call fall through to check
1463 // SSL_read() again. This is because DoTransportIO() may complete
1464 // in between the next call to DoPayloadRead(), and thus it is
1465 // important to check SSL_read() on subsequent invocations to see
1466 // if a complete record may now be read.
1467 *next_result = kNoPendingReadResult;
1468 }
1469 }
1470 }
1471
1472 if (rv >= 0) {
1473 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, rv,
1474 user_read_buf_->data());
davidbenb8c23212014-10-28 00:12:161475 } else if (rv != ERR_IO_PENDING) {
1476 net_log_.AddEvent(
1477 NetLog::TYPE_SSL_READ_ERROR,
1478 CreateNetLogOpenSSLErrorCallback(rv, pending_read_ssl_error_,
1479 pending_read_error_info_));
1480 pending_read_ssl_error_ = SSL_ERROR_NONE;
1481 pending_read_error_info_ = OpenSSLErrorInfo();
[email protected]b9b651f2013-11-09 04:32:221482 }
1483 return rv;
1484}
1485
1486int SSLClientSocketOpenSSL::DoPayloadWrite() {
1487 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1488 int rv = SSL_write(ssl_, user_write_buf_->data(), user_write_buf_len_);
[email protected]b9b651f2013-11-09 04:32:221489 if (rv >= 0) {
1490 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_SENT, rv,
1491 user_write_buf_->data());
1492 return rv;
1493 }
1494
davidbenb8c23212014-10-28 00:12:161495 int ssl_error = SSL_get_error(ssl_, rv);
1496 OpenSSLErrorInfo error_info;
1497 int net_error = MapOpenSSLErrorWithDetails(ssl_error, err_tracer,
1498 &error_info);
1499
1500 if (net_error != ERR_IO_PENDING) {
1501 net_log_.AddEvent(
1502 NetLog::TYPE_SSL_WRITE_ERROR,
1503 CreateNetLogOpenSSLErrorCallback(net_error, ssl_error, error_info));
1504 }
1505 return net_error;
[email protected]b9b651f2013-11-09 04:32:221506}
1507
1508int SSLClientSocketOpenSSL::BufferSend(void) {
1509 if (transport_send_busy_)
1510 return ERR_IO_PENDING;
1511
1512 if (!send_buffer_.get()) {
1513 // Get a fresh send buffer out of the send BIO.
[email protected]edfd0f42014-07-22 18:20:371514 size_t max_read = BIO_pending(transport_bio_);
[email protected]b9b651f2013-11-09 04:32:221515 if (!max_read)
1516 return 0; // Nothing pending in the OpenSSL write BIO.
1517 send_buffer_ = new DrainableIOBuffer(new IOBuffer(max_read), max_read);
1518 int read_bytes = BIO_read(transport_bio_, send_buffer_->data(), max_read);
1519 DCHECK_GT(read_bytes, 0);
1520 CHECK_EQ(static_cast<int>(max_read), read_bytes);
1521 }
1522
1523 int rv = transport_->socket()->Write(
1524 send_buffer_.get(),
1525 send_buffer_->BytesRemaining(),
1526 base::Bind(&SSLClientSocketOpenSSL::BufferSendComplete,
1527 base::Unretained(this)));
1528 if (rv == ERR_IO_PENDING) {
1529 transport_send_busy_ = true;
1530 } else {
1531 TransportWriteComplete(rv);
1532 }
1533 return rv;
1534}
1535
1536int SSLClientSocketOpenSSL::BufferRecv(void) {
1537 if (transport_recv_busy_)
1538 return ERR_IO_PENDING;
1539
1540 // Determine how much was requested from |transport_bio_| that was not
1541 // actually available.
1542 size_t requested = BIO_ctrl_get_read_request(transport_bio_);
1543 if (requested == 0) {
1544 // This is not a perfect match of error codes, as no operation is
1545 // actually pending. However, returning 0 would be interpreted as
1546 // a possible sign of EOF, which is also an inappropriate match.
1547 return ERR_IO_PENDING;
1548 }
1549
1550 // Known Issue: While only reading |requested| data is the more correct
1551 // implementation, it has the downside of resulting in frequent reads:
1552 // One read for the SSL record header (~5 bytes) and one read for the SSL
1553 // record body. Rather than issuing these reads to the underlying socket
1554 // (and constantly allocating new IOBuffers), a single Read() request to
1555 // fill |transport_bio_| is issued. As long as an SSL client socket cannot
1556 // be gracefully shutdown (via SSL close alerts) and re-used for non-SSL
1557 // traffic, this over-subscribed Read()ing will not cause issues.
1558 size_t max_write = BIO_ctrl_get_write_guarantee(transport_bio_);
1559 if (!max_write)
1560 return ERR_IO_PENDING;
1561
1562 recv_buffer_ = new IOBuffer(max_write);
1563 int rv = transport_->socket()->Read(
1564 recv_buffer_.get(),
1565 max_write,
1566 base::Bind(&SSLClientSocketOpenSSL::BufferRecvComplete,
1567 base::Unretained(this)));
1568 if (rv == ERR_IO_PENDING) {
1569 transport_recv_busy_ = true;
1570 } else {
[email protected]3e5c6922014-02-06 02:42:161571 rv = TransportReadComplete(rv);
[email protected]b9b651f2013-11-09 04:32:221572 }
1573 return rv;
1574}
1575
1576void SSLClientSocketOpenSSL::BufferSendComplete(int result) {
1577 transport_send_busy_ = false;
1578 TransportWriteComplete(result);
1579 OnSendComplete(result);
1580}
1581
1582void SSLClientSocketOpenSSL::BufferRecvComplete(int result) {
[email protected]3e5c6922014-02-06 02:42:161583 result = TransportReadComplete(result);
[email protected]b9b651f2013-11-09 04:32:221584 OnRecvComplete(result);
1585}
1586
1587void SSLClientSocketOpenSSL::TransportWriteComplete(int result) {
1588 DCHECK(ERR_IO_PENDING != result);
1589 if (result < 0) {
[email protected]5aea79182014-07-14 20:43:411590 // Record the error. Save it to be reported in a future read or write on
1591 // transport_bio_'s peer.
[email protected]3e5c6922014-02-06 02:42:161592 transport_write_error_ = result;
[email protected]b9b651f2013-11-09 04:32:221593 send_buffer_ = NULL;
1594 } else {
1595 DCHECK(send_buffer_.get());
1596 send_buffer_->DidConsume(result);
1597 DCHECK_GE(send_buffer_->BytesRemaining(), 0);
1598 if (send_buffer_->BytesRemaining() <= 0)
1599 send_buffer_ = NULL;
1600 }
1601}
1602
[email protected]3e5c6922014-02-06 02:42:161603int SSLClientSocketOpenSSL::TransportReadComplete(int result) {
[email protected]b9b651f2013-11-09 04:32:221604 DCHECK(ERR_IO_PENDING != result);
[email protected]5aea79182014-07-14 20:43:411605 // If an EOF, canonicalize to ERR_CONNECTION_CLOSED here so MapOpenSSLError
1606 // does not report success.
1607 if (result == 0)
1608 result = ERR_CONNECTION_CLOSED;
1609 if (result < 0) {
[email protected]b9b651f2013-11-09 04:32:221610 DVLOG(1) << "TransportReadComplete result " << result;
[email protected]5aea79182014-07-14 20:43:411611 // Received an error. Save it to be reported in a future read on
1612 // transport_bio_'s peer.
1613 transport_read_error_ = result;
[email protected]b9b651f2013-11-09 04:32:221614 } else {
1615 DCHECK(recv_buffer_.get());
1616 int ret = BIO_write(transport_bio_, recv_buffer_->data(), result);
1617 // A write into a memory BIO should always succeed.
[email protected]c8a80e92014-05-17 16:02:081618 DCHECK_EQ(result, ret);
[email protected]b9b651f2013-11-09 04:32:221619 }
1620 recv_buffer_ = NULL;
1621 transport_recv_busy_ = false;
[email protected]3e5c6922014-02-06 02:42:161622 return result;
[email protected]b9b651f2013-11-09 04:32:221623}
1624
[email protected]82c59022014-08-15 09:38:271625int SSLClientSocketOpenSSL::ClientCertRequestCallback(SSL* ssl) {
vadimtb2a77c762014-11-21 19:49:221626 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1627 tracked_objects::ScopedTracker tracking_profile(
1628 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1629 "424386 SSLClientSocketOpenSSL::ClientCertRequestCallback"));
1630
[email protected]5ac981e182010-12-06 17:56:271631 DVLOG(3) << "OpenSSL ClientCertRequestCallback called";
1632 DCHECK(ssl == ssl_);
[email protected]82c59022014-08-15 09:38:271633
davidbenaf42cbe2014-11-13 03:27:461634 net_log_.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED);
1635
[email protected]82c59022014-08-15 09:38:271636 // Clear any currently configured certificates.
1637 SSL_certs_clear(ssl_);
[email protected]97a854f2014-07-29 07:51:361638
1639#if defined(OS_IOS)
1640 // TODO(droger): Support client auth on iOS. See http://crbug.com/145954).
1641 LOG(WARNING) << "Client auth is not supported";
1642#else // !defined(OS_IOS)
[email protected]5ac981e182010-12-06 17:56:271643 if (!ssl_config_.send_client_cert) {
[email protected]515adc22013-01-09 16:01:231644 // First pass: we know that a client certificate is needed, but we do not
1645 // have one at hand.
[email protected]5ac981e182010-12-06 17:56:271646 client_auth_cert_needed_ = true;
[email protected]515adc22013-01-09 16:01:231647 STACK_OF(X509_NAME) *authorities = SSL_get_client_CA_list(ssl);
[email protected]edfd0f42014-07-22 18:20:371648 for (size_t i = 0; i < sk_X509_NAME_num(authorities); i++) {
[email protected]515adc22013-01-09 16:01:231649 X509_NAME *ca_name = (X509_NAME *)sk_X509_NAME_value(authorities, i);
1650 unsigned char* str = NULL;
1651 int length = i2d_X509_NAME(ca_name, &str);
1652 cert_authorities_.push_back(std::string(
1653 reinterpret_cast<const char*>(str),
1654 static_cast<size_t>(length)));
1655 OPENSSL_free(str);
1656 }
1657
[email protected]c0787702014-05-20 21:51:441658 const unsigned char* client_cert_types;
[email protected]e7e883e2014-07-25 06:03:081659 size_t num_client_cert_types =
1660 SSL_get0_certificate_types(ssl, &client_cert_types);
[email protected]c0787702014-05-20 21:51:441661 for (size_t i = 0; i < num_client_cert_types; i++) {
1662 cert_key_types_.push_back(
1663 static_cast<SSLClientCertType>(client_cert_types[i]));
1664 }
1665
[email protected]5ac981e182010-12-06 17:56:271666 return -1; // Suspends handshake.
1667 }
1668
1669 // Second pass: a client certificate should have been selected.
[email protected]13914c92013-06-13 22:42:421670 if (ssl_config_.client_cert.get()) {
[email protected]6bad5052014-07-12 01:25:131671 ScopedX509 leaf_x509 =
1672 OSCertHandleToOpenSSL(ssl_config_.client_cert->os_cert_handle());
1673 if (!leaf_x509) {
1674 LOG(WARNING) << "Failed to import certificate";
1675 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT);
1676 return -1;
1677 }
1678
[email protected]82c59022014-08-15 09:38:271679 ScopedX509Stack chain = OSCertHandlesToOpenSSL(
1680 ssl_config_.client_cert->GetIntermediateCertificates());
1681 if (!chain) {
1682 LOG(WARNING) << "Failed to import intermediate certificates";
1683 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT);
1684 return -1;
1685 }
1686
[email protected]97a854f2014-07-29 07:51:361687 // TODO(davidben): With Linux client auth support, this should be
1688 // conditioned on OS_ANDROID and then, with https://crbug.com/394131,
1689 // removed altogether. OpenSSLClientKeyStore is mostly an artifact of the
1690 // net/ client auth API lacking a private key handle.
[email protected]c0787702014-05-20 21:51:441691#if defined(USE_OPENSSL_CERTS)
[email protected]97a854f2014-07-29 07:51:361692 crypto::ScopedEVP_PKEY privkey =
1693 OpenSSLClientKeyStore::GetInstance()->FetchClientCertPrivateKey(
1694 ssl_config_.client_cert.get());
1695#else // !defined(USE_OPENSSL_CERTS)
1696 crypto::ScopedEVP_PKEY privkey =
1697 FetchClientCertPrivateKey(ssl_config_.client_cert.get());
1698#endif // defined(USE_OPENSSL_CERTS)
1699 if (!privkey) {
[email protected]6bad5052014-07-12 01:25:131700 // Could not find the private key. Fail the handshake and surface an
1701 // appropriate error to the caller.
1702 LOG(WARNING) << "Client cert found without private key";
1703 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY);
1704 return -1;
[email protected]0c6523f2010-12-10 10:56:241705 }
[email protected]6bad5052014-07-12 01:25:131706
[email protected]82c59022014-08-15 09:38:271707 if (!SSL_use_certificate(ssl_, leaf_x509.get()) ||
1708 !SSL_use_PrivateKey(ssl_, privkey.get()) ||
1709 !SSL_set1_chain(ssl_, chain.get())) {
1710 LOG(WARNING) << "Failed to set client certificate";
1711 return -1;
1712 }
davidbenaf42cbe2014-11-13 03:27:461713
1714 int cert_count = 1 + sk_X509_num(chain.get());
1715 net_log_.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED,
1716 NetLog::IntegerCallback("cert_count", cert_count));
[email protected]6bad5052014-07-12 01:25:131717 return 1;
[email protected]c0787702014-05-20 21:51:441718 }
[email protected]97a854f2014-07-29 07:51:361719#endif // defined(OS_IOS)
[email protected]5ac981e182010-12-06 17:56:271720
1721 // Send no client certificate.
davidbenaf42cbe2014-11-13 03:27:461722 net_log_.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED,
1723 NetLog::IntegerCallback("cert_count", 0));
[email protected]82c59022014-08-15 09:38:271724 return 1;
[email protected]5ac981e182010-12-06 17:56:271725}
1726
[email protected]b051cdb62014-02-28 02:20:161727int SSLClientSocketOpenSSL::CertVerifyCallback(X509_STORE_CTX* store_ctx) {
vadimtb2a77c762014-11-21 19:49:221728 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1729 tracked_objects::ScopedTracker tracking_profile(
1730 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1731 "424386 SSLClientSocketOpenSSL::CertVerifyCallback"));
1732
[email protected]64b5c892014-08-08 09:39:261733 if (!completed_connect_) {
[email protected]b051cdb62014-02-28 02:20:161734 // If the first handshake hasn't completed then we accept any certificates
1735 // because we verify after the handshake.
1736 return 1;
1737 }
1738
davidben30798ed82014-09-19 19:28:201739 // Disallow the server certificate to change in a renegotiation.
1740 if (server_cert_chain_->empty()) {
[email protected]76e85392014-03-20 17:54:141741 LOG(ERROR) << "Received invalid certificate chain between handshakes";
davidben30798ed82014-09-19 19:28:201742 return 0;
1743 }
1744 base::StringPiece old_der, new_der;
1745 if (store_ctx->cert == NULL ||
1746 !x509_util::GetDER(server_cert_chain_->Get(0), &old_der) ||
1747 !x509_util::GetDER(store_ctx->cert, &new_der)) {
1748 LOG(ERROR) << "Failed to encode certificates";
1749 return 0;
1750 }
1751 if (old_der != new_der) {
[email protected]76e85392014-03-20 17:54:141752 LOG(ERROR) << "Server certificate changed between handshakes";
davidben30798ed82014-09-19 19:28:201753 return 0;
1754 }
1755
1756 return 1;
[email protected]b051cdb62014-02-28 02:20:161757}
1758
[email protected]ae7c9f42011-11-21 11:41:161759// SelectNextProtoCallback is called by OpenSSL during the handshake. If the
1760// server supports NPN, selects a protocol from the list that the server
1761// provides. According to third_party/openssl/openssl/ssl/ssl_lib.c, the
1762// callback can assume that |in| is syntactically valid.
[email protected]ea4a1c6a2010-12-09 13:33:281763int SSLClientSocketOpenSSL::SelectNextProtoCallback(unsigned char** out,
1764 unsigned char* outlen,
1765 const unsigned char* in,
1766 unsigned int inlen) {
vadimtb2a77c762014-11-21 19:49:221767 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1768 tracked_objects::ScopedTracker tracking_profile(
1769 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1770 "424386 SSLClientSocketOpenSSL::SelectNextProtoCallback"));
1771
[email protected]ea4a1c6a2010-12-09 13:33:281772 if (ssl_config_.next_protos.empty()) {
[email protected]168a8412012-06-14 05:05:491773 *out = reinterpret_cast<uint8*>(
1774 const_cast<char*>(kDefaultSupportedNPNProtocol));
1775 *outlen = arraysize(kDefaultSupportedNPNProtocol) - 1;
1776 npn_status_ = kNextProtoUnsupported;
[email protected]ea4a1c6a2010-12-09 13:33:281777 return SSL_TLSEXT_ERR_OK;
1778 }
1779
[email protected]ae7c9f42011-11-21 11:41:161780 // Assume there's no overlap between our protocols and the server's list.
[email protected]168a8412012-06-14 05:05:491781 npn_status_ = kNextProtoNoOverlap;
[email protected]ae7c9f42011-11-21 11:41:161782
1783 // For each protocol in server preference order, see if we support it.
1784 for (unsigned int i = 0; i < inlen; i += in[i] + 1) {
bnc0d23cf42014-12-11 14:09:461785 for (NextProto next_proto : ssl_config_.next_protos) {
1786 const std::string proto = NextProtoToString(next_proto);
1787 if (in[i] == proto.size() &&
1788 memcmp(&in[i + 1], proto.data(), in[i]) == 0) {
[email protected]168a8412012-06-14 05:05:491789 // We found a match.
[email protected]ae7c9f42011-11-21 11:41:161790 *out = const_cast<unsigned char*>(in) + i + 1;
1791 *outlen = in[i];
[email protected]168a8412012-06-14 05:05:491792 npn_status_ = kNextProtoNegotiated;
[email protected]ae7c9f42011-11-21 11:41:161793 break;
1794 }
1795 }
[email protected]168a8412012-06-14 05:05:491796 if (npn_status_ == kNextProtoNegotiated)
[email protected]ae7c9f42011-11-21 11:41:161797 break;
1798 }
[email protected]ea4a1c6a2010-12-09 13:33:281799
[email protected]168a8412012-06-14 05:05:491800 // If we didn't find a protocol, we select the first one from our list.
1801 if (npn_status_ == kNextProtoNoOverlap) {
bnc0d23cf42014-12-11 14:09:461802 const std::string proto = NextProtoToString(ssl_config_.next_protos[0]);
1803 *out = reinterpret_cast<uint8*>(const_cast<char*>(proto.data()));
1804 *outlen = proto.size();
[email protected]168a8412012-06-14 05:05:491805 }
1806
[email protected]ea4a1c6a2010-12-09 13:33:281807 npn_proto_.assign(reinterpret_cast<const char*>(*out), *outlen);
[email protected]32e1dee2010-12-09 18:36:241808 DVLOG(2) << "next protocol: '" << npn_proto_ << "' status: " << npn_status_;
bnc0d28ea52014-10-13 15:15:381809 set_negotiation_extension(kExtensionNPN);
[email protected]ea4a1c6a2010-12-09 13:33:281810 return SSL_TLSEXT_ERR_OK;
1811}
1812
[email protected]5aea79182014-07-14 20:43:411813long SSLClientSocketOpenSSL::MaybeReplayTransportError(
1814 BIO *bio,
1815 int cmd,
1816 const char *argp, int argi, long argl,
1817 long retvalue) {
1818 if (cmd == (BIO_CB_READ|BIO_CB_RETURN) && retvalue <= 0) {
1819 // If there is no more data in the buffer, report any pending errors that
1820 // were observed. Note that both the readbuf and the writebuf are checked
1821 // for errors, since the application may have encountered a socket error
1822 // while writing that would otherwise not be reported until the application
1823 // attempted to write again - which it may never do. See
1824 // https://crbug.com/249848.
1825 if (transport_read_error_ != OK) {
1826 OpenSSLPutNetError(FROM_HERE, transport_read_error_);
1827 return -1;
1828 }
1829 if (transport_write_error_ != OK) {
1830 OpenSSLPutNetError(FROM_HERE, transport_write_error_);
1831 return -1;
1832 }
1833 } else if (cmd == BIO_CB_WRITE) {
1834 // Because of the write buffer, this reports a failure from the previous
1835 // write payload. If the current payload fails to write, the error will be
1836 // reported in a future write or read to |bio|.
1837 if (transport_write_error_ != OK) {
1838 OpenSSLPutNetError(FROM_HERE, transport_write_error_);
1839 return -1;
1840 }
1841 }
1842 return retvalue;
1843}
1844
1845// static
1846long SSLClientSocketOpenSSL::BIOCallback(
1847 BIO *bio,
1848 int cmd,
1849 const char *argp, int argi, long argl,
1850 long retvalue) {
1851 SSLClientSocketOpenSSL* socket = reinterpret_cast<SSLClientSocketOpenSSL*>(
1852 BIO_get_callback_arg(bio));
1853 CHECK(socket);
1854 return socket->MaybeReplayTransportError(
1855 bio, cmd, argp, argi, argl, retvalue);
1856}
1857
[email protected]64b5c892014-08-08 09:39:261858// static
1859void SSLClientSocketOpenSSL::InfoCallback(const SSL* ssl,
1860 int type,
1861 int /*val*/) {
1862 if (type == SSL_CB_HANDSHAKE_DONE) {
1863 SSLClientSocketOpenSSL* ssl_socket =
1864 SSLContext::GetInstance()->GetClientSocketFromSSL(ssl);
1865 ssl_socket->handshake_succeeded_ = true;
1866 ssl_socket->CheckIfHandshakeFinished();
1867 }
1868}
1869
1870// Determines if both the handshake and certificate verification have completed
1871// successfully, and calls the handshake completion callback if that is the
1872// case.
1873//
1874// CheckIfHandshakeFinished is called twice per connection: once after
1875// MarkSSLSessionAsGood, when the certificate has been verified, and
1876// once via an OpenSSL callback when the handshake has completed. On the
1877// second call, when the certificate has been verified and the handshake
1878// has completed, the connection's handshake completion callback is run.
1879void SSLClientSocketOpenSSL::CheckIfHandshakeFinished() {
1880 if (handshake_succeeded_ && marked_session_as_good_)
1881 OnHandshakeCompletion();
1882}
1883
davidbeneb5f8ef32014-09-04 14:14:321884void SSLClientSocketOpenSSL::AddSCTInfoToSSLInfo(SSLInfo* ssl_info) const {
1885 for (ct::SCTList::const_iterator iter =
1886 ct_verify_result_.verified_scts.begin();
1887 iter != ct_verify_result_.verified_scts.end(); ++iter) {
1888 ssl_info->signed_certificate_timestamps.push_back(
1889 SignedCertificateTimestampAndStatus(*iter, ct::SCT_STATUS_OK));
1890 }
1891 for (ct::SCTList::const_iterator iter =
1892 ct_verify_result_.invalid_scts.begin();
1893 iter != ct_verify_result_.invalid_scts.end(); ++iter) {
1894 ssl_info->signed_certificate_timestamps.push_back(
1895 SignedCertificateTimestampAndStatus(*iter, ct::SCT_STATUS_INVALID));
1896 }
1897 for (ct::SCTList::const_iterator iter =
1898 ct_verify_result_.unknown_logs_scts.begin();
1899 iter != ct_verify_result_.unknown_logs_scts.end(); ++iter) {
1900 ssl_info->signed_certificate_timestamps.push_back(
1901 SignedCertificateTimestampAndStatus(*iter,
1902 ct::SCT_STATUS_LOG_UNKNOWN));
1903 }
1904}
1905
[email protected]7f38da8a2014-03-17 16:44:261906scoped_refptr<X509Certificate>
1907SSLClientSocketOpenSSL::GetUnverifiedServerCertificateChain() const {
1908 return server_cert_;
1909}
1910
[email protected]7e5dd49f2010-12-08 18:33:491911} // namespace net