- add sources.
[platform/framework/web/crosswalk.git] / src / net / socket / ssl_client_socket_openssl.cc
1 // Copyright (c) 2012 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/err.h>
11 #include <openssl/opensslv.h>
12 #include <openssl/ssl.h>
13
14 #include "base/bind.h"
15 #include "base/callback_helpers.h"
16 #include "base/memory/singleton.h"
17 #include "base/metrics/histogram.h"
18 #include "base/synchronization/lock.h"
19 #include "crypto/ec_private_key.h"
20 #include "crypto/openssl_util.h"
21 #include "net/base/net_errors.h"
22 #include "net/cert/cert_verifier.h"
23 #include "net/cert/single_request_cert_verifier.h"
24 #include "net/cert/x509_certificate_net_log_param.h"
25 #include "net/socket/ssl_error_params.h"
26 #include "net/ssl/openssl_client_key_store.h"
27 #include "net/ssl/ssl_cert_request_info.h"
28 #include "net/ssl/ssl_connection_status_flags.h"
29 #include "net/ssl/ssl_info.h"
30
31 namespace net {
32
33 namespace {
34
35 // Enable this to see logging for state machine state transitions.
36 #if 0
37 #define GotoState(s) do { DVLOG(2) << (void *)this << " " << __FUNCTION__ << \
38                            " jump to state " << s; \
39                            next_handshake_state_ = s; } while (0)
40 #else
41 #define GotoState(s) next_handshake_state_ = s
42 #endif
43
44 const int kSessionCacheTimeoutSeconds = 60 * 60;
45 const size_t kSessionCacheMaxEntires = 1024;
46
47 // This constant can be any non-negative/non-zero value (eg: it does not
48 // overlap with any value of the net::Error range, including net::OK).
49 const int kNoPendingReadResult = 1;
50
51 // If a client doesn't have a list of protocols that it supports, but
52 // the server supports NPN, choosing "http/1.1" is the best answer.
53 const char kDefaultSupportedNPNProtocol[] = "http/1.1";
54
55 #if OPENSSL_VERSION_NUMBER < 0x1000103fL
56 // This method doesn't seem to have made it into the OpenSSL headers.
57 unsigned long SSL_CIPHER_get_id(const SSL_CIPHER* cipher) { return cipher->id; }
58 #endif
59
60 // Used for encoding the |connection_status| field of an SSLInfo object.
61 int EncodeSSLConnectionStatus(int cipher_suite,
62                               int compression,
63                               int version) {
64   return ((cipher_suite & SSL_CONNECTION_CIPHERSUITE_MASK) <<
65           SSL_CONNECTION_CIPHERSUITE_SHIFT) |
66          ((compression & SSL_CONNECTION_COMPRESSION_MASK) <<
67           SSL_CONNECTION_COMPRESSION_SHIFT) |
68          ((version & SSL_CONNECTION_VERSION_MASK) <<
69           SSL_CONNECTION_VERSION_SHIFT);
70 }
71
72 // Returns the net SSL version number (see ssl_connection_status_flags.h) for
73 // this SSL connection.
74 int GetNetSSLVersion(SSL* ssl) {
75   switch (SSL_version(ssl)) {
76     case SSL2_VERSION:
77       return SSL_CONNECTION_VERSION_SSL2;
78     case SSL3_VERSION:
79       return SSL_CONNECTION_VERSION_SSL3;
80     case TLS1_VERSION:
81       return SSL_CONNECTION_VERSION_TLS1;
82     case 0x0302:
83       return SSL_CONNECTION_VERSION_TLS1_1;
84     case 0x0303:
85       return SSL_CONNECTION_VERSION_TLS1_2;
86     default:
87       return SSL_CONNECTION_VERSION_UNKNOWN;
88   }
89 }
90
91 int MapOpenSSLErrorSSL() {
92   // Walk down the error stack to find the SSLerr generated reason.
93   unsigned long error_code;
94   do {
95     error_code = ERR_get_error();
96     if (error_code == 0)
97       return ERR_SSL_PROTOCOL_ERROR;
98   } while (ERR_GET_LIB(error_code) != ERR_LIB_SSL);
99
100   DVLOG(1) << "OpenSSL SSL error, reason: " << ERR_GET_REASON(error_code)
101            << ", name: " << ERR_error_string(error_code, NULL);
102   switch (ERR_GET_REASON(error_code)) {
103     case SSL_R_READ_TIMEOUT_EXPIRED:
104       return ERR_TIMED_OUT;
105     case SSL_R_BAD_RESPONSE_ARGUMENT:
106       return ERR_INVALID_ARGUMENT;
107     case SSL_R_UNKNOWN_CERTIFICATE_TYPE:
108     case SSL_R_UNKNOWN_CIPHER_TYPE:
109     case SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE:
110     case SSL_R_UNKNOWN_PKEY_TYPE:
111     case SSL_R_UNKNOWN_REMOTE_ERROR_TYPE:
112     case SSL_R_UNKNOWN_SSL_VERSION:
113       return ERR_NOT_IMPLEMENTED;
114     case SSL_R_UNSUPPORTED_SSL_VERSION:
115     case SSL_R_NO_CIPHER_MATCH:
116     case SSL_R_NO_SHARED_CIPHER:
117     case SSL_R_TLSV1_ALERT_INSUFFICIENT_SECURITY:
118     case SSL_R_TLSV1_ALERT_PROTOCOL_VERSION:
119     case SSL_R_UNSUPPORTED_PROTOCOL:
120       return ERR_SSL_VERSION_OR_CIPHER_MISMATCH;
121     case SSL_R_SSLV3_ALERT_BAD_CERTIFICATE:
122     case SSL_R_SSLV3_ALERT_UNSUPPORTED_CERTIFICATE:
123     case SSL_R_SSLV3_ALERT_CERTIFICATE_REVOKED:
124     case SSL_R_SSLV3_ALERT_CERTIFICATE_EXPIRED:
125     case SSL_R_SSLV3_ALERT_CERTIFICATE_UNKNOWN:
126     case SSL_R_TLSV1_ALERT_ACCESS_DENIED:
127     case SSL_R_TLSV1_ALERT_UNKNOWN_CA:
128       return ERR_BAD_SSL_CLIENT_AUTH_CERT;
129     case SSL_R_BAD_DECOMPRESSION:
130     case SSL_R_SSLV3_ALERT_DECOMPRESSION_FAILURE:
131       return ERR_SSL_DECOMPRESSION_FAILURE_ALERT;
132     case SSL_R_SSLV3_ALERT_BAD_RECORD_MAC:
133       return ERR_SSL_BAD_RECORD_MAC_ALERT;
134     case SSL_R_TLSV1_ALERT_DECRYPT_ERROR:
135       return ERR_SSL_DECRYPT_ERROR_ALERT;
136     case SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED:
137       return ERR_SSL_UNSAFE_NEGOTIATION;
138     case SSL_R_WRONG_NUMBER_OF_KEY_BITS:
139       return ERR_SSL_WEAK_SERVER_EPHEMERAL_DH_KEY;
140     // SSL_R_UNKNOWN_PROTOCOL is reported if premature application data is
141     // received (see http://crbug.com/42538), and also if all the protocol
142     // versions supported by the server were disabled in this socket instance.
143     // Mapped to ERR_SSL_PROTOCOL_ERROR for compatibility with other SSL sockets
144     // in the former scenario.
145     case SSL_R_UNKNOWN_PROTOCOL:
146     case SSL_R_SSL_HANDSHAKE_FAILURE:
147     case SSL_R_DECRYPTION_FAILED:
148     case SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC:
149     case SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG:
150     case SSL_R_DIGEST_CHECK_FAILED:
151     case SSL_R_DUPLICATE_COMPRESSION_ID:
152     case SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER:
153     case SSL_R_ENCRYPTED_LENGTH_TOO_LONG:
154     case SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST:
155     case SSL_R_EXCESSIVE_MESSAGE_SIZE:
156     case SSL_R_EXTRA_DATA_IN_MESSAGE:
157     case SSL_R_GOT_A_FIN_BEFORE_A_CCS:
158     case SSL_R_ILLEGAL_PADDING:
159     case SSL_R_INVALID_CHALLENGE_LENGTH:
160     case SSL_R_INVALID_COMMAND:
161     case SSL_R_INVALID_PURPOSE:
162     case SSL_R_INVALID_STATUS_RESPONSE:
163     case SSL_R_INVALID_TICKET_KEYS_LENGTH:
164     case SSL_R_KEY_ARG_TOO_LONG:
165     case SSL_R_READ_WRONG_PACKET_TYPE:
166     case SSL_R_SSLV3_ALERT_UNEXPECTED_MESSAGE:
167     // TODO(joth): SSL_R_SSLV3_ALERT_HANDSHAKE_FAILURE may be returned from the
168     // server after receiving ClientHello if there's no common supported cipher.
169     // Ideally we'd map that specific case to ERR_SSL_VERSION_OR_CIPHER_MISMATCH
170     // to match the NSS implementation. See also http://goo.gl/oMtZW
171     case SSL_R_SSLV3_ALERT_HANDSHAKE_FAILURE:
172     case SSL_R_SSLV3_ALERT_NO_CERTIFICATE:
173     case SSL_R_SSLV3_ALERT_ILLEGAL_PARAMETER:
174     case SSL_R_TLSV1_ALERT_DECODE_ERROR:
175     case SSL_R_TLSV1_ALERT_DECRYPTION_FAILED:
176     case SSL_R_TLSV1_ALERT_EXPORT_RESTRICTION:
177     case SSL_R_TLSV1_ALERT_INTERNAL_ERROR:
178     case SSL_R_TLSV1_ALERT_NO_RENEGOTIATION:
179     case SSL_R_TLSV1_ALERT_RECORD_OVERFLOW:
180     case SSL_R_TLSV1_ALERT_USER_CANCELLED:
181       return ERR_SSL_PROTOCOL_ERROR;
182     default:
183       LOG(WARNING) << "Unmapped error reason: " << ERR_GET_REASON(error_code);
184       return ERR_FAILED;
185   }
186 }
187
188 // Converts an OpenSSL error code into a net error code, walking the OpenSSL
189 // error stack if needed. Note that |tracer| is not currently used in the
190 // implementation, but is passed in anyway as this ensures the caller will clear
191 // any residual codes left on the error stack.
192 int MapOpenSSLError(int err, const crypto::OpenSSLErrStackTracer& tracer) {
193   switch (err) {
194     case SSL_ERROR_WANT_READ:
195     case SSL_ERROR_WANT_WRITE:
196       return ERR_IO_PENDING;
197     case SSL_ERROR_SYSCALL:
198       LOG(ERROR) << "OpenSSL SYSCALL error, earliest error code in "
199                     "error queue: " << ERR_peek_error() << ", errno: "
200                  << errno;
201       return ERR_SSL_PROTOCOL_ERROR;
202     case SSL_ERROR_SSL:
203       return MapOpenSSLErrorSSL();
204     default:
205       // TODO(joth): Implement full mapping.
206       LOG(WARNING) << "Unknown OpenSSL error " << err;
207       return ERR_SSL_PROTOCOL_ERROR;
208   }
209 }
210
211 // We do certificate verification after handshake, so we disable the default
212 // by registering a no-op verify function.
213 int NoOpVerifyCallback(X509_STORE_CTX*, void *) {
214   DVLOG(3) << "skipping cert verify";
215   return 1;
216 }
217
218 // OpenSSL manages a cache of SSL_SESSION, this class provides the application
219 // side policy for that cache about session re-use: we retain one session per
220 // unique HostPortPair, per shard.
221 class SSLSessionCache {
222  public:
223   SSLSessionCache() {}
224
225   void OnSessionAdded(const HostPortPair& host_and_port,
226                       const std::string& shard,
227                       SSL_SESSION* session) {
228     // Declare the session cleaner-upper before the lock, so any call into
229     // OpenSSL to free the session will happen after the lock is released.
230     crypto::ScopedOpenSSL<SSL_SESSION, SSL_SESSION_free> session_to_free;
231     base::AutoLock lock(lock_);
232
233     DCHECK_EQ(0U, session_map_.count(session));
234     const std::string cache_key = GetCacheKey(host_and_port, shard);
235
236     std::pair<HostPortMap::iterator, bool> res =
237         host_port_map_.insert(std::make_pair(cache_key, session));
238     if (!res.second) {  // Already exists: replace old entry.
239       session_to_free.reset(res.first->second);
240       session_map_.erase(session_to_free.get());
241       res.first->second = session;
242     }
243     DVLOG(2) << "Adding session " << session << " => "
244              << cache_key << ", new entry = " << res.second;
245     DCHECK(host_port_map_[cache_key] == session);
246     session_map_[session] = res.first;
247     DCHECK_EQ(host_port_map_.size(), session_map_.size());
248     DCHECK_LE(host_port_map_.size(), kSessionCacheMaxEntires);
249   }
250
251   void OnSessionRemoved(SSL_SESSION* session) {
252     // Declare the session cleaner-upper before the lock, so any call into
253     // OpenSSL to free the session will happen after the lock is released.
254     crypto::ScopedOpenSSL<SSL_SESSION, SSL_SESSION_free> session_to_free;
255     base::AutoLock lock(lock_);
256
257     SessionMap::iterator it = session_map_.find(session);
258     if (it == session_map_.end())
259       return;
260     DVLOG(2) << "Remove session " << session << " => " << it->second->first;
261     DCHECK(it->second->second == session);
262     host_port_map_.erase(it->second);
263     session_map_.erase(it);
264     session_to_free.reset(session);
265     DCHECK_EQ(host_port_map_.size(), session_map_.size());
266   }
267
268   // Looks up the host:port in the cache, and if a session is found it is added
269   // to |ssl|, returning true on success.
270   bool SetSSLSession(SSL* ssl, const HostPortPair& host_and_port,
271                      const std::string& shard) {
272     base::AutoLock lock(lock_);
273     const std::string cache_key = GetCacheKey(host_and_port, shard);
274     HostPortMap::iterator it = host_port_map_.find(cache_key);
275     if (it == host_port_map_.end())
276       return false;
277     DVLOG(2) << "Lookup session: " << it->second << " => " << cache_key;
278     SSL_SESSION* session = it->second;
279     DCHECK(session);
280     DCHECK(session_map_[session] == it);
281     // Ideally we'd release |lock_| before calling into OpenSSL here, however
282     // that opens a small risk |session| will go out of scope before it is used.
283     // Alternatively we would take a temporary local refcount on |session|,
284     // except OpenSSL does not provide a public API for adding a ref (c.f.
285     // SSL_SESSION_free which decrements the ref).
286     return SSL_set_session(ssl, session) == 1;
287   }
288
289   // Flush removes all entries from the cache. This is called when a client
290   // certificate is added.
291   void Flush() {
292     for (HostPortMap::iterator i = host_port_map_.begin();
293          i != host_port_map_.end(); i++) {
294       SSL_SESSION_free(i->second);
295     }
296     host_port_map_.clear();
297     session_map_.clear();
298   }
299
300  private:
301   static std::string GetCacheKey(const HostPortPair& host_and_port,
302                                  const std::string& shard) {
303     return host_and_port.ToString() + "/" + shard;
304   }
305
306   // A pair of maps to allow bi-directional lookups between host:port and an
307   // associated session.
308   typedef std::map<std::string, SSL_SESSION*> HostPortMap;
309   typedef std::map<SSL_SESSION*, HostPortMap::iterator> SessionMap;
310   HostPortMap host_port_map_;
311   SessionMap session_map_;
312
313   // Protects access to both the above maps.
314   base::Lock lock_;
315
316   DISALLOW_COPY_AND_ASSIGN(SSLSessionCache);
317 };
318
319 class SSLContext {
320  public:
321   static SSLContext* GetInstance() { return Singleton<SSLContext>::get(); }
322   SSL_CTX* ssl_ctx() { return ssl_ctx_.get(); }
323   SSLSessionCache* session_cache() { return &session_cache_; }
324
325   SSLClientSocketOpenSSL* GetClientSocketFromSSL(SSL* ssl) {
326     DCHECK(ssl);
327     SSLClientSocketOpenSSL* socket = static_cast<SSLClientSocketOpenSSL*>(
328         SSL_get_ex_data(ssl, ssl_socket_data_index_));
329     DCHECK(socket);
330     return socket;
331   }
332
333   bool SetClientSocketForSSL(SSL* ssl, SSLClientSocketOpenSSL* socket) {
334     return SSL_set_ex_data(ssl, ssl_socket_data_index_, socket) != 0;
335   }
336
337  private:
338   friend struct DefaultSingletonTraits<SSLContext>;
339
340   SSLContext() {
341     crypto::EnsureOpenSSLInit();
342     ssl_socket_data_index_ = SSL_get_ex_new_index(0, 0, 0, 0, 0);
343     DCHECK_NE(ssl_socket_data_index_, -1);
344     ssl_ctx_.reset(SSL_CTX_new(SSLv23_client_method()));
345     SSL_CTX_set_cert_verify_callback(ssl_ctx_.get(), NoOpVerifyCallback, NULL);
346     SSL_CTX_set_session_cache_mode(ssl_ctx_.get(), SSL_SESS_CACHE_CLIENT);
347     SSL_CTX_sess_set_new_cb(ssl_ctx_.get(), NewSessionCallbackStatic);
348     SSL_CTX_sess_set_remove_cb(ssl_ctx_.get(), RemoveSessionCallbackStatic);
349     SSL_CTX_set_timeout(ssl_ctx_.get(), kSessionCacheTimeoutSeconds);
350     SSL_CTX_sess_set_cache_size(ssl_ctx_.get(), kSessionCacheMaxEntires);
351     SSL_CTX_set_client_cert_cb(ssl_ctx_.get(), ClientCertCallback);
352     SSL_CTX_set_channel_id_cb(ssl_ctx_.get(), ChannelIDCallback);
353 #if defined(OPENSSL_NPN_NEGOTIATED)
354     // TODO(kristianm): Only select this if ssl_config_.next_proto is not empty.
355     // It would be better if the callback were not a global setting,
356     // but that is an OpenSSL issue.
357     SSL_CTX_set_next_proto_select_cb(ssl_ctx_.get(), SelectNextProtoCallback,
358                                      NULL);
359 #endif
360   }
361
362   static int NewSessionCallbackStatic(SSL* ssl, SSL_SESSION* session) {
363     return GetInstance()->NewSessionCallback(ssl, session);
364   }
365
366   int NewSessionCallback(SSL* ssl, SSL_SESSION* session) {
367     SSLClientSocketOpenSSL* socket = GetClientSocketFromSSL(ssl);
368     session_cache_.OnSessionAdded(socket->host_and_port(),
369                                   socket->ssl_session_cache_shard(),
370                                   session);
371     return 1;  // 1 => We took ownership of |session|.
372   }
373
374   static void RemoveSessionCallbackStatic(SSL_CTX* ctx, SSL_SESSION* session) {
375     return GetInstance()->RemoveSessionCallback(ctx, session);
376   }
377
378   void RemoveSessionCallback(SSL_CTX* ctx, SSL_SESSION* session) {
379     DCHECK(ctx == ssl_ctx());
380     session_cache_.OnSessionRemoved(session);
381   }
382
383   static int ClientCertCallback(SSL* ssl, X509** x509, EVP_PKEY** pkey) {
384     SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
385     CHECK(socket);
386     return socket->ClientCertRequestCallback(ssl, x509, pkey);
387   }
388
389   static void ChannelIDCallback(SSL* ssl, EVP_PKEY** pkey) {
390     SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
391     CHECK(socket);
392     socket->ChannelIDRequestCallback(ssl, pkey);
393   }
394
395   static int SelectNextProtoCallback(SSL* ssl,
396                                      unsigned char** out, unsigned char* outlen,
397                                      const unsigned char* in,
398                                      unsigned int inlen, void* arg) {
399     SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
400     return socket->SelectNextProtoCallback(out, outlen, in, inlen);
401   }
402
403   // This is the index used with SSL_get_ex_data to retrieve the owner
404   // SSLClientSocketOpenSSL object from an SSL instance.
405   int ssl_socket_data_index_;
406
407   // session_cache_ must appear before |ssl_ctx_| because the destruction of
408   // |ssl_ctx_| may trigger callbacks into |session_cache_|. Therefore,
409   // |session_cache_| must be destructed after |ssl_ctx_|.
410   SSLSessionCache session_cache_;
411   crypto::ScopedOpenSSL<SSL_CTX, SSL_CTX_free> ssl_ctx_;
412 };
413
414 // Utility to construct the appropriate set & clear masks for use the OpenSSL
415 // options and mode configuration functions. (SSL_set_options etc)
416 struct SslSetClearMask {
417   SslSetClearMask() : set_mask(0), clear_mask(0) {}
418   void ConfigureFlag(long flag, bool state) {
419     (state ? set_mask : clear_mask) |= flag;
420     // Make sure we haven't got any intersection in the set & clear options.
421     DCHECK_EQ(0, set_mask & clear_mask) << flag << ":" << state;
422   }
423   long set_mask;
424   long clear_mask;
425 };
426
427 }  // namespace
428
429 // static
430 void SSLClientSocket::ClearSessionCache() {
431   SSLContext* context = SSLContext::GetInstance();
432   context->session_cache()->Flush();
433 }
434
435 SSLClientSocketOpenSSL::SSLClientSocketOpenSSL(
436     scoped_ptr<ClientSocketHandle> transport_socket,
437     const HostPortPair& host_and_port,
438     const SSLConfig& ssl_config,
439     const SSLClientSocketContext& context)
440     : transport_send_busy_(false),
441       transport_recv_busy_(false),
442       transport_recv_eof_(false),
443       weak_factory_(this),
444       pending_read_error_(kNoPendingReadResult),
445       completed_handshake_(false),
446       client_auth_cert_needed_(false),
447       cert_verifier_(context.cert_verifier),
448       server_bound_cert_service_(context.server_bound_cert_service),
449       ssl_(NULL),
450       transport_bio_(NULL),
451       transport_(transport_socket.Pass()),
452       host_and_port_(host_and_port),
453       ssl_config_(ssl_config),
454       ssl_session_cache_shard_(context.ssl_session_cache_shard),
455       trying_cached_session_(false),
456       next_handshake_state_(STATE_NONE),
457       npn_status_(kNextProtoUnsupported),
458       channel_id_request_return_value_(ERR_UNEXPECTED),
459       channel_id_xtn_negotiated_(false),
460       net_log_(transport_->socket()->NetLog()) {
461 }
462
463 SSLClientSocketOpenSSL::~SSLClientSocketOpenSSL() {
464   Disconnect();
465 }
466
467 bool SSLClientSocketOpenSSL::Init() {
468   DCHECK(!ssl_);
469   DCHECK(!transport_bio_);
470
471   SSLContext* context = SSLContext::GetInstance();
472   crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
473
474   ssl_ = SSL_new(context->ssl_ctx());
475   if (!ssl_ || !context->SetClientSocketForSSL(ssl_, this))
476     return false;
477
478   if (!SSL_set_tlsext_host_name(ssl_, host_and_port_.host().c_str()))
479     return false;
480
481   trying_cached_session_ =
482       context->session_cache()->SetSSLSession(ssl_, host_and_port_,
483                                               ssl_session_cache_shard_);
484
485   BIO* ssl_bio = NULL;
486   // 0 => use default buffer sizes.
487   if (!BIO_new_bio_pair(&ssl_bio, 0, &transport_bio_, 0))
488     return false;
489   DCHECK(ssl_bio);
490   DCHECK(transport_bio_);
491
492   SSL_set_bio(ssl_, ssl_bio, ssl_bio);
493
494   // OpenSSL defaults some options to on, others to off. To avoid ambiguity,
495   // set everything we care about to an absolute value.
496   SslSetClearMask options;
497   options.ConfigureFlag(SSL_OP_NO_SSLv2, true);
498   bool ssl3_enabled = (ssl_config_.version_min == SSL_PROTOCOL_VERSION_SSL3);
499   options.ConfigureFlag(SSL_OP_NO_SSLv3, !ssl3_enabled);
500   bool tls1_enabled = (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1 &&
501                        ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1);
502   options.ConfigureFlag(SSL_OP_NO_TLSv1, !tls1_enabled);
503 #if defined(SSL_OP_NO_TLSv1_1)
504   bool tls1_1_enabled =
505       (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1_1 &&
506        ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1_1);
507   options.ConfigureFlag(SSL_OP_NO_TLSv1_1, !tls1_1_enabled);
508 #endif
509 #if defined(SSL_OP_NO_TLSv1_2)
510   bool tls1_2_enabled =
511       (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1_2 &&
512        ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1_2);
513   options.ConfigureFlag(SSL_OP_NO_TLSv1_2, !tls1_2_enabled);
514 #endif
515
516 #if defined(SSL_OP_NO_COMPRESSION)
517   options.ConfigureFlag(SSL_OP_NO_COMPRESSION, true);
518 #endif
519
520   // TODO(joth): Set this conditionally, see http://crbug.com/55410
521   options.ConfigureFlag(SSL_OP_LEGACY_SERVER_CONNECT, true);
522
523   SSL_set_options(ssl_, options.set_mask);
524   SSL_clear_options(ssl_, options.clear_mask);
525
526   // Same as above, this time for the SSL mode.
527   SslSetClearMask mode;
528
529 #if defined(SSL_MODE_RELEASE_BUFFERS)
530   mode.ConfigureFlag(SSL_MODE_RELEASE_BUFFERS, true);
531 #endif
532
533 #if defined(SSL_MODE_SMALL_BUFFERS)
534   mode.ConfigureFlag(SSL_MODE_SMALL_BUFFERS, true);
535 #endif
536
537   SSL_set_mode(ssl_, mode.set_mask);
538   SSL_clear_mode(ssl_, mode.clear_mask);
539
540   // Removing ciphers by ID from OpenSSL is a bit involved as we must use the
541   // textual name with SSL_set_cipher_list because there is no public API to
542   // directly remove a cipher by ID.
543   STACK_OF(SSL_CIPHER)* ciphers = SSL_get_ciphers(ssl_);
544   DCHECK(ciphers);
545   // See SSLConfig::disabled_cipher_suites for description of the suites
546   // disabled by default. Note that !SHA256 and !SHA384 only remove HMAC-SHA256
547   // and HMAC-SHA384 cipher suites, not GCM cipher suites with SHA256 or SHA384
548   // as the handshake hash.
549   std::string command("DEFAULT:!NULL:!aNULL:!IDEA:!FZA:!SRP:!SHA256:!SHA384:"
550                       "!aECDH:!AESGCM+AES256");
551   // Walk through all the installed ciphers, seeing if any need to be
552   // appended to the cipher removal |command|.
553   for (int i = 0; i < sk_SSL_CIPHER_num(ciphers); ++i) {
554     const SSL_CIPHER* cipher = sk_SSL_CIPHER_value(ciphers, i);
555     const uint16 id = SSL_CIPHER_get_id(cipher);
556     // Remove any ciphers with a strength of less than 80 bits. Note the NSS
557     // implementation uses "effective" bits here but OpenSSL does not provide
558     // this detail. This only impacts Triple DES: reports 112 vs. 168 bits,
559     // both of which are greater than 80 anyway.
560     bool disable = SSL_CIPHER_get_bits(cipher, NULL) < 80;
561     if (!disable) {
562       disable = std::find(ssl_config_.disabled_cipher_suites.begin(),
563                           ssl_config_.disabled_cipher_suites.end(), id) !=
564                     ssl_config_.disabled_cipher_suites.end();
565     }
566     if (disable) {
567        const char* name = SSL_CIPHER_get_name(cipher);
568        DVLOG(3) << "Found cipher to remove: '" << name << "', ID: " << id
569                 << " strength: " << SSL_CIPHER_get_bits(cipher, NULL);
570        command.append(":!");
571        command.append(name);
572      }
573   }
574   int rv = SSL_set_cipher_list(ssl_, command.c_str());
575   // If this fails (rv = 0) it means there are no ciphers enabled on this SSL.
576   // This will almost certainly result in the socket failing to complete the
577   // handshake at which point the appropriate error is bubbled up to the client.
578   LOG_IF(WARNING, rv != 1) << "SSL_set_cipher_list('" << command << "') "
579                               "returned " << rv;
580
581   // TLS channel ids.
582   if (IsChannelIDEnabled(ssl_config_, server_bound_cert_service_)) {
583     SSL_enable_tls_channel_id(ssl_);
584   }
585
586   return true;
587 }
588
589 int SSLClientSocketOpenSSL::ClientCertRequestCallback(SSL* ssl,
590                                                       X509** x509,
591                                                       EVP_PKEY** pkey) {
592   DVLOG(3) << "OpenSSL ClientCertRequestCallback called";
593   DCHECK(ssl == ssl_);
594   DCHECK(*x509 == NULL);
595   DCHECK(*pkey == NULL);
596
597   if (!ssl_config_.send_client_cert) {
598     // First pass: we know that a client certificate is needed, but we do not
599     // have one at hand.
600     client_auth_cert_needed_ = true;
601     STACK_OF(X509_NAME) *authorities = SSL_get_client_CA_list(ssl);
602     for (int i = 0; i < sk_X509_NAME_num(authorities); i++) {
603       X509_NAME *ca_name = (X509_NAME *)sk_X509_NAME_value(authorities, i);
604       unsigned char* str = NULL;
605       int length = i2d_X509_NAME(ca_name, &str);
606       cert_authorities_.push_back(std::string(
607           reinterpret_cast<const char*>(str),
608           static_cast<size_t>(length)));
609       OPENSSL_free(str);
610     }
611
612     return -1;  // Suspends handshake.
613   }
614
615   // Second pass: a client certificate should have been selected.
616   if (ssl_config_.client_cert.get()) {
617     // A note about ownership: FetchClientCertPrivateKey() increments
618     // the reference count of the EVP_PKEY. Ownership of this reference
619     // is passed directly to OpenSSL, which will release the reference
620     // using EVP_PKEY_free() when the SSL object is destroyed.
621     OpenSSLClientKeyStore::ScopedEVP_PKEY privkey;
622     if (OpenSSLClientKeyStore::GetInstance()->FetchClientCertPrivateKey(
623             ssl_config_.client_cert.get(), &privkey)) {
624       // TODO(joth): (copied from NSS) We should wait for server certificate
625       // verification before sending our credentials. See http://crbug.com/13934
626       *x509 = X509Certificate::DupOSCertHandle(
627           ssl_config_.client_cert->os_cert_handle());
628       *pkey = privkey.release();
629       return 1;
630     }
631     LOG(WARNING) << "Client cert found without private key";
632   }
633
634   // Send no client certificate.
635   return 0;
636 }
637
638 void SSLClientSocketOpenSSL::ChannelIDRequestCallback(SSL* ssl,
639                                                       EVP_PKEY** pkey) {
640   DVLOG(3) << "OpenSSL ChannelIDRequestCallback called";
641   DCHECK_EQ(ssl, ssl_);
642   DCHECK(!*pkey);
643
644   channel_id_xtn_negotiated_ = true;
645   if (!channel_id_private_key_.size()) {
646     channel_id_request_return_value_ =
647         server_bound_cert_service_->GetOrCreateDomainBoundCert(
648             host_and_port_.host(),
649             &channel_id_private_key_,
650             &channel_id_cert_,
651             base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete,
652                        base::Unretained(this)),
653             &channel_id_request_handle_);
654     if (channel_id_request_return_value_ != OK)
655       return;
656   }
657
658   // Decode key.
659   std::vector<uint8> encrypted_private_key_info;
660   std::vector<uint8> subject_public_key_info;
661   encrypted_private_key_info.assign(
662       channel_id_private_key_.data(),
663       channel_id_private_key_.data() + channel_id_private_key_.size());
664   subject_public_key_info.assign(
665       channel_id_cert_.data(),
666       channel_id_cert_.data() + channel_id_cert_.size());
667   scoped_ptr<crypto::ECPrivateKey> ec_private_key(
668       crypto::ECPrivateKey::CreateFromEncryptedPrivateKeyInfo(
669           ServerBoundCertService::kEPKIPassword,
670           encrypted_private_key_info,
671           subject_public_key_info));
672   set_channel_id_sent(true);
673   *pkey = EVP_PKEY_dup(ec_private_key->key());
674 }
675
676 // SSLClientSocket methods
677
678 bool SSLClientSocketOpenSSL::GetSSLInfo(SSLInfo* ssl_info) {
679   ssl_info->Reset();
680   if (!server_cert_.get())
681     return false;
682
683   ssl_info->cert = server_cert_verify_result_.verified_cert;
684   ssl_info->cert_status = server_cert_verify_result_.cert_status;
685   ssl_info->is_issued_by_known_root =
686       server_cert_verify_result_.is_issued_by_known_root;
687   ssl_info->public_key_hashes =
688     server_cert_verify_result_.public_key_hashes;
689   ssl_info->client_cert_sent =
690       ssl_config_.send_client_cert && ssl_config_.client_cert.get();
691   ssl_info->channel_id_sent = WasChannelIDSent();
692
693   RecordChannelIDSupport(server_bound_cert_service_,
694                          channel_id_xtn_negotiated_,
695                          ssl_config_.channel_id_enabled,
696                          crypto::ECPrivateKey::IsSupported());
697
698   const SSL_CIPHER* cipher = SSL_get_current_cipher(ssl_);
699   CHECK(cipher);
700   ssl_info->security_bits = SSL_CIPHER_get_bits(cipher, NULL);
701   const COMP_METHOD* compression = SSL_get_current_compression(ssl_);
702
703   ssl_info->connection_status = EncodeSSLConnectionStatus(
704       SSL_CIPHER_get_id(cipher),
705       compression ? compression->type : 0,
706       GetNetSSLVersion(ssl_));
707
708   bool peer_supports_renego_ext = !!SSL_get_secure_renegotiation_support(ssl_);
709   if (!peer_supports_renego_ext)
710     ssl_info->connection_status |= SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION;
711   UMA_HISTOGRAM_ENUMERATION("Net.RenegotiationExtensionSupported",
712                             implicit_cast<int>(peer_supports_renego_ext), 2);
713
714   if (ssl_config_.version_fallback)
715     ssl_info->connection_status |= SSL_CONNECTION_VERSION_FALLBACK;
716
717   ssl_info->handshake_type = SSL_session_reused(ssl_) ?
718       SSLInfo::HANDSHAKE_RESUME : SSLInfo::HANDSHAKE_FULL;
719
720   DVLOG(3) << "Encoded connection status: cipher suite = "
721       << SSLConnectionStatusToCipherSuite(ssl_info->connection_status)
722       << " version = "
723       << SSLConnectionStatusToVersion(ssl_info->connection_status);
724   return true;
725 }
726
727 void SSLClientSocketOpenSSL::GetSSLCertRequestInfo(
728     SSLCertRequestInfo* cert_request_info) {
729   cert_request_info->host_and_port = host_and_port_.ToString();
730   cert_request_info->cert_authorities = cert_authorities_;
731 }
732
733 int SSLClientSocketOpenSSL::ExportKeyingMaterial(
734     const base::StringPiece& label,
735     bool has_context, const base::StringPiece& context,
736     unsigned char* out, unsigned int outlen) {
737   crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
738
739   int rv = SSL_export_keying_material(
740       ssl_, out, outlen, const_cast<char*>(label.data()),
741       label.size(),
742       reinterpret_cast<unsigned char*>(const_cast<char*>(context.data())),
743       context.length(),
744       context.length() > 0);
745
746   if (rv != 1) {
747     int ssl_error = SSL_get_error(ssl_, rv);
748     LOG(ERROR) << "Failed to export keying material;"
749                << " returned " << rv
750                << ", SSL error code " << ssl_error;
751     return MapOpenSSLError(ssl_error, err_tracer);
752   }
753   return OK;
754 }
755
756 int SSLClientSocketOpenSSL::GetTLSUniqueChannelBinding(std::string* out) {
757   return ERR_NOT_IMPLEMENTED;
758 }
759
760 SSLClientSocket::NextProtoStatus SSLClientSocketOpenSSL::GetNextProto(
761     std::string* proto, std::string* server_protos) {
762   *proto = npn_proto_;
763   *server_protos = server_protos_;
764   return npn_status_;
765 }
766
767 ServerBoundCertService*
768 SSLClientSocketOpenSSL::GetServerBoundCertService() const {
769   return server_bound_cert_service_;
770 }
771
772 void SSLClientSocketOpenSSL::DoReadCallback(int rv) {
773   // Since Run may result in Read being called, clear |user_read_callback_|
774   // up front.
775   user_read_buf_ = NULL;
776   user_read_buf_len_ = 0;
777   base::ResetAndReturn(&user_read_callback_).Run(rv);
778 }
779
780 void SSLClientSocketOpenSSL::DoWriteCallback(int rv) {
781   // Since Run may result in Write being called, clear |user_write_callback_|
782   // up front.
783   user_write_buf_ = NULL;
784   user_write_buf_len_ = 0;
785   base::ResetAndReturn(&user_write_callback_).Run(rv);
786 }
787
788 // StreamSocket implementation.
789 int SSLClientSocketOpenSSL::Connect(const CompletionCallback& callback) {
790   net_log_.BeginEvent(NetLog::TYPE_SSL_CONNECT);
791
792   // Set up new ssl object.
793   if (!Init()) {
794     int result = ERR_UNEXPECTED;
795     net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, result);
796     return result;
797   }
798
799   // Set SSL to client mode. Handshake happens in the loop below.
800   SSL_set_connect_state(ssl_);
801
802   GotoState(STATE_HANDSHAKE);
803   int rv = DoHandshakeLoop(net::OK);
804   if (rv == ERR_IO_PENDING) {
805     user_connect_callback_ = callback;
806   } else {
807     net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
808   }
809
810   return rv > OK ? OK : rv;
811 }
812
813 void SSLClientSocketOpenSSL::Disconnect() {
814   if (ssl_) {
815     // Calling SSL_shutdown prevents the session from being marked as
816     // unresumable.
817     SSL_shutdown(ssl_);
818     SSL_free(ssl_);
819     ssl_ = NULL;
820   }
821   if (transport_bio_) {
822     BIO_free_all(transport_bio_);
823     transport_bio_ = NULL;
824   }
825
826   // Shut down anything that may call us back.
827   verifier_.reset();
828   transport_->socket()->Disconnect();
829
830   // Null all callbacks, delete all buffers.
831   transport_send_busy_ = false;
832   send_buffer_ = NULL;
833   transport_recv_busy_ = false;
834   transport_recv_eof_ = false;
835   recv_buffer_ = NULL;
836
837   user_connect_callback_.Reset();
838   user_read_callback_.Reset();
839   user_write_callback_.Reset();
840   user_read_buf_         = NULL;
841   user_read_buf_len_     = 0;
842   user_write_buf_        = NULL;
843   user_write_buf_len_    = 0;
844
845   server_cert_verify_result_.Reset();
846   completed_handshake_ = false;
847
848   cert_authorities_.clear();
849   client_auth_cert_needed_ = false;
850 }
851
852 int SSLClientSocketOpenSSL::DoHandshakeLoop(int last_io_result) {
853   int rv = last_io_result;
854   do {
855     // Default to STATE_NONE for next state.
856     // (This is a quirk carried over from the windows
857     // implementation.  It makes reading the logs a bit harder.)
858     // State handlers can and often do call GotoState just
859     // to stay in the current state.
860     State state = next_handshake_state_;
861     GotoState(STATE_NONE);
862     switch (state) {
863       case STATE_HANDSHAKE:
864         rv = DoHandshake();
865         break;
866       case STATE_VERIFY_CERT:
867         DCHECK(rv == OK);
868         rv = DoVerifyCert(rv);
869        break;
870       case STATE_VERIFY_CERT_COMPLETE:
871         rv = DoVerifyCertComplete(rv);
872         break;
873       case STATE_NONE:
874       default:
875         rv = ERR_UNEXPECTED;
876         NOTREACHED() << "unexpected state" << state;
877         break;
878     }
879
880     bool network_moved = DoTransportIO();
881     if (network_moved && next_handshake_state_ == STATE_HANDSHAKE) {
882       // In general we exit the loop if rv is ERR_IO_PENDING.  In this
883       // special case we keep looping even if rv is ERR_IO_PENDING because
884       // the transport IO may allow DoHandshake to make progress.
885       rv = OK;  // This causes us to stay in the loop.
886     }
887   } while (rv != ERR_IO_PENDING && next_handshake_state_ != STATE_NONE);
888   return rv;
889 }
890
891 int SSLClientSocketOpenSSL::DoHandshake() {
892   crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
893   int net_error = net::OK;
894   int rv = SSL_do_handshake(ssl_);
895
896   if (client_auth_cert_needed_) {
897     net_error = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
898     // If the handshake already succeeded (because the server requests but
899     // doesn't require a client cert), we need to invalidate the SSL session
900     // so that we won't try to resume the non-client-authenticated session in
901     // the next handshake.  This will cause the server to ask for a client
902     // cert again.
903     if (rv == 1) {
904       // Remove from session cache but don't clear this connection.
905       SSL_SESSION* session = SSL_get_session(ssl_);
906       if (session) {
907         int rv = SSL_CTX_remove_session(SSL_get_SSL_CTX(ssl_), session);
908         LOG_IF(WARNING, !rv) << "Couldn't invalidate SSL session: " << session;
909       }
910     }
911   } else if (rv == 1) {
912     if (trying_cached_session_ && logging::DEBUG_MODE) {
913       DVLOG(2) << "Result of session reuse for " << host_and_port_.ToString()
914                << " is: " << (SSL_session_reused(ssl_) ? "Success" : "Fail");
915     }
916     // SSL handshake is completed.  Let's verify the certificate.
917     const bool got_cert = !!UpdateServerCert();
918     DCHECK(got_cert);
919     net_log_.AddEvent(
920         NetLog::TYPE_SSL_CERTIFICATES_RECEIVED,
921         base::Bind(&NetLogX509CertificateCallback,
922                    base::Unretained(server_cert_.get())));
923     GotoState(STATE_VERIFY_CERT);
924   } else {
925     int ssl_error = SSL_get_error(ssl_, rv);
926
927     if (ssl_error == SSL_ERROR_WANT_CHANNEL_ID_LOOKUP) {
928       // The server supports TLS channel id and the lookup is asynchronous.
929       // Retrieve the error from the call to |server_bound_cert_service_|.
930       net_error = channel_id_request_return_value_;
931     } else {
932       net_error = MapOpenSSLError(ssl_error, err_tracer);
933     }
934
935     // If not done, stay in this state
936     if (net_error == ERR_IO_PENDING) {
937       GotoState(STATE_HANDSHAKE);
938     } else {
939       LOG(ERROR) << "handshake failed; returned " << rv
940                  << ", SSL error code " << ssl_error
941                  << ", net_error " << net_error;
942       net_log_.AddEvent(
943           NetLog::TYPE_SSL_HANDSHAKE_ERROR,
944           CreateNetLogSSLErrorCallback(net_error, ssl_error));
945     }
946   }
947   return net_error;
948 }
949
950 // SelectNextProtoCallback is called by OpenSSL during the handshake. If the
951 // server supports NPN, selects a protocol from the list that the server
952 // provides. According to third_party/openssl/openssl/ssl/ssl_lib.c, the
953 // callback can assume that |in| is syntactically valid.
954 int SSLClientSocketOpenSSL::SelectNextProtoCallback(unsigned char** out,
955                                                     unsigned char* outlen,
956                                                     const unsigned char* in,
957                                                     unsigned int inlen) {
958 #if defined(OPENSSL_NPN_NEGOTIATED)
959   if (ssl_config_.next_protos.empty()) {
960     *out = reinterpret_cast<uint8*>(
961         const_cast<char*>(kDefaultSupportedNPNProtocol));
962     *outlen = arraysize(kDefaultSupportedNPNProtocol) - 1;
963     npn_status_ = kNextProtoUnsupported;
964     return SSL_TLSEXT_ERR_OK;
965   }
966
967   // Assume there's no overlap between our protocols and the server's list.
968   npn_status_ = kNextProtoNoOverlap;
969
970   // For each protocol in server preference order, see if we support it.
971   for (unsigned int i = 0; i < inlen; i += in[i] + 1) {
972     for (std::vector<std::string>::const_iterator
973              j = ssl_config_.next_protos.begin();
974          j != ssl_config_.next_protos.end(); ++j) {
975       if (in[i] == j->size() &&
976           memcmp(&in[i + 1], j->data(), in[i]) == 0) {
977         // We found a match.
978         *out = const_cast<unsigned char*>(in) + i + 1;
979         *outlen = in[i];
980         npn_status_ = kNextProtoNegotiated;
981         break;
982       }
983     }
984     if (npn_status_ == kNextProtoNegotiated)
985       break;
986   }
987
988   // If we didn't find a protocol, we select the first one from our list.
989   if (npn_status_ == kNextProtoNoOverlap) {
990     *out = reinterpret_cast<uint8*>(const_cast<char*>(
991         ssl_config_.next_protos[0].data()));
992     *outlen = ssl_config_.next_protos[0].size();
993   }
994
995   npn_proto_.assign(reinterpret_cast<const char*>(*out), *outlen);
996   server_protos_.assign(reinterpret_cast<const char*>(in), inlen);
997   DVLOG(2) << "next protocol: '" << npn_proto_ << "' status: " << npn_status_;
998 #endif
999   return SSL_TLSEXT_ERR_OK;
1000 }
1001
1002 int SSLClientSocketOpenSSL::DoVerifyCert(int result) {
1003   DCHECK(server_cert_.get());
1004   GotoState(STATE_VERIFY_CERT_COMPLETE);
1005
1006   CertStatus cert_status;
1007   if (ssl_config_.IsAllowedBadCert(server_cert_.get(), &cert_status)) {
1008     VLOG(1) << "Received an expected bad cert with status: " << cert_status;
1009     server_cert_verify_result_.Reset();
1010     server_cert_verify_result_.cert_status = cert_status;
1011     server_cert_verify_result_.verified_cert = server_cert_;
1012     return OK;
1013   }
1014
1015   int flags = 0;
1016   if (ssl_config_.rev_checking_enabled)
1017     flags |= CertVerifier::VERIFY_REV_CHECKING_ENABLED;
1018   if (ssl_config_.verify_ev_cert)
1019     flags |= CertVerifier::VERIFY_EV_CERT;
1020   if (ssl_config_.cert_io_enabled)
1021     flags |= CertVerifier::VERIFY_CERT_IO_ENABLED;
1022   if (ssl_config_.rev_checking_required_local_anchors)
1023     flags |= CertVerifier::VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS;
1024   verifier_.reset(new SingleRequestCertVerifier(cert_verifier_));
1025   return verifier_->Verify(
1026       server_cert_.get(),
1027       host_and_port_.host(),
1028       flags,
1029       NULL /* no CRL set */,
1030       &server_cert_verify_result_,
1031       base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete,
1032                  base::Unretained(this)),
1033       net_log_);
1034 }
1035
1036 int SSLClientSocketOpenSSL::DoVerifyCertComplete(int result) {
1037   verifier_.reset();
1038
1039   if (result == OK) {
1040     // TODO(joth): Work out if we need to remember the intermediate CA certs
1041     // when the server sends them to us, and do so here.
1042   } else {
1043     DVLOG(1) << "DoVerifyCertComplete error " << ErrorToString(result)
1044              << " (" << result << ")";
1045   }
1046
1047   completed_handshake_ = true;
1048   // Exit DoHandshakeLoop and return the result to the caller to Connect.
1049   DCHECK_EQ(STATE_NONE, next_handshake_state_);
1050   return result;
1051 }
1052
1053 X509Certificate* SSLClientSocketOpenSSL::UpdateServerCert() {
1054   if (server_cert_.get())
1055     return server_cert_.get();
1056
1057   crypto::ScopedOpenSSL<X509, X509_free> cert(SSL_get_peer_certificate(ssl_));
1058   if (!cert.get()) {
1059     LOG(WARNING) << "SSL_get_peer_certificate returned NULL";
1060     return NULL;
1061   }
1062
1063   // Unlike SSL_get_peer_certificate, SSL_get_peer_cert_chain does not
1064   // increment the reference so sk_X509_free does not need to be called.
1065   STACK_OF(X509)* chain = SSL_get_peer_cert_chain(ssl_);
1066   X509Certificate::OSCertHandles intermediates;
1067   if (chain) {
1068     for (int i = 0; i < sk_X509_num(chain); ++i)
1069       intermediates.push_back(sk_X509_value(chain, i));
1070   }
1071   server_cert_ = X509Certificate::CreateFromHandle(cert.get(), intermediates);
1072   DCHECK(server_cert_.get());
1073
1074   return server_cert_.get();
1075 }
1076
1077 bool SSLClientSocketOpenSSL::DoTransportIO() {
1078   bool network_moved = false;
1079   int rv;
1080   // Read and write as much data as possible. The loop is necessary because
1081   // Write() may return synchronously.
1082   do {
1083     rv = BufferSend();
1084     if (rv != ERR_IO_PENDING && rv != 0)
1085       network_moved = true;
1086   } while (rv > 0);
1087   if (!transport_recv_eof_ && BufferRecv() != ERR_IO_PENDING)
1088     network_moved = true;
1089   return network_moved;
1090 }
1091
1092 int SSLClientSocketOpenSSL::BufferSend(void) {
1093   if (transport_send_busy_)
1094     return ERR_IO_PENDING;
1095
1096   if (!send_buffer_.get()) {
1097     // Get a fresh send buffer out of the send BIO.
1098     size_t max_read = BIO_ctrl_pending(transport_bio_);
1099     if (!max_read)
1100       return 0;  // Nothing pending in the OpenSSL write BIO.
1101     send_buffer_ = new DrainableIOBuffer(new IOBuffer(max_read), max_read);
1102     int read_bytes = BIO_read(transport_bio_, send_buffer_->data(), max_read);
1103     DCHECK_GT(read_bytes, 0);
1104     CHECK_EQ(static_cast<int>(max_read), read_bytes);
1105   }
1106
1107   int rv = transport_->socket()->Write(
1108       send_buffer_.get(),
1109       send_buffer_->BytesRemaining(),
1110       base::Bind(&SSLClientSocketOpenSSL::BufferSendComplete,
1111                  base::Unretained(this)));
1112   if (rv == ERR_IO_PENDING) {
1113     transport_send_busy_ = true;
1114   } else {
1115     TransportWriteComplete(rv);
1116   }
1117   return rv;
1118 }
1119
1120 void SSLClientSocketOpenSSL::BufferSendComplete(int result) {
1121   transport_send_busy_ = false;
1122   TransportWriteComplete(result);
1123   OnSendComplete(result);
1124 }
1125
1126 void SSLClientSocketOpenSSL::TransportWriteComplete(int result) {
1127   DCHECK(ERR_IO_PENDING != result);
1128   if (result < 0) {
1129     // Got a socket write error; close the BIO to indicate this upward.
1130     DVLOG(1) << "TransportWriteComplete error " << result;
1131     (void)BIO_shutdown_wr(transport_bio_);
1132     BIO_set_mem_eof_return(transport_bio_, 0);
1133     send_buffer_ = NULL;
1134   } else {
1135     DCHECK(send_buffer_.get());
1136     send_buffer_->DidConsume(result);
1137     DCHECK_GE(send_buffer_->BytesRemaining(), 0);
1138     if (send_buffer_->BytesRemaining() <= 0)
1139       send_buffer_ = NULL;
1140   }
1141 }
1142
1143 int SSLClientSocketOpenSSL::BufferRecv(void) {
1144   if (transport_recv_busy_)
1145     return ERR_IO_PENDING;
1146
1147   // Determine how much was requested from |transport_bio_| that was not
1148   // actually available.
1149   size_t requested = BIO_ctrl_get_read_request(transport_bio_);
1150   if (requested == 0) {
1151     // This is not a perfect match of error codes, as no operation is
1152     // actually pending. However, returning 0 would be interpreted as
1153     // a possible sign of EOF, which is also an inappropriate match.
1154     return ERR_IO_PENDING;
1155   }
1156
1157   // Known Issue: While only reading |requested| data is the more correct
1158   // implementation, it has the downside of resulting in frequent reads:
1159   // One read for the SSL record header (~5 bytes) and one read for the SSL
1160   // record body. Rather than issuing these reads to the underlying socket
1161   // (and constantly allocating new IOBuffers), a single Read() request to
1162   // fill |transport_bio_| is issued. As long as an SSL client socket cannot
1163   // be gracefully shutdown (via SSL close alerts) and re-used for non-SSL
1164   // traffic, this over-subscribed Read()ing will not cause issues.
1165   size_t max_write = BIO_ctrl_get_write_guarantee(transport_bio_);
1166   if (!max_write)
1167     return ERR_IO_PENDING;
1168
1169   recv_buffer_ = new IOBuffer(max_write);
1170   int rv = transport_->socket()->Read(
1171       recv_buffer_.get(),
1172       max_write,
1173       base::Bind(&SSLClientSocketOpenSSL::BufferRecvComplete,
1174                  base::Unretained(this)));
1175   if (rv == ERR_IO_PENDING) {
1176     transport_recv_busy_ = true;
1177   } else {
1178     TransportReadComplete(rv);
1179   }
1180   return rv;
1181 }
1182
1183 void SSLClientSocketOpenSSL::BufferRecvComplete(int result) {
1184   TransportReadComplete(result);
1185   OnRecvComplete(result);
1186 }
1187
1188 void SSLClientSocketOpenSSL::TransportReadComplete(int result) {
1189   DCHECK(ERR_IO_PENDING != result);
1190   if (result <= 0) {
1191     DVLOG(1) << "TransportReadComplete result " << result;
1192     // Received 0 (end of file) or an error. Either way, bubble it up to the
1193     // SSL layer via the BIO. TODO(joth): consider stashing the error code, to
1194     // relay up to the SSL socket client (i.e. via DoReadCallback).
1195     if (result == 0)
1196       transport_recv_eof_ = true;
1197     BIO_set_mem_eof_return(transport_bio_, 0);
1198     (void)BIO_shutdown_wr(transport_bio_);
1199   } else {
1200     DCHECK(recv_buffer_.get());
1201     int ret = BIO_write(transport_bio_, recv_buffer_->data(), result);
1202     // A write into a memory BIO should always succeed.
1203     CHECK_EQ(result, ret);
1204   }
1205   recv_buffer_ = NULL;
1206   transport_recv_busy_ = false;
1207 }
1208
1209 void SSLClientSocketOpenSSL::DoConnectCallback(int rv) {
1210   if (!user_connect_callback_.is_null()) {
1211     CompletionCallback c = user_connect_callback_;
1212     user_connect_callback_.Reset();
1213     c.Run(rv > OK ? OK : rv);
1214   }
1215 }
1216
1217 void SSLClientSocketOpenSSL::OnHandshakeIOComplete(int result) {
1218   int rv = DoHandshakeLoop(result);
1219   if (rv != ERR_IO_PENDING) {
1220     net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
1221     DoConnectCallback(rv);
1222   }
1223 }
1224
1225 void SSLClientSocketOpenSSL::OnSendComplete(int result) {
1226   if (next_handshake_state_ == STATE_HANDSHAKE) {
1227     // In handshake phase.
1228     OnHandshakeIOComplete(result);
1229     return;
1230   }
1231
1232   // OnSendComplete may need to call DoPayloadRead while the renegotiation
1233   // handshake is in progress.
1234   int rv_read = ERR_IO_PENDING;
1235   int rv_write = ERR_IO_PENDING;
1236   bool network_moved;
1237   do {
1238     if (user_read_buf_.get())
1239       rv_read = DoPayloadRead();
1240     if (user_write_buf_.get())
1241       rv_write = DoPayloadWrite();
1242     network_moved = DoTransportIO();
1243   } while (rv_read == ERR_IO_PENDING && rv_write == ERR_IO_PENDING &&
1244            (user_read_buf_.get() || user_write_buf_.get()) && network_moved);
1245
1246   // Performing the Read callback may cause |this| to be deleted. If this
1247   // happens, the Write callback should not be invoked. Guard against this by
1248   // holding a WeakPtr to |this| and ensuring it's still valid.
1249   base::WeakPtr<SSLClientSocketOpenSSL> guard(weak_factory_.GetWeakPtr());
1250   if (user_read_buf_.get() && rv_read != ERR_IO_PENDING)
1251     DoReadCallback(rv_read);
1252
1253   if (!guard.get())
1254     return;
1255
1256   if (user_write_buf_.get() && rv_write != ERR_IO_PENDING)
1257     DoWriteCallback(rv_write);
1258 }
1259
1260 void SSLClientSocketOpenSSL::OnRecvComplete(int result) {
1261   if (next_handshake_state_ == STATE_HANDSHAKE) {
1262     // In handshake phase.
1263     OnHandshakeIOComplete(result);
1264     return;
1265   }
1266
1267   // Network layer received some data, check if client requested to read
1268   // decrypted data.
1269   if (!user_read_buf_.get())
1270     return;
1271
1272   int rv = DoReadLoop(result);
1273   if (rv != ERR_IO_PENDING)
1274     DoReadCallback(rv);
1275 }
1276
1277 bool SSLClientSocketOpenSSL::IsConnected() const {
1278   // If the handshake has not yet completed.
1279   if (!completed_handshake_)
1280     return false;
1281   // If an asynchronous operation is still pending.
1282   if (user_read_buf_.get() || user_write_buf_.get())
1283     return true;
1284
1285   return transport_->socket()->IsConnected();
1286 }
1287
1288 bool SSLClientSocketOpenSSL::IsConnectedAndIdle() const {
1289   // If the handshake has not yet completed.
1290   if (!completed_handshake_)
1291     return false;
1292   // If an asynchronous operation is still pending.
1293   if (user_read_buf_.get() || user_write_buf_.get())
1294     return false;
1295   // If there is data waiting to be sent, or data read from the network that
1296   // has not yet been consumed.
1297   if (BIO_ctrl_pending(transport_bio_) > 0 ||
1298       BIO_ctrl_wpending(transport_bio_) > 0) {
1299     return false;
1300   }
1301
1302   return transport_->socket()->IsConnectedAndIdle();
1303 }
1304
1305 int SSLClientSocketOpenSSL::GetPeerAddress(IPEndPoint* addressList) const {
1306   return transport_->socket()->GetPeerAddress(addressList);
1307 }
1308
1309 int SSLClientSocketOpenSSL::GetLocalAddress(IPEndPoint* addressList) const {
1310   return transport_->socket()->GetLocalAddress(addressList);
1311 }
1312
1313 const BoundNetLog& SSLClientSocketOpenSSL::NetLog() const {
1314   return net_log_;
1315 }
1316
1317 void SSLClientSocketOpenSSL::SetSubresourceSpeculation() {
1318   if (transport_.get() && transport_->socket()) {
1319     transport_->socket()->SetSubresourceSpeculation();
1320   } else {
1321     NOTREACHED();
1322   }
1323 }
1324
1325 void SSLClientSocketOpenSSL::SetOmniboxSpeculation() {
1326   if (transport_.get() && transport_->socket()) {
1327     transport_->socket()->SetOmniboxSpeculation();
1328   } else {
1329     NOTREACHED();
1330   }
1331 }
1332
1333 bool SSLClientSocketOpenSSL::WasEverUsed() const {
1334   if (transport_.get() && transport_->socket())
1335     return transport_->socket()->WasEverUsed();
1336
1337   NOTREACHED();
1338   return false;
1339 }
1340
1341 bool SSLClientSocketOpenSSL::UsingTCPFastOpen() const {
1342   if (transport_.get() && transport_->socket())
1343     return transport_->socket()->UsingTCPFastOpen();
1344
1345   NOTREACHED();
1346   return false;
1347 }
1348
1349 // Socket methods
1350
1351 int SSLClientSocketOpenSSL::Read(IOBuffer* buf,
1352                                  int buf_len,
1353                                  const CompletionCallback& callback) {
1354   user_read_buf_ = buf;
1355   user_read_buf_len_ = buf_len;
1356
1357   int rv = DoReadLoop(OK);
1358
1359   if (rv == ERR_IO_PENDING) {
1360     user_read_callback_ = callback;
1361   } else {
1362     user_read_buf_ = NULL;
1363     user_read_buf_len_ = 0;
1364   }
1365
1366   return rv;
1367 }
1368
1369 int SSLClientSocketOpenSSL::DoReadLoop(int result) {
1370   if (result < 0)
1371     return result;
1372
1373   bool network_moved;
1374   int rv;
1375   do {
1376     rv = DoPayloadRead();
1377     network_moved = DoTransportIO();
1378   } while (rv == ERR_IO_PENDING && network_moved);
1379
1380   return rv;
1381 }
1382
1383 int SSLClientSocketOpenSSL::Write(IOBuffer* buf,
1384                                   int buf_len,
1385                                   const CompletionCallback& callback) {
1386   user_write_buf_ = buf;
1387   user_write_buf_len_ = buf_len;
1388
1389   int rv = DoWriteLoop(OK);
1390
1391   if (rv == ERR_IO_PENDING) {
1392     user_write_callback_ = callback;
1393   } else {
1394     user_write_buf_ = NULL;
1395     user_write_buf_len_ = 0;
1396   }
1397
1398   return rv;
1399 }
1400
1401 int SSLClientSocketOpenSSL::DoWriteLoop(int result) {
1402   if (result < 0)
1403     return result;
1404
1405   bool network_moved;
1406   int rv;
1407   do {
1408     rv = DoPayloadWrite();
1409     network_moved = DoTransportIO();
1410   } while (rv == ERR_IO_PENDING && network_moved);
1411
1412   return rv;
1413 }
1414
1415 bool SSLClientSocketOpenSSL::SetReceiveBufferSize(int32 size) {
1416   return transport_->socket()->SetReceiveBufferSize(size);
1417 }
1418
1419 bool SSLClientSocketOpenSSL::SetSendBufferSize(int32 size) {
1420   return transport_->socket()->SetSendBufferSize(size);
1421 }
1422
1423 int SSLClientSocketOpenSSL::DoPayloadRead() {
1424   crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1425
1426   int rv;
1427   if (pending_read_error_ != kNoPendingReadResult) {
1428     rv = pending_read_error_;
1429     pending_read_error_ = kNoPendingReadResult;
1430     if (rv == 0) {
1431       net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED,
1432                                     rv, user_read_buf_->data());
1433     }
1434     return rv;
1435   }
1436
1437   int total_bytes_read = 0;
1438   do {
1439     rv = SSL_read(ssl_, user_read_buf_->data() + total_bytes_read,
1440                   user_read_buf_len_ - total_bytes_read);
1441     if (rv > 0)
1442       total_bytes_read += rv;
1443   } while (total_bytes_read < user_read_buf_len_ && rv > 0);
1444
1445   if (total_bytes_read == user_read_buf_len_) {
1446     rv = total_bytes_read;
1447   } else {
1448     // Otherwise, an error occurred (rv <= 0). The error needs to be handled
1449     // immediately, while the OpenSSL errors are still available in
1450     // thread-local storage. However, the handled/remapped error code should
1451     // only be returned if no application data was already read; if it was, the
1452     // error code should be deferred until the next call of DoPayloadRead.
1453     //
1454     // If no data was read, |*next_result| will point to the return value of
1455     // this function. If at least some data was read, |*next_result| will point
1456     // to |pending_read_error_|, to be returned in a future call to
1457     // DoPayloadRead() (e.g.: after the current data is handled).
1458     int *next_result = &rv;
1459     if (total_bytes_read > 0) {
1460       pending_read_error_ = rv;
1461       rv = total_bytes_read;
1462       next_result = &pending_read_error_;
1463     }
1464
1465     if (client_auth_cert_needed_) {
1466       *next_result = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
1467     } else if (*next_result < 0) {
1468       int err = SSL_get_error(ssl_, *next_result);
1469       *next_result = MapOpenSSLError(err, err_tracer);
1470       if (rv > 0 && *next_result == ERR_IO_PENDING) {
1471           // If at least some data was read from SSL_read(), do not treat
1472           // insufficient data as an error to return in the next call to
1473           // DoPayloadRead() - instead, let the call fall through to check
1474           // SSL_read() again. This is because DoTransportIO() may complete
1475           // in between the next call to DoPayloadRead(), and thus it is
1476           // important to check SSL_read() on subsequent invocations to see
1477           // if a complete record may now be read.
1478         *next_result = kNoPendingReadResult;
1479       }
1480     }
1481   }
1482
1483   if (rv >= 0) {
1484     net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, rv,
1485                                   user_read_buf_->data());
1486   }
1487   return rv;
1488 }
1489
1490 int SSLClientSocketOpenSSL::DoPayloadWrite() {
1491   crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1492   int rv = SSL_write(ssl_, user_write_buf_->data(), user_write_buf_len_);
1493
1494   if (rv >= 0) {
1495     net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_SENT, rv,
1496                                   user_write_buf_->data());
1497     return rv;
1498   }
1499
1500   int err = SSL_get_error(ssl_, rv);
1501   return MapOpenSSLError(err, err_tracer);
1502 }
1503
1504 }  // namespace net