blob: 2e8ba873ca16b8218a56bd9c6dae5758ab2853fe [file] [log] [blame]
[email protected]013c17c2012-01-21 19:09:011// Copyright (c) 2012 The Chromium Authors. All rights reserved.
[email protected]d518cd92010-09-29 12:27:442// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5// OpenSSL binding for SSLClientSocket. The class layout and general principle
6// of operation is derived from SSLClientSocketNSS.
7
8#include "net/socket/ssl_client_socket_openssl.h"
9
[email protected]edfd0f42014-07-22 18:20:3710#include <errno.h>
davidben018aad62014-09-12 02:25:1911#include <openssl/bio.h>
[email protected]d518cd92010-09-29 12:27:4412#include <openssl/err.h>
[email protected]536fd0b2013-03-14 17:41:5713#include <openssl/ssl.h>
[email protected]d518cd92010-09-29 12:27:4414
[email protected]0f7804ec2011-10-07 20:04:1815#include "base/bind.h"
[email protected]f2da6ac2013-02-04 08:22:5316#include "base/callback_helpers.h"
davidben018aad62014-09-12 02:25:1917#include "base/environment.h"
[email protected]3b63f8f42011-03-28 01:54:1518#include "base/memory/singleton.h"
[email protected]835d7c82010-10-14 04:38:3819#include "base/metrics/histogram.h"
vadimtb2a77c762014-11-21 19:49:2220#include "base/profiler/scoped_tracker.h"
davidben018aad62014-09-12 02:25:1921#include "base/strings/string_piece.h"
[email protected]20305ec2011-01-21 04:55:5222#include "base/synchronization/lock.h"
[email protected]ee0f2aa82013-10-25 11:59:2623#include "crypto/ec_private_key.h"
[email protected]4b559b4d2011-04-14 17:37:1424#include "crypto/openssl_util.h"
[email protected]cd9b75b2014-07-10 04:39:3825#include "crypto/scoped_openssl_types.h"
[email protected]d518cd92010-09-29 12:27:4426#include "net/base/net_errors.h"
[email protected]6e7845ae2013-03-29 21:48:1127#include "net/cert/cert_verifier.h"
eranmefbd3132014-10-28 16:35:1628#include "net/cert/ct_ev_whitelist.h"
davidbeneb5f8ef32014-09-04 14:14:3229#include "net/cert/ct_verifier.h"
[email protected]6e7845ae2013-03-29 21:48:1130#include "net/cert/single_request_cert_verifier.h"
31#include "net/cert/x509_certificate_net_log_param.h"
davidben30798ed82014-09-19 19:28:2032#include "net/cert/x509_util_openssl.h"
[email protected]8bd4e7a2014-08-09 14:49:1733#include "net/http/transport_security_state.h"
[email protected]1279de12013-12-03 15:13:3234#include "net/socket/ssl_session_cache_openssl.h"
[email protected]536fd0b2013-03-14 17:41:5735#include "net/ssl/ssl_cert_request_info.h"
36#include "net/ssl/ssl_connection_status_flags.h"
37#include "net/ssl/ssl_info.h"
[email protected]d518cd92010-09-29 12:27:4438
davidben8ecc3072014-09-03 23:19:0939#if defined(OS_WIN)
40#include "base/win/windows_version.h"
41#endif
42
[email protected]97a854f2014-07-29 07:51:3643#if defined(USE_OPENSSL_CERTS)
44#include "net/ssl/openssl_client_key_store.h"
45#else
46#include "net/ssl/openssl_platform_key.h"
47#endif
48
[email protected]d518cd92010-09-29 12:27:4449namespace net {
50
51namespace {
52
53// Enable this to see logging for state machine state transitions.
54#if 0
[email protected]3b112772010-10-04 10:54:4955#define GotoState(s) do { DVLOG(2) << (void *)this << " " << __FUNCTION__ << \
[email protected]d518cd92010-09-29 12:27:4456 " jump to state " << s; \
57 next_handshake_state_ = s; } while (0)
58#else
59#define GotoState(s) next_handshake_state_ = s
60#endif
61
[email protected]4b768562013-02-16 04:10:0762// This constant can be any non-negative/non-zero value (eg: it does not
63// overlap with any value of the net::Error range, including net::OK).
64const int kNoPendingReadResult = 1;
65
[email protected]168a8412012-06-14 05:05:4966// If a client doesn't have a list of protocols that it supports, but
67// the server supports NPN, choosing "http/1.1" is the best answer.
68const char kDefaultSupportedNPNProtocol[] = "http/1.1";
69
[email protected]82c59022014-08-15 09:38:2770void FreeX509Stack(STACK_OF(X509)* ptr) {
71 sk_X509_pop_free(ptr, X509_free);
72}
73
[email protected]6bad5052014-07-12 01:25:1374typedef crypto::ScopedOpenSSL<X509, X509_free>::Type ScopedX509;
[email protected]82c59022014-08-15 09:38:2775typedef crypto::ScopedOpenSSL<STACK_OF(X509), FreeX509Stack>::Type
76 ScopedX509Stack;
[email protected]6bad5052014-07-12 01:25:1377
[email protected]89038152012-09-07 06:30:1778#if OPENSSL_VERSION_NUMBER < 0x1000103fL
79// This method doesn't seem to have made it into the OpenSSL headers.
[email protected]109805a2010-12-07 18:17:0680unsigned long SSL_CIPHER_get_id(const SSL_CIPHER* cipher) { return cipher->id; }
[email protected]89038152012-09-07 06:30:1781#endif
[email protected]109805a2010-12-07 18:17:0682
83// Used for encoding the |connection_status| field of an SSLInfo object.
pkasting6b68a162014-12-01 22:10:2984int EncodeSSLConnectionStatus(uint16 cipher_suite,
[email protected]109805a2010-12-07 18:17:0685 int compression,
86 int version) {
pkasting6b68a162014-12-01 22:10:2987 return cipher_suite |
[email protected]109805a2010-12-07 18:17:0688 ((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
davidbend1fb2f12014-11-08 02:51:00143bool IsOCSPStaplingSupported() {
144#if defined(OS_WIN)
145 // CERT_OCSP_RESPONSE_PROP_ID is only implemented on Vista+, but it can be
146 // set on Windows XP without error. There is some overhead from the server
147 // sending the OCSP response if it supports the extension, for the subset of
148 // XP clients who will request it but be unable to use it, but this is an
149 // acceptable trade-off for simplicity of implementation.
150 return true;
151#else
152 return false;
153#endif
154}
155
[email protected]821e3bb2013-11-08 01:06:01156} // namespace
157
158class SSLClientSocketOpenSSL::SSLContext {
[email protected]fbef13932010-11-23 12:38:53159 public:
[email protected]b29af7d2010-12-14 11:52:47160 static SSLContext* GetInstance() { return Singleton<SSLContext>::get(); }
[email protected]fbef13932010-11-23 12:38:53161 SSL_CTX* ssl_ctx() { return ssl_ctx_.get(); }
[email protected]1279de12013-12-03 15:13:32162 SSLSessionCacheOpenSSL* session_cache() { return &session_cache_; }
[email protected]fbef13932010-11-23 12:38:53163
[email protected]1279de12013-12-03 15:13:32164 SSLClientSocketOpenSSL* GetClientSocketFromSSL(const SSL* ssl) {
[email protected]fbef13932010-11-23 12:38:53165 DCHECK(ssl);
166 SSLClientSocketOpenSSL* socket = static_cast<SSLClientSocketOpenSSL*>(
167 SSL_get_ex_data(ssl, ssl_socket_data_index_));
168 DCHECK(socket);
169 return socket;
170 }
171
172 bool SetClientSocketForSSL(SSL* ssl, SSLClientSocketOpenSSL* socket) {
173 return SSL_set_ex_data(ssl, ssl_socket_data_index_, socket) != 0;
174 }
175
176 private:
177 friend struct DefaultSingletonTraits<SSLContext>;
178
179 SSLContext() {
[email protected]4b559b4d2011-04-14 17:37:14180 crypto::EnsureOpenSSLInit();
[email protected]fbef13932010-11-23 12:38:53181 ssl_socket_data_index_ = SSL_get_ex_new_index(0, 0, 0, 0, 0);
182 DCHECK_NE(ssl_socket_data_index_, -1);
183 ssl_ctx_.reset(SSL_CTX_new(SSLv23_client_method()));
[email protected]1279de12013-12-03 15:13:32184 session_cache_.Reset(ssl_ctx_.get(), kDefaultSessionCacheConfig);
[email protected]b051cdb62014-02-28 02:20:16185 SSL_CTX_set_cert_verify_callback(ssl_ctx_.get(), CertVerifyCallback, NULL);
[email protected]82c59022014-08-15 09:38:27186 SSL_CTX_set_cert_cb(ssl_ctx_.get(), ClientCertRequestCallback, NULL);
[email protected]b051cdb62014-02-28 02:20:16187 SSL_CTX_set_verify(ssl_ctx_.get(), SSL_VERIFY_PEER, NULL);
[email protected]ea4a1c6a2010-12-09 13:33:28188 // TODO(kristianm): Only select this if ssl_config_.next_proto is not empty.
189 // It would be better if the callback were not a global setting,
190 // but that is an OpenSSL issue.
191 SSL_CTX_set_next_proto_select_cb(ssl_ctx_.get(), SelectNextProtoCallback,
192 NULL);
[email protected]edfd0f42014-07-22 18:20:37193 ssl_ctx_->tlsext_channel_id_enabled_new = 1;
davidben018aad62014-09-12 02:25:19194
195 scoped_ptr<base::Environment> env(base::Environment::Create());
196 std::string ssl_keylog_file;
197 if (env->GetVar("SSLKEYLOGFILE", &ssl_keylog_file) &&
198 !ssl_keylog_file.empty()) {
199 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
200 BIO* bio = BIO_new_file(ssl_keylog_file.c_str(), "a");
201 if (!bio) {
202 LOG(ERROR) << "Failed to open " << ssl_keylog_file;
203 ERR_print_errors_cb(&LogErrorCallback, NULL);
204 } else {
205 SSL_CTX_set_keylog_bio(ssl_ctx_.get(), bio);
206 }
207 }
[email protected]fbef13932010-11-23 12:38:53208 }
209
[email protected]1279de12013-12-03 15:13:32210 static std::string GetSessionCacheKey(const SSL* ssl) {
211 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
212 DCHECK(socket);
[email protected]8e458552014-08-05 00:02:15213 return socket->GetSessionCacheKey();
[email protected]fbef13932010-11-23 12:38:53214 }
215
[email protected]1279de12013-12-03 15:13:32216 static SSLSessionCacheOpenSSL::Config kDefaultSessionCacheConfig;
[email protected]fbef13932010-11-23 12:38:53217
[email protected]82c59022014-08-15 09:38:27218 static int ClientCertRequestCallback(SSL* ssl, void* arg) {
[email protected]b29af7d2010-12-14 11:52:47219 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
[email protected]82c59022014-08-15 09:38:27220 DCHECK(socket);
221 return socket->ClientCertRequestCallback(ssl);
[email protected]718c9672010-12-02 10:04:10222 }
223
[email protected]b051cdb62014-02-28 02:20:16224 static int CertVerifyCallback(X509_STORE_CTX *store_ctx, void *arg) {
225 SSL* ssl = reinterpret_cast<SSL*>(X509_STORE_CTX_get_ex_data(
226 store_ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
227 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
228 CHECK(socket);
229
230 return socket->CertVerifyCallback(store_ctx);
231 }
232
[email protected]ea4a1c6a2010-12-09 13:33:28233 static int SelectNextProtoCallback(SSL* ssl,
234 unsigned char** out, unsigned char* outlen,
235 const unsigned char* in,
236 unsigned int inlen, void* arg) {
[email protected]b29af7d2010-12-14 11:52:47237 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
[email protected]ea4a1c6a2010-12-09 13:33:28238 return socket->SelectNextProtoCallback(out, outlen, in, inlen);
239 }
240
[email protected]fbef13932010-11-23 12:38:53241 // This is the index used with SSL_get_ex_data to retrieve the owner
242 // SSLClientSocketOpenSSL object from an SSL instance.
243 int ssl_socket_data_index_;
244
[email protected]cd9b75b2014-07-10 04:39:38245 crypto::ScopedOpenSSL<SSL_CTX, SSL_CTX_free>::Type ssl_ctx_;
[email protected]1279de12013-12-03 15:13:32246 // |session_cache_| must be destroyed before |ssl_ctx_|.
247 SSLSessionCacheOpenSSL session_cache_;
248};
249
[email protected]7f38da8a2014-03-17 16:44:26250// PeerCertificateChain is a helper object which extracts the certificate
251// chain, as given by the server, from an OpenSSL socket and performs the needed
252// resource management. The first element of the chain is the leaf certificate
253// and the other elements are in the order given by the server.
254class SSLClientSocketOpenSSL::PeerCertificateChain {
255 public:
[email protected]76e85392014-03-20 17:54:14256 explicit PeerCertificateChain(STACK_OF(X509)* chain) { Reset(chain); }
[email protected]7f38da8a2014-03-17 16:44:26257 PeerCertificateChain(const PeerCertificateChain& other) { *this = other; }
258 ~PeerCertificateChain() {}
259 PeerCertificateChain& operator=(const PeerCertificateChain& other);
260
[email protected]76e85392014-03-20 17:54:14261 // Resets the PeerCertificateChain to the set of certificates in|chain|,
262 // which may be NULL, indicating to empty the store certificates.
263 // Note: If an error occurs, such as being unable to parse the certificates,
264 // this will behave as if Reset(NULL) was called.
265 void Reset(STACK_OF(X509)* chain);
266
[email protected]7f38da8a2014-03-17 16:44:26267 // Note that when USE_OPENSSL is defined, OSCertHandle is X509*
davidben30798ed82014-09-19 19:28:20268 scoped_refptr<X509Certificate> AsOSChain() const;
[email protected]7f38da8a2014-03-17 16:44:26269
270 size_t size() const {
271 if (!openssl_chain_.get())
272 return 0;
273 return sk_X509_num(openssl_chain_.get());
274 }
275
davidben30798ed82014-09-19 19:28:20276 bool empty() const {
277 return size() == 0;
278 }
279
280 X509* Get(size_t index) const {
[email protected]7f38da8a2014-03-17 16:44:26281 DCHECK_LT(index, size());
282 return sk_X509_value(openssl_chain_.get(), index);
283 }
284
285 private:
[email protected]cd9b75b2014-07-10 04:39:38286 ScopedX509Stack openssl_chain_;
[email protected]7f38da8a2014-03-17 16:44:26287};
288
289SSLClientSocketOpenSSL::PeerCertificateChain&
290SSLClientSocketOpenSSL::PeerCertificateChain::operator=(
291 const PeerCertificateChain& other) {
292 if (this == &other)
293 return *this;
294
[email protected]24176af2014-08-14 09:31:04295 openssl_chain_.reset(X509_chain_up_ref(other.openssl_chain_.get()));
[email protected]7f38da8a2014-03-17 16:44:26296 return *this;
297}
298
[email protected]76e85392014-03-20 17:54:14299void SSLClientSocketOpenSSL::PeerCertificateChain::Reset(
300 STACK_OF(X509)* chain) {
davidben30798ed82014-09-19 19:28:20301 openssl_chain_.reset(chain ? X509_chain_up_ref(chain) : NULL);
[email protected]7f38da8a2014-03-17 16:44:26302}
[email protected]7f38da8a2014-03-17 16:44:26303
davidben30798ed82014-09-19 19:28:20304scoped_refptr<X509Certificate>
305SSLClientSocketOpenSSL::PeerCertificateChain::AsOSChain() const {
306#if defined(USE_OPENSSL_CERTS)
307 // When OSCertHandle is typedef'ed to X509, this implementation does a short
308 // cut to avoid converting back and forth between DER and the X509 struct.
309 X509Certificate::OSCertHandles intermediates;
310 for (size_t i = 1; i < sk_X509_num(openssl_chain_.get()); ++i) {
311 intermediates.push_back(sk_X509_value(openssl_chain_.get(), i));
312 }
[email protected]7f38da8a2014-03-17 16:44:26313
davidben30798ed82014-09-19 19:28:20314 return make_scoped_refptr(X509Certificate::CreateFromHandle(
315 sk_X509_value(openssl_chain_.get(), 0), intermediates));
316#else
317 // DER-encode the chain and convert to a platform certificate handle.
[email protected]7f38da8a2014-03-17 16:44:26318 std::vector<base::StringPiece> der_chain;
[email protected]edfd0f42014-07-22 18:20:37319 for (size_t i = 0; i < sk_X509_num(openssl_chain_.get()); ++i) {
[email protected]7f38da8a2014-03-17 16:44:26320 X509* x = sk_X509_value(openssl_chain_.get(), i);
davidben30798ed82014-09-19 19:28:20321 base::StringPiece der;
322 if (!x509_util::GetDER(x, &der))
323 return NULL;
324 der_chain.push_back(der);
[email protected]7f38da8a2014-03-17 16:44:26325 }
326
davidben30798ed82014-09-19 19:28:20327 return make_scoped_refptr(X509Certificate::CreateFromDERCertChain(der_chain));
328#endif
[email protected]7f38da8a2014-03-17 16:44:26329}
[email protected]7f38da8a2014-03-17 16:44:26330
[email protected]1279de12013-12-03 15:13:32331// static
332SSLSessionCacheOpenSSL::Config
333 SSLClientSocketOpenSSL::SSLContext::kDefaultSessionCacheConfig = {
334 &GetSessionCacheKey, // key_func
335 1024, // max_entries
336 256, // expiration_check_count
337 60 * 60, // timeout_seconds
[email protected]fbef13932010-11-23 12:38:53338};
[email protected]313834722010-11-17 09:57:18339
[email protected]c3456bb2011-12-12 22:22:19340// static
341void SSLClientSocket::ClearSessionCache() {
[email protected]821e3bb2013-11-08 01:06:01342 SSLClientSocketOpenSSL::SSLContext* context =
343 SSLClientSocketOpenSSL::SSLContext::GetInstance();
[email protected]c3456bb2011-12-12 22:22:19344 context->session_cache()->Flush();
345}
346
[email protected]d518cd92010-09-29 12:27:44347SSLClientSocketOpenSSL::SSLClientSocketOpenSSL(
[email protected]18ccfdb2013-08-15 00:13:44348 scoped_ptr<ClientSocketHandle> transport_socket,
[email protected]055d7f22010-11-15 12:03:12349 const HostPortPair& host_and_port,
[email protected]822581d2010-12-16 17:27:15350 const SSLConfig& ssl_config,
[email protected]feb79bcd2011-07-21 16:55:17351 const SSLClientSocketContext& context)
[email protected]83039bb2011-12-09 18:43:55352 : transport_send_busy_(false),
[email protected]d518cd92010-09-29 12:27:44353 transport_recv_busy_(false),
[email protected]4b768562013-02-16 04:10:07354 pending_read_error_(kNoPendingReadResult),
davidbenb8c23212014-10-28 00:12:16355 pending_read_ssl_error_(SSL_ERROR_NONE),
[email protected]5aea79182014-07-14 20:43:41356 transport_read_error_(OK),
[email protected]3e5c6922014-02-06 02:42:16357 transport_write_error_(OK),
[email protected]7f38da8a2014-03-17 16:44:26358 server_cert_chain_(new PeerCertificateChain(NULL)),
[email protected]64b5c892014-08-08 09:39:26359 completed_connect_(false),
[email protected]0dc88b32014-03-26 20:12:28360 was_ever_used_(false),
[email protected]d518cd92010-09-29 12:27:44361 client_auth_cert_needed_(false),
[email protected]feb79bcd2011-07-21 16:55:17362 cert_verifier_(context.cert_verifier),
davidbeneb5f8ef32014-09-04 14:14:32363 cert_transparency_verifier_(context.cert_transparency_verifier),
[email protected]6b8a3c742014-07-25 00:25:35364 channel_id_service_(context.channel_id_service),
[email protected]d518cd92010-09-29 12:27:44365 ssl_(NULL),
366 transport_bio_(NULL),
[email protected]18ccfdb2013-08-15 00:13:44367 transport_(transport_socket.Pass()),
[email protected]055d7f22010-11-15 12:03:12368 host_and_port_(host_and_port),
[email protected]d518cd92010-09-29 12:27:44369 ssl_config_(ssl_config),
[email protected]c3456bb2011-12-12 22:22:19370 ssl_session_cache_shard_(context.ssl_session_cache_shard),
[email protected]fbef13932010-11-23 12:38:53371 trying_cached_session_(false),
[email protected]013c17c2012-01-21 19:09:01372 next_handshake_state_(STATE_NONE),
[email protected]ea4a1c6a2010-12-09 13:33:28373 npn_status_(kNextProtoUnsupported),
[email protected]ee0f2aa82013-10-25 11:59:26374 channel_id_xtn_negotiated_(false),
[email protected]64b5c892014-08-08 09:39:26375 handshake_succeeded_(false),
[email protected]e4738ba52014-08-07 10:07:22376 marked_session_as_good_(false),
[email protected]8bd4e7a2014-08-09 14:49:17377 transport_security_state_(context.transport_security_state),
kulkarni.acd7b4462014-08-28 07:41:34378 net_log_(transport_->socket()->NetLog()),
379 weak_factory_(this) {
[email protected]8e458552014-08-05 00:02:15380}
[email protected]d518cd92010-09-29 12:27:44381
382SSLClientSocketOpenSSL::~SSLClientSocketOpenSSL() {
383 Disconnect();
384}
385
[email protected]cffd7f92014-08-21 21:30:50386std::string SSLClientSocketOpenSSL::GetSessionCacheKey() const {
387 std::string result = host_and_port_.ToString();
388 result.append("/");
389 result.append(ssl_session_cache_shard_);
390 return result;
391}
392
[email protected]8e458552014-08-05 00:02:15393bool SSLClientSocketOpenSSL::InSessionCache() const {
394 SSLContext* context = SSLContext::GetInstance();
395 std::string cache_key = GetSessionCacheKey();
396 return context->session_cache()->SSLSessionIsInCache(cache_key);
397}
398
399void SSLClientSocketOpenSSL::SetHandshakeCompletionCallback(
400 const base::Closure& callback) {
401 handshake_completion_callback_ = callback;
402}
403
[email protected]b9b651f2013-11-09 04:32:22404void SSLClientSocketOpenSSL::GetSSLCertRequestInfo(
405 SSLCertRequestInfo* cert_request_info) {
[email protected]791879c2013-12-17 07:22:41406 cert_request_info->host_and_port = host_and_port_;
[email protected]b9b651f2013-11-09 04:32:22407 cert_request_info->cert_authorities = cert_authorities_;
[email protected]c0787702014-05-20 21:51:44408 cert_request_info->cert_key_types = cert_key_types_;
[email protected]b9b651f2013-11-09 04:32:22409}
410
411SSLClientSocket::NextProtoStatus SSLClientSocketOpenSSL::GetNextProto(
[email protected]abc44b752014-07-30 03:52:15412 std::string* proto) {
[email protected]b9b651f2013-11-09 04:32:22413 *proto = npn_proto_;
[email protected]b9b651f2013-11-09 04:32:22414 return npn_status_;
415}
416
[email protected]6b8a3c742014-07-25 00:25:35417ChannelIDService*
418SSLClientSocketOpenSSL::GetChannelIDService() const {
419 return channel_id_service_;
[email protected]b9b651f2013-11-09 04:32:22420}
421
422int SSLClientSocketOpenSSL::ExportKeyingMaterial(
423 const base::StringPiece& label,
424 bool has_context, const base::StringPiece& context,
425 unsigned char* out, unsigned int outlen) {
426 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
427
428 int rv = SSL_export_keying_material(
[email protected]c8a80e92014-05-17 16:02:08429 ssl_, out, outlen, label.data(), label.size(),
430 reinterpret_cast<const unsigned char*>(context.data()),
431 context.length(), context.length() > 0);
[email protected]b9b651f2013-11-09 04:32:22432
433 if (rv != 1) {
434 int ssl_error = SSL_get_error(ssl_, rv);
435 LOG(ERROR) << "Failed to export keying material;"
436 << " returned " << rv
437 << ", SSL error code " << ssl_error;
438 return MapOpenSSLError(ssl_error, err_tracer);
439 }
440 return OK;
441}
442
443int SSLClientSocketOpenSSL::GetTLSUniqueChannelBinding(std::string* out) {
[email protected]c8a80e92014-05-17 16:02:08444 NOTIMPLEMENTED();
[email protected]b9b651f2013-11-09 04:32:22445 return ERR_NOT_IMPLEMENTED;
446}
447
448int SSLClientSocketOpenSSL::Connect(const CompletionCallback& callback) {
[email protected]8bd4e7a2014-08-09 14:49:17449 // It is an error to create an SSLClientSocket whose context has no
450 // TransportSecurityState.
451 DCHECK(transport_security_state_);
452
[email protected]b9b651f2013-11-09 04:32:22453 net_log_.BeginEvent(NetLog::TYPE_SSL_CONNECT);
454
455 // Set up new ssl object.
[email protected]c8a80e92014-05-17 16:02:08456 int rv = Init();
457 if (rv != OK) {
458 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
459 return rv;
[email protected]b9b651f2013-11-09 04:32:22460 }
461
462 // Set SSL to client mode. Handshake happens in the loop below.
463 SSL_set_connect_state(ssl_);
464
465 GotoState(STATE_HANDSHAKE);
[email protected]c8a80e92014-05-17 16:02:08466 rv = DoHandshakeLoop(OK);
[email protected]b9b651f2013-11-09 04:32:22467 if (rv == ERR_IO_PENDING) {
468 user_connect_callback_ = callback;
469 } else {
470 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
[email protected]8e458552014-08-05 00:02:15471 if (rv < OK)
472 OnHandshakeCompletion();
[email protected]b9b651f2013-11-09 04:32:22473 }
474
475 return rv > OK ? OK : rv;
476}
477
478void SSLClientSocketOpenSSL::Disconnect() {
[email protected]8e458552014-08-05 00:02:15479 // If a handshake was pending (Connect() had been called), notify interested
480 // parties that it's been aborted now. If the handshake had already
481 // completed, this is a no-op.
482 OnHandshakeCompletion();
[email protected]b9b651f2013-11-09 04:32:22483 if (ssl_) {
484 // Calling SSL_shutdown prevents the session from being marked as
485 // unresumable.
486 SSL_shutdown(ssl_);
487 SSL_free(ssl_);
488 ssl_ = NULL;
489 }
490 if (transport_bio_) {
491 BIO_free_all(transport_bio_);
492 transport_bio_ = NULL;
493 }
494
495 // Shut down anything that may call us back.
496 verifier_.reset();
497 transport_->socket()->Disconnect();
498
499 // Null all callbacks, delete all buffers.
500 transport_send_busy_ = false;
501 send_buffer_ = NULL;
502 transport_recv_busy_ = false;
[email protected]b9b651f2013-11-09 04:32:22503 recv_buffer_ = NULL;
504
505 user_connect_callback_.Reset();
506 user_read_callback_.Reset();
507 user_write_callback_.Reset();
508 user_read_buf_ = NULL;
509 user_read_buf_len_ = 0;
510 user_write_buf_ = NULL;
511 user_write_buf_len_ = 0;
512
[email protected]3e5c6922014-02-06 02:42:16513 pending_read_error_ = kNoPendingReadResult;
davidbenb8c23212014-10-28 00:12:16514 pending_read_ssl_error_ = SSL_ERROR_NONE;
515 pending_read_error_info_ = OpenSSLErrorInfo();
516
[email protected]5aea79182014-07-14 20:43:41517 transport_read_error_ = OK;
[email protected]3e5c6922014-02-06 02:42:16518 transport_write_error_ = OK;
519
[email protected]b9b651f2013-11-09 04:32:22520 server_cert_verify_result_.Reset();
[email protected]64b5c892014-08-08 09:39:26521 completed_connect_ = false;
[email protected]b9b651f2013-11-09 04:32:22522
523 cert_authorities_.clear();
[email protected]c0787702014-05-20 21:51:44524 cert_key_types_.clear();
[email protected]b9b651f2013-11-09 04:32:22525 client_auth_cert_needed_ = false;
[email protected]faff9852014-06-21 06:13:46526
davidben09c3d072014-08-25 20:33:58527 start_cert_verification_time_ = base::TimeTicks();
528
[email protected]abc44b752014-07-30 03:52:15529 npn_status_ = kNextProtoUnsupported;
530 npn_proto_.clear();
531
[email protected]faff9852014-06-21 06:13:46532 channel_id_xtn_negotiated_ = false;
533 channel_id_request_handle_.Cancel();
[email protected]b9b651f2013-11-09 04:32:22534}
535
536bool SSLClientSocketOpenSSL::IsConnected() const {
537 // If the handshake has not yet completed.
[email protected]64b5c892014-08-08 09:39:26538 if (!completed_connect_)
[email protected]b9b651f2013-11-09 04:32:22539 return false;
540 // If an asynchronous operation is still pending.
541 if (user_read_buf_.get() || user_write_buf_.get())
542 return true;
543
544 return transport_->socket()->IsConnected();
545}
546
547bool SSLClientSocketOpenSSL::IsConnectedAndIdle() const {
548 // If the handshake has not yet completed.
[email protected]64b5c892014-08-08 09:39:26549 if (!completed_connect_)
[email protected]b9b651f2013-11-09 04:32:22550 return false;
551 // If an asynchronous operation is still pending.
552 if (user_read_buf_.get() || user_write_buf_.get())
553 return false;
554 // If there is data waiting to be sent, or data read from the network that
555 // has not yet been consumed.
[email protected]edfd0f42014-07-22 18:20:37556 if (BIO_pending(transport_bio_) > 0 ||
557 BIO_wpending(transport_bio_) > 0) {
[email protected]b9b651f2013-11-09 04:32:22558 return false;
559 }
560
561 return transport_->socket()->IsConnectedAndIdle();
562}
563
564int SSLClientSocketOpenSSL::GetPeerAddress(IPEndPoint* addressList) const {
565 return transport_->socket()->GetPeerAddress(addressList);
566}
567
568int SSLClientSocketOpenSSL::GetLocalAddress(IPEndPoint* addressList) const {
569 return transport_->socket()->GetLocalAddress(addressList);
570}
571
572const BoundNetLog& SSLClientSocketOpenSSL::NetLog() const {
573 return net_log_;
574}
575
576void SSLClientSocketOpenSSL::SetSubresourceSpeculation() {
577 if (transport_.get() && transport_->socket()) {
578 transport_->socket()->SetSubresourceSpeculation();
579 } else {
580 NOTREACHED();
581 }
582}
583
584void SSLClientSocketOpenSSL::SetOmniboxSpeculation() {
585 if (transport_.get() && transport_->socket()) {
586 transport_->socket()->SetOmniboxSpeculation();
587 } else {
588 NOTREACHED();
589 }
590}
591
592bool SSLClientSocketOpenSSL::WasEverUsed() const {
[email protected]0dc88b32014-03-26 20:12:28593 return was_ever_used_;
[email protected]b9b651f2013-11-09 04:32:22594}
595
596bool SSLClientSocketOpenSSL::UsingTCPFastOpen() const {
597 if (transport_.get() && transport_->socket())
598 return transport_->socket()->UsingTCPFastOpen();
599
600 NOTREACHED();
601 return false;
602}
603
604bool SSLClientSocketOpenSSL::GetSSLInfo(SSLInfo* ssl_info) {
605 ssl_info->Reset();
davidben30798ed82014-09-19 19:28:20606 if (server_cert_chain_->empty())
[email protected]b9b651f2013-11-09 04:32:22607 return false;
608
609 ssl_info->cert = server_cert_verify_result_.verified_cert;
610 ssl_info->cert_status = server_cert_verify_result_.cert_status;
611 ssl_info->is_issued_by_known_root =
612 server_cert_verify_result_.is_issued_by_known_root;
613 ssl_info->public_key_hashes =
614 server_cert_verify_result_.public_key_hashes;
615 ssl_info->client_cert_sent =
616 ssl_config_.send_client_cert && ssl_config_.client_cert.get();
617 ssl_info->channel_id_sent = WasChannelIDSent();
[email protected]8bd4e7a2014-08-09 14:49:17618 ssl_info->pinning_failure_log = pinning_failure_log_;
[email protected]b9b651f2013-11-09 04:32:22619
davidbeneb5f8ef32014-09-04 14:14:32620 AddSCTInfoToSSLInfo(ssl_info);
621
[email protected]b9b651f2013-11-09 04:32:22622 const SSL_CIPHER* cipher = SSL_get_current_cipher(ssl_);
623 CHECK(cipher);
624 ssl_info->security_bits = SSL_CIPHER_get_bits(cipher, NULL);
[email protected]b9b651f2013-11-09 04:32:22625
626 ssl_info->connection_status = EncodeSSLConnectionStatus(
pkasting6b68a162014-12-01 22:10:29627 static_cast<uint16>(SSL_CIPHER_get_id(cipher)), 0 /* no compression */,
[email protected]b9b651f2013-11-09 04:32:22628 GetNetSSLVersion(ssl_));
629
davidben09c3d072014-08-25 20:33:58630 if (!SSL_get_secure_renegotiation_support(ssl_))
[email protected]b9b651f2013-11-09 04:32:22631 ssl_info->connection_status |= SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION;
[email protected]b9b651f2013-11-09 04:32:22632
633 if (ssl_config_.version_fallback)
634 ssl_info->connection_status |= SSL_CONNECTION_VERSION_FALLBACK;
635
636 ssl_info->handshake_type = SSL_session_reused(ssl_) ?
637 SSLInfo::HANDSHAKE_RESUME : SSLInfo::HANDSHAKE_FULL;
638
639 DVLOG(3) << "Encoded connection status: cipher suite = "
640 << SSLConnectionStatusToCipherSuite(ssl_info->connection_status)
641 << " version = "
642 << SSLConnectionStatusToVersion(ssl_info->connection_status);
643 return true;
644}
645
646int SSLClientSocketOpenSSL::Read(IOBuffer* buf,
647 int buf_len,
648 const CompletionCallback& callback) {
649 user_read_buf_ = buf;
650 user_read_buf_len_ = buf_len;
651
davidben1b133ad2014-10-23 04:23:13652 int rv = DoReadLoop();
[email protected]b9b651f2013-11-09 04:32:22653
654 if (rv == ERR_IO_PENDING) {
655 user_read_callback_ = callback;
656 } else {
[email protected]0dc88b32014-03-26 20:12:28657 if (rv > 0)
658 was_ever_used_ = true;
[email protected]b9b651f2013-11-09 04:32:22659 user_read_buf_ = NULL;
660 user_read_buf_len_ = 0;
[email protected]8e458552014-08-05 00:02:15661 if (rv <= 0) {
662 // Failure of a read attempt may indicate a failed false start
663 // connection.
664 OnHandshakeCompletion();
665 }
[email protected]b9b651f2013-11-09 04:32:22666 }
667
668 return rv;
669}
670
671int SSLClientSocketOpenSSL::Write(IOBuffer* buf,
672 int buf_len,
673 const CompletionCallback& callback) {
674 user_write_buf_ = buf;
675 user_write_buf_len_ = buf_len;
676
davidben1b133ad2014-10-23 04:23:13677 int rv = DoWriteLoop();
[email protected]b9b651f2013-11-09 04:32:22678
679 if (rv == ERR_IO_PENDING) {
680 user_write_callback_ = callback;
681 } else {
[email protected]0dc88b32014-03-26 20:12:28682 if (rv > 0)
683 was_ever_used_ = true;
[email protected]b9b651f2013-11-09 04:32:22684 user_write_buf_ = NULL;
685 user_write_buf_len_ = 0;
[email protected]8e458552014-08-05 00:02:15686 if (rv < 0) {
687 // Failure of a write attempt may indicate a failed false start
688 // connection.
689 OnHandshakeCompletion();
690 }
[email protected]b9b651f2013-11-09 04:32:22691 }
692
693 return rv;
694}
695
[email protected]28b96d1c2014-04-09 12:21:15696int SSLClientSocketOpenSSL::SetReceiveBufferSize(int32 size) {
[email protected]b9b651f2013-11-09 04:32:22697 return transport_->socket()->SetReceiveBufferSize(size);
698}
699
[email protected]28b96d1c2014-04-09 12:21:15700int SSLClientSocketOpenSSL::SetSendBufferSize(int32 size) {
[email protected]b9b651f2013-11-09 04:32:22701 return transport_->socket()->SetSendBufferSize(size);
702}
703
[email protected]c8a80e92014-05-17 16:02:08704int SSLClientSocketOpenSSL::Init() {
[email protected]9e733f32010-10-04 18:19:08705 DCHECK(!ssl_);
706 DCHECK(!transport_bio_);
707
[email protected]b29af7d2010-12-14 11:52:47708 SSLContext* context = SSLContext::GetInstance();
[email protected]4b559b4d2011-04-14 17:37:14709 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
[email protected]d518cd92010-09-29 12:27:44710
[email protected]fbef13932010-11-23 12:38:53711 ssl_ = SSL_new(context->ssl_ctx());
712 if (!ssl_ || !context->SetClientSocketForSSL(ssl_, this))
[email protected]c8a80e92014-05-17 16:02:08713 return ERR_UNEXPECTED;
[email protected]fbef13932010-11-23 12:38:53714
715 if (!SSL_set_tlsext_host_name(ssl_, host_and_port_.host().c_str()))
[email protected]c8a80e92014-05-17 16:02:08716 return ERR_UNEXPECTED;
[email protected]fbef13932010-11-23 12:38:53717
[email protected]e4738ba52014-08-07 10:07:22718 // Set an OpenSSL callback to monitor this SSL*'s connection.
719 SSL_set_info_callback(ssl_, &InfoCallback);
720
[email protected]1279de12013-12-03 15:13:32721 trying_cached_session_ = context->session_cache()->SetSSLSessionWithKey(
[email protected]8e458552014-08-05 00:02:15722 ssl_, GetSessionCacheKey());
[email protected]d518cd92010-09-29 12:27:44723
724 BIO* ssl_bio = NULL;
[email protected]fbef13932010-11-23 12:38:53725 // 0 => use default buffer sizes.
726 if (!BIO_new_bio_pair(&ssl_bio, 0, &transport_bio_, 0))
[email protected]c8a80e92014-05-17 16:02:08727 return ERR_UNEXPECTED;
[email protected]d518cd92010-09-29 12:27:44728 DCHECK(ssl_bio);
729 DCHECK(transport_bio_);
730
[email protected]5aea79182014-07-14 20:43:41731 // Install a callback on OpenSSL's end to plumb transport errors through.
[email protected]64b5c892014-08-08 09:39:26732 BIO_set_callback(ssl_bio, BIOCallback);
[email protected]5aea79182014-07-14 20:43:41733 BIO_set_callback_arg(ssl_bio, reinterpret_cast<char*>(this));
734
[email protected]d518cd92010-09-29 12:27:44735 SSL_set_bio(ssl_, ssl_bio, ssl_bio);
736
[email protected]9e733f32010-10-04 18:19:08737 // OpenSSL defaults some options to on, others to off. To avoid ambiguity,
738 // set everything we care about to an absolute value.
[email protected]fb10e2282010-12-01 17:08:48739 SslSetClearMask options;
740 options.ConfigureFlag(SSL_OP_NO_SSLv2, true);
[email protected]80c75f682012-05-26 16:22:17741 bool ssl3_enabled = (ssl_config_.version_min == SSL_PROTOCOL_VERSION_SSL3);
742 options.ConfigureFlag(SSL_OP_NO_SSLv3, !ssl3_enabled);
743 bool tls1_enabled = (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1 &&
744 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1);
745 options.ConfigureFlag(SSL_OP_NO_TLSv1, !tls1_enabled);
[email protected]80c75f682012-05-26 16:22:17746 bool tls1_1_enabled =
747 (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1_1 &&
748 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1_1);
749 options.ConfigureFlag(SSL_OP_NO_TLSv1_1, !tls1_1_enabled);
[email protected]80c75f682012-05-26 16:22:17750 bool tls1_2_enabled =
751 (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1_2 &&
752 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1_2);
753 options.ConfigureFlag(SSL_OP_NO_TLSv1_2, !tls1_2_enabled);
[email protected]fb10e2282010-12-01 17:08:48754
[email protected]d0f00492012-08-03 22:35:13755 options.ConfigureFlag(SSL_OP_NO_COMPRESSION, true);
[email protected]9e733f32010-10-04 18:19:08756
757 // TODO(joth): Set this conditionally, see http://crbug.com/55410
[email protected]fb10e2282010-12-01 17:08:48758 options.ConfigureFlag(SSL_OP_LEGACY_SERVER_CONNECT, true);
[email protected]9e733f32010-10-04 18:19:08759
[email protected]fb10e2282010-12-01 17:08:48760 SSL_set_options(ssl_, options.set_mask);
761 SSL_clear_options(ssl_, options.clear_mask);
[email protected]9e733f32010-10-04 18:19:08762
[email protected]fb10e2282010-12-01 17:08:48763 // Same as above, this time for the SSL mode.
764 SslSetClearMask mode;
[email protected]9e733f32010-10-04 18:19:08765
[email protected]fb10e2282010-12-01 17:08:48766 mode.ConfigureFlag(SSL_MODE_RELEASE_BUFFERS, true);
ishermane5c05e12014-09-09 20:32:15767 mode.ConfigureFlag(SSL_MODE_CBC_RECORD_SPLITTING, true);
[email protected]fb10e2282010-12-01 17:08:48768
[email protected]b788de02014-04-23 18:06:07769 mode.ConfigureFlag(SSL_MODE_HANDSHAKE_CUTTHROUGH,
770 ssl_config_.false_start_enabled);
771
[email protected]fb10e2282010-12-01 17:08:48772 SSL_set_mode(ssl_, mode.set_mask);
773 SSL_clear_mode(ssl_, mode.clear_mask);
[email protected]109805a2010-12-07 18:17:06774
775 // Removing ciphers by ID from OpenSSL is a bit involved as we must use the
776 // textual name with SSL_set_cipher_list because there is no public API to
777 // directly remove a cipher by ID.
778 STACK_OF(SSL_CIPHER)* ciphers = SSL_get_ciphers(ssl_);
779 DCHECK(ciphers);
780 // See SSLConfig::disabled_cipher_suites for description of the suites
[email protected]9b4bc4a92013-08-20 22:59:07781 // disabled by default. Note that !SHA256 and !SHA384 only remove HMAC-SHA256
782 // and HMAC-SHA384 cipher suites, not GCM cipher suites with SHA256 or SHA384
783 // as the handshake hash.
784 std::string command("DEFAULT:!NULL:!aNULL:!IDEA:!FZA:!SRP:!SHA256:!SHA384:"
785 "!aECDH:!AESGCM+AES256");
[email protected]109805a2010-12-07 18:17:06786 // Walk through all the installed ciphers, seeing if any need to be
787 // appended to the cipher removal |command|.
[email protected]edfd0f42014-07-22 18:20:37788 for (size_t i = 0; i < sk_SSL_CIPHER_num(ciphers); ++i) {
[email protected]109805a2010-12-07 18:17:06789 const SSL_CIPHER* cipher = sk_SSL_CIPHER_value(ciphers, i);
pkasting6b68a162014-12-01 22:10:29790 const uint16 id = static_cast<uint16>(SSL_CIPHER_get_id(cipher));
[email protected]109805a2010-12-07 18:17:06791 // Remove any ciphers with a strength of less than 80 bits. Note the NSS
792 // implementation uses "effective" bits here but OpenSSL does not provide
793 // this detail. This only impacts Triple DES: reports 112 vs. 168 bits,
794 // both of which are greater than 80 anyway.
795 bool disable = SSL_CIPHER_get_bits(cipher, NULL) < 80;
796 if (!disable) {
797 disable = std::find(ssl_config_.disabled_cipher_suites.begin(),
798 ssl_config_.disabled_cipher_suites.end(), id) !=
799 ssl_config_.disabled_cipher_suites.end();
800 }
801 if (disable) {
802 const char* name = SSL_CIPHER_get_name(cipher);
803 DVLOG(3) << "Found cipher to remove: '" << name << "', ID: " << id
804 << " strength: " << SSL_CIPHER_get_bits(cipher, NULL);
805 command.append(":!");
806 command.append(name);
807 }
808 }
davidben8ecc3072014-09-03 23:19:09809
810 // Disable ECDSA cipher suites on platforms that do not support ECDSA
811 // signed certificates, as servers may use the presence of such
812 // ciphersuites as a hint to send an ECDSA certificate.
813#if defined(OS_WIN)
814 if (base::win::GetVersion() < base::win::VERSION_VISTA)
815 command.append(":!ECDSA");
816#endif
817
[email protected]109805a2010-12-07 18:17:06818 int rv = SSL_set_cipher_list(ssl_, command.c_str());
819 // If this fails (rv = 0) it means there are no ciphers enabled on this SSL.
820 // This will almost certainly result in the socket failing to complete the
821 // handshake at which point the appropriate error is bubbled up to the client.
822 LOG_IF(WARNING, rv != 1) << "SSL_set_cipher_list('" << command << "') "
823 "returned " << rv;
[email protected]ee0f2aa82013-10-25 11:59:26824
[email protected]0d0a6872014-07-26 18:05:11825 if (ssl_config_.version_fallback)
826 SSL_enable_fallback_scsv(ssl_);
827
[email protected]ee0f2aa82013-10-25 11:59:26828 // TLS channel ids.
[email protected]6b8a3c742014-07-25 00:25:35829 if (IsChannelIDEnabled(ssl_config_, channel_id_service_)) {
[email protected]ee0f2aa82013-10-25 11:59:26830 SSL_enable_tls_channel_id(ssl_);
831 }
832
[email protected]abc44b752014-07-30 03:52:15833 if (!ssl_config_.next_protos.empty()) {
834 std::vector<uint8_t> wire_protos =
835 SerializeNextProtos(ssl_config_.next_protos);
836 SSL_set_alpn_protos(ssl_, wire_protos.empty() ? NULL : &wire_protos[0],
837 wire_protos.size());
838 }
839
davidbeneb5f8ef32014-09-04 14:14:32840 if (ssl_config_.signed_cert_timestamps_enabled) {
841 SSL_enable_signed_cert_timestamps(ssl_);
842 SSL_enable_ocsp_stapling(ssl_);
843 }
844
davidbend1fb2f12014-11-08 02:51:00845 if (IsOCSPStaplingSupported())
846 SSL_enable_ocsp_stapling(ssl_);
davidbeneb5f8ef32014-09-04 14:14:32847
[email protected]c8a80e92014-05-17 16:02:08848 return OK;
[email protected]d518cd92010-09-29 12:27:44849}
850
[email protected]b9b651f2013-11-09 04:32:22851void SSLClientSocketOpenSSL::DoReadCallback(int rv) {
852 // Since Run may result in Read being called, clear |user_read_callback_|
853 // up front.
[email protected]0dc88b32014-03-26 20:12:28854 if (rv > 0)
855 was_ever_used_ = true;
[email protected]b9b651f2013-11-09 04:32:22856 user_read_buf_ = NULL;
857 user_read_buf_len_ = 0;
[email protected]8e458552014-08-05 00:02:15858 if (rv <= 0) {
859 // Failure of a read attempt may indicate a failed false start
860 // connection.
861 OnHandshakeCompletion();
862 }
[email protected]b9b651f2013-11-09 04:32:22863 base::ResetAndReturn(&user_read_callback_).Run(rv);
864}
865
866void SSLClientSocketOpenSSL::DoWriteCallback(int rv) {
867 // Since Run may result in Write being called, clear |user_write_callback_|
868 // up front.
[email protected]0dc88b32014-03-26 20:12:28869 if (rv > 0)
870 was_ever_used_ = true;
[email protected]b9b651f2013-11-09 04:32:22871 user_write_buf_ = NULL;
872 user_write_buf_len_ = 0;
[email protected]8e458552014-08-05 00:02:15873 if (rv < 0) {
874 // Failure of a write attempt may indicate a failed false start
875 // connection.
876 OnHandshakeCompletion();
877 }
[email protected]b9b651f2013-11-09 04:32:22878 base::ResetAndReturn(&user_write_callback_).Run(rv);
879}
880
[email protected]8e458552014-08-05 00:02:15881void SSLClientSocketOpenSSL::OnHandshakeCompletion() {
882 if (!handshake_completion_callback_.is_null())
883 base::ResetAndReturn(&handshake_completion_callback_).Run();
884}
885
[email protected]b9b651f2013-11-09 04:32:22886bool SSLClientSocketOpenSSL::DoTransportIO() {
887 bool network_moved = false;
888 int rv;
889 // Read and write as much data as possible. The loop is necessary because
890 // Write() may return synchronously.
891 do {
892 rv = BufferSend();
893 if (rv != ERR_IO_PENDING && rv != 0)
894 network_moved = true;
895 } while (rv > 0);
[email protected]5aea79182014-07-14 20:43:41896 if (transport_read_error_ == OK && BufferRecv() != ERR_IO_PENDING)
[email protected]b9b651f2013-11-09 04:32:22897 network_moved = true;
898 return network_moved;
899}
900
901int SSLClientSocketOpenSSL::DoHandshake() {
vadimtb2a77c762014-11-21 19:49:22902 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
903 tracked_objects::ScopedTracker tracking_profile1(
904 FROM_HERE_WITH_EXPLICIT_FUNCTION(
905 "424386 SSLClientSocketOpenSSL::DoHandshake1"));
906
[email protected]b9b651f2013-11-09 04:32:22907 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
[email protected]c8a80e92014-05-17 16:02:08908 int net_error = OK;
[email protected]b9b651f2013-11-09 04:32:22909 int rv = SSL_do_handshake(ssl_);
910
vadimtb2a77c762014-11-21 19:49:22911 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
912 tracked_objects::ScopedTracker tracking_profile2(
913 FROM_HERE_WITH_EXPLICIT_FUNCTION(
914 "424386 SSLClientSocketOpenSSL::DoHandshake2"));
915
[email protected]b9b651f2013-11-09 04:32:22916 if (client_auth_cert_needed_) {
917 net_error = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
918 // If the handshake already succeeded (because the server requests but
919 // doesn't require a client cert), we need to invalidate the SSL session
920 // so that we won't try to resume the non-client-authenticated session in
921 // the next handshake. This will cause the server to ask for a client
922 // cert again.
923 if (rv == 1) {
924 // Remove from session cache but don't clear this connection.
925 SSL_SESSION* session = SSL_get_session(ssl_);
926 if (session) {
927 int rv = SSL_CTX_remove_session(SSL_get_SSL_CTX(ssl_), session);
928 LOG_IF(WARNING, !rv) << "Couldn't invalidate SSL session: " << session;
929 }
930 }
931 } else if (rv == 1) {
932 if (trying_cached_session_ && logging::DEBUG_MODE) {
933 DVLOG(2) << "Result of session reuse for " << host_and_port_.ToString()
934 << " is: " << (SSL_session_reused(ssl_) ? "Success" : "Fail");
935 }
[email protected]abc44b752014-07-30 03:52:15936
Adam Langley32352ad2014-10-14 22:31:00937 if (ssl_config_.version_fallback &&
938 ssl_config_.version_max < ssl_config_.version_fallback_min) {
939 return ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION;
940 }
941
[email protected]abc44b752014-07-30 03:52:15942 // SSL handshake is completed. If NPN wasn't negotiated, see if ALPN was.
943 if (npn_status_ == kNextProtoUnsupported) {
944 const uint8_t* alpn_proto = NULL;
945 unsigned alpn_len = 0;
946 SSL_get0_alpn_selected(ssl_, &alpn_proto, &alpn_len);
947 if (alpn_len > 0) {
948 npn_proto_.assign(reinterpret_cast<const char*>(alpn_proto), alpn_len);
949 npn_status_ = kNextProtoNegotiated;
bnc0d28ea52014-10-13 15:15:38950 set_negotiation_extension(kExtensionALPN);
[email protected]abc44b752014-07-30 03:52:15951 }
952 }
953
davidben09c3d072014-08-25 20:33:58954 RecordChannelIDSupport(channel_id_service_,
955 channel_id_xtn_negotiated_,
956 ssl_config_.channel_id_enabled,
957 crypto::ECPrivateKey::IsSupported());
958
davidbend1fb2f12014-11-08 02:51:00959 // Only record OCSP histograms if OCSP was requested.
960 if (ssl_config_.signed_cert_timestamps_enabled ||
961 IsOCSPStaplingSupported()) {
davidben54015aa2014-12-02 22:16:23962 const uint8_t* ocsp_response;
davidbend1fb2f12014-11-08 02:51:00963 size_t ocsp_response_len;
964 SSL_get0_ocsp_response(ssl_, &ocsp_response, &ocsp_response_len);
965
966 set_stapled_ocsp_response_received(ocsp_response_len != 0);
967 UMA_HISTOGRAM_BOOLEAN("Net.OCSPResponseStapled", ocsp_response_len != 0);
968 }
davidbeneb5f8ef32014-09-04 14:14:32969
davidben54015aa2014-12-02 22:16:23970 const uint8_t* sct_list;
davidbeneb5f8ef32014-09-04 14:14:32971 size_t sct_list_len;
972 SSL_get0_signed_cert_timestamp_list(ssl_, &sct_list, &sct_list_len);
973 set_signed_cert_timestamps_received(sct_list_len != 0);
974
[email protected]abc44b752014-07-30 03:52:15975 // Verify the certificate.
davidben30798ed82014-09-19 19:28:20976 UpdateServerCert();
[email protected]b9b651f2013-11-09 04:32:22977 GotoState(STATE_VERIFY_CERT);
978 } else {
979 int ssl_error = SSL_get_error(ssl_, rv);
980
981 if (ssl_error == SSL_ERROR_WANT_CHANNEL_ID_LOOKUP) {
[email protected]faff9852014-06-21 06:13:46982 // The server supports channel ID. Stop to look one up before returning to
983 // the handshake.
984 channel_id_xtn_negotiated_ = true;
985 GotoState(STATE_CHANNEL_ID_LOOKUP);
986 return OK;
[email protected]b9b651f2013-11-09 04:32:22987 }
988
davidbena4409c62014-08-27 17:05:51989 OpenSSLErrorInfo error_info;
990 net_error = MapOpenSSLErrorWithDetails(ssl_error, err_tracer, &error_info);
[email protected]faff9852014-06-21 06:13:46991
[email protected]b9b651f2013-11-09 04:32:22992 // If not done, stay in this state
993 if (net_error == ERR_IO_PENDING) {
994 GotoState(STATE_HANDSHAKE);
995 } else {
996 LOG(ERROR) << "handshake failed; returned " << rv
997 << ", SSL error code " << ssl_error
998 << ", net_error " << net_error;
999 net_log_.AddEvent(
1000 NetLog::TYPE_SSL_HANDSHAKE_ERROR,
davidbena4409c62014-08-27 17:05:511001 CreateNetLogOpenSSLErrorCallback(net_error, ssl_error, error_info));
[email protected]b9b651f2013-11-09 04:32:221002 }
1003 }
1004 return net_error;
1005}
1006
[email protected]faff9852014-06-21 06:13:461007int SSLClientSocketOpenSSL::DoChannelIDLookup() {
1008 GotoState(STATE_CHANNEL_ID_LOOKUP_COMPLETE);
[email protected]6b8a3c742014-07-25 00:25:351009 return channel_id_service_->GetOrCreateChannelID(
[email protected]faff9852014-06-21 06:13:461010 host_and_port_.host(),
1011 &channel_id_private_key_,
1012 &channel_id_cert_,
1013 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete,
1014 base::Unretained(this)),
1015 &channel_id_request_handle_);
1016}
1017
1018int SSLClientSocketOpenSSL::DoChannelIDLookupComplete(int result) {
1019 if (result < 0)
1020 return result;
1021
1022 DCHECK_LT(0u, channel_id_private_key_.size());
1023 // Decode key.
1024 std::vector<uint8> encrypted_private_key_info;
1025 std::vector<uint8> subject_public_key_info;
1026 encrypted_private_key_info.assign(
1027 channel_id_private_key_.data(),
1028 channel_id_private_key_.data() + channel_id_private_key_.size());
1029 subject_public_key_info.assign(
1030 channel_id_cert_.data(),
1031 channel_id_cert_.data() + channel_id_cert_.size());
1032 scoped_ptr<crypto::ECPrivateKey> ec_private_key(
1033 crypto::ECPrivateKey::CreateFromEncryptedPrivateKeyInfo(
[email protected]6b8a3c742014-07-25 00:25:351034 ChannelIDService::kEPKIPassword,
[email protected]faff9852014-06-21 06:13:461035 encrypted_private_key_info,
1036 subject_public_key_info));
1037 if (!ec_private_key) {
1038 LOG(ERROR) << "Failed to import Channel ID.";
1039 return ERR_CHANNEL_ID_IMPORT_FAILED;
1040 }
1041
1042 // Hand the key to OpenSSL. Check for error in case OpenSSL rejects the key
1043 // type.
1044 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1045 int rv = SSL_set1_tls_channel_id(ssl_, ec_private_key->key());
1046 if (!rv) {
1047 LOG(ERROR) << "Failed to set Channel ID.";
1048 int err = SSL_get_error(ssl_, rv);
1049 return MapOpenSSLError(err, err_tracer);
1050 }
1051
1052 // Return to the handshake.
1053 set_channel_id_sent(true);
1054 GotoState(STATE_HANDSHAKE);
1055 return OK;
1056}
1057
[email protected]b9b651f2013-11-09 04:32:221058int SSLClientSocketOpenSSL::DoVerifyCert(int result) {
davidben30798ed82014-09-19 19:28:201059 DCHECK(!server_cert_chain_->empty());
davidben09c3d072014-08-25 20:33:581060 DCHECK(start_cert_verification_time_.is_null());
davidben30798ed82014-09-19 19:28:201061
[email protected]b9b651f2013-11-09 04:32:221062 GotoState(STATE_VERIFY_CERT_COMPLETE);
1063
davidben30798ed82014-09-19 19:28:201064 // If the certificate is bad and has been previously accepted, use
1065 // the previous status and bypass the error.
1066 base::StringPiece der_cert;
1067 if (!x509_util::GetDER(server_cert_chain_->Get(0), &der_cert)) {
1068 NOTREACHED();
1069 return ERR_CERT_INVALID;
1070 }
[email protected]b9b651f2013-11-09 04:32:221071 CertStatus cert_status;
davidben30798ed82014-09-19 19:28:201072 if (ssl_config_.IsAllowedBadCert(der_cert, &cert_status)) {
[email protected]b9b651f2013-11-09 04:32:221073 VLOG(1) << "Received an expected bad cert with status: " << cert_status;
1074 server_cert_verify_result_.Reset();
1075 server_cert_verify_result_.cert_status = cert_status;
1076 server_cert_verify_result_.verified_cert = server_cert_;
1077 return OK;
1078 }
1079
davidben30798ed82014-09-19 19:28:201080 // When running in a sandbox, it may not be possible to create an
1081 // X509Certificate*, as that may depend on OS functionality blocked
1082 // in the sandbox.
1083 if (!server_cert_.get()) {
1084 server_cert_verify_result_.Reset();
1085 server_cert_verify_result_.cert_status = CERT_STATUS_INVALID;
1086 return ERR_CERT_INVALID;
1087 }
1088
davidben09c3d072014-08-25 20:33:581089 start_cert_verification_time_ = base::TimeTicks::Now();
1090
[email protected]b9b651f2013-11-09 04:32:221091 int flags = 0;
1092 if (ssl_config_.rev_checking_enabled)
1093 flags |= CertVerifier::VERIFY_REV_CHECKING_ENABLED;
1094 if (ssl_config_.verify_ev_cert)
1095 flags |= CertVerifier::VERIFY_EV_CERT;
1096 if (ssl_config_.cert_io_enabled)
1097 flags |= CertVerifier::VERIFY_CERT_IO_ENABLED;
1098 if (ssl_config_.rev_checking_required_local_anchors)
1099 flags |= CertVerifier::VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS;
1100 verifier_.reset(new SingleRequestCertVerifier(cert_verifier_));
1101 return verifier_->Verify(
1102 server_cert_.get(),
1103 host_and_port_.host(),
1104 flags,
[email protected]591cffcd2014-08-18 20:02:301105 // TODO(davidben): Route the CRLSet through SSLConfig so
1106 // SSLClientSocket doesn't depend on SSLConfigService.
1107 SSLConfigService::GetCRLSet().get(),
[email protected]b9b651f2013-11-09 04:32:221108 &server_cert_verify_result_,
1109 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete,
1110 base::Unretained(this)),
1111 net_log_);
1112}
1113
1114int SSLClientSocketOpenSSL::DoVerifyCertComplete(int result) {
1115 verifier_.reset();
1116
davidben09c3d072014-08-25 20:33:581117 if (!start_cert_verification_time_.is_null()) {
1118 base::TimeDelta verify_time =
1119 base::TimeTicks::Now() - start_cert_verification_time_;
1120 if (result == OK) {
1121 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTime", verify_time);
1122 } else {
1123 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTimeError", verify_time);
1124 }
1125 }
1126
davidben7c7ab602014-11-05 22:27:441127 if (result == OK)
1128 RecordConnectionTypeMetrics(GetNetSSLVersion(ssl_));
1129
[email protected]8bd4e7a2014-08-09 14:49:171130 const CertStatus cert_status = server_cert_verify_result_.cert_status;
1131 if (transport_security_state_ &&
1132 (result == OK ||
1133 (IsCertificateError(result) && IsCertStatusMinorError(cert_status))) &&
1134 !transport_security_state_->CheckPublicKeyPins(
1135 host_and_port_.host(),
[email protected]8bd4e7a2014-08-09 14:49:171136 server_cert_verify_result_.is_issued_by_known_root,
1137 server_cert_verify_result_.public_key_hashes,
1138 &pinning_failure_log_)) {
1139 result = ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN;
1140 }
1141
eranmefbd3132014-10-28 16:35:161142 scoped_refptr<ct::EVCertsWhitelist> ev_whitelist =
1143 SSLConfigService::GetEVCertsWhitelist();
1144 if (server_cert_verify_result_.cert_status & CERT_STATUS_IS_EV) {
1145 if (ev_whitelist.get() && ev_whitelist->IsValid()) {
1146 const SHA256HashValue fingerprint(
1147 X509Certificate::CalculateFingerprint256(
1148 server_cert_verify_result_.verified_cert->os_cert_handle()));
1149
1150 UMA_HISTOGRAM_BOOLEAN(
1151 "Net.SSL_EVCertificateInWhitelist",
1152 ev_whitelist->ContainsCertificateHash(
1153 std::string(reinterpret_cast<const char*>(fingerprint.data), 8)));
1154 }
1155 }
1156
[email protected]b9b651f2013-11-09 04:32:221157 if (result == OK) {
davidbeneb5f8ef32014-09-04 14:14:321158 // Only check Certificate Transparency if there were no other errors with
1159 // the connection.
1160 VerifyCT();
1161
[email protected]b9b651f2013-11-09 04:32:221162 // TODO(joth): Work out if we need to remember the intermediate CA certs
1163 // when the server sends them to us, and do so here.
[email protected]a8fed1742013-12-27 02:14:241164 SSLContext::GetInstance()->session_cache()->MarkSSLSessionAsGood(ssl_);
[email protected]e4738ba52014-08-07 10:07:221165 marked_session_as_good_ = true;
1166 CheckIfHandshakeFinished();
[email protected]b9b651f2013-11-09 04:32:221167 } else {
1168 DVLOG(1) << "DoVerifyCertComplete error " << ErrorToString(result)
1169 << " (" << result << ")";
1170 }
1171
[email protected]64b5c892014-08-08 09:39:261172 completed_connect_ = true;
[email protected]8bd4e7a2014-08-09 14:49:171173
[email protected]b9b651f2013-11-09 04:32:221174 // Exit DoHandshakeLoop and return the result to the caller to Connect.
1175 DCHECK_EQ(STATE_NONE, next_handshake_state_);
1176 return result;
1177}
1178
1179void SSLClientSocketOpenSSL::DoConnectCallback(int rv) {
[email protected]8e458552014-08-05 00:02:151180 if (rv < OK)
1181 OnHandshakeCompletion();
[email protected]b9b651f2013-11-09 04:32:221182 if (!user_connect_callback_.is_null()) {
1183 CompletionCallback c = user_connect_callback_;
1184 user_connect_callback_.Reset();
1185 c.Run(rv > OK ? OK : rv);
1186 }
1187}
1188
davidben30798ed82014-09-19 19:28:201189void SSLClientSocketOpenSSL::UpdateServerCert() {
[email protected]76e85392014-03-20 17:54:141190 server_cert_chain_->Reset(SSL_get_peer_cert_chain(ssl_));
[email protected]7f38da8a2014-03-17 16:44:261191 server_cert_ = server_cert_chain_->AsOSChain();
[email protected]76e85392014-03-20 17:54:141192
davidben30798ed82014-09-19 19:28:201193 if (server_cert_.get()) {
1194 net_log_.AddEvent(
1195 NetLog::TYPE_SSL_CERTIFICATES_RECEIVED,
1196 base::Bind(&NetLogX509CertificateCallback,
1197 base::Unretained(server_cert_.get())));
davidbend1fb2f12014-11-08 02:51:001198
1199 // TODO(rsleevi): Plumb an OCSP response into the Mac system library and
1200 // update IsOCSPStaplingSupported for Mac. https://crbug.com/430714
1201 if (IsOCSPStaplingSupported()) {
1202#if defined(OS_WIN)
davidben54015aa2014-12-02 22:16:231203 const uint8_t* ocsp_response_raw;
davidbend1fb2f12014-11-08 02:51:001204 size_t ocsp_response_len;
1205 SSL_get0_ocsp_response(ssl_, &ocsp_response_raw, &ocsp_response_len);
1206
1207 CRYPT_DATA_BLOB ocsp_response_blob;
1208 ocsp_response_blob.cbData = ocsp_response_len;
davidben54015aa2014-12-02 22:16:231209 ocsp_response_blob.pbData = const_cast<BYTE*>(ocsp_response_raw);
davidbend1fb2f12014-11-08 02:51:001210 BOOL ok = CertSetCertificateContextProperty(
1211 server_cert_->os_cert_handle(),
1212 CERT_OCSP_RESPONSE_PROP_ID,
1213 CERT_SET_PROPERTY_IGNORE_PERSIST_ERROR_FLAG,
1214 &ocsp_response_blob);
1215 if (!ok) {
1216 VLOG(1) << "Failed to set OCSP response property: "
1217 << GetLastError();
1218 }
1219#else
1220 NOTREACHED();
1221#endif
1222 }
davidben30798ed82014-09-19 19:28:201223 }
[email protected]b9b651f2013-11-09 04:32:221224}
1225
davidbeneb5f8ef32014-09-04 14:14:321226void SSLClientSocketOpenSSL::VerifyCT() {
1227 if (!cert_transparency_verifier_)
1228 return;
1229
davidben54015aa2014-12-02 22:16:231230 const uint8_t* ocsp_response_raw;
davidbeneb5f8ef32014-09-04 14:14:321231 size_t ocsp_response_len;
1232 SSL_get0_ocsp_response(ssl_, &ocsp_response_raw, &ocsp_response_len);
1233 std::string ocsp_response;
1234 if (ocsp_response_len > 0) {
1235 ocsp_response.assign(reinterpret_cast<const char*>(ocsp_response_raw),
1236 ocsp_response_len);
1237 }
1238
davidben54015aa2014-12-02 22:16:231239 const uint8_t* sct_list_raw;
davidbeneb5f8ef32014-09-04 14:14:321240 size_t sct_list_len;
1241 SSL_get0_signed_cert_timestamp_list(ssl_, &sct_list_raw, &sct_list_len);
1242 std::string sct_list;
1243 if (sct_list_len > 0)
1244 sct_list.assign(reinterpret_cast<const char*>(sct_list_raw), sct_list_len);
1245
1246 // Note that this is a completely synchronous operation: The CT Log Verifier
1247 // gets all the data it needs for SCT verification and does not do any
1248 // external communication.
1249 int result = cert_transparency_verifier_->Verify(
1250 server_cert_verify_result_.verified_cert.get(),
1251 ocsp_response, sct_list, &ct_verify_result_, net_log_);
1252
1253 VLOG(1) << "CT Verification complete: result " << result
1254 << " Invalid scts: " << ct_verify_result_.invalid_scts.size()
1255 << " Verified scts: " << ct_verify_result_.verified_scts.size()
1256 << " scts from unknown logs: "
1257 << ct_verify_result_.unknown_logs_scts.size();
1258}
1259
[email protected]b9b651f2013-11-09 04:32:221260void SSLClientSocketOpenSSL::OnHandshakeIOComplete(int result) {
1261 int rv = DoHandshakeLoop(result);
1262 if (rv != ERR_IO_PENDING) {
1263 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
1264 DoConnectCallback(rv);
1265 }
1266}
1267
1268void SSLClientSocketOpenSSL::OnSendComplete(int result) {
1269 if (next_handshake_state_ == STATE_HANDSHAKE) {
1270 // In handshake phase.
1271 OnHandshakeIOComplete(result);
1272 return;
1273 }
1274
1275 // OnSendComplete may need to call DoPayloadRead while the renegotiation
1276 // handshake is in progress.
1277 int rv_read = ERR_IO_PENDING;
1278 int rv_write = ERR_IO_PENDING;
1279 bool network_moved;
1280 do {
1281 if (user_read_buf_.get())
1282 rv_read = DoPayloadRead();
1283 if (user_write_buf_.get())
1284 rv_write = DoPayloadWrite();
1285 network_moved = DoTransportIO();
1286 } while (rv_read == ERR_IO_PENDING && rv_write == ERR_IO_PENDING &&
1287 (user_read_buf_.get() || user_write_buf_.get()) && network_moved);
1288
1289 // Performing the Read callback may cause |this| to be deleted. If this
1290 // happens, the Write callback should not be invoked. Guard against this by
1291 // holding a WeakPtr to |this| and ensuring it's still valid.
1292 base::WeakPtr<SSLClientSocketOpenSSL> guard(weak_factory_.GetWeakPtr());
1293 if (user_read_buf_.get() && rv_read != ERR_IO_PENDING)
1294 DoReadCallback(rv_read);
1295
1296 if (!guard.get())
1297 return;
1298
1299 if (user_write_buf_.get() && rv_write != ERR_IO_PENDING)
1300 DoWriteCallback(rv_write);
1301}
1302
1303void SSLClientSocketOpenSSL::OnRecvComplete(int result) {
1304 if (next_handshake_state_ == STATE_HANDSHAKE) {
1305 // In handshake phase.
1306 OnHandshakeIOComplete(result);
1307 return;
1308 }
1309
1310 // Network layer received some data, check if client requested to read
1311 // decrypted data.
1312 if (!user_read_buf_.get())
1313 return;
1314
davidben1b133ad2014-10-23 04:23:131315 int rv = DoReadLoop();
[email protected]b9b651f2013-11-09 04:32:221316 if (rv != ERR_IO_PENDING)
1317 DoReadCallback(rv);
1318}
1319
1320int SSLClientSocketOpenSSL::DoHandshakeLoop(int last_io_result) {
1321 int rv = last_io_result;
1322 do {
1323 // Default to STATE_NONE for next state.
1324 // (This is a quirk carried over from the windows
1325 // implementation. It makes reading the logs a bit harder.)
1326 // State handlers can and often do call GotoState just
1327 // to stay in the current state.
1328 State state = next_handshake_state_;
1329 GotoState(STATE_NONE);
1330 switch (state) {
1331 case STATE_HANDSHAKE:
1332 rv = DoHandshake();
1333 break;
[email protected]faff9852014-06-21 06:13:461334 case STATE_CHANNEL_ID_LOOKUP:
1335 DCHECK_EQ(OK, rv);
1336 rv = DoChannelIDLookup();
1337 break;
1338 case STATE_CHANNEL_ID_LOOKUP_COMPLETE:
1339 rv = DoChannelIDLookupComplete(rv);
1340 break;
[email protected]b9b651f2013-11-09 04:32:221341 case STATE_VERIFY_CERT:
[email protected]faff9852014-06-21 06:13:461342 DCHECK_EQ(OK, rv);
[email protected]b9b651f2013-11-09 04:32:221343 rv = DoVerifyCert(rv);
1344 break;
1345 case STATE_VERIFY_CERT_COMPLETE:
1346 rv = DoVerifyCertComplete(rv);
1347 break;
1348 case STATE_NONE:
1349 default:
1350 rv = ERR_UNEXPECTED;
1351 NOTREACHED() << "unexpected state" << state;
1352 break;
1353 }
1354
1355 bool network_moved = DoTransportIO();
1356 if (network_moved && next_handshake_state_ == STATE_HANDSHAKE) {
1357 // In general we exit the loop if rv is ERR_IO_PENDING. In this
1358 // special case we keep looping even if rv is ERR_IO_PENDING because
1359 // the transport IO may allow DoHandshake to make progress.
1360 rv = OK; // This causes us to stay in the loop.
1361 }
1362 } while (rv != ERR_IO_PENDING && next_handshake_state_ != STATE_NONE);
[email protected]8e458552014-08-05 00:02:151363
[email protected]b9b651f2013-11-09 04:32:221364 return rv;
1365}
1366
davidben1b133ad2014-10-23 04:23:131367int SSLClientSocketOpenSSL::DoReadLoop() {
[email protected]b9b651f2013-11-09 04:32:221368 bool network_moved;
1369 int rv;
1370 do {
1371 rv = DoPayloadRead();
1372 network_moved = DoTransportIO();
1373 } while (rv == ERR_IO_PENDING && network_moved);
1374
1375 return rv;
1376}
1377
davidben1b133ad2014-10-23 04:23:131378int SSLClientSocketOpenSSL::DoWriteLoop() {
[email protected]b9b651f2013-11-09 04:32:221379 bool network_moved;
1380 int rv;
1381 do {
1382 rv = DoPayloadWrite();
1383 network_moved = DoTransportIO();
1384 } while (rv == ERR_IO_PENDING && network_moved);
1385
1386 return rv;
1387}
1388
1389int SSLClientSocketOpenSSL::DoPayloadRead() {
1390 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1391
1392 int rv;
1393 if (pending_read_error_ != kNoPendingReadResult) {
1394 rv = pending_read_error_;
1395 pending_read_error_ = kNoPendingReadResult;
1396 if (rv == 0) {
1397 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED,
1398 rv, user_read_buf_->data());
davidbenb8c23212014-10-28 00:12:161399 } else {
1400 net_log_.AddEvent(
1401 NetLog::TYPE_SSL_READ_ERROR,
1402 CreateNetLogOpenSSLErrorCallback(rv, pending_read_ssl_error_,
1403 pending_read_error_info_));
[email protected]b9b651f2013-11-09 04:32:221404 }
davidbenb8c23212014-10-28 00:12:161405 pending_read_ssl_error_ = SSL_ERROR_NONE;
1406 pending_read_error_info_ = OpenSSLErrorInfo();
[email protected]b9b651f2013-11-09 04:32:221407 return rv;
1408 }
1409
1410 int total_bytes_read = 0;
1411 do {
1412 rv = SSL_read(ssl_, user_read_buf_->data() + total_bytes_read,
1413 user_read_buf_len_ - total_bytes_read);
1414 if (rv > 0)
1415 total_bytes_read += rv;
1416 } while (total_bytes_read < user_read_buf_len_ && rv > 0);
1417
1418 if (total_bytes_read == user_read_buf_len_) {
1419 rv = total_bytes_read;
1420 } else {
1421 // Otherwise, an error occurred (rv <= 0). The error needs to be handled
1422 // immediately, while the OpenSSL errors are still available in
1423 // thread-local storage. However, the handled/remapped error code should
1424 // only be returned if no application data was already read; if it was, the
1425 // error code should be deferred until the next call of DoPayloadRead.
1426 //
1427 // If no data was read, |*next_result| will point to the return value of
1428 // this function. If at least some data was read, |*next_result| will point
1429 // to |pending_read_error_|, to be returned in a future call to
1430 // DoPayloadRead() (e.g.: after the current data is handled).
1431 int *next_result = &rv;
1432 if (total_bytes_read > 0) {
1433 pending_read_error_ = rv;
1434 rv = total_bytes_read;
1435 next_result = &pending_read_error_;
1436 }
1437
1438 if (client_auth_cert_needed_) {
1439 *next_result = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
1440 } else if (*next_result < 0) {
davidbenb8c23212014-10-28 00:12:161441 pending_read_ssl_error_ = SSL_get_error(ssl_, *next_result);
1442 *next_result = MapOpenSSLErrorWithDetails(pending_read_ssl_error_,
1443 err_tracer,
1444 &pending_read_error_info_);
davidbenbe6ce7ec2014-10-20 19:15:561445
1446 // Many servers do not reliably send a close_notify alert when shutting
1447 // down a connection, and instead terminate the TCP connection. This is
1448 // reported as ERR_CONNECTION_CLOSED. Because of this, map the unclean
1449 // shutdown to a graceful EOF, instead of treating it as an error as it
1450 // should be.
1451 if (*next_result == ERR_CONNECTION_CLOSED)
1452 *next_result = 0;
1453
[email protected]b9b651f2013-11-09 04:32:221454 if (rv > 0 && *next_result == ERR_IO_PENDING) {
1455 // If at least some data was read from SSL_read(), do not treat
1456 // insufficient data as an error to return in the next call to
1457 // DoPayloadRead() - instead, let the call fall through to check
1458 // SSL_read() again. This is because DoTransportIO() may complete
1459 // in between the next call to DoPayloadRead(), and thus it is
1460 // important to check SSL_read() on subsequent invocations to see
1461 // if a complete record may now be read.
1462 *next_result = kNoPendingReadResult;
1463 }
1464 }
1465 }
1466
1467 if (rv >= 0) {
1468 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, rv,
1469 user_read_buf_->data());
davidbenb8c23212014-10-28 00:12:161470 } else if (rv != ERR_IO_PENDING) {
1471 net_log_.AddEvent(
1472 NetLog::TYPE_SSL_READ_ERROR,
1473 CreateNetLogOpenSSLErrorCallback(rv, pending_read_ssl_error_,
1474 pending_read_error_info_));
1475 pending_read_ssl_error_ = SSL_ERROR_NONE;
1476 pending_read_error_info_ = OpenSSLErrorInfo();
[email protected]b9b651f2013-11-09 04:32:221477 }
1478 return rv;
1479}
1480
1481int SSLClientSocketOpenSSL::DoPayloadWrite() {
1482 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1483 int rv = SSL_write(ssl_, user_write_buf_->data(), user_write_buf_len_);
[email protected]b9b651f2013-11-09 04:32:221484 if (rv >= 0) {
1485 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_SENT, rv,
1486 user_write_buf_->data());
1487 return rv;
1488 }
1489
davidbenb8c23212014-10-28 00:12:161490 int ssl_error = SSL_get_error(ssl_, rv);
1491 OpenSSLErrorInfo error_info;
1492 int net_error = MapOpenSSLErrorWithDetails(ssl_error, err_tracer,
1493 &error_info);
1494
1495 if (net_error != ERR_IO_PENDING) {
1496 net_log_.AddEvent(
1497 NetLog::TYPE_SSL_WRITE_ERROR,
1498 CreateNetLogOpenSSLErrorCallback(net_error, ssl_error, error_info));
1499 }
1500 return net_error;
[email protected]b9b651f2013-11-09 04:32:221501}
1502
1503int SSLClientSocketOpenSSL::BufferSend(void) {
1504 if (transport_send_busy_)
1505 return ERR_IO_PENDING;
1506
1507 if (!send_buffer_.get()) {
1508 // Get a fresh send buffer out of the send BIO.
[email protected]edfd0f42014-07-22 18:20:371509 size_t max_read = BIO_pending(transport_bio_);
[email protected]b9b651f2013-11-09 04:32:221510 if (!max_read)
1511 return 0; // Nothing pending in the OpenSSL write BIO.
1512 send_buffer_ = new DrainableIOBuffer(new IOBuffer(max_read), max_read);
1513 int read_bytes = BIO_read(transport_bio_, send_buffer_->data(), max_read);
1514 DCHECK_GT(read_bytes, 0);
1515 CHECK_EQ(static_cast<int>(max_read), read_bytes);
1516 }
1517
1518 int rv = transport_->socket()->Write(
1519 send_buffer_.get(),
1520 send_buffer_->BytesRemaining(),
1521 base::Bind(&SSLClientSocketOpenSSL::BufferSendComplete,
1522 base::Unretained(this)));
1523 if (rv == ERR_IO_PENDING) {
1524 transport_send_busy_ = true;
1525 } else {
1526 TransportWriteComplete(rv);
1527 }
1528 return rv;
1529}
1530
1531int SSLClientSocketOpenSSL::BufferRecv(void) {
1532 if (transport_recv_busy_)
1533 return ERR_IO_PENDING;
1534
1535 // Determine how much was requested from |transport_bio_| that was not
1536 // actually available.
1537 size_t requested = BIO_ctrl_get_read_request(transport_bio_);
1538 if (requested == 0) {
1539 // This is not a perfect match of error codes, as no operation is
1540 // actually pending. However, returning 0 would be interpreted as
1541 // a possible sign of EOF, which is also an inappropriate match.
1542 return ERR_IO_PENDING;
1543 }
1544
1545 // Known Issue: While only reading |requested| data is the more correct
1546 // implementation, it has the downside of resulting in frequent reads:
1547 // One read for the SSL record header (~5 bytes) and one read for the SSL
1548 // record body. Rather than issuing these reads to the underlying socket
1549 // (and constantly allocating new IOBuffers), a single Read() request to
1550 // fill |transport_bio_| is issued. As long as an SSL client socket cannot
1551 // be gracefully shutdown (via SSL close alerts) and re-used for non-SSL
1552 // traffic, this over-subscribed Read()ing will not cause issues.
1553 size_t max_write = BIO_ctrl_get_write_guarantee(transport_bio_);
1554 if (!max_write)
1555 return ERR_IO_PENDING;
1556
1557 recv_buffer_ = new IOBuffer(max_write);
1558 int rv = transport_->socket()->Read(
1559 recv_buffer_.get(),
1560 max_write,
1561 base::Bind(&SSLClientSocketOpenSSL::BufferRecvComplete,
1562 base::Unretained(this)));
1563 if (rv == ERR_IO_PENDING) {
1564 transport_recv_busy_ = true;
1565 } else {
[email protected]3e5c6922014-02-06 02:42:161566 rv = TransportReadComplete(rv);
[email protected]b9b651f2013-11-09 04:32:221567 }
1568 return rv;
1569}
1570
1571void SSLClientSocketOpenSSL::BufferSendComplete(int result) {
1572 transport_send_busy_ = false;
1573 TransportWriteComplete(result);
1574 OnSendComplete(result);
1575}
1576
1577void SSLClientSocketOpenSSL::BufferRecvComplete(int result) {
[email protected]3e5c6922014-02-06 02:42:161578 result = TransportReadComplete(result);
[email protected]b9b651f2013-11-09 04:32:221579 OnRecvComplete(result);
1580}
1581
1582void SSLClientSocketOpenSSL::TransportWriteComplete(int result) {
1583 DCHECK(ERR_IO_PENDING != result);
1584 if (result < 0) {
[email protected]5aea79182014-07-14 20:43:411585 // Record the error. Save it to be reported in a future read or write on
1586 // transport_bio_'s peer.
[email protected]3e5c6922014-02-06 02:42:161587 transport_write_error_ = result;
[email protected]b9b651f2013-11-09 04:32:221588 send_buffer_ = NULL;
1589 } else {
1590 DCHECK(send_buffer_.get());
1591 send_buffer_->DidConsume(result);
1592 DCHECK_GE(send_buffer_->BytesRemaining(), 0);
1593 if (send_buffer_->BytesRemaining() <= 0)
1594 send_buffer_ = NULL;
1595 }
1596}
1597
[email protected]3e5c6922014-02-06 02:42:161598int SSLClientSocketOpenSSL::TransportReadComplete(int result) {
[email protected]b9b651f2013-11-09 04:32:221599 DCHECK(ERR_IO_PENDING != result);
[email protected]5aea79182014-07-14 20:43:411600 // If an EOF, canonicalize to ERR_CONNECTION_CLOSED here so MapOpenSSLError
1601 // does not report success.
1602 if (result == 0)
1603 result = ERR_CONNECTION_CLOSED;
1604 if (result < 0) {
[email protected]b9b651f2013-11-09 04:32:221605 DVLOG(1) << "TransportReadComplete result " << result;
[email protected]5aea79182014-07-14 20:43:411606 // Received an error. Save it to be reported in a future read on
1607 // transport_bio_'s peer.
1608 transport_read_error_ = result;
[email protected]b9b651f2013-11-09 04:32:221609 } else {
1610 DCHECK(recv_buffer_.get());
1611 int ret = BIO_write(transport_bio_, recv_buffer_->data(), result);
1612 // A write into a memory BIO should always succeed.
[email protected]c8a80e92014-05-17 16:02:081613 DCHECK_EQ(result, ret);
[email protected]b9b651f2013-11-09 04:32:221614 }
1615 recv_buffer_ = NULL;
1616 transport_recv_busy_ = false;
[email protected]3e5c6922014-02-06 02:42:161617 return result;
[email protected]b9b651f2013-11-09 04:32:221618}
1619
[email protected]82c59022014-08-15 09:38:271620int SSLClientSocketOpenSSL::ClientCertRequestCallback(SSL* ssl) {
vadimtb2a77c762014-11-21 19:49:221621 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1622 tracked_objects::ScopedTracker tracking_profile(
1623 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1624 "424386 SSLClientSocketOpenSSL::ClientCertRequestCallback"));
1625
[email protected]5ac981e182010-12-06 17:56:271626 DVLOG(3) << "OpenSSL ClientCertRequestCallback called";
1627 DCHECK(ssl == ssl_);
[email protected]82c59022014-08-15 09:38:271628
davidbenaf42cbe2014-11-13 03:27:461629 net_log_.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED);
1630
[email protected]82c59022014-08-15 09:38:271631 // Clear any currently configured certificates.
1632 SSL_certs_clear(ssl_);
[email protected]97a854f2014-07-29 07:51:361633
1634#if defined(OS_IOS)
1635 // TODO(droger): Support client auth on iOS. See http://crbug.com/145954).
1636 LOG(WARNING) << "Client auth is not supported";
1637#else // !defined(OS_IOS)
[email protected]5ac981e182010-12-06 17:56:271638 if (!ssl_config_.send_client_cert) {
[email protected]515adc22013-01-09 16:01:231639 // First pass: we know that a client certificate is needed, but we do not
1640 // have one at hand.
[email protected]5ac981e182010-12-06 17:56:271641 client_auth_cert_needed_ = true;
[email protected]515adc22013-01-09 16:01:231642 STACK_OF(X509_NAME) *authorities = SSL_get_client_CA_list(ssl);
[email protected]edfd0f42014-07-22 18:20:371643 for (size_t i = 0; i < sk_X509_NAME_num(authorities); i++) {
[email protected]515adc22013-01-09 16:01:231644 X509_NAME *ca_name = (X509_NAME *)sk_X509_NAME_value(authorities, i);
1645 unsigned char* str = NULL;
1646 int length = i2d_X509_NAME(ca_name, &str);
1647 cert_authorities_.push_back(std::string(
1648 reinterpret_cast<const char*>(str),
1649 static_cast<size_t>(length)));
1650 OPENSSL_free(str);
1651 }
1652
[email protected]c0787702014-05-20 21:51:441653 const unsigned char* client_cert_types;
[email protected]e7e883e2014-07-25 06:03:081654 size_t num_client_cert_types =
1655 SSL_get0_certificate_types(ssl, &client_cert_types);
[email protected]c0787702014-05-20 21:51:441656 for (size_t i = 0; i < num_client_cert_types; i++) {
1657 cert_key_types_.push_back(
1658 static_cast<SSLClientCertType>(client_cert_types[i]));
1659 }
1660
[email protected]5ac981e182010-12-06 17:56:271661 return -1; // Suspends handshake.
1662 }
1663
1664 // Second pass: a client certificate should have been selected.
[email protected]13914c92013-06-13 22:42:421665 if (ssl_config_.client_cert.get()) {
[email protected]6bad5052014-07-12 01:25:131666 ScopedX509 leaf_x509 =
1667 OSCertHandleToOpenSSL(ssl_config_.client_cert->os_cert_handle());
1668 if (!leaf_x509) {
1669 LOG(WARNING) << "Failed to import certificate";
1670 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT);
1671 return -1;
1672 }
1673
[email protected]82c59022014-08-15 09:38:271674 ScopedX509Stack chain = OSCertHandlesToOpenSSL(
1675 ssl_config_.client_cert->GetIntermediateCertificates());
1676 if (!chain) {
1677 LOG(WARNING) << "Failed to import intermediate certificates";
1678 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT);
1679 return -1;
1680 }
1681
[email protected]97a854f2014-07-29 07:51:361682 // TODO(davidben): With Linux client auth support, this should be
1683 // conditioned on OS_ANDROID and then, with https://crbug.com/394131,
1684 // removed altogether. OpenSSLClientKeyStore is mostly an artifact of the
1685 // net/ client auth API lacking a private key handle.
[email protected]c0787702014-05-20 21:51:441686#if defined(USE_OPENSSL_CERTS)
[email protected]97a854f2014-07-29 07:51:361687 crypto::ScopedEVP_PKEY privkey =
1688 OpenSSLClientKeyStore::GetInstance()->FetchClientCertPrivateKey(
1689 ssl_config_.client_cert.get());
1690#else // !defined(USE_OPENSSL_CERTS)
1691 crypto::ScopedEVP_PKEY privkey =
1692 FetchClientCertPrivateKey(ssl_config_.client_cert.get());
1693#endif // defined(USE_OPENSSL_CERTS)
1694 if (!privkey) {
[email protected]6bad5052014-07-12 01:25:131695 // Could not find the private key. Fail the handshake and surface an
1696 // appropriate error to the caller.
1697 LOG(WARNING) << "Client cert found without private key";
1698 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY);
1699 return -1;
[email protected]0c6523f2010-12-10 10:56:241700 }
[email protected]6bad5052014-07-12 01:25:131701
[email protected]82c59022014-08-15 09:38:271702 if (!SSL_use_certificate(ssl_, leaf_x509.get()) ||
1703 !SSL_use_PrivateKey(ssl_, privkey.get()) ||
1704 !SSL_set1_chain(ssl_, chain.get())) {
1705 LOG(WARNING) << "Failed to set client certificate";
1706 return -1;
1707 }
davidbenaf42cbe2014-11-13 03:27:461708
1709 int cert_count = 1 + sk_X509_num(chain.get());
1710 net_log_.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED,
1711 NetLog::IntegerCallback("cert_count", cert_count));
[email protected]6bad5052014-07-12 01:25:131712 return 1;
[email protected]c0787702014-05-20 21:51:441713 }
[email protected]97a854f2014-07-29 07:51:361714#endif // defined(OS_IOS)
[email protected]5ac981e182010-12-06 17:56:271715
1716 // Send no client certificate.
davidbenaf42cbe2014-11-13 03:27:461717 net_log_.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED,
1718 NetLog::IntegerCallback("cert_count", 0));
[email protected]82c59022014-08-15 09:38:271719 return 1;
[email protected]5ac981e182010-12-06 17:56:271720}
1721
[email protected]b051cdb62014-02-28 02:20:161722int SSLClientSocketOpenSSL::CertVerifyCallback(X509_STORE_CTX* store_ctx) {
vadimtb2a77c762014-11-21 19:49:221723 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1724 tracked_objects::ScopedTracker tracking_profile(
1725 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1726 "424386 SSLClientSocketOpenSSL::CertVerifyCallback"));
1727
[email protected]64b5c892014-08-08 09:39:261728 if (!completed_connect_) {
[email protected]b051cdb62014-02-28 02:20:161729 // If the first handshake hasn't completed then we accept any certificates
1730 // because we verify after the handshake.
1731 return 1;
1732 }
1733
davidben30798ed82014-09-19 19:28:201734 // Disallow the server certificate to change in a renegotiation.
1735 if (server_cert_chain_->empty()) {
[email protected]76e85392014-03-20 17:54:141736 LOG(ERROR) << "Received invalid certificate chain between handshakes";
davidben30798ed82014-09-19 19:28:201737 return 0;
1738 }
1739 base::StringPiece old_der, new_der;
1740 if (store_ctx->cert == NULL ||
1741 !x509_util::GetDER(server_cert_chain_->Get(0), &old_der) ||
1742 !x509_util::GetDER(store_ctx->cert, &new_der)) {
1743 LOG(ERROR) << "Failed to encode certificates";
1744 return 0;
1745 }
1746 if (old_der != new_der) {
[email protected]76e85392014-03-20 17:54:141747 LOG(ERROR) << "Server certificate changed between handshakes";
davidben30798ed82014-09-19 19:28:201748 return 0;
1749 }
1750
1751 return 1;
[email protected]b051cdb62014-02-28 02:20:161752}
1753
[email protected]ae7c9f42011-11-21 11:41:161754// SelectNextProtoCallback is called by OpenSSL during the handshake. If the
1755// server supports NPN, selects a protocol from the list that the server
1756// provides. According to third_party/openssl/openssl/ssl/ssl_lib.c, the
1757// callback can assume that |in| is syntactically valid.
[email protected]ea4a1c6a2010-12-09 13:33:281758int SSLClientSocketOpenSSL::SelectNextProtoCallback(unsigned char** out,
1759 unsigned char* outlen,
1760 const unsigned char* in,
1761 unsigned int inlen) {
vadimtb2a77c762014-11-21 19:49:221762 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1763 tracked_objects::ScopedTracker tracking_profile(
1764 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1765 "424386 SSLClientSocketOpenSSL::SelectNextProtoCallback"));
1766
[email protected]ea4a1c6a2010-12-09 13:33:281767 if (ssl_config_.next_protos.empty()) {
[email protected]168a8412012-06-14 05:05:491768 *out = reinterpret_cast<uint8*>(
1769 const_cast<char*>(kDefaultSupportedNPNProtocol));
1770 *outlen = arraysize(kDefaultSupportedNPNProtocol) - 1;
1771 npn_status_ = kNextProtoUnsupported;
[email protected]ea4a1c6a2010-12-09 13:33:281772 return SSL_TLSEXT_ERR_OK;
1773 }
1774
[email protected]ae7c9f42011-11-21 11:41:161775 // Assume there's no overlap between our protocols and the server's list.
[email protected]168a8412012-06-14 05:05:491776 npn_status_ = kNextProtoNoOverlap;
[email protected]ae7c9f42011-11-21 11:41:161777
1778 // For each protocol in server preference order, see if we support it.
1779 for (unsigned int i = 0; i < inlen; i += in[i] + 1) {
1780 for (std::vector<std::string>::const_iterator
1781 j = ssl_config_.next_protos.begin();
1782 j != ssl_config_.next_protos.end(); ++j) {
1783 if (in[i] == j->size() &&
1784 memcmp(&in[i + 1], j->data(), in[i]) == 0) {
[email protected]168a8412012-06-14 05:05:491785 // We found a match.
[email protected]ae7c9f42011-11-21 11:41:161786 *out = const_cast<unsigned char*>(in) + i + 1;
1787 *outlen = in[i];
[email protected]168a8412012-06-14 05:05:491788 npn_status_ = kNextProtoNegotiated;
[email protected]ae7c9f42011-11-21 11:41:161789 break;
1790 }
1791 }
[email protected]168a8412012-06-14 05:05:491792 if (npn_status_ == kNextProtoNegotiated)
[email protected]ae7c9f42011-11-21 11:41:161793 break;
1794 }
[email protected]ea4a1c6a2010-12-09 13:33:281795
[email protected]168a8412012-06-14 05:05:491796 // If we didn't find a protocol, we select the first one from our list.
1797 if (npn_status_ == kNextProtoNoOverlap) {
1798 *out = reinterpret_cast<uint8*>(const_cast<char*>(
1799 ssl_config_.next_protos[0].data()));
1800 *outlen = ssl_config_.next_protos[0].size();
1801 }
1802
[email protected]ea4a1c6a2010-12-09 13:33:281803 npn_proto_.assign(reinterpret_cast<const char*>(*out), *outlen);
[email protected]32e1dee2010-12-09 18:36:241804 DVLOG(2) << "next protocol: '" << npn_proto_ << "' status: " << npn_status_;
bnc0d28ea52014-10-13 15:15:381805 set_negotiation_extension(kExtensionNPN);
[email protected]ea4a1c6a2010-12-09 13:33:281806 return SSL_TLSEXT_ERR_OK;
1807}
1808
[email protected]5aea79182014-07-14 20:43:411809long SSLClientSocketOpenSSL::MaybeReplayTransportError(
1810 BIO *bio,
1811 int cmd,
1812 const char *argp, int argi, long argl,
1813 long retvalue) {
1814 if (cmd == (BIO_CB_READ|BIO_CB_RETURN) && retvalue <= 0) {
1815 // If there is no more data in the buffer, report any pending errors that
1816 // were observed. Note that both the readbuf and the writebuf are checked
1817 // for errors, since the application may have encountered a socket error
1818 // while writing that would otherwise not be reported until the application
1819 // attempted to write again - which it may never do. See
1820 // https://crbug.com/249848.
1821 if (transport_read_error_ != OK) {
1822 OpenSSLPutNetError(FROM_HERE, transport_read_error_);
1823 return -1;
1824 }
1825 if (transport_write_error_ != OK) {
1826 OpenSSLPutNetError(FROM_HERE, transport_write_error_);
1827 return -1;
1828 }
1829 } else if (cmd == BIO_CB_WRITE) {
1830 // Because of the write buffer, this reports a failure from the previous
1831 // write payload. If the current payload fails to write, the error will be
1832 // reported in a future write or read to |bio|.
1833 if (transport_write_error_ != OK) {
1834 OpenSSLPutNetError(FROM_HERE, transport_write_error_);
1835 return -1;
1836 }
1837 }
1838 return retvalue;
1839}
1840
1841// static
1842long SSLClientSocketOpenSSL::BIOCallback(
1843 BIO *bio,
1844 int cmd,
1845 const char *argp, int argi, long argl,
1846 long retvalue) {
1847 SSLClientSocketOpenSSL* socket = reinterpret_cast<SSLClientSocketOpenSSL*>(
1848 BIO_get_callback_arg(bio));
1849 CHECK(socket);
1850 return socket->MaybeReplayTransportError(
1851 bio, cmd, argp, argi, argl, retvalue);
1852}
1853
[email protected]64b5c892014-08-08 09:39:261854// static
1855void SSLClientSocketOpenSSL::InfoCallback(const SSL* ssl,
1856 int type,
1857 int /*val*/) {
1858 if (type == SSL_CB_HANDSHAKE_DONE) {
1859 SSLClientSocketOpenSSL* ssl_socket =
1860 SSLContext::GetInstance()->GetClientSocketFromSSL(ssl);
1861 ssl_socket->handshake_succeeded_ = true;
1862 ssl_socket->CheckIfHandshakeFinished();
1863 }
1864}
1865
1866// Determines if both the handshake and certificate verification have completed
1867// successfully, and calls the handshake completion callback if that is the
1868// case.
1869//
1870// CheckIfHandshakeFinished is called twice per connection: once after
1871// MarkSSLSessionAsGood, when the certificate has been verified, and
1872// once via an OpenSSL callback when the handshake has completed. On the
1873// second call, when the certificate has been verified and the handshake
1874// has completed, the connection's handshake completion callback is run.
1875void SSLClientSocketOpenSSL::CheckIfHandshakeFinished() {
1876 if (handshake_succeeded_ && marked_session_as_good_)
1877 OnHandshakeCompletion();
1878}
1879
davidbeneb5f8ef32014-09-04 14:14:321880void SSLClientSocketOpenSSL::AddSCTInfoToSSLInfo(SSLInfo* ssl_info) const {
1881 for (ct::SCTList::const_iterator iter =
1882 ct_verify_result_.verified_scts.begin();
1883 iter != ct_verify_result_.verified_scts.end(); ++iter) {
1884 ssl_info->signed_certificate_timestamps.push_back(
1885 SignedCertificateTimestampAndStatus(*iter, ct::SCT_STATUS_OK));
1886 }
1887 for (ct::SCTList::const_iterator iter =
1888 ct_verify_result_.invalid_scts.begin();
1889 iter != ct_verify_result_.invalid_scts.end(); ++iter) {
1890 ssl_info->signed_certificate_timestamps.push_back(
1891 SignedCertificateTimestampAndStatus(*iter, ct::SCT_STATUS_INVALID));
1892 }
1893 for (ct::SCTList::const_iterator iter =
1894 ct_verify_result_.unknown_logs_scts.begin();
1895 iter != ct_verify_result_.unknown_logs_scts.end(); ++iter) {
1896 ssl_info->signed_certificate_timestamps.push_back(
1897 SignedCertificateTimestampAndStatus(*iter,
1898 ct::SCT_STATUS_LOG_UNKNOWN));
1899 }
1900}
1901
[email protected]7f38da8a2014-03-17 16:44:261902scoped_refptr<X509Certificate>
1903SSLClientSocketOpenSSL::GetUnverifiedServerCertificateChain() const {
1904 return server_cert_;
1905}
1906
[email protected]7e5dd49f2010-12-08 18:33:491907} // namespace net