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