blob: aa45a9d3a830260837568207fbac8c666e25c01a [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"
davidben018aad62014-09-12 02:25:1920#include "base/strings/string_piece.h"
[email protected]20305ec2011-01-21 04:55:5221#include "base/synchronization/lock.h"
[email protected]ee0f2aa82013-10-25 11:59:2622#include "crypto/ec_private_key.h"
[email protected]4b559b4d2011-04-14 17:37:1423#include "crypto/openssl_util.h"
[email protected]cd9b75b2014-07-10 04:39:3824#include "crypto/scoped_openssl_types.h"
[email protected]d518cd92010-09-29 12:27:4425#include "net/base/net_errors.h"
[email protected]6e7845ae2013-03-29 21:48:1126#include "net/cert/cert_verifier.h"
davidbeneb5f8ef32014-09-04 14:14:3227#include "net/cert/ct_verifier.h"
[email protected]6e7845ae2013-03-29 21:48:1128#include "net/cert/single_request_cert_verifier.h"
29#include "net/cert/x509_certificate_net_log_param.h"
davidben30798ed82014-09-19 19:28:2030#include "net/cert/x509_util_openssl.h"
[email protected]8bd4e7a2014-08-09 14:49:1731#include "net/http/transport_security_state.h"
[email protected]1279de12013-12-03 15:13:3232#include "net/socket/ssl_session_cache_openssl.h"
[email protected]97a854f2014-07-29 07:51:3633#include "net/ssl/openssl_ssl_util.h"
[email protected]536fd0b2013-03-14 17:41:5734#include "net/ssl/ssl_cert_request_info.h"
35#include "net/ssl/ssl_connection_status_flags.h"
36#include "net/ssl/ssl_info.h"
[email protected]d518cd92010-09-29 12:27:4437
davidben8ecc3072014-09-03 23:19:0938#if defined(OS_WIN)
39#include "base/win/windows_version.h"
40#endif
41
[email protected]97a854f2014-07-29 07:51:3642#if defined(USE_OPENSSL_CERTS)
43#include "net/ssl/openssl_client_key_store.h"
44#else
45#include "net/ssl/openssl_platform_key.h"
46#endif
47
[email protected]d518cd92010-09-29 12:27:4448namespace net {
49
50namespace {
51
52// Enable this to see logging for state machine state transitions.
53#if 0
[email protected]3b112772010-10-04 10:54:4954#define GotoState(s) do { DVLOG(2) << (void *)this << " " << __FUNCTION__ << \
[email protected]d518cd92010-09-29 12:27:4455 " jump to state " << s; \
56 next_handshake_state_ = s; } while (0)
57#else
58#define GotoState(s) next_handshake_state_ = s
59#endif
60
[email protected]4b768562013-02-16 04:10:0761// This constant can be any non-negative/non-zero value (eg: it does not
62// overlap with any value of the net::Error range, including net::OK).
63const int kNoPendingReadResult = 1;
64
[email protected]168a8412012-06-14 05:05:4965// If a client doesn't have a list of protocols that it supports, but
66// the server supports NPN, choosing "http/1.1" is the best answer.
67const char kDefaultSupportedNPNProtocol[] = "http/1.1";
68
[email protected]82c59022014-08-15 09:38:2769void FreeX509Stack(STACK_OF(X509)* ptr) {
70 sk_X509_pop_free(ptr, X509_free);
71}
72
[email protected]6bad5052014-07-12 01:25:1373typedef crypto::ScopedOpenSSL<X509, X509_free>::Type ScopedX509;
[email protected]82c59022014-08-15 09:38:2774typedef crypto::ScopedOpenSSL<STACK_OF(X509), FreeX509Stack>::Type
75 ScopedX509Stack;
[email protected]6bad5052014-07-12 01:25:1376
[email protected]89038152012-09-07 06:30:1777#if OPENSSL_VERSION_NUMBER < 0x1000103fL
78// This method doesn't seem to have made it into the OpenSSL headers.
[email protected]109805a2010-12-07 18:17:0679unsigned long SSL_CIPHER_get_id(const SSL_CIPHER* cipher) { return cipher->id; }
[email protected]89038152012-09-07 06:30:1780#endif
[email protected]109805a2010-12-07 18:17:0681
82// Used for encoding the |connection_status| field of an SSLInfo object.
83int EncodeSSLConnectionStatus(int cipher_suite,
84 int compression,
85 int version) {
86 return ((cipher_suite & SSL_CONNECTION_CIPHERSUITE_MASK) <<
87 SSL_CONNECTION_CIPHERSUITE_SHIFT) |
88 ((compression & SSL_CONNECTION_COMPRESSION_MASK) <<
89 SSL_CONNECTION_COMPRESSION_SHIFT) |
90 ((version & SSL_CONNECTION_VERSION_MASK) <<
91 SSL_CONNECTION_VERSION_SHIFT);
92}
93
94// Returns the net SSL version number (see ssl_connection_status_flags.h) for
95// this SSL connection.
96int GetNetSSLVersion(SSL* ssl) {
[email protected]7e5dd49f2010-12-08 18:33:4997 switch (SSL_version(ssl)) {
[email protected]109805a2010-12-07 18:17:0698 case SSL2_VERSION:
99 return SSL_CONNECTION_VERSION_SSL2;
100 case SSL3_VERSION:
101 return SSL_CONNECTION_VERSION_SSL3;
102 case TLS1_VERSION:
103 return SSL_CONNECTION_VERSION_TLS1;
104 case 0x0302:
105 return SSL_CONNECTION_VERSION_TLS1_1;
106 case 0x0303:
107 return SSL_CONNECTION_VERSION_TLS1_2;
108 default:
109 return SSL_CONNECTION_VERSION_UNKNOWN;
110 }
111}
112
[email protected]6bad5052014-07-12 01:25:13113ScopedX509 OSCertHandleToOpenSSL(
114 X509Certificate::OSCertHandle os_handle) {
115#if defined(USE_OPENSSL_CERTS)
116 return ScopedX509(X509Certificate::DupOSCertHandle(os_handle));
117#else // !defined(USE_OPENSSL_CERTS)
118 std::string der_encoded;
119 if (!X509Certificate::GetDEREncoded(os_handle, &der_encoded))
120 return ScopedX509();
121 const uint8_t* bytes = reinterpret_cast<const uint8_t*>(der_encoded.data());
122 return ScopedX509(d2i_X509(NULL, &bytes, der_encoded.size()));
123#endif // defined(USE_OPENSSL_CERTS)
124}
125
[email protected]82c59022014-08-15 09:38:27126ScopedX509Stack OSCertHandlesToOpenSSL(
127 const X509Certificate::OSCertHandles& os_handles) {
128 ScopedX509Stack stack(sk_X509_new_null());
129 for (size_t i = 0; i < os_handles.size(); i++) {
130 ScopedX509 x509 = OSCertHandleToOpenSSL(os_handles[i]);
131 if (!x509)
132 return ScopedX509Stack();
133 sk_X509_push(stack.get(), x509.release());
134 }
135 return stack.Pass();
136}
137
davidben018aad62014-09-12 02:25:19138int LogErrorCallback(const char* str, size_t len, void* context) {
139 LOG(ERROR) << base::StringPiece(str, len);
140 return 1;
141}
142
[email protected]821e3bb2013-11-08 01:06:01143} // namespace
144
145class SSLClientSocketOpenSSL::SSLContext {
[email protected]fbef13932010-11-23 12:38:53146 public:
[email protected]b29af7d2010-12-14 11:52:47147 static SSLContext* GetInstance() { return Singleton<SSLContext>::get(); }
[email protected]fbef13932010-11-23 12:38:53148 SSL_CTX* ssl_ctx() { return ssl_ctx_.get(); }
[email protected]1279de12013-12-03 15:13:32149 SSLSessionCacheOpenSSL* session_cache() { return &session_cache_; }
[email protected]fbef13932010-11-23 12:38:53150
[email protected]1279de12013-12-03 15:13:32151 SSLClientSocketOpenSSL* GetClientSocketFromSSL(const SSL* ssl) {
[email protected]fbef13932010-11-23 12:38:53152 DCHECK(ssl);
153 SSLClientSocketOpenSSL* socket = static_cast<SSLClientSocketOpenSSL*>(
154 SSL_get_ex_data(ssl, ssl_socket_data_index_));
155 DCHECK(socket);
156 return socket;
157 }
158
159 bool SetClientSocketForSSL(SSL* ssl, SSLClientSocketOpenSSL* socket) {
160 return SSL_set_ex_data(ssl, ssl_socket_data_index_, socket) != 0;
161 }
162
163 private:
164 friend struct DefaultSingletonTraits<SSLContext>;
165
166 SSLContext() {
[email protected]4b559b4d2011-04-14 17:37:14167 crypto::EnsureOpenSSLInit();
[email protected]fbef13932010-11-23 12:38:53168 ssl_socket_data_index_ = SSL_get_ex_new_index(0, 0, 0, 0, 0);
169 DCHECK_NE(ssl_socket_data_index_, -1);
170 ssl_ctx_.reset(SSL_CTX_new(SSLv23_client_method()));
[email protected]1279de12013-12-03 15:13:32171 session_cache_.Reset(ssl_ctx_.get(), kDefaultSessionCacheConfig);
[email protected]b051cdb62014-02-28 02:20:16172 SSL_CTX_set_cert_verify_callback(ssl_ctx_.get(), CertVerifyCallback, NULL);
[email protected]82c59022014-08-15 09:38:27173 SSL_CTX_set_cert_cb(ssl_ctx_.get(), ClientCertRequestCallback, NULL);
[email protected]b051cdb62014-02-28 02:20:16174 SSL_CTX_set_verify(ssl_ctx_.get(), SSL_VERIFY_PEER, NULL);
[email protected]ea4a1c6a2010-12-09 13:33:28175 // TODO(kristianm): Only select this if ssl_config_.next_proto is not empty.
176 // It would be better if the callback were not a global setting,
177 // but that is an OpenSSL issue.
178 SSL_CTX_set_next_proto_select_cb(ssl_ctx_.get(), SelectNextProtoCallback,
179 NULL);
[email protected]edfd0f42014-07-22 18:20:37180 ssl_ctx_->tlsext_channel_id_enabled_new = 1;
davidben018aad62014-09-12 02:25:19181
182 scoped_ptr<base::Environment> env(base::Environment::Create());
183 std::string ssl_keylog_file;
184 if (env->GetVar("SSLKEYLOGFILE", &ssl_keylog_file) &&
185 !ssl_keylog_file.empty()) {
186 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
187 BIO* bio = BIO_new_file(ssl_keylog_file.c_str(), "a");
188 if (!bio) {
189 LOG(ERROR) << "Failed to open " << ssl_keylog_file;
190 ERR_print_errors_cb(&LogErrorCallback, NULL);
191 } else {
192 SSL_CTX_set_keylog_bio(ssl_ctx_.get(), bio);
193 }
194 }
[email protected]fbef13932010-11-23 12:38:53195 }
196
[email protected]1279de12013-12-03 15:13:32197 static std::string GetSessionCacheKey(const SSL* ssl) {
198 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
199 DCHECK(socket);
[email protected]8e458552014-08-05 00:02:15200 return socket->GetSessionCacheKey();
[email protected]fbef13932010-11-23 12:38:53201 }
202
[email protected]1279de12013-12-03 15:13:32203 static SSLSessionCacheOpenSSL::Config kDefaultSessionCacheConfig;
[email protected]fbef13932010-11-23 12:38:53204
[email protected]82c59022014-08-15 09:38:27205 static int ClientCertRequestCallback(SSL* ssl, void* arg) {
[email protected]b29af7d2010-12-14 11:52:47206 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
[email protected]82c59022014-08-15 09:38:27207 DCHECK(socket);
208 return socket->ClientCertRequestCallback(ssl);
[email protected]718c9672010-12-02 10:04:10209 }
210
[email protected]b051cdb62014-02-28 02:20:16211 static int CertVerifyCallback(X509_STORE_CTX *store_ctx, void *arg) {
212 SSL* ssl = reinterpret_cast<SSL*>(X509_STORE_CTX_get_ex_data(
213 store_ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
214 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
215 CHECK(socket);
216
217 return socket->CertVerifyCallback(store_ctx);
218 }
219
[email protected]ea4a1c6a2010-12-09 13:33:28220 static int SelectNextProtoCallback(SSL* ssl,
221 unsigned char** out, unsigned char* outlen,
222 const unsigned char* in,
223 unsigned int inlen, void* arg) {
[email protected]b29af7d2010-12-14 11:52:47224 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
[email protected]ea4a1c6a2010-12-09 13:33:28225 return socket->SelectNextProtoCallback(out, outlen, in, inlen);
226 }
227
[email protected]fbef13932010-11-23 12:38:53228 // This is the index used with SSL_get_ex_data to retrieve the owner
229 // SSLClientSocketOpenSSL object from an SSL instance.
230 int ssl_socket_data_index_;
231
[email protected]cd9b75b2014-07-10 04:39:38232 crypto::ScopedOpenSSL<SSL_CTX, SSL_CTX_free>::Type ssl_ctx_;
[email protected]1279de12013-12-03 15:13:32233 // |session_cache_| must be destroyed before |ssl_ctx_|.
234 SSLSessionCacheOpenSSL session_cache_;
235};
236
[email protected]7f38da8a2014-03-17 16:44:26237// PeerCertificateChain is a helper object which extracts the certificate
238// chain, as given by the server, from an OpenSSL socket and performs the needed
239// resource management. The first element of the chain is the leaf certificate
240// and the other elements are in the order given by the server.
241class SSLClientSocketOpenSSL::PeerCertificateChain {
242 public:
[email protected]76e85392014-03-20 17:54:14243 explicit PeerCertificateChain(STACK_OF(X509)* chain) { Reset(chain); }
[email protected]7f38da8a2014-03-17 16:44:26244 PeerCertificateChain(const PeerCertificateChain& other) { *this = other; }
245 ~PeerCertificateChain() {}
246 PeerCertificateChain& operator=(const PeerCertificateChain& other);
247
[email protected]76e85392014-03-20 17:54:14248 // Resets the PeerCertificateChain to the set of certificates in|chain|,
249 // which may be NULL, indicating to empty the store certificates.
250 // Note: If an error occurs, such as being unable to parse the certificates,
251 // this will behave as if Reset(NULL) was called.
252 void Reset(STACK_OF(X509)* chain);
253
[email protected]7f38da8a2014-03-17 16:44:26254 // Note that when USE_OPENSSL is defined, OSCertHandle is X509*
davidben30798ed82014-09-19 19:28:20255 scoped_refptr<X509Certificate> AsOSChain() const;
[email protected]7f38da8a2014-03-17 16:44:26256
257 size_t size() const {
258 if (!openssl_chain_.get())
259 return 0;
260 return sk_X509_num(openssl_chain_.get());
261 }
262
davidben30798ed82014-09-19 19:28:20263 bool empty() const {
264 return size() == 0;
265 }
266
267 X509* Get(size_t index) const {
[email protected]7f38da8a2014-03-17 16:44:26268 DCHECK_LT(index, size());
269 return sk_X509_value(openssl_chain_.get(), index);
270 }
271
[email protected]7f38da8a2014-03-17 16:44:26272 private:
[email protected]cd9b75b2014-07-10 04:39:38273 ScopedX509Stack openssl_chain_;
[email protected]7f38da8a2014-03-17 16:44:26274};
275
276SSLClientSocketOpenSSL::PeerCertificateChain&
277SSLClientSocketOpenSSL::PeerCertificateChain::operator=(
278 const PeerCertificateChain& other) {
279 if (this == &other)
280 return *this;
281
[email protected]24176af2014-08-14 09:31:04282 openssl_chain_.reset(X509_chain_up_ref(other.openssl_chain_.get()));
[email protected]7f38da8a2014-03-17 16:44:26283 return *this;
284}
285
[email protected]76e85392014-03-20 17:54:14286void SSLClientSocketOpenSSL::PeerCertificateChain::Reset(
287 STACK_OF(X509)* chain) {
davidben30798ed82014-09-19 19:28:20288 openssl_chain_.reset(chain ? X509_chain_up_ref(chain) : NULL);
[email protected]7f38da8a2014-03-17 16:44:26289}
[email protected]7f38da8a2014-03-17 16:44:26290
davidben30798ed82014-09-19 19:28:20291scoped_refptr<X509Certificate>
292SSLClientSocketOpenSSL::PeerCertificateChain::AsOSChain() const {
293#if defined(USE_OPENSSL_CERTS)
294 // When OSCertHandle is typedef'ed to X509, this implementation does a short
295 // cut to avoid converting back and forth between DER and the X509 struct.
296 X509Certificate::OSCertHandles intermediates;
297 for (size_t i = 1; i < sk_X509_num(openssl_chain_.get()); ++i) {
298 intermediates.push_back(sk_X509_value(openssl_chain_.get(), i));
299 }
[email protected]7f38da8a2014-03-17 16:44:26300
davidben30798ed82014-09-19 19:28:20301 return make_scoped_refptr(X509Certificate::CreateFromHandle(
302 sk_X509_value(openssl_chain_.get(), 0), intermediates));
303#else
304 // DER-encode the chain and convert to a platform certificate handle.
[email protected]7f38da8a2014-03-17 16:44:26305 std::vector<base::StringPiece> der_chain;
[email protected]edfd0f42014-07-22 18:20:37306 for (size_t i = 0; i < sk_X509_num(openssl_chain_.get()); ++i) {
[email protected]7f38da8a2014-03-17 16:44:26307 X509* x = sk_X509_value(openssl_chain_.get(), i);
davidben30798ed82014-09-19 19:28:20308 base::StringPiece der;
309 if (!x509_util::GetDER(x, &der))
310 return NULL;
311 der_chain.push_back(der);
[email protected]7f38da8a2014-03-17 16:44:26312 }
313
davidben30798ed82014-09-19 19:28:20314 return make_scoped_refptr(X509Certificate::CreateFromDERCertChain(der_chain));
315#endif
[email protected]7f38da8a2014-03-17 16:44:26316}
[email protected]7f38da8a2014-03-17 16:44:26317
[email protected]1279de12013-12-03 15:13:32318// static
319SSLSessionCacheOpenSSL::Config
320 SSLClientSocketOpenSSL::SSLContext::kDefaultSessionCacheConfig = {
321 &GetSessionCacheKey, // key_func
322 1024, // max_entries
323 256, // expiration_check_count
324 60 * 60, // timeout_seconds
[email protected]fbef13932010-11-23 12:38:53325};
[email protected]313834722010-11-17 09:57:18326
[email protected]c3456bb2011-12-12 22:22:19327// static
328void SSLClientSocket::ClearSessionCache() {
[email protected]821e3bb2013-11-08 01:06:01329 SSLClientSocketOpenSSL::SSLContext* context =
330 SSLClientSocketOpenSSL::SSLContext::GetInstance();
[email protected]c3456bb2011-12-12 22:22:19331 context->session_cache()->Flush();
332}
333
[email protected]d518cd92010-09-29 12:27:44334SSLClientSocketOpenSSL::SSLClientSocketOpenSSL(
[email protected]18ccfdb2013-08-15 00:13:44335 scoped_ptr<ClientSocketHandle> transport_socket,
[email protected]055d7f22010-11-15 12:03:12336 const HostPortPair& host_and_port,
[email protected]822581d2010-12-16 17:27:15337 const SSLConfig& ssl_config,
[email protected]feb79bcd2011-07-21 16:55:17338 const SSLClientSocketContext& context)
[email protected]83039bb2011-12-09 18:43:55339 : transport_send_busy_(false),
[email protected]d518cd92010-09-29 12:27:44340 transport_recv_busy_(false),
[email protected]4b768562013-02-16 04:10:07341 pending_read_error_(kNoPendingReadResult),
[email protected]5aea79182014-07-14 20:43:41342 transport_read_error_(OK),
[email protected]3e5c6922014-02-06 02:42:16343 transport_write_error_(OK),
[email protected]7f38da8a2014-03-17 16:44:26344 server_cert_chain_(new PeerCertificateChain(NULL)),
[email protected]64b5c892014-08-08 09:39:26345 completed_connect_(false),
[email protected]0dc88b32014-03-26 20:12:28346 was_ever_used_(false),
[email protected]d518cd92010-09-29 12:27:44347 client_auth_cert_needed_(false),
[email protected]feb79bcd2011-07-21 16:55:17348 cert_verifier_(context.cert_verifier),
davidbeneb5f8ef32014-09-04 14:14:32349 cert_transparency_verifier_(context.cert_transparency_verifier),
[email protected]6b8a3c742014-07-25 00:25:35350 channel_id_service_(context.channel_id_service),
[email protected]d518cd92010-09-29 12:27:44351 ssl_(NULL),
352 transport_bio_(NULL),
[email protected]18ccfdb2013-08-15 00:13:44353 transport_(transport_socket.Pass()),
[email protected]055d7f22010-11-15 12:03:12354 host_and_port_(host_and_port),
[email protected]d518cd92010-09-29 12:27:44355 ssl_config_(ssl_config),
[email protected]c3456bb2011-12-12 22:22:19356 ssl_session_cache_shard_(context.ssl_session_cache_shard),
[email protected]fbef13932010-11-23 12:38:53357 trying_cached_session_(false),
[email protected]013c17c2012-01-21 19:09:01358 next_handshake_state_(STATE_NONE),
[email protected]ea4a1c6a2010-12-09 13:33:28359 npn_status_(kNextProtoUnsupported),
[email protected]ee0f2aa82013-10-25 11:59:26360 channel_id_xtn_negotiated_(false),
[email protected]64b5c892014-08-08 09:39:26361 handshake_succeeded_(false),
[email protected]e4738ba52014-08-07 10:07:22362 marked_session_as_good_(false),
[email protected]8bd4e7a2014-08-09 14:49:17363 transport_security_state_(context.transport_security_state),
kulkarni.acd7b4462014-08-28 07:41:34364 net_log_(transport_->socket()->NetLog()),
365 weak_factory_(this) {
[email protected]8e458552014-08-05 00:02:15366}
[email protected]d518cd92010-09-29 12:27:44367
368SSLClientSocketOpenSSL::~SSLClientSocketOpenSSL() {
369 Disconnect();
370}
371
[email protected]cffd7f92014-08-21 21:30:50372std::string SSLClientSocketOpenSSL::GetSessionCacheKey() const {
373 std::string result = host_and_port_.ToString();
374 result.append("/");
375 result.append(ssl_session_cache_shard_);
376 return result;
377}
378
[email protected]8e458552014-08-05 00:02:15379bool SSLClientSocketOpenSSL::InSessionCache() const {
380 SSLContext* context = SSLContext::GetInstance();
381 std::string cache_key = GetSessionCacheKey();
382 return context->session_cache()->SSLSessionIsInCache(cache_key);
383}
384
385void SSLClientSocketOpenSSL::SetHandshakeCompletionCallback(
386 const base::Closure& callback) {
387 handshake_completion_callback_ = callback;
388}
389
[email protected]b9b651f2013-11-09 04:32:22390void SSLClientSocketOpenSSL::GetSSLCertRequestInfo(
391 SSLCertRequestInfo* cert_request_info) {
[email protected]791879c2013-12-17 07:22:41392 cert_request_info->host_and_port = host_and_port_;
[email protected]b9b651f2013-11-09 04:32:22393 cert_request_info->cert_authorities = cert_authorities_;
[email protected]c0787702014-05-20 21:51:44394 cert_request_info->cert_key_types = cert_key_types_;
[email protected]b9b651f2013-11-09 04:32:22395}
396
397SSLClientSocket::NextProtoStatus SSLClientSocketOpenSSL::GetNextProto(
[email protected]abc44b752014-07-30 03:52:15398 std::string* proto) {
[email protected]b9b651f2013-11-09 04:32:22399 *proto = npn_proto_;
[email protected]b9b651f2013-11-09 04:32:22400 return npn_status_;
401}
402
[email protected]6b8a3c742014-07-25 00:25:35403ChannelIDService*
404SSLClientSocketOpenSSL::GetChannelIDService() const {
405 return channel_id_service_;
[email protected]b9b651f2013-11-09 04:32:22406}
407
408int SSLClientSocketOpenSSL::ExportKeyingMaterial(
409 const base::StringPiece& label,
410 bool has_context, const base::StringPiece& context,
411 unsigned char* out, unsigned int outlen) {
412 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
413
414 int rv = SSL_export_keying_material(
[email protected]c8a80e92014-05-17 16:02:08415 ssl_, out, outlen, label.data(), label.size(),
416 reinterpret_cast<const unsigned char*>(context.data()),
417 context.length(), context.length() > 0);
[email protected]b9b651f2013-11-09 04:32:22418
419 if (rv != 1) {
420 int ssl_error = SSL_get_error(ssl_, rv);
421 LOG(ERROR) << "Failed to export keying material;"
422 << " returned " << rv
423 << ", SSL error code " << ssl_error;
424 return MapOpenSSLError(ssl_error, err_tracer);
425 }
426 return OK;
427}
428
429int SSLClientSocketOpenSSL::GetTLSUniqueChannelBinding(std::string* out) {
[email protected]c8a80e92014-05-17 16:02:08430 NOTIMPLEMENTED();
[email protected]b9b651f2013-11-09 04:32:22431 return ERR_NOT_IMPLEMENTED;
432}
433
434int SSLClientSocketOpenSSL::Connect(const CompletionCallback& callback) {
[email protected]8bd4e7a2014-08-09 14:49:17435 // It is an error to create an SSLClientSocket whose context has no
436 // TransportSecurityState.
437 DCHECK(transport_security_state_);
438
[email protected]b9b651f2013-11-09 04:32:22439 net_log_.BeginEvent(NetLog::TYPE_SSL_CONNECT);
440
441 // Set up new ssl object.
[email protected]c8a80e92014-05-17 16:02:08442 int rv = Init();
443 if (rv != OK) {
444 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
445 return rv;
[email protected]b9b651f2013-11-09 04:32:22446 }
447
448 // Set SSL to client mode. Handshake happens in the loop below.
449 SSL_set_connect_state(ssl_);
450
451 GotoState(STATE_HANDSHAKE);
[email protected]c8a80e92014-05-17 16:02:08452 rv = DoHandshakeLoop(OK);
[email protected]b9b651f2013-11-09 04:32:22453 if (rv == ERR_IO_PENDING) {
454 user_connect_callback_ = callback;
455 } else {
456 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
[email protected]8e458552014-08-05 00:02:15457 if (rv < OK)
458 OnHandshakeCompletion();
[email protected]b9b651f2013-11-09 04:32:22459 }
460
461 return rv > OK ? OK : rv;
462}
463
464void SSLClientSocketOpenSSL::Disconnect() {
[email protected]8e458552014-08-05 00:02:15465 // If a handshake was pending (Connect() had been called), notify interested
466 // parties that it's been aborted now. If the handshake had already
467 // completed, this is a no-op.
468 OnHandshakeCompletion();
[email protected]b9b651f2013-11-09 04:32:22469 if (ssl_) {
470 // Calling SSL_shutdown prevents the session from being marked as
471 // unresumable.
472 SSL_shutdown(ssl_);
473 SSL_free(ssl_);
474 ssl_ = NULL;
475 }
476 if (transport_bio_) {
477 BIO_free_all(transport_bio_);
478 transport_bio_ = NULL;
479 }
480
481 // Shut down anything that may call us back.
482 verifier_.reset();
483 transport_->socket()->Disconnect();
484
485 // Null all callbacks, delete all buffers.
486 transport_send_busy_ = false;
487 send_buffer_ = NULL;
488 transport_recv_busy_ = false;
[email protected]b9b651f2013-11-09 04:32:22489 recv_buffer_ = NULL;
490
491 user_connect_callback_.Reset();
492 user_read_callback_.Reset();
493 user_write_callback_.Reset();
494 user_read_buf_ = NULL;
495 user_read_buf_len_ = 0;
496 user_write_buf_ = NULL;
497 user_write_buf_len_ = 0;
498
[email protected]3e5c6922014-02-06 02:42:16499 pending_read_error_ = kNoPendingReadResult;
[email protected]5aea79182014-07-14 20:43:41500 transport_read_error_ = OK;
[email protected]3e5c6922014-02-06 02:42:16501 transport_write_error_ = OK;
502
[email protected]b9b651f2013-11-09 04:32:22503 server_cert_verify_result_.Reset();
[email protected]64b5c892014-08-08 09:39:26504 completed_connect_ = false;
[email protected]b9b651f2013-11-09 04:32:22505
506 cert_authorities_.clear();
[email protected]c0787702014-05-20 21:51:44507 cert_key_types_.clear();
[email protected]b9b651f2013-11-09 04:32:22508 client_auth_cert_needed_ = false;
[email protected]faff9852014-06-21 06:13:46509
davidben09c3d072014-08-25 20:33:58510 start_cert_verification_time_ = base::TimeTicks();
511
[email protected]abc44b752014-07-30 03:52:15512 npn_status_ = kNextProtoUnsupported;
513 npn_proto_.clear();
514
[email protected]faff9852014-06-21 06:13:46515 channel_id_xtn_negotiated_ = false;
516 channel_id_request_handle_.Cancel();
[email protected]b9b651f2013-11-09 04:32:22517}
518
519bool SSLClientSocketOpenSSL::IsConnected() const {
520 // If the handshake has not yet completed.
[email protected]64b5c892014-08-08 09:39:26521 if (!completed_connect_)
[email protected]b9b651f2013-11-09 04:32:22522 return false;
523 // If an asynchronous operation is still pending.
524 if (user_read_buf_.get() || user_write_buf_.get())
525 return true;
526
527 return transport_->socket()->IsConnected();
528}
529
530bool SSLClientSocketOpenSSL::IsConnectedAndIdle() const {
531 // If the handshake has not yet completed.
[email protected]64b5c892014-08-08 09:39:26532 if (!completed_connect_)
[email protected]b9b651f2013-11-09 04:32:22533 return false;
534 // If an asynchronous operation is still pending.
535 if (user_read_buf_.get() || user_write_buf_.get())
536 return false;
537 // If there is data waiting to be sent, or data read from the network that
538 // has not yet been consumed.
[email protected]edfd0f42014-07-22 18:20:37539 if (BIO_pending(transport_bio_) > 0 ||
540 BIO_wpending(transport_bio_) > 0) {
[email protected]b9b651f2013-11-09 04:32:22541 return false;
542 }
543
544 return transport_->socket()->IsConnectedAndIdle();
545}
546
547int SSLClientSocketOpenSSL::GetPeerAddress(IPEndPoint* addressList) const {
548 return transport_->socket()->GetPeerAddress(addressList);
549}
550
551int SSLClientSocketOpenSSL::GetLocalAddress(IPEndPoint* addressList) const {
552 return transport_->socket()->GetLocalAddress(addressList);
553}
554
555const BoundNetLog& SSLClientSocketOpenSSL::NetLog() const {
556 return net_log_;
557}
558
559void SSLClientSocketOpenSSL::SetSubresourceSpeculation() {
560 if (transport_.get() && transport_->socket()) {
561 transport_->socket()->SetSubresourceSpeculation();
562 } else {
563 NOTREACHED();
564 }
565}
566
567void SSLClientSocketOpenSSL::SetOmniboxSpeculation() {
568 if (transport_.get() && transport_->socket()) {
569 transport_->socket()->SetOmniboxSpeculation();
570 } else {
571 NOTREACHED();
572 }
573}
574
575bool SSLClientSocketOpenSSL::WasEverUsed() const {
[email protected]0dc88b32014-03-26 20:12:28576 return was_ever_used_;
[email protected]b9b651f2013-11-09 04:32:22577}
578
579bool SSLClientSocketOpenSSL::UsingTCPFastOpen() const {
580 if (transport_.get() && transport_->socket())
581 return transport_->socket()->UsingTCPFastOpen();
582
583 NOTREACHED();
584 return false;
585}
586
587bool SSLClientSocketOpenSSL::GetSSLInfo(SSLInfo* ssl_info) {
588 ssl_info->Reset();
davidben30798ed82014-09-19 19:28:20589 if (server_cert_chain_->empty())
[email protected]b9b651f2013-11-09 04:32:22590 return false;
591
592 ssl_info->cert = server_cert_verify_result_.verified_cert;
593 ssl_info->cert_status = server_cert_verify_result_.cert_status;
594 ssl_info->is_issued_by_known_root =
595 server_cert_verify_result_.is_issued_by_known_root;
596 ssl_info->public_key_hashes =
597 server_cert_verify_result_.public_key_hashes;
598 ssl_info->client_cert_sent =
599 ssl_config_.send_client_cert && ssl_config_.client_cert.get();
600 ssl_info->channel_id_sent = WasChannelIDSent();
[email protected]8bd4e7a2014-08-09 14:49:17601 ssl_info->pinning_failure_log = pinning_failure_log_;
[email protected]b9b651f2013-11-09 04:32:22602
davidbeneb5f8ef32014-09-04 14:14:32603 AddSCTInfoToSSLInfo(ssl_info);
604
[email protected]b9b651f2013-11-09 04:32:22605 const SSL_CIPHER* cipher = SSL_get_current_cipher(ssl_);
606 CHECK(cipher);
607 ssl_info->security_bits = SSL_CIPHER_get_bits(cipher, NULL);
[email protected]b9b651f2013-11-09 04:32:22608
609 ssl_info->connection_status = EncodeSSLConnectionStatus(
[email protected]edfd0f42014-07-22 18:20:37610 SSL_CIPHER_get_id(cipher), 0 /* no compression */,
[email protected]b9b651f2013-11-09 04:32:22611 GetNetSSLVersion(ssl_));
612
davidben09c3d072014-08-25 20:33:58613 if (!SSL_get_secure_renegotiation_support(ssl_))
[email protected]b9b651f2013-11-09 04:32:22614 ssl_info->connection_status |= SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION;
[email protected]b9b651f2013-11-09 04:32:22615
616 if (ssl_config_.version_fallback)
617 ssl_info->connection_status |= SSL_CONNECTION_VERSION_FALLBACK;
618
619 ssl_info->handshake_type = SSL_session_reused(ssl_) ?
620 SSLInfo::HANDSHAKE_RESUME : SSLInfo::HANDSHAKE_FULL;
621
622 DVLOG(3) << "Encoded connection status: cipher suite = "
623 << SSLConnectionStatusToCipherSuite(ssl_info->connection_status)
624 << " version = "
625 << SSLConnectionStatusToVersion(ssl_info->connection_status);
626 return true;
627}
628
629int SSLClientSocketOpenSSL::Read(IOBuffer* buf,
630 int buf_len,
631 const CompletionCallback& callback) {
632 user_read_buf_ = buf;
633 user_read_buf_len_ = buf_len;
634
635 int rv = DoReadLoop(OK);
636
637 if (rv == ERR_IO_PENDING) {
638 user_read_callback_ = callback;
639 } else {
[email protected]0dc88b32014-03-26 20:12:28640 if (rv > 0)
641 was_ever_used_ = true;
[email protected]b9b651f2013-11-09 04:32:22642 user_read_buf_ = NULL;
643 user_read_buf_len_ = 0;
[email protected]8e458552014-08-05 00:02:15644 if (rv <= 0) {
645 // Failure of a read attempt may indicate a failed false start
646 // connection.
647 OnHandshakeCompletion();
648 }
[email protected]b9b651f2013-11-09 04:32:22649 }
650
651 return rv;
652}
653
654int SSLClientSocketOpenSSL::Write(IOBuffer* buf,
655 int buf_len,
656 const CompletionCallback& callback) {
657 user_write_buf_ = buf;
658 user_write_buf_len_ = buf_len;
659
660 int rv = DoWriteLoop(OK);
661
662 if (rv == ERR_IO_PENDING) {
663 user_write_callback_ = callback;
664 } else {
[email protected]0dc88b32014-03-26 20:12:28665 if (rv > 0)
666 was_ever_used_ = true;
[email protected]b9b651f2013-11-09 04:32:22667 user_write_buf_ = NULL;
668 user_write_buf_len_ = 0;
[email protected]8e458552014-08-05 00:02:15669 if (rv < 0) {
670 // Failure of a write attempt may indicate a failed false start
671 // connection.
672 OnHandshakeCompletion();
673 }
[email protected]b9b651f2013-11-09 04:32:22674 }
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
[email protected]e4738ba52014-08-07 10:07:22701 // Set an OpenSSL callback to monitor this SSL*'s connection.
702 SSL_set_info_callback(ssl_, &InfoCallback);
703
[email protected]1279de12013-12-03 15:13:32704 trying_cached_session_ = context->session_cache()->SetSSLSessionWithKey(
[email protected]8e458552014-08-05 00:02:15705 ssl_, GetSessionCacheKey());
[email protected]d518cd92010-09-29 12:27:44706
707 BIO* ssl_bio = NULL;
[email protected]fbef13932010-11-23 12:38:53708 // 0 => use default buffer sizes.
709 if (!BIO_new_bio_pair(&ssl_bio, 0, &transport_bio_, 0))
[email protected]c8a80e92014-05-17 16:02:08710 return ERR_UNEXPECTED;
[email protected]d518cd92010-09-29 12:27:44711 DCHECK(ssl_bio);
712 DCHECK(transport_bio_);
713
[email protected]5aea79182014-07-14 20:43:41714 // Install a callback on OpenSSL's end to plumb transport errors through.
[email protected]64b5c892014-08-08 09:39:26715 BIO_set_callback(ssl_bio, BIOCallback);
[email protected]5aea79182014-07-14 20:43:41716 BIO_set_callback_arg(ssl_bio, reinterpret_cast<char*>(this));
717
[email protected]d518cd92010-09-29 12:27:44718 SSL_set_bio(ssl_, ssl_bio, ssl_bio);
719
[email protected]9e733f32010-10-04 18:19:08720 // OpenSSL defaults some options to on, others to off. To avoid ambiguity,
721 // set everything we care about to an absolute value.
[email protected]fb10e2282010-12-01 17:08:48722 SslSetClearMask options;
723 options.ConfigureFlag(SSL_OP_NO_SSLv2, true);
[email protected]80c75f682012-05-26 16:22:17724 bool ssl3_enabled = (ssl_config_.version_min == SSL_PROTOCOL_VERSION_SSL3);
725 options.ConfigureFlag(SSL_OP_NO_SSLv3, !ssl3_enabled);
726 bool tls1_enabled = (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1 &&
727 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1);
728 options.ConfigureFlag(SSL_OP_NO_TLSv1, !tls1_enabled);
[email protected]80c75f682012-05-26 16:22:17729 bool tls1_1_enabled =
730 (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1_1 &&
731 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1_1);
732 options.ConfigureFlag(SSL_OP_NO_TLSv1_1, !tls1_1_enabled);
[email protected]80c75f682012-05-26 16:22:17733 bool tls1_2_enabled =
734 (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1_2 &&
735 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1_2);
736 options.ConfigureFlag(SSL_OP_NO_TLSv1_2, !tls1_2_enabled);
[email protected]fb10e2282010-12-01 17:08:48737
[email protected]d0f00492012-08-03 22:35:13738 options.ConfigureFlag(SSL_OP_NO_COMPRESSION, true);
[email protected]9e733f32010-10-04 18:19:08739
740 // TODO(joth): Set this conditionally, see http://crbug.com/55410
[email protected]fb10e2282010-12-01 17:08:48741 options.ConfigureFlag(SSL_OP_LEGACY_SERVER_CONNECT, true);
[email protected]9e733f32010-10-04 18:19:08742
[email protected]fb10e2282010-12-01 17:08:48743 SSL_set_options(ssl_, options.set_mask);
744 SSL_clear_options(ssl_, options.clear_mask);
[email protected]9e733f32010-10-04 18:19:08745
[email protected]fb10e2282010-12-01 17:08:48746 // Same as above, this time for the SSL mode.
747 SslSetClearMask mode;
[email protected]9e733f32010-10-04 18:19:08748
[email protected]fb10e2282010-12-01 17:08:48749 mode.ConfigureFlag(SSL_MODE_RELEASE_BUFFERS, true);
ishermane5c05e12014-09-09 20:32:15750 mode.ConfigureFlag(SSL_MODE_CBC_RECORD_SPLITTING, true);
[email protected]fb10e2282010-12-01 17:08:48751
[email protected]b788de02014-04-23 18:06:07752 mode.ConfigureFlag(SSL_MODE_HANDSHAKE_CUTTHROUGH,
753 ssl_config_.false_start_enabled);
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.
767 std::string command("DEFAULT:!NULL:!aNULL:!IDEA:!FZA:!SRP:!SHA256:!SHA384:"
768 "!aECDH:!AESGCM+AES256");
[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);
773 const uint16 id = SSL_CIPHER_get_id(cipher);
774 // 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
793 // Disable ECDSA cipher suites on platforms that do not support ECDSA
794 // signed certificates, as servers may use the presence of such
795 // ciphersuites as a hint to send an ECDSA certificate.
796#if defined(OS_WIN)
797 if (base::win::GetVersion() < base::win::VERSION_VISTA)
798 command.append(":!ECDSA");
799#endif
800
[email protected]109805a2010-12-07 18:17:06801 int rv = SSL_set_cipher_list(ssl_, command.c_str());
802 // If this fails (rv = 0) it means there are no ciphers enabled on this SSL.
803 // This will almost certainly result in the socket failing to complete the
804 // handshake at which point the appropriate error is bubbled up to the client.
805 LOG_IF(WARNING, rv != 1) << "SSL_set_cipher_list('" << command << "') "
806 "returned " << rv;
[email protected]ee0f2aa82013-10-25 11:59:26807
[email protected]0d0a6872014-07-26 18:05:11808 if (ssl_config_.version_fallback)
809 SSL_enable_fallback_scsv(ssl_);
810
[email protected]ee0f2aa82013-10-25 11:59:26811 // 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()) {
817 std::vector<uint8_t> wire_protos =
818 SerializeNextProtos(ssl_config_.next_protos);
819 SSL_set_alpn_protos(ssl_, wire_protos.empty() ? NULL : &wire_protos[0],
820 wire_protos.size());
821 }
822
davidbeneb5f8ef32014-09-04 14:14:32823 if (ssl_config_.signed_cert_timestamps_enabled) {
824 SSL_enable_signed_cert_timestamps(ssl_);
825 SSL_enable_ocsp_stapling(ssl_);
826 }
827
828 // TODO(davidben): Enable OCSP stapling on platforms which support it and pass
829 // into the certificate verifier. https://crbug.com/398677
830
[email protected]c8a80e92014-05-17 16:02:08831 return OK;
[email protected]d518cd92010-09-29 12:27:44832}
833
[email protected]b9b651f2013-11-09 04:32:22834void SSLClientSocketOpenSSL::DoReadCallback(int rv) {
835 // Since Run may result in Read being called, clear |user_read_callback_|
836 // up front.
[email protected]0dc88b32014-03-26 20:12:28837 if (rv > 0)
838 was_ever_used_ = true;
[email protected]b9b651f2013-11-09 04:32:22839 user_read_buf_ = NULL;
840 user_read_buf_len_ = 0;
[email protected]8e458552014-08-05 00:02:15841 if (rv <= 0) {
842 // Failure of a read attempt may indicate a failed false start
843 // connection.
844 OnHandshakeCompletion();
845 }
[email protected]b9b651f2013-11-09 04:32:22846 base::ResetAndReturn(&user_read_callback_).Run(rv);
847}
848
849void SSLClientSocketOpenSSL::DoWriteCallback(int rv) {
850 // Since Run may result in Write being called, clear |user_write_callback_|
851 // up front.
[email protected]0dc88b32014-03-26 20:12:28852 if (rv > 0)
853 was_ever_used_ = true;
[email protected]b9b651f2013-11-09 04:32:22854 user_write_buf_ = NULL;
855 user_write_buf_len_ = 0;
[email protected]8e458552014-08-05 00:02:15856 if (rv < 0) {
857 // Failure of a write attempt may indicate a failed false start
858 // connection.
859 OnHandshakeCompletion();
860 }
[email protected]b9b651f2013-11-09 04:32:22861 base::ResetAndReturn(&user_write_callback_).Run(rv);
862}
863
[email protected]8e458552014-08-05 00:02:15864void SSLClientSocketOpenSSL::OnHandshakeCompletion() {
865 if (!handshake_completion_callback_.is_null())
866 base::ResetAndReturn(&handshake_completion_callback_).Run();
867}
868
[email protected]b9b651f2013-11-09 04:32:22869bool SSLClientSocketOpenSSL::DoTransportIO() {
870 bool network_moved = false;
871 int rv;
872 // Read and write as much data as possible. The loop is necessary because
873 // Write() may return synchronously.
874 do {
875 rv = BufferSend();
876 if (rv != ERR_IO_PENDING && rv != 0)
877 network_moved = true;
878 } while (rv > 0);
[email protected]5aea79182014-07-14 20:43:41879 if (transport_read_error_ == OK && BufferRecv() != ERR_IO_PENDING)
[email protected]b9b651f2013-11-09 04:32:22880 network_moved = true;
881 return network_moved;
882}
883
884int SSLClientSocketOpenSSL::DoHandshake() {
885 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
[email protected]c8a80e92014-05-17 16:02:08886 int net_error = OK;
[email protected]b9b651f2013-11-09 04:32:22887 int rv = SSL_do_handshake(ssl_);
888
889 if (client_auth_cert_needed_) {
890 net_error = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
891 // If the handshake already succeeded (because the server requests but
892 // doesn't require a client cert), we need to invalidate the SSL session
893 // so that we won't try to resume the non-client-authenticated session in
894 // the next handshake. This will cause the server to ask for a client
895 // cert again.
896 if (rv == 1) {
897 // Remove from session cache but don't clear this connection.
898 SSL_SESSION* session = SSL_get_session(ssl_);
899 if (session) {
900 int rv = SSL_CTX_remove_session(SSL_get_SSL_CTX(ssl_), session);
901 LOG_IF(WARNING, !rv) << "Couldn't invalidate SSL session: " << session;
902 }
903 }
904 } else if (rv == 1) {
905 if (trying_cached_session_ && logging::DEBUG_MODE) {
906 DVLOG(2) << "Result of session reuse for " << host_and_port_.ToString()
907 << " is: " << (SSL_session_reused(ssl_) ? "Success" : "Fail");
908 }
[email protected]abc44b752014-07-30 03:52:15909
910 // SSL handshake is completed. If NPN wasn't negotiated, see if ALPN was.
911 if (npn_status_ == kNextProtoUnsupported) {
912 const uint8_t* alpn_proto = NULL;
913 unsigned alpn_len = 0;
914 SSL_get0_alpn_selected(ssl_, &alpn_proto, &alpn_len);
915 if (alpn_len > 0) {
916 npn_proto_.assign(reinterpret_cast<const char*>(alpn_proto), alpn_len);
917 npn_status_ = kNextProtoNegotiated;
bnc0d28ea52014-10-13 15:15:38918 set_negotiation_extension(kExtensionALPN);
[email protected]abc44b752014-07-30 03:52:15919 }
920 }
921
davidben09c3d072014-08-25 20:33:58922 RecordChannelIDSupport(channel_id_service_,
923 channel_id_xtn_negotiated_,
924 ssl_config_.channel_id_enabled,
925 crypto::ECPrivateKey::IsSupported());
926
davidbeneb5f8ef32014-09-04 14:14:32927 uint8_t* ocsp_response;
928 size_t ocsp_response_len;
929 SSL_get0_ocsp_response(ssl_, &ocsp_response, &ocsp_response_len);
930 set_stapled_ocsp_response_received(ocsp_response_len != 0);
931
932 uint8_t* sct_list;
933 size_t sct_list_len;
934 SSL_get0_signed_cert_timestamp_list(ssl_, &sct_list, &sct_list_len);
935 set_signed_cert_timestamps_received(sct_list_len != 0);
936
[email protected]abc44b752014-07-30 03:52:15937 // Verify the certificate.
davidben30798ed82014-09-19 19:28:20938 UpdateServerCert();
[email protected]b9b651f2013-11-09 04:32:22939 GotoState(STATE_VERIFY_CERT);
940 } else {
941 int ssl_error = SSL_get_error(ssl_, rv);
942
943 if (ssl_error == SSL_ERROR_WANT_CHANNEL_ID_LOOKUP) {
[email protected]faff9852014-06-21 06:13:46944 // The server supports channel ID. Stop to look one up before returning to
945 // the handshake.
946 channel_id_xtn_negotiated_ = true;
947 GotoState(STATE_CHANNEL_ID_LOOKUP);
948 return OK;
[email protected]b9b651f2013-11-09 04:32:22949 }
950
davidbena4409c62014-08-27 17:05:51951 OpenSSLErrorInfo error_info;
952 net_error = MapOpenSSLErrorWithDetails(ssl_error, err_tracer, &error_info);
[email protected]faff9852014-06-21 06:13:46953
[email protected]b9b651f2013-11-09 04:32:22954 // If not done, stay in this state
955 if (net_error == ERR_IO_PENDING) {
956 GotoState(STATE_HANDSHAKE);
957 } else {
958 LOG(ERROR) << "handshake failed; returned " << rv
959 << ", SSL error code " << ssl_error
960 << ", net_error " << net_error;
961 net_log_.AddEvent(
962 NetLog::TYPE_SSL_HANDSHAKE_ERROR,
davidbena4409c62014-08-27 17:05:51963 CreateNetLogOpenSSLErrorCallback(net_error, ssl_error, error_info));
[email protected]b9b651f2013-11-09 04:32:22964 }
965 }
966 return net_error;
967}
968
[email protected]faff9852014-06-21 06:13:46969int SSLClientSocketOpenSSL::DoChannelIDLookup() {
970 GotoState(STATE_CHANNEL_ID_LOOKUP_COMPLETE);
[email protected]6b8a3c742014-07-25 00:25:35971 return channel_id_service_->GetOrCreateChannelID(
[email protected]faff9852014-06-21 06:13:46972 host_and_port_.host(),
973 &channel_id_private_key_,
974 &channel_id_cert_,
975 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete,
976 base::Unretained(this)),
977 &channel_id_request_handle_);
978}
979
980int SSLClientSocketOpenSSL::DoChannelIDLookupComplete(int result) {
981 if (result < 0)
982 return result;
983
984 DCHECK_LT(0u, channel_id_private_key_.size());
985 // Decode key.
986 std::vector<uint8> encrypted_private_key_info;
987 std::vector<uint8> subject_public_key_info;
988 encrypted_private_key_info.assign(
989 channel_id_private_key_.data(),
990 channel_id_private_key_.data() + channel_id_private_key_.size());
991 subject_public_key_info.assign(
992 channel_id_cert_.data(),
993 channel_id_cert_.data() + channel_id_cert_.size());
994 scoped_ptr<crypto::ECPrivateKey> ec_private_key(
995 crypto::ECPrivateKey::CreateFromEncryptedPrivateKeyInfo(
[email protected]6b8a3c742014-07-25 00:25:35996 ChannelIDService::kEPKIPassword,
[email protected]faff9852014-06-21 06:13:46997 encrypted_private_key_info,
998 subject_public_key_info));
999 if (!ec_private_key) {
1000 LOG(ERROR) << "Failed to import Channel ID.";
1001 return ERR_CHANNEL_ID_IMPORT_FAILED;
1002 }
1003
1004 // Hand the key to OpenSSL. Check for error in case OpenSSL rejects the key
1005 // type.
1006 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1007 int rv = SSL_set1_tls_channel_id(ssl_, ec_private_key->key());
1008 if (!rv) {
1009 LOG(ERROR) << "Failed to set Channel ID.";
1010 int err = SSL_get_error(ssl_, rv);
1011 return MapOpenSSLError(err, err_tracer);
1012 }
1013
1014 // Return to the handshake.
1015 set_channel_id_sent(true);
1016 GotoState(STATE_HANDSHAKE);
1017 return OK;
1018}
1019
[email protected]b9b651f2013-11-09 04:32:221020int SSLClientSocketOpenSSL::DoVerifyCert(int result) {
davidben30798ed82014-09-19 19:28:201021 DCHECK(!server_cert_chain_->empty());
davidben09c3d072014-08-25 20:33:581022 DCHECK(start_cert_verification_time_.is_null());
davidben30798ed82014-09-19 19:28:201023
[email protected]b9b651f2013-11-09 04:32:221024 GotoState(STATE_VERIFY_CERT_COMPLETE);
1025
davidben30798ed82014-09-19 19:28:201026 // If the certificate is bad and has been previously accepted, use
1027 // the previous status and bypass the error.
1028 base::StringPiece der_cert;
1029 if (!x509_util::GetDER(server_cert_chain_->Get(0), &der_cert)) {
1030 NOTREACHED();
1031 return ERR_CERT_INVALID;
1032 }
[email protected]b9b651f2013-11-09 04:32:221033 CertStatus cert_status;
davidben30798ed82014-09-19 19:28:201034 if (ssl_config_.IsAllowedBadCert(der_cert, &cert_status)) {
[email protected]b9b651f2013-11-09 04:32:221035 VLOG(1) << "Received an expected bad cert with status: " << cert_status;
1036 server_cert_verify_result_.Reset();
1037 server_cert_verify_result_.cert_status = cert_status;
1038 server_cert_verify_result_.verified_cert = server_cert_;
1039 return OK;
1040 }
1041
davidben30798ed82014-09-19 19:28:201042 // When running in a sandbox, it may not be possible to create an
1043 // X509Certificate*, as that may depend on OS functionality blocked
1044 // in the sandbox.
1045 if (!server_cert_.get()) {
1046 server_cert_verify_result_.Reset();
1047 server_cert_verify_result_.cert_status = CERT_STATUS_INVALID;
1048 return ERR_CERT_INVALID;
1049 }
1050
davidben09c3d072014-08-25 20:33:581051 start_cert_verification_time_ = base::TimeTicks::Now();
1052
[email protected]b9b651f2013-11-09 04:32:221053 int flags = 0;
1054 if (ssl_config_.rev_checking_enabled)
1055 flags |= CertVerifier::VERIFY_REV_CHECKING_ENABLED;
1056 if (ssl_config_.verify_ev_cert)
1057 flags |= CertVerifier::VERIFY_EV_CERT;
1058 if (ssl_config_.cert_io_enabled)
1059 flags |= CertVerifier::VERIFY_CERT_IO_ENABLED;
1060 if (ssl_config_.rev_checking_required_local_anchors)
1061 flags |= CertVerifier::VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS;
1062 verifier_.reset(new SingleRequestCertVerifier(cert_verifier_));
1063 return verifier_->Verify(
1064 server_cert_.get(),
1065 host_and_port_.host(),
1066 flags,
[email protected]591cffcd2014-08-18 20:02:301067 // TODO(davidben): Route the CRLSet through SSLConfig so
1068 // SSLClientSocket doesn't depend on SSLConfigService.
1069 SSLConfigService::GetCRLSet().get(),
[email protected]b9b651f2013-11-09 04:32:221070 &server_cert_verify_result_,
1071 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete,
1072 base::Unretained(this)),
1073 net_log_);
1074}
1075
1076int SSLClientSocketOpenSSL::DoVerifyCertComplete(int result) {
1077 verifier_.reset();
1078
davidben09c3d072014-08-25 20:33:581079 if (!start_cert_verification_time_.is_null()) {
1080 base::TimeDelta verify_time =
1081 base::TimeTicks::Now() - start_cert_verification_time_;
1082 if (result == OK) {
1083 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTime", verify_time);
1084 } else {
1085 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTimeError", verify_time);
1086 }
1087 }
1088
[email protected]8bd4e7a2014-08-09 14:49:171089 const CertStatus cert_status = server_cert_verify_result_.cert_status;
1090 if (transport_security_state_ &&
1091 (result == OK ||
1092 (IsCertificateError(result) && IsCertStatusMinorError(cert_status))) &&
1093 !transport_security_state_->CheckPublicKeyPins(
1094 host_and_port_.host(),
[email protected]8bd4e7a2014-08-09 14:49:171095 server_cert_verify_result_.is_issued_by_known_root,
1096 server_cert_verify_result_.public_key_hashes,
1097 &pinning_failure_log_)) {
1098 result = ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN;
1099 }
1100
[email protected]b9b651f2013-11-09 04:32:221101 if (result == OK) {
davidbeneb5f8ef32014-09-04 14:14:321102 // Only check Certificate Transparency if there were no other errors with
1103 // the connection.
1104 VerifyCT();
1105
[email protected]b9b651f2013-11-09 04:32:221106 // TODO(joth): Work out if we need to remember the intermediate CA certs
1107 // when the server sends them to us, and do so here.
[email protected]a8fed1742013-12-27 02:14:241108 SSLContext::GetInstance()->session_cache()->MarkSSLSessionAsGood(ssl_);
[email protected]e4738ba52014-08-07 10:07:221109 marked_session_as_good_ = true;
1110 CheckIfHandshakeFinished();
[email protected]b9b651f2013-11-09 04:32:221111 } else {
1112 DVLOG(1) << "DoVerifyCertComplete error " << ErrorToString(result)
1113 << " (" << result << ")";
1114 }
1115
[email protected]64b5c892014-08-08 09:39:261116 completed_connect_ = true;
[email protected]8bd4e7a2014-08-09 14:49:171117
[email protected]b9b651f2013-11-09 04:32:221118 // Exit DoHandshakeLoop and return the result to the caller to Connect.
1119 DCHECK_EQ(STATE_NONE, next_handshake_state_);
1120 return result;
1121}
1122
1123void SSLClientSocketOpenSSL::DoConnectCallback(int rv) {
[email protected]8e458552014-08-05 00:02:151124 if (rv < OK)
1125 OnHandshakeCompletion();
[email protected]b9b651f2013-11-09 04:32:221126 if (!user_connect_callback_.is_null()) {
1127 CompletionCallback c = user_connect_callback_;
1128 user_connect_callback_.Reset();
1129 c.Run(rv > OK ? OK : rv);
1130 }
1131}
1132
davidben30798ed82014-09-19 19:28:201133void SSLClientSocketOpenSSL::UpdateServerCert() {
[email protected]76e85392014-03-20 17:54:141134 server_cert_chain_->Reset(SSL_get_peer_cert_chain(ssl_));
[email protected]7f38da8a2014-03-17 16:44:261135 server_cert_ = server_cert_chain_->AsOSChain();
[email protected]76e85392014-03-20 17:54:141136
davidben30798ed82014-09-19 19:28:201137 if (server_cert_.get()) {
1138 net_log_.AddEvent(
1139 NetLog::TYPE_SSL_CERTIFICATES_RECEIVED,
1140 base::Bind(&NetLogX509CertificateCallback,
1141 base::Unretained(server_cert_.get())));
1142 }
[email protected]b9b651f2013-11-09 04:32:221143}
1144
davidbeneb5f8ef32014-09-04 14:14:321145void SSLClientSocketOpenSSL::VerifyCT() {
1146 if (!cert_transparency_verifier_)
1147 return;
1148
1149 uint8_t* ocsp_response_raw;
1150 size_t ocsp_response_len;
1151 SSL_get0_ocsp_response(ssl_, &ocsp_response_raw, &ocsp_response_len);
1152 std::string ocsp_response;
1153 if (ocsp_response_len > 0) {
1154 ocsp_response.assign(reinterpret_cast<const char*>(ocsp_response_raw),
1155 ocsp_response_len);
1156 }
1157
1158 uint8_t* sct_list_raw;
1159 size_t sct_list_len;
1160 SSL_get0_signed_cert_timestamp_list(ssl_, &sct_list_raw, &sct_list_len);
1161 std::string sct_list;
1162 if (sct_list_len > 0)
1163 sct_list.assign(reinterpret_cast<const char*>(sct_list_raw), sct_list_len);
1164
1165 // Note that this is a completely synchronous operation: The CT Log Verifier
1166 // gets all the data it needs for SCT verification and does not do any
1167 // external communication.
1168 int result = cert_transparency_verifier_->Verify(
1169 server_cert_verify_result_.verified_cert.get(),
1170 ocsp_response, sct_list, &ct_verify_result_, net_log_);
1171
1172 VLOG(1) << "CT Verification complete: result " << result
1173 << " Invalid scts: " << ct_verify_result_.invalid_scts.size()
1174 << " Verified scts: " << ct_verify_result_.verified_scts.size()
1175 << " scts from unknown logs: "
1176 << ct_verify_result_.unknown_logs_scts.size();
1177}
1178
[email protected]b9b651f2013-11-09 04:32:221179void SSLClientSocketOpenSSL::OnHandshakeIOComplete(int result) {
1180 int rv = DoHandshakeLoop(result);
1181 if (rv != ERR_IO_PENDING) {
1182 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
1183 DoConnectCallback(rv);
1184 }
1185}
1186
1187void SSLClientSocketOpenSSL::OnSendComplete(int result) {
1188 if (next_handshake_state_ == STATE_HANDSHAKE) {
1189 // In handshake phase.
1190 OnHandshakeIOComplete(result);
1191 return;
1192 }
1193
1194 // OnSendComplete may need to call DoPayloadRead while the renegotiation
1195 // handshake is in progress.
1196 int rv_read = ERR_IO_PENDING;
1197 int rv_write = ERR_IO_PENDING;
1198 bool network_moved;
1199 do {
1200 if (user_read_buf_.get())
1201 rv_read = DoPayloadRead();
1202 if (user_write_buf_.get())
1203 rv_write = DoPayloadWrite();
1204 network_moved = DoTransportIO();
1205 } while (rv_read == ERR_IO_PENDING && rv_write == ERR_IO_PENDING &&
1206 (user_read_buf_.get() || user_write_buf_.get()) && network_moved);
1207
1208 // Performing the Read callback may cause |this| to be deleted. If this
1209 // happens, the Write callback should not be invoked. Guard against this by
1210 // holding a WeakPtr to |this| and ensuring it's still valid.
1211 base::WeakPtr<SSLClientSocketOpenSSL> guard(weak_factory_.GetWeakPtr());
1212 if (user_read_buf_.get() && rv_read != ERR_IO_PENDING)
1213 DoReadCallback(rv_read);
1214
1215 if (!guard.get())
1216 return;
1217
1218 if (user_write_buf_.get() && rv_write != ERR_IO_PENDING)
1219 DoWriteCallback(rv_write);
1220}
1221
1222void SSLClientSocketOpenSSL::OnRecvComplete(int result) {
1223 if (next_handshake_state_ == STATE_HANDSHAKE) {
1224 // In handshake phase.
1225 OnHandshakeIOComplete(result);
1226 return;
1227 }
1228
1229 // Network layer received some data, check if client requested to read
1230 // decrypted data.
1231 if (!user_read_buf_.get())
1232 return;
1233
1234 int rv = DoReadLoop(result);
1235 if (rv != ERR_IO_PENDING)
1236 DoReadCallback(rv);
1237}
1238
1239int SSLClientSocketOpenSSL::DoHandshakeLoop(int last_io_result) {
1240 int rv = last_io_result;
1241 do {
1242 // Default to STATE_NONE for next state.
1243 // (This is a quirk carried over from the windows
1244 // implementation. It makes reading the logs a bit harder.)
1245 // State handlers can and often do call GotoState just
1246 // to stay in the current state.
1247 State state = next_handshake_state_;
1248 GotoState(STATE_NONE);
1249 switch (state) {
1250 case STATE_HANDSHAKE:
1251 rv = DoHandshake();
1252 break;
[email protected]faff9852014-06-21 06:13:461253 case STATE_CHANNEL_ID_LOOKUP:
1254 DCHECK_EQ(OK, rv);
1255 rv = DoChannelIDLookup();
1256 break;
1257 case STATE_CHANNEL_ID_LOOKUP_COMPLETE:
1258 rv = DoChannelIDLookupComplete(rv);
1259 break;
[email protected]b9b651f2013-11-09 04:32:221260 case STATE_VERIFY_CERT:
[email protected]faff9852014-06-21 06:13:461261 DCHECK_EQ(OK, rv);
[email protected]b9b651f2013-11-09 04:32:221262 rv = DoVerifyCert(rv);
1263 break;
1264 case STATE_VERIFY_CERT_COMPLETE:
1265 rv = DoVerifyCertComplete(rv);
1266 break;
1267 case STATE_NONE:
1268 default:
1269 rv = ERR_UNEXPECTED;
1270 NOTREACHED() << "unexpected state" << state;
1271 break;
1272 }
1273
1274 bool network_moved = DoTransportIO();
1275 if (network_moved && next_handshake_state_ == STATE_HANDSHAKE) {
1276 // In general we exit the loop if rv is ERR_IO_PENDING. In this
1277 // special case we keep looping even if rv is ERR_IO_PENDING because
1278 // the transport IO may allow DoHandshake to make progress.
1279 rv = OK; // This causes us to stay in the loop.
1280 }
1281 } while (rv != ERR_IO_PENDING && next_handshake_state_ != STATE_NONE);
[email protected]8e458552014-08-05 00:02:151282
[email protected]b9b651f2013-11-09 04:32:221283 return rv;
1284}
1285
1286int SSLClientSocketOpenSSL::DoReadLoop(int result) {
1287 if (result < 0)
1288 return result;
1289
1290 bool network_moved;
1291 int rv;
1292 do {
1293 rv = DoPayloadRead();
1294 network_moved = DoTransportIO();
1295 } while (rv == ERR_IO_PENDING && network_moved);
1296
1297 return rv;
1298}
1299
1300int SSLClientSocketOpenSSL::DoWriteLoop(int result) {
1301 if (result < 0)
1302 return result;
1303
1304 bool network_moved;
1305 int rv;
1306 do {
1307 rv = DoPayloadWrite();
1308 network_moved = DoTransportIO();
1309 } while (rv == ERR_IO_PENDING && network_moved);
1310
1311 return rv;
1312}
1313
1314int SSLClientSocketOpenSSL::DoPayloadRead() {
1315 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1316
1317 int rv;
1318 if (pending_read_error_ != kNoPendingReadResult) {
1319 rv = pending_read_error_;
1320 pending_read_error_ = kNoPendingReadResult;
1321 if (rv == 0) {
1322 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED,
1323 rv, user_read_buf_->data());
1324 }
1325 return rv;
1326 }
1327
1328 int total_bytes_read = 0;
1329 do {
1330 rv = SSL_read(ssl_, user_read_buf_->data() + total_bytes_read,
1331 user_read_buf_len_ - total_bytes_read);
1332 if (rv > 0)
1333 total_bytes_read += rv;
1334 } while (total_bytes_read < user_read_buf_len_ && rv > 0);
1335
1336 if (total_bytes_read == user_read_buf_len_) {
1337 rv = total_bytes_read;
1338 } else {
1339 // Otherwise, an error occurred (rv <= 0). The error needs to be handled
1340 // immediately, while the OpenSSL errors are still available in
1341 // thread-local storage. However, the handled/remapped error code should
1342 // only be returned if no application data was already read; if it was, the
1343 // error code should be deferred until the next call of DoPayloadRead.
1344 //
1345 // If no data was read, |*next_result| will point to the return value of
1346 // this function. If at least some data was read, |*next_result| will point
1347 // to |pending_read_error_|, to be returned in a future call to
1348 // DoPayloadRead() (e.g.: after the current data is handled).
1349 int *next_result = &rv;
1350 if (total_bytes_read > 0) {
1351 pending_read_error_ = rv;
1352 rv = total_bytes_read;
1353 next_result = &pending_read_error_;
1354 }
1355
1356 if (client_auth_cert_needed_) {
1357 *next_result = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
1358 } else if (*next_result < 0) {
1359 int err = SSL_get_error(ssl_, *next_result);
1360 *next_result = MapOpenSSLError(err, err_tracer);
1361 if (rv > 0 && *next_result == ERR_IO_PENDING) {
1362 // If at least some data was read from SSL_read(), do not treat
1363 // insufficient data as an error to return in the next call to
1364 // DoPayloadRead() - instead, let the call fall through to check
1365 // SSL_read() again. This is because DoTransportIO() may complete
1366 // in between the next call to DoPayloadRead(), and thus it is
1367 // important to check SSL_read() on subsequent invocations to see
1368 // if a complete record may now be read.
1369 *next_result = kNoPendingReadResult;
1370 }
1371 }
1372 }
1373
1374 if (rv >= 0) {
1375 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, rv,
1376 user_read_buf_->data());
1377 }
1378 return rv;
1379}
1380
1381int SSLClientSocketOpenSSL::DoPayloadWrite() {
1382 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1383 int rv = SSL_write(ssl_, user_write_buf_->data(), user_write_buf_len_);
[email protected]b9b651f2013-11-09 04:32:221384 if (rv >= 0) {
1385 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_SENT, rv,
1386 user_write_buf_->data());
1387 return rv;
1388 }
1389
1390 int err = SSL_get_error(ssl_, rv);
1391 return MapOpenSSLError(err, err_tracer);
1392}
1393
1394int SSLClientSocketOpenSSL::BufferSend(void) {
1395 if (transport_send_busy_)
1396 return ERR_IO_PENDING;
1397
1398 if (!send_buffer_.get()) {
1399 // Get a fresh send buffer out of the send BIO.
[email protected]edfd0f42014-07-22 18:20:371400 size_t max_read = BIO_pending(transport_bio_);
[email protected]b9b651f2013-11-09 04:32:221401 if (!max_read)
1402 return 0; // Nothing pending in the OpenSSL write BIO.
1403 send_buffer_ = new DrainableIOBuffer(new IOBuffer(max_read), max_read);
1404 int read_bytes = BIO_read(transport_bio_, send_buffer_->data(), max_read);
1405 DCHECK_GT(read_bytes, 0);
1406 CHECK_EQ(static_cast<int>(max_read), read_bytes);
1407 }
1408
1409 int rv = transport_->socket()->Write(
1410 send_buffer_.get(),
1411 send_buffer_->BytesRemaining(),
1412 base::Bind(&SSLClientSocketOpenSSL::BufferSendComplete,
1413 base::Unretained(this)));
1414 if (rv == ERR_IO_PENDING) {
1415 transport_send_busy_ = true;
1416 } else {
1417 TransportWriteComplete(rv);
1418 }
1419 return rv;
1420}
1421
1422int SSLClientSocketOpenSSL::BufferRecv(void) {
1423 if (transport_recv_busy_)
1424 return ERR_IO_PENDING;
1425
1426 // Determine how much was requested from |transport_bio_| that was not
1427 // actually available.
1428 size_t requested = BIO_ctrl_get_read_request(transport_bio_);
1429 if (requested == 0) {
1430 // This is not a perfect match of error codes, as no operation is
1431 // actually pending. However, returning 0 would be interpreted as
1432 // a possible sign of EOF, which is also an inappropriate match.
1433 return ERR_IO_PENDING;
1434 }
1435
1436 // Known Issue: While only reading |requested| data is the more correct
1437 // implementation, it has the downside of resulting in frequent reads:
1438 // One read for the SSL record header (~5 bytes) and one read for the SSL
1439 // record body. Rather than issuing these reads to the underlying socket
1440 // (and constantly allocating new IOBuffers), a single Read() request to
1441 // fill |transport_bio_| is issued. As long as an SSL client socket cannot
1442 // be gracefully shutdown (via SSL close alerts) and re-used for non-SSL
1443 // traffic, this over-subscribed Read()ing will not cause issues.
1444 size_t max_write = BIO_ctrl_get_write_guarantee(transport_bio_);
1445 if (!max_write)
1446 return ERR_IO_PENDING;
1447
1448 recv_buffer_ = new IOBuffer(max_write);
1449 int rv = transport_->socket()->Read(
1450 recv_buffer_.get(),
1451 max_write,
1452 base::Bind(&SSLClientSocketOpenSSL::BufferRecvComplete,
1453 base::Unretained(this)));
1454 if (rv == ERR_IO_PENDING) {
1455 transport_recv_busy_ = true;
1456 } else {
[email protected]3e5c6922014-02-06 02:42:161457 rv = TransportReadComplete(rv);
[email protected]b9b651f2013-11-09 04:32:221458 }
1459 return rv;
1460}
1461
1462void SSLClientSocketOpenSSL::BufferSendComplete(int result) {
1463 transport_send_busy_ = false;
1464 TransportWriteComplete(result);
1465 OnSendComplete(result);
1466}
1467
1468void SSLClientSocketOpenSSL::BufferRecvComplete(int result) {
[email protected]3e5c6922014-02-06 02:42:161469 result = TransportReadComplete(result);
[email protected]b9b651f2013-11-09 04:32:221470 OnRecvComplete(result);
1471}
1472
1473void SSLClientSocketOpenSSL::TransportWriteComplete(int result) {
1474 DCHECK(ERR_IO_PENDING != result);
1475 if (result < 0) {
[email protected]5aea79182014-07-14 20:43:411476 // Record the error. Save it to be reported in a future read or write on
1477 // transport_bio_'s peer.
[email protected]3e5c6922014-02-06 02:42:161478 transport_write_error_ = result;
[email protected]b9b651f2013-11-09 04:32:221479 send_buffer_ = NULL;
1480 } else {
1481 DCHECK(send_buffer_.get());
1482 send_buffer_->DidConsume(result);
1483 DCHECK_GE(send_buffer_->BytesRemaining(), 0);
1484 if (send_buffer_->BytesRemaining() <= 0)
1485 send_buffer_ = NULL;
1486 }
1487}
1488
[email protected]3e5c6922014-02-06 02:42:161489int SSLClientSocketOpenSSL::TransportReadComplete(int result) {
[email protected]b9b651f2013-11-09 04:32:221490 DCHECK(ERR_IO_PENDING != result);
[email protected]5aea79182014-07-14 20:43:411491 // If an EOF, canonicalize to ERR_CONNECTION_CLOSED here so MapOpenSSLError
1492 // does not report success.
1493 if (result == 0)
1494 result = ERR_CONNECTION_CLOSED;
1495 if (result < 0) {
[email protected]b9b651f2013-11-09 04:32:221496 DVLOG(1) << "TransportReadComplete result " << result;
[email protected]5aea79182014-07-14 20:43:411497 // Received an error. Save it to be reported in a future read on
1498 // transport_bio_'s peer.
1499 transport_read_error_ = result;
[email protected]b9b651f2013-11-09 04:32:221500 } else {
1501 DCHECK(recv_buffer_.get());
1502 int ret = BIO_write(transport_bio_, recv_buffer_->data(), result);
1503 // A write into a memory BIO should always succeed.
[email protected]c8a80e92014-05-17 16:02:081504 DCHECK_EQ(result, ret);
[email protected]b9b651f2013-11-09 04:32:221505 }
1506 recv_buffer_ = NULL;
1507 transport_recv_busy_ = false;
[email protected]3e5c6922014-02-06 02:42:161508 return result;
[email protected]b9b651f2013-11-09 04:32:221509}
1510
[email protected]82c59022014-08-15 09:38:271511int SSLClientSocketOpenSSL::ClientCertRequestCallback(SSL* ssl) {
[email protected]5ac981e182010-12-06 17:56:271512 DVLOG(3) << "OpenSSL ClientCertRequestCallback called";
1513 DCHECK(ssl == ssl_);
[email protected]82c59022014-08-15 09:38:271514
1515 // Clear any currently configured certificates.
1516 SSL_certs_clear(ssl_);
[email protected]97a854f2014-07-29 07:51:361517
1518#if defined(OS_IOS)
1519 // TODO(droger): Support client auth on iOS. See http://crbug.com/145954).
1520 LOG(WARNING) << "Client auth is not supported";
1521#else // !defined(OS_IOS)
[email protected]5ac981e182010-12-06 17:56:271522 if (!ssl_config_.send_client_cert) {
[email protected]515adc22013-01-09 16:01:231523 // First pass: we know that a client certificate is needed, but we do not
1524 // have one at hand.
[email protected]5ac981e182010-12-06 17:56:271525 client_auth_cert_needed_ = true;
[email protected]515adc22013-01-09 16:01:231526 STACK_OF(X509_NAME) *authorities = SSL_get_client_CA_list(ssl);
[email protected]edfd0f42014-07-22 18:20:371527 for (size_t i = 0; i < sk_X509_NAME_num(authorities); i++) {
[email protected]515adc22013-01-09 16:01:231528 X509_NAME *ca_name = (X509_NAME *)sk_X509_NAME_value(authorities, i);
1529 unsigned char* str = NULL;
1530 int length = i2d_X509_NAME(ca_name, &str);
1531 cert_authorities_.push_back(std::string(
1532 reinterpret_cast<const char*>(str),
1533 static_cast<size_t>(length)));
1534 OPENSSL_free(str);
1535 }
1536
[email protected]c0787702014-05-20 21:51:441537 const unsigned char* client_cert_types;
[email protected]e7e883e2014-07-25 06:03:081538 size_t num_client_cert_types =
1539 SSL_get0_certificate_types(ssl, &client_cert_types);
[email protected]c0787702014-05-20 21:51:441540 for (size_t i = 0; i < num_client_cert_types; i++) {
1541 cert_key_types_.push_back(
1542 static_cast<SSLClientCertType>(client_cert_types[i]));
1543 }
1544
[email protected]5ac981e182010-12-06 17:56:271545 return -1; // Suspends handshake.
1546 }
1547
1548 // Second pass: a client certificate should have been selected.
[email protected]13914c92013-06-13 22:42:421549 if (ssl_config_.client_cert.get()) {
[email protected]6bad5052014-07-12 01:25:131550 ScopedX509 leaf_x509 =
1551 OSCertHandleToOpenSSL(ssl_config_.client_cert->os_cert_handle());
1552 if (!leaf_x509) {
1553 LOG(WARNING) << "Failed to import certificate";
1554 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT);
1555 return -1;
1556 }
1557
[email protected]82c59022014-08-15 09:38:271558 ScopedX509Stack chain = OSCertHandlesToOpenSSL(
1559 ssl_config_.client_cert->GetIntermediateCertificates());
1560 if (!chain) {
1561 LOG(WARNING) << "Failed to import intermediate certificates";
1562 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT);
1563 return -1;
1564 }
1565
[email protected]97a854f2014-07-29 07:51:361566 // TODO(davidben): With Linux client auth support, this should be
1567 // conditioned on OS_ANDROID and then, with https://crbug.com/394131,
1568 // removed altogether. OpenSSLClientKeyStore is mostly an artifact of the
1569 // net/ client auth API lacking a private key handle.
[email protected]c0787702014-05-20 21:51:441570#if defined(USE_OPENSSL_CERTS)
[email protected]97a854f2014-07-29 07:51:361571 crypto::ScopedEVP_PKEY privkey =
1572 OpenSSLClientKeyStore::GetInstance()->FetchClientCertPrivateKey(
1573 ssl_config_.client_cert.get());
1574#else // !defined(USE_OPENSSL_CERTS)
1575 crypto::ScopedEVP_PKEY privkey =
1576 FetchClientCertPrivateKey(ssl_config_.client_cert.get());
1577#endif // defined(USE_OPENSSL_CERTS)
1578 if (!privkey) {
[email protected]6bad5052014-07-12 01:25:131579 // Could not find the private key. Fail the handshake and surface an
1580 // appropriate error to the caller.
1581 LOG(WARNING) << "Client cert found without private key";
1582 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY);
1583 return -1;
[email protected]0c6523f2010-12-10 10:56:241584 }
[email protected]6bad5052014-07-12 01:25:131585
[email protected]82c59022014-08-15 09:38:271586 if (!SSL_use_certificate(ssl_, leaf_x509.get()) ||
1587 !SSL_use_PrivateKey(ssl_, privkey.get()) ||
1588 !SSL_set1_chain(ssl_, chain.get())) {
1589 LOG(WARNING) << "Failed to set client certificate";
1590 return -1;
1591 }
[email protected]6bad5052014-07-12 01:25:131592 return 1;
[email protected]c0787702014-05-20 21:51:441593 }
[email protected]97a854f2014-07-29 07:51:361594#endif // defined(OS_IOS)
[email protected]5ac981e182010-12-06 17:56:271595
1596 // Send no client certificate.
[email protected]82c59022014-08-15 09:38:271597 return 1;
[email protected]5ac981e182010-12-06 17:56:271598}
1599
[email protected]b051cdb62014-02-28 02:20:161600int SSLClientSocketOpenSSL::CertVerifyCallback(X509_STORE_CTX* store_ctx) {
[email protected]64b5c892014-08-08 09:39:261601 if (!completed_connect_) {
[email protected]b051cdb62014-02-28 02:20:161602 // If the first handshake hasn't completed then we accept any certificates
1603 // because we verify after the handshake.
1604 return 1;
1605 }
1606
davidben30798ed82014-09-19 19:28:201607 // Disallow the server certificate to change in a renegotiation.
1608 if (server_cert_chain_->empty()) {
[email protected]76e85392014-03-20 17:54:141609 LOG(ERROR) << "Received invalid certificate chain between handshakes";
davidben30798ed82014-09-19 19:28:201610 return 0;
1611 }
1612 base::StringPiece old_der, new_der;
1613 if (store_ctx->cert == NULL ||
1614 !x509_util::GetDER(server_cert_chain_->Get(0), &old_der) ||
1615 !x509_util::GetDER(store_ctx->cert, &new_der)) {
1616 LOG(ERROR) << "Failed to encode certificates";
1617 return 0;
1618 }
1619 if (old_der != new_der) {
[email protected]76e85392014-03-20 17:54:141620 LOG(ERROR) << "Server certificate changed between handshakes";
davidben30798ed82014-09-19 19:28:201621 return 0;
1622 }
1623
1624 return 1;
[email protected]b051cdb62014-02-28 02:20:161625}
1626
[email protected]ae7c9f42011-11-21 11:41:161627// SelectNextProtoCallback is called by OpenSSL during the handshake. If the
1628// server supports NPN, selects a protocol from the list that the server
1629// provides. According to third_party/openssl/openssl/ssl/ssl_lib.c, the
1630// callback can assume that |in| is syntactically valid.
[email protected]ea4a1c6a2010-12-09 13:33:281631int SSLClientSocketOpenSSL::SelectNextProtoCallback(unsigned char** out,
1632 unsigned char* outlen,
1633 const unsigned char* in,
1634 unsigned int inlen) {
[email protected]ea4a1c6a2010-12-09 13:33:281635 if (ssl_config_.next_protos.empty()) {
[email protected]168a8412012-06-14 05:05:491636 *out = reinterpret_cast<uint8*>(
1637 const_cast<char*>(kDefaultSupportedNPNProtocol));
1638 *outlen = arraysize(kDefaultSupportedNPNProtocol) - 1;
1639 npn_status_ = kNextProtoUnsupported;
[email protected]ea4a1c6a2010-12-09 13:33:281640 return SSL_TLSEXT_ERR_OK;
1641 }
1642
[email protected]ae7c9f42011-11-21 11:41:161643 // Assume there's no overlap between our protocols and the server's list.
[email protected]168a8412012-06-14 05:05:491644 npn_status_ = kNextProtoNoOverlap;
[email protected]ae7c9f42011-11-21 11:41:161645
1646 // For each protocol in server preference order, see if we support it.
1647 for (unsigned int i = 0; i < inlen; i += in[i] + 1) {
1648 for (std::vector<std::string>::const_iterator
1649 j = ssl_config_.next_protos.begin();
1650 j != ssl_config_.next_protos.end(); ++j) {
1651 if (in[i] == j->size() &&
1652 memcmp(&in[i + 1], j->data(), in[i]) == 0) {
[email protected]168a8412012-06-14 05:05:491653 // We found a match.
[email protected]ae7c9f42011-11-21 11:41:161654 *out = const_cast<unsigned char*>(in) + i + 1;
1655 *outlen = in[i];
[email protected]168a8412012-06-14 05:05:491656 npn_status_ = kNextProtoNegotiated;
[email protected]ae7c9f42011-11-21 11:41:161657 break;
1658 }
1659 }
[email protected]168a8412012-06-14 05:05:491660 if (npn_status_ == kNextProtoNegotiated)
[email protected]ae7c9f42011-11-21 11:41:161661 break;
1662 }
[email protected]ea4a1c6a2010-12-09 13:33:281663
[email protected]168a8412012-06-14 05:05:491664 // If we didn't find a protocol, we select the first one from our list.
1665 if (npn_status_ == kNextProtoNoOverlap) {
1666 *out = reinterpret_cast<uint8*>(const_cast<char*>(
1667 ssl_config_.next_protos[0].data()));
1668 *outlen = ssl_config_.next_protos[0].size();
1669 }
1670
[email protected]ea4a1c6a2010-12-09 13:33:281671 npn_proto_.assign(reinterpret_cast<const char*>(*out), *outlen);
[email protected]32e1dee2010-12-09 18:36:241672 DVLOG(2) << "next protocol: '" << npn_proto_ << "' status: " << npn_status_;
bnc0d28ea52014-10-13 15:15:381673 set_negotiation_extension(kExtensionNPN);
[email protected]ea4a1c6a2010-12-09 13:33:281674 return SSL_TLSEXT_ERR_OK;
1675}
1676
[email protected]5aea79182014-07-14 20:43:411677long SSLClientSocketOpenSSL::MaybeReplayTransportError(
1678 BIO *bio,
1679 int cmd,
1680 const char *argp, int argi, long argl,
1681 long retvalue) {
1682 if (cmd == (BIO_CB_READ|BIO_CB_RETURN) && retvalue <= 0) {
1683 // If there is no more data in the buffer, report any pending errors that
1684 // were observed. Note that both the readbuf and the writebuf are checked
1685 // for errors, since the application may have encountered a socket error
1686 // while writing that would otherwise not be reported until the application
1687 // attempted to write again - which it may never do. See
1688 // https://crbug.com/249848.
1689 if (transport_read_error_ != OK) {
1690 OpenSSLPutNetError(FROM_HERE, transport_read_error_);
1691 return -1;
1692 }
1693 if (transport_write_error_ != OK) {
1694 OpenSSLPutNetError(FROM_HERE, transport_write_error_);
1695 return -1;
1696 }
1697 } else if (cmd == BIO_CB_WRITE) {
1698 // Because of the write buffer, this reports a failure from the previous
1699 // write payload. If the current payload fails to write, the error will be
1700 // reported in a future write or read to |bio|.
1701 if (transport_write_error_ != OK) {
1702 OpenSSLPutNetError(FROM_HERE, transport_write_error_);
1703 return -1;
1704 }
1705 }
1706 return retvalue;
1707}
1708
1709// static
1710long SSLClientSocketOpenSSL::BIOCallback(
1711 BIO *bio,
1712 int cmd,
1713 const char *argp, int argi, long argl,
1714 long retvalue) {
1715 SSLClientSocketOpenSSL* socket = reinterpret_cast<SSLClientSocketOpenSSL*>(
1716 BIO_get_callback_arg(bio));
1717 CHECK(socket);
1718 return socket->MaybeReplayTransportError(
1719 bio, cmd, argp, argi, argl, retvalue);
1720}
1721
[email protected]64b5c892014-08-08 09:39:261722// static
1723void SSLClientSocketOpenSSL::InfoCallback(const SSL* ssl,
1724 int type,
1725 int /*val*/) {
1726 if (type == SSL_CB_HANDSHAKE_DONE) {
1727 SSLClientSocketOpenSSL* ssl_socket =
1728 SSLContext::GetInstance()->GetClientSocketFromSSL(ssl);
1729 ssl_socket->handshake_succeeded_ = true;
1730 ssl_socket->CheckIfHandshakeFinished();
1731 }
1732}
1733
1734// Determines if both the handshake and certificate verification have completed
1735// successfully, and calls the handshake completion callback if that is the
1736// case.
1737//
1738// CheckIfHandshakeFinished is called twice per connection: once after
1739// MarkSSLSessionAsGood, when the certificate has been verified, and
1740// once via an OpenSSL callback when the handshake has completed. On the
1741// second call, when the certificate has been verified and the handshake
1742// has completed, the connection's handshake completion callback is run.
1743void SSLClientSocketOpenSSL::CheckIfHandshakeFinished() {
1744 if (handshake_succeeded_ && marked_session_as_good_)
1745 OnHandshakeCompletion();
1746}
1747
davidbeneb5f8ef32014-09-04 14:14:321748void SSLClientSocketOpenSSL::AddSCTInfoToSSLInfo(SSLInfo* ssl_info) const {
1749 for (ct::SCTList::const_iterator iter =
1750 ct_verify_result_.verified_scts.begin();
1751 iter != ct_verify_result_.verified_scts.end(); ++iter) {
1752 ssl_info->signed_certificate_timestamps.push_back(
1753 SignedCertificateTimestampAndStatus(*iter, ct::SCT_STATUS_OK));
1754 }
1755 for (ct::SCTList::const_iterator iter =
1756 ct_verify_result_.invalid_scts.begin();
1757 iter != ct_verify_result_.invalid_scts.end(); ++iter) {
1758 ssl_info->signed_certificate_timestamps.push_back(
1759 SignedCertificateTimestampAndStatus(*iter, ct::SCT_STATUS_INVALID));
1760 }
1761 for (ct::SCTList::const_iterator iter =
1762 ct_verify_result_.unknown_logs_scts.begin();
1763 iter != ct_verify_result_.unknown_logs_scts.end(); ++iter) {
1764 ssl_info->signed_certificate_timestamps.push_back(
1765 SignedCertificateTimestampAndStatus(*iter,
1766 ct::SCT_STATUS_LOG_UNKNOWN));
1767 }
1768}
1769
[email protected]7f38da8a2014-03-17 16:44:261770scoped_refptr<X509Certificate>
1771SSLClientSocketOpenSSL::GetUnverifiedServerCertificateChain() const {
1772 return server_cert_;
1773}
1774
[email protected]7e5dd49f2010-12-08 18:33:491775} // namespace net