blob: 0c480c9d42b36e097a72b0fdd1a6697a76cfc505 [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]d518cd92010-09-29 12:27:4410#include <openssl/err.h>
[email protected]89038152012-09-07 06:30:1711#include <openssl/opensslv.h>
[email protected]536fd0b2013-03-14 17:41:5712#include <openssl/ssl.h>
[email protected]d518cd92010-09-29 12:27:4413
[email protected]0f7804ec2011-10-07 20:04:1814#include "base/bind.h"
[email protected]f2da6ac2013-02-04 08:22:5315#include "base/callback_helpers.h"
[email protected]3b63f8f42011-03-28 01:54:1516#include "base/memory/singleton.h"
[email protected]835d7c82010-10-14 04:38:3817#include "base/metrics/histogram.h"
[email protected]20305ec2011-01-21 04:55:5218#include "base/synchronization/lock.h"
[email protected]ee0f2aa82013-10-25 11:59:2619#include "crypto/ec_private_key.h"
[email protected]4b559b4d2011-04-14 17:37:1420#include "crypto/openssl_util.h"
[email protected]cd9b75b2014-07-10 04:39:3821#include "crypto/scoped_openssl_types.h"
[email protected]d518cd92010-09-29 12:27:4422#include "net/base/net_errors.h"
[email protected]6e7845ae2013-03-29 21:48:1123#include "net/cert/cert_verifier.h"
24#include "net/cert/single_request_cert_verifier.h"
25#include "net/cert/x509_certificate_net_log_param.h"
[email protected]c8a80e92014-05-17 16:02:0826#include "net/socket/openssl_ssl_util.h"
[email protected]109805a2010-12-07 18:17:0627#include "net/socket/ssl_error_params.h"
[email protected]1279de12013-12-03 15:13:3228#include "net/socket/ssl_session_cache_openssl.h"
[email protected]5cf67592013-04-02 17:42:1229#include "net/ssl/openssl_client_key_store.h"
[email protected]536fd0b2013-03-14 17:41:5730#include "net/ssl/ssl_cert_request_info.h"
31#include "net/ssl/ssl_connection_status_flags.h"
32#include "net/ssl/ssl_info.h"
[email protected]d518cd92010-09-29 12:27:4433
34namespace net {
35
36namespace {
37
38// Enable this to see logging for state machine state transitions.
39#if 0
[email protected]3b112772010-10-04 10:54:4940#define GotoState(s) do { DVLOG(2) << (void *)this << " " << __FUNCTION__ << \
[email protected]d518cd92010-09-29 12:27:4441 " jump to state " << s; \
42 next_handshake_state_ = s; } while (0)
43#else
44#define GotoState(s) next_handshake_state_ = s
45#endif
46
[email protected]4b768562013-02-16 04:10:0747// This constant can be any non-negative/non-zero value (eg: it does not
48// overlap with any value of the net::Error range, including net::OK).
49const int kNoPendingReadResult = 1;
50
[email protected]168a8412012-06-14 05:05:4951// If a client doesn't have a list of protocols that it supports, but
52// the server supports NPN, choosing "http/1.1" is the best answer.
53const char kDefaultSupportedNPNProtocol[] = "http/1.1";
54
[email protected]6bad5052014-07-12 01:25:1355typedef crypto::ScopedOpenSSL<X509, X509_free>::Type ScopedX509;
56
[email protected]89038152012-09-07 06:30:1757#if OPENSSL_VERSION_NUMBER < 0x1000103fL
58// This method doesn't seem to have made it into the OpenSSL headers.
[email protected]109805a2010-12-07 18:17:0659unsigned long SSL_CIPHER_get_id(const SSL_CIPHER* cipher) { return cipher->id; }
[email protected]89038152012-09-07 06:30:1760#endif
[email protected]109805a2010-12-07 18:17:0661
62// Used for encoding the |connection_status| field of an SSLInfo object.
63int EncodeSSLConnectionStatus(int cipher_suite,
64 int compression,
65 int version) {
66 return ((cipher_suite & SSL_CONNECTION_CIPHERSUITE_MASK) <<
67 SSL_CONNECTION_CIPHERSUITE_SHIFT) |
68 ((compression & SSL_CONNECTION_COMPRESSION_MASK) <<
69 SSL_CONNECTION_COMPRESSION_SHIFT) |
70 ((version & SSL_CONNECTION_VERSION_MASK) <<
71 SSL_CONNECTION_VERSION_SHIFT);
72}
73
74// Returns the net SSL version number (see ssl_connection_status_flags.h) for
75// this SSL connection.
76int GetNetSSLVersion(SSL* ssl) {
[email protected]7e5dd49f2010-12-08 18:33:4977 switch (SSL_version(ssl)) {
[email protected]109805a2010-12-07 18:17:0678 case SSL2_VERSION:
79 return SSL_CONNECTION_VERSION_SSL2;
80 case SSL3_VERSION:
81 return SSL_CONNECTION_VERSION_SSL3;
82 case TLS1_VERSION:
83 return SSL_CONNECTION_VERSION_TLS1;
84 case 0x0302:
85 return SSL_CONNECTION_VERSION_TLS1_1;
86 case 0x0303:
87 return SSL_CONNECTION_VERSION_TLS1_2;
88 default:
89 return SSL_CONNECTION_VERSION_UNKNOWN;
90 }
91}
92
[email protected]1279de12013-12-03 15:13:3293// Compute a unique key string for the SSL session cache. |socket| is an
94// input socket object. Return a string.
95std::string GetSocketSessionCacheKey(const SSLClientSocketOpenSSL& socket) {
96 std::string result = socket.host_and_port().ToString();
97 result.append("/");
98 result.append(socket.ssl_session_cache_shard());
99 return result;
100}
101
[email protected]6bad5052014-07-12 01:25:13102void FreeX509Stack(STACK_OF(X509) * ptr) {
[email protected]cd9b75b2014-07-10 04:39:38103 sk_X509_pop_free(ptr, X509_free);
104}
105
[email protected]6bad5052014-07-12 01:25:13106ScopedX509 OSCertHandleToOpenSSL(
107 X509Certificate::OSCertHandle os_handle) {
108#if defined(USE_OPENSSL_CERTS)
109 return ScopedX509(X509Certificate::DupOSCertHandle(os_handle));
110#else // !defined(USE_OPENSSL_CERTS)
111 std::string der_encoded;
112 if (!X509Certificate::GetDEREncoded(os_handle, &der_encoded))
113 return ScopedX509();
114 const uint8_t* bytes = reinterpret_cast<const uint8_t*>(der_encoded.data());
115 return ScopedX509(d2i_X509(NULL, &bytes, der_encoded.size()));
116#endif // defined(USE_OPENSSL_CERTS)
117}
118
[email protected]821e3bb2013-11-08 01:06:01119} // namespace
120
121class SSLClientSocketOpenSSL::SSLContext {
[email protected]fbef13932010-11-23 12:38:53122 public:
[email protected]b29af7d2010-12-14 11:52:47123 static SSLContext* GetInstance() { return Singleton<SSLContext>::get(); }
[email protected]fbef13932010-11-23 12:38:53124 SSL_CTX* ssl_ctx() { return ssl_ctx_.get(); }
[email protected]1279de12013-12-03 15:13:32125 SSLSessionCacheOpenSSL* session_cache() { return &session_cache_; }
[email protected]fbef13932010-11-23 12:38:53126
[email protected]1279de12013-12-03 15:13:32127 SSLClientSocketOpenSSL* GetClientSocketFromSSL(const SSL* ssl) {
[email protected]fbef13932010-11-23 12:38:53128 DCHECK(ssl);
129 SSLClientSocketOpenSSL* socket = static_cast<SSLClientSocketOpenSSL*>(
130 SSL_get_ex_data(ssl, ssl_socket_data_index_));
131 DCHECK(socket);
132 return socket;
133 }
134
135 bool SetClientSocketForSSL(SSL* ssl, SSLClientSocketOpenSSL* socket) {
136 return SSL_set_ex_data(ssl, ssl_socket_data_index_, socket) != 0;
137 }
138
139 private:
140 friend struct DefaultSingletonTraits<SSLContext>;
141
142 SSLContext() {
[email protected]4b559b4d2011-04-14 17:37:14143 crypto::EnsureOpenSSLInit();
[email protected]fbef13932010-11-23 12:38:53144 ssl_socket_data_index_ = SSL_get_ex_new_index(0, 0, 0, 0, 0);
145 DCHECK_NE(ssl_socket_data_index_, -1);
146 ssl_ctx_.reset(SSL_CTX_new(SSLv23_client_method()));
[email protected]1279de12013-12-03 15:13:32147 session_cache_.Reset(ssl_ctx_.get(), kDefaultSessionCacheConfig);
[email protected]b051cdb62014-02-28 02:20:16148 SSL_CTX_set_cert_verify_callback(ssl_ctx_.get(), CertVerifyCallback, NULL);
[email protected]718c9672010-12-02 10:04:10149 SSL_CTX_set_client_cert_cb(ssl_ctx_.get(), ClientCertCallback);
[email protected]b051cdb62014-02-28 02:20:16150 SSL_CTX_set_verify(ssl_ctx_.get(), SSL_VERIFY_PEER, NULL);
[email protected]ea4a1c6a2010-12-09 13:33:28151 // TODO(kristianm): Only select this if ssl_config_.next_proto is not empty.
152 // It would be better if the callback were not a global setting,
153 // but that is an OpenSSL issue.
154 SSL_CTX_set_next_proto_select_cb(ssl_ctx_.get(), SelectNextProtoCallback,
155 NULL);
[email protected]fbef13932010-11-23 12:38:53156 }
157
[email protected]1279de12013-12-03 15:13:32158 static std::string GetSessionCacheKey(const SSL* ssl) {
159 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
160 DCHECK(socket);
161 return GetSocketSessionCacheKey(*socket);
[email protected]fbef13932010-11-23 12:38:53162 }
163
[email protected]1279de12013-12-03 15:13:32164 static SSLSessionCacheOpenSSL::Config kDefaultSessionCacheConfig;
[email protected]fbef13932010-11-23 12:38:53165
[email protected]718c9672010-12-02 10:04:10166 static int ClientCertCallback(SSL* ssl, X509** x509, EVP_PKEY** pkey) {
[email protected]b29af7d2010-12-14 11:52:47167 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
[email protected]718c9672010-12-02 10:04:10168 CHECK(socket);
169 return socket->ClientCertRequestCallback(ssl, x509, pkey);
170 }
171
[email protected]b051cdb62014-02-28 02:20:16172 static int CertVerifyCallback(X509_STORE_CTX *store_ctx, void *arg) {
173 SSL* ssl = reinterpret_cast<SSL*>(X509_STORE_CTX_get_ex_data(
174 store_ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
175 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
176 CHECK(socket);
177
178 return socket->CertVerifyCallback(store_ctx);
179 }
180
[email protected]ea4a1c6a2010-12-09 13:33:28181 static int SelectNextProtoCallback(SSL* ssl,
182 unsigned char** out, unsigned char* outlen,
183 const unsigned char* in,
184 unsigned int inlen, void* arg) {
[email protected]b29af7d2010-12-14 11:52:47185 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
[email protected]ea4a1c6a2010-12-09 13:33:28186 return socket->SelectNextProtoCallback(out, outlen, in, inlen);
187 }
188
[email protected]fbef13932010-11-23 12:38:53189 // This is the index used with SSL_get_ex_data to retrieve the owner
190 // SSLClientSocketOpenSSL object from an SSL instance.
191 int ssl_socket_data_index_;
192
[email protected]cd9b75b2014-07-10 04:39:38193 crypto::ScopedOpenSSL<SSL_CTX, SSL_CTX_free>::Type ssl_ctx_;
[email protected]1279de12013-12-03 15:13:32194 // |session_cache_| must be destroyed before |ssl_ctx_|.
195 SSLSessionCacheOpenSSL session_cache_;
196};
197
[email protected]7f38da8a2014-03-17 16:44:26198// PeerCertificateChain is a helper object which extracts the certificate
199// chain, as given by the server, from an OpenSSL socket and performs the needed
200// resource management. The first element of the chain is the leaf certificate
201// and the other elements are in the order given by the server.
202class SSLClientSocketOpenSSL::PeerCertificateChain {
203 public:
[email protected]76e85392014-03-20 17:54:14204 explicit PeerCertificateChain(STACK_OF(X509)* chain) { Reset(chain); }
[email protected]7f38da8a2014-03-17 16:44:26205 PeerCertificateChain(const PeerCertificateChain& other) { *this = other; }
206 ~PeerCertificateChain() {}
207 PeerCertificateChain& operator=(const PeerCertificateChain& other);
208
[email protected]76e85392014-03-20 17:54:14209 // Resets the PeerCertificateChain to the set of certificates in|chain|,
210 // which may be NULL, indicating to empty the store certificates.
211 // Note: If an error occurs, such as being unable to parse the certificates,
212 // this will behave as if Reset(NULL) was called.
213 void Reset(STACK_OF(X509)* chain);
214
[email protected]7f38da8a2014-03-17 16:44:26215 // Note that when USE_OPENSSL is defined, OSCertHandle is X509*
216 const scoped_refptr<X509Certificate>& AsOSChain() const { return os_chain_; }
217
218 size_t size() const {
219 if (!openssl_chain_.get())
220 return 0;
221 return sk_X509_num(openssl_chain_.get());
222 }
223
224 X509* operator[](size_t index) const {
225 DCHECK_LT(index, size());
226 return sk_X509_value(openssl_chain_.get(), index);
227 }
228
[email protected]76e85392014-03-20 17:54:14229 bool IsValid() { return os_chain_.get() && openssl_chain_.get(); }
230
[email protected]7f38da8a2014-03-17 16:44:26231 private:
[email protected]cd9b75b2014-07-10 04:39:38232 typedef crypto::ScopedOpenSSL<STACK_OF(X509), FreeX509Stack>::Type
233 ScopedX509Stack;
[email protected]7f38da8a2014-03-17 16:44:26234
[email protected]cd9b75b2014-07-10 04:39:38235 ScopedX509Stack openssl_chain_;
[email protected]7f38da8a2014-03-17 16:44:26236
237 scoped_refptr<X509Certificate> os_chain_;
238};
239
240SSLClientSocketOpenSSL::PeerCertificateChain&
241SSLClientSocketOpenSSL::PeerCertificateChain::operator=(
242 const PeerCertificateChain& other) {
243 if (this == &other)
244 return *this;
245
246 // os_chain_ is reference counted by scoped_refptr;
247 os_chain_ = other.os_chain_;
248
249 // Must increase the reference count manually for sk_X509_dup
250 openssl_chain_.reset(sk_X509_dup(other.openssl_chain_.get()));
251 for (int i = 0; i < sk_X509_num(openssl_chain_.get()); ++i) {
252 X509* x = sk_X509_value(openssl_chain_.get(), i);
253 CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509);
254 }
255 return *this;
256}
257
[email protected]e1b2d732014-03-28 16:20:32258#if defined(USE_OPENSSL_CERTS)
[email protected]7f38da8a2014-03-17 16:44:26259// When OSCertHandle is typedef'ed to X509, this implementation does a short cut
260// to avoid converting back and forth between der and X509 struct.
[email protected]76e85392014-03-20 17:54:14261void SSLClientSocketOpenSSL::PeerCertificateChain::Reset(
262 STACK_OF(X509)* chain) {
[email protected]7f38da8a2014-03-17 16:44:26263 openssl_chain_.reset(NULL);
264 os_chain_ = NULL;
265
[email protected]7f38da8a2014-03-17 16:44:26266 if (!chain)
267 return;
268
269 X509Certificate::OSCertHandles intermediates;
270 for (int i = 1; i < sk_X509_num(chain); ++i)
271 intermediates.push_back(sk_X509_value(chain, i));
272
273 os_chain_ =
274 X509Certificate::CreateFromHandle(sk_X509_value(chain, 0), intermediates);
275
276 // sk_X509_dup does not increase reference count on the certs in the stack.
277 openssl_chain_.reset(sk_X509_dup(chain));
278
279 std::vector<base::StringPiece> der_chain;
280 for (int i = 0; i < sk_X509_num(openssl_chain_.get()); ++i) {
281 X509* x = sk_X509_value(openssl_chain_.get(), i);
282 // Increase the reference count for the certs in openssl_chain_.
283 CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509);
284 }
285}
[email protected]e1b2d732014-03-28 16:20:32286#else // !defined(USE_OPENSSL_CERTS)
[email protected]76e85392014-03-20 17:54:14287void SSLClientSocketOpenSSL::PeerCertificateChain::Reset(
288 STACK_OF(X509)* chain) {
[email protected]7f38da8a2014-03-17 16:44:26289 openssl_chain_.reset(NULL);
290 os_chain_ = NULL;
291
[email protected]7f38da8a2014-03-17 16:44:26292 if (!chain)
293 return;
294
295 // sk_X509_dup does not increase reference count on the certs in the stack.
296 openssl_chain_.reset(sk_X509_dup(chain));
297
298 std::vector<base::StringPiece> der_chain;
299 for (int i = 0; i < sk_X509_num(openssl_chain_.get()); ++i) {
300 X509* x = sk_X509_value(openssl_chain_.get(), i);
301
302 // Increase the reference count for the certs in openssl_chain_.
303 CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509);
304
305 unsigned char* cert_data = NULL;
306 int cert_data_length = i2d_X509(x, &cert_data);
307 if (cert_data_length && cert_data)
308 der_chain.push_back(base::StringPiece(reinterpret_cast<char*>(cert_data),
309 cert_data_length));
310 }
311
312 os_chain_ = X509Certificate::CreateFromDERCertChain(der_chain);
313
314 for (size_t i = 0; i < der_chain.size(); ++i) {
315 OPENSSL_free(const_cast<char*>(der_chain[i].data()));
316 }
317
318 if (der_chain.size() !=
319 static_cast<size_t>(sk_X509_num(openssl_chain_.get()))) {
320 openssl_chain_.reset(NULL);
321 os_chain_ = NULL;
322 }
323}
[email protected]e1b2d732014-03-28 16:20:32324#endif // defined(USE_OPENSSL_CERTS)
[email protected]7f38da8a2014-03-17 16:44:26325
[email protected]1279de12013-12-03 15:13:32326// static
327SSLSessionCacheOpenSSL::Config
328 SSLClientSocketOpenSSL::SSLContext::kDefaultSessionCacheConfig = {
329 &GetSessionCacheKey, // key_func
330 1024, // max_entries
331 256, // expiration_check_count
332 60 * 60, // timeout_seconds
[email protected]fbef13932010-11-23 12:38:53333};
[email protected]313834722010-11-17 09:57:18334
[email protected]c3456bb2011-12-12 22:22:19335// static
336void SSLClientSocket::ClearSessionCache() {
[email protected]821e3bb2013-11-08 01:06:01337 SSLClientSocketOpenSSL::SSLContext* context =
338 SSLClientSocketOpenSSL::SSLContext::GetInstance();
[email protected]c3456bb2011-12-12 22:22:19339 context->session_cache()->Flush();
340}
341
[email protected]d518cd92010-09-29 12:27:44342SSLClientSocketOpenSSL::SSLClientSocketOpenSSL(
[email protected]18ccfdb2013-08-15 00:13:44343 scoped_ptr<ClientSocketHandle> transport_socket,
[email protected]055d7f22010-11-15 12:03:12344 const HostPortPair& host_and_port,
[email protected]822581d2010-12-16 17:27:15345 const SSLConfig& ssl_config,
[email protected]feb79bcd2011-07-21 16:55:17346 const SSLClientSocketContext& context)
[email protected]83039bb2011-12-09 18:43:55347 : transport_send_busy_(false),
[email protected]d518cd92010-09-29 12:27:44348 transport_recv_busy_(false),
[email protected]be90ba32013-05-13 20:05:25349 weak_factory_(this),
[email protected]4b768562013-02-16 04:10:07350 pending_read_error_(kNoPendingReadResult),
[email protected]5aea79182014-07-14 20:43:41351 transport_read_error_(OK),
[email protected]3e5c6922014-02-06 02:42:16352 transport_write_error_(OK),
[email protected]7f38da8a2014-03-17 16:44:26353 server_cert_chain_(new PeerCertificateChain(NULL)),
[email protected]fbef13932010-11-23 12:38:53354 completed_handshake_(false),
[email protected]0dc88b32014-03-26 20:12:28355 was_ever_used_(false),
[email protected]d518cd92010-09-29 12:27:44356 client_auth_cert_needed_(false),
[email protected]feb79bcd2011-07-21 16:55:17357 cert_verifier_(context.cert_verifier),
[email protected]ee0f2aa82013-10-25 11:59:26358 server_bound_cert_service_(context.server_bound_cert_service),
[email protected]d518cd92010-09-29 12:27:44359 ssl_(NULL),
360 transport_bio_(NULL),
[email protected]18ccfdb2013-08-15 00:13:44361 transport_(transport_socket.Pass()),
[email protected]055d7f22010-11-15 12:03:12362 host_and_port_(host_and_port),
[email protected]d518cd92010-09-29 12:27:44363 ssl_config_(ssl_config),
[email protected]c3456bb2011-12-12 22:22:19364 ssl_session_cache_shard_(context.ssl_session_cache_shard),
[email protected]fbef13932010-11-23 12:38:53365 trying_cached_session_(false),
[email protected]013c17c2012-01-21 19:09:01366 next_handshake_state_(STATE_NONE),
[email protected]ea4a1c6a2010-12-09 13:33:28367 npn_status_(kNextProtoUnsupported),
[email protected]ee0f2aa82013-10-25 11:59:26368 channel_id_xtn_negotiated_(false),
[email protected]7f38da8a2014-03-17 16:44:26369 net_log_(transport_->socket()->NetLog()) {}
[email protected]d518cd92010-09-29 12:27:44370
371SSLClientSocketOpenSSL::~SSLClientSocketOpenSSL() {
372 Disconnect();
373}
374
[email protected]b9b651f2013-11-09 04:32:22375void SSLClientSocketOpenSSL::GetSSLCertRequestInfo(
376 SSLCertRequestInfo* cert_request_info) {
[email protected]791879c2013-12-17 07:22:41377 cert_request_info->host_and_port = host_and_port_;
[email protected]b9b651f2013-11-09 04:32:22378 cert_request_info->cert_authorities = cert_authorities_;
[email protected]c0787702014-05-20 21:51:44379 cert_request_info->cert_key_types = cert_key_types_;
[email protected]b9b651f2013-11-09 04:32:22380}
381
382SSLClientSocket::NextProtoStatus SSLClientSocketOpenSSL::GetNextProto(
383 std::string* proto, std::string* server_protos) {
384 *proto = npn_proto_;
385 *server_protos = server_protos_;
386 return npn_status_;
387}
388
389ServerBoundCertService*
390SSLClientSocketOpenSSL::GetServerBoundCertService() const {
391 return server_bound_cert_service_;
392}
393
394int SSLClientSocketOpenSSL::ExportKeyingMaterial(
395 const base::StringPiece& label,
396 bool has_context, const base::StringPiece& context,
397 unsigned char* out, unsigned int outlen) {
398 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
399
400 int rv = SSL_export_keying_material(
[email protected]c8a80e92014-05-17 16:02:08401 ssl_, out, outlen, label.data(), label.size(),
402 reinterpret_cast<const unsigned char*>(context.data()),
403 context.length(), context.length() > 0);
[email protected]b9b651f2013-11-09 04:32:22404
405 if (rv != 1) {
406 int ssl_error = SSL_get_error(ssl_, rv);
407 LOG(ERROR) << "Failed to export keying material;"
408 << " returned " << rv
409 << ", SSL error code " << ssl_error;
410 return MapOpenSSLError(ssl_error, err_tracer);
411 }
412 return OK;
413}
414
415int SSLClientSocketOpenSSL::GetTLSUniqueChannelBinding(std::string* out) {
[email protected]c8a80e92014-05-17 16:02:08416 NOTIMPLEMENTED();
[email protected]b9b651f2013-11-09 04:32:22417 return ERR_NOT_IMPLEMENTED;
418}
419
420int SSLClientSocketOpenSSL::Connect(const CompletionCallback& callback) {
421 net_log_.BeginEvent(NetLog::TYPE_SSL_CONNECT);
422
423 // Set up new ssl object.
[email protected]c8a80e92014-05-17 16:02:08424 int rv = Init();
425 if (rv != OK) {
426 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
427 return rv;
[email protected]b9b651f2013-11-09 04:32:22428 }
429
430 // Set SSL to client mode. Handshake happens in the loop below.
431 SSL_set_connect_state(ssl_);
432
433 GotoState(STATE_HANDSHAKE);
[email protected]c8a80e92014-05-17 16:02:08434 rv = DoHandshakeLoop(OK);
[email protected]b9b651f2013-11-09 04:32:22435 if (rv == ERR_IO_PENDING) {
436 user_connect_callback_ = callback;
437 } else {
438 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
439 }
440
441 return rv > OK ? OK : rv;
442}
443
444void SSLClientSocketOpenSSL::Disconnect() {
445 if (ssl_) {
446 // Calling SSL_shutdown prevents the session from being marked as
447 // unresumable.
448 SSL_shutdown(ssl_);
449 SSL_free(ssl_);
450 ssl_ = NULL;
451 }
452 if (transport_bio_) {
453 BIO_free_all(transport_bio_);
454 transport_bio_ = NULL;
455 }
456
457 // Shut down anything that may call us back.
458 verifier_.reset();
459 transport_->socket()->Disconnect();
460
461 // Null all callbacks, delete all buffers.
462 transport_send_busy_ = false;
463 send_buffer_ = NULL;
464 transport_recv_busy_ = false;
[email protected]b9b651f2013-11-09 04:32:22465 recv_buffer_ = NULL;
466
467 user_connect_callback_.Reset();
468 user_read_callback_.Reset();
469 user_write_callback_.Reset();
470 user_read_buf_ = NULL;
471 user_read_buf_len_ = 0;
472 user_write_buf_ = NULL;
473 user_write_buf_len_ = 0;
474
[email protected]3e5c6922014-02-06 02:42:16475 pending_read_error_ = kNoPendingReadResult;
[email protected]5aea79182014-07-14 20:43:41476 transport_read_error_ = OK;
[email protected]3e5c6922014-02-06 02:42:16477 transport_write_error_ = OK;
478
[email protected]b9b651f2013-11-09 04:32:22479 server_cert_verify_result_.Reset();
480 completed_handshake_ = false;
481
482 cert_authorities_.clear();
[email protected]c0787702014-05-20 21:51:44483 cert_key_types_.clear();
[email protected]b9b651f2013-11-09 04:32:22484 client_auth_cert_needed_ = false;
[email protected]faff9852014-06-21 06:13:46485
486 channel_id_xtn_negotiated_ = false;
487 channel_id_request_handle_.Cancel();
[email protected]b9b651f2013-11-09 04:32:22488}
489
490bool SSLClientSocketOpenSSL::IsConnected() const {
491 // If the handshake has not yet completed.
492 if (!completed_handshake_)
493 return false;
494 // If an asynchronous operation is still pending.
495 if (user_read_buf_.get() || user_write_buf_.get())
496 return true;
497
498 return transport_->socket()->IsConnected();
499}
500
501bool SSLClientSocketOpenSSL::IsConnectedAndIdle() const {
502 // If the handshake has not yet completed.
503 if (!completed_handshake_)
504 return false;
505 // If an asynchronous operation is still pending.
506 if (user_read_buf_.get() || user_write_buf_.get())
507 return false;
508 // If there is data waiting to be sent, or data read from the network that
509 // has not yet been consumed.
510 if (BIO_ctrl_pending(transport_bio_) > 0 ||
511 BIO_ctrl_wpending(transport_bio_) > 0) {
512 return false;
513 }
514
515 return transport_->socket()->IsConnectedAndIdle();
516}
517
518int SSLClientSocketOpenSSL::GetPeerAddress(IPEndPoint* addressList) const {
519 return transport_->socket()->GetPeerAddress(addressList);
520}
521
522int SSLClientSocketOpenSSL::GetLocalAddress(IPEndPoint* addressList) const {
523 return transport_->socket()->GetLocalAddress(addressList);
524}
525
526const BoundNetLog& SSLClientSocketOpenSSL::NetLog() const {
527 return net_log_;
528}
529
530void SSLClientSocketOpenSSL::SetSubresourceSpeculation() {
531 if (transport_.get() && transport_->socket()) {
532 transport_->socket()->SetSubresourceSpeculation();
533 } else {
534 NOTREACHED();
535 }
536}
537
538void SSLClientSocketOpenSSL::SetOmniboxSpeculation() {
539 if (transport_.get() && transport_->socket()) {
540 transport_->socket()->SetOmniboxSpeculation();
541 } else {
542 NOTREACHED();
543 }
544}
545
546bool SSLClientSocketOpenSSL::WasEverUsed() const {
[email protected]0dc88b32014-03-26 20:12:28547 return was_ever_used_;
[email protected]b9b651f2013-11-09 04:32:22548}
549
550bool SSLClientSocketOpenSSL::UsingTCPFastOpen() const {
551 if (transport_.get() && transport_->socket())
552 return transport_->socket()->UsingTCPFastOpen();
553
554 NOTREACHED();
555 return false;
556}
557
558bool SSLClientSocketOpenSSL::GetSSLInfo(SSLInfo* ssl_info) {
559 ssl_info->Reset();
560 if (!server_cert_.get())
561 return false;
562
563 ssl_info->cert = server_cert_verify_result_.verified_cert;
564 ssl_info->cert_status = server_cert_verify_result_.cert_status;
565 ssl_info->is_issued_by_known_root =
566 server_cert_verify_result_.is_issued_by_known_root;
567 ssl_info->public_key_hashes =
568 server_cert_verify_result_.public_key_hashes;
569 ssl_info->client_cert_sent =
570 ssl_config_.send_client_cert && ssl_config_.client_cert.get();
571 ssl_info->channel_id_sent = WasChannelIDSent();
572
573 RecordChannelIDSupport(server_bound_cert_service_,
574 channel_id_xtn_negotiated_,
575 ssl_config_.channel_id_enabled,
576 crypto::ECPrivateKey::IsSupported());
577
578 const SSL_CIPHER* cipher = SSL_get_current_cipher(ssl_);
579 CHECK(cipher);
580 ssl_info->security_bits = SSL_CIPHER_get_bits(cipher, NULL);
581 const COMP_METHOD* compression = SSL_get_current_compression(ssl_);
582
583 ssl_info->connection_status = EncodeSSLConnectionStatus(
584 SSL_CIPHER_get_id(cipher),
585 compression ? compression->type : 0,
586 GetNetSSLVersion(ssl_));
587
588 bool peer_supports_renego_ext = !!SSL_get_secure_renegotiation_support(ssl_);
589 if (!peer_supports_renego_ext)
590 ssl_info->connection_status |= SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION;
591 UMA_HISTOGRAM_ENUMERATION("Net.RenegotiationExtensionSupported",
592 implicit_cast<int>(peer_supports_renego_ext), 2);
593
594 if (ssl_config_.version_fallback)
595 ssl_info->connection_status |= SSL_CONNECTION_VERSION_FALLBACK;
596
597 ssl_info->handshake_type = SSL_session_reused(ssl_) ?
598 SSLInfo::HANDSHAKE_RESUME : SSLInfo::HANDSHAKE_FULL;
599
600 DVLOG(3) << "Encoded connection status: cipher suite = "
601 << SSLConnectionStatusToCipherSuite(ssl_info->connection_status)
602 << " version = "
603 << SSLConnectionStatusToVersion(ssl_info->connection_status);
604 return true;
605}
606
607int SSLClientSocketOpenSSL::Read(IOBuffer* buf,
608 int buf_len,
609 const CompletionCallback& callback) {
610 user_read_buf_ = buf;
611 user_read_buf_len_ = buf_len;
612
613 int rv = DoReadLoop(OK);
614
615 if (rv == ERR_IO_PENDING) {
616 user_read_callback_ = callback;
617 } else {
[email protected]0dc88b32014-03-26 20:12:28618 if (rv > 0)
619 was_ever_used_ = true;
[email protected]b9b651f2013-11-09 04:32:22620 user_read_buf_ = NULL;
621 user_read_buf_len_ = 0;
622 }
623
624 return rv;
625}
626
627int SSLClientSocketOpenSSL::Write(IOBuffer* buf,
628 int buf_len,
629 const CompletionCallback& callback) {
630 user_write_buf_ = buf;
631 user_write_buf_len_ = buf_len;
632
633 int rv = DoWriteLoop(OK);
634
635 if (rv == ERR_IO_PENDING) {
636 user_write_callback_ = callback;
637 } else {
[email protected]0dc88b32014-03-26 20:12:28638 if (rv > 0)
639 was_ever_used_ = true;
[email protected]b9b651f2013-11-09 04:32:22640 user_write_buf_ = NULL;
641 user_write_buf_len_ = 0;
642 }
643
644 return rv;
645}
646
[email protected]28b96d1c2014-04-09 12:21:15647int SSLClientSocketOpenSSL::SetReceiveBufferSize(int32 size) {
[email protected]b9b651f2013-11-09 04:32:22648 return transport_->socket()->SetReceiveBufferSize(size);
649}
650
[email protected]28b96d1c2014-04-09 12:21:15651int SSLClientSocketOpenSSL::SetSendBufferSize(int32 size) {
[email protected]b9b651f2013-11-09 04:32:22652 return transport_->socket()->SetSendBufferSize(size);
653}
654
[email protected]c8a80e92014-05-17 16:02:08655int SSLClientSocketOpenSSL::Init() {
[email protected]9e733f32010-10-04 18:19:08656 DCHECK(!ssl_);
657 DCHECK(!transport_bio_);
658
[email protected]b29af7d2010-12-14 11:52:47659 SSLContext* context = SSLContext::GetInstance();
[email protected]4b559b4d2011-04-14 17:37:14660 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
[email protected]d518cd92010-09-29 12:27:44661
[email protected]fbef13932010-11-23 12:38:53662 ssl_ = SSL_new(context->ssl_ctx());
663 if (!ssl_ || !context->SetClientSocketForSSL(ssl_, this))
[email protected]c8a80e92014-05-17 16:02:08664 return ERR_UNEXPECTED;
[email protected]fbef13932010-11-23 12:38:53665
666 if (!SSL_set_tlsext_host_name(ssl_, host_and_port_.host().c_str()))
[email protected]c8a80e92014-05-17 16:02:08667 return ERR_UNEXPECTED;
[email protected]fbef13932010-11-23 12:38:53668
[email protected]1279de12013-12-03 15:13:32669 trying_cached_session_ = context->session_cache()->SetSSLSessionWithKey(
670 ssl_, GetSocketSessionCacheKey(*this));
[email protected]d518cd92010-09-29 12:27:44671
672 BIO* ssl_bio = NULL;
[email protected]fbef13932010-11-23 12:38:53673 // 0 => use default buffer sizes.
674 if (!BIO_new_bio_pair(&ssl_bio, 0, &transport_bio_, 0))
[email protected]c8a80e92014-05-17 16:02:08675 return ERR_UNEXPECTED;
[email protected]d518cd92010-09-29 12:27:44676 DCHECK(ssl_bio);
677 DCHECK(transport_bio_);
678
[email protected]5aea79182014-07-14 20:43:41679 // Install a callback on OpenSSL's end to plumb transport errors through.
680 BIO_set_callback(ssl_bio, &SSLClientSocketOpenSSL::BIOCallback);
681 BIO_set_callback_arg(ssl_bio, reinterpret_cast<char*>(this));
682
[email protected]d518cd92010-09-29 12:27:44683 SSL_set_bio(ssl_, ssl_bio, ssl_bio);
684
[email protected]9e733f32010-10-04 18:19:08685 // OpenSSL defaults some options to on, others to off. To avoid ambiguity,
686 // set everything we care about to an absolute value.
[email protected]fb10e2282010-12-01 17:08:48687 SslSetClearMask options;
688 options.ConfigureFlag(SSL_OP_NO_SSLv2, true);
[email protected]80c75f682012-05-26 16:22:17689 bool ssl3_enabled = (ssl_config_.version_min == SSL_PROTOCOL_VERSION_SSL3);
690 options.ConfigureFlag(SSL_OP_NO_SSLv3, !ssl3_enabled);
691 bool tls1_enabled = (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1 &&
692 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1);
693 options.ConfigureFlag(SSL_OP_NO_TLSv1, !tls1_enabled);
[email protected]80c75f682012-05-26 16:22:17694 bool tls1_1_enabled =
695 (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1_1 &&
696 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1_1);
697 options.ConfigureFlag(SSL_OP_NO_TLSv1_1, !tls1_1_enabled);
[email protected]80c75f682012-05-26 16:22:17698 bool tls1_2_enabled =
699 (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1_2 &&
700 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1_2);
701 options.ConfigureFlag(SSL_OP_NO_TLSv1_2, !tls1_2_enabled);
[email protected]fb10e2282010-12-01 17:08:48702
[email protected]d0f00492012-08-03 22:35:13703 options.ConfigureFlag(SSL_OP_NO_COMPRESSION, true);
[email protected]9e733f32010-10-04 18:19:08704
705 // TODO(joth): Set this conditionally, see http://crbug.com/55410
[email protected]fb10e2282010-12-01 17:08:48706 options.ConfigureFlag(SSL_OP_LEGACY_SERVER_CONNECT, true);
[email protected]9e733f32010-10-04 18:19:08707
[email protected]fb10e2282010-12-01 17:08:48708 SSL_set_options(ssl_, options.set_mask);
709 SSL_clear_options(ssl_, options.clear_mask);
[email protected]9e733f32010-10-04 18:19:08710
[email protected]fb10e2282010-12-01 17:08:48711 // Same as above, this time for the SSL mode.
712 SslSetClearMask mode;
[email protected]9e733f32010-10-04 18:19:08713
[email protected]fb10e2282010-12-01 17:08:48714 mode.ConfigureFlag(SSL_MODE_RELEASE_BUFFERS, true);
[email protected]fb10e2282010-12-01 17:08:48715
[email protected]b788de02014-04-23 18:06:07716 mode.ConfigureFlag(SSL_MODE_HANDSHAKE_CUTTHROUGH,
717 ssl_config_.false_start_enabled);
718
[email protected]fb10e2282010-12-01 17:08:48719 SSL_set_mode(ssl_, mode.set_mask);
720 SSL_clear_mode(ssl_, mode.clear_mask);
[email protected]109805a2010-12-07 18:17:06721
722 // Removing ciphers by ID from OpenSSL is a bit involved as we must use the
723 // textual name with SSL_set_cipher_list because there is no public API to
724 // directly remove a cipher by ID.
725 STACK_OF(SSL_CIPHER)* ciphers = SSL_get_ciphers(ssl_);
726 DCHECK(ciphers);
727 // See SSLConfig::disabled_cipher_suites for description of the suites
[email protected]9b4bc4a92013-08-20 22:59:07728 // disabled by default. Note that !SHA256 and !SHA384 only remove HMAC-SHA256
729 // and HMAC-SHA384 cipher suites, not GCM cipher suites with SHA256 or SHA384
730 // as the handshake hash.
731 std::string command("DEFAULT:!NULL:!aNULL:!IDEA:!FZA:!SRP:!SHA256:!SHA384:"
732 "!aECDH:!AESGCM+AES256");
[email protected]109805a2010-12-07 18:17:06733 // Walk through all the installed ciphers, seeing if any need to be
734 // appended to the cipher removal |command|.
735 for (int i = 0; i < sk_SSL_CIPHER_num(ciphers); ++i) {
736 const SSL_CIPHER* cipher = sk_SSL_CIPHER_value(ciphers, i);
737 const uint16 id = SSL_CIPHER_get_id(cipher);
738 // Remove any ciphers with a strength of less than 80 bits. Note the NSS
739 // implementation uses "effective" bits here but OpenSSL does not provide
740 // this detail. This only impacts Triple DES: reports 112 vs. 168 bits,
741 // both of which are greater than 80 anyway.
742 bool disable = SSL_CIPHER_get_bits(cipher, NULL) < 80;
743 if (!disable) {
744 disable = std::find(ssl_config_.disabled_cipher_suites.begin(),
745 ssl_config_.disabled_cipher_suites.end(), id) !=
746 ssl_config_.disabled_cipher_suites.end();
747 }
748 if (disable) {
749 const char* name = SSL_CIPHER_get_name(cipher);
750 DVLOG(3) << "Found cipher to remove: '" << name << "', ID: " << id
751 << " strength: " << SSL_CIPHER_get_bits(cipher, NULL);
752 command.append(":!");
753 command.append(name);
754 }
755 }
756 int rv = SSL_set_cipher_list(ssl_, command.c_str());
757 // If this fails (rv = 0) it means there are no ciphers enabled on this SSL.
758 // This will almost certainly result in the socket failing to complete the
759 // handshake at which point the appropriate error is bubbled up to the client.
760 LOG_IF(WARNING, rv != 1) << "SSL_set_cipher_list('" << command << "') "
761 "returned " << rv;
[email protected]ee0f2aa82013-10-25 11:59:26762
763 // TLS channel ids.
764 if (IsChannelIDEnabled(ssl_config_, server_bound_cert_service_)) {
765 SSL_enable_tls_channel_id(ssl_);
766 }
767
[email protected]c8a80e92014-05-17 16:02:08768 return OK;
[email protected]d518cd92010-09-29 12:27:44769}
770
[email protected]b9b651f2013-11-09 04:32:22771void SSLClientSocketOpenSSL::DoReadCallback(int rv) {
772 // Since Run may result in Read being called, clear |user_read_callback_|
773 // up front.
[email protected]0dc88b32014-03-26 20:12:28774 if (rv > 0)
775 was_ever_used_ = true;
[email protected]b9b651f2013-11-09 04:32:22776 user_read_buf_ = NULL;
777 user_read_buf_len_ = 0;
778 base::ResetAndReturn(&user_read_callback_).Run(rv);
779}
780
781void SSLClientSocketOpenSSL::DoWriteCallback(int rv) {
782 // Since Run may result in Write being called, clear |user_write_callback_|
783 // up front.
[email protected]0dc88b32014-03-26 20:12:28784 if (rv > 0)
785 was_ever_used_ = true;
[email protected]b9b651f2013-11-09 04:32:22786 user_write_buf_ = NULL;
787 user_write_buf_len_ = 0;
788 base::ResetAndReturn(&user_write_callback_).Run(rv);
789}
790
791bool SSLClientSocketOpenSSL::DoTransportIO() {
792 bool network_moved = false;
793 int rv;
794 // Read and write as much data as possible. The loop is necessary because
795 // Write() may return synchronously.
796 do {
797 rv = BufferSend();
798 if (rv != ERR_IO_PENDING && rv != 0)
799 network_moved = true;
800 } while (rv > 0);
[email protected]5aea79182014-07-14 20:43:41801 if (transport_read_error_ == OK && BufferRecv() != ERR_IO_PENDING)
[email protected]b9b651f2013-11-09 04:32:22802 network_moved = true;
803 return network_moved;
804}
805
806int SSLClientSocketOpenSSL::DoHandshake() {
807 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
[email protected]c8a80e92014-05-17 16:02:08808 int net_error = OK;
[email protected]b9b651f2013-11-09 04:32:22809 int rv = SSL_do_handshake(ssl_);
810
811 if (client_auth_cert_needed_) {
812 net_error = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
813 // If the handshake already succeeded (because the server requests but
814 // doesn't require a client cert), we need to invalidate the SSL session
815 // so that we won't try to resume the non-client-authenticated session in
816 // the next handshake. This will cause the server to ask for a client
817 // cert again.
818 if (rv == 1) {
819 // Remove from session cache but don't clear this connection.
820 SSL_SESSION* session = SSL_get_session(ssl_);
821 if (session) {
822 int rv = SSL_CTX_remove_session(SSL_get_SSL_CTX(ssl_), session);
823 LOG_IF(WARNING, !rv) << "Couldn't invalidate SSL session: " << session;
824 }
825 }
826 } else if (rv == 1) {
827 if (trying_cached_session_ && logging::DEBUG_MODE) {
828 DVLOG(2) << "Result of session reuse for " << host_and_port_.ToString()
829 << " is: " << (SSL_session_reused(ssl_) ? "Success" : "Fail");
830 }
831 // SSL handshake is completed. Let's verify the certificate.
832 const bool got_cert = !!UpdateServerCert();
833 DCHECK(got_cert);
834 net_log_.AddEvent(
835 NetLog::TYPE_SSL_CERTIFICATES_RECEIVED,
836 base::Bind(&NetLogX509CertificateCallback,
837 base::Unretained(server_cert_.get())));
838 GotoState(STATE_VERIFY_CERT);
839 } else {
840 int ssl_error = SSL_get_error(ssl_, rv);
841
842 if (ssl_error == SSL_ERROR_WANT_CHANNEL_ID_LOOKUP) {
[email protected]faff9852014-06-21 06:13:46843 // The server supports channel ID. Stop to look one up before returning to
844 // the handshake.
845 channel_id_xtn_negotiated_ = true;
846 GotoState(STATE_CHANNEL_ID_LOOKUP);
847 return OK;
[email protected]b9b651f2013-11-09 04:32:22848 }
849
[email protected]faff9852014-06-21 06:13:46850 net_error = MapOpenSSLError(ssl_error, err_tracer);
851
[email protected]b9b651f2013-11-09 04:32:22852 // If not done, stay in this state
853 if (net_error == ERR_IO_PENDING) {
854 GotoState(STATE_HANDSHAKE);
855 } else {
856 LOG(ERROR) << "handshake failed; returned " << rv
857 << ", SSL error code " << ssl_error
858 << ", net_error " << net_error;
859 net_log_.AddEvent(
860 NetLog::TYPE_SSL_HANDSHAKE_ERROR,
861 CreateNetLogSSLErrorCallback(net_error, ssl_error));
862 }
863 }
864 return net_error;
865}
866
[email protected]faff9852014-06-21 06:13:46867int SSLClientSocketOpenSSL::DoChannelIDLookup() {
868 GotoState(STATE_CHANNEL_ID_LOOKUP_COMPLETE);
869 return server_bound_cert_service_->GetOrCreateDomainBoundCert(
870 host_and_port_.host(),
871 &channel_id_private_key_,
872 &channel_id_cert_,
873 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete,
874 base::Unretained(this)),
875 &channel_id_request_handle_);
876}
877
878int SSLClientSocketOpenSSL::DoChannelIDLookupComplete(int result) {
879 if (result < 0)
880 return result;
881
882 DCHECK_LT(0u, channel_id_private_key_.size());
883 // Decode key.
884 std::vector<uint8> encrypted_private_key_info;
885 std::vector<uint8> subject_public_key_info;
886 encrypted_private_key_info.assign(
887 channel_id_private_key_.data(),
888 channel_id_private_key_.data() + channel_id_private_key_.size());
889 subject_public_key_info.assign(
890 channel_id_cert_.data(),
891 channel_id_cert_.data() + channel_id_cert_.size());
892 scoped_ptr<crypto::ECPrivateKey> ec_private_key(
893 crypto::ECPrivateKey::CreateFromEncryptedPrivateKeyInfo(
894 ServerBoundCertService::kEPKIPassword,
895 encrypted_private_key_info,
896 subject_public_key_info));
897 if (!ec_private_key) {
898 LOG(ERROR) << "Failed to import Channel ID.";
899 return ERR_CHANNEL_ID_IMPORT_FAILED;
900 }
901
902 // Hand the key to OpenSSL. Check for error in case OpenSSL rejects the key
903 // type.
904 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
905 int rv = SSL_set1_tls_channel_id(ssl_, ec_private_key->key());
906 if (!rv) {
907 LOG(ERROR) << "Failed to set Channel ID.";
908 int err = SSL_get_error(ssl_, rv);
909 return MapOpenSSLError(err, err_tracer);
910 }
911
912 // Return to the handshake.
913 set_channel_id_sent(true);
914 GotoState(STATE_HANDSHAKE);
915 return OK;
916}
917
[email protected]b9b651f2013-11-09 04:32:22918int SSLClientSocketOpenSSL::DoVerifyCert(int result) {
919 DCHECK(server_cert_.get());
920 GotoState(STATE_VERIFY_CERT_COMPLETE);
921
922 CertStatus cert_status;
923 if (ssl_config_.IsAllowedBadCert(server_cert_.get(), &cert_status)) {
924 VLOG(1) << "Received an expected bad cert with status: " << cert_status;
925 server_cert_verify_result_.Reset();
926 server_cert_verify_result_.cert_status = cert_status;
927 server_cert_verify_result_.verified_cert = server_cert_;
928 return OK;
929 }
930
931 int flags = 0;
932 if (ssl_config_.rev_checking_enabled)
933 flags |= CertVerifier::VERIFY_REV_CHECKING_ENABLED;
934 if (ssl_config_.verify_ev_cert)
935 flags |= CertVerifier::VERIFY_EV_CERT;
936 if (ssl_config_.cert_io_enabled)
937 flags |= CertVerifier::VERIFY_CERT_IO_ENABLED;
938 if (ssl_config_.rev_checking_required_local_anchors)
939 flags |= CertVerifier::VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS;
940 verifier_.reset(new SingleRequestCertVerifier(cert_verifier_));
941 return verifier_->Verify(
942 server_cert_.get(),
943 host_and_port_.host(),
944 flags,
945 NULL /* no CRL set */,
946 &server_cert_verify_result_,
947 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete,
948 base::Unretained(this)),
949 net_log_);
950}
951
952int SSLClientSocketOpenSSL::DoVerifyCertComplete(int result) {
953 verifier_.reset();
954
955 if (result == OK) {
956 // TODO(joth): Work out if we need to remember the intermediate CA certs
957 // when the server sends them to us, and do so here.
[email protected]a8fed1742013-12-27 02:14:24958 SSLContext::GetInstance()->session_cache()->MarkSSLSessionAsGood(ssl_);
[email protected]b9b651f2013-11-09 04:32:22959 } else {
960 DVLOG(1) << "DoVerifyCertComplete error " << ErrorToString(result)
961 << " (" << result << ")";
962 }
963
964 completed_handshake_ = true;
965 // Exit DoHandshakeLoop and return the result to the caller to Connect.
966 DCHECK_EQ(STATE_NONE, next_handshake_state_);
967 return result;
968}
969
970void SSLClientSocketOpenSSL::DoConnectCallback(int rv) {
971 if (!user_connect_callback_.is_null()) {
972 CompletionCallback c = user_connect_callback_;
973 user_connect_callback_.Reset();
974 c.Run(rv > OK ? OK : rv);
975 }
976}
977
978X509Certificate* SSLClientSocketOpenSSL::UpdateServerCert() {
[email protected]76e85392014-03-20 17:54:14979 server_cert_chain_->Reset(SSL_get_peer_cert_chain(ssl_));
[email protected]7f38da8a2014-03-17 16:44:26980 server_cert_ = server_cert_chain_->AsOSChain();
[email protected]76e85392014-03-20 17:54:14981
982 if (!server_cert_chain_->IsValid())
983 DVLOG(1) << "UpdateServerCert received invalid certificate chain from peer";
984
[email protected]b9b651f2013-11-09 04:32:22985 return server_cert_.get();
986}
987
988void SSLClientSocketOpenSSL::OnHandshakeIOComplete(int result) {
989 int rv = DoHandshakeLoop(result);
990 if (rv != ERR_IO_PENDING) {
991 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
992 DoConnectCallback(rv);
993 }
994}
995
996void SSLClientSocketOpenSSL::OnSendComplete(int result) {
997 if (next_handshake_state_ == STATE_HANDSHAKE) {
998 // In handshake phase.
999 OnHandshakeIOComplete(result);
1000 return;
1001 }
1002
1003 // OnSendComplete may need to call DoPayloadRead while the renegotiation
1004 // handshake is in progress.
1005 int rv_read = ERR_IO_PENDING;
1006 int rv_write = ERR_IO_PENDING;
1007 bool network_moved;
1008 do {
1009 if (user_read_buf_.get())
1010 rv_read = DoPayloadRead();
1011 if (user_write_buf_.get())
1012 rv_write = DoPayloadWrite();
1013 network_moved = DoTransportIO();
1014 } while (rv_read == ERR_IO_PENDING && rv_write == ERR_IO_PENDING &&
1015 (user_read_buf_.get() || user_write_buf_.get()) && network_moved);
1016
1017 // Performing the Read callback may cause |this| to be deleted. If this
1018 // happens, the Write callback should not be invoked. Guard against this by
1019 // holding a WeakPtr to |this| and ensuring it's still valid.
1020 base::WeakPtr<SSLClientSocketOpenSSL> guard(weak_factory_.GetWeakPtr());
1021 if (user_read_buf_.get() && rv_read != ERR_IO_PENDING)
1022 DoReadCallback(rv_read);
1023
1024 if (!guard.get())
1025 return;
1026
1027 if (user_write_buf_.get() && rv_write != ERR_IO_PENDING)
1028 DoWriteCallback(rv_write);
1029}
1030
1031void SSLClientSocketOpenSSL::OnRecvComplete(int result) {
1032 if (next_handshake_state_ == STATE_HANDSHAKE) {
1033 // In handshake phase.
1034 OnHandshakeIOComplete(result);
1035 return;
1036 }
1037
1038 // Network layer received some data, check if client requested to read
1039 // decrypted data.
1040 if (!user_read_buf_.get())
1041 return;
1042
1043 int rv = DoReadLoop(result);
1044 if (rv != ERR_IO_PENDING)
1045 DoReadCallback(rv);
1046}
1047
1048int SSLClientSocketOpenSSL::DoHandshakeLoop(int last_io_result) {
1049 int rv = last_io_result;
1050 do {
1051 // Default to STATE_NONE for next state.
1052 // (This is a quirk carried over from the windows
1053 // implementation. It makes reading the logs a bit harder.)
1054 // State handlers can and often do call GotoState just
1055 // to stay in the current state.
1056 State state = next_handshake_state_;
1057 GotoState(STATE_NONE);
1058 switch (state) {
1059 case STATE_HANDSHAKE:
1060 rv = DoHandshake();
1061 break;
[email protected]faff9852014-06-21 06:13:461062 case STATE_CHANNEL_ID_LOOKUP:
1063 DCHECK_EQ(OK, rv);
1064 rv = DoChannelIDLookup();
1065 break;
1066 case STATE_CHANNEL_ID_LOOKUP_COMPLETE:
1067 rv = DoChannelIDLookupComplete(rv);
1068 break;
[email protected]b9b651f2013-11-09 04:32:221069 case STATE_VERIFY_CERT:
[email protected]faff9852014-06-21 06:13:461070 DCHECK_EQ(OK, rv);
[email protected]b9b651f2013-11-09 04:32:221071 rv = DoVerifyCert(rv);
1072 break;
1073 case STATE_VERIFY_CERT_COMPLETE:
1074 rv = DoVerifyCertComplete(rv);
1075 break;
1076 case STATE_NONE:
1077 default:
1078 rv = ERR_UNEXPECTED;
1079 NOTREACHED() << "unexpected state" << state;
1080 break;
1081 }
1082
1083 bool network_moved = DoTransportIO();
1084 if (network_moved && next_handshake_state_ == STATE_HANDSHAKE) {
1085 // In general we exit the loop if rv is ERR_IO_PENDING. In this
1086 // special case we keep looping even if rv is ERR_IO_PENDING because
1087 // the transport IO may allow DoHandshake to make progress.
1088 rv = OK; // This causes us to stay in the loop.
1089 }
1090 } while (rv != ERR_IO_PENDING && next_handshake_state_ != STATE_NONE);
1091 return rv;
1092}
1093
1094int SSLClientSocketOpenSSL::DoReadLoop(int result) {
1095 if (result < 0)
1096 return result;
1097
1098 bool network_moved;
1099 int rv;
1100 do {
1101 rv = DoPayloadRead();
1102 network_moved = DoTransportIO();
1103 } while (rv == ERR_IO_PENDING && network_moved);
1104
1105 return rv;
1106}
1107
1108int SSLClientSocketOpenSSL::DoWriteLoop(int result) {
1109 if (result < 0)
1110 return result;
1111
1112 bool network_moved;
1113 int rv;
1114 do {
1115 rv = DoPayloadWrite();
1116 network_moved = DoTransportIO();
1117 } while (rv == ERR_IO_PENDING && network_moved);
1118
1119 return rv;
1120}
1121
1122int SSLClientSocketOpenSSL::DoPayloadRead() {
1123 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1124
1125 int rv;
1126 if (pending_read_error_ != kNoPendingReadResult) {
1127 rv = pending_read_error_;
1128 pending_read_error_ = kNoPendingReadResult;
1129 if (rv == 0) {
1130 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED,
1131 rv, user_read_buf_->data());
1132 }
1133 return rv;
1134 }
1135
1136 int total_bytes_read = 0;
1137 do {
1138 rv = SSL_read(ssl_, user_read_buf_->data() + total_bytes_read,
1139 user_read_buf_len_ - total_bytes_read);
1140 if (rv > 0)
1141 total_bytes_read += rv;
1142 } while (total_bytes_read < user_read_buf_len_ && rv > 0);
1143
1144 if (total_bytes_read == user_read_buf_len_) {
1145 rv = total_bytes_read;
1146 } else {
1147 // Otherwise, an error occurred (rv <= 0). The error needs to be handled
1148 // immediately, while the OpenSSL errors are still available in
1149 // thread-local storage. However, the handled/remapped error code should
1150 // only be returned if no application data was already read; if it was, the
1151 // error code should be deferred until the next call of DoPayloadRead.
1152 //
1153 // If no data was read, |*next_result| will point to the return value of
1154 // this function. If at least some data was read, |*next_result| will point
1155 // to |pending_read_error_|, to be returned in a future call to
1156 // DoPayloadRead() (e.g.: after the current data is handled).
1157 int *next_result = &rv;
1158 if (total_bytes_read > 0) {
1159 pending_read_error_ = rv;
1160 rv = total_bytes_read;
1161 next_result = &pending_read_error_;
1162 }
1163
1164 if (client_auth_cert_needed_) {
1165 *next_result = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
1166 } else if (*next_result < 0) {
1167 int err = SSL_get_error(ssl_, *next_result);
1168 *next_result = MapOpenSSLError(err, err_tracer);
1169 if (rv > 0 && *next_result == ERR_IO_PENDING) {
1170 // If at least some data was read from SSL_read(), do not treat
1171 // insufficient data as an error to return in the next call to
1172 // DoPayloadRead() - instead, let the call fall through to check
1173 // SSL_read() again. This is because DoTransportIO() may complete
1174 // in between the next call to DoPayloadRead(), and thus it is
1175 // important to check SSL_read() on subsequent invocations to see
1176 // if a complete record may now be read.
1177 *next_result = kNoPendingReadResult;
1178 }
1179 }
1180 }
1181
1182 if (rv >= 0) {
1183 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, rv,
1184 user_read_buf_->data());
1185 }
1186 return rv;
1187}
1188
1189int SSLClientSocketOpenSSL::DoPayloadWrite() {
1190 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1191 int rv = SSL_write(ssl_, user_write_buf_->data(), user_write_buf_len_);
1192
1193 if (rv >= 0) {
1194 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_SENT, rv,
1195 user_write_buf_->data());
1196 return rv;
1197 }
1198
1199 int err = SSL_get_error(ssl_, rv);
1200 return MapOpenSSLError(err, err_tracer);
1201}
1202
1203int SSLClientSocketOpenSSL::BufferSend(void) {
1204 if (transport_send_busy_)
1205 return ERR_IO_PENDING;
1206
1207 if (!send_buffer_.get()) {
1208 // Get a fresh send buffer out of the send BIO.
1209 size_t max_read = BIO_ctrl_pending(transport_bio_);
1210 if (!max_read)
1211 return 0; // Nothing pending in the OpenSSL write BIO.
1212 send_buffer_ = new DrainableIOBuffer(new IOBuffer(max_read), max_read);
1213 int read_bytes = BIO_read(transport_bio_, send_buffer_->data(), max_read);
1214 DCHECK_GT(read_bytes, 0);
1215 CHECK_EQ(static_cast<int>(max_read), read_bytes);
1216 }
1217
1218 int rv = transport_->socket()->Write(
1219 send_buffer_.get(),
1220 send_buffer_->BytesRemaining(),
1221 base::Bind(&SSLClientSocketOpenSSL::BufferSendComplete,
1222 base::Unretained(this)));
1223 if (rv == ERR_IO_PENDING) {
1224 transport_send_busy_ = true;
1225 } else {
1226 TransportWriteComplete(rv);
1227 }
1228 return rv;
1229}
1230
1231int SSLClientSocketOpenSSL::BufferRecv(void) {
1232 if (transport_recv_busy_)
1233 return ERR_IO_PENDING;
1234
1235 // Determine how much was requested from |transport_bio_| that was not
1236 // actually available.
1237 size_t requested = BIO_ctrl_get_read_request(transport_bio_);
1238 if (requested == 0) {
1239 // This is not a perfect match of error codes, as no operation is
1240 // actually pending. However, returning 0 would be interpreted as
1241 // a possible sign of EOF, which is also an inappropriate match.
1242 return ERR_IO_PENDING;
1243 }
1244
1245 // Known Issue: While only reading |requested| data is the more correct
1246 // implementation, it has the downside of resulting in frequent reads:
1247 // One read for the SSL record header (~5 bytes) and one read for the SSL
1248 // record body. Rather than issuing these reads to the underlying socket
1249 // (and constantly allocating new IOBuffers), a single Read() request to
1250 // fill |transport_bio_| is issued. As long as an SSL client socket cannot
1251 // be gracefully shutdown (via SSL close alerts) and re-used for non-SSL
1252 // traffic, this over-subscribed Read()ing will not cause issues.
1253 size_t max_write = BIO_ctrl_get_write_guarantee(transport_bio_);
1254 if (!max_write)
1255 return ERR_IO_PENDING;
1256
1257 recv_buffer_ = new IOBuffer(max_write);
1258 int rv = transport_->socket()->Read(
1259 recv_buffer_.get(),
1260 max_write,
1261 base::Bind(&SSLClientSocketOpenSSL::BufferRecvComplete,
1262 base::Unretained(this)));
1263 if (rv == ERR_IO_PENDING) {
1264 transport_recv_busy_ = true;
1265 } else {
[email protected]3e5c6922014-02-06 02:42:161266 rv = TransportReadComplete(rv);
[email protected]b9b651f2013-11-09 04:32:221267 }
1268 return rv;
1269}
1270
1271void SSLClientSocketOpenSSL::BufferSendComplete(int result) {
1272 transport_send_busy_ = false;
1273 TransportWriteComplete(result);
1274 OnSendComplete(result);
1275}
1276
1277void SSLClientSocketOpenSSL::BufferRecvComplete(int result) {
[email protected]3e5c6922014-02-06 02:42:161278 result = TransportReadComplete(result);
[email protected]b9b651f2013-11-09 04:32:221279 OnRecvComplete(result);
1280}
1281
1282void SSLClientSocketOpenSSL::TransportWriteComplete(int result) {
1283 DCHECK(ERR_IO_PENDING != result);
1284 if (result < 0) {
[email protected]5aea79182014-07-14 20:43:411285 // Record the error. Save it to be reported in a future read or write on
1286 // transport_bio_'s peer.
[email protected]3e5c6922014-02-06 02:42:161287 transport_write_error_ = result;
[email protected]b9b651f2013-11-09 04:32:221288 send_buffer_ = NULL;
1289 } else {
1290 DCHECK(send_buffer_.get());
1291 send_buffer_->DidConsume(result);
1292 DCHECK_GE(send_buffer_->BytesRemaining(), 0);
1293 if (send_buffer_->BytesRemaining() <= 0)
1294 send_buffer_ = NULL;
1295 }
1296}
1297
[email protected]3e5c6922014-02-06 02:42:161298int SSLClientSocketOpenSSL::TransportReadComplete(int result) {
[email protected]b9b651f2013-11-09 04:32:221299 DCHECK(ERR_IO_PENDING != result);
[email protected]5aea79182014-07-14 20:43:411300 // If an EOF, canonicalize to ERR_CONNECTION_CLOSED here so MapOpenSSLError
1301 // does not report success.
1302 if (result == 0)
1303 result = ERR_CONNECTION_CLOSED;
1304 if (result < 0) {
[email protected]b9b651f2013-11-09 04:32:221305 DVLOG(1) << "TransportReadComplete result " << result;
[email protected]5aea79182014-07-14 20:43:411306 // Received an error. Save it to be reported in a future read on
1307 // transport_bio_'s peer.
1308 transport_read_error_ = result;
[email protected]b9b651f2013-11-09 04:32:221309 } else {
1310 DCHECK(recv_buffer_.get());
1311 int ret = BIO_write(transport_bio_, recv_buffer_->data(), result);
1312 // A write into a memory BIO should always succeed.
[email protected]c8a80e92014-05-17 16:02:081313 DCHECK_EQ(result, ret);
[email protected]b9b651f2013-11-09 04:32:221314 }
1315 recv_buffer_ = NULL;
1316 transport_recv_busy_ = false;
[email protected]3e5c6922014-02-06 02:42:161317 return result;
[email protected]b9b651f2013-11-09 04:32:221318}
1319
[email protected]5ac981e182010-12-06 17:56:271320int SSLClientSocketOpenSSL::ClientCertRequestCallback(SSL* ssl,
1321 X509** x509,
1322 EVP_PKEY** pkey) {
1323 DVLOG(3) << "OpenSSL ClientCertRequestCallback called";
1324 DCHECK(ssl == ssl_);
1325 DCHECK(*x509 == NULL);
1326 DCHECK(*pkey == NULL);
[email protected]5ac981e182010-12-06 17:56:271327 if (!ssl_config_.send_client_cert) {
[email protected]515adc22013-01-09 16:01:231328 // First pass: we know that a client certificate is needed, but we do not
1329 // have one at hand.
[email protected]5ac981e182010-12-06 17:56:271330 client_auth_cert_needed_ = true;
[email protected]515adc22013-01-09 16:01:231331 STACK_OF(X509_NAME) *authorities = SSL_get_client_CA_list(ssl);
1332 for (int i = 0; i < sk_X509_NAME_num(authorities); i++) {
1333 X509_NAME *ca_name = (X509_NAME *)sk_X509_NAME_value(authorities, i);
1334 unsigned char* str = NULL;
1335 int length = i2d_X509_NAME(ca_name, &str);
1336 cert_authorities_.push_back(std::string(
1337 reinterpret_cast<const char*>(str),
1338 static_cast<size_t>(length)));
1339 OPENSSL_free(str);
1340 }
1341
[email protected]c0787702014-05-20 21:51:441342 const unsigned char* client_cert_types;
1343 size_t num_client_cert_types;
1344 SSL_get_client_certificate_types(ssl, &client_cert_types,
1345 &num_client_cert_types);
1346 for (size_t i = 0; i < num_client_cert_types; i++) {
1347 cert_key_types_.push_back(
1348 static_cast<SSLClientCertType>(client_cert_types[i]));
1349 }
1350
[email protected]5ac981e182010-12-06 17:56:271351 return -1; // Suspends handshake.
1352 }
1353
1354 // Second pass: a client certificate should have been selected.
[email protected]13914c92013-06-13 22:42:421355 if (ssl_config_.client_cert.get()) {
[email protected]6bad5052014-07-12 01:25:131356 // TODO(davidben): Configure OpenSSL to also send the intermediates.
1357 ScopedX509 leaf_x509 =
1358 OSCertHandleToOpenSSL(ssl_config_.client_cert->os_cert_handle());
1359 if (!leaf_x509) {
1360 LOG(WARNING) << "Failed to import certificate";
1361 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT);
1362 return -1;
1363 }
1364
1365 crypto::ScopedEVP_PKEY privkey;
[email protected]c0787702014-05-20 21:51:441366#if defined(USE_OPENSSL_CERTS)
[email protected]ede323ea2013-03-02 22:54:411367 // A note about ownership: FetchClientCertPrivateKey() increments
1368 // the reference count of the EVP_PKEY. Ownership of this reference
1369 // is passed directly to OpenSSL, which will release the reference
1370 // using EVP_PKEY_free() when the SSL object is destroyed.
[email protected]6bad5052014-07-12 01:25:131371 if (!OpenSSLClientKeyStore::GetInstance()->FetchClientCertPrivateKey(
[email protected]ede323ea2013-03-02 22:54:411372 ssl_config_.client_cert.get(), &privkey)) {
[email protected]6bad5052014-07-12 01:25:131373 // Could not find the private key. Fail the handshake and surface an
1374 // appropriate error to the caller.
1375 LOG(WARNING) << "Client cert found without private key";
1376 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY);
1377 return -1;
[email protected]0c6523f2010-12-10 10:56:241378 }
[email protected]e1b2d732014-03-28 16:20:321379#else // !defined(USE_OPENSSL_CERTS)
[email protected]6bad5052014-07-12 01:25:131380 // OS handling of private keys is not yet implemented.
[email protected]c0787702014-05-20 21:51:441381 NOTIMPLEMENTED();
[email protected]6bad5052014-07-12 01:25:131382 return 0;
[email protected]e1b2d732014-03-28 16:20:321383#endif // defined(USE_OPENSSL_CERTS)
[email protected]6bad5052014-07-12 01:25:131384
1385 // TODO(joth): (copied from NSS) We should wait for server certificate
1386 // verification before sending our credentials. See http://crbug.com/13934
1387 *x509 = leaf_x509.release();
1388 *pkey = privkey.release();
1389 return 1;
[email protected]c0787702014-05-20 21:51:441390 }
[email protected]5ac981e182010-12-06 17:56:271391
1392 // Send no client certificate.
1393 return 0;
1394}
1395
[email protected]b051cdb62014-02-28 02:20:161396int SSLClientSocketOpenSSL::CertVerifyCallback(X509_STORE_CTX* store_ctx) {
1397 if (!completed_handshake_) {
1398 // If the first handshake hasn't completed then we accept any certificates
1399 // because we verify after the handshake.
1400 return 1;
1401 }
1402
[email protected]76e85392014-03-20 17:54:141403 CHECK(server_cert_.get());
[email protected]b051cdb62014-02-28 02:20:161404
[email protected]3b6df022014-05-27 22:28:381405 PeerCertificateChain chain(store_ctx->untrusted);
[email protected]76e85392014-03-20 17:54:141406 if (chain.IsValid() && server_cert_->Equals(chain.AsOSChain()))
1407 return 1;
1408
1409 if (!chain.IsValid())
1410 LOG(ERROR) << "Received invalid certificate chain between handshakes";
1411 else
1412 LOG(ERROR) << "Server certificate changed between handshakes";
[email protected]b051cdb62014-02-28 02:20:161413 return 0;
1414}
1415
[email protected]ae7c9f42011-11-21 11:41:161416// SelectNextProtoCallback is called by OpenSSL during the handshake. If the
1417// server supports NPN, selects a protocol from the list that the server
1418// provides. According to third_party/openssl/openssl/ssl/ssl_lib.c, the
1419// callback can assume that |in| is syntactically valid.
[email protected]ea4a1c6a2010-12-09 13:33:281420int SSLClientSocketOpenSSL::SelectNextProtoCallback(unsigned char** out,
1421 unsigned char* outlen,
1422 const unsigned char* in,
1423 unsigned int inlen) {
[email protected]ea4a1c6a2010-12-09 13:33:281424 if (ssl_config_.next_protos.empty()) {
[email protected]168a8412012-06-14 05:05:491425 *out = reinterpret_cast<uint8*>(
1426 const_cast<char*>(kDefaultSupportedNPNProtocol));
1427 *outlen = arraysize(kDefaultSupportedNPNProtocol) - 1;
1428 npn_status_ = kNextProtoUnsupported;
[email protected]ea4a1c6a2010-12-09 13:33:281429 return SSL_TLSEXT_ERR_OK;
1430 }
1431
[email protected]ae7c9f42011-11-21 11:41:161432 // Assume there's no overlap between our protocols and the server's list.
[email protected]168a8412012-06-14 05:05:491433 npn_status_ = kNextProtoNoOverlap;
[email protected]ae7c9f42011-11-21 11:41:161434
1435 // For each protocol in server preference order, see if we support it.
1436 for (unsigned int i = 0; i < inlen; i += in[i] + 1) {
1437 for (std::vector<std::string>::const_iterator
1438 j = ssl_config_.next_protos.begin();
1439 j != ssl_config_.next_protos.end(); ++j) {
1440 if (in[i] == j->size() &&
1441 memcmp(&in[i + 1], j->data(), in[i]) == 0) {
[email protected]168a8412012-06-14 05:05:491442 // We found a match.
[email protected]ae7c9f42011-11-21 11:41:161443 *out = const_cast<unsigned char*>(in) + i + 1;
1444 *outlen = in[i];
[email protected]168a8412012-06-14 05:05:491445 npn_status_ = kNextProtoNegotiated;
[email protected]ae7c9f42011-11-21 11:41:161446 break;
1447 }
1448 }
[email protected]168a8412012-06-14 05:05:491449 if (npn_status_ == kNextProtoNegotiated)
[email protected]ae7c9f42011-11-21 11:41:161450 break;
1451 }
[email protected]ea4a1c6a2010-12-09 13:33:281452
[email protected]168a8412012-06-14 05:05:491453 // If we didn't find a protocol, we select the first one from our list.
1454 if (npn_status_ == kNextProtoNoOverlap) {
1455 *out = reinterpret_cast<uint8*>(const_cast<char*>(
1456 ssl_config_.next_protos[0].data()));
1457 *outlen = ssl_config_.next_protos[0].size();
1458 }
1459
[email protected]ea4a1c6a2010-12-09 13:33:281460 npn_proto_.assign(reinterpret_cast<const char*>(*out), *outlen);
[email protected]55e973d2011-12-05 23:03:241461 server_protos_.assign(reinterpret_cast<const char*>(in), inlen);
[email protected]32e1dee2010-12-09 18:36:241462 DVLOG(2) << "next protocol: '" << npn_proto_ << "' status: " << npn_status_;
[email protected]ea4a1c6a2010-12-09 13:33:281463 return SSL_TLSEXT_ERR_OK;
1464}
1465
[email protected]5aea79182014-07-14 20:43:411466long SSLClientSocketOpenSSL::MaybeReplayTransportError(
1467 BIO *bio,
1468 int cmd,
1469 const char *argp, int argi, long argl,
1470 long retvalue) {
1471 if (cmd == (BIO_CB_READ|BIO_CB_RETURN) && retvalue <= 0) {
1472 // If there is no more data in the buffer, report any pending errors that
1473 // were observed. Note that both the readbuf and the writebuf are checked
1474 // for errors, since the application may have encountered a socket error
1475 // while writing that would otherwise not be reported until the application
1476 // attempted to write again - which it may never do. See
1477 // https://crbug.com/249848.
1478 if (transport_read_error_ != OK) {
1479 OpenSSLPutNetError(FROM_HERE, transport_read_error_);
1480 return -1;
1481 }
1482 if (transport_write_error_ != OK) {
1483 OpenSSLPutNetError(FROM_HERE, transport_write_error_);
1484 return -1;
1485 }
1486 } else if (cmd == BIO_CB_WRITE) {
1487 // Because of the write buffer, this reports a failure from the previous
1488 // write payload. If the current payload fails to write, the error will be
1489 // reported in a future write or read to |bio|.
1490 if (transport_write_error_ != OK) {
1491 OpenSSLPutNetError(FROM_HERE, transport_write_error_);
1492 return -1;
1493 }
1494 }
1495 return retvalue;
1496}
1497
1498// static
1499long SSLClientSocketOpenSSL::BIOCallback(
1500 BIO *bio,
1501 int cmd,
1502 const char *argp, int argi, long argl,
1503 long retvalue) {
1504 SSLClientSocketOpenSSL* socket = reinterpret_cast<SSLClientSocketOpenSSL*>(
1505 BIO_get_callback_arg(bio));
1506 CHECK(socket);
1507 return socket->MaybeReplayTransportError(
1508 bio, cmd, argp, argi, argl, retvalue);
1509}
1510
[email protected]7f38da8a2014-03-17 16:44:261511scoped_refptr<X509Certificate>
1512SSLClientSocketOpenSSL::GetUnverifiedServerCertificateChain() const {
1513 return server_cert_;
1514}
1515
[email protected]7e5dd49f2010-12-08 18:33:491516} // namespace net