blob: 8bdc3148d11e83b8b2a28ee5ceebca57d6bce9f5 [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]89038152012-09-07 06:30:1755#if OPENSSL_VERSION_NUMBER < 0x1000103fL
56// This method doesn't seem to have made it into the OpenSSL headers.
[email protected]109805a2010-12-07 18:17:0657unsigned long SSL_CIPHER_get_id(const SSL_CIPHER* cipher) { return cipher->id; }
[email protected]89038152012-09-07 06:30:1758#endif
[email protected]109805a2010-12-07 18:17:0659
60// Used for encoding the |connection_status| field of an SSLInfo object.
61int EncodeSSLConnectionStatus(int cipher_suite,
62 int compression,
63 int version) {
64 return ((cipher_suite & SSL_CONNECTION_CIPHERSUITE_MASK) <<
65 SSL_CONNECTION_CIPHERSUITE_SHIFT) |
66 ((compression & SSL_CONNECTION_COMPRESSION_MASK) <<
67 SSL_CONNECTION_COMPRESSION_SHIFT) |
68 ((version & SSL_CONNECTION_VERSION_MASK) <<
69 SSL_CONNECTION_VERSION_SHIFT);
70}
71
72// Returns the net SSL version number (see ssl_connection_status_flags.h) for
73// this SSL connection.
74int GetNetSSLVersion(SSL* ssl) {
[email protected]7e5dd49f2010-12-08 18:33:4975 switch (SSL_version(ssl)) {
[email protected]109805a2010-12-07 18:17:0676 case SSL2_VERSION:
77 return SSL_CONNECTION_VERSION_SSL2;
78 case SSL3_VERSION:
79 return SSL_CONNECTION_VERSION_SSL3;
80 case TLS1_VERSION:
81 return SSL_CONNECTION_VERSION_TLS1;
82 case 0x0302:
83 return SSL_CONNECTION_VERSION_TLS1_1;
84 case 0x0303:
85 return SSL_CONNECTION_VERSION_TLS1_2;
86 default:
87 return SSL_CONNECTION_VERSION_UNKNOWN;
88 }
89}
90
[email protected]1279de12013-12-03 15:13:3291// Compute a unique key string for the SSL session cache. |socket| is an
92// input socket object. Return a string.
93std::string GetSocketSessionCacheKey(const SSLClientSocketOpenSSL& socket) {
94 std::string result = socket.host_and_port().ToString();
95 result.append("/");
96 result.append(socket.ssl_session_cache_shard());
97 return result;
98}
99
[email protected]cd9b75b2014-07-10 04:39:38100static void FreeX509Stack(STACK_OF(X509) * ptr) {
101 sk_X509_pop_free(ptr, X509_free);
102}
103
[email protected]821e3bb2013-11-08 01:06:01104} // namespace
105
106class SSLClientSocketOpenSSL::SSLContext {
[email protected]fbef13932010-11-23 12:38:53107 public:
[email protected]b29af7d2010-12-14 11:52:47108 static SSLContext* GetInstance() { return Singleton<SSLContext>::get(); }
[email protected]fbef13932010-11-23 12:38:53109 SSL_CTX* ssl_ctx() { return ssl_ctx_.get(); }
[email protected]1279de12013-12-03 15:13:32110 SSLSessionCacheOpenSSL* session_cache() { return &session_cache_; }
[email protected]fbef13932010-11-23 12:38:53111
[email protected]1279de12013-12-03 15:13:32112 SSLClientSocketOpenSSL* GetClientSocketFromSSL(const SSL* ssl) {
[email protected]fbef13932010-11-23 12:38:53113 DCHECK(ssl);
114 SSLClientSocketOpenSSL* socket = static_cast<SSLClientSocketOpenSSL*>(
115 SSL_get_ex_data(ssl, ssl_socket_data_index_));
116 DCHECK(socket);
117 return socket;
118 }
119
120 bool SetClientSocketForSSL(SSL* ssl, SSLClientSocketOpenSSL* socket) {
121 return SSL_set_ex_data(ssl, ssl_socket_data_index_, socket) != 0;
122 }
123
124 private:
125 friend struct DefaultSingletonTraits<SSLContext>;
126
127 SSLContext() {
[email protected]4b559b4d2011-04-14 17:37:14128 crypto::EnsureOpenSSLInit();
[email protected]fbef13932010-11-23 12:38:53129 ssl_socket_data_index_ = SSL_get_ex_new_index(0, 0, 0, 0, 0);
130 DCHECK_NE(ssl_socket_data_index_, -1);
131 ssl_ctx_.reset(SSL_CTX_new(SSLv23_client_method()));
[email protected]1279de12013-12-03 15:13:32132 session_cache_.Reset(ssl_ctx_.get(), kDefaultSessionCacheConfig);
[email protected]b051cdb62014-02-28 02:20:16133 SSL_CTX_set_cert_verify_callback(ssl_ctx_.get(), CertVerifyCallback, NULL);
[email protected]718c9672010-12-02 10:04:10134 SSL_CTX_set_client_cert_cb(ssl_ctx_.get(), ClientCertCallback);
[email protected]b051cdb62014-02-28 02:20:16135 SSL_CTX_set_verify(ssl_ctx_.get(), SSL_VERIFY_PEER, NULL);
[email protected]ea4a1c6a2010-12-09 13:33:28136 // TODO(kristianm): Only select this if ssl_config_.next_proto is not empty.
137 // It would be better if the callback were not a global setting,
138 // but that is an OpenSSL issue.
139 SSL_CTX_set_next_proto_select_cb(ssl_ctx_.get(), SelectNextProtoCallback,
140 NULL);
[email protected]fbef13932010-11-23 12:38:53141 }
142
[email protected]1279de12013-12-03 15:13:32143 static std::string GetSessionCacheKey(const SSL* ssl) {
144 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
145 DCHECK(socket);
146 return GetSocketSessionCacheKey(*socket);
[email protected]fbef13932010-11-23 12:38:53147 }
148
[email protected]1279de12013-12-03 15:13:32149 static SSLSessionCacheOpenSSL::Config kDefaultSessionCacheConfig;
[email protected]fbef13932010-11-23 12:38:53150
[email protected]718c9672010-12-02 10:04:10151 static int ClientCertCallback(SSL* ssl, X509** x509, EVP_PKEY** pkey) {
[email protected]b29af7d2010-12-14 11:52:47152 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
[email protected]718c9672010-12-02 10:04:10153 CHECK(socket);
154 return socket->ClientCertRequestCallback(ssl, x509, pkey);
155 }
156
[email protected]b051cdb62014-02-28 02:20:16157 static int CertVerifyCallback(X509_STORE_CTX *store_ctx, void *arg) {
158 SSL* ssl = reinterpret_cast<SSL*>(X509_STORE_CTX_get_ex_data(
159 store_ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
160 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
161 CHECK(socket);
162
163 return socket->CertVerifyCallback(store_ctx);
164 }
165
[email protected]ea4a1c6a2010-12-09 13:33:28166 static int SelectNextProtoCallback(SSL* ssl,
167 unsigned char** out, unsigned char* outlen,
168 const unsigned char* in,
169 unsigned int inlen, void* arg) {
[email protected]b29af7d2010-12-14 11:52:47170 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
[email protected]ea4a1c6a2010-12-09 13:33:28171 return socket->SelectNextProtoCallback(out, outlen, in, inlen);
172 }
173
[email protected]fbef13932010-11-23 12:38:53174 // This is the index used with SSL_get_ex_data to retrieve the owner
175 // SSLClientSocketOpenSSL object from an SSL instance.
176 int ssl_socket_data_index_;
177
[email protected]cd9b75b2014-07-10 04:39:38178 crypto::ScopedOpenSSL<SSL_CTX, SSL_CTX_free>::Type ssl_ctx_;
[email protected]1279de12013-12-03 15:13:32179 // |session_cache_| must be destroyed before |ssl_ctx_|.
180 SSLSessionCacheOpenSSL session_cache_;
181};
182
[email protected]7f38da8a2014-03-17 16:44:26183// PeerCertificateChain is a helper object which extracts the certificate
184// chain, as given by the server, from an OpenSSL socket and performs the needed
185// resource management. The first element of the chain is the leaf certificate
186// and the other elements are in the order given by the server.
187class SSLClientSocketOpenSSL::PeerCertificateChain {
188 public:
[email protected]76e85392014-03-20 17:54:14189 explicit PeerCertificateChain(STACK_OF(X509)* chain) { Reset(chain); }
[email protected]7f38da8a2014-03-17 16:44:26190 PeerCertificateChain(const PeerCertificateChain& other) { *this = other; }
191 ~PeerCertificateChain() {}
192 PeerCertificateChain& operator=(const PeerCertificateChain& other);
193
[email protected]76e85392014-03-20 17:54:14194 // Resets the PeerCertificateChain to the set of certificates in|chain|,
195 // which may be NULL, indicating to empty the store certificates.
196 // Note: If an error occurs, such as being unable to parse the certificates,
197 // this will behave as if Reset(NULL) was called.
198 void Reset(STACK_OF(X509)* chain);
199
[email protected]7f38da8a2014-03-17 16:44:26200 // Note that when USE_OPENSSL is defined, OSCertHandle is X509*
201 const scoped_refptr<X509Certificate>& AsOSChain() const { return os_chain_; }
202
203 size_t size() const {
204 if (!openssl_chain_.get())
205 return 0;
206 return sk_X509_num(openssl_chain_.get());
207 }
208
209 X509* operator[](size_t index) const {
210 DCHECK_LT(index, size());
211 return sk_X509_value(openssl_chain_.get(), index);
212 }
213
[email protected]76e85392014-03-20 17:54:14214 bool IsValid() { return os_chain_.get() && openssl_chain_.get(); }
215
[email protected]7f38da8a2014-03-17 16:44:26216 private:
[email protected]cd9b75b2014-07-10 04:39:38217 typedef crypto::ScopedOpenSSL<STACK_OF(X509), FreeX509Stack>::Type
218 ScopedX509Stack;
[email protected]7f38da8a2014-03-17 16:44:26219
[email protected]cd9b75b2014-07-10 04:39:38220 ScopedX509Stack openssl_chain_;
[email protected]7f38da8a2014-03-17 16:44:26221
222 scoped_refptr<X509Certificate> os_chain_;
223};
224
225SSLClientSocketOpenSSL::PeerCertificateChain&
226SSLClientSocketOpenSSL::PeerCertificateChain::operator=(
227 const PeerCertificateChain& other) {
228 if (this == &other)
229 return *this;
230
231 // os_chain_ is reference counted by scoped_refptr;
232 os_chain_ = other.os_chain_;
233
234 // Must increase the reference count manually for sk_X509_dup
235 openssl_chain_.reset(sk_X509_dup(other.openssl_chain_.get()));
236 for (int i = 0; i < sk_X509_num(openssl_chain_.get()); ++i) {
237 X509* x = sk_X509_value(openssl_chain_.get(), i);
238 CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509);
239 }
240 return *this;
241}
242
[email protected]e1b2d732014-03-28 16:20:32243#if defined(USE_OPENSSL_CERTS)
[email protected]7f38da8a2014-03-17 16:44:26244// When OSCertHandle is typedef'ed to X509, this implementation does a short cut
245// to avoid converting back and forth between der and X509 struct.
[email protected]76e85392014-03-20 17:54:14246void SSLClientSocketOpenSSL::PeerCertificateChain::Reset(
247 STACK_OF(X509)* chain) {
[email protected]7f38da8a2014-03-17 16:44:26248 openssl_chain_.reset(NULL);
249 os_chain_ = NULL;
250
[email protected]7f38da8a2014-03-17 16:44:26251 if (!chain)
252 return;
253
254 X509Certificate::OSCertHandles intermediates;
255 for (int i = 1; i < sk_X509_num(chain); ++i)
256 intermediates.push_back(sk_X509_value(chain, i));
257
258 os_chain_ =
259 X509Certificate::CreateFromHandle(sk_X509_value(chain, 0), intermediates);
260
261 // sk_X509_dup does not increase reference count on the certs in the stack.
262 openssl_chain_.reset(sk_X509_dup(chain));
263
264 std::vector<base::StringPiece> der_chain;
265 for (int i = 0; i < sk_X509_num(openssl_chain_.get()); ++i) {
266 X509* x = sk_X509_value(openssl_chain_.get(), i);
267 // Increase the reference count for the certs in openssl_chain_.
268 CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509);
269 }
270}
[email protected]e1b2d732014-03-28 16:20:32271#else // !defined(USE_OPENSSL_CERTS)
[email protected]76e85392014-03-20 17:54:14272void SSLClientSocketOpenSSL::PeerCertificateChain::Reset(
273 STACK_OF(X509)* chain) {
[email protected]7f38da8a2014-03-17 16:44:26274 openssl_chain_.reset(NULL);
275 os_chain_ = NULL;
276
[email protected]7f38da8a2014-03-17 16:44:26277 if (!chain)
278 return;
279
280 // sk_X509_dup does not increase reference count on the certs in the stack.
281 openssl_chain_.reset(sk_X509_dup(chain));
282
283 std::vector<base::StringPiece> der_chain;
284 for (int i = 0; i < sk_X509_num(openssl_chain_.get()); ++i) {
285 X509* x = sk_X509_value(openssl_chain_.get(), i);
286
287 // Increase the reference count for the certs in openssl_chain_.
288 CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509);
289
290 unsigned char* cert_data = NULL;
291 int cert_data_length = i2d_X509(x, &cert_data);
292 if (cert_data_length && cert_data)
293 der_chain.push_back(base::StringPiece(reinterpret_cast<char*>(cert_data),
294 cert_data_length));
295 }
296
297 os_chain_ = X509Certificate::CreateFromDERCertChain(der_chain);
298
299 for (size_t i = 0; i < der_chain.size(); ++i) {
300 OPENSSL_free(const_cast<char*>(der_chain[i].data()));
301 }
302
303 if (der_chain.size() !=
304 static_cast<size_t>(sk_X509_num(openssl_chain_.get()))) {
305 openssl_chain_.reset(NULL);
306 os_chain_ = NULL;
307 }
308}
[email protected]e1b2d732014-03-28 16:20:32309#endif // defined(USE_OPENSSL_CERTS)
[email protected]7f38da8a2014-03-17 16:44:26310
[email protected]1279de12013-12-03 15:13:32311// static
312SSLSessionCacheOpenSSL::Config
313 SSLClientSocketOpenSSL::SSLContext::kDefaultSessionCacheConfig = {
314 &GetSessionCacheKey, // key_func
315 1024, // max_entries
316 256, // expiration_check_count
317 60 * 60, // timeout_seconds
[email protected]fbef13932010-11-23 12:38:53318};
[email protected]313834722010-11-17 09:57:18319
[email protected]c3456bb2011-12-12 22:22:19320// static
321void SSLClientSocket::ClearSessionCache() {
[email protected]821e3bb2013-11-08 01:06:01322 SSLClientSocketOpenSSL::SSLContext* context =
323 SSLClientSocketOpenSSL::SSLContext::GetInstance();
[email protected]c3456bb2011-12-12 22:22:19324 context->session_cache()->Flush();
325}
326
[email protected]d518cd92010-09-29 12:27:44327SSLClientSocketOpenSSL::SSLClientSocketOpenSSL(
[email protected]18ccfdb2013-08-15 00:13:44328 scoped_ptr<ClientSocketHandle> transport_socket,
[email protected]055d7f22010-11-15 12:03:12329 const HostPortPair& host_and_port,
[email protected]822581d2010-12-16 17:27:15330 const SSLConfig& ssl_config,
[email protected]feb79bcd2011-07-21 16:55:17331 const SSLClientSocketContext& context)
[email protected]83039bb2011-12-09 18:43:55332 : transport_send_busy_(false),
[email protected]d518cd92010-09-29 12:27:44333 transport_recv_busy_(false),
[email protected]a85197e2012-05-22 19:07:28334 transport_recv_eof_(false),
[email protected]be90ba32013-05-13 20:05:25335 weak_factory_(this),
[email protected]4b768562013-02-16 04:10:07336 pending_read_error_(kNoPendingReadResult),
[email protected]3e5c6922014-02-06 02:42:16337 transport_write_error_(OK),
[email protected]7f38da8a2014-03-17 16:44:26338 server_cert_chain_(new PeerCertificateChain(NULL)),
[email protected]fbef13932010-11-23 12:38:53339 completed_handshake_(false),
[email protected]0dc88b32014-03-26 20:12:28340 was_ever_used_(false),
[email protected]d518cd92010-09-29 12:27:44341 client_auth_cert_needed_(false),
[email protected]feb79bcd2011-07-21 16:55:17342 cert_verifier_(context.cert_verifier),
[email protected]ee0f2aa82013-10-25 11:59:26343 server_bound_cert_service_(context.server_bound_cert_service),
[email protected]d518cd92010-09-29 12:27:44344 ssl_(NULL),
345 transport_bio_(NULL),
[email protected]18ccfdb2013-08-15 00:13:44346 transport_(transport_socket.Pass()),
[email protected]055d7f22010-11-15 12:03:12347 host_and_port_(host_and_port),
[email protected]d518cd92010-09-29 12:27:44348 ssl_config_(ssl_config),
[email protected]c3456bb2011-12-12 22:22:19349 ssl_session_cache_shard_(context.ssl_session_cache_shard),
[email protected]fbef13932010-11-23 12:38:53350 trying_cached_session_(false),
[email protected]013c17c2012-01-21 19:09:01351 next_handshake_state_(STATE_NONE),
[email protected]ea4a1c6a2010-12-09 13:33:28352 npn_status_(kNextProtoUnsupported),
[email protected]ee0f2aa82013-10-25 11:59:26353 channel_id_xtn_negotiated_(false),
[email protected]7f38da8a2014-03-17 16:44:26354 net_log_(transport_->socket()->NetLog()) {}
[email protected]d518cd92010-09-29 12:27:44355
356SSLClientSocketOpenSSL::~SSLClientSocketOpenSSL() {
357 Disconnect();
358}
359
[email protected]b9b651f2013-11-09 04:32:22360void SSLClientSocketOpenSSL::GetSSLCertRequestInfo(
361 SSLCertRequestInfo* cert_request_info) {
[email protected]791879c2013-12-17 07:22:41362 cert_request_info->host_and_port = host_and_port_;
[email protected]b9b651f2013-11-09 04:32:22363 cert_request_info->cert_authorities = cert_authorities_;
[email protected]c0787702014-05-20 21:51:44364 cert_request_info->cert_key_types = cert_key_types_;
[email protected]b9b651f2013-11-09 04:32:22365}
366
367SSLClientSocket::NextProtoStatus SSLClientSocketOpenSSL::GetNextProto(
368 std::string* proto, std::string* server_protos) {
369 *proto = npn_proto_;
370 *server_protos = server_protos_;
371 return npn_status_;
372}
373
374ServerBoundCertService*
375SSLClientSocketOpenSSL::GetServerBoundCertService() const {
376 return server_bound_cert_service_;
377}
378
379int SSLClientSocketOpenSSL::ExportKeyingMaterial(
380 const base::StringPiece& label,
381 bool has_context, const base::StringPiece& context,
382 unsigned char* out, unsigned int outlen) {
383 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
384
385 int rv = SSL_export_keying_material(
[email protected]c8a80e92014-05-17 16:02:08386 ssl_, out, outlen, label.data(), label.size(),
387 reinterpret_cast<const unsigned char*>(context.data()),
388 context.length(), context.length() > 0);
[email protected]b9b651f2013-11-09 04:32:22389
390 if (rv != 1) {
391 int ssl_error = SSL_get_error(ssl_, rv);
392 LOG(ERROR) << "Failed to export keying material;"
393 << " returned " << rv
394 << ", SSL error code " << ssl_error;
395 return MapOpenSSLError(ssl_error, err_tracer);
396 }
397 return OK;
398}
399
400int SSLClientSocketOpenSSL::GetTLSUniqueChannelBinding(std::string* out) {
[email protected]c8a80e92014-05-17 16:02:08401 NOTIMPLEMENTED();
[email protected]b9b651f2013-11-09 04:32:22402 return ERR_NOT_IMPLEMENTED;
403}
404
405int SSLClientSocketOpenSSL::Connect(const CompletionCallback& callback) {
406 net_log_.BeginEvent(NetLog::TYPE_SSL_CONNECT);
407
408 // Set up new ssl object.
[email protected]c8a80e92014-05-17 16:02:08409 int rv = Init();
410 if (rv != OK) {
411 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
412 return rv;
[email protected]b9b651f2013-11-09 04:32:22413 }
414
415 // Set SSL to client mode. Handshake happens in the loop below.
416 SSL_set_connect_state(ssl_);
417
418 GotoState(STATE_HANDSHAKE);
[email protected]c8a80e92014-05-17 16:02:08419 rv = DoHandshakeLoop(OK);
[email protected]b9b651f2013-11-09 04:32:22420 if (rv == ERR_IO_PENDING) {
421 user_connect_callback_ = callback;
422 } else {
423 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
424 }
425
426 return rv > OK ? OK : rv;
427}
428
429void SSLClientSocketOpenSSL::Disconnect() {
430 if (ssl_) {
431 // Calling SSL_shutdown prevents the session from being marked as
432 // unresumable.
433 SSL_shutdown(ssl_);
434 SSL_free(ssl_);
435 ssl_ = NULL;
436 }
437 if (transport_bio_) {
438 BIO_free_all(transport_bio_);
439 transport_bio_ = NULL;
440 }
441
442 // Shut down anything that may call us back.
443 verifier_.reset();
444 transport_->socket()->Disconnect();
445
446 // Null all callbacks, delete all buffers.
447 transport_send_busy_ = false;
448 send_buffer_ = NULL;
449 transport_recv_busy_ = false;
450 transport_recv_eof_ = false;
451 recv_buffer_ = NULL;
452
453 user_connect_callback_.Reset();
454 user_read_callback_.Reset();
455 user_write_callback_.Reset();
456 user_read_buf_ = NULL;
457 user_read_buf_len_ = 0;
458 user_write_buf_ = NULL;
459 user_write_buf_len_ = 0;
460
[email protected]3e5c6922014-02-06 02:42:16461 pending_read_error_ = kNoPendingReadResult;
462 transport_write_error_ = OK;
463
[email protected]b9b651f2013-11-09 04:32:22464 server_cert_verify_result_.Reset();
465 completed_handshake_ = false;
466
467 cert_authorities_.clear();
[email protected]c0787702014-05-20 21:51:44468 cert_key_types_.clear();
[email protected]b9b651f2013-11-09 04:32:22469 client_auth_cert_needed_ = false;
[email protected]faff9852014-06-21 06:13:46470
471 channel_id_xtn_negotiated_ = false;
472 channel_id_request_handle_.Cancel();
[email protected]b9b651f2013-11-09 04:32:22473}
474
475bool SSLClientSocketOpenSSL::IsConnected() const {
476 // If the handshake has not yet completed.
477 if (!completed_handshake_)
478 return false;
479 // If an asynchronous operation is still pending.
480 if (user_read_buf_.get() || user_write_buf_.get())
481 return true;
482
483 return transport_->socket()->IsConnected();
484}
485
486bool SSLClientSocketOpenSSL::IsConnectedAndIdle() const {
487 // If the handshake has not yet completed.
488 if (!completed_handshake_)
489 return false;
490 // If an asynchronous operation is still pending.
491 if (user_read_buf_.get() || user_write_buf_.get())
492 return false;
493 // If there is data waiting to be sent, or data read from the network that
494 // has not yet been consumed.
495 if (BIO_ctrl_pending(transport_bio_) > 0 ||
496 BIO_ctrl_wpending(transport_bio_) > 0) {
497 return false;
498 }
499
500 return transport_->socket()->IsConnectedAndIdle();
501}
502
503int SSLClientSocketOpenSSL::GetPeerAddress(IPEndPoint* addressList) const {
504 return transport_->socket()->GetPeerAddress(addressList);
505}
506
507int SSLClientSocketOpenSSL::GetLocalAddress(IPEndPoint* addressList) const {
508 return transport_->socket()->GetLocalAddress(addressList);
509}
510
511const BoundNetLog& SSLClientSocketOpenSSL::NetLog() const {
512 return net_log_;
513}
514
515void SSLClientSocketOpenSSL::SetSubresourceSpeculation() {
516 if (transport_.get() && transport_->socket()) {
517 transport_->socket()->SetSubresourceSpeculation();
518 } else {
519 NOTREACHED();
520 }
521}
522
523void SSLClientSocketOpenSSL::SetOmniboxSpeculation() {
524 if (transport_.get() && transport_->socket()) {
525 transport_->socket()->SetOmniboxSpeculation();
526 } else {
527 NOTREACHED();
528 }
529}
530
531bool SSLClientSocketOpenSSL::WasEverUsed() const {
[email protected]0dc88b32014-03-26 20:12:28532 return was_ever_used_;
[email protected]b9b651f2013-11-09 04:32:22533}
534
535bool SSLClientSocketOpenSSL::UsingTCPFastOpen() const {
536 if (transport_.get() && transport_->socket())
537 return transport_->socket()->UsingTCPFastOpen();
538
539 NOTREACHED();
540 return false;
541}
542
543bool SSLClientSocketOpenSSL::GetSSLInfo(SSLInfo* ssl_info) {
544 ssl_info->Reset();
545 if (!server_cert_.get())
546 return false;
547
548 ssl_info->cert = server_cert_verify_result_.verified_cert;
549 ssl_info->cert_status = server_cert_verify_result_.cert_status;
550 ssl_info->is_issued_by_known_root =
551 server_cert_verify_result_.is_issued_by_known_root;
552 ssl_info->public_key_hashes =
553 server_cert_verify_result_.public_key_hashes;
554 ssl_info->client_cert_sent =
555 ssl_config_.send_client_cert && ssl_config_.client_cert.get();
556 ssl_info->channel_id_sent = WasChannelIDSent();
557
558 RecordChannelIDSupport(server_bound_cert_service_,
559 channel_id_xtn_negotiated_,
560 ssl_config_.channel_id_enabled,
561 crypto::ECPrivateKey::IsSupported());
562
563 const SSL_CIPHER* cipher = SSL_get_current_cipher(ssl_);
564 CHECK(cipher);
565 ssl_info->security_bits = SSL_CIPHER_get_bits(cipher, NULL);
566 const COMP_METHOD* compression = SSL_get_current_compression(ssl_);
567
568 ssl_info->connection_status = EncodeSSLConnectionStatus(
569 SSL_CIPHER_get_id(cipher),
570 compression ? compression->type : 0,
571 GetNetSSLVersion(ssl_));
572
573 bool peer_supports_renego_ext = !!SSL_get_secure_renegotiation_support(ssl_);
574 if (!peer_supports_renego_ext)
575 ssl_info->connection_status |= SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION;
576 UMA_HISTOGRAM_ENUMERATION("Net.RenegotiationExtensionSupported",
577 implicit_cast<int>(peer_supports_renego_ext), 2);
578
579 if (ssl_config_.version_fallback)
580 ssl_info->connection_status |= SSL_CONNECTION_VERSION_FALLBACK;
581
582 ssl_info->handshake_type = SSL_session_reused(ssl_) ?
583 SSLInfo::HANDSHAKE_RESUME : SSLInfo::HANDSHAKE_FULL;
584
585 DVLOG(3) << "Encoded connection status: cipher suite = "
586 << SSLConnectionStatusToCipherSuite(ssl_info->connection_status)
587 << " version = "
588 << SSLConnectionStatusToVersion(ssl_info->connection_status);
589 return true;
590}
591
592int SSLClientSocketOpenSSL::Read(IOBuffer* buf,
593 int buf_len,
594 const CompletionCallback& callback) {
595 user_read_buf_ = buf;
596 user_read_buf_len_ = buf_len;
597
598 int rv = DoReadLoop(OK);
599
600 if (rv == ERR_IO_PENDING) {
601 user_read_callback_ = callback;
602 } else {
[email protected]0dc88b32014-03-26 20:12:28603 if (rv > 0)
604 was_ever_used_ = true;
[email protected]b9b651f2013-11-09 04:32:22605 user_read_buf_ = NULL;
606 user_read_buf_len_ = 0;
607 }
608
609 return rv;
610}
611
612int SSLClientSocketOpenSSL::Write(IOBuffer* buf,
613 int buf_len,
614 const CompletionCallback& callback) {
615 user_write_buf_ = buf;
616 user_write_buf_len_ = buf_len;
617
618 int rv = DoWriteLoop(OK);
619
620 if (rv == ERR_IO_PENDING) {
621 user_write_callback_ = callback;
622 } else {
[email protected]0dc88b32014-03-26 20:12:28623 if (rv > 0)
624 was_ever_used_ = true;
[email protected]b9b651f2013-11-09 04:32:22625 user_write_buf_ = NULL;
626 user_write_buf_len_ = 0;
627 }
628
629 return rv;
630}
631
[email protected]28b96d1c2014-04-09 12:21:15632int SSLClientSocketOpenSSL::SetReceiveBufferSize(int32 size) {
[email protected]b9b651f2013-11-09 04:32:22633 return transport_->socket()->SetReceiveBufferSize(size);
634}
635
[email protected]28b96d1c2014-04-09 12:21:15636int SSLClientSocketOpenSSL::SetSendBufferSize(int32 size) {
[email protected]b9b651f2013-11-09 04:32:22637 return transport_->socket()->SetSendBufferSize(size);
638}
639
[email protected]c8a80e92014-05-17 16:02:08640int SSLClientSocketOpenSSL::Init() {
[email protected]9e733f32010-10-04 18:19:08641 DCHECK(!ssl_);
642 DCHECK(!transport_bio_);
643
[email protected]b29af7d2010-12-14 11:52:47644 SSLContext* context = SSLContext::GetInstance();
[email protected]4b559b4d2011-04-14 17:37:14645 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
[email protected]d518cd92010-09-29 12:27:44646
[email protected]fbef13932010-11-23 12:38:53647 ssl_ = SSL_new(context->ssl_ctx());
648 if (!ssl_ || !context->SetClientSocketForSSL(ssl_, this))
[email protected]c8a80e92014-05-17 16:02:08649 return ERR_UNEXPECTED;
[email protected]fbef13932010-11-23 12:38:53650
651 if (!SSL_set_tlsext_host_name(ssl_, host_and_port_.host().c_str()))
[email protected]c8a80e92014-05-17 16:02:08652 return ERR_UNEXPECTED;
[email protected]fbef13932010-11-23 12:38:53653
[email protected]1279de12013-12-03 15:13:32654 trying_cached_session_ = context->session_cache()->SetSSLSessionWithKey(
655 ssl_, GetSocketSessionCacheKey(*this));
[email protected]d518cd92010-09-29 12:27:44656
657 BIO* ssl_bio = NULL;
[email protected]fbef13932010-11-23 12:38:53658 // 0 => use default buffer sizes.
659 if (!BIO_new_bio_pair(&ssl_bio, 0, &transport_bio_, 0))
[email protected]c8a80e92014-05-17 16:02:08660 return ERR_UNEXPECTED;
[email protected]d518cd92010-09-29 12:27:44661 DCHECK(ssl_bio);
662 DCHECK(transport_bio_);
663
664 SSL_set_bio(ssl_, ssl_bio, ssl_bio);
665
[email protected]9e733f32010-10-04 18:19:08666 // OpenSSL defaults some options to on, others to off. To avoid ambiguity,
667 // set everything we care about to an absolute value.
[email protected]fb10e2282010-12-01 17:08:48668 SslSetClearMask options;
669 options.ConfigureFlag(SSL_OP_NO_SSLv2, true);
[email protected]80c75f682012-05-26 16:22:17670 bool ssl3_enabled = (ssl_config_.version_min == SSL_PROTOCOL_VERSION_SSL3);
671 options.ConfigureFlag(SSL_OP_NO_SSLv3, !ssl3_enabled);
672 bool tls1_enabled = (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1 &&
673 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1);
674 options.ConfigureFlag(SSL_OP_NO_TLSv1, !tls1_enabled);
[email protected]80c75f682012-05-26 16:22:17675 bool tls1_1_enabled =
676 (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1_1 &&
677 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1_1);
678 options.ConfigureFlag(SSL_OP_NO_TLSv1_1, !tls1_1_enabled);
[email protected]80c75f682012-05-26 16:22:17679 bool tls1_2_enabled =
680 (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1_2 &&
681 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1_2);
682 options.ConfigureFlag(SSL_OP_NO_TLSv1_2, !tls1_2_enabled);
[email protected]fb10e2282010-12-01 17:08:48683
[email protected]d0f00492012-08-03 22:35:13684 options.ConfigureFlag(SSL_OP_NO_COMPRESSION, true);
[email protected]9e733f32010-10-04 18:19:08685
686 // TODO(joth): Set this conditionally, see http://crbug.com/55410
[email protected]fb10e2282010-12-01 17:08:48687 options.ConfigureFlag(SSL_OP_LEGACY_SERVER_CONNECT, true);
[email protected]9e733f32010-10-04 18:19:08688
[email protected]fb10e2282010-12-01 17:08:48689 SSL_set_options(ssl_, options.set_mask);
690 SSL_clear_options(ssl_, options.clear_mask);
[email protected]9e733f32010-10-04 18:19:08691
[email protected]fb10e2282010-12-01 17:08:48692 // Same as above, this time for the SSL mode.
693 SslSetClearMask mode;
[email protected]9e733f32010-10-04 18:19:08694
[email protected]fb10e2282010-12-01 17:08:48695 mode.ConfigureFlag(SSL_MODE_RELEASE_BUFFERS, true);
[email protected]fb10e2282010-12-01 17:08:48696
[email protected]b788de02014-04-23 18:06:07697 mode.ConfigureFlag(SSL_MODE_HANDSHAKE_CUTTHROUGH,
698 ssl_config_.false_start_enabled);
699
[email protected]fb10e2282010-12-01 17:08:48700 SSL_set_mode(ssl_, mode.set_mask);
701 SSL_clear_mode(ssl_, mode.clear_mask);
[email protected]109805a2010-12-07 18:17:06702
703 // Removing ciphers by ID from OpenSSL is a bit involved as we must use the
704 // textual name with SSL_set_cipher_list because there is no public API to
705 // directly remove a cipher by ID.
706 STACK_OF(SSL_CIPHER)* ciphers = SSL_get_ciphers(ssl_);
707 DCHECK(ciphers);
708 // See SSLConfig::disabled_cipher_suites for description of the suites
[email protected]9b4bc4a92013-08-20 22:59:07709 // disabled by default. Note that !SHA256 and !SHA384 only remove HMAC-SHA256
710 // and HMAC-SHA384 cipher suites, not GCM cipher suites with SHA256 or SHA384
711 // as the handshake hash.
712 std::string command("DEFAULT:!NULL:!aNULL:!IDEA:!FZA:!SRP:!SHA256:!SHA384:"
713 "!aECDH:!AESGCM+AES256");
[email protected]109805a2010-12-07 18:17:06714 // Walk through all the installed ciphers, seeing if any need to be
715 // appended to the cipher removal |command|.
716 for (int i = 0; i < sk_SSL_CIPHER_num(ciphers); ++i) {
717 const SSL_CIPHER* cipher = sk_SSL_CIPHER_value(ciphers, i);
718 const uint16 id = SSL_CIPHER_get_id(cipher);
719 // Remove any ciphers with a strength of less than 80 bits. Note the NSS
720 // implementation uses "effective" bits here but OpenSSL does not provide
721 // this detail. This only impacts Triple DES: reports 112 vs. 168 bits,
722 // both of which are greater than 80 anyway.
723 bool disable = SSL_CIPHER_get_bits(cipher, NULL) < 80;
724 if (!disable) {
725 disable = std::find(ssl_config_.disabled_cipher_suites.begin(),
726 ssl_config_.disabled_cipher_suites.end(), id) !=
727 ssl_config_.disabled_cipher_suites.end();
728 }
729 if (disable) {
730 const char* name = SSL_CIPHER_get_name(cipher);
731 DVLOG(3) << "Found cipher to remove: '" << name << "', ID: " << id
732 << " strength: " << SSL_CIPHER_get_bits(cipher, NULL);
733 command.append(":!");
734 command.append(name);
735 }
736 }
737 int rv = SSL_set_cipher_list(ssl_, command.c_str());
738 // If this fails (rv = 0) it means there are no ciphers enabled on this SSL.
739 // This will almost certainly result in the socket failing to complete the
740 // handshake at which point the appropriate error is bubbled up to the client.
741 LOG_IF(WARNING, rv != 1) << "SSL_set_cipher_list('" << command << "') "
742 "returned " << rv;
[email protected]ee0f2aa82013-10-25 11:59:26743
744 // TLS channel ids.
745 if (IsChannelIDEnabled(ssl_config_, server_bound_cert_service_)) {
746 SSL_enable_tls_channel_id(ssl_);
747 }
748
[email protected]c8a80e92014-05-17 16:02:08749 return OK;
[email protected]d518cd92010-09-29 12:27:44750}
751
[email protected]b9b651f2013-11-09 04:32:22752void SSLClientSocketOpenSSL::DoReadCallback(int rv) {
753 // Since Run may result in Read being called, clear |user_read_callback_|
754 // up front.
[email protected]0dc88b32014-03-26 20:12:28755 if (rv > 0)
756 was_ever_used_ = true;
[email protected]b9b651f2013-11-09 04:32:22757 user_read_buf_ = NULL;
758 user_read_buf_len_ = 0;
759 base::ResetAndReturn(&user_read_callback_).Run(rv);
760}
761
762void SSLClientSocketOpenSSL::DoWriteCallback(int rv) {
763 // Since Run may result in Write being called, clear |user_write_callback_|
764 // up front.
[email protected]0dc88b32014-03-26 20:12:28765 if (rv > 0)
766 was_ever_used_ = true;
[email protected]b9b651f2013-11-09 04:32:22767 user_write_buf_ = NULL;
768 user_write_buf_len_ = 0;
769 base::ResetAndReturn(&user_write_callback_).Run(rv);
770}
771
772bool SSLClientSocketOpenSSL::DoTransportIO() {
773 bool network_moved = false;
774 int rv;
775 // Read and write as much data as possible. The loop is necessary because
776 // Write() may return synchronously.
777 do {
778 rv = BufferSend();
779 if (rv != ERR_IO_PENDING && rv != 0)
780 network_moved = true;
781 } while (rv > 0);
782 if (!transport_recv_eof_ && BufferRecv() != ERR_IO_PENDING)
783 network_moved = true;
784 return network_moved;
785}
786
787int SSLClientSocketOpenSSL::DoHandshake() {
788 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
[email protected]c8a80e92014-05-17 16:02:08789 int net_error = OK;
[email protected]b9b651f2013-11-09 04:32:22790 int rv = SSL_do_handshake(ssl_);
791
792 if (client_auth_cert_needed_) {
793 net_error = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
794 // If the handshake already succeeded (because the server requests but
795 // doesn't require a client cert), we need to invalidate the SSL session
796 // so that we won't try to resume the non-client-authenticated session in
797 // the next handshake. This will cause the server to ask for a client
798 // cert again.
799 if (rv == 1) {
800 // Remove from session cache but don't clear this connection.
801 SSL_SESSION* session = SSL_get_session(ssl_);
802 if (session) {
803 int rv = SSL_CTX_remove_session(SSL_get_SSL_CTX(ssl_), session);
804 LOG_IF(WARNING, !rv) << "Couldn't invalidate SSL session: " << session;
805 }
806 }
807 } else if (rv == 1) {
808 if (trying_cached_session_ && logging::DEBUG_MODE) {
809 DVLOG(2) << "Result of session reuse for " << host_and_port_.ToString()
810 << " is: " << (SSL_session_reused(ssl_) ? "Success" : "Fail");
811 }
812 // SSL handshake is completed. Let's verify the certificate.
813 const bool got_cert = !!UpdateServerCert();
814 DCHECK(got_cert);
815 net_log_.AddEvent(
816 NetLog::TYPE_SSL_CERTIFICATES_RECEIVED,
817 base::Bind(&NetLogX509CertificateCallback,
818 base::Unretained(server_cert_.get())));
819 GotoState(STATE_VERIFY_CERT);
820 } else {
821 int ssl_error = SSL_get_error(ssl_, rv);
822
823 if (ssl_error == SSL_ERROR_WANT_CHANNEL_ID_LOOKUP) {
[email protected]faff9852014-06-21 06:13:46824 // The server supports channel ID. Stop to look one up before returning to
825 // the handshake.
826 channel_id_xtn_negotiated_ = true;
827 GotoState(STATE_CHANNEL_ID_LOOKUP);
828 return OK;
[email protected]b9b651f2013-11-09 04:32:22829 }
830
[email protected]faff9852014-06-21 06:13:46831 net_error = MapOpenSSLError(ssl_error, err_tracer);
832
[email protected]b9b651f2013-11-09 04:32:22833 // If not done, stay in this state
834 if (net_error == ERR_IO_PENDING) {
835 GotoState(STATE_HANDSHAKE);
836 } else {
837 LOG(ERROR) << "handshake failed; returned " << rv
838 << ", SSL error code " << ssl_error
839 << ", net_error " << net_error;
840 net_log_.AddEvent(
841 NetLog::TYPE_SSL_HANDSHAKE_ERROR,
842 CreateNetLogSSLErrorCallback(net_error, ssl_error));
843 }
844 }
845 return net_error;
846}
847
[email protected]faff9852014-06-21 06:13:46848int SSLClientSocketOpenSSL::DoChannelIDLookup() {
849 GotoState(STATE_CHANNEL_ID_LOOKUP_COMPLETE);
850 return server_bound_cert_service_->GetOrCreateDomainBoundCert(
851 host_and_port_.host(),
852 &channel_id_private_key_,
853 &channel_id_cert_,
854 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete,
855 base::Unretained(this)),
856 &channel_id_request_handle_);
857}
858
859int SSLClientSocketOpenSSL::DoChannelIDLookupComplete(int result) {
860 if (result < 0)
861 return result;
862
863 DCHECK_LT(0u, channel_id_private_key_.size());
864 // Decode key.
865 std::vector<uint8> encrypted_private_key_info;
866 std::vector<uint8> subject_public_key_info;
867 encrypted_private_key_info.assign(
868 channel_id_private_key_.data(),
869 channel_id_private_key_.data() + channel_id_private_key_.size());
870 subject_public_key_info.assign(
871 channel_id_cert_.data(),
872 channel_id_cert_.data() + channel_id_cert_.size());
873 scoped_ptr<crypto::ECPrivateKey> ec_private_key(
874 crypto::ECPrivateKey::CreateFromEncryptedPrivateKeyInfo(
875 ServerBoundCertService::kEPKIPassword,
876 encrypted_private_key_info,
877 subject_public_key_info));
878 if (!ec_private_key) {
879 LOG(ERROR) << "Failed to import Channel ID.";
880 return ERR_CHANNEL_ID_IMPORT_FAILED;
881 }
882
883 // Hand the key to OpenSSL. Check for error in case OpenSSL rejects the key
884 // type.
885 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
886 int rv = SSL_set1_tls_channel_id(ssl_, ec_private_key->key());
887 if (!rv) {
888 LOG(ERROR) << "Failed to set Channel ID.";
889 int err = SSL_get_error(ssl_, rv);
890 return MapOpenSSLError(err, err_tracer);
891 }
892
893 // Return to the handshake.
894 set_channel_id_sent(true);
895 GotoState(STATE_HANDSHAKE);
896 return OK;
897}
898
[email protected]b9b651f2013-11-09 04:32:22899int SSLClientSocketOpenSSL::DoVerifyCert(int result) {
900 DCHECK(server_cert_.get());
901 GotoState(STATE_VERIFY_CERT_COMPLETE);
902
903 CertStatus cert_status;
904 if (ssl_config_.IsAllowedBadCert(server_cert_.get(), &cert_status)) {
905 VLOG(1) << "Received an expected bad cert with status: " << cert_status;
906 server_cert_verify_result_.Reset();
907 server_cert_verify_result_.cert_status = cert_status;
908 server_cert_verify_result_.verified_cert = server_cert_;
909 return OK;
910 }
911
912 int flags = 0;
913 if (ssl_config_.rev_checking_enabled)
914 flags |= CertVerifier::VERIFY_REV_CHECKING_ENABLED;
915 if (ssl_config_.verify_ev_cert)
916 flags |= CertVerifier::VERIFY_EV_CERT;
917 if (ssl_config_.cert_io_enabled)
918 flags |= CertVerifier::VERIFY_CERT_IO_ENABLED;
919 if (ssl_config_.rev_checking_required_local_anchors)
920 flags |= CertVerifier::VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS;
921 verifier_.reset(new SingleRequestCertVerifier(cert_verifier_));
922 return verifier_->Verify(
923 server_cert_.get(),
924 host_and_port_.host(),
925 flags,
926 NULL /* no CRL set */,
927 &server_cert_verify_result_,
928 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete,
929 base::Unretained(this)),
930 net_log_);
931}
932
933int SSLClientSocketOpenSSL::DoVerifyCertComplete(int result) {
934 verifier_.reset();
935
936 if (result == OK) {
937 // TODO(joth): Work out if we need to remember the intermediate CA certs
938 // when the server sends them to us, and do so here.
[email protected]a8fed1742013-12-27 02:14:24939 SSLContext::GetInstance()->session_cache()->MarkSSLSessionAsGood(ssl_);
[email protected]b9b651f2013-11-09 04:32:22940 } else {
941 DVLOG(1) << "DoVerifyCertComplete error " << ErrorToString(result)
942 << " (" << result << ")";
943 }
944
945 completed_handshake_ = true;
946 // Exit DoHandshakeLoop and return the result to the caller to Connect.
947 DCHECK_EQ(STATE_NONE, next_handshake_state_);
948 return result;
949}
950
951void SSLClientSocketOpenSSL::DoConnectCallback(int rv) {
952 if (!user_connect_callback_.is_null()) {
953 CompletionCallback c = user_connect_callback_;
954 user_connect_callback_.Reset();
955 c.Run(rv > OK ? OK : rv);
956 }
957}
958
959X509Certificate* SSLClientSocketOpenSSL::UpdateServerCert() {
[email protected]76e85392014-03-20 17:54:14960 server_cert_chain_->Reset(SSL_get_peer_cert_chain(ssl_));
[email protected]7f38da8a2014-03-17 16:44:26961 server_cert_ = server_cert_chain_->AsOSChain();
[email protected]76e85392014-03-20 17:54:14962
963 if (!server_cert_chain_->IsValid())
964 DVLOG(1) << "UpdateServerCert received invalid certificate chain from peer";
965
[email protected]b9b651f2013-11-09 04:32:22966 return server_cert_.get();
967}
968
969void SSLClientSocketOpenSSL::OnHandshakeIOComplete(int result) {
970 int rv = DoHandshakeLoop(result);
971 if (rv != ERR_IO_PENDING) {
972 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
973 DoConnectCallback(rv);
974 }
975}
976
977void SSLClientSocketOpenSSL::OnSendComplete(int result) {
978 if (next_handshake_state_ == STATE_HANDSHAKE) {
979 // In handshake phase.
980 OnHandshakeIOComplete(result);
981 return;
982 }
983
984 // OnSendComplete may need to call DoPayloadRead while the renegotiation
985 // handshake is in progress.
986 int rv_read = ERR_IO_PENDING;
987 int rv_write = ERR_IO_PENDING;
988 bool network_moved;
989 do {
990 if (user_read_buf_.get())
991 rv_read = DoPayloadRead();
992 if (user_write_buf_.get())
993 rv_write = DoPayloadWrite();
994 network_moved = DoTransportIO();
995 } while (rv_read == ERR_IO_PENDING && rv_write == ERR_IO_PENDING &&
996 (user_read_buf_.get() || user_write_buf_.get()) && network_moved);
997
998 // Performing the Read callback may cause |this| to be deleted. If this
999 // happens, the Write callback should not be invoked. Guard against this by
1000 // holding a WeakPtr to |this| and ensuring it's still valid.
1001 base::WeakPtr<SSLClientSocketOpenSSL> guard(weak_factory_.GetWeakPtr());
1002 if (user_read_buf_.get() && rv_read != ERR_IO_PENDING)
1003 DoReadCallback(rv_read);
1004
1005 if (!guard.get())
1006 return;
1007
1008 if (user_write_buf_.get() && rv_write != ERR_IO_PENDING)
1009 DoWriteCallback(rv_write);
1010}
1011
1012void SSLClientSocketOpenSSL::OnRecvComplete(int result) {
1013 if (next_handshake_state_ == STATE_HANDSHAKE) {
1014 // In handshake phase.
1015 OnHandshakeIOComplete(result);
1016 return;
1017 }
1018
1019 // Network layer received some data, check if client requested to read
1020 // decrypted data.
1021 if (!user_read_buf_.get())
1022 return;
1023
1024 int rv = DoReadLoop(result);
1025 if (rv != ERR_IO_PENDING)
1026 DoReadCallback(rv);
1027}
1028
1029int SSLClientSocketOpenSSL::DoHandshakeLoop(int last_io_result) {
1030 int rv = last_io_result;
1031 do {
1032 // Default to STATE_NONE for next state.
1033 // (This is a quirk carried over from the windows
1034 // implementation. It makes reading the logs a bit harder.)
1035 // State handlers can and often do call GotoState just
1036 // to stay in the current state.
1037 State state = next_handshake_state_;
1038 GotoState(STATE_NONE);
1039 switch (state) {
1040 case STATE_HANDSHAKE:
1041 rv = DoHandshake();
1042 break;
[email protected]faff9852014-06-21 06:13:461043 case STATE_CHANNEL_ID_LOOKUP:
1044 DCHECK_EQ(OK, rv);
1045 rv = DoChannelIDLookup();
1046 break;
1047 case STATE_CHANNEL_ID_LOOKUP_COMPLETE:
1048 rv = DoChannelIDLookupComplete(rv);
1049 break;
[email protected]b9b651f2013-11-09 04:32:221050 case STATE_VERIFY_CERT:
[email protected]faff9852014-06-21 06:13:461051 DCHECK_EQ(OK, rv);
[email protected]b9b651f2013-11-09 04:32:221052 rv = DoVerifyCert(rv);
1053 break;
1054 case STATE_VERIFY_CERT_COMPLETE:
1055 rv = DoVerifyCertComplete(rv);
1056 break;
1057 case STATE_NONE:
1058 default:
1059 rv = ERR_UNEXPECTED;
1060 NOTREACHED() << "unexpected state" << state;
1061 break;
1062 }
1063
1064 bool network_moved = DoTransportIO();
1065 if (network_moved && next_handshake_state_ == STATE_HANDSHAKE) {
1066 // In general we exit the loop if rv is ERR_IO_PENDING. In this
1067 // special case we keep looping even if rv is ERR_IO_PENDING because
1068 // the transport IO may allow DoHandshake to make progress.
1069 rv = OK; // This causes us to stay in the loop.
1070 }
1071 } while (rv != ERR_IO_PENDING && next_handshake_state_ != STATE_NONE);
1072 return rv;
1073}
1074
1075int SSLClientSocketOpenSSL::DoReadLoop(int result) {
1076 if (result < 0)
1077 return result;
1078
1079 bool network_moved;
1080 int rv;
1081 do {
1082 rv = DoPayloadRead();
1083 network_moved = DoTransportIO();
1084 } while (rv == ERR_IO_PENDING && network_moved);
1085
1086 return rv;
1087}
1088
1089int SSLClientSocketOpenSSL::DoWriteLoop(int result) {
1090 if (result < 0)
1091 return result;
1092
1093 bool network_moved;
1094 int rv;
1095 do {
1096 rv = DoPayloadWrite();
1097 network_moved = DoTransportIO();
1098 } while (rv == ERR_IO_PENDING && network_moved);
1099
1100 return rv;
1101}
1102
1103int SSLClientSocketOpenSSL::DoPayloadRead() {
1104 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1105
1106 int rv;
1107 if (pending_read_error_ != kNoPendingReadResult) {
1108 rv = pending_read_error_;
1109 pending_read_error_ = kNoPendingReadResult;
1110 if (rv == 0) {
1111 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED,
1112 rv, user_read_buf_->data());
1113 }
1114 return rv;
1115 }
1116
1117 int total_bytes_read = 0;
1118 do {
1119 rv = SSL_read(ssl_, user_read_buf_->data() + total_bytes_read,
1120 user_read_buf_len_ - total_bytes_read);
1121 if (rv > 0)
1122 total_bytes_read += rv;
1123 } while (total_bytes_read < user_read_buf_len_ && rv > 0);
1124
1125 if (total_bytes_read == user_read_buf_len_) {
1126 rv = total_bytes_read;
1127 } else {
1128 // Otherwise, an error occurred (rv <= 0). The error needs to be handled
1129 // immediately, while the OpenSSL errors are still available in
1130 // thread-local storage. However, the handled/remapped error code should
1131 // only be returned if no application data was already read; if it was, the
1132 // error code should be deferred until the next call of DoPayloadRead.
1133 //
1134 // If no data was read, |*next_result| will point to the return value of
1135 // this function. If at least some data was read, |*next_result| will point
1136 // to |pending_read_error_|, to be returned in a future call to
1137 // DoPayloadRead() (e.g.: after the current data is handled).
1138 int *next_result = &rv;
1139 if (total_bytes_read > 0) {
1140 pending_read_error_ = rv;
1141 rv = total_bytes_read;
1142 next_result = &pending_read_error_;
1143 }
1144
1145 if (client_auth_cert_needed_) {
1146 *next_result = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
1147 } else if (*next_result < 0) {
1148 int err = SSL_get_error(ssl_, *next_result);
1149 *next_result = MapOpenSSLError(err, err_tracer);
1150 if (rv > 0 && *next_result == ERR_IO_PENDING) {
1151 // If at least some data was read from SSL_read(), do not treat
1152 // insufficient data as an error to return in the next call to
1153 // DoPayloadRead() - instead, let the call fall through to check
1154 // SSL_read() again. This is because DoTransportIO() may complete
1155 // in between the next call to DoPayloadRead(), and thus it is
1156 // important to check SSL_read() on subsequent invocations to see
1157 // if a complete record may now be read.
1158 *next_result = kNoPendingReadResult;
1159 }
1160 }
1161 }
1162
1163 if (rv >= 0) {
1164 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, rv,
1165 user_read_buf_->data());
1166 }
1167 return rv;
1168}
1169
1170int SSLClientSocketOpenSSL::DoPayloadWrite() {
1171 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1172 int rv = SSL_write(ssl_, user_write_buf_->data(), user_write_buf_len_);
1173
1174 if (rv >= 0) {
1175 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_SENT, rv,
1176 user_write_buf_->data());
1177 return rv;
1178 }
1179
1180 int err = SSL_get_error(ssl_, rv);
1181 return MapOpenSSLError(err, err_tracer);
1182}
1183
1184int SSLClientSocketOpenSSL::BufferSend(void) {
1185 if (transport_send_busy_)
1186 return ERR_IO_PENDING;
1187
1188 if (!send_buffer_.get()) {
1189 // Get a fresh send buffer out of the send BIO.
1190 size_t max_read = BIO_ctrl_pending(transport_bio_);
1191 if (!max_read)
1192 return 0; // Nothing pending in the OpenSSL write BIO.
1193 send_buffer_ = new DrainableIOBuffer(new IOBuffer(max_read), max_read);
1194 int read_bytes = BIO_read(transport_bio_, send_buffer_->data(), max_read);
1195 DCHECK_GT(read_bytes, 0);
1196 CHECK_EQ(static_cast<int>(max_read), read_bytes);
1197 }
1198
1199 int rv = transport_->socket()->Write(
1200 send_buffer_.get(),
1201 send_buffer_->BytesRemaining(),
1202 base::Bind(&SSLClientSocketOpenSSL::BufferSendComplete,
1203 base::Unretained(this)));
1204 if (rv == ERR_IO_PENDING) {
1205 transport_send_busy_ = true;
1206 } else {
1207 TransportWriteComplete(rv);
1208 }
1209 return rv;
1210}
1211
1212int SSLClientSocketOpenSSL::BufferRecv(void) {
1213 if (transport_recv_busy_)
1214 return ERR_IO_PENDING;
1215
1216 // Determine how much was requested from |transport_bio_| that was not
1217 // actually available.
1218 size_t requested = BIO_ctrl_get_read_request(transport_bio_);
1219 if (requested == 0) {
1220 // This is not a perfect match of error codes, as no operation is
1221 // actually pending. However, returning 0 would be interpreted as
1222 // a possible sign of EOF, which is also an inappropriate match.
1223 return ERR_IO_PENDING;
1224 }
1225
1226 // Known Issue: While only reading |requested| data is the more correct
1227 // implementation, it has the downside of resulting in frequent reads:
1228 // One read for the SSL record header (~5 bytes) and one read for the SSL
1229 // record body. Rather than issuing these reads to the underlying socket
1230 // (and constantly allocating new IOBuffers), a single Read() request to
1231 // fill |transport_bio_| is issued. As long as an SSL client socket cannot
1232 // be gracefully shutdown (via SSL close alerts) and re-used for non-SSL
1233 // traffic, this over-subscribed Read()ing will not cause issues.
1234 size_t max_write = BIO_ctrl_get_write_guarantee(transport_bio_);
1235 if (!max_write)
1236 return ERR_IO_PENDING;
1237
1238 recv_buffer_ = new IOBuffer(max_write);
1239 int rv = transport_->socket()->Read(
1240 recv_buffer_.get(),
1241 max_write,
1242 base::Bind(&SSLClientSocketOpenSSL::BufferRecvComplete,
1243 base::Unretained(this)));
1244 if (rv == ERR_IO_PENDING) {
1245 transport_recv_busy_ = true;
1246 } else {
[email protected]3e5c6922014-02-06 02:42:161247 rv = TransportReadComplete(rv);
[email protected]b9b651f2013-11-09 04:32:221248 }
1249 return rv;
1250}
1251
1252void SSLClientSocketOpenSSL::BufferSendComplete(int result) {
1253 transport_send_busy_ = false;
1254 TransportWriteComplete(result);
1255 OnSendComplete(result);
1256}
1257
1258void SSLClientSocketOpenSSL::BufferRecvComplete(int result) {
[email protected]3e5c6922014-02-06 02:42:161259 result = TransportReadComplete(result);
[email protected]b9b651f2013-11-09 04:32:221260 OnRecvComplete(result);
1261}
1262
1263void SSLClientSocketOpenSSL::TransportWriteComplete(int result) {
1264 DCHECK(ERR_IO_PENDING != result);
1265 if (result < 0) {
1266 // Got a socket write error; close the BIO to indicate this upward.
[email protected]3e5c6922014-02-06 02:42:161267 //
1268 // TODO(davidben): The value of |result| gets lost. Feed the error back into
1269 // the BIO so it gets (re-)detected in OnSendComplete. Perhaps with
1270 // BIO_set_callback.
[email protected]b9b651f2013-11-09 04:32:221271 DVLOG(1) << "TransportWriteComplete error " << result;
[email protected]3e5c6922014-02-06 02:42:161272 (void)BIO_shutdown_wr(SSL_get_wbio(ssl_));
1273
1274 // Match the fix for http://crbug.com/249848 in NSS by erroring future reads
1275 // from the socket after a write error.
1276 //
1277 // TODO(davidben): Avoid having read and write ends interact this way.
1278 transport_write_error_ = result;
[email protected]b9b651f2013-11-09 04:32:221279 (void)BIO_shutdown_wr(transport_bio_);
[email protected]b9b651f2013-11-09 04:32:221280 send_buffer_ = NULL;
1281 } else {
1282 DCHECK(send_buffer_.get());
1283 send_buffer_->DidConsume(result);
1284 DCHECK_GE(send_buffer_->BytesRemaining(), 0);
1285 if (send_buffer_->BytesRemaining() <= 0)
1286 send_buffer_ = NULL;
1287 }
1288}
1289
[email protected]3e5c6922014-02-06 02:42:161290int SSLClientSocketOpenSSL::TransportReadComplete(int result) {
[email protected]b9b651f2013-11-09 04:32:221291 DCHECK(ERR_IO_PENDING != result);
1292 if (result <= 0) {
1293 DVLOG(1) << "TransportReadComplete result " << result;
1294 // Received 0 (end of file) or an error. Either way, bubble it up to the
1295 // SSL layer via the BIO. TODO(joth): consider stashing the error code, to
1296 // relay up to the SSL socket client (i.e. via DoReadCallback).
1297 if (result == 0)
1298 transport_recv_eof_ = true;
[email protected]b9b651f2013-11-09 04:32:221299 (void)BIO_shutdown_wr(transport_bio_);
[email protected]3e5c6922014-02-06 02:42:161300 } else if (transport_write_error_ < 0) {
1301 // Mirror transport write errors as read failures; transport_bio_ has been
1302 // shut down by TransportWriteComplete, so the BIO_write will fail, failing
1303 // the CHECK. http://crbug.com/335557.
1304 result = transport_write_error_;
[email protected]b9b651f2013-11-09 04:32:221305 } else {
1306 DCHECK(recv_buffer_.get());
1307 int ret = BIO_write(transport_bio_, recv_buffer_->data(), result);
1308 // A write into a memory BIO should always succeed.
[email protected]c8a80e92014-05-17 16:02:081309 DCHECK_EQ(result, ret);
[email protected]b9b651f2013-11-09 04:32:221310 }
1311 recv_buffer_ = NULL;
1312 transport_recv_busy_ = false;
[email protected]3e5c6922014-02-06 02:42:161313 return result;
[email protected]b9b651f2013-11-09 04:32:221314}
1315
[email protected]5ac981e182010-12-06 17:56:271316int SSLClientSocketOpenSSL::ClientCertRequestCallback(SSL* ssl,
1317 X509** x509,
1318 EVP_PKEY** pkey) {
1319 DVLOG(3) << "OpenSSL ClientCertRequestCallback called";
1320 DCHECK(ssl == ssl_);
1321 DCHECK(*x509 == NULL);
1322 DCHECK(*pkey == NULL);
[email protected]5ac981e182010-12-06 17:56:271323 if (!ssl_config_.send_client_cert) {
[email protected]515adc22013-01-09 16:01:231324 // First pass: we know that a client certificate is needed, but we do not
1325 // have one at hand.
[email protected]5ac981e182010-12-06 17:56:271326 client_auth_cert_needed_ = true;
[email protected]515adc22013-01-09 16:01:231327 STACK_OF(X509_NAME) *authorities = SSL_get_client_CA_list(ssl);
1328 for (int i = 0; i < sk_X509_NAME_num(authorities); i++) {
1329 X509_NAME *ca_name = (X509_NAME *)sk_X509_NAME_value(authorities, i);
1330 unsigned char* str = NULL;
1331 int length = i2d_X509_NAME(ca_name, &str);
1332 cert_authorities_.push_back(std::string(
1333 reinterpret_cast<const char*>(str),
1334 static_cast<size_t>(length)));
1335 OPENSSL_free(str);
1336 }
1337
[email protected]c0787702014-05-20 21:51:441338 const unsigned char* client_cert_types;
1339 size_t num_client_cert_types;
1340 SSL_get_client_certificate_types(ssl, &client_cert_types,
1341 &num_client_cert_types);
1342 for (size_t i = 0; i < num_client_cert_types; i++) {
1343 cert_key_types_.push_back(
1344 static_cast<SSLClientCertType>(client_cert_types[i]));
1345 }
1346
[email protected]5ac981e182010-12-06 17:56:271347 return -1; // Suspends handshake.
1348 }
1349
1350 // Second pass: a client certificate should have been selected.
[email protected]13914c92013-06-13 22:42:421351 if (ssl_config_.client_cert.get()) {
[email protected]c0787702014-05-20 21:51:441352#if defined(USE_OPENSSL_CERTS)
[email protected]ede323ea2013-03-02 22:54:411353 // A note about ownership: FetchClientCertPrivateKey() increments
1354 // the reference count of the EVP_PKEY. Ownership of this reference
1355 // is passed directly to OpenSSL, which will release the reference
1356 // using EVP_PKEY_free() when the SSL object is destroyed.
1357 OpenSSLClientKeyStore::ScopedEVP_PKEY privkey;
1358 if (OpenSSLClientKeyStore::GetInstance()->FetchClientCertPrivateKey(
1359 ssl_config_.client_cert.get(), &privkey)) {
[email protected]0c6523f2010-12-10 10:56:241360 // TODO(joth): (copied from NSS) We should wait for server certificate
1361 // verification before sending our credentials. See http://crbug.com/13934
1362 *x509 = X509Certificate::DupOSCertHandle(
1363 ssl_config_.client_cert->os_cert_handle());
[email protected]ede323ea2013-03-02 22:54:411364 *pkey = privkey.release();
[email protected]0c6523f2010-12-10 10:56:241365 return 1;
1366 }
[email protected]b639ba52014-06-26 06:19:151367
1368 // Could not find the private key. Fail the handshake and surface an
1369 // appropriate error to the caller.
[email protected]0c6523f2010-12-10 10:56:241370 LOG(WARNING) << "Client cert found without private key";
[email protected]b639ba52014-06-26 06:19:151371 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY);
1372 return -1;
[email protected]e1b2d732014-03-28 16:20:321373#else // !defined(USE_OPENSSL_CERTS)
[email protected]c0787702014-05-20 21:51:441374 // OS handling of client certificates is not yet implemented.
1375 NOTIMPLEMENTED();
[email protected]e1b2d732014-03-28 16:20:321376#endif // defined(USE_OPENSSL_CERTS)
[email protected]c0787702014-05-20 21:51:441377 }
[email protected]5ac981e182010-12-06 17:56:271378
1379 // Send no client certificate.
1380 return 0;
1381}
1382
[email protected]b051cdb62014-02-28 02:20:161383int SSLClientSocketOpenSSL::CertVerifyCallback(X509_STORE_CTX* store_ctx) {
1384 if (!completed_handshake_) {
1385 // If the first handshake hasn't completed then we accept any certificates
1386 // because we verify after the handshake.
1387 return 1;
1388 }
1389
[email protected]76e85392014-03-20 17:54:141390 CHECK(server_cert_.get());
[email protected]b051cdb62014-02-28 02:20:161391
[email protected]3b6df022014-05-27 22:28:381392 PeerCertificateChain chain(store_ctx->untrusted);
[email protected]76e85392014-03-20 17:54:141393 if (chain.IsValid() && server_cert_->Equals(chain.AsOSChain()))
1394 return 1;
1395
1396 if (!chain.IsValid())
1397 LOG(ERROR) << "Received invalid certificate chain between handshakes";
1398 else
1399 LOG(ERROR) << "Server certificate changed between handshakes";
[email protected]b051cdb62014-02-28 02:20:161400 return 0;
1401}
1402
[email protected]ae7c9f42011-11-21 11:41:161403// SelectNextProtoCallback is called by OpenSSL during the handshake. If the
1404// server supports NPN, selects a protocol from the list that the server
1405// provides. According to third_party/openssl/openssl/ssl/ssl_lib.c, the
1406// callback can assume that |in| is syntactically valid.
[email protected]ea4a1c6a2010-12-09 13:33:281407int SSLClientSocketOpenSSL::SelectNextProtoCallback(unsigned char** out,
1408 unsigned char* outlen,
1409 const unsigned char* in,
1410 unsigned int inlen) {
[email protected]ea4a1c6a2010-12-09 13:33:281411 if (ssl_config_.next_protos.empty()) {
[email protected]168a8412012-06-14 05:05:491412 *out = reinterpret_cast<uint8*>(
1413 const_cast<char*>(kDefaultSupportedNPNProtocol));
1414 *outlen = arraysize(kDefaultSupportedNPNProtocol) - 1;
1415 npn_status_ = kNextProtoUnsupported;
[email protected]ea4a1c6a2010-12-09 13:33:281416 return SSL_TLSEXT_ERR_OK;
1417 }
1418
[email protected]ae7c9f42011-11-21 11:41:161419 // Assume there's no overlap between our protocols and the server's list.
[email protected]168a8412012-06-14 05:05:491420 npn_status_ = kNextProtoNoOverlap;
[email protected]ae7c9f42011-11-21 11:41:161421
1422 // For each protocol in server preference order, see if we support it.
1423 for (unsigned int i = 0; i < inlen; i += in[i] + 1) {
1424 for (std::vector<std::string>::const_iterator
1425 j = ssl_config_.next_protos.begin();
1426 j != ssl_config_.next_protos.end(); ++j) {
1427 if (in[i] == j->size() &&
1428 memcmp(&in[i + 1], j->data(), in[i]) == 0) {
[email protected]168a8412012-06-14 05:05:491429 // We found a match.
[email protected]ae7c9f42011-11-21 11:41:161430 *out = const_cast<unsigned char*>(in) + i + 1;
1431 *outlen = in[i];
[email protected]168a8412012-06-14 05:05:491432 npn_status_ = kNextProtoNegotiated;
[email protected]ae7c9f42011-11-21 11:41:161433 break;
1434 }
1435 }
[email protected]168a8412012-06-14 05:05:491436 if (npn_status_ == kNextProtoNegotiated)
[email protected]ae7c9f42011-11-21 11:41:161437 break;
1438 }
[email protected]ea4a1c6a2010-12-09 13:33:281439
[email protected]168a8412012-06-14 05:05:491440 // If we didn't find a protocol, we select the first one from our list.
1441 if (npn_status_ == kNextProtoNoOverlap) {
1442 *out = reinterpret_cast<uint8*>(const_cast<char*>(
1443 ssl_config_.next_protos[0].data()));
1444 *outlen = ssl_config_.next_protos[0].size();
1445 }
1446
[email protected]ea4a1c6a2010-12-09 13:33:281447 npn_proto_.assign(reinterpret_cast<const char*>(*out), *outlen);
[email protected]55e973d2011-12-05 23:03:241448 server_protos_.assign(reinterpret_cast<const char*>(in), inlen);
[email protected]32e1dee2010-12-09 18:36:241449 DVLOG(2) << "next protocol: '" << npn_proto_ << "' status: " << npn_status_;
[email protected]ea4a1c6a2010-12-09 13:33:281450 return SSL_TLSEXT_ERR_OK;
1451}
1452
[email protected]7f38da8a2014-03-17 16:44:261453scoped_refptr<X509Certificate>
1454SSLClientSocketOpenSSL::GetUnverifiedServerCertificateChain() const {
1455 return server_cert_;
1456}
1457
[email protected]7e5dd49f2010-12-08 18:33:491458} // namespace net