• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2011 The Chromium Authors. All rights reserved.
2 // 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 
10 #include <openssl/ssl.h>
11 #include <openssl/err.h>
12 #ifdef ANDROID
13 #include <string>
14 #endif
15 
16 #include "base/memory/singleton.h"
17 #include "base/metrics/histogram.h"
18 #include "base/synchronization/lock.h"
19 #include "crypto/openssl_util.h"
20 #include "net/base/cert_verifier.h"
21 #include "net/base/net_errors.h"
22 #include "net/base/openssl_private_key_store.h"
23 #include "net/base/ssl_cert_request_info.h"
24 #include "net/base/ssl_connection_status_flags.h"
25 #include "net/base/ssl_info.h"
26 #include "net/socket/ssl_error_params.h"
27 
28 namespace net {
29 
30 namespace {
31 
32 // Enable this to see logging for state machine state transitions.
33 #if 0
34 #define GotoState(s) do { DVLOG(2) << (void *)this << " " << __FUNCTION__ << \
35                            " jump to state " << s; \
36                            next_handshake_state_ = s; } while (0)
37 #else
38 #define GotoState(s) next_handshake_state_ = s
39 #endif
40 
41 const size_t kMaxRecvBufferSize = 4096;
42 const int kSessionCacheTimeoutSeconds = 60 * 60;
43 const size_t kSessionCacheMaxEntires = 1024;
44 
45 #if OPENSSL_VERSION_NUMBER < 0x1000100fL
46 // This method was first included in OpenSSL 1.0.1.
SSL_CIPHER_get_id(const SSL_CIPHER * cipher)47 unsigned long SSL_CIPHER_get_id(const SSL_CIPHER* cipher) { return cipher->id; }
48 #endif
49 
50 // Used for encoding the |connection_status| field of an SSLInfo object.
EncodeSSLConnectionStatus(int cipher_suite,int compression,int version)51 int EncodeSSLConnectionStatus(int cipher_suite,
52                               int compression,
53                               int version) {
54   return ((cipher_suite & SSL_CONNECTION_CIPHERSUITE_MASK) <<
55           SSL_CONNECTION_CIPHERSUITE_SHIFT) |
56          ((compression & SSL_CONNECTION_COMPRESSION_MASK) <<
57           SSL_CONNECTION_COMPRESSION_SHIFT) |
58          ((version & SSL_CONNECTION_VERSION_MASK) <<
59           SSL_CONNECTION_VERSION_SHIFT);
60 }
61 
62 // Returns the net SSL version number (see ssl_connection_status_flags.h) for
63 // this SSL connection.
GetNetSSLVersion(SSL * ssl)64 int GetNetSSLVersion(SSL* ssl) {
65   switch (SSL_version(ssl)) {
66     case SSL2_VERSION:
67       return SSL_CONNECTION_VERSION_SSL2;
68     case SSL3_VERSION:
69       return SSL_CONNECTION_VERSION_SSL3;
70     case TLS1_VERSION:
71       return SSL_CONNECTION_VERSION_TLS1;
72     case 0x0302:
73       return SSL_CONNECTION_VERSION_TLS1_1;
74     case 0x0303:
75       return SSL_CONNECTION_VERSION_TLS1_2;
76     default:
77       return SSL_CONNECTION_VERSION_UNKNOWN;
78   }
79 }
80 
MapOpenSSLErrorSSL()81 int MapOpenSSLErrorSSL() {
82   // Walk down the error stack to find the SSLerr generated reason.
83   unsigned long error_code;
84   do {
85     error_code = ERR_get_error();
86     if (error_code == 0)
87       return ERR_SSL_PROTOCOL_ERROR;
88   } while (ERR_GET_LIB(error_code) != ERR_LIB_SSL);
89 
90   DVLOG(1) << "OpenSSL SSL error, reason: " << ERR_GET_REASON(error_code)
91            << ", name: " << ERR_error_string(error_code, NULL);
92   switch (ERR_GET_REASON(error_code)) {
93     case SSL_R_READ_TIMEOUT_EXPIRED:
94       return ERR_TIMED_OUT;
95     case SSL_R_BAD_RESPONSE_ARGUMENT:
96       return ERR_INVALID_ARGUMENT;
97     case SSL_R_UNKNOWN_CERTIFICATE_TYPE:
98     case SSL_R_UNKNOWN_CIPHER_TYPE:
99     case SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE:
100     case SSL_R_UNKNOWN_PKEY_TYPE:
101     case SSL_R_UNKNOWN_REMOTE_ERROR_TYPE:
102     case SSL_R_UNKNOWN_SSL_VERSION:
103       return ERR_NOT_IMPLEMENTED;
104     case SSL_R_UNSUPPORTED_SSL_VERSION:
105     case SSL_R_NO_CIPHER_MATCH:
106     case SSL_R_NO_SHARED_CIPHER:
107     case SSL_R_TLSV1_ALERT_INSUFFICIENT_SECURITY:
108     case SSL_R_TLSV1_ALERT_PROTOCOL_VERSION:
109       return ERR_SSL_VERSION_OR_CIPHER_MISMATCH;
110     case SSL_R_SSLV3_ALERT_BAD_CERTIFICATE:
111     case SSL_R_SSLV3_ALERT_UNSUPPORTED_CERTIFICATE:
112     case SSL_R_SSLV3_ALERT_CERTIFICATE_REVOKED:
113     case SSL_R_SSLV3_ALERT_CERTIFICATE_EXPIRED:
114     case SSL_R_SSLV3_ALERT_CERTIFICATE_UNKNOWN:
115     case SSL_R_TLSV1_ALERT_ACCESS_DENIED:
116     case SSL_R_TLSV1_ALERT_UNKNOWN_CA:
117       return ERR_BAD_SSL_CLIENT_AUTH_CERT;
118     case SSL_R_BAD_DECOMPRESSION:
119     case SSL_R_SSLV3_ALERT_DECOMPRESSION_FAILURE:
120       return ERR_SSL_DECOMPRESSION_FAILURE_ALERT;
121     case SSL_R_SSLV3_ALERT_BAD_RECORD_MAC:
122       return ERR_SSL_BAD_RECORD_MAC_ALERT;
123     case SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED:
124       return ERR_SSL_UNSAFE_NEGOTIATION;
125     case SSL_R_WRONG_NUMBER_OF_KEY_BITS:
126       return ERR_SSL_WEAK_SERVER_EPHEMERAL_DH_KEY;
127     // SSL_R_UNKNOWN_PROTOCOL is reported if premature application data is
128     // received (see http://crbug.com/42538), and also if all the protocol
129     // versions supported by the server were disabled in this socket instance.
130     // Mapped to ERR_SSL_PROTOCOL_ERROR for compatibility with other SSL sockets
131     // in the former scenario.
132     case SSL_R_UNKNOWN_PROTOCOL:
133     case SSL_R_SSL_HANDSHAKE_FAILURE:
134     case SSL_R_DECRYPTION_FAILED:
135     case SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC:
136     case SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG:
137     case SSL_R_DIGEST_CHECK_FAILED:
138     case SSL_R_DUPLICATE_COMPRESSION_ID:
139     case SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER:
140     case SSL_R_ENCRYPTED_LENGTH_TOO_LONG:
141     case SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST:
142     case SSL_R_EXCESSIVE_MESSAGE_SIZE:
143     case SSL_R_EXTRA_DATA_IN_MESSAGE:
144     case SSL_R_GOT_A_FIN_BEFORE_A_CCS:
145     case SSL_R_ILLEGAL_PADDING:
146     case SSL_R_INVALID_CHALLENGE_LENGTH:
147     case SSL_R_INVALID_COMMAND:
148     case SSL_R_INVALID_PURPOSE:
149     case SSL_R_INVALID_STATUS_RESPONSE:
150     case SSL_R_INVALID_TICKET_KEYS_LENGTH:
151     case SSL_R_KEY_ARG_TOO_LONG:
152     case SSL_R_READ_WRONG_PACKET_TYPE:
153     case SSL_R_SSLV3_ALERT_UNEXPECTED_MESSAGE:
154     // TODO(joth): SSL_R_SSLV3_ALERT_HANDSHAKE_FAILURE may be returned from the
155     // server after receiving ClientHello if there's no common supported cipher.
156     // Ideally we'd map that specific case to ERR_SSL_VERSION_OR_CIPHER_MISMATCH
157     // to match the NSS implementation. See also http://goo.gl/oMtZW
158     case SSL_R_SSLV3_ALERT_HANDSHAKE_FAILURE:
159     case SSL_R_SSLV3_ALERT_NO_CERTIFICATE:
160     case SSL_R_SSLV3_ALERT_ILLEGAL_PARAMETER:
161     case SSL_R_TLSV1_ALERT_DECODE_ERROR:
162     case SSL_R_TLSV1_ALERT_DECRYPTION_FAILED:
163     case SSL_R_TLSV1_ALERT_DECRYPT_ERROR:
164     case SSL_R_TLSV1_ALERT_EXPORT_RESTRICTION:
165     case SSL_R_TLSV1_ALERT_INTERNAL_ERROR:
166     case SSL_R_TLSV1_ALERT_NO_RENEGOTIATION:
167     case SSL_R_TLSV1_ALERT_RECORD_OVERFLOW:
168     case SSL_R_TLSV1_ALERT_USER_CANCELLED:
169       return ERR_SSL_PROTOCOL_ERROR;
170     default:
171       LOG(WARNING) << "Unmapped error reason: " << ERR_GET_REASON(error_code);
172       return ERR_FAILED;
173   }
174 }
175 
176 // Converts an OpenSSL error code into a net error code, walking the OpenSSL
177 // error stack if needed. Note that |tracer| is not currently used in the
178 // implementation, but is passed in anyway as this ensures the caller will clear
179 // any residual codes left on the error stack.
MapOpenSSLError(int err,const crypto::OpenSSLErrStackTracer & tracer)180 int MapOpenSSLError(int err, const crypto::OpenSSLErrStackTracer& tracer) {
181   switch (err) {
182     case SSL_ERROR_WANT_READ:
183     case SSL_ERROR_WANT_WRITE:
184       return ERR_IO_PENDING;
185     case SSL_ERROR_SYSCALL:
186       DVLOG(1) << "OpenSSL SYSCALL error, errno " << errno;
187       return ERR_SSL_PROTOCOL_ERROR;
188     case SSL_ERROR_SSL:
189       return MapOpenSSLErrorSSL();
190     default:
191       // TODO(joth): Implement full mapping.
192       LOG(WARNING) << "Unknown OpenSSL error " << err;
193       return ERR_SSL_PROTOCOL_ERROR;
194   }
195 }
196 
197 // We do certificate verification after handshake, so we disable the default
198 // by registering a no-op verify function.
NoOpVerifyCallback(X509_STORE_CTX *,void *)199 int NoOpVerifyCallback(X509_STORE_CTX*, void *) {
200   DVLOG(3) << "skipping cert verify";
201   return 1;
202 }
203 
204 // OpenSSL manages a cache of SSL_SESSION, this class provides the application
205 // side policy for that cache about session re-use: we retain one session per
206 // unique HostPortPair.
207 class SSLSessionCache {
208  public:
SSLSessionCache()209   SSLSessionCache() {}
210 
OnSessionAdded(const HostPortPair & host_and_port,SSL_SESSION * session)211   void OnSessionAdded(const HostPortPair& host_and_port, SSL_SESSION* session) {
212     // Declare the session cleaner-upper before the lock, so any call into
213     // OpenSSL to free the session will happen after the lock is released.
214     crypto::ScopedOpenSSL<SSL_SESSION, SSL_SESSION_free> session_to_free;
215     base::AutoLock lock(lock_);
216 
217     DCHECK_EQ(0U, session_map_.count(session));
218     std::pair<HostPortMap::iterator, bool> res =
219         host_port_map_.insert(std::make_pair(host_and_port, session));
220     if (!res.second) {  // Already exists: replace old entry.
221       session_to_free.reset(res.first->second);
222       session_map_.erase(session_to_free.get());
223       res.first->second = session;
224     }
225     DVLOG(2) << "Adding session " << session << " => "
226              << host_and_port.ToString() << ", new entry = " << res.second;
227     DCHECK(host_port_map_[host_and_port] == session);
228     session_map_[session] = res.first;
229     DCHECK_EQ(host_port_map_.size(), session_map_.size());
230     DCHECK_LE(host_port_map_.size(), kSessionCacheMaxEntires);
231   }
232 
OnSessionRemoved(SSL_SESSION * session)233   void OnSessionRemoved(SSL_SESSION* session) {
234     // Declare the session cleaner-upper before the lock, so any call into
235     // OpenSSL to free the session will happen after the lock is released.
236     crypto::ScopedOpenSSL<SSL_SESSION, SSL_SESSION_free> session_to_free;
237     base::AutoLock lock(lock_);
238 
239     SessionMap::iterator it = session_map_.find(session);
240     if (it == session_map_.end())
241       return;
242     DVLOG(2) << "Remove session " << session << " => "
243              << it->second->first.ToString();
244     DCHECK(it->second->second == session);
245     host_port_map_.erase(it->second);
246     session_map_.erase(it);
247     session_to_free.reset(session);
248     DCHECK_EQ(host_port_map_.size(), session_map_.size());
249   }
250 
251   // Looks up the host:port in the cache, and if a session is found it is added
252   // to |ssl|, returning true on success.
SetSSLSession(SSL * ssl,const HostPortPair & host_and_port)253   bool SetSSLSession(SSL* ssl, const HostPortPair& host_and_port) {
254     base::AutoLock lock(lock_);
255     HostPortMap::iterator it = host_port_map_.find(host_and_port);
256     if (it == host_port_map_.end())
257       return false;
258     DVLOG(2) << "Lookup session: " << it->second << " => "
259              << host_and_port.ToString();
260     SSL_SESSION* session = it->second;
261     DCHECK(session);
262     DCHECK(session_map_[session] == it);
263     // Ideally we'd release |lock_| before calling into OpenSSL here, however
264     // that opens a small risk |session| will go out of scope before it is used.
265     // Alternatively we would take a temporary local refcount on |session|,
266     // except OpenSSL does not provide a public API for adding a ref (c.f.
267     // SSL_SESSION_free which decrements the ref).
268     return SSL_set_session(ssl, session) == 1;
269   }
270 
271  private:
272   // A pair of maps to allow bi-directional lookups between host:port and an
273   // associated session.
274   // TODO(joth): When client certificates are implemented we should key the
275   // cache on the client certificate used in addition to the host-port pair.
276   typedef std::map<HostPortPair, SSL_SESSION*> HostPortMap;
277   typedef std::map<SSL_SESSION*, HostPortMap::iterator> SessionMap;
278   HostPortMap host_port_map_;
279   SessionMap session_map_;
280 
281   // Protects access to both the above maps.
282   base::Lock lock_;
283 
284   DISALLOW_COPY_AND_ASSIGN(SSLSessionCache);
285 };
286 
287 class SSLContext {
288  public:
GetInstance()289   static SSLContext* GetInstance() { return Singleton<SSLContext>::get(); }
ssl_ctx()290   SSL_CTX* ssl_ctx() { return ssl_ctx_.get(); }
session_cache()291   SSLSessionCache* session_cache() { return &session_cache_; }
292 
GetClientSocketFromSSL(SSL * ssl)293   SSLClientSocketOpenSSL* GetClientSocketFromSSL(SSL* ssl) {
294     DCHECK(ssl);
295     SSLClientSocketOpenSSL* socket = static_cast<SSLClientSocketOpenSSL*>(
296         SSL_get_ex_data(ssl, ssl_socket_data_index_));
297     DCHECK(socket);
298     return socket;
299   }
300 
SetClientSocketForSSL(SSL * ssl,SSLClientSocketOpenSSL * socket)301   bool SetClientSocketForSSL(SSL* ssl, SSLClientSocketOpenSSL* socket) {
302     return SSL_set_ex_data(ssl, ssl_socket_data_index_, socket) != 0;
303   }
304 
305  private:
306   friend struct DefaultSingletonTraits<SSLContext>;
307 
SSLContext()308   SSLContext() {
309     crypto::EnsureOpenSSLInit();
310     ssl_socket_data_index_ = SSL_get_ex_new_index(0, 0, 0, 0, 0);
311     DCHECK_NE(ssl_socket_data_index_, -1);
312     ssl_ctx_.reset(SSL_CTX_new(SSLv23_client_method()));
313     SSL_CTX_set_cert_verify_callback(ssl_ctx_.get(), NoOpVerifyCallback, NULL);
314     SSL_CTX_set_session_cache_mode(ssl_ctx_.get(), SSL_SESS_CACHE_CLIENT);
315     SSL_CTX_sess_set_new_cb(ssl_ctx_.get(), NewSessionCallbackStatic);
316     SSL_CTX_sess_set_remove_cb(ssl_ctx_.get(), RemoveSessionCallbackStatic);
317     SSL_CTX_set_timeout(ssl_ctx_.get(), kSessionCacheTimeoutSeconds);
318     SSL_CTX_sess_set_cache_size(ssl_ctx_.get(), kSessionCacheMaxEntires);
319     SSL_CTX_set_client_cert_cb(ssl_ctx_.get(), ClientCertCallback);
320 #if defined(OPENSSL_NPN_NEGOTIATED)
321     // TODO(kristianm): Only select this if ssl_config_.next_proto is not empty.
322     // It would be better if the callback were not a global setting,
323     // but that is an OpenSSL issue.
324     SSL_CTX_set_next_proto_select_cb(ssl_ctx_.get(), SelectNextProtoCallback,
325                                      NULL);
326 #endif
327   }
328 
NewSessionCallbackStatic(SSL * ssl,SSL_SESSION * session)329   static int NewSessionCallbackStatic(SSL* ssl, SSL_SESSION* session) {
330     return GetInstance()->NewSessionCallback(ssl, session);
331   }
332 
NewSessionCallback(SSL * ssl,SSL_SESSION * session)333   int NewSessionCallback(SSL* ssl, SSL_SESSION* session) {
334     SSLClientSocketOpenSSL* socket = GetClientSocketFromSSL(ssl);
335     session_cache_.OnSessionAdded(socket->host_and_port(), session);
336     return 1;  // 1 => We took ownership of |session|.
337   }
338 
RemoveSessionCallbackStatic(SSL_CTX * ctx,SSL_SESSION * session)339   static void RemoveSessionCallbackStatic(SSL_CTX* ctx, SSL_SESSION* session) {
340     return GetInstance()->RemoveSessionCallback(ctx, session);
341   }
342 
RemoveSessionCallback(SSL_CTX * ctx,SSL_SESSION * session)343   void RemoveSessionCallback(SSL_CTX* ctx, SSL_SESSION* session) {
344     DCHECK(ctx == ssl_ctx());
345     session_cache_.OnSessionRemoved(session);
346   }
347 
ClientCertCallback(SSL * ssl,X509 ** x509,EVP_PKEY ** pkey)348   static int ClientCertCallback(SSL* ssl, X509** x509, EVP_PKEY** pkey) {
349     SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
350     CHECK(socket);
351     return socket->ClientCertRequestCallback(ssl, x509, pkey);
352   }
353 
SelectNextProtoCallback(SSL * ssl,unsigned char ** out,unsigned char * outlen,const unsigned char * in,unsigned int inlen,void * arg)354   static int SelectNextProtoCallback(SSL* ssl,
355                                      unsigned char** out, unsigned char* outlen,
356                                      const unsigned char* in,
357                                      unsigned int inlen, void* arg) {
358     SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
359     return socket->SelectNextProtoCallback(out, outlen, in, inlen);
360   }
361 
362   // This is the index used with SSL_get_ex_data to retrieve the owner
363   // SSLClientSocketOpenSSL object from an SSL instance.
364   int ssl_socket_data_index_;
365 
366   crypto::ScopedOpenSSL<SSL_CTX, SSL_CTX_free> ssl_ctx_;
367   SSLSessionCache session_cache_;
368 };
369 
370 // Utility to construct the appropriate set & clear masks for use the OpenSSL
371 // options and mode configuration functions. (SSL_set_options etc)
372 struct SslSetClearMask {
SslSetClearMasknet::__anon4938df450111::SslSetClearMask373   SslSetClearMask() : set_mask(0), clear_mask(0) {}
ConfigureFlagnet::__anon4938df450111::SslSetClearMask374   void ConfigureFlag(long flag, bool state) {
375     (state ? set_mask : clear_mask) |= flag;
376     // Make sure we haven't got any intersection in the set & clear options.
377     DCHECK_EQ(0, set_mask & clear_mask) << flag << ":" << state;
378   }
379   long set_mask;
380   long clear_mask;
381 };
382 
383 }  // namespace
384 
SSLClientSocketOpenSSL(ClientSocketHandle * transport_socket,const HostPortPair & host_and_port,const SSLConfig & ssl_config,CertVerifier * cert_verifier)385 SSLClientSocketOpenSSL::SSLClientSocketOpenSSL(
386     ClientSocketHandle* transport_socket,
387     const HostPortPair& host_and_port,
388     const SSLConfig& ssl_config,
389     CertVerifier* cert_verifier)
390     : ALLOW_THIS_IN_INITIALIZER_LIST(buffer_send_callback_(
391           this, &SSLClientSocketOpenSSL::BufferSendComplete)),
392       ALLOW_THIS_IN_INITIALIZER_LIST(buffer_recv_callback_(
393           this, &SSLClientSocketOpenSSL::BufferRecvComplete)),
394       transport_send_busy_(false),
395       transport_recv_busy_(false),
396       user_connect_callback_(NULL),
397       user_read_callback_(NULL),
398       user_write_callback_(NULL),
399       completed_handshake_(false),
400       client_auth_cert_needed_(false),
401       cert_verifier_(cert_verifier),
402       ALLOW_THIS_IN_INITIALIZER_LIST(handshake_io_callback_(
403           this, &SSLClientSocketOpenSSL::OnHandshakeIOComplete)),
404       ssl_(NULL),
405       transport_bio_(NULL),
406       transport_(transport_socket),
407       host_and_port_(host_and_port),
408       ssl_config_(ssl_config),
409       trying_cached_session_(false),
410       npn_status_(kNextProtoUnsupported),
411       net_log_(transport_socket->socket()->NetLog()) {
412 }
413 
~SSLClientSocketOpenSSL()414 SSLClientSocketOpenSSL::~SSLClientSocketOpenSSL() {
415   Disconnect();
416 }
417 
Init()418 bool SSLClientSocketOpenSSL::Init() {
419   DCHECK(!ssl_);
420   DCHECK(!transport_bio_);
421 
422   SSLContext* context = SSLContext::GetInstance();
423   crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
424 
425   ssl_ = SSL_new(context->ssl_ctx());
426   if (!ssl_ || !context->SetClientSocketForSSL(ssl_, this))
427     return false;
428 
429   if (!SSL_set_tlsext_host_name(ssl_, host_and_port_.host().c_str()))
430     return false;
431 
432   trying_cached_session_ =
433       context->session_cache()->SetSSLSession(ssl_, host_and_port_);
434 
435   BIO* ssl_bio = NULL;
436   // 0 => use default buffer sizes.
437   if (!BIO_new_bio_pair(&ssl_bio, 0, &transport_bio_, 0))
438     return false;
439   DCHECK(ssl_bio);
440   DCHECK(transport_bio_);
441 
442   SSL_set_bio(ssl_, ssl_bio, ssl_bio);
443 
444   // OpenSSL defaults some options to on, others to off. To avoid ambiguity,
445   // set everything we care about to an absolute value.
446   SslSetClearMask options;
447   options.ConfigureFlag(SSL_OP_NO_SSLv2, true);
448   options.ConfigureFlag(SSL_OP_NO_SSLv3, !ssl_config_.ssl3_enabled);
449   options.ConfigureFlag(SSL_OP_NO_TLSv1, !ssl_config_.tls1_enabled);
450 #ifdef SSL_OP_NO_TLSv1_1
451   options.ConfigureFlag(SSL_OP_NO_TLSv1_1, true);
452 #endif
453 #ifdef SSL_OP_NO_TLSv1_2
454   options.ConfigureFlag(SSL_OP_NO_TLSv1_2, true);
455 #endif
456 
457 #if defined(SSL_OP_NO_COMPRESSION)
458   // If TLS was disabled also disable compression, to provide maximum site
459   // compatibility in the case of protocol fallback. See http://crbug.com/31628
460   options.ConfigureFlag(SSL_OP_NO_COMPRESSION, !ssl_config_.tls1_enabled);
461 #endif
462 
463   // TODO(joth): Set this conditionally, see http://crbug.com/55410
464   options.ConfigureFlag(SSL_OP_LEGACY_SERVER_CONNECT, true);
465 
466   SSL_set_options(ssl_, options.set_mask);
467   SSL_clear_options(ssl_, options.clear_mask);
468 
469   // Same as above, this time for the SSL mode.
470   SslSetClearMask mode;
471 
472 #if defined(SSL_MODE_HANDSHAKE_CUTTHROUGH)
473   mode.ConfigureFlag(SSL_MODE_HANDSHAKE_CUTTHROUGH,
474                      ssl_config_.false_start_enabled &&
475                      !SSLConfigService::IsKnownFalseStartIncompatibleServer(
476                          host_and_port_.host()));
477 #endif
478 
479 #if defined(SSL_MODE_RELEASE_BUFFERS)
480   mode.ConfigureFlag(SSL_MODE_RELEASE_BUFFERS, true);
481 #endif
482 
483 #if defined(SSL_MODE_SMALL_BUFFERS)
484   mode.ConfigureFlag(SSL_MODE_SMALL_BUFFERS, true);
485 #endif
486 
487   SSL_set_mode(ssl_, mode.set_mask);
488   SSL_clear_mode(ssl_, mode.clear_mask);
489 
490   // Removing ciphers by ID from OpenSSL is a bit involved as we must use the
491   // textual name with SSL_set_cipher_list because there is no public API to
492   // directly remove a cipher by ID.
493   STACK_OF(SSL_CIPHER)* ciphers = SSL_get_ciphers(ssl_);
494   DCHECK(ciphers);
495   // See SSLConfig::disabled_cipher_suites for description of the suites
496   // disabled by default.
497   std::string command("DEFAULT:!NULL:!aNULL:!IDEA:!FZA");
498   // Walk through all the installed ciphers, seeing if any need to be
499   // appended to the cipher removal |command|.
500   for (int i = 0; i < sk_SSL_CIPHER_num(ciphers); ++i) {
501     const SSL_CIPHER* cipher = sk_SSL_CIPHER_value(ciphers, i);
502     const uint16 id = SSL_CIPHER_get_id(cipher);
503     // Remove any ciphers with a strength of less than 80 bits. Note the NSS
504     // implementation uses "effective" bits here but OpenSSL does not provide
505     // this detail. This only impacts Triple DES: reports 112 vs. 168 bits,
506     // both of which are greater than 80 anyway.
507     bool disable = SSL_CIPHER_get_bits(cipher, NULL) < 80;
508     if (!disable) {
509       disable = std::find(ssl_config_.disabled_cipher_suites.begin(),
510                           ssl_config_.disabled_cipher_suites.end(), id) !=
511                     ssl_config_.disabled_cipher_suites.end();
512     }
513     if (disable) {
514        const char* name = SSL_CIPHER_get_name(cipher);
515        DVLOG(3) << "Found cipher to remove: '" << name << "', ID: " << id
516                 << " strength: " << SSL_CIPHER_get_bits(cipher, NULL);
517        command.append(":!");
518        command.append(name);
519      }
520   }
521   int rv = SSL_set_cipher_list(ssl_, command.c_str());
522   // If this fails (rv = 0) it means there are no ciphers enabled on this SSL.
523   // This will almost certainly result in the socket failing to complete the
524   // handshake at which point the appropriate error is bubbled up to the client.
525   LOG_IF(WARNING, rv != 1) << "SSL_set_cipher_list('" << command << "') "
526                               "returned " << rv;
527   return true;
528 }
529 
ClientCertRequestCallback(SSL * ssl,X509 ** x509,EVP_PKEY ** pkey)530 int SSLClientSocketOpenSSL::ClientCertRequestCallback(SSL* ssl,
531                                                       X509** x509,
532                                                       EVP_PKEY** pkey) {
533   DVLOG(3) << "OpenSSL ClientCertRequestCallback called";
534   DCHECK(ssl == ssl_);
535   DCHECK(*x509 == NULL);
536   DCHECK(*pkey == NULL);
537 
538   if (!ssl_config_.send_client_cert) {
539     client_auth_cert_needed_ = true;
540     return -1;  // Suspends handshake.
541   }
542 
543   // Second pass: a client certificate should have been selected.
544   if (ssl_config_.client_cert) {
545     EVP_PKEY* privkey = OpenSSLPrivateKeyStore::GetInstance()->FetchPrivateKey(
546         X509_PUBKEY_get(X509_get_X509_PUBKEY(
547             ssl_config_.client_cert->os_cert_handle())));
548     if (privkey) {
549       CRYPTO_add(&privkey->references, 1, CRYPTO_LOCK_EVP_PKEY);
550       // TODO(joth): (copied from NSS) We should wait for server certificate
551       // verification before sending our credentials. See http://crbug.com/13934
552       *x509 = X509Certificate::DupOSCertHandle(
553           ssl_config_.client_cert->os_cert_handle());
554       *pkey = privkey;
555       return 1;
556     }
557     LOG(WARNING) << "Client cert found without private key";
558   }
559 
560   // Send no client certificate.
561   return 0;
562 }
563 
564 // SSLClientSocket methods
565 
GetSSLInfo(SSLInfo * ssl_info)566 void SSLClientSocketOpenSSL::GetSSLInfo(SSLInfo* ssl_info) {
567   ssl_info->Reset();
568   if (!server_cert_)
569     return;
570 
571   ssl_info->cert = server_cert_;
572   ssl_info->cert_status = server_cert_verify_result_.cert_status;
573   ssl_info->is_issued_by_known_root =
574       server_cert_verify_result_.is_issued_by_known_root;
575   ssl_info->public_key_hashes =
576     server_cert_verify_result_.public_key_hashes;
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_.ssl3_fallback)
595     ssl_info->connection_status |= SSL_CONNECTION_SSL3_FALLBACK;
596 
597   DVLOG(3) << "Encoded connection status: cipher suite = "
598       << SSLConnectionStatusToCipherSuite(ssl_info->connection_status)
599       << " compression = "
600       << SSLConnectionStatusToCompression(ssl_info->connection_status)
601       << " version = "
602       << SSLConnectionStatusToVersion(ssl_info->connection_status);
603 }
604 
GetSSLCertRequestInfo(SSLCertRequestInfo * cert_request_info)605 void SSLClientSocketOpenSSL::GetSSLCertRequestInfo(
606     SSLCertRequestInfo* cert_request_info) {
607   cert_request_info->host_and_port = host_and_port_.ToString();
608   cert_request_info->client_certs = client_certs_;
609 }
610 
GetNextProto(std::string * proto)611 SSLClientSocket::NextProtoStatus SSLClientSocketOpenSSL::GetNextProto(
612     std::string* proto) {
613   *proto = npn_proto_;
614   return npn_status_;
615 }
616 
DoReadCallback(int rv)617 void SSLClientSocketOpenSSL::DoReadCallback(int rv) {
618   // Since Run may result in Read being called, clear |user_read_callback_|
619   // up front.
620   CompletionCallback* c = user_read_callback_;
621   user_read_callback_ = NULL;
622   user_read_buf_ = NULL;
623   user_read_buf_len_ = 0;
624   c->Run(rv);
625 }
626 
DoWriteCallback(int rv)627 void SSLClientSocketOpenSSL::DoWriteCallback(int rv) {
628   // Since Run may result in Write being called, clear |user_write_callback_|
629   // up front.
630   CompletionCallback* c = user_write_callback_;
631   user_write_callback_ = NULL;
632   user_write_buf_ = NULL;
633   user_write_buf_len_ = 0;
634   c->Run(rv);
635 }
636 
637 // ClientSocket methods
638 
639 #ifdef ANDROID
640 // TODO(kristianm): handle the case when wait_for_connect is true
641 // (sync requests)
642 #endif
Connect(CompletionCallback * callback,bool wait_for_connect,bool valid_uid,uid_t calling_uid)643 int SSLClientSocketOpenSSL::Connect(CompletionCallback* callback
644 #ifdef ANDROID
645                                     , bool wait_for_connect
646                                     , bool valid_uid
647                                     , uid_t calling_uid
648 #endif
649                                    ) {
650   net_log_.BeginEvent(NetLog::TYPE_SSL_CONNECT, NULL);
651 
652   // Set up new ssl object.
653   if (!Init()) {
654     int result = ERR_UNEXPECTED;
655     net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, result);
656     return result;
657   }
658 
659   // Set SSL to client mode. Handshake happens in the loop below.
660   SSL_set_connect_state(ssl_);
661 
662   GotoState(STATE_HANDSHAKE);
663   int rv = DoHandshakeLoop(net::OK);
664   if (rv == ERR_IO_PENDING) {
665     user_connect_callback_ = callback;
666   } else {
667     net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
668   }
669 
670   return rv > OK ? OK : rv;
671 }
672 
Disconnect()673 void SSLClientSocketOpenSSL::Disconnect() {
674   if (ssl_) {
675     SSL_free(ssl_);
676     ssl_ = NULL;
677   }
678   if (transport_bio_) {
679     BIO_free_all(transport_bio_);
680     transport_bio_ = NULL;
681   }
682 
683   // Shut down anything that may call us back (through buffer_send_callback_,
684   // buffer_recv_callback, or handshake_io_callback_).
685   verifier_.reset();
686   transport_->socket()->Disconnect();
687 
688   // Null all callbacks, delete all buffers.
689   transport_send_busy_ = false;
690   send_buffer_ = NULL;
691   transport_recv_busy_ = false;
692   recv_buffer_ = NULL;
693 
694   user_connect_callback_ = NULL;
695   user_read_callback_    = NULL;
696   user_write_callback_   = NULL;
697   user_read_buf_         = NULL;
698   user_read_buf_len_     = 0;
699   user_write_buf_        = NULL;
700   user_write_buf_len_    = 0;
701 
702   server_cert_verify_result_.Reset();
703   completed_handshake_ = false;
704 
705   client_certs_.clear();
706   client_auth_cert_needed_ = false;
707 }
708 
DoHandshakeLoop(int last_io_result)709 int SSLClientSocketOpenSSL::DoHandshakeLoop(int last_io_result) {
710   bool network_moved;
711   int rv = last_io_result;
712   do {
713     // Default to STATE_NONE for next state.
714     // (This is a quirk carried over from the windows
715     // implementation.  It makes reading the logs a bit harder.)
716     // State handlers can and often do call GotoState just
717     // to stay in the current state.
718     State state = next_handshake_state_;
719     GotoState(STATE_NONE);
720     switch (state) {
721       case STATE_NONE:
722         // we're just pumping data between the buffer and the network
723         break;
724       case STATE_HANDSHAKE:
725         rv = DoHandshake();
726         break;
727       case STATE_VERIFY_CERT:
728         DCHECK(rv == OK);
729         rv = DoVerifyCert(rv);
730        break;
731       case STATE_VERIFY_CERT_COMPLETE:
732         rv = DoVerifyCertComplete(rv);
733         break;
734       default:
735         rv = ERR_UNEXPECTED;
736         NOTREACHED() << "unexpected state" << state;
737         break;
738     }
739 
740     // To avoid getting an ERR_IO_PENDING here after handshake complete.
741     if (next_handshake_state_ == STATE_NONE)
742       break;
743 
744     // Do the actual network I/O.
745     network_moved = DoTransportIO();
746   } while ((rv != ERR_IO_PENDING || network_moved) &&
747             next_handshake_state_ != STATE_NONE);
748   return rv;
749 }
750 
DoHandshake()751 int SSLClientSocketOpenSSL::DoHandshake() {
752   crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
753   int net_error = net::OK;
754   int rv = SSL_do_handshake(ssl_);
755 
756   if (client_auth_cert_needed_) {
757     net_error = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
758     // If the handshake already succeeded (because the server requests but
759     // doesn't require a client cert), we need to invalidate the SSL session
760     // so that we won't try to resume the non-client-authenticated session in
761     // the next handshake.  This will cause the server to ask for a client
762     // cert again.
763     if (rv == 1) {
764       // Remove from session cache but don't clear this connection.
765       SSL_SESSION* session = SSL_get_session(ssl_);
766       if (session) {
767         int rv = SSL_CTX_remove_session(SSL_get_SSL_CTX(ssl_), session);
768         LOG_IF(WARNING, !rv) << "Couldn't invalidate SSL session: " << session;
769       }
770     }
771   } else if (rv == 1) {
772     if (trying_cached_session_ && logging::DEBUG_MODE) {
773       DVLOG(2) << "Result of session reuse for " << host_and_port_.ToString()
774                << " is: " << (SSL_session_reused(ssl_) ? "Success" : "Fail");
775     }
776     // SSL handshake is completed.  Let's verify the certificate.
777     const bool got_cert = !!UpdateServerCert();
778     DCHECK(got_cert);
779     GotoState(STATE_VERIFY_CERT);
780   } else {
781     int ssl_error = SSL_get_error(ssl_, rv);
782     net_error = MapOpenSSLError(ssl_error, err_tracer);
783 
784     // If not done, stay in this state
785     if (net_error == ERR_IO_PENDING) {
786       GotoState(STATE_HANDSHAKE);
787     } else {
788       LOG(ERROR) << "handshake failed; returned " << rv
789                  << ", SSL error code " << ssl_error
790                  << ", net_error " << net_error;
791       net_log_.AddEvent(
792           NetLog::TYPE_SSL_HANDSHAKE_ERROR,
793           make_scoped_refptr(new SSLErrorParams(net_error, ssl_error)));
794     }
795   }
796   return net_error;
797 }
798 
SelectNextProtoCallback(unsigned char ** out,unsigned char * outlen,const unsigned char * in,unsigned int inlen)799 int SSLClientSocketOpenSSL::SelectNextProtoCallback(unsigned char** out,
800                                                     unsigned char* outlen,
801                                                     const unsigned char* in,
802                                                     unsigned int inlen) {
803 #if defined(OPENSSL_NPN_NEGOTIATED)
804   if (ssl_config_.next_protos.empty()) {
805     *out = reinterpret_cast<uint8*>(const_cast<char*>("http/1.1"));
806     *outlen = 8;
807     npn_status_ = SSLClientSocket::kNextProtoUnsupported;
808     return SSL_TLSEXT_ERR_OK;
809   }
810 
811   int status = SSL_select_next_proto(
812       out, outlen, in, inlen,
813       reinterpret_cast<const unsigned char*>(ssl_config_.next_protos.data()),
814       ssl_config_.next_protos.size());
815 
816   npn_proto_.assign(reinterpret_cast<const char*>(*out), *outlen);
817   switch (status) {
818     case OPENSSL_NPN_UNSUPPORTED:
819       npn_status_ = SSLClientSocket::kNextProtoUnsupported;
820       break;
821     case OPENSSL_NPN_NEGOTIATED:
822       npn_status_ = SSLClientSocket::kNextProtoNegotiated;
823       break;
824     case OPENSSL_NPN_NO_OVERLAP:
825       npn_status_ = SSLClientSocket::kNextProtoNoOverlap;
826       break;
827     default:
828       NOTREACHED() << status;
829       break;
830   }
831   DVLOG(2) << "next protocol: '" << npn_proto_ << "' status: " << npn_status_;
832 #endif
833   return SSL_TLSEXT_ERR_OK;
834 }
835 
DoVerifyCert(int result)836 int SSLClientSocketOpenSSL::DoVerifyCert(int result) {
837   DCHECK(server_cert_);
838   GotoState(STATE_VERIFY_CERT_COMPLETE);
839   int flags = 0;
840 
841   if (ssl_config_.rev_checking_enabled)
842     flags |= X509Certificate::VERIFY_REV_CHECKING_ENABLED;
843   if (ssl_config_.verify_ev_cert)
844     flags |= X509Certificate::VERIFY_EV_CERT;
845   verifier_.reset(new SingleRequestCertVerifier(cert_verifier_));
846   return verifier_->Verify(server_cert_, host_and_port_.host(), flags,
847                            &server_cert_verify_result_,
848                            &handshake_io_callback_);
849 }
850 
DoVerifyCertComplete(int result)851 int SSLClientSocketOpenSSL::DoVerifyCertComplete(int result) {
852   verifier_.reset();
853 
854   if (result == OK) {
855     // TODO(joth): Work out if we need to remember the intermediate CA certs
856     // when the server sends them to us, and do so here.
857   } else {
858     DVLOG(1) << "DoVerifyCertComplete error " << ErrorToString(result)
859              << " (" << result << ")";
860   }
861 
862   // If we have been explicitly told to accept this certificate, override the
863   // result of verifier_.Verify.
864   // Eventually, we should cache the cert verification results so that we don't
865   // need to call verifier_.Verify repeatedly.  But for now we need to do this.
866   // Alternatively, we could use the cert's status that we stored along with
867   // the cert in the allowed_bad_certs vector.
868   if (IsCertificateError(result) &&
869       ssl_config_.IsAllowedBadCert(server_cert_)) {
870     VLOG(1) << "accepting bad SSL certificate, as user told us to";
871     result = OK;
872   }
873 
874   completed_handshake_ = true;
875   // Exit DoHandshakeLoop and return the result to the caller to Connect.
876   DCHECK_EQ(STATE_NONE, next_handshake_state_);
877   return result;
878 }
879 
UpdateServerCert()880 X509Certificate* SSLClientSocketOpenSSL::UpdateServerCert() {
881   if (server_cert_)
882     return server_cert_;
883 
884   crypto::ScopedOpenSSL<X509, X509_free> cert(SSL_get_peer_certificate(ssl_));
885   if (!cert.get()) {
886     LOG(WARNING) << "SSL_get_peer_certificate returned NULL";
887     return NULL;
888   }
889 
890   // Unlike SSL_get_peer_certificate, SSL_get_peer_cert_chain does not
891   // increment the reference so sk_X509_free does not need to be called.
892   STACK_OF(X509)* chain = SSL_get_peer_cert_chain(ssl_);
893   X509Certificate::OSCertHandles intermediates;
894   if (chain) {
895     for (int i = 0; i < sk_X509_num(chain); ++i)
896       intermediates.push_back(sk_X509_value(chain, i));
897   }
898   server_cert_ = X509Certificate::CreateFromHandle(
899       cert.get(), X509Certificate::SOURCE_FROM_NETWORK, intermediates);
900   DCHECK(server_cert_);
901 
902   return server_cert_;
903 }
904 
DoTransportIO()905 bool SSLClientSocketOpenSSL::DoTransportIO() {
906   bool network_moved = false;
907   int nsent = BufferSend();
908   int nreceived = BufferRecv();
909   network_moved = (nsent > 0 || nreceived >= 0);
910   return network_moved;
911 }
912 
BufferSend(void)913 int SSLClientSocketOpenSSL::BufferSend(void) {
914   if (transport_send_busy_)
915     return ERR_IO_PENDING;
916 
917   if (!send_buffer_) {
918     // Get a fresh send buffer out of the send BIO.
919     size_t max_read = BIO_ctrl_pending(transport_bio_);
920     if (max_read > 0) {
921       send_buffer_ = new DrainableIOBuffer(new IOBuffer(max_read), max_read);
922       int read_bytes = BIO_read(transport_bio_, send_buffer_->data(), max_read);
923       DCHECK_GT(read_bytes, 0);
924       CHECK_EQ(static_cast<int>(max_read), read_bytes);
925     }
926   }
927 
928   int rv = 0;
929   while (send_buffer_) {
930     rv = transport_->socket()->Write(send_buffer_,
931                                      send_buffer_->BytesRemaining(),
932                                      &buffer_send_callback_);
933     if (rv == ERR_IO_PENDING) {
934       transport_send_busy_ = true;
935       return rv;
936     }
937     TransportWriteComplete(rv);
938   }
939   return rv;
940 }
941 
BufferSendComplete(int result)942 void SSLClientSocketOpenSSL::BufferSendComplete(int result) {
943   transport_send_busy_ = false;
944   TransportWriteComplete(result);
945   OnSendComplete(result);
946 }
947 
TransportWriteComplete(int result)948 void SSLClientSocketOpenSSL::TransportWriteComplete(int result) {
949   DCHECK(ERR_IO_PENDING != result);
950   if (result < 0) {
951     // Got a socket write error; close the BIO to indicate this upward.
952     DVLOG(1) << "TransportWriteComplete error " << result;
953     (void)BIO_shutdown_wr(transport_bio_);
954     send_buffer_ = NULL;
955   } else {
956     DCHECK(send_buffer_);
957     send_buffer_->DidConsume(result);
958     DCHECK_GE(send_buffer_->BytesRemaining(), 0);
959     if (send_buffer_->BytesRemaining() <= 0)
960       send_buffer_ = NULL;
961   }
962 }
963 
BufferRecv(void)964 int SSLClientSocketOpenSSL::BufferRecv(void) {
965   if (transport_recv_busy_)
966     return ERR_IO_PENDING;
967 
968   size_t max_write = BIO_ctrl_get_write_guarantee(transport_bio_);
969   if (max_write > kMaxRecvBufferSize)
970     max_write = kMaxRecvBufferSize;
971 
972   if (!max_write)
973     return ERR_IO_PENDING;
974 
975   recv_buffer_ = new IOBuffer(max_write);
976   int rv = transport_->socket()->Read(recv_buffer_, max_write,
977                                       &buffer_recv_callback_);
978   if (rv == ERR_IO_PENDING) {
979     transport_recv_busy_ = true;
980   } else {
981     TransportReadComplete(rv);
982   }
983   return rv;
984 }
985 
BufferRecvComplete(int result)986 void SSLClientSocketOpenSSL::BufferRecvComplete(int result) {
987   TransportReadComplete(result);
988   OnRecvComplete(result);
989 }
990 
TransportReadComplete(int result)991 void SSLClientSocketOpenSSL::TransportReadComplete(int result) {
992   DCHECK(ERR_IO_PENDING != result);
993   if (result <= 0) {
994     DVLOG(1) << "TransportReadComplete result " << result;
995     // Received 0 (end of file) or an error. Either way, bubble it up to the
996     // SSL layer via the BIO. TODO(joth): consider stashing the error code, to
997     // relay up to the SSL socket client (i.e. via DoReadCallback).
998     BIO_set_mem_eof_return(transport_bio_, 0);
999     (void)BIO_shutdown_wr(transport_bio_);
1000   } else {
1001     DCHECK(recv_buffer_);
1002     int ret = BIO_write(transport_bio_, recv_buffer_->data(), result);
1003     // A write into a memory BIO should always succeed.
1004     CHECK_EQ(result, ret);
1005   }
1006   recv_buffer_ = NULL;
1007   transport_recv_busy_ = false;
1008 }
1009 
DoConnectCallback(int rv)1010 void SSLClientSocketOpenSSL::DoConnectCallback(int rv) {
1011   CompletionCallback* c = user_connect_callback_;
1012   user_connect_callback_ = NULL;
1013   c->Run(rv > OK ? OK : rv);
1014 }
1015 
OnHandshakeIOComplete(int result)1016 void SSLClientSocketOpenSSL::OnHandshakeIOComplete(int result) {
1017   int rv = DoHandshakeLoop(result);
1018   if (rv != ERR_IO_PENDING) {
1019     net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
1020     DoConnectCallback(rv);
1021   }
1022 }
1023 
OnSendComplete(int result)1024 void SSLClientSocketOpenSSL::OnSendComplete(int result) {
1025   if (next_handshake_state_ != STATE_NONE) {
1026     // In handshake phase.
1027     OnHandshakeIOComplete(result);
1028     return;
1029   }
1030 
1031   // OnSendComplete may need to call DoPayloadRead while the renegotiation
1032   // handshake is in progress.
1033   int rv_read = ERR_IO_PENDING;
1034   int rv_write = ERR_IO_PENDING;
1035   bool network_moved;
1036   do {
1037       if (user_read_buf_)
1038           rv_read = DoPayloadRead();
1039       if (user_write_buf_)
1040           rv_write = DoPayloadWrite();
1041       network_moved = DoTransportIO();
1042   } while (rv_read == ERR_IO_PENDING &&
1043            rv_write == ERR_IO_PENDING &&
1044            network_moved);
1045 
1046   if (user_read_buf_ && rv_read != ERR_IO_PENDING)
1047       DoReadCallback(rv_read);
1048   if (user_write_buf_ && rv_write != ERR_IO_PENDING)
1049       DoWriteCallback(rv_write);
1050 }
1051 
OnRecvComplete(int result)1052 void SSLClientSocketOpenSSL::OnRecvComplete(int result) {
1053   if (next_handshake_state_ != STATE_NONE) {
1054     // In handshake phase.
1055     OnHandshakeIOComplete(result);
1056     return;
1057   }
1058 
1059   // Network layer received some data, check if client requested to read
1060   // decrypted data.
1061   if (!user_read_buf_)
1062     return;
1063 
1064   int rv = DoReadLoop(result);
1065   if (rv != ERR_IO_PENDING)
1066     DoReadCallback(rv);
1067 }
1068 
IsConnected() const1069 bool SSLClientSocketOpenSSL::IsConnected() const {
1070   bool ret = completed_handshake_ && transport_->socket()->IsConnected();
1071   return ret;
1072 }
1073 
IsConnectedAndIdle() const1074 bool SSLClientSocketOpenSSL::IsConnectedAndIdle() const {
1075   bool ret = completed_handshake_ && transport_->socket()->IsConnectedAndIdle();
1076   return ret;
1077 }
1078 
GetPeerAddress(AddressList * addressList) const1079 int SSLClientSocketOpenSSL::GetPeerAddress(AddressList* addressList) const {
1080   return transport_->socket()->GetPeerAddress(addressList);
1081 }
1082 
GetLocalAddress(IPEndPoint * addressList) const1083 int SSLClientSocketOpenSSL::GetLocalAddress(IPEndPoint* addressList) const {
1084   return transport_->socket()->GetLocalAddress(addressList);
1085 }
1086 
NetLog() const1087 const BoundNetLog& SSLClientSocketOpenSSL::NetLog() const {
1088   return net_log_;
1089 }
1090 
SetSubresourceSpeculation()1091 void SSLClientSocketOpenSSL::SetSubresourceSpeculation() {
1092   if (transport_.get() && transport_->socket()) {
1093     transport_->socket()->SetSubresourceSpeculation();
1094   } else {
1095     NOTREACHED();
1096   }
1097 }
1098 
SetOmniboxSpeculation()1099 void SSLClientSocketOpenSSL::SetOmniboxSpeculation() {
1100   if (transport_.get() && transport_->socket()) {
1101     transport_->socket()->SetOmniboxSpeculation();
1102   } else {
1103     NOTREACHED();
1104   }
1105 }
1106 
WasEverUsed() const1107 bool SSLClientSocketOpenSSL::WasEverUsed() const {
1108   if (transport_.get() && transport_->socket())
1109     return transport_->socket()->WasEverUsed();
1110 
1111   NOTREACHED();
1112   return false;
1113 }
1114 
UsingTCPFastOpen() const1115 bool SSLClientSocketOpenSSL::UsingTCPFastOpen() const {
1116   if (transport_.get() && transport_->socket())
1117     return transport_->socket()->UsingTCPFastOpen();
1118 
1119   NOTREACHED();
1120   return false;
1121 }
1122 
1123 // Socket methods
1124 
Read(IOBuffer * buf,int buf_len,CompletionCallback * callback)1125 int SSLClientSocketOpenSSL::Read(IOBuffer* buf,
1126                                  int buf_len,
1127                                  CompletionCallback* callback) {
1128   user_read_buf_ = buf;
1129   user_read_buf_len_ = buf_len;
1130 
1131   int rv = DoReadLoop(OK);
1132 
1133   if (rv == ERR_IO_PENDING) {
1134     user_read_callback_ = callback;
1135   } else {
1136     user_read_buf_ = NULL;
1137     user_read_buf_len_ = 0;
1138   }
1139 
1140   return rv;
1141 }
1142 
DoReadLoop(int result)1143 int SSLClientSocketOpenSSL::DoReadLoop(int result) {
1144   if (result < 0)
1145     return result;
1146 
1147   bool network_moved;
1148   int rv;
1149   do {
1150     rv = DoPayloadRead();
1151     network_moved = DoTransportIO();
1152   } while (rv == ERR_IO_PENDING && network_moved);
1153 
1154   return rv;
1155 }
1156 
Write(IOBuffer * buf,int buf_len,CompletionCallback * callback)1157 int SSLClientSocketOpenSSL::Write(IOBuffer* buf,
1158                                   int buf_len,
1159                                   CompletionCallback* callback) {
1160   user_write_buf_ = buf;
1161   user_write_buf_len_ = buf_len;
1162 
1163   int rv = DoWriteLoop(OK);
1164 
1165   if (rv == ERR_IO_PENDING) {
1166     user_write_callback_ = callback;
1167   } else {
1168     user_write_buf_ = NULL;
1169     user_write_buf_len_ = 0;
1170   }
1171 
1172   return rv;
1173 }
1174 
DoWriteLoop(int result)1175 int SSLClientSocketOpenSSL::DoWriteLoop(int result) {
1176   if (result < 0)
1177     return result;
1178 
1179   bool network_moved;
1180   int rv;
1181   do {
1182     rv = DoPayloadWrite();
1183     network_moved = DoTransportIO();
1184   } while (rv == ERR_IO_PENDING && network_moved);
1185 
1186   return rv;
1187 }
1188 
SetReceiveBufferSize(int32 size)1189 bool SSLClientSocketOpenSSL::SetReceiveBufferSize(int32 size) {
1190   return transport_->socket()->SetReceiveBufferSize(size);
1191 }
1192 
SetSendBufferSize(int32 size)1193 bool SSLClientSocketOpenSSL::SetSendBufferSize(int32 size) {
1194   return transport_->socket()->SetSendBufferSize(size);
1195 }
1196 
DoPayloadRead()1197 int SSLClientSocketOpenSSL::DoPayloadRead() {
1198   crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1199   int rv = SSL_read(ssl_, user_read_buf_->data(), user_read_buf_len_);
1200   // We don't need to invalidate the non-client-authenticated SSL session
1201   // because the server will renegotiate anyway.
1202   if (client_auth_cert_needed_)
1203     return ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
1204 
1205   if (rv >= 0)
1206     return rv;
1207 
1208   int err = SSL_get_error(ssl_, rv);
1209   return MapOpenSSLError(err, err_tracer);
1210 }
1211 
DoPayloadWrite()1212 int SSLClientSocketOpenSSL::DoPayloadWrite() {
1213   crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1214   int rv = SSL_write(ssl_, user_write_buf_->data(), user_write_buf_len_);
1215 
1216   if (rv >= 0)
1217     return rv;
1218 
1219   int err = SSL_get_error(ssl_, rv);
1220   return MapOpenSSLError(err, err_tracer);
1221 }
1222 
1223 }  // namespace net
1224