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