blob: c0ce045e043662c3684e1fa9a2c06754b7603b26 [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"
eranmefbd3132014-10-28 16:35:1627#include "net/cert/ct_ev_whitelist.h"
davidbeneb5f8ef32014-09-04 14:14:3228#include "net/cert/ct_verifier.h"
[email protected]6e7845ae2013-03-29 21:48:1129#include "net/cert/single_request_cert_verifier.h"
30#include "net/cert/x509_certificate_net_log_param.h"
davidben30798ed82014-09-19 19:28:2031#include "net/cert/x509_util_openssl.h"
[email protected]8bd4e7a2014-08-09 14:49:1732#include "net/http/transport_security_state.h"
[email protected]1279de12013-12-03 15:13:3233#include "net/socket/ssl_session_cache_openssl.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;
davidben1d094022014-11-05 18:55:47104 case TLS1_1_VERSION:
[email protected]109805a2010-12-07 18:17:06105 return SSL_CONNECTION_VERSION_TLS1_1;
davidben1d094022014-11-05 18:55:47106 case TLS1_2_VERSION:
[email protected]109805a2010-12-07 18:17:06107 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
272 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),
davidbenb8c23212014-10-28 00:12:16342 pending_read_ssl_error_(SSL_ERROR_NONE),
[email protected]5aea79182014-07-14 20:43:41343 transport_read_error_(OK),
[email protected]3e5c6922014-02-06 02:42:16344 transport_write_error_(OK),
[email protected]7f38da8a2014-03-17 16:44:26345 server_cert_chain_(new PeerCertificateChain(NULL)),
[email protected]64b5c892014-08-08 09:39:26346 completed_connect_(false),
[email protected]0dc88b32014-03-26 20:12:28347 was_ever_used_(false),
[email protected]d518cd92010-09-29 12:27:44348 client_auth_cert_needed_(false),
[email protected]feb79bcd2011-07-21 16:55:17349 cert_verifier_(context.cert_verifier),
davidbeneb5f8ef32014-09-04 14:14:32350 cert_transparency_verifier_(context.cert_transparency_verifier),
[email protected]6b8a3c742014-07-25 00:25:35351 channel_id_service_(context.channel_id_service),
[email protected]d518cd92010-09-29 12:27:44352 ssl_(NULL),
353 transport_bio_(NULL),
[email protected]18ccfdb2013-08-15 00:13:44354 transport_(transport_socket.Pass()),
[email protected]055d7f22010-11-15 12:03:12355 host_and_port_(host_and_port),
[email protected]d518cd92010-09-29 12:27:44356 ssl_config_(ssl_config),
[email protected]c3456bb2011-12-12 22:22:19357 ssl_session_cache_shard_(context.ssl_session_cache_shard),
[email protected]fbef13932010-11-23 12:38:53358 trying_cached_session_(false),
[email protected]013c17c2012-01-21 19:09:01359 next_handshake_state_(STATE_NONE),
[email protected]ea4a1c6a2010-12-09 13:33:28360 npn_status_(kNextProtoUnsupported),
[email protected]ee0f2aa82013-10-25 11:59:26361 channel_id_xtn_negotiated_(false),
[email protected]64b5c892014-08-08 09:39:26362 handshake_succeeded_(false),
[email protected]e4738ba52014-08-07 10:07:22363 marked_session_as_good_(false),
[email protected]8bd4e7a2014-08-09 14:49:17364 transport_security_state_(context.transport_security_state),
kulkarni.acd7b4462014-08-28 07:41:34365 net_log_(transport_->socket()->NetLog()),
366 weak_factory_(this) {
[email protected]8e458552014-08-05 00:02:15367}
[email protected]d518cd92010-09-29 12:27:44368
369SSLClientSocketOpenSSL::~SSLClientSocketOpenSSL() {
370 Disconnect();
371}
372
[email protected]cffd7f92014-08-21 21:30:50373std::string SSLClientSocketOpenSSL::GetSessionCacheKey() const {
374 std::string result = host_and_port_.ToString();
375 result.append("/");
376 result.append(ssl_session_cache_shard_);
377 return result;
378}
379
[email protected]8e458552014-08-05 00:02:15380bool SSLClientSocketOpenSSL::InSessionCache() const {
381 SSLContext* context = SSLContext::GetInstance();
382 std::string cache_key = GetSessionCacheKey();
383 return context->session_cache()->SSLSessionIsInCache(cache_key);
384}
385
386void SSLClientSocketOpenSSL::SetHandshakeCompletionCallback(
387 const base::Closure& callback) {
388 handshake_completion_callback_ = callback;
389}
390
[email protected]b9b651f2013-11-09 04:32:22391void SSLClientSocketOpenSSL::GetSSLCertRequestInfo(
392 SSLCertRequestInfo* cert_request_info) {
[email protected]791879c2013-12-17 07:22:41393 cert_request_info->host_and_port = host_and_port_;
[email protected]b9b651f2013-11-09 04:32:22394 cert_request_info->cert_authorities = cert_authorities_;
[email protected]c0787702014-05-20 21:51:44395 cert_request_info->cert_key_types = cert_key_types_;
[email protected]b9b651f2013-11-09 04:32:22396}
397
398SSLClientSocket::NextProtoStatus SSLClientSocketOpenSSL::GetNextProto(
[email protected]abc44b752014-07-30 03:52:15399 std::string* proto) {
[email protected]b9b651f2013-11-09 04:32:22400 *proto = npn_proto_;
[email protected]b9b651f2013-11-09 04:32:22401 return npn_status_;
402}
403
[email protected]6b8a3c742014-07-25 00:25:35404ChannelIDService*
405SSLClientSocketOpenSSL::GetChannelIDService() const {
406 return channel_id_service_;
[email protected]b9b651f2013-11-09 04:32:22407}
408
409int SSLClientSocketOpenSSL::ExportKeyingMaterial(
410 const base::StringPiece& label,
411 bool has_context, const base::StringPiece& context,
412 unsigned char* out, unsigned int outlen) {
413 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
414
415 int rv = SSL_export_keying_material(
[email protected]c8a80e92014-05-17 16:02:08416 ssl_, out, outlen, label.data(), label.size(),
417 reinterpret_cast<const unsigned char*>(context.data()),
418 context.length(), context.length() > 0);
[email protected]b9b651f2013-11-09 04:32:22419
420 if (rv != 1) {
421 int ssl_error = SSL_get_error(ssl_, rv);
422 LOG(ERROR) << "Failed to export keying material;"
423 << " returned " << rv
424 << ", SSL error code " << ssl_error;
425 return MapOpenSSLError(ssl_error, err_tracer);
426 }
427 return OK;
428}
429
430int SSLClientSocketOpenSSL::GetTLSUniqueChannelBinding(std::string* out) {
[email protected]c8a80e92014-05-17 16:02:08431 NOTIMPLEMENTED();
[email protected]b9b651f2013-11-09 04:32:22432 return ERR_NOT_IMPLEMENTED;
433}
434
435int SSLClientSocketOpenSSL::Connect(const CompletionCallback& callback) {
[email protected]8bd4e7a2014-08-09 14:49:17436 // It is an error to create an SSLClientSocket whose context has no
437 // TransportSecurityState.
438 DCHECK(transport_security_state_);
439
[email protected]b9b651f2013-11-09 04:32:22440 net_log_.BeginEvent(NetLog::TYPE_SSL_CONNECT);
441
442 // Set up new ssl object.
[email protected]c8a80e92014-05-17 16:02:08443 int rv = Init();
444 if (rv != OK) {
445 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
446 return rv;
[email protected]b9b651f2013-11-09 04:32:22447 }
448
449 // Set SSL to client mode. Handshake happens in the loop below.
450 SSL_set_connect_state(ssl_);
451
452 GotoState(STATE_HANDSHAKE);
[email protected]c8a80e92014-05-17 16:02:08453 rv = DoHandshakeLoop(OK);
[email protected]b9b651f2013-11-09 04:32:22454 if (rv == ERR_IO_PENDING) {
455 user_connect_callback_ = callback;
456 } else {
457 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
[email protected]8e458552014-08-05 00:02:15458 if (rv < OK)
459 OnHandshakeCompletion();
[email protected]b9b651f2013-11-09 04:32:22460 }
461
462 return rv > OK ? OK : rv;
463}
464
465void SSLClientSocketOpenSSL::Disconnect() {
[email protected]8e458552014-08-05 00:02:15466 // If a handshake was pending (Connect() had been called), notify interested
467 // parties that it's been aborted now. If the handshake had already
468 // completed, this is a no-op.
469 OnHandshakeCompletion();
[email protected]b9b651f2013-11-09 04:32:22470 if (ssl_) {
471 // Calling SSL_shutdown prevents the session from being marked as
472 // unresumable.
473 SSL_shutdown(ssl_);
474 SSL_free(ssl_);
475 ssl_ = NULL;
476 }
477 if (transport_bio_) {
478 BIO_free_all(transport_bio_);
479 transport_bio_ = NULL;
480 }
481
482 // Shut down anything that may call us back.
483 verifier_.reset();
484 transport_->socket()->Disconnect();
485
486 // Null all callbacks, delete all buffers.
487 transport_send_busy_ = false;
488 send_buffer_ = NULL;
489 transport_recv_busy_ = false;
[email protected]b9b651f2013-11-09 04:32:22490 recv_buffer_ = NULL;
491
492 user_connect_callback_.Reset();
493 user_read_callback_.Reset();
494 user_write_callback_.Reset();
495 user_read_buf_ = NULL;
496 user_read_buf_len_ = 0;
497 user_write_buf_ = NULL;
498 user_write_buf_len_ = 0;
499
[email protected]3e5c6922014-02-06 02:42:16500 pending_read_error_ = kNoPendingReadResult;
davidbenb8c23212014-10-28 00:12:16501 pending_read_ssl_error_ = SSL_ERROR_NONE;
502 pending_read_error_info_ = OpenSSLErrorInfo();
503
[email protected]5aea79182014-07-14 20:43:41504 transport_read_error_ = OK;
[email protected]3e5c6922014-02-06 02:42:16505 transport_write_error_ = OK;
506
[email protected]b9b651f2013-11-09 04:32:22507 server_cert_verify_result_.Reset();
[email protected]64b5c892014-08-08 09:39:26508 completed_connect_ = false;
[email protected]b9b651f2013-11-09 04:32:22509
510 cert_authorities_.clear();
[email protected]c0787702014-05-20 21:51:44511 cert_key_types_.clear();
[email protected]b9b651f2013-11-09 04:32:22512 client_auth_cert_needed_ = false;
[email protected]faff9852014-06-21 06:13:46513
davidben09c3d072014-08-25 20:33:58514 start_cert_verification_time_ = base::TimeTicks();
515
[email protected]abc44b752014-07-30 03:52:15516 npn_status_ = kNextProtoUnsupported;
517 npn_proto_.clear();
518
[email protected]faff9852014-06-21 06:13:46519 channel_id_xtn_negotiated_ = false;
520 channel_id_request_handle_.Cancel();
[email protected]b9b651f2013-11-09 04:32:22521}
522
523bool SSLClientSocketOpenSSL::IsConnected() const {
524 // If the handshake has not yet completed.
[email protected]64b5c892014-08-08 09:39:26525 if (!completed_connect_)
[email protected]b9b651f2013-11-09 04:32:22526 return false;
527 // If an asynchronous operation is still pending.
528 if (user_read_buf_.get() || user_write_buf_.get())
529 return true;
530
531 return transport_->socket()->IsConnected();
532}
533
534bool SSLClientSocketOpenSSL::IsConnectedAndIdle() const {
535 // If the handshake has not yet completed.
[email protected]64b5c892014-08-08 09:39:26536 if (!completed_connect_)
[email protected]b9b651f2013-11-09 04:32:22537 return false;
538 // If an asynchronous operation is still pending.
539 if (user_read_buf_.get() || user_write_buf_.get())
540 return false;
541 // If there is data waiting to be sent, or data read from the network that
542 // has not yet been consumed.
[email protected]edfd0f42014-07-22 18:20:37543 if (BIO_pending(transport_bio_) > 0 ||
544 BIO_wpending(transport_bio_) > 0) {
[email protected]b9b651f2013-11-09 04:32:22545 return false;
546 }
547
548 return transport_->socket()->IsConnectedAndIdle();
549}
550
551int SSLClientSocketOpenSSL::GetPeerAddress(IPEndPoint* addressList) const {
552 return transport_->socket()->GetPeerAddress(addressList);
553}
554
555int SSLClientSocketOpenSSL::GetLocalAddress(IPEndPoint* addressList) const {
556 return transport_->socket()->GetLocalAddress(addressList);
557}
558
559const BoundNetLog& SSLClientSocketOpenSSL::NetLog() const {
560 return net_log_;
561}
562
563void SSLClientSocketOpenSSL::SetSubresourceSpeculation() {
564 if (transport_.get() && transport_->socket()) {
565 transport_->socket()->SetSubresourceSpeculation();
566 } else {
567 NOTREACHED();
568 }
569}
570
571void SSLClientSocketOpenSSL::SetOmniboxSpeculation() {
572 if (transport_.get() && transport_->socket()) {
573 transport_->socket()->SetOmniboxSpeculation();
574 } else {
575 NOTREACHED();
576 }
577}
578
579bool SSLClientSocketOpenSSL::WasEverUsed() const {
[email protected]0dc88b32014-03-26 20:12:28580 return was_ever_used_;
[email protected]b9b651f2013-11-09 04:32:22581}
582
583bool SSLClientSocketOpenSSL::UsingTCPFastOpen() const {
584 if (transport_.get() && transport_->socket())
585 return transport_->socket()->UsingTCPFastOpen();
586
587 NOTREACHED();
588 return false;
589}
590
591bool SSLClientSocketOpenSSL::GetSSLInfo(SSLInfo* ssl_info) {
592 ssl_info->Reset();
davidben30798ed82014-09-19 19:28:20593 if (server_cert_chain_->empty())
[email protected]b9b651f2013-11-09 04:32:22594 return false;
595
596 ssl_info->cert = server_cert_verify_result_.verified_cert;
597 ssl_info->cert_status = server_cert_verify_result_.cert_status;
598 ssl_info->is_issued_by_known_root =
599 server_cert_verify_result_.is_issued_by_known_root;
600 ssl_info->public_key_hashes =
601 server_cert_verify_result_.public_key_hashes;
602 ssl_info->client_cert_sent =
603 ssl_config_.send_client_cert && ssl_config_.client_cert.get();
604 ssl_info->channel_id_sent = WasChannelIDSent();
[email protected]8bd4e7a2014-08-09 14:49:17605 ssl_info->pinning_failure_log = pinning_failure_log_;
[email protected]b9b651f2013-11-09 04:32:22606
davidbeneb5f8ef32014-09-04 14:14:32607 AddSCTInfoToSSLInfo(ssl_info);
608
[email protected]b9b651f2013-11-09 04:32:22609 const SSL_CIPHER* cipher = SSL_get_current_cipher(ssl_);
610 CHECK(cipher);
611 ssl_info->security_bits = SSL_CIPHER_get_bits(cipher, NULL);
[email protected]b9b651f2013-11-09 04:32:22612
613 ssl_info->connection_status = EncodeSSLConnectionStatus(
[email protected]edfd0f42014-07-22 18:20:37614 SSL_CIPHER_get_id(cipher), 0 /* no compression */,
[email protected]b9b651f2013-11-09 04:32:22615 GetNetSSLVersion(ssl_));
616
davidben09c3d072014-08-25 20:33:58617 if (!SSL_get_secure_renegotiation_support(ssl_))
[email protected]b9b651f2013-11-09 04:32:22618 ssl_info->connection_status |= SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION;
[email protected]b9b651f2013-11-09 04:32:22619
620 if (ssl_config_.version_fallback)
621 ssl_info->connection_status |= SSL_CONNECTION_VERSION_FALLBACK;
622
623 ssl_info->handshake_type = SSL_session_reused(ssl_) ?
624 SSLInfo::HANDSHAKE_RESUME : SSLInfo::HANDSHAKE_FULL;
625
626 DVLOG(3) << "Encoded connection status: cipher suite = "
627 << SSLConnectionStatusToCipherSuite(ssl_info->connection_status)
628 << " version = "
629 << SSLConnectionStatusToVersion(ssl_info->connection_status);
630 return true;
631}
632
633int SSLClientSocketOpenSSL::Read(IOBuffer* buf,
634 int buf_len,
635 const CompletionCallback& callback) {
636 user_read_buf_ = buf;
637 user_read_buf_len_ = buf_len;
638
davidben1b133ad2014-10-23 04:23:13639 int rv = DoReadLoop();
[email protected]b9b651f2013-11-09 04:32:22640
641 if (rv == ERR_IO_PENDING) {
642 user_read_callback_ = callback;
643 } else {
[email protected]0dc88b32014-03-26 20:12:28644 if (rv > 0)
645 was_ever_used_ = true;
[email protected]b9b651f2013-11-09 04:32:22646 user_read_buf_ = NULL;
647 user_read_buf_len_ = 0;
[email protected]8e458552014-08-05 00:02:15648 if (rv <= 0) {
649 // Failure of a read attempt may indicate a failed false start
650 // connection.
651 OnHandshakeCompletion();
652 }
[email protected]b9b651f2013-11-09 04:32:22653 }
654
655 return rv;
656}
657
658int SSLClientSocketOpenSSL::Write(IOBuffer* buf,
659 int buf_len,
660 const CompletionCallback& callback) {
661 user_write_buf_ = buf;
662 user_write_buf_len_ = buf_len;
663
davidben1b133ad2014-10-23 04:23:13664 int rv = DoWriteLoop();
[email protected]b9b651f2013-11-09 04:32:22665
666 if (rv == ERR_IO_PENDING) {
667 user_write_callback_ = callback;
668 } else {
[email protected]0dc88b32014-03-26 20:12:28669 if (rv > 0)
670 was_ever_used_ = true;
[email protected]b9b651f2013-11-09 04:32:22671 user_write_buf_ = NULL;
672 user_write_buf_len_ = 0;
[email protected]8e458552014-08-05 00:02:15673 if (rv < 0) {
674 // Failure of a write attempt may indicate a failed false start
675 // connection.
676 OnHandshakeCompletion();
677 }
[email protected]b9b651f2013-11-09 04:32:22678 }
679
680 return rv;
681}
682
[email protected]28b96d1c2014-04-09 12:21:15683int SSLClientSocketOpenSSL::SetReceiveBufferSize(int32 size) {
[email protected]b9b651f2013-11-09 04:32:22684 return transport_->socket()->SetReceiveBufferSize(size);
685}
686
[email protected]28b96d1c2014-04-09 12:21:15687int SSLClientSocketOpenSSL::SetSendBufferSize(int32 size) {
[email protected]b9b651f2013-11-09 04:32:22688 return transport_->socket()->SetSendBufferSize(size);
689}
690
[email protected]c8a80e92014-05-17 16:02:08691int SSLClientSocketOpenSSL::Init() {
[email protected]9e733f32010-10-04 18:19:08692 DCHECK(!ssl_);
693 DCHECK(!transport_bio_);
694
[email protected]b29af7d2010-12-14 11:52:47695 SSLContext* context = SSLContext::GetInstance();
[email protected]4b559b4d2011-04-14 17:37:14696 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
[email protected]d518cd92010-09-29 12:27:44697
[email protected]fbef13932010-11-23 12:38:53698 ssl_ = SSL_new(context->ssl_ctx());
699 if (!ssl_ || !context->SetClientSocketForSSL(ssl_, this))
[email protected]c8a80e92014-05-17 16:02:08700 return ERR_UNEXPECTED;
[email protected]fbef13932010-11-23 12:38:53701
702 if (!SSL_set_tlsext_host_name(ssl_, host_and_port_.host().c_str()))
[email protected]c8a80e92014-05-17 16:02:08703 return ERR_UNEXPECTED;
[email protected]fbef13932010-11-23 12:38:53704
[email protected]e4738ba52014-08-07 10:07:22705 // Set an OpenSSL callback to monitor this SSL*'s connection.
706 SSL_set_info_callback(ssl_, &InfoCallback);
707
[email protected]1279de12013-12-03 15:13:32708 trying_cached_session_ = context->session_cache()->SetSSLSessionWithKey(
[email protected]8e458552014-08-05 00:02:15709 ssl_, GetSessionCacheKey());
[email protected]d518cd92010-09-29 12:27:44710
711 BIO* ssl_bio = NULL;
[email protected]fbef13932010-11-23 12:38:53712 // 0 => use default buffer sizes.
713 if (!BIO_new_bio_pair(&ssl_bio, 0, &transport_bio_, 0))
[email protected]c8a80e92014-05-17 16:02:08714 return ERR_UNEXPECTED;
[email protected]d518cd92010-09-29 12:27:44715 DCHECK(ssl_bio);
716 DCHECK(transport_bio_);
717
[email protected]5aea79182014-07-14 20:43:41718 // Install a callback on OpenSSL's end to plumb transport errors through.
[email protected]64b5c892014-08-08 09:39:26719 BIO_set_callback(ssl_bio, BIOCallback);
[email protected]5aea79182014-07-14 20:43:41720 BIO_set_callback_arg(ssl_bio, reinterpret_cast<char*>(this));
721
[email protected]d518cd92010-09-29 12:27:44722 SSL_set_bio(ssl_, ssl_bio, ssl_bio);
723
[email protected]9e733f32010-10-04 18:19:08724 // OpenSSL defaults some options to on, others to off. To avoid ambiguity,
725 // set everything we care about to an absolute value.
[email protected]fb10e2282010-12-01 17:08:48726 SslSetClearMask options;
727 options.ConfigureFlag(SSL_OP_NO_SSLv2, true);
[email protected]80c75f682012-05-26 16:22:17728 bool ssl3_enabled = (ssl_config_.version_min == SSL_PROTOCOL_VERSION_SSL3);
729 options.ConfigureFlag(SSL_OP_NO_SSLv3, !ssl3_enabled);
730 bool tls1_enabled = (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1 &&
731 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1);
732 options.ConfigureFlag(SSL_OP_NO_TLSv1, !tls1_enabled);
[email protected]80c75f682012-05-26 16:22:17733 bool tls1_1_enabled =
734 (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1_1 &&
735 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1_1);
736 options.ConfigureFlag(SSL_OP_NO_TLSv1_1, !tls1_1_enabled);
[email protected]80c75f682012-05-26 16:22:17737 bool tls1_2_enabled =
738 (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1_2 &&
739 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1_2);
740 options.ConfigureFlag(SSL_OP_NO_TLSv1_2, !tls1_2_enabled);
[email protected]fb10e2282010-12-01 17:08:48741
[email protected]d0f00492012-08-03 22:35:13742 options.ConfigureFlag(SSL_OP_NO_COMPRESSION, true);
[email protected]9e733f32010-10-04 18:19:08743
744 // TODO(joth): Set this conditionally, see http://crbug.com/55410
[email protected]fb10e2282010-12-01 17:08:48745 options.ConfigureFlag(SSL_OP_LEGACY_SERVER_CONNECT, true);
[email protected]9e733f32010-10-04 18:19:08746
[email protected]fb10e2282010-12-01 17:08:48747 SSL_set_options(ssl_, options.set_mask);
748 SSL_clear_options(ssl_, options.clear_mask);
[email protected]9e733f32010-10-04 18:19:08749
[email protected]fb10e2282010-12-01 17:08:48750 // Same as above, this time for the SSL mode.
751 SslSetClearMask mode;
[email protected]9e733f32010-10-04 18:19:08752
[email protected]fb10e2282010-12-01 17:08:48753 mode.ConfigureFlag(SSL_MODE_RELEASE_BUFFERS, true);
ishermane5c05e12014-09-09 20:32:15754 mode.ConfigureFlag(SSL_MODE_CBC_RECORD_SPLITTING, true);
[email protected]fb10e2282010-12-01 17:08:48755
[email protected]b788de02014-04-23 18:06:07756 mode.ConfigureFlag(SSL_MODE_HANDSHAKE_CUTTHROUGH,
757 ssl_config_.false_start_enabled);
758
[email protected]fb10e2282010-12-01 17:08:48759 SSL_set_mode(ssl_, mode.set_mask);
760 SSL_clear_mode(ssl_, mode.clear_mask);
[email protected]109805a2010-12-07 18:17:06761
762 // Removing ciphers by ID from OpenSSL is a bit involved as we must use the
763 // textual name with SSL_set_cipher_list because there is no public API to
764 // directly remove a cipher by ID.
765 STACK_OF(SSL_CIPHER)* ciphers = SSL_get_ciphers(ssl_);
766 DCHECK(ciphers);
767 // See SSLConfig::disabled_cipher_suites for description of the suites
[email protected]9b4bc4a92013-08-20 22:59:07768 // disabled by default. Note that !SHA256 and !SHA384 only remove HMAC-SHA256
769 // and HMAC-SHA384 cipher suites, not GCM cipher suites with SHA256 or SHA384
770 // as the handshake hash.
771 std::string command("DEFAULT:!NULL:!aNULL:!IDEA:!FZA:!SRP:!SHA256:!SHA384:"
772 "!aECDH:!AESGCM+AES256");
[email protected]109805a2010-12-07 18:17:06773 // Walk through all the installed ciphers, seeing if any need to be
774 // appended to the cipher removal |command|.
[email protected]edfd0f42014-07-22 18:20:37775 for (size_t i = 0; i < sk_SSL_CIPHER_num(ciphers); ++i) {
[email protected]109805a2010-12-07 18:17:06776 const SSL_CIPHER* cipher = sk_SSL_CIPHER_value(ciphers, i);
777 const uint16 id = SSL_CIPHER_get_id(cipher);
778 // Remove any ciphers with a strength of less than 80 bits. Note the NSS
779 // implementation uses "effective" bits here but OpenSSL does not provide
780 // this detail. This only impacts Triple DES: reports 112 vs. 168 bits,
781 // both of which are greater than 80 anyway.
782 bool disable = SSL_CIPHER_get_bits(cipher, NULL) < 80;
783 if (!disable) {
784 disable = std::find(ssl_config_.disabled_cipher_suites.begin(),
785 ssl_config_.disabled_cipher_suites.end(), id) !=
786 ssl_config_.disabled_cipher_suites.end();
787 }
788 if (disable) {
789 const char* name = SSL_CIPHER_get_name(cipher);
790 DVLOG(3) << "Found cipher to remove: '" << name << "', ID: " << id
791 << " strength: " << SSL_CIPHER_get_bits(cipher, NULL);
792 command.append(":!");
793 command.append(name);
794 }
795 }
davidben8ecc3072014-09-03 23:19:09796
797 // Disable ECDSA cipher suites on platforms that do not support ECDSA
798 // signed certificates, as servers may use the presence of such
799 // ciphersuites as a hint to send an ECDSA certificate.
800#if defined(OS_WIN)
801 if (base::win::GetVersion() < base::win::VERSION_VISTA)
802 command.append(":!ECDSA");
803#endif
804
[email protected]109805a2010-12-07 18:17:06805 int rv = SSL_set_cipher_list(ssl_, command.c_str());
806 // If this fails (rv = 0) it means there are no ciphers enabled on this SSL.
807 // This will almost certainly result in the socket failing to complete the
808 // handshake at which point the appropriate error is bubbled up to the client.
809 LOG_IF(WARNING, rv != 1) << "SSL_set_cipher_list('" << command << "') "
810 "returned " << rv;
[email protected]ee0f2aa82013-10-25 11:59:26811
[email protected]0d0a6872014-07-26 18:05:11812 if (ssl_config_.version_fallback)
813 SSL_enable_fallback_scsv(ssl_);
814
[email protected]ee0f2aa82013-10-25 11:59:26815 // TLS channel ids.
[email protected]6b8a3c742014-07-25 00:25:35816 if (IsChannelIDEnabled(ssl_config_, channel_id_service_)) {
[email protected]ee0f2aa82013-10-25 11:59:26817 SSL_enable_tls_channel_id(ssl_);
818 }
819
[email protected]abc44b752014-07-30 03:52:15820 if (!ssl_config_.next_protos.empty()) {
821 std::vector<uint8_t> wire_protos =
822 SerializeNextProtos(ssl_config_.next_protos);
823 SSL_set_alpn_protos(ssl_, wire_protos.empty() ? NULL : &wire_protos[0],
824 wire_protos.size());
825 }
826
davidbeneb5f8ef32014-09-04 14:14:32827 if (ssl_config_.signed_cert_timestamps_enabled) {
828 SSL_enable_signed_cert_timestamps(ssl_);
829 SSL_enable_ocsp_stapling(ssl_);
830 }
831
832 // TODO(davidben): Enable OCSP stapling on platforms which support it and pass
833 // into the certificate verifier. https://crbug.com/398677
834
[email protected]c8a80e92014-05-17 16:02:08835 return OK;
[email protected]d518cd92010-09-29 12:27:44836}
837
[email protected]b9b651f2013-11-09 04:32:22838void SSLClientSocketOpenSSL::DoReadCallback(int rv) {
839 // Since Run may result in Read being called, clear |user_read_callback_|
840 // up front.
[email protected]0dc88b32014-03-26 20:12:28841 if (rv > 0)
842 was_ever_used_ = true;
[email protected]b9b651f2013-11-09 04:32:22843 user_read_buf_ = NULL;
844 user_read_buf_len_ = 0;
[email protected]8e458552014-08-05 00:02:15845 if (rv <= 0) {
846 // Failure of a read attempt may indicate a failed false start
847 // connection.
848 OnHandshakeCompletion();
849 }
[email protected]b9b651f2013-11-09 04:32:22850 base::ResetAndReturn(&user_read_callback_).Run(rv);
851}
852
853void SSLClientSocketOpenSSL::DoWriteCallback(int rv) {
854 // Since Run may result in Write being called, clear |user_write_callback_|
855 // up front.
[email protected]0dc88b32014-03-26 20:12:28856 if (rv > 0)
857 was_ever_used_ = true;
[email protected]b9b651f2013-11-09 04:32:22858 user_write_buf_ = NULL;
859 user_write_buf_len_ = 0;
[email protected]8e458552014-08-05 00:02:15860 if (rv < 0) {
861 // Failure of a write attempt may indicate a failed false start
862 // connection.
863 OnHandshakeCompletion();
864 }
[email protected]b9b651f2013-11-09 04:32:22865 base::ResetAndReturn(&user_write_callback_).Run(rv);
866}
867
[email protected]8e458552014-08-05 00:02:15868void SSLClientSocketOpenSSL::OnHandshakeCompletion() {
869 if (!handshake_completion_callback_.is_null())
870 base::ResetAndReturn(&handshake_completion_callback_).Run();
871}
872
[email protected]b9b651f2013-11-09 04:32:22873bool SSLClientSocketOpenSSL::DoTransportIO() {
874 bool network_moved = false;
875 int rv;
876 // Read and write as much data as possible. The loop is necessary because
877 // Write() may return synchronously.
878 do {
879 rv = BufferSend();
880 if (rv != ERR_IO_PENDING && rv != 0)
881 network_moved = true;
882 } while (rv > 0);
[email protected]5aea79182014-07-14 20:43:41883 if (transport_read_error_ == OK && BufferRecv() != ERR_IO_PENDING)
[email protected]b9b651f2013-11-09 04:32:22884 network_moved = true;
885 return network_moved;
886}
887
888int SSLClientSocketOpenSSL::DoHandshake() {
889 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
[email protected]c8a80e92014-05-17 16:02:08890 int net_error = OK;
[email protected]b9b651f2013-11-09 04:32:22891 int rv = SSL_do_handshake(ssl_);
892
893 if (client_auth_cert_needed_) {
894 net_error = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
895 // If the handshake already succeeded (because the server requests but
896 // doesn't require a client cert), we need to invalidate the SSL session
897 // so that we won't try to resume the non-client-authenticated session in
898 // the next handshake. This will cause the server to ask for a client
899 // cert again.
900 if (rv == 1) {
901 // Remove from session cache but don't clear this connection.
902 SSL_SESSION* session = SSL_get_session(ssl_);
903 if (session) {
904 int rv = SSL_CTX_remove_session(SSL_get_SSL_CTX(ssl_), session);
905 LOG_IF(WARNING, !rv) << "Couldn't invalidate SSL session: " << session;
906 }
907 }
908 } else if (rv == 1) {
909 if (trying_cached_session_ && logging::DEBUG_MODE) {
910 DVLOG(2) << "Result of session reuse for " << host_and_port_.ToString()
911 << " is: " << (SSL_session_reused(ssl_) ? "Success" : "Fail");
912 }
[email protected]abc44b752014-07-30 03:52:15913
Adam Langley32352ad2014-10-14 22:31:00914 if (ssl_config_.version_fallback &&
915 ssl_config_.version_max < ssl_config_.version_fallback_min) {
916 return ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION;
917 }
918
[email protected]abc44b752014-07-30 03:52:15919 // SSL handshake is completed. If NPN wasn't negotiated, see if ALPN was.
920 if (npn_status_ == kNextProtoUnsupported) {
921 const uint8_t* alpn_proto = NULL;
922 unsigned alpn_len = 0;
923 SSL_get0_alpn_selected(ssl_, &alpn_proto, &alpn_len);
924 if (alpn_len > 0) {
925 npn_proto_.assign(reinterpret_cast<const char*>(alpn_proto), alpn_len);
926 npn_status_ = kNextProtoNegotiated;
bnc0d28ea52014-10-13 15:15:38927 set_negotiation_extension(kExtensionALPN);
[email protected]abc44b752014-07-30 03:52:15928 }
929 }
930
davidben09c3d072014-08-25 20:33:58931 RecordChannelIDSupport(channel_id_service_,
932 channel_id_xtn_negotiated_,
933 ssl_config_.channel_id_enabled,
934 crypto::ECPrivateKey::IsSupported());
935
davidbeneb5f8ef32014-09-04 14:14:32936 uint8_t* ocsp_response;
937 size_t ocsp_response_len;
938 SSL_get0_ocsp_response(ssl_, &ocsp_response, &ocsp_response_len);
939 set_stapled_ocsp_response_received(ocsp_response_len != 0);
940
941 uint8_t* sct_list;
942 size_t sct_list_len;
943 SSL_get0_signed_cert_timestamp_list(ssl_, &sct_list, &sct_list_len);
944 set_signed_cert_timestamps_received(sct_list_len != 0);
945
[email protected]abc44b752014-07-30 03:52:15946 // Verify the certificate.
davidben30798ed82014-09-19 19:28:20947 UpdateServerCert();
[email protected]b9b651f2013-11-09 04:32:22948 GotoState(STATE_VERIFY_CERT);
949 } else {
950 int ssl_error = SSL_get_error(ssl_, rv);
951
952 if (ssl_error == SSL_ERROR_WANT_CHANNEL_ID_LOOKUP) {
[email protected]faff9852014-06-21 06:13:46953 // The server supports channel ID. Stop to look one up before returning to
954 // the handshake.
955 channel_id_xtn_negotiated_ = true;
956 GotoState(STATE_CHANNEL_ID_LOOKUP);
957 return OK;
[email protected]b9b651f2013-11-09 04:32:22958 }
959
davidbena4409c62014-08-27 17:05:51960 OpenSSLErrorInfo error_info;
961 net_error = MapOpenSSLErrorWithDetails(ssl_error, err_tracer, &error_info);
[email protected]faff9852014-06-21 06:13:46962
[email protected]b9b651f2013-11-09 04:32:22963 // If not done, stay in this state
964 if (net_error == ERR_IO_PENDING) {
965 GotoState(STATE_HANDSHAKE);
966 } else {
967 LOG(ERROR) << "handshake failed; returned " << rv
968 << ", SSL error code " << ssl_error
969 << ", net_error " << net_error;
970 net_log_.AddEvent(
971 NetLog::TYPE_SSL_HANDSHAKE_ERROR,
davidbena4409c62014-08-27 17:05:51972 CreateNetLogOpenSSLErrorCallback(net_error, ssl_error, error_info));
[email protected]b9b651f2013-11-09 04:32:22973 }
974 }
975 return net_error;
976}
977
[email protected]faff9852014-06-21 06:13:46978int SSLClientSocketOpenSSL::DoChannelIDLookup() {
979 GotoState(STATE_CHANNEL_ID_LOOKUP_COMPLETE);
[email protected]6b8a3c742014-07-25 00:25:35980 return channel_id_service_->GetOrCreateChannelID(
[email protected]faff9852014-06-21 06:13:46981 host_and_port_.host(),
982 &channel_id_private_key_,
983 &channel_id_cert_,
984 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete,
985 base::Unretained(this)),
986 &channel_id_request_handle_);
987}
988
989int SSLClientSocketOpenSSL::DoChannelIDLookupComplete(int result) {
990 if (result < 0)
991 return result;
992
993 DCHECK_LT(0u, channel_id_private_key_.size());
994 // Decode key.
995 std::vector<uint8> encrypted_private_key_info;
996 std::vector<uint8> subject_public_key_info;
997 encrypted_private_key_info.assign(
998 channel_id_private_key_.data(),
999 channel_id_private_key_.data() + channel_id_private_key_.size());
1000 subject_public_key_info.assign(
1001 channel_id_cert_.data(),
1002 channel_id_cert_.data() + channel_id_cert_.size());
1003 scoped_ptr<crypto::ECPrivateKey> ec_private_key(
1004 crypto::ECPrivateKey::CreateFromEncryptedPrivateKeyInfo(
[email protected]6b8a3c742014-07-25 00:25:351005 ChannelIDService::kEPKIPassword,
[email protected]faff9852014-06-21 06:13:461006 encrypted_private_key_info,
1007 subject_public_key_info));
1008 if (!ec_private_key) {
1009 LOG(ERROR) << "Failed to import Channel ID.";
1010 return ERR_CHANNEL_ID_IMPORT_FAILED;
1011 }
1012
1013 // Hand the key to OpenSSL. Check for error in case OpenSSL rejects the key
1014 // type.
1015 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1016 int rv = SSL_set1_tls_channel_id(ssl_, ec_private_key->key());
1017 if (!rv) {
1018 LOG(ERROR) << "Failed to set Channel ID.";
1019 int err = SSL_get_error(ssl_, rv);
1020 return MapOpenSSLError(err, err_tracer);
1021 }
1022
1023 // Return to the handshake.
1024 set_channel_id_sent(true);
1025 GotoState(STATE_HANDSHAKE);
1026 return OK;
1027}
1028
[email protected]b9b651f2013-11-09 04:32:221029int SSLClientSocketOpenSSL::DoVerifyCert(int result) {
davidben30798ed82014-09-19 19:28:201030 DCHECK(!server_cert_chain_->empty());
davidben09c3d072014-08-25 20:33:581031 DCHECK(start_cert_verification_time_.is_null());
davidben30798ed82014-09-19 19:28:201032
[email protected]b9b651f2013-11-09 04:32:221033 GotoState(STATE_VERIFY_CERT_COMPLETE);
1034
davidben30798ed82014-09-19 19:28:201035 // If the certificate is bad and has been previously accepted, use
1036 // the previous status and bypass the error.
1037 base::StringPiece der_cert;
1038 if (!x509_util::GetDER(server_cert_chain_->Get(0), &der_cert)) {
1039 NOTREACHED();
1040 return ERR_CERT_INVALID;
1041 }
[email protected]b9b651f2013-11-09 04:32:221042 CertStatus cert_status;
davidben30798ed82014-09-19 19:28:201043 if (ssl_config_.IsAllowedBadCert(der_cert, &cert_status)) {
[email protected]b9b651f2013-11-09 04:32:221044 VLOG(1) << "Received an expected bad cert with status: " << cert_status;
1045 server_cert_verify_result_.Reset();
1046 server_cert_verify_result_.cert_status = cert_status;
1047 server_cert_verify_result_.verified_cert = server_cert_;
1048 return OK;
1049 }
1050
davidben30798ed82014-09-19 19:28:201051 // When running in a sandbox, it may not be possible to create an
1052 // X509Certificate*, as that may depend on OS functionality blocked
1053 // in the sandbox.
1054 if (!server_cert_.get()) {
1055 server_cert_verify_result_.Reset();
1056 server_cert_verify_result_.cert_status = CERT_STATUS_INVALID;
1057 return ERR_CERT_INVALID;
1058 }
1059
davidben09c3d072014-08-25 20:33:581060 start_cert_verification_time_ = base::TimeTicks::Now();
1061
[email protected]b9b651f2013-11-09 04:32:221062 int flags = 0;
1063 if (ssl_config_.rev_checking_enabled)
1064 flags |= CertVerifier::VERIFY_REV_CHECKING_ENABLED;
1065 if (ssl_config_.verify_ev_cert)
1066 flags |= CertVerifier::VERIFY_EV_CERT;
1067 if (ssl_config_.cert_io_enabled)
1068 flags |= CertVerifier::VERIFY_CERT_IO_ENABLED;
1069 if (ssl_config_.rev_checking_required_local_anchors)
1070 flags |= CertVerifier::VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS;
1071 verifier_.reset(new SingleRequestCertVerifier(cert_verifier_));
1072 return verifier_->Verify(
1073 server_cert_.get(),
1074 host_and_port_.host(),
1075 flags,
[email protected]591cffcd2014-08-18 20:02:301076 // TODO(davidben): Route the CRLSet through SSLConfig so
1077 // SSLClientSocket doesn't depend on SSLConfigService.
1078 SSLConfigService::GetCRLSet().get(),
[email protected]b9b651f2013-11-09 04:32:221079 &server_cert_verify_result_,
1080 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete,
1081 base::Unretained(this)),
1082 net_log_);
1083}
1084
1085int SSLClientSocketOpenSSL::DoVerifyCertComplete(int result) {
1086 verifier_.reset();
1087
davidben09c3d072014-08-25 20:33:581088 if (!start_cert_verification_time_.is_null()) {
1089 base::TimeDelta verify_time =
1090 base::TimeTicks::Now() - start_cert_verification_time_;
1091 if (result == OK) {
1092 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTime", verify_time);
1093 } else {
1094 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTimeError", verify_time);
1095 }
1096 }
1097
[email protected]8bd4e7a2014-08-09 14:49:171098 const CertStatus cert_status = server_cert_verify_result_.cert_status;
1099 if (transport_security_state_ &&
1100 (result == OK ||
1101 (IsCertificateError(result) && IsCertStatusMinorError(cert_status))) &&
1102 !transport_security_state_->CheckPublicKeyPins(
1103 host_and_port_.host(),
[email protected]8bd4e7a2014-08-09 14:49:171104 server_cert_verify_result_.is_issued_by_known_root,
1105 server_cert_verify_result_.public_key_hashes,
1106 &pinning_failure_log_)) {
1107 result = ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN;
1108 }
1109
eranmefbd3132014-10-28 16:35:161110 scoped_refptr<ct::EVCertsWhitelist> ev_whitelist =
1111 SSLConfigService::GetEVCertsWhitelist();
1112 if (server_cert_verify_result_.cert_status & CERT_STATUS_IS_EV) {
1113 if (ev_whitelist.get() && ev_whitelist->IsValid()) {
1114 const SHA256HashValue fingerprint(
1115 X509Certificate::CalculateFingerprint256(
1116 server_cert_verify_result_.verified_cert->os_cert_handle()));
1117
1118 UMA_HISTOGRAM_BOOLEAN(
1119 "Net.SSL_EVCertificateInWhitelist",
1120 ev_whitelist->ContainsCertificateHash(
1121 std::string(reinterpret_cast<const char*>(fingerprint.data), 8)));
1122 }
1123 }
1124
[email protected]b9b651f2013-11-09 04:32:221125 if (result == OK) {
davidbeneb5f8ef32014-09-04 14:14:321126 // Only check Certificate Transparency if there were no other errors with
1127 // the connection.
1128 VerifyCT();
1129
[email protected]b9b651f2013-11-09 04:32:221130 // TODO(joth): Work out if we need to remember the intermediate CA certs
1131 // when the server sends them to us, and do so here.
[email protected]a8fed1742013-12-27 02:14:241132 SSLContext::GetInstance()->session_cache()->MarkSSLSessionAsGood(ssl_);
[email protected]e4738ba52014-08-07 10:07:221133 marked_session_as_good_ = true;
1134 CheckIfHandshakeFinished();
[email protected]b9b651f2013-11-09 04:32:221135 } else {
1136 DVLOG(1) << "DoVerifyCertComplete error " << ErrorToString(result)
1137 << " (" << result << ")";
1138 }
1139
[email protected]64b5c892014-08-08 09:39:261140 completed_connect_ = true;
[email protected]8bd4e7a2014-08-09 14:49:171141
[email protected]b9b651f2013-11-09 04:32:221142 // Exit DoHandshakeLoop and return the result to the caller to Connect.
1143 DCHECK_EQ(STATE_NONE, next_handshake_state_);
1144 return result;
1145}
1146
1147void SSLClientSocketOpenSSL::DoConnectCallback(int rv) {
[email protected]8e458552014-08-05 00:02:151148 if (rv < OK)
1149 OnHandshakeCompletion();
[email protected]b9b651f2013-11-09 04:32:221150 if (!user_connect_callback_.is_null()) {
1151 CompletionCallback c = user_connect_callback_;
1152 user_connect_callback_.Reset();
1153 c.Run(rv > OK ? OK : rv);
1154 }
1155}
1156
davidben30798ed82014-09-19 19:28:201157void SSLClientSocketOpenSSL::UpdateServerCert() {
[email protected]76e85392014-03-20 17:54:141158 server_cert_chain_->Reset(SSL_get_peer_cert_chain(ssl_));
[email protected]7f38da8a2014-03-17 16:44:261159 server_cert_ = server_cert_chain_->AsOSChain();
[email protected]76e85392014-03-20 17:54:141160
davidben30798ed82014-09-19 19:28:201161 if (server_cert_.get()) {
1162 net_log_.AddEvent(
1163 NetLog::TYPE_SSL_CERTIFICATES_RECEIVED,
1164 base::Bind(&NetLogX509CertificateCallback,
1165 base::Unretained(server_cert_.get())));
1166 }
[email protected]b9b651f2013-11-09 04:32:221167}
1168
davidbeneb5f8ef32014-09-04 14:14:321169void SSLClientSocketOpenSSL::VerifyCT() {
1170 if (!cert_transparency_verifier_)
1171 return;
1172
1173 uint8_t* ocsp_response_raw;
1174 size_t ocsp_response_len;
1175 SSL_get0_ocsp_response(ssl_, &ocsp_response_raw, &ocsp_response_len);
1176 std::string ocsp_response;
1177 if (ocsp_response_len > 0) {
1178 ocsp_response.assign(reinterpret_cast<const char*>(ocsp_response_raw),
1179 ocsp_response_len);
1180 }
1181
1182 uint8_t* sct_list_raw;
1183 size_t sct_list_len;
1184 SSL_get0_signed_cert_timestamp_list(ssl_, &sct_list_raw, &sct_list_len);
1185 std::string sct_list;
1186 if (sct_list_len > 0)
1187 sct_list.assign(reinterpret_cast<const char*>(sct_list_raw), sct_list_len);
1188
1189 // Note that this is a completely synchronous operation: The CT Log Verifier
1190 // gets all the data it needs for SCT verification and does not do any
1191 // external communication.
1192 int result = cert_transparency_verifier_->Verify(
1193 server_cert_verify_result_.verified_cert.get(),
1194 ocsp_response, sct_list, &ct_verify_result_, net_log_);
1195
1196 VLOG(1) << "CT Verification complete: result " << result
1197 << " Invalid scts: " << ct_verify_result_.invalid_scts.size()
1198 << " Verified scts: " << ct_verify_result_.verified_scts.size()
1199 << " scts from unknown logs: "
1200 << ct_verify_result_.unknown_logs_scts.size();
1201}
1202
[email protected]b9b651f2013-11-09 04:32:221203void SSLClientSocketOpenSSL::OnHandshakeIOComplete(int result) {
1204 int rv = DoHandshakeLoop(result);
1205 if (rv != ERR_IO_PENDING) {
1206 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
1207 DoConnectCallback(rv);
1208 }
1209}
1210
1211void SSLClientSocketOpenSSL::OnSendComplete(int result) {
1212 if (next_handshake_state_ == STATE_HANDSHAKE) {
1213 // In handshake phase.
1214 OnHandshakeIOComplete(result);
1215 return;
1216 }
1217
1218 // OnSendComplete may need to call DoPayloadRead while the renegotiation
1219 // handshake is in progress.
1220 int rv_read = ERR_IO_PENDING;
1221 int rv_write = ERR_IO_PENDING;
1222 bool network_moved;
1223 do {
1224 if (user_read_buf_.get())
1225 rv_read = DoPayloadRead();
1226 if (user_write_buf_.get())
1227 rv_write = DoPayloadWrite();
1228 network_moved = DoTransportIO();
1229 } while (rv_read == ERR_IO_PENDING && rv_write == ERR_IO_PENDING &&
1230 (user_read_buf_.get() || user_write_buf_.get()) && network_moved);
1231
1232 // Performing the Read callback may cause |this| to be deleted. If this
1233 // happens, the Write callback should not be invoked. Guard against this by
1234 // holding a WeakPtr to |this| and ensuring it's still valid.
1235 base::WeakPtr<SSLClientSocketOpenSSL> guard(weak_factory_.GetWeakPtr());
1236 if (user_read_buf_.get() && rv_read != ERR_IO_PENDING)
1237 DoReadCallback(rv_read);
1238
1239 if (!guard.get())
1240 return;
1241
1242 if (user_write_buf_.get() && rv_write != ERR_IO_PENDING)
1243 DoWriteCallback(rv_write);
1244}
1245
1246void SSLClientSocketOpenSSL::OnRecvComplete(int result) {
1247 if (next_handshake_state_ == STATE_HANDSHAKE) {
1248 // In handshake phase.
1249 OnHandshakeIOComplete(result);
1250 return;
1251 }
1252
1253 // Network layer received some data, check if client requested to read
1254 // decrypted data.
1255 if (!user_read_buf_.get())
1256 return;
1257
davidben1b133ad2014-10-23 04:23:131258 int rv = DoReadLoop();
[email protected]b9b651f2013-11-09 04:32:221259 if (rv != ERR_IO_PENDING)
1260 DoReadCallback(rv);
1261}
1262
1263int SSLClientSocketOpenSSL::DoHandshakeLoop(int last_io_result) {
1264 int rv = last_io_result;
1265 do {
1266 // Default to STATE_NONE for next state.
1267 // (This is a quirk carried over from the windows
1268 // implementation. It makes reading the logs a bit harder.)
1269 // State handlers can and often do call GotoState just
1270 // to stay in the current state.
1271 State state = next_handshake_state_;
1272 GotoState(STATE_NONE);
1273 switch (state) {
1274 case STATE_HANDSHAKE:
1275 rv = DoHandshake();
1276 break;
[email protected]faff9852014-06-21 06:13:461277 case STATE_CHANNEL_ID_LOOKUP:
1278 DCHECK_EQ(OK, rv);
1279 rv = DoChannelIDLookup();
1280 break;
1281 case STATE_CHANNEL_ID_LOOKUP_COMPLETE:
1282 rv = DoChannelIDLookupComplete(rv);
1283 break;
[email protected]b9b651f2013-11-09 04:32:221284 case STATE_VERIFY_CERT:
[email protected]faff9852014-06-21 06:13:461285 DCHECK_EQ(OK, rv);
[email protected]b9b651f2013-11-09 04:32:221286 rv = DoVerifyCert(rv);
1287 break;
1288 case STATE_VERIFY_CERT_COMPLETE:
1289 rv = DoVerifyCertComplete(rv);
1290 break;
1291 case STATE_NONE:
1292 default:
1293 rv = ERR_UNEXPECTED;
1294 NOTREACHED() << "unexpected state" << state;
1295 break;
1296 }
1297
1298 bool network_moved = DoTransportIO();
1299 if (network_moved && next_handshake_state_ == STATE_HANDSHAKE) {
1300 // In general we exit the loop if rv is ERR_IO_PENDING. In this
1301 // special case we keep looping even if rv is ERR_IO_PENDING because
1302 // the transport IO may allow DoHandshake to make progress.
1303 rv = OK; // This causes us to stay in the loop.
1304 }
1305 } while (rv != ERR_IO_PENDING && next_handshake_state_ != STATE_NONE);
[email protected]8e458552014-08-05 00:02:151306
[email protected]b9b651f2013-11-09 04:32:221307 return rv;
1308}
1309
davidben1b133ad2014-10-23 04:23:131310int SSLClientSocketOpenSSL::DoReadLoop() {
[email protected]b9b651f2013-11-09 04:32:221311 bool network_moved;
1312 int rv;
1313 do {
1314 rv = DoPayloadRead();
1315 network_moved = DoTransportIO();
1316 } while (rv == ERR_IO_PENDING && network_moved);
1317
1318 return rv;
1319}
1320
davidben1b133ad2014-10-23 04:23:131321int SSLClientSocketOpenSSL::DoWriteLoop() {
[email protected]b9b651f2013-11-09 04:32:221322 bool network_moved;
1323 int rv;
1324 do {
1325 rv = DoPayloadWrite();
1326 network_moved = DoTransportIO();
1327 } while (rv == ERR_IO_PENDING && network_moved);
1328
1329 return rv;
1330}
1331
1332int SSLClientSocketOpenSSL::DoPayloadRead() {
1333 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1334
1335 int rv;
1336 if (pending_read_error_ != kNoPendingReadResult) {
1337 rv = pending_read_error_;
1338 pending_read_error_ = kNoPendingReadResult;
1339 if (rv == 0) {
1340 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED,
1341 rv, user_read_buf_->data());
davidbenb8c23212014-10-28 00:12:161342 } else {
1343 net_log_.AddEvent(
1344 NetLog::TYPE_SSL_READ_ERROR,
1345 CreateNetLogOpenSSLErrorCallback(rv, pending_read_ssl_error_,
1346 pending_read_error_info_));
[email protected]b9b651f2013-11-09 04:32:221347 }
davidbenb8c23212014-10-28 00:12:161348 pending_read_ssl_error_ = SSL_ERROR_NONE;
1349 pending_read_error_info_ = OpenSSLErrorInfo();
[email protected]b9b651f2013-11-09 04:32:221350 return rv;
1351 }
1352
1353 int total_bytes_read = 0;
1354 do {
1355 rv = SSL_read(ssl_, user_read_buf_->data() + total_bytes_read,
1356 user_read_buf_len_ - total_bytes_read);
1357 if (rv > 0)
1358 total_bytes_read += rv;
1359 } while (total_bytes_read < user_read_buf_len_ && rv > 0);
1360
1361 if (total_bytes_read == user_read_buf_len_) {
1362 rv = total_bytes_read;
1363 } else {
1364 // Otherwise, an error occurred (rv <= 0). The error needs to be handled
1365 // immediately, while the OpenSSL errors are still available in
1366 // thread-local storage. However, the handled/remapped error code should
1367 // only be returned if no application data was already read; if it was, the
1368 // error code should be deferred until the next call of DoPayloadRead.
1369 //
1370 // If no data was read, |*next_result| will point to the return value of
1371 // this function. If at least some data was read, |*next_result| will point
1372 // to |pending_read_error_|, to be returned in a future call to
1373 // DoPayloadRead() (e.g.: after the current data is handled).
1374 int *next_result = &rv;
1375 if (total_bytes_read > 0) {
1376 pending_read_error_ = rv;
1377 rv = total_bytes_read;
1378 next_result = &pending_read_error_;
1379 }
1380
1381 if (client_auth_cert_needed_) {
1382 *next_result = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
1383 } else if (*next_result < 0) {
davidbenb8c23212014-10-28 00:12:161384 pending_read_ssl_error_ = SSL_get_error(ssl_, *next_result);
1385 *next_result = MapOpenSSLErrorWithDetails(pending_read_ssl_error_,
1386 err_tracer,
1387 &pending_read_error_info_);
davidbenbe6ce7ec2014-10-20 19:15:561388
1389 // Many servers do not reliably send a close_notify alert when shutting
1390 // down a connection, and instead terminate the TCP connection. This is
1391 // reported as ERR_CONNECTION_CLOSED. Because of this, map the unclean
1392 // shutdown to a graceful EOF, instead of treating it as an error as it
1393 // should be.
1394 if (*next_result == ERR_CONNECTION_CLOSED)
1395 *next_result = 0;
1396
[email protected]b9b651f2013-11-09 04:32:221397 if (rv > 0 && *next_result == ERR_IO_PENDING) {
1398 // If at least some data was read from SSL_read(), do not treat
1399 // insufficient data as an error to return in the next call to
1400 // DoPayloadRead() - instead, let the call fall through to check
1401 // SSL_read() again. This is because DoTransportIO() may complete
1402 // in between the next call to DoPayloadRead(), and thus it is
1403 // important to check SSL_read() on subsequent invocations to see
1404 // if a complete record may now be read.
1405 *next_result = kNoPendingReadResult;
1406 }
1407 }
1408 }
1409
1410 if (rv >= 0) {
1411 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, rv,
1412 user_read_buf_->data());
davidbenb8c23212014-10-28 00:12:161413 } else if (rv != ERR_IO_PENDING) {
1414 net_log_.AddEvent(
1415 NetLog::TYPE_SSL_READ_ERROR,
1416 CreateNetLogOpenSSLErrorCallback(rv, pending_read_ssl_error_,
1417 pending_read_error_info_));
1418 pending_read_ssl_error_ = SSL_ERROR_NONE;
1419 pending_read_error_info_ = OpenSSLErrorInfo();
[email protected]b9b651f2013-11-09 04:32:221420 }
1421 return rv;
1422}
1423
1424int SSLClientSocketOpenSSL::DoPayloadWrite() {
1425 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1426 int rv = SSL_write(ssl_, user_write_buf_->data(), user_write_buf_len_);
[email protected]b9b651f2013-11-09 04:32:221427 if (rv >= 0) {
1428 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_SENT, rv,
1429 user_write_buf_->data());
1430 return rv;
1431 }
1432
davidbenb8c23212014-10-28 00:12:161433 int ssl_error = SSL_get_error(ssl_, rv);
1434 OpenSSLErrorInfo error_info;
1435 int net_error = MapOpenSSLErrorWithDetails(ssl_error, err_tracer,
1436 &error_info);
1437
1438 if (net_error != ERR_IO_PENDING) {
1439 net_log_.AddEvent(
1440 NetLog::TYPE_SSL_WRITE_ERROR,
1441 CreateNetLogOpenSSLErrorCallback(net_error, ssl_error, error_info));
1442 }
1443 return net_error;
[email protected]b9b651f2013-11-09 04:32:221444}
1445
1446int SSLClientSocketOpenSSL::BufferSend(void) {
1447 if (transport_send_busy_)
1448 return ERR_IO_PENDING;
1449
1450 if (!send_buffer_.get()) {
1451 // Get a fresh send buffer out of the send BIO.
[email protected]edfd0f42014-07-22 18:20:371452 size_t max_read = BIO_pending(transport_bio_);
[email protected]b9b651f2013-11-09 04:32:221453 if (!max_read)
1454 return 0; // Nothing pending in the OpenSSL write BIO.
1455 send_buffer_ = new DrainableIOBuffer(new IOBuffer(max_read), max_read);
1456 int read_bytes = BIO_read(transport_bio_, send_buffer_->data(), max_read);
1457 DCHECK_GT(read_bytes, 0);
1458 CHECK_EQ(static_cast<int>(max_read), read_bytes);
1459 }
1460
1461 int rv = transport_->socket()->Write(
1462 send_buffer_.get(),
1463 send_buffer_->BytesRemaining(),
1464 base::Bind(&SSLClientSocketOpenSSL::BufferSendComplete,
1465 base::Unretained(this)));
1466 if (rv == ERR_IO_PENDING) {
1467 transport_send_busy_ = true;
1468 } else {
1469 TransportWriteComplete(rv);
1470 }
1471 return rv;
1472}
1473
1474int SSLClientSocketOpenSSL::BufferRecv(void) {
1475 if (transport_recv_busy_)
1476 return ERR_IO_PENDING;
1477
1478 // Determine how much was requested from |transport_bio_| that was not
1479 // actually available.
1480 size_t requested = BIO_ctrl_get_read_request(transport_bio_);
1481 if (requested == 0) {
1482 // This is not a perfect match of error codes, as no operation is
1483 // actually pending. However, returning 0 would be interpreted as
1484 // a possible sign of EOF, which is also an inappropriate match.
1485 return ERR_IO_PENDING;
1486 }
1487
1488 // Known Issue: While only reading |requested| data is the more correct
1489 // implementation, it has the downside of resulting in frequent reads:
1490 // One read for the SSL record header (~5 bytes) and one read for the SSL
1491 // record body. Rather than issuing these reads to the underlying socket
1492 // (and constantly allocating new IOBuffers), a single Read() request to
1493 // fill |transport_bio_| is issued. As long as an SSL client socket cannot
1494 // be gracefully shutdown (via SSL close alerts) and re-used for non-SSL
1495 // traffic, this over-subscribed Read()ing will not cause issues.
1496 size_t max_write = BIO_ctrl_get_write_guarantee(transport_bio_);
1497 if (!max_write)
1498 return ERR_IO_PENDING;
1499
1500 recv_buffer_ = new IOBuffer(max_write);
1501 int rv = transport_->socket()->Read(
1502 recv_buffer_.get(),
1503 max_write,
1504 base::Bind(&SSLClientSocketOpenSSL::BufferRecvComplete,
1505 base::Unretained(this)));
1506 if (rv == ERR_IO_PENDING) {
1507 transport_recv_busy_ = true;
1508 } else {
[email protected]3e5c6922014-02-06 02:42:161509 rv = TransportReadComplete(rv);
[email protected]b9b651f2013-11-09 04:32:221510 }
1511 return rv;
1512}
1513
1514void SSLClientSocketOpenSSL::BufferSendComplete(int result) {
1515 transport_send_busy_ = false;
1516 TransportWriteComplete(result);
1517 OnSendComplete(result);
1518}
1519
1520void SSLClientSocketOpenSSL::BufferRecvComplete(int result) {
[email protected]3e5c6922014-02-06 02:42:161521 result = TransportReadComplete(result);
[email protected]b9b651f2013-11-09 04:32:221522 OnRecvComplete(result);
1523}
1524
1525void SSLClientSocketOpenSSL::TransportWriteComplete(int result) {
1526 DCHECK(ERR_IO_PENDING != result);
1527 if (result < 0) {
[email protected]5aea79182014-07-14 20:43:411528 // Record the error. Save it to be reported in a future read or write on
1529 // transport_bio_'s peer.
[email protected]3e5c6922014-02-06 02:42:161530 transport_write_error_ = result;
[email protected]b9b651f2013-11-09 04:32:221531 send_buffer_ = NULL;
1532 } else {
1533 DCHECK(send_buffer_.get());
1534 send_buffer_->DidConsume(result);
1535 DCHECK_GE(send_buffer_->BytesRemaining(), 0);
1536 if (send_buffer_->BytesRemaining() <= 0)
1537 send_buffer_ = NULL;
1538 }
1539}
1540
[email protected]3e5c6922014-02-06 02:42:161541int SSLClientSocketOpenSSL::TransportReadComplete(int result) {
[email protected]b9b651f2013-11-09 04:32:221542 DCHECK(ERR_IO_PENDING != result);
[email protected]5aea79182014-07-14 20:43:411543 // If an EOF, canonicalize to ERR_CONNECTION_CLOSED here so MapOpenSSLError
1544 // does not report success.
1545 if (result == 0)
1546 result = ERR_CONNECTION_CLOSED;
1547 if (result < 0) {
[email protected]b9b651f2013-11-09 04:32:221548 DVLOG(1) << "TransportReadComplete result " << result;
[email protected]5aea79182014-07-14 20:43:411549 // Received an error. Save it to be reported in a future read on
1550 // transport_bio_'s peer.
1551 transport_read_error_ = result;
[email protected]b9b651f2013-11-09 04:32:221552 } else {
1553 DCHECK(recv_buffer_.get());
1554 int ret = BIO_write(transport_bio_, recv_buffer_->data(), result);
1555 // A write into a memory BIO should always succeed.
[email protected]c8a80e92014-05-17 16:02:081556 DCHECK_EQ(result, ret);
[email protected]b9b651f2013-11-09 04:32:221557 }
1558 recv_buffer_ = NULL;
1559 transport_recv_busy_ = false;
[email protected]3e5c6922014-02-06 02:42:161560 return result;
[email protected]b9b651f2013-11-09 04:32:221561}
1562
[email protected]82c59022014-08-15 09:38:271563int SSLClientSocketOpenSSL::ClientCertRequestCallback(SSL* ssl) {
[email protected]5ac981e182010-12-06 17:56:271564 DVLOG(3) << "OpenSSL ClientCertRequestCallback called";
1565 DCHECK(ssl == ssl_);
[email protected]82c59022014-08-15 09:38:271566
1567 // Clear any currently configured certificates.
1568 SSL_certs_clear(ssl_);
[email protected]97a854f2014-07-29 07:51:361569
1570#if defined(OS_IOS)
1571 // TODO(droger): Support client auth on iOS. See http://crbug.com/145954).
1572 LOG(WARNING) << "Client auth is not supported";
1573#else // !defined(OS_IOS)
[email protected]5ac981e182010-12-06 17:56:271574 if (!ssl_config_.send_client_cert) {
[email protected]515adc22013-01-09 16:01:231575 // First pass: we know that a client certificate is needed, but we do not
1576 // have one at hand.
[email protected]5ac981e182010-12-06 17:56:271577 client_auth_cert_needed_ = true;
[email protected]515adc22013-01-09 16:01:231578 STACK_OF(X509_NAME) *authorities = SSL_get_client_CA_list(ssl);
[email protected]edfd0f42014-07-22 18:20:371579 for (size_t i = 0; i < sk_X509_NAME_num(authorities); i++) {
[email protected]515adc22013-01-09 16:01:231580 X509_NAME *ca_name = (X509_NAME *)sk_X509_NAME_value(authorities, i);
1581 unsigned char* str = NULL;
1582 int length = i2d_X509_NAME(ca_name, &str);
1583 cert_authorities_.push_back(std::string(
1584 reinterpret_cast<const char*>(str),
1585 static_cast<size_t>(length)));
1586 OPENSSL_free(str);
1587 }
1588
[email protected]c0787702014-05-20 21:51:441589 const unsigned char* client_cert_types;
[email protected]e7e883e2014-07-25 06:03:081590 size_t num_client_cert_types =
1591 SSL_get0_certificate_types(ssl, &client_cert_types);
[email protected]c0787702014-05-20 21:51:441592 for (size_t i = 0; i < num_client_cert_types; i++) {
1593 cert_key_types_.push_back(
1594 static_cast<SSLClientCertType>(client_cert_types[i]));
1595 }
1596
[email protected]5ac981e182010-12-06 17:56:271597 return -1; // Suspends handshake.
1598 }
1599
1600 // Second pass: a client certificate should have been selected.
[email protected]13914c92013-06-13 22:42:421601 if (ssl_config_.client_cert.get()) {
[email protected]6bad5052014-07-12 01:25:131602 ScopedX509 leaf_x509 =
1603 OSCertHandleToOpenSSL(ssl_config_.client_cert->os_cert_handle());
1604 if (!leaf_x509) {
1605 LOG(WARNING) << "Failed to import certificate";
1606 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT);
1607 return -1;
1608 }
1609
[email protected]82c59022014-08-15 09:38:271610 ScopedX509Stack chain = OSCertHandlesToOpenSSL(
1611 ssl_config_.client_cert->GetIntermediateCertificates());
1612 if (!chain) {
1613 LOG(WARNING) << "Failed to import intermediate certificates";
1614 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT);
1615 return -1;
1616 }
1617
[email protected]97a854f2014-07-29 07:51:361618 // TODO(davidben): With Linux client auth support, this should be
1619 // conditioned on OS_ANDROID and then, with https://crbug.com/394131,
1620 // removed altogether. OpenSSLClientKeyStore is mostly an artifact of the
1621 // net/ client auth API lacking a private key handle.
[email protected]c0787702014-05-20 21:51:441622#if defined(USE_OPENSSL_CERTS)
[email protected]97a854f2014-07-29 07:51:361623 crypto::ScopedEVP_PKEY privkey =
1624 OpenSSLClientKeyStore::GetInstance()->FetchClientCertPrivateKey(
1625 ssl_config_.client_cert.get());
1626#else // !defined(USE_OPENSSL_CERTS)
1627 crypto::ScopedEVP_PKEY privkey =
1628 FetchClientCertPrivateKey(ssl_config_.client_cert.get());
1629#endif // defined(USE_OPENSSL_CERTS)
1630 if (!privkey) {
[email protected]6bad5052014-07-12 01:25:131631 // Could not find the private key. Fail the handshake and surface an
1632 // appropriate error to the caller.
1633 LOG(WARNING) << "Client cert found without private key";
1634 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY);
1635 return -1;
[email protected]0c6523f2010-12-10 10:56:241636 }
[email protected]6bad5052014-07-12 01:25:131637
[email protected]82c59022014-08-15 09:38:271638 if (!SSL_use_certificate(ssl_, leaf_x509.get()) ||
1639 !SSL_use_PrivateKey(ssl_, privkey.get()) ||
1640 !SSL_set1_chain(ssl_, chain.get())) {
1641 LOG(WARNING) << "Failed to set client certificate";
1642 return -1;
1643 }
[email protected]6bad5052014-07-12 01:25:131644 return 1;
[email protected]c0787702014-05-20 21:51:441645 }
[email protected]97a854f2014-07-29 07:51:361646#endif // defined(OS_IOS)
[email protected]5ac981e182010-12-06 17:56:271647
1648 // Send no client certificate.
[email protected]82c59022014-08-15 09:38:271649 return 1;
[email protected]5ac981e182010-12-06 17:56:271650}
1651
[email protected]b051cdb62014-02-28 02:20:161652int SSLClientSocketOpenSSL::CertVerifyCallback(X509_STORE_CTX* store_ctx) {
[email protected]64b5c892014-08-08 09:39:261653 if (!completed_connect_) {
[email protected]b051cdb62014-02-28 02:20:161654 // If the first handshake hasn't completed then we accept any certificates
1655 // because we verify after the handshake.
1656 return 1;
1657 }
1658
davidben30798ed82014-09-19 19:28:201659 // Disallow the server certificate to change in a renegotiation.
1660 if (server_cert_chain_->empty()) {
[email protected]76e85392014-03-20 17:54:141661 LOG(ERROR) << "Received invalid certificate chain between handshakes";
davidben30798ed82014-09-19 19:28:201662 return 0;
1663 }
1664 base::StringPiece old_der, new_der;
1665 if (store_ctx->cert == NULL ||
1666 !x509_util::GetDER(server_cert_chain_->Get(0), &old_der) ||
1667 !x509_util::GetDER(store_ctx->cert, &new_der)) {
1668 LOG(ERROR) << "Failed to encode certificates";
1669 return 0;
1670 }
1671 if (old_der != new_der) {
[email protected]76e85392014-03-20 17:54:141672 LOG(ERROR) << "Server certificate changed between handshakes";
davidben30798ed82014-09-19 19:28:201673 return 0;
1674 }
1675
1676 return 1;
[email protected]b051cdb62014-02-28 02:20:161677}
1678
[email protected]ae7c9f42011-11-21 11:41:161679// SelectNextProtoCallback is called by OpenSSL during the handshake. If the
1680// server supports NPN, selects a protocol from the list that the server
1681// provides. According to third_party/openssl/openssl/ssl/ssl_lib.c, the
1682// callback can assume that |in| is syntactically valid.
[email protected]ea4a1c6a2010-12-09 13:33:281683int SSLClientSocketOpenSSL::SelectNextProtoCallback(unsigned char** out,
1684 unsigned char* outlen,
1685 const unsigned char* in,
1686 unsigned int inlen) {
[email protected]ea4a1c6a2010-12-09 13:33:281687 if (ssl_config_.next_protos.empty()) {
[email protected]168a8412012-06-14 05:05:491688 *out = reinterpret_cast<uint8*>(
1689 const_cast<char*>(kDefaultSupportedNPNProtocol));
1690 *outlen = arraysize(kDefaultSupportedNPNProtocol) - 1;
1691 npn_status_ = kNextProtoUnsupported;
[email protected]ea4a1c6a2010-12-09 13:33:281692 return SSL_TLSEXT_ERR_OK;
1693 }
1694
[email protected]ae7c9f42011-11-21 11:41:161695 // Assume there's no overlap between our protocols and the server's list.
[email protected]168a8412012-06-14 05:05:491696 npn_status_ = kNextProtoNoOverlap;
[email protected]ae7c9f42011-11-21 11:41:161697
1698 // For each protocol in server preference order, see if we support it.
1699 for (unsigned int i = 0; i < inlen; i += in[i] + 1) {
1700 for (std::vector<std::string>::const_iterator
1701 j = ssl_config_.next_protos.begin();
1702 j != ssl_config_.next_protos.end(); ++j) {
1703 if (in[i] == j->size() &&
1704 memcmp(&in[i + 1], j->data(), in[i]) == 0) {
[email protected]168a8412012-06-14 05:05:491705 // We found a match.
[email protected]ae7c9f42011-11-21 11:41:161706 *out = const_cast<unsigned char*>(in) + i + 1;
1707 *outlen = in[i];
[email protected]168a8412012-06-14 05:05:491708 npn_status_ = kNextProtoNegotiated;
[email protected]ae7c9f42011-11-21 11:41:161709 break;
1710 }
1711 }
[email protected]168a8412012-06-14 05:05:491712 if (npn_status_ == kNextProtoNegotiated)
[email protected]ae7c9f42011-11-21 11:41:161713 break;
1714 }
[email protected]ea4a1c6a2010-12-09 13:33:281715
[email protected]168a8412012-06-14 05:05:491716 // If we didn't find a protocol, we select the first one from our list.
1717 if (npn_status_ == kNextProtoNoOverlap) {
1718 *out = reinterpret_cast<uint8*>(const_cast<char*>(
1719 ssl_config_.next_protos[0].data()));
1720 *outlen = ssl_config_.next_protos[0].size();
1721 }
1722
[email protected]ea4a1c6a2010-12-09 13:33:281723 npn_proto_.assign(reinterpret_cast<const char*>(*out), *outlen);
[email protected]32e1dee2010-12-09 18:36:241724 DVLOG(2) << "next protocol: '" << npn_proto_ << "' status: " << npn_status_;
bnc0d28ea52014-10-13 15:15:381725 set_negotiation_extension(kExtensionNPN);
[email protected]ea4a1c6a2010-12-09 13:33:281726 return SSL_TLSEXT_ERR_OK;
1727}
1728
[email protected]5aea79182014-07-14 20:43:411729long SSLClientSocketOpenSSL::MaybeReplayTransportError(
1730 BIO *bio,
1731 int cmd,
1732 const char *argp, int argi, long argl,
1733 long retvalue) {
1734 if (cmd == (BIO_CB_READ|BIO_CB_RETURN) && retvalue <= 0) {
1735 // If there is no more data in the buffer, report any pending errors that
1736 // were observed. Note that both the readbuf and the writebuf are checked
1737 // for errors, since the application may have encountered a socket error
1738 // while writing that would otherwise not be reported until the application
1739 // attempted to write again - which it may never do. See
1740 // https://crbug.com/249848.
1741 if (transport_read_error_ != OK) {
1742 OpenSSLPutNetError(FROM_HERE, transport_read_error_);
1743 return -1;
1744 }
1745 if (transport_write_error_ != OK) {
1746 OpenSSLPutNetError(FROM_HERE, transport_write_error_);
1747 return -1;
1748 }
1749 } else if (cmd == BIO_CB_WRITE) {
1750 // Because of the write buffer, this reports a failure from the previous
1751 // write payload. If the current payload fails to write, the error will be
1752 // reported in a future write or read to |bio|.
1753 if (transport_write_error_ != OK) {
1754 OpenSSLPutNetError(FROM_HERE, transport_write_error_);
1755 return -1;
1756 }
1757 }
1758 return retvalue;
1759}
1760
1761// static
1762long SSLClientSocketOpenSSL::BIOCallback(
1763 BIO *bio,
1764 int cmd,
1765 const char *argp, int argi, long argl,
1766 long retvalue) {
1767 SSLClientSocketOpenSSL* socket = reinterpret_cast<SSLClientSocketOpenSSL*>(
1768 BIO_get_callback_arg(bio));
1769 CHECK(socket);
1770 return socket->MaybeReplayTransportError(
1771 bio, cmd, argp, argi, argl, retvalue);
1772}
1773
[email protected]64b5c892014-08-08 09:39:261774// static
1775void SSLClientSocketOpenSSL::InfoCallback(const SSL* ssl,
1776 int type,
1777 int /*val*/) {
1778 if (type == SSL_CB_HANDSHAKE_DONE) {
1779 SSLClientSocketOpenSSL* ssl_socket =
1780 SSLContext::GetInstance()->GetClientSocketFromSSL(ssl);
1781 ssl_socket->handshake_succeeded_ = true;
1782 ssl_socket->CheckIfHandshakeFinished();
1783 }
1784}
1785
1786// Determines if both the handshake and certificate verification have completed
1787// successfully, and calls the handshake completion callback if that is the
1788// case.
1789//
1790// CheckIfHandshakeFinished is called twice per connection: once after
1791// MarkSSLSessionAsGood, when the certificate has been verified, and
1792// once via an OpenSSL callback when the handshake has completed. On the
1793// second call, when the certificate has been verified and the handshake
1794// has completed, the connection's handshake completion callback is run.
1795void SSLClientSocketOpenSSL::CheckIfHandshakeFinished() {
1796 if (handshake_succeeded_ && marked_session_as_good_)
1797 OnHandshakeCompletion();
1798}
1799
davidbeneb5f8ef32014-09-04 14:14:321800void SSLClientSocketOpenSSL::AddSCTInfoToSSLInfo(SSLInfo* ssl_info) const {
1801 for (ct::SCTList::const_iterator iter =
1802 ct_verify_result_.verified_scts.begin();
1803 iter != ct_verify_result_.verified_scts.end(); ++iter) {
1804 ssl_info->signed_certificate_timestamps.push_back(
1805 SignedCertificateTimestampAndStatus(*iter, ct::SCT_STATUS_OK));
1806 }
1807 for (ct::SCTList::const_iterator iter =
1808 ct_verify_result_.invalid_scts.begin();
1809 iter != ct_verify_result_.invalid_scts.end(); ++iter) {
1810 ssl_info->signed_certificate_timestamps.push_back(
1811 SignedCertificateTimestampAndStatus(*iter, ct::SCT_STATUS_INVALID));
1812 }
1813 for (ct::SCTList::const_iterator iter =
1814 ct_verify_result_.unknown_logs_scts.begin();
1815 iter != ct_verify_result_.unknown_logs_scts.end(); ++iter) {
1816 ssl_info->signed_certificate_timestamps.push_back(
1817 SignedCertificateTimestampAndStatus(*iter,
1818 ct::SCT_STATUS_LOG_UNKNOWN));
1819 }
1820}
1821
[email protected]7f38da8a2014-03-17 16:44:261822scoped_refptr<X509Certificate>
1823SSLClientSocketOpenSSL::GetUnverifiedServerCertificateChain() const {
1824 return server_cert_;
1825}
1826
[email protected]7e5dd49f2010-12-08 18:33:491827} // namespace net