blob: df4e14df8013962c5de9572adfa52713549c917a [file] [log] [blame]
[email protected]013c17c2012-01-21 19:09:011// Copyright (c) 2012 The Chromium Authors. All rights reserved.
[email protected]d518cd92010-09-29 12:27:442// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5// OpenSSL binding for SSLClientSocket. The class layout and general principle
6// of operation is derived from SSLClientSocketNSS.
7
8#include "net/socket/ssl_client_socket_openssl.h"
9
[email protected]d518cd92010-09-29 12:27:4410#include <openssl/err.h>
[email protected]89038152012-09-07 06:30:1711#include <openssl/opensslv.h>
[email protected]536fd0b2013-03-14 17:41:5712#include <openssl/ssl.h>
[email protected]d518cd92010-09-29 12:27:4413
[email protected]0f7804ec2011-10-07 20:04:1814#include "base/bind.h"
[email protected]f2da6ac2013-02-04 08:22:5315#include "base/callback_helpers.h"
[email protected]3b63f8f42011-03-28 01:54:1516#include "base/memory/singleton.h"
[email protected]835d7c82010-10-14 04:38:3817#include "base/metrics/histogram.h"
[email protected]20305ec2011-01-21 04:55:5218#include "base/synchronization/lock.h"
[email protected]4b559b4d2011-04-14 17:37:1419#include "crypto/openssl_util.h"
[email protected]d518cd92010-09-29 12:27:4420#include "net/base/net_errors.h"
[email protected]6e7845ae2013-03-29 21:48:1121#include "net/cert/cert_verifier.h"
22#include "net/cert/single_request_cert_verifier.h"
23#include "net/cert/x509_certificate_net_log_param.h"
[email protected]109805a2010-12-07 18:17:0624#include "net/socket/ssl_error_params.h"
[email protected]5cf67592013-04-02 17:42:1225#include "net/ssl/openssl_client_key_store.h"
[email protected]536fd0b2013-03-14 17:41:5726#include "net/ssl/ssl_cert_request_info.h"
27#include "net/ssl/ssl_connection_status_flags.h"
28#include "net/ssl/ssl_info.h"
[email protected]d518cd92010-09-29 12:27:4429
30namespace net {
31
32namespace {
33
34// Enable this to see logging for state machine state transitions.
35#if 0
[email protected]3b112772010-10-04 10:54:4936#define GotoState(s) do { DVLOG(2) << (void *)this << " " << __FUNCTION__ << \
[email protected]d518cd92010-09-29 12:27:4437 " jump to state " << s; \
38 next_handshake_state_ = s; } while (0)
39#else
40#define GotoState(s) next_handshake_state_ = s
41#endif
42
[email protected]fbef13932010-11-23 12:38:5343const int kSessionCacheTimeoutSeconds = 60 * 60;
44const size_t kSessionCacheMaxEntires = 1024;
[email protected]d518cd92010-09-29 12:27:4445
[email protected]4b768562013-02-16 04:10:0746// 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
[email protected]168a8412012-06-14 05:05:4950// 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
[email protected]89038152012-09-07 06:30:1754#if OPENSSL_VERSION_NUMBER < 0x1000103fL
55// This method doesn't seem to have made it into the OpenSSL headers.
[email protected]109805a2010-12-07 18:17:0656unsigned long SSL_CIPHER_get_id(const SSL_CIPHER* cipher) { return cipher->id; }
[email protected]89038152012-09-07 06:30:1757#endif
[email protected]109805a2010-12-07 18:17:0658
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) {
[email protected]7e5dd49f2010-12-08 18:33:4974 switch (SSL_version(ssl)) {
[email protected]109805a2010-12-07 18:17:0675 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;
[email protected]109805a2010-12-07 18:17:06113 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:
[email protected]8bc50922012-12-10 19:39:43118 case SSL_R_UNSUPPORTED_PROTOCOL:
[email protected]109805a2010-12-07 18:17:06119 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_UNSAFE_LEGACY_RENEGOTIATION_DISABLED:
134 return ERR_SSL_UNSAFE_NEGOTIATION;
135 case SSL_R_WRONG_NUMBER_OF_KEY_BITS:
136 return ERR_SSL_WEAK_SERVER_EPHEMERAL_DH_KEY;
[email protected]aa4bb6892010-12-08 10:52:02137 // SSL_R_UNKNOWN_PROTOCOL is reported if premature application data is
138 // received (see http://crbug.com/42538), and also if all the protocol
139 // versions supported by the server were disabled in this socket instance.
140 // Mapped to ERR_SSL_PROTOCOL_ERROR for compatibility with other SSL sockets
141 // in the former scenario.
142 case SSL_R_UNKNOWN_PROTOCOL:
[email protected]109805a2010-12-07 18:17:06143 case SSL_R_SSL_HANDSHAKE_FAILURE:
144 case SSL_R_DECRYPTION_FAILED:
145 case SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC:
146 case SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG:
147 case SSL_R_DIGEST_CHECK_FAILED:
148 case SSL_R_DUPLICATE_COMPRESSION_ID:
149 case SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER:
150 case SSL_R_ENCRYPTED_LENGTH_TOO_LONG:
151 case SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST:
152 case SSL_R_EXCESSIVE_MESSAGE_SIZE:
153 case SSL_R_EXTRA_DATA_IN_MESSAGE:
154 case SSL_R_GOT_A_FIN_BEFORE_A_CCS:
155 case SSL_R_ILLEGAL_PADDING:
156 case SSL_R_INVALID_CHALLENGE_LENGTH:
157 case SSL_R_INVALID_COMMAND:
158 case SSL_R_INVALID_PURPOSE:
159 case SSL_R_INVALID_STATUS_RESPONSE:
160 case SSL_R_INVALID_TICKET_KEYS_LENGTH:
161 case SSL_R_KEY_ARG_TOO_LONG:
162 case SSL_R_READ_WRONG_PACKET_TYPE:
163 case SSL_R_SSLV3_ALERT_UNEXPECTED_MESSAGE:
164 // TODO(joth): SSL_R_SSLV3_ALERT_HANDSHAKE_FAILURE may be returned from the
165 // server after receiving ClientHello if there's no common supported cipher.
166 // Ideally we'd map that specific case to ERR_SSL_VERSION_OR_CIPHER_MISMATCH
167 // to match the NSS implementation. See also http://goo.gl/oMtZW
168 case SSL_R_SSLV3_ALERT_HANDSHAKE_FAILURE:
169 case SSL_R_SSLV3_ALERT_NO_CERTIFICATE:
170 case SSL_R_SSLV3_ALERT_ILLEGAL_PARAMETER:
171 case SSL_R_TLSV1_ALERT_DECODE_ERROR:
172 case SSL_R_TLSV1_ALERT_DECRYPTION_FAILED:
173 case SSL_R_TLSV1_ALERT_DECRYPT_ERROR:
174 case SSL_R_TLSV1_ALERT_EXPORT_RESTRICTION:
175 case SSL_R_TLSV1_ALERT_INTERNAL_ERROR:
176 case SSL_R_TLSV1_ALERT_NO_RENEGOTIATION:
177 case SSL_R_TLSV1_ALERT_RECORD_OVERFLOW:
178 case SSL_R_TLSV1_ALERT_USER_CANCELLED:
179 return ERR_SSL_PROTOCOL_ERROR;
180 default:
181 LOG(WARNING) << "Unmapped error reason: " << ERR_GET_REASON(error_code);
182 return ERR_FAILED;
183 }
184}
185
186// Converts an OpenSSL error code into a net error code, walking the OpenSSL
187// error stack if needed. Note that |tracer| is not currently used in the
188// implementation, but is passed in anyway as this ensures the caller will clear
189// any residual codes left on the error stack.
[email protected]4b559b4d2011-04-14 17:37:14190int MapOpenSSLError(int err, const crypto::OpenSSLErrStackTracer& tracer) {
[email protected]d518cd92010-09-29 12:27:44191 switch (err) {
192 case SSL_ERROR_WANT_READ:
193 case SSL_ERROR_WANT_WRITE:
194 return ERR_IO_PENDING;
[email protected]170e76c2010-10-04 15:04:20195 case SSL_ERROR_SYSCALL:
[email protected]abc7e06d2010-10-06 15:40:35196 DVLOG(1) << "OpenSSL SYSCALL error, errno " << errno;
[email protected]170e76c2010-10-04 15:04:20197 return ERR_SSL_PROTOCOL_ERROR;
[email protected]109805a2010-12-07 18:17:06198 case SSL_ERROR_SSL:
199 return MapOpenSSLErrorSSL();
[email protected]d518cd92010-09-29 12:27:44200 default:
201 // TODO(joth): Implement full mapping.
202 LOG(WARNING) << "Unknown OpenSSL error " << err;
[email protected]d518cd92010-09-29 12:27:44203 return ERR_SSL_PROTOCOL_ERROR;
204 }
205}
206
[email protected]313834722010-11-17 09:57:18207// We do certificate verification after handshake, so we disable the default
208// by registering a no-op verify function.
209int NoOpVerifyCallback(X509_STORE_CTX*, void *) {
210 DVLOG(3) << "skipping cert verify";
211 return 1;
212}
213
[email protected]fbef13932010-11-23 12:38:53214// OpenSSL manages a cache of SSL_SESSION, this class provides the application
215// side policy for that cache about session re-use: we retain one session per
[email protected]c3456bb2011-12-12 22:22:19216// unique HostPortPair, per shard.
[email protected]fbef13932010-11-23 12:38:53217class SSLSessionCache {
218 public:
219 SSLSessionCache() {}
220
[email protected]c3456bb2011-12-12 22:22:19221 void OnSessionAdded(const HostPortPair& host_and_port,
222 const std::string& shard,
223 SSL_SESSION* session) {
[email protected]fbef13932010-11-23 12:38:53224 // Declare the session cleaner-upper before the lock, so any call into
225 // OpenSSL to free the session will happen after the lock is released.
[email protected]4b559b4d2011-04-14 17:37:14226 crypto::ScopedOpenSSL<SSL_SESSION, SSL_SESSION_free> session_to_free;
[email protected]20305ec2011-01-21 04:55:52227 base::AutoLock lock(lock_);
[email protected]fbef13932010-11-23 12:38:53228
229 DCHECK_EQ(0U, session_map_.count(session));
[email protected]c3456bb2011-12-12 22:22:19230 const std::string cache_key = GetCacheKey(host_and_port, shard);
231
[email protected]fbef13932010-11-23 12:38:53232 std::pair<HostPortMap::iterator, bool> res =
[email protected]c3456bb2011-12-12 22:22:19233 host_port_map_.insert(std::make_pair(cache_key, session));
[email protected]fbef13932010-11-23 12:38:53234 if (!res.second) { // Already exists: replace old entry.
235 session_to_free.reset(res.first->second);
236 session_map_.erase(session_to_free.get());
237 res.first->second = session;
238 }
239 DVLOG(2) << "Adding session " << session << " => "
[email protected]c3456bb2011-12-12 22:22:19240 << cache_key << ", new entry = " << res.second;
241 DCHECK(host_port_map_[cache_key] == session);
[email protected]fbef13932010-11-23 12:38:53242 session_map_[session] = res.first;
243 DCHECK_EQ(host_port_map_.size(), session_map_.size());
244 DCHECK_LE(host_port_map_.size(), kSessionCacheMaxEntires);
[email protected]313834722010-11-17 09:57:18245 }
[email protected]fbef13932010-11-23 12:38:53246
247 void OnSessionRemoved(SSL_SESSION* session) {
248 // Declare the session cleaner-upper before the lock, so any call into
249 // OpenSSL to free the session will happen after the lock is released.
[email protected]4b559b4d2011-04-14 17:37:14250 crypto::ScopedOpenSSL<SSL_SESSION, SSL_SESSION_free> session_to_free;
[email protected]20305ec2011-01-21 04:55:52251 base::AutoLock lock(lock_);
[email protected]fbef13932010-11-23 12:38:53252
253 SessionMap::iterator it = session_map_.find(session);
254 if (it == session_map_.end())
255 return;
[email protected]c3456bb2011-12-12 22:22:19256 DVLOG(2) << "Remove session " << session << " => " << it->second->first;
[email protected]fbef13932010-11-23 12:38:53257 DCHECK(it->second->second == session);
258 host_port_map_.erase(it->second);
259 session_map_.erase(it);
260 session_to_free.reset(session);
261 DCHECK_EQ(host_port_map_.size(), session_map_.size());
[email protected]313834722010-11-17 09:57:18262 }
[email protected]fbef13932010-11-23 12:38:53263
264 // Looks up the host:port in the cache, and if a session is found it is added
265 // to |ssl|, returning true on success.
[email protected]c3456bb2011-12-12 22:22:19266 bool SetSSLSession(SSL* ssl, const HostPortPair& host_and_port,
267 const std::string& shard) {
[email protected]20305ec2011-01-21 04:55:52268 base::AutoLock lock(lock_);
[email protected]c3456bb2011-12-12 22:22:19269 const std::string cache_key = GetCacheKey(host_and_port, shard);
270 HostPortMap::iterator it = host_port_map_.find(cache_key);
[email protected]fbef13932010-11-23 12:38:53271 if (it == host_port_map_.end())
272 return false;
[email protected]c3456bb2011-12-12 22:22:19273 DVLOG(2) << "Lookup session: " << it->second << " => " << cache_key;
[email protected]fbef13932010-11-23 12:38:53274 SSL_SESSION* session = it->second;
275 DCHECK(session);
276 DCHECK(session_map_[session] == it);
277 // Ideally we'd release |lock_| before calling into OpenSSL here, however
278 // that opens a small risk |session| will go out of scope before it is used.
279 // Alternatively we would take a temporary local refcount on |session|,
280 // except OpenSSL does not provide a public API for adding a ref (c.f.
281 // SSL_SESSION_free which decrements the ref).
282 return SSL_set_session(ssl, session) == 1;
283 }
284
[email protected]c3456bb2011-12-12 22:22:19285 // Flush removes all entries from the cache. This is called when a client
286 // certificate is added.
287 void Flush() {
288 for (HostPortMap::iterator i = host_port_map_.begin();
289 i != host_port_map_.end(); i++) {
290 SSL_SESSION_free(i->second);
291 }
292 host_port_map_.clear();
293 session_map_.clear();
294 }
295
[email protected]fbef13932010-11-23 12:38:53296 private:
[email protected]c3456bb2011-12-12 22:22:19297 static std::string GetCacheKey(const HostPortPair& host_and_port,
298 const std::string& shard) {
299 return host_and_port.ToString() + "/" + shard;
300 }
301
[email protected]fbef13932010-11-23 12:38:53302 // A pair of maps to allow bi-directional lookups between host:port and an
[email protected]109805a2010-12-07 18:17:06303 // associated session.
[email protected]c3456bb2011-12-12 22:22:19304 typedef std::map<std::string, SSL_SESSION*> HostPortMap;
[email protected]fbef13932010-11-23 12:38:53305 typedef std::map<SSL_SESSION*, HostPortMap::iterator> SessionMap;
306 HostPortMap host_port_map_;
307 SessionMap session_map_;
308
309 // Protects access to both the above maps.
[email protected]20305ec2011-01-21 04:55:52310 base::Lock lock_;
[email protected]fbef13932010-11-23 12:38:53311
312 DISALLOW_COPY_AND_ASSIGN(SSLSessionCache);
[email protected]313834722010-11-17 09:57:18313};
314
[email protected]fbef13932010-11-23 12:38:53315class SSLContext {
316 public:
[email protected]b29af7d2010-12-14 11:52:47317 static SSLContext* GetInstance() { return Singleton<SSLContext>::get(); }
[email protected]fbef13932010-11-23 12:38:53318 SSL_CTX* ssl_ctx() { return ssl_ctx_.get(); }
319 SSLSessionCache* session_cache() { return &session_cache_; }
320
321 SSLClientSocketOpenSSL* GetClientSocketFromSSL(SSL* ssl) {
322 DCHECK(ssl);
323 SSLClientSocketOpenSSL* socket = static_cast<SSLClientSocketOpenSSL*>(
324 SSL_get_ex_data(ssl, ssl_socket_data_index_));
325 DCHECK(socket);
326 return socket;
327 }
328
329 bool SetClientSocketForSSL(SSL* ssl, SSLClientSocketOpenSSL* socket) {
330 return SSL_set_ex_data(ssl, ssl_socket_data_index_, socket) != 0;
331 }
332
333 private:
334 friend struct DefaultSingletonTraits<SSLContext>;
335
336 SSLContext() {
[email protected]4b559b4d2011-04-14 17:37:14337 crypto::EnsureOpenSSLInit();
[email protected]fbef13932010-11-23 12:38:53338 ssl_socket_data_index_ = SSL_get_ex_new_index(0, 0, 0, 0, 0);
339 DCHECK_NE(ssl_socket_data_index_, -1);
340 ssl_ctx_.reset(SSL_CTX_new(SSLv23_client_method()));
341 SSL_CTX_set_cert_verify_callback(ssl_ctx_.get(), NoOpVerifyCallback, NULL);
342 SSL_CTX_set_session_cache_mode(ssl_ctx_.get(), SSL_SESS_CACHE_CLIENT);
343 SSL_CTX_sess_set_new_cb(ssl_ctx_.get(), NewSessionCallbackStatic);
344 SSL_CTX_sess_set_remove_cb(ssl_ctx_.get(), RemoveSessionCallbackStatic);
345 SSL_CTX_set_timeout(ssl_ctx_.get(), kSessionCacheTimeoutSeconds);
346 SSL_CTX_sess_set_cache_size(ssl_ctx_.get(), kSessionCacheMaxEntires);
[email protected]718c9672010-12-02 10:04:10347 SSL_CTX_set_client_cert_cb(ssl_ctx_.get(), ClientCertCallback);
[email protected]ea4a1c6a2010-12-09 13:33:28348#if defined(OPENSSL_NPN_NEGOTIATED)
349 // TODO(kristianm): Only select this if ssl_config_.next_proto is not empty.
350 // It would be better if the callback were not a global setting,
351 // but that is an OpenSSL issue.
352 SSL_CTX_set_next_proto_select_cb(ssl_ctx_.get(), SelectNextProtoCallback,
353 NULL);
354#endif
[email protected]fbef13932010-11-23 12:38:53355 }
356
357 static int NewSessionCallbackStatic(SSL* ssl, SSL_SESSION* session) {
[email protected]b29af7d2010-12-14 11:52:47358 return GetInstance()->NewSessionCallback(ssl, session);
[email protected]fbef13932010-11-23 12:38:53359 }
360
361 int NewSessionCallback(SSL* ssl, SSL_SESSION* session) {
362 SSLClientSocketOpenSSL* socket = GetClientSocketFromSSL(ssl);
[email protected]c3456bb2011-12-12 22:22:19363 session_cache_.OnSessionAdded(socket->host_and_port(),
364 socket->ssl_session_cache_shard(),
365 session);
[email protected]fbef13932010-11-23 12:38:53366 return 1; // 1 => We took ownership of |session|.
367 }
368
369 static void RemoveSessionCallbackStatic(SSL_CTX* ctx, SSL_SESSION* session) {
[email protected]b29af7d2010-12-14 11:52:47370 return GetInstance()->RemoveSessionCallback(ctx, session);
[email protected]fbef13932010-11-23 12:38:53371 }
372
373 void RemoveSessionCallback(SSL_CTX* ctx, SSL_SESSION* session) {
374 DCHECK(ctx == ssl_ctx());
375 session_cache_.OnSessionRemoved(session);
376 }
377
[email protected]718c9672010-12-02 10:04:10378 static int ClientCertCallback(SSL* ssl, X509** x509, EVP_PKEY** pkey) {
[email protected]b29af7d2010-12-14 11:52:47379 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
[email protected]718c9672010-12-02 10:04:10380 CHECK(socket);
381 return socket->ClientCertRequestCallback(ssl, x509, pkey);
382 }
383
[email protected]ea4a1c6a2010-12-09 13:33:28384 static int SelectNextProtoCallback(SSL* ssl,
385 unsigned char** out, unsigned char* outlen,
386 const unsigned char* in,
387 unsigned int inlen, void* arg) {
[email protected]b29af7d2010-12-14 11:52:47388 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
[email protected]ea4a1c6a2010-12-09 13:33:28389 return socket->SelectNextProtoCallback(out, outlen, in, inlen);
390 }
391
[email protected]fbef13932010-11-23 12:38:53392 // This is the index used with SSL_get_ex_data to retrieve the owner
393 // SSLClientSocketOpenSSL object from an SSL instance.
394 int ssl_socket_data_index_;
395
[email protected]c3456bb2011-12-12 22:22:19396 // session_cache_ must appear before |ssl_ctx_| because the destruction of
397 // |ssl_ctx_| may trigger callbacks into |session_cache_|. Therefore,
398 // |session_cache_| must be destructed after |ssl_ctx_|.
[email protected]fbef13932010-11-23 12:38:53399 SSLSessionCache session_cache_;
[email protected]c3456bb2011-12-12 22:22:19400 crypto::ScopedOpenSSL<SSL_CTX, SSL_CTX_free> ssl_ctx_;
[email protected]fbef13932010-11-23 12:38:53401};
[email protected]313834722010-11-17 09:57:18402
[email protected]fb10e2282010-12-01 17:08:48403// Utility to construct the appropriate set & clear masks for use the OpenSSL
404// options and mode configuration functions. (SSL_set_options etc)
405struct SslSetClearMask {
406 SslSetClearMask() : set_mask(0), clear_mask(0) {}
407 void ConfigureFlag(long flag, bool state) {
408 (state ? set_mask : clear_mask) |= flag;
409 // Make sure we haven't got any intersection in the set & clear options.
410 DCHECK_EQ(0, set_mask & clear_mask) << flag << ":" << state;
411 }
412 long set_mask;
413 long clear_mask;
414};
415
[email protected]3b112772010-10-04 10:54:49416} // namespace
[email protected]d518cd92010-09-29 12:27:44417
[email protected]c3456bb2011-12-12 22:22:19418// static
419void SSLClientSocket::ClearSessionCache() {
420 SSLContext* context = SSLContext::GetInstance();
421 context->session_cache()->Flush();
422}
423
[email protected]d518cd92010-09-29 12:27:44424SSLClientSocketOpenSSL::SSLClientSocketOpenSSL(
425 ClientSocketHandle* transport_socket,
[email protected]055d7f22010-11-15 12:03:12426 const HostPortPair& host_and_port,
[email protected]822581d2010-12-16 17:27:15427 const SSLConfig& ssl_config,
[email protected]feb79bcd2011-07-21 16:55:17428 const SSLClientSocketContext& context)
[email protected]83039bb2011-12-09 18:43:55429 : transport_send_busy_(false),
[email protected]d518cd92010-09-29 12:27:44430 transport_recv_busy_(false),
[email protected]a85197e2012-05-22 19:07:28431 transport_recv_eof_(false),
[email protected]4b768562013-02-16 04:10:07432 pending_read_error_(kNoPendingReadResult),
[email protected]fbef13932010-11-23 12:38:53433 completed_handshake_(false),
[email protected]d518cd92010-09-29 12:27:44434 client_auth_cert_needed_(false),
[email protected]feb79bcd2011-07-21 16:55:17435 cert_verifier_(context.cert_verifier),
[email protected]d518cd92010-09-29 12:27:44436 ssl_(NULL),
437 transport_bio_(NULL),
438 transport_(transport_socket),
[email protected]055d7f22010-11-15 12:03:12439 host_and_port_(host_and_port),
[email protected]d518cd92010-09-29 12:27:44440 ssl_config_(ssl_config),
[email protected]c3456bb2011-12-12 22:22:19441 ssl_session_cache_shard_(context.ssl_session_cache_shard),
[email protected]fbef13932010-11-23 12:38:53442 trying_cached_session_(false),
[email protected]013c17c2012-01-21 19:09:01443 next_handshake_state_(STATE_NONE),
[email protected]ea4a1c6a2010-12-09 13:33:28444 npn_status_(kNextProtoUnsupported),
[email protected]d518cd92010-09-29 12:27:44445 net_log_(transport_socket->socket()->NetLog()) {
446}
447
448SSLClientSocketOpenSSL::~SSLClientSocketOpenSSL() {
449 Disconnect();
450}
451
[email protected]d518cd92010-09-29 12:27:44452bool SSLClientSocketOpenSSL::Init() {
[email protected]9e733f32010-10-04 18:19:08453 DCHECK(!ssl_);
454 DCHECK(!transport_bio_);
455
[email protected]b29af7d2010-12-14 11:52:47456 SSLContext* context = SSLContext::GetInstance();
[email protected]4b559b4d2011-04-14 17:37:14457 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
[email protected]d518cd92010-09-29 12:27:44458
[email protected]fbef13932010-11-23 12:38:53459 ssl_ = SSL_new(context->ssl_ctx());
460 if (!ssl_ || !context->SetClientSocketForSSL(ssl_, this))
[email protected]d518cd92010-09-29 12:27:44461 return false;
[email protected]fbef13932010-11-23 12:38:53462
463 if (!SSL_set_tlsext_host_name(ssl_, host_and_port_.host().c_str()))
464 return false;
465
466 trying_cached_session_ =
[email protected]c3456bb2011-12-12 22:22:19467 context->session_cache()->SetSSLSession(ssl_, host_and_port_,
468 ssl_session_cache_shard_);
[email protected]d518cd92010-09-29 12:27:44469
470 BIO* ssl_bio = NULL;
[email protected]fbef13932010-11-23 12:38:53471 // 0 => use default buffer sizes.
472 if (!BIO_new_bio_pair(&ssl_bio, 0, &transport_bio_, 0))
[email protected]d518cd92010-09-29 12:27:44473 return false;
[email protected]d518cd92010-09-29 12:27:44474 DCHECK(ssl_bio);
475 DCHECK(transport_bio_);
476
477 SSL_set_bio(ssl_, ssl_bio, ssl_bio);
478
[email protected]9e733f32010-10-04 18:19:08479 // OpenSSL defaults some options to on, others to off. To avoid ambiguity,
480 // set everything we care about to an absolute value.
[email protected]fb10e2282010-12-01 17:08:48481 SslSetClearMask options;
482 options.ConfigureFlag(SSL_OP_NO_SSLv2, true);
[email protected]80c75f682012-05-26 16:22:17483 bool ssl3_enabled = (ssl_config_.version_min == SSL_PROTOCOL_VERSION_SSL3);
484 options.ConfigureFlag(SSL_OP_NO_SSLv3, !ssl3_enabled);
485 bool tls1_enabled = (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1 &&
486 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1);
487 options.ConfigureFlag(SSL_OP_NO_TLSv1, !tls1_enabled);
488#if defined(SSL_OP_NO_TLSv1_1)
489 bool tls1_1_enabled =
490 (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1_1 &&
491 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1_1);
492 options.ConfigureFlag(SSL_OP_NO_TLSv1_1, !tls1_1_enabled);
493#endif
494#if defined(SSL_OP_NO_TLSv1_2)
495 bool tls1_2_enabled =
496 (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1_2 &&
497 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1_2);
498 options.ConfigureFlag(SSL_OP_NO_TLSv1_2, !tls1_2_enabled);
499#endif
[email protected]fb10e2282010-12-01 17:08:48500
501#if defined(SSL_OP_NO_COMPRESSION)
[email protected]d0f00492012-08-03 22:35:13502 options.ConfigureFlag(SSL_OP_NO_COMPRESSION, true);
[email protected]fb10e2282010-12-01 17:08:48503#endif
[email protected]9e733f32010-10-04 18:19:08504
505 // TODO(joth): Set this conditionally, see http://crbug.com/55410
[email protected]fb10e2282010-12-01 17:08:48506 options.ConfigureFlag(SSL_OP_LEGACY_SERVER_CONNECT, true);
[email protected]9e733f32010-10-04 18:19:08507
[email protected]fb10e2282010-12-01 17:08:48508 SSL_set_options(ssl_, options.set_mask);
509 SSL_clear_options(ssl_, options.clear_mask);
[email protected]9e733f32010-10-04 18:19:08510
[email protected]fb10e2282010-12-01 17:08:48511 // Same as above, this time for the SSL mode.
512 SslSetClearMask mode;
[email protected]9e733f32010-10-04 18:19:08513
[email protected]fb10e2282010-12-01 17:08:48514#if defined(SSL_MODE_RELEASE_BUFFERS)
515 mode.ConfigureFlag(SSL_MODE_RELEASE_BUFFERS, true);
516#endif
517
518#if defined(SSL_MODE_SMALL_BUFFERS)
519 mode.ConfigureFlag(SSL_MODE_SMALL_BUFFERS, true);
520#endif
521
522 SSL_set_mode(ssl_, mode.set_mask);
523 SSL_clear_mode(ssl_, mode.clear_mask);
[email protected]109805a2010-12-07 18:17:06524
525 // Removing ciphers by ID from OpenSSL is a bit involved as we must use the
526 // textual name with SSL_set_cipher_list because there is no public API to
527 // directly remove a cipher by ID.
528 STACK_OF(SSL_CIPHER)* ciphers = SSL_get_ciphers(ssl_);
529 DCHECK(ciphers);
530 // See SSLConfig::disabled_cipher_suites for description of the suites
531 // disabled by default.
532 std::string command("DEFAULT:!NULL:!aNULL:!IDEA:!FZA");
533 // Walk through all the installed ciphers, seeing if any need to be
534 // appended to the cipher removal |command|.
535 for (int i = 0; i < sk_SSL_CIPHER_num(ciphers); ++i) {
536 const SSL_CIPHER* cipher = sk_SSL_CIPHER_value(ciphers, i);
537 const uint16 id = SSL_CIPHER_get_id(cipher);
538 // Remove any ciphers with a strength of less than 80 bits. Note the NSS
539 // implementation uses "effective" bits here but OpenSSL does not provide
540 // this detail. This only impacts Triple DES: reports 112 vs. 168 bits,
541 // both of which are greater than 80 anyway.
542 bool disable = SSL_CIPHER_get_bits(cipher, NULL) < 80;
543 if (!disable) {
544 disable = std::find(ssl_config_.disabled_cipher_suites.begin(),
545 ssl_config_.disabled_cipher_suites.end(), id) !=
546 ssl_config_.disabled_cipher_suites.end();
547 }
548 if (disable) {
549 const char* name = SSL_CIPHER_get_name(cipher);
550 DVLOG(3) << "Found cipher to remove: '" << name << "', ID: " << id
551 << " strength: " << SSL_CIPHER_get_bits(cipher, NULL);
552 command.append(":!");
553 command.append(name);
554 }
555 }
556 int rv = SSL_set_cipher_list(ssl_, command.c_str());
557 // If this fails (rv = 0) it means there are no ciphers enabled on this SSL.
558 // This will almost certainly result in the socket failing to complete the
559 // handshake at which point the appropriate error is bubbled up to the client.
560 LOG_IF(WARNING, rv != 1) << "SSL_set_cipher_list('" << command << "') "
561 "returned " << rv;
[email protected]d518cd92010-09-29 12:27:44562 return true;
563}
564
[email protected]5ac981e182010-12-06 17:56:27565int SSLClientSocketOpenSSL::ClientCertRequestCallback(SSL* ssl,
566 X509** x509,
567 EVP_PKEY** pkey) {
568 DVLOG(3) << "OpenSSL ClientCertRequestCallback called";
569 DCHECK(ssl == ssl_);
570 DCHECK(*x509 == NULL);
571 DCHECK(*pkey == NULL);
572
573 if (!ssl_config_.send_client_cert) {
[email protected]515adc22013-01-09 16:01:23574 // First pass: we know that a client certificate is needed, but we do not
575 // have one at hand.
[email protected]5ac981e182010-12-06 17:56:27576 client_auth_cert_needed_ = true;
[email protected]515adc22013-01-09 16:01:23577 STACK_OF(X509_NAME) *authorities = SSL_get_client_CA_list(ssl);
578 for (int i = 0; i < sk_X509_NAME_num(authorities); i++) {
579 X509_NAME *ca_name = (X509_NAME *)sk_X509_NAME_value(authorities, i);
580 unsigned char* str = NULL;
581 int length = i2d_X509_NAME(ca_name, &str);
582 cert_authorities_.push_back(std::string(
583 reinterpret_cast<const char*>(str),
584 static_cast<size_t>(length)));
585 OPENSSL_free(str);
586 }
587
[email protected]5ac981e182010-12-06 17:56:27588 return -1; // Suspends handshake.
589 }
590
591 // Second pass: a client certificate should have been selected.
592 if (ssl_config_.client_cert) {
[email protected]ede323ea2013-03-02 22:54:41593 // A note about ownership: FetchClientCertPrivateKey() increments
594 // the reference count of the EVP_PKEY. Ownership of this reference
595 // is passed directly to OpenSSL, which will release the reference
596 // using EVP_PKEY_free() when the SSL object is destroyed.
597 OpenSSLClientKeyStore::ScopedEVP_PKEY privkey;
598 if (OpenSSLClientKeyStore::GetInstance()->FetchClientCertPrivateKey(
599 ssl_config_.client_cert.get(), &privkey)) {
[email protected]0c6523f2010-12-10 10:56:24600 // TODO(joth): (copied from NSS) We should wait for server certificate
601 // verification before sending our credentials. See http://crbug.com/13934
602 *x509 = X509Certificate::DupOSCertHandle(
603 ssl_config_.client_cert->os_cert_handle());
[email protected]ede323ea2013-03-02 22:54:41604 *pkey = privkey.release();
[email protected]0c6523f2010-12-10 10:56:24605 return 1;
606 }
607 LOG(WARNING) << "Client cert found without private key";
[email protected]5ac981e182010-12-06 17:56:27608 }
609
610 // Send no client certificate.
611 return 0;
612}
613
[email protected]d518cd92010-09-29 12:27:44614// SSLClientSocket methods
615
[email protected]2d88e7d2012-07-19 17:55:17616bool SSLClientSocketOpenSSL::GetSSLInfo(SSLInfo* ssl_info) {
[email protected]170e76c2010-10-04 15:04:20617 ssl_info->Reset();
618 if (!server_cert_)
[email protected]2d88e7d2012-07-19 17:55:17619 return false;
[email protected]170e76c2010-10-04 15:04:20620
[email protected]e54d0af2012-03-03 01:07:15621 ssl_info->cert = server_cert_verify_result_.verified_cert;
[email protected]170e76c2010-10-04 15:04:20622 ssl_info->cert_status = server_cert_verify_result_.cert_status;
[email protected]1f522492011-04-13 22:06:38623 ssl_info->is_issued_by_known_root =
624 server_cert_verify_result_.is_issued_by_known_root;
625 ssl_info->public_key_hashes =
626 server_cert_verify_result_.public_key_hashes;
[email protected]6b4903f2012-06-26 02:13:49627 ssl_info->client_cert_sent =
628 ssl_config_.send_client_cert && ssl_config_.client_cert;
629 ssl_info->channel_id_sent = WasChannelIDSent();
[email protected]2907525c2010-10-08 15:53:52630
631 const SSL_CIPHER* cipher = SSL_get_current_cipher(ssl_);
632 CHECK(cipher);
633 ssl_info->security_bits = SSL_CIPHER_get_bits(cipher, NULL);
[email protected]2907525c2010-10-08 15:53:52634 const COMP_METHOD* compression = SSL_get_current_compression(ssl_);
[email protected]109805a2010-12-07 18:17:06635
636 ssl_info->connection_status = EncodeSSLConnectionStatus(
637 SSL_CIPHER_get_id(cipher),
638 compression ? compression->type : 0,
639 GetNetSSLVersion(ssl_));
[email protected]9e733f32010-10-04 18:19:08640
641 bool peer_supports_renego_ext = !!SSL_get_secure_renegotiation_support(ssl_);
642 if (!peer_supports_renego_ext)
643 ssl_info->connection_status |= SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION;
[email protected]109805a2010-12-07 18:17:06644 UMA_HISTOGRAM_ENUMERATION("Net.RenegotiationExtensionSupported",
645 implicit_cast<int>(peer_supports_renego_ext), 2);
[email protected]9e733f32010-10-04 18:19:08646
[email protected]80c75f682012-05-26 16:22:17647 if (ssl_config_.version_fallback)
648 ssl_info->connection_status |= SSL_CONNECTION_VERSION_FALLBACK;
[email protected]109805a2010-12-07 18:17:06649
[email protected]acb8c7c2013-03-02 17:50:13650 ssl_info->handshake_type = SSL_session_reused(ssl_) ?
651 SSLInfo::HANDSHAKE_RESUME : SSLInfo::HANDSHAKE_FULL;
652
[email protected]109805a2010-12-07 18:17:06653 DVLOG(3) << "Encoded connection status: cipher suite = "
654 << SSLConnectionStatusToCipherSuite(ssl_info->connection_status)
[email protected]109805a2010-12-07 18:17:06655 << " version = "
656 << SSLConnectionStatusToVersion(ssl_info->connection_status);
[email protected]2d88e7d2012-07-19 17:55:17657 return true;
[email protected]d518cd92010-09-29 12:27:44658}
659
660void SSLClientSocketOpenSSL::GetSSLCertRequestInfo(
661 SSLCertRequestInfo* cert_request_info) {
[email protected]718c9672010-12-02 10:04:10662 cert_request_info->host_and_port = host_and_port_.ToString();
[email protected]515adc22013-01-09 16:01:23663 cert_request_info->cert_authorities = cert_authorities_;
[email protected]d518cd92010-09-29 12:27:44664}
665
[email protected]b0ff3f82011-07-23 05:12:39666int SSLClientSocketOpenSSL::ExportKeyingMaterial(
[email protected]1bc6f5e2012-03-15 00:20:58667 const base::StringPiece& label,
668 bool has_context, const base::StringPiece& context,
669 unsigned char* out, unsigned int outlen) {
[email protected]dffa6872012-03-08 23:20:42670 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
671
672 int rv = SSL_export_keying_material(
673 ssl_, out, outlen, const_cast<char*>(label.data()),
674 label.size(),
675 reinterpret_cast<unsigned char*>(const_cast<char*>(context.data())),
676 context.length(),
677 context.length() > 0);
678
679 if (rv != 1) {
680 int ssl_error = SSL_get_error(ssl_, rv);
681 LOG(ERROR) << "Failed to export keying material;"
682 << " returned " << rv
683 << ", SSL error code " << ssl_error;
684 return MapOpenSSLError(ssl_error, err_tracer);
685 }
686 return OK;
[email protected]b0ff3f82011-07-23 05:12:39687}
688
[email protected]81ec7c12012-07-31 18:32:19689int SSLClientSocketOpenSSL::GetTLSUniqueChannelBinding(std::string* out) {
690 return ERR_NOT_IMPLEMENTED;
691}
692
[email protected]d518cd92010-09-29 12:27:44693SSLClientSocket::NextProtoStatus SSLClientSocketOpenSSL::GetNextProto(
[email protected]55e973d2011-12-05 23:03:24694 std::string* proto, std::string* server_protos) {
[email protected]ea4a1c6a2010-12-09 13:33:28695 *proto = npn_proto_;
[email protected]55e973d2011-12-05 23:03:24696 *server_protos = server_protos_;
[email protected]ea4a1c6a2010-12-09 13:33:28697 return npn_status_;
[email protected]d518cd92010-09-29 12:27:44698}
699
[email protected]9c4eff22012-03-20 22:42:29700ServerBoundCertService*
701SSLClientSocketOpenSSL::GetServerBoundCertService() const {
[email protected]61f3ddf2012-02-08 02:45:39702 return NULL;
703}
704
[email protected]d518cd92010-09-29 12:27:44705void SSLClientSocketOpenSSL::DoReadCallback(int rv) {
706 // Since Run may result in Read being called, clear |user_read_callback_|
707 // up front.
[email protected]83039bb2011-12-09 18:43:55708 user_read_buf_ = NULL;
709 user_read_buf_len_ = 0;
[email protected]f2da6ac2013-02-04 08:22:53710 base::ResetAndReturn(&user_read_callback_).Run(rv);
[email protected]d518cd92010-09-29 12:27:44711}
712
713void SSLClientSocketOpenSSL::DoWriteCallback(int rv) {
714 // Since Run may result in Write being called, clear |user_write_callback_|
715 // up front.
[email protected]f749f9c2011-12-09 01:06:19716 user_write_buf_ = NULL;
717 user_write_buf_len_ = 0;
[email protected]f2da6ac2013-02-04 08:22:53718 base::ResetAndReturn(&user_write_callback_).Run(rv);
[email protected]d518cd92010-09-29 12:27:44719}
720
[email protected]83039bb2011-12-09 18:43:55721// StreamSocket implementation.
[email protected]dbf036f2011-12-06 23:33:24722int SSLClientSocketOpenSSL::Connect(const CompletionCallback& callback) {
[email protected]3aa4af042012-06-14 21:02:31723 net_log_.BeginEvent(NetLog::TYPE_SSL_CONNECT);
[email protected]dbf036f2011-12-06 23:33:24724
725 // Set up new ssl object.
726 if (!Init()) {
727 int result = ERR_UNEXPECTED;
728 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, result);
729 return result;
730 }
731
732 // Set SSL to client mode. Handshake happens in the loop below.
733 SSL_set_connect_state(ssl_);
734
735 GotoState(STATE_HANDSHAKE);
736 int rv = DoHandshakeLoop(net::OK);
737 if (rv == ERR_IO_PENDING) {
[email protected]d518cd92010-09-29 12:27:44738 user_connect_callback_ = callback;
739 } else {
[email protected]d7fd1782011-02-08 19:16:43740 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
[email protected]d518cd92010-09-29 12:27:44741 }
742
743 return rv > OK ? OK : rv;
744}
745
746void SSLClientSocketOpenSSL::Disconnect() {
[email protected]170e76c2010-10-04 15:04:20747 if (ssl_) {
[email protected]c3456bb2011-12-12 22:22:19748 // Calling SSL_shutdown prevents the session from being marked as
749 // unresumable.
750 SSL_shutdown(ssl_);
[email protected]170e76c2010-10-04 15:04:20751 SSL_free(ssl_);
752 ssl_ = NULL;
753 }
754 if (transport_bio_) {
755 BIO_free_all(transport_bio_);
756 transport_bio_ = NULL;
757 }
758
[email protected]0f7804ec2011-10-07 20:04:18759 // Shut down anything that may call us back.
[email protected]170e76c2010-10-04 15:04:20760 verifier_.reset();
761 transport_->socket()->Disconnect();
762
[email protected]d518cd92010-09-29 12:27:44763 // Null all callbacks, delete all buffers.
764 transport_send_busy_ = false;
765 send_buffer_ = NULL;
766 transport_recv_busy_ = false;
[email protected]a85197e2012-05-22 19:07:28767 transport_recv_eof_ = false;
[email protected]d518cd92010-09-29 12:27:44768 recv_buffer_ = NULL;
769
[email protected]dbf036f2011-12-06 23:33:24770 user_connect_callback_.Reset();
[email protected]3f55aa12011-12-07 02:03:33771 user_read_callback_.Reset();
[email protected]83039bb2011-12-09 18:43:55772 user_write_callback_.Reset();
[email protected]d518cd92010-09-29 12:27:44773 user_read_buf_ = NULL;
774 user_read_buf_len_ = 0;
775 user_write_buf_ = NULL;
776 user_write_buf_len_ = 0;
777
[email protected]170e76c2010-10-04 15:04:20778 server_cert_verify_result_.Reset();
[email protected]d518cd92010-09-29 12:27:44779 completed_handshake_ = false;
[email protected]fbef13932010-11-23 12:38:53780
[email protected]515adc22013-01-09 16:01:23781 cert_authorities_.clear();
[email protected]fbef13932010-11-23 12:38:53782 client_auth_cert_needed_ = false;
[email protected]d518cd92010-09-29 12:27:44783}
784
785int SSLClientSocketOpenSSL::DoHandshakeLoop(int last_io_result) {
[email protected]d518cd92010-09-29 12:27:44786 int rv = last_io_result;
787 do {
788 // Default to STATE_NONE for next state.
789 // (This is a quirk carried over from the windows
790 // implementation. It makes reading the logs a bit harder.)
791 // State handlers can and often do call GotoState just
792 // to stay in the current state.
793 State state = next_handshake_state_;
794 GotoState(STATE_NONE);
795 switch (state) {
[email protected]d518cd92010-09-29 12:27:44796 case STATE_HANDSHAKE:
797 rv = DoHandshake();
798 break;
[email protected]d518cd92010-09-29 12:27:44799 case STATE_VERIFY_CERT:
800 DCHECK(rv == OK);
801 rv = DoVerifyCert(rv);
802 break;
803 case STATE_VERIFY_CERT_COMPLETE:
804 rv = DoVerifyCertComplete(rv);
805 break;
[email protected]013c17c2012-01-21 19:09:01806 case STATE_NONE:
[email protected]d518cd92010-09-29 12:27:44807 default:
808 rv = ERR_UNEXPECTED;
809 NOTREACHED() << "unexpected state" << state;
810 break;
811 }
812
[email protected]013c17c2012-01-21 19:09:01813 bool network_moved = DoTransportIO();
814 if (network_moved && next_handshake_state_ == STATE_HANDSHAKE) {
815 // In general we exit the loop if rv is ERR_IO_PENDING. In this
816 // special case we keep looping even if rv is ERR_IO_PENDING because
817 // the transport IO may allow DoHandshake to make progress.
818 rv = OK; // This causes us to stay in the loop.
819 }
820 } while (rv != ERR_IO_PENDING && next_handshake_state_ != STATE_NONE);
[email protected]d518cd92010-09-29 12:27:44821 return rv;
822}
823
824int SSLClientSocketOpenSSL::DoHandshake() {
[email protected]4b559b4d2011-04-14 17:37:14825 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
[email protected]d518cd92010-09-29 12:27:44826 int net_error = net::OK;
827 int rv = SSL_do_handshake(ssl_);
828
[email protected]718c9672010-12-02 10:04:10829 if (client_auth_cert_needed_) {
830 net_error = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
831 // If the handshake already succeeded (because the server requests but
832 // doesn't require a client cert), we need to invalidate the SSL session
833 // so that we won't try to resume the non-client-authenticated session in
834 // the next handshake. This will cause the server to ask for a client
835 // cert again.
836 if (rv == 1) {
837 // Remove from session cache but don't clear this connection.
838 SSL_SESSION* session = SSL_get_session(ssl_);
839 if (session) {
840 int rv = SSL_CTX_remove_session(SSL_get_SSL_CTX(ssl_), session);
841 LOG_IF(WARNING, !rv) << "Couldn't invalidate SSL session: " << session;
842 }
843 }
844 } else if (rv == 1) {
[email protected]fbef13932010-11-23 12:38:53845 if (trying_cached_session_ && logging::DEBUG_MODE) {
846 DVLOG(2) << "Result of session reuse for " << host_and_port_.ToString()
847 << " is: " << (SSL_session_reused(ssl_) ? "Success" : "Fail");
848 }
[email protected]d518cd92010-09-29 12:27:44849 // SSL handshake is completed. Let's verify the certificate.
[email protected]abc7e06d2010-10-06 15:40:35850 const bool got_cert = !!UpdateServerCert();
851 DCHECK(got_cert);
[email protected]784832b2012-02-22 06:43:45852 net_log_.AddEvent(
853 NetLog::TYPE_SSL_CERTIFICATES_RECEIVED,
[email protected]cd565142012-06-12 16:21:45854 base::Bind(&NetLogX509CertificateCallback,
855 base::Unretained(server_cert_.get())));
[email protected]abc7e06d2010-10-06 15:40:35856 GotoState(STATE_VERIFY_CERT);
[email protected]d518cd92010-09-29 12:27:44857 } else {
858 int ssl_error = SSL_get_error(ssl_, rv);
[email protected]109805a2010-12-07 18:17:06859 net_error = MapOpenSSLError(ssl_error, err_tracer);
[email protected]d518cd92010-09-29 12:27:44860
861 // If not done, stay in this state
[email protected]170e76c2010-10-04 15:04:20862 if (net_error == ERR_IO_PENDING) {
863 GotoState(STATE_HANDSHAKE);
864 } else {
865 LOG(ERROR) << "handshake failed; returned " << rv
866 << ", SSL error code " << ssl_error
867 << ", net_error " << net_error;
[email protected]109805a2010-12-07 18:17:06868 net_log_.AddEvent(
869 NetLog::TYPE_SSL_HANDSHAKE_ERROR,
[email protected]3aa4af042012-06-14 21:02:31870 CreateNetLogSSLErrorCallback(net_error, ssl_error));
[email protected]170e76c2010-10-04 15:04:20871 }
872 }
873 return net_error;
874}
875
[email protected]ae7c9f42011-11-21 11:41:16876// SelectNextProtoCallback is called by OpenSSL during the handshake. If the
877// server supports NPN, selects a protocol from the list that the server
878// provides. According to third_party/openssl/openssl/ssl/ssl_lib.c, the
879// callback can assume that |in| is syntactically valid.
[email protected]ea4a1c6a2010-12-09 13:33:28880int SSLClientSocketOpenSSL::SelectNextProtoCallback(unsigned char** out,
881 unsigned char* outlen,
882 const unsigned char* in,
883 unsigned int inlen) {
884#if defined(OPENSSL_NPN_NEGOTIATED)
885 if (ssl_config_.next_protos.empty()) {
[email protected]168a8412012-06-14 05:05:49886 *out = reinterpret_cast<uint8*>(
887 const_cast<char*>(kDefaultSupportedNPNProtocol));
888 *outlen = arraysize(kDefaultSupportedNPNProtocol) - 1;
889 npn_status_ = kNextProtoUnsupported;
[email protected]ea4a1c6a2010-12-09 13:33:28890 return SSL_TLSEXT_ERR_OK;
891 }
892
[email protected]ae7c9f42011-11-21 11:41:16893 // Assume there's no overlap between our protocols and the server's list.
[email protected]168a8412012-06-14 05:05:49894 npn_status_ = kNextProtoNoOverlap;
[email protected]ae7c9f42011-11-21 11:41:16895
896 // For each protocol in server preference order, see if we support it.
897 for (unsigned int i = 0; i < inlen; i += in[i] + 1) {
898 for (std::vector<std::string>::const_iterator
899 j = ssl_config_.next_protos.begin();
900 j != ssl_config_.next_protos.end(); ++j) {
901 if (in[i] == j->size() &&
902 memcmp(&in[i + 1], j->data(), in[i]) == 0) {
[email protected]168a8412012-06-14 05:05:49903 // We found a match.
[email protected]ae7c9f42011-11-21 11:41:16904 *out = const_cast<unsigned char*>(in) + i + 1;
905 *outlen = in[i];
[email protected]168a8412012-06-14 05:05:49906 npn_status_ = kNextProtoNegotiated;
[email protected]ae7c9f42011-11-21 11:41:16907 break;
908 }
909 }
[email protected]168a8412012-06-14 05:05:49910 if (npn_status_ == kNextProtoNegotiated)
[email protected]ae7c9f42011-11-21 11:41:16911 break;
912 }
[email protected]ea4a1c6a2010-12-09 13:33:28913
[email protected]168a8412012-06-14 05:05:49914 // If we didn't find a protocol, we select the first one from our list.
915 if (npn_status_ == kNextProtoNoOverlap) {
916 *out = reinterpret_cast<uint8*>(const_cast<char*>(
917 ssl_config_.next_protos[0].data()));
918 *outlen = ssl_config_.next_protos[0].size();
919 }
920
[email protected]ea4a1c6a2010-12-09 13:33:28921 npn_proto_.assign(reinterpret_cast<const char*>(*out), *outlen);
[email protected]55e973d2011-12-05 23:03:24922 server_protos_.assign(reinterpret_cast<const char*>(in), inlen);
[email protected]32e1dee2010-12-09 18:36:24923 DVLOG(2) << "next protocol: '" << npn_proto_ << "' status: " << npn_status_;
[email protected]ea4a1c6a2010-12-09 13:33:28924#endif
925 return SSL_TLSEXT_ERR_OK;
926}
927
[email protected]170e76c2010-10-04 15:04:20928int SSLClientSocketOpenSSL::DoVerifyCert(int result) {
929 DCHECK(server_cert_);
930 GotoState(STATE_VERIFY_CERT_COMPLETE);
[email protected]170e76c2010-10-04 15:04:20931
[email protected]70d66502011-09-23 00:55:08932 CertStatus cert_status;
[email protected]4dc832e2011-04-28 22:04:24933 if (ssl_config_.IsAllowedBadCert(server_cert_, &cert_status)) {
934 VLOG(1) << "Received an expected bad cert with status: " << cert_status;
935 server_cert_verify_result_.Reset();
936 server_cert_verify_result_.cert_status = cert_status;
[email protected]eb8414e2011-07-30 08:47:47937 server_cert_verify_result_.verified_cert = server_cert_;
[email protected]4dc832e2011-04-28 22:04:24938 return OK;
939 }
940
941 int flags = 0;
[email protected]170e76c2010-10-04 15:04:20942 if (ssl_config_.rev_checking_enabled)
[email protected]8738e0d72012-08-23 02:00:47943 flags |= CertVerifier::VERIFY_REV_CHECKING_ENABLED;
[email protected]170e76c2010-10-04 15:04:20944 if (ssl_config_.verify_ev_cert)
[email protected]8738e0d72012-08-23 02:00:47945 flags |= CertVerifier::VERIFY_EV_CERT;
[email protected]526b3f202012-03-15 22:44:30946 if (ssl_config_.cert_io_enabled)
[email protected]8738e0d72012-08-23 02:00:47947 flags |= CertVerifier::VERIFY_CERT_IO_ENABLED;
[email protected]822581d2010-12-16 17:27:15948 verifier_.reset(new SingleRequestCertVerifier(cert_verifier_));
[email protected]0f7804ec2011-10-07 20:04:18949 return verifier_->Verify(
950 server_cert_, host_and_port_.host(), flags,
[email protected]a642e33d2011-10-25 19:50:49951 NULL /* no CRL set */,
[email protected]0f7804ec2011-10-07 20:04:18952 &server_cert_verify_result_,
953 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete,
[email protected]8420c6f2011-10-19 13:54:57954 base::Unretained(this)),
955 net_log_);
[email protected]170e76c2010-10-04 15:04:20956}
957
958int SSLClientSocketOpenSSL::DoVerifyCertComplete(int result) {
959 verifier_.reset();
960
961 if (result == OK) {
962 // TODO(joth): Work out if we need to remember the intermediate CA certs
963 // when the server sends them to us, and do so here.
[email protected]2907525c2010-10-08 15:53:52964 } else {
965 DVLOG(1) << "DoVerifyCertComplete error " << ErrorToString(result)
966 << " (" << result << ")";
[email protected]d518cd92010-09-29 12:27:44967 }
968
[email protected]170e76c2010-10-04 15:04:20969 completed_handshake_ = true;
[email protected]170e76c2010-10-04 15:04:20970 // Exit DoHandshakeLoop and return the result to the caller to Connect.
971 DCHECK_EQ(STATE_NONE, next_handshake_state_);
972 return result;
973}
974
[email protected]170e76c2010-10-04 15:04:20975X509Certificate* SSLClientSocketOpenSSL::UpdateServerCert() {
976 if (server_cert_)
977 return server_cert_;
978
[email protected]4b559b4d2011-04-14 17:37:14979 crypto::ScopedOpenSSL<X509, X509_free> cert(SSL_get_peer_certificate(ssl_));
[email protected]2907525c2010-10-08 15:53:52980 if (!cert.get()) {
[email protected]170e76c2010-10-04 15:04:20981 LOG(WARNING) << "SSL_get_peer_certificate returned NULL";
982 return NULL;
983 }
984
[email protected]2907525c2010-10-08 15:53:52985 // Unlike SSL_get_peer_certificate, SSL_get_peer_cert_chain does not
986 // increment the reference so sk_X509_free does not need to be called.
987 STACK_OF(X509)* chain = SSL_get_peer_cert_chain(ssl_);
988 X509Certificate::OSCertHandles intermediates;
989 if (chain) {
990 for (int i = 0; i < sk_X509_num(chain); ++i)
991 intermediates.push_back(sk_X509_value(chain, i));
992 }
[email protected]72f508122011-07-19 05:12:17993 server_cert_ = X509Certificate::CreateFromHandle(cert.get(), intermediates);
[email protected]170e76c2010-10-04 15:04:20994 DCHECK(server_cert_);
[email protected]170e76c2010-10-04 15:04:20995
996 return server_cert_;
[email protected]d518cd92010-09-29 12:27:44997}
998
999bool SSLClientSocketOpenSSL::DoTransportIO() {
1000 bool network_moved = false;
[email protected]a85197e2012-05-22 19:07:281001 if (BufferSend() > 0)
1002 network_moved = true;
1003 if (!transport_recv_eof_ && BufferRecv() >= 0)
1004 network_moved = true;
[email protected]d518cd92010-09-29 12:27:441005 return network_moved;
1006}
1007
1008int SSLClientSocketOpenSSL::BufferSend(void) {
1009 if (transport_send_busy_)
1010 return ERR_IO_PENDING;
1011
1012 if (!send_buffer_) {
1013 // Get a fresh send buffer out of the send BIO.
1014 size_t max_read = BIO_ctrl_pending(transport_bio_);
1015 if (max_read > 0) {
1016 send_buffer_ = new DrainableIOBuffer(new IOBuffer(max_read), max_read);
1017 int read_bytes = BIO_read(transport_bio_, send_buffer_->data(), max_read);
1018 DCHECK_GT(read_bytes, 0);
1019 CHECK_EQ(static_cast<int>(max_read), read_bytes);
1020 }
1021 }
1022
1023 int rv = 0;
1024 while (send_buffer_) {
[email protected]83039bb2011-12-09 18:43:551025 rv = transport_->socket()->Write(
1026 send_buffer_,
1027 send_buffer_->BytesRemaining(),
1028 base::Bind(&SSLClientSocketOpenSSL::BufferSendComplete,
1029 base::Unretained(this)));
[email protected]d518cd92010-09-29 12:27:441030 if (rv == ERR_IO_PENDING) {
1031 transport_send_busy_ = true;
1032 return rv;
1033 }
1034 TransportWriteComplete(rv);
1035 }
1036 return rv;
1037}
1038
1039void SSLClientSocketOpenSSL::BufferSendComplete(int result) {
1040 transport_send_busy_ = false;
1041 TransportWriteComplete(result);
1042 OnSendComplete(result);
1043}
1044
1045void SSLClientSocketOpenSSL::TransportWriteComplete(int result) {
[email protected]abc7e06d2010-10-06 15:40:351046 DCHECK(ERR_IO_PENDING != result);
[email protected]d518cd92010-09-29 12:27:441047 if (result < 0) {
1048 // Got a socket write error; close the BIO to indicate this upward.
[email protected]abc7e06d2010-10-06 15:40:351049 DVLOG(1) << "TransportWriteComplete error " << result;
[email protected]d518cd92010-09-29 12:27:441050 (void)BIO_shutdown_wr(transport_bio_);
1051 send_buffer_ = NULL;
1052 } else {
1053 DCHECK(send_buffer_);
1054 send_buffer_->DidConsume(result);
1055 DCHECK_GE(send_buffer_->BytesRemaining(), 0);
1056 if (send_buffer_->BytesRemaining() <= 0)
1057 send_buffer_ = NULL;
1058 }
1059}
1060
1061int SSLClientSocketOpenSSL::BufferRecv(void) {
1062 if (transport_recv_busy_)
1063 return ERR_IO_PENDING;
1064
[email protected]30f201c2012-12-19 09:16:341065 // Determine how much was requested from |transport_bio_| that was not
1066 // actually available.
1067 size_t requested = BIO_ctrl_get_read_request(transport_bio_);
1068 if (requested == 0) {
1069 // This is not a perfect match of error codes, as no operation is
1070 // actually pending. However, returning 0 would be interpreted as
1071 // a possible sign of EOF, which is also an inappropriate match.
1072 return ERR_IO_PENDING;
1073 }
1074
1075 // Known Issue: While only reading |requested| data is the more correct
1076 // implementation, it has the downside of resulting in frequent reads:
1077 // One read for the SSL record header (~5 bytes) and one read for the SSL
1078 // record body. Rather than issuing these reads to the underlying socket
1079 // (and constantly allocating new IOBuffers), a single Read() request to
1080 // fill |transport_bio_| is issued. As long as an SSL client socket cannot
1081 // be gracefully shutdown (via SSL close alerts) and re-used for non-SSL
1082 // traffic, this over-subscribed Read()ing will not cause issues.
[email protected]d518cd92010-09-29 12:27:441083 size_t max_write = BIO_ctrl_get_write_guarantee(transport_bio_);
[email protected]d518cd92010-09-29 12:27:441084 if (!max_write)
1085 return ERR_IO_PENDING;
1086
1087 recv_buffer_ = new IOBuffer(max_write);
[email protected]83039bb2011-12-09 18:43:551088 int rv = transport_->socket()->Read(
1089 recv_buffer_, max_write,
1090 base::Bind(&SSLClientSocketOpenSSL::BufferRecvComplete,
1091 base::Unretained(this)));
[email protected]d518cd92010-09-29 12:27:441092 if (rv == ERR_IO_PENDING) {
1093 transport_recv_busy_ = true;
1094 } else {
1095 TransportReadComplete(rv);
1096 }
1097 return rv;
1098}
1099
1100void SSLClientSocketOpenSSL::BufferRecvComplete(int result) {
1101 TransportReadComplete(result);
1102 OnRecvComplete(result);
1103}
1104
1105void SSLClientSocketOpenSSL::TransportReadComplete(int result) {
[email protected]abc7e06d2010-10-06 15:40:351106 DCHECK(ERR_IO_PENDING != result);
1107 if (result <= 0) {
1108 DVLOG(1) << "TransportReadComplete result " << result;
1109 // Received 0 (end of file) or an error. Either way, bubble it up to the
1110 // SSL layer via the BIO. TODO(joth): consider stashing the error code, to
1111 // relay up to the SSL socket client (i.e. via DoReadCallback).
[email protected]a85197e2012-05-22 19:07:281112 if (result == 0)
1113 transport_recv_eof_ = true;
[email protected]abc7e06d2010-10-06 15:40:351114 BIO_set_mem_eof_return(transport_bio_, 0);
1115 (void)BIO_shutdown_wr(transport_bio_);
1116 } else {
1117 DCHECK(recv_buffer_);
[email protected]d518cd92010-09-29 12:27:441118 int ret = BIO_write(transport_bio_, recv_buffer_->data(), result);
1119 // A write into a memory BIO should always succeed.
1120 CHECK_EQ(result, ret);
[email protected]d518cd92010-09-29 12:27:441121 }
1122 recv_buffer_ = NULL;
1123 transport_recv_busy_ = false;
1124}
1125
1126void SSLClientSocketOpenSSL::DoConnectCallback(int rv) {
[email protected]83039bb2011-12-09 18:43:551127 if (!user_connect_callback_.is_null()) {
[email protected]dbf036f2011-12-06 23:33:241128 CompletionCallback c = user_connect_callback_;
1129 user_connect_callback_.Reset();
1130 c.Run(rv > OK ? OK : rv);
1131 }
[email protected]d518cd92010-09-29 12:27:441132}
1133
1134void SSLClientSocketOpenSSL::OnHandshakeIOComplete(int result) {
1135 int rv = DoHandshakeLoop(result);
1136 if (rv != ERR_IO_PENDING) {
[email protected]d7fd1782011-02-08 19:16:431137 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
[email protected]d518cd92010-09-29 12:27:441138 DoConnectCallback(rv);
1139 }
1140}
1141
1142void SSLClientSocketOpenSSL::OnSendComplete(int result) {
[email protected]013c17c2012-01-21 19:09:011143 if (next_handshake_state_ == STATE_HANDSHAKE) {
[email protected]d518cd92010-09-29 12:27:441144 // In handshake phase.
1145 OnHandshakeIOComplete(result);
1146 return;
1147 }
1148
1149 // OnSendComplete may need to call DoPayloadRead while the renegotiation
1150 // handshake is in progress.
1151 int rv_read = ERR_IO_PENDING;
1152 int rv_write = ERR_IO_PENDING;
1153 bool network_moved;
1154 do {
1155 if (user_read_buf_)
1156 rv_read = DoPayloadRead();
1157 if (user_write_buf_)
1158 rv_write = DoPayloadWrite();
1159 network_moved = DoTransportIO();
1160 } while (rv_read == ERR_IO_PENDING &&
1161 rv_write == ERR_IO_PENDING &&
[email protected]a85197e2012-05-22 19:07:281162 (user_read_buf_ || user_write_buf_) &&
[email protected]d518cd92010-09-29 12:27:441163 network_moved);
1164
1165 if (user_read_buf_ && rv_read != ERR_IO_PENDING)
1166 DoReadCallback(rv_read);
1167 if (user_write_buf_ && rv_write != ERR_IO_PENDING)
1168 DoWriteCallback(rv_write);
1169}
1170
1171void SSLClientSocketOpenSSL::OnRecvComplete(int result) {
[email protected]013c17c2012-01-21 19:09:011172 if (next_handshake_state_ == STATE_HANDSHAKE) {
[email protected]d518cd92010-09-29 12:27:441173 // In handshake phase.
1174 OnHandshakeIOComplete(result);
1175 return;
1176 }
1177
1178 // Network layer received some data, check if client requested to read
1179 // decrypted data.
1180 if (!user_read_buf_)
1181 return;
1182
1183 int rv = DoReadLoop(result);
1184 if (rv != ERR_IO_PENDING)
1185 DoReadCallback(rv);
1186}
1187
1188bool SSLClientSocketOpenSSL::IsConnected() const {
[email protected]f2da6ac2013-02-04 08:22:531189 // If the handshake has not yet completed.
1190 if (!completed_handshake_)
1191 return false;
1192 // If an asynchronous operation is still pending.
1193 if (user_read_buf_ || user_write_buf_)
1194 return true;
1195
1196 return transport_->socket()->IsConnected();
[email protected]d518cd92010-09-29 12:27:441197}
1198
1199bool SSLClientSocketOpenSSL::IsConnectedAndIdle() const {
[email protected]f2da6ac2013-02-04 08:22:531200 // If the handshake has not yet completed.
1201 if (!completed_handshake_)
1202 return false;
1203 // If an asynchronous operation is still pending.
1204 if (user_read_buf_ || user_write_buf_)
1205 return false;
1206 // If there is data waiting to be sent, or data read from the network that
1207 // has not yet been consumed.
1208 if (BIO_ctrl_pending(transport_bio_) > 0 ||
1209 BIO_ctrl_wpending(transport_bio_) > 0) {
1210 return false;
1211 }
1212
1213 return transport_->socket()->IsConnectedAndIdle();
[email protected]d518cd92010-09-29 12:27:441214}
1215
[email protected]a3528692012-06-08 00:11:421216int SSLClientSocketOpenSSL::GetPeerAddress(IPEndPoint* addressList) const {
[email protected]d518cd92010-09-29 12:27:441217 return transport_->socket()->GetPeerAddress(addressList);
1218}
1219
[email protected]e7f74da2011-04-19 23:49:351220int SSLClientSocketOpenSSL::GetLocalAddress(IPEndPoint* addressList) const {
1221 return transport_->socket()->GetLocalAddress(addressList);
1222}
1223
[email protected]d518cd92010-09-29 12:27:441224const BoundNetLog& SSLClientSocketOpenSSL::NetLog() const {
1225 return net_log_;
1226}
1227
1228void SSLClientSocketOpenSSL::SetSubresourceSpeculation() {
1229 if (transport_.get() && transport_->socket()) {
1230 transport_->socket()->SetSubresourceSpeculation();
1231 } else {
1232 NOTREACHED();
1233 }
1234}
1235
1236void SSLClientSocketOpenSSL::SetOmniboxSpeculation() {
1237 if (transport_.get() && transport_->socket()) {
1238 transport_->socket()->SetOmniboxSpeculation();
1239 } else {
1240 NOTREACHED();
1241 }
1242}
1243
1244bool SSLClientSocketOpenSSL::WasEverUsed() const {
1245 if (transport_.get() && transport_->socket())
1246 return transport_->socket()->WasEverUsed();
1247
1248 NOTREACHED();
1249 return false;
1250}
1251
[email protected]7f7e92392010-10-26 18:29:291252bool SSLClientSocketOpenSSL::UsingTCPFastOpen() const {
1253 if (transport_.get() && transport_->socket())
1254 return transport_->socket()->UsingTCPFastOpen();
1255
1256 NOTREACHED();
1257 return false;
1258}
1259
[email protected]d518cd92010-09-29 12:27:441260// Socket methods
1261
1262int SSLClientSocketOpenSSL::Read(IOBuffer* buf,
1263 int buf_len,
[email protected]3f55aa12011-12-07 02:03:331264 const CompletionCallback& callback) {
1265 user_read_buf_ = buf;
1266 user_read_buf_len_ = buf_len;
1267
1268 int rv = DoReadLoop(OK);
1269
1270 if (rv == ERR_IO_PENDING) {
[email protected]d518cd92010-09-29 12:27:441271 user_read_callback_ = callback;
1272 } else {
1273 user_read_buf_ = NULL;
1274 user_read_buf_len_ = 0;
1275 }
1276
1277 return rv;
1278}
1279
1280int SSLClientSocketOpenSSL::DoReadLoop(int result) {
1281 if (result < 0)
1282 return result;
1283
1284 bool network_moved;
1285 int rv;
1286 do {
1287 rv = DoPayloadRead();
1288 network_moved = DoTransportIO();
1289 } while (rv == ERR_IO_PENDING && network_moved);
1290
1291 return rv;
1292}
1293
1294int SSLClientSocketOpenSSL::Write(IOBuffer* buf,
1295 int buf_len,
[email protected]83039bb2011-12-09 18:43:551296 const CompletionCallback& callback) {
[email protected]d518cd92010-09-29 12:27:441297 user_write_buf_ = buf;
1298 user_write_buf_len_ = buf_len;
1299
1300 int rv = DoWriteLoop(OK);
1301
1302 if (rv == ERR_IO_PENDING) {
1303 user_write_callback_ = callback;
1304 } else {
1305 user_write_buf_ = NULL;
1306 user_write_buf_len_ = 0;
1307 }
1308
1309 return rv;
1310}
1311
1312int SSLClientSocketOpenSSL::DoWriteLoop(int result) {
1313 if (result < 0)
1314 return result;
1315
1316 bool network_moved;
1317 int rv;
1318 do {
1319 rv = DoPayloadWrite();
1320 network_moved = DoTransportIO();
1321 } while (rv == ERR_IO_PENDING && network_moved);
1322
1323 return rv;
1324}
1325
1326bool SSLClientSocketOpenSSL::SetReceiveBufferSize(int32 size) {
1327 return transport_->socket()->SetReceiveBufferSize(size);
1328}
1329
1330bool SSLClientSocketOpenSSL::SetSendBufferSize(int32 size) {
1331 return transport_->socket()->SetSendBufferSize(size);
1332}
1333
1334int SSLClientSocketOpenSSL::DoPayloadRead() {
[email protected]4b559b4d2011-04-14 17:37:141335 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
[email protected]4b768562013-02-16 04:10:071336
1337 int rv;
1338 if (pending_read_error_ != kNoPendingReadResult) {
1339 rv = pending_read_error_;
1340 pending_read_error_ = kNoPendingReadResult;
1341 if (rv == 0) {
1342 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED,
1343 rv, user_read_buf_->data());
1344 }
1345 return rv;
1346 }
1347
1348 int total_bytes_read = 0;
1349 do {
1350 rv = SSL_read(ssl_, user_read_buf_->data() + total_bytes_read,
1351 user_read_buf_len_ - total_bytes_read);
1352 if (rv > 0)
1353 total_bytes_read += rv;
1354 } while (total_bytes_read < user_read_buf_len_ && rv > 0);
1355
1356 if (total_bytes_read == user_read_buf_len_) {
1357 rv = total_bytes_read;
1358 } else {
1359 // Otherwise, an error occurred (rv <= 0). The error needs to be handled
1360 // immediately, while the OpenSSL errors are still available in
1361 // thread-local storage. However, the handled/remapped error code should
1362 // only be returned if no application data was already read; if it was, the
1363 // error code should be deferred until the next call of DoPayloadRead.
1364 //
1365 // If no data was read, |*next_result| will point to the return value of
1366 // this function. If at least some data was read, |*next_result| will point
1367 // to |pending_read_error_|, to be returned in a future call to
1368 // DoPayloadRead() (e.g.: after the current data is handled).
1369 int *next_result = &rv;
1370 if (total_bytes_read > 0) {
1371 pending_read_error_ = rv;
1372 rv = total_bytes_read;
1373 next_result = &pending_read_error_;
1374 }
1375
1376 if (client_auth_cert_needed_) {
1377 *next_result = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
1378 } else if (*next_result < 0) {
1379 int err = SSL_get_error(ssl_, *next_result);
1380 *next_result = MapOpenSSLError(err, err_tracer);
1381 if (rv > 0 && *next_result == ERR_IO_PENDING) {
1382 // If at least some data was read from SSL_read(), do not treat
1383 // insufficient data as an error to return in the next call to
1384 // DoPayloadRead() - instead, let the call fall through to check
1385 // SSL_read() again. This is because DoTransportIO() may complete
1386 // in between the next call to DoPayloadRead(), and thus it is
1387 // important to check SSL_read() on subsequent invocations to see
1388 // if a complete record may now be read.
1389 *next_result = kNoPendingReadResult;
1390 }
1391 }
1392 }
[email protected]d518cd92010-09-29 12:27:441393
[email protected]1d872d32011-05-19 02:45:331394 if (rv >= 0) {
[email protected]267a0d66d2011-06-01 21:15:191395 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, rv,
1396 user_read_buf_->data());
[email protected]1d872d32011-05-19 02:45:331397 }
[email protected]4b768562013-02-16 04:10:071398 return rv;
[email protected]d518cd92010-09-29 12:27:441399}
1400
1401int SSLClientSocketOpenSSL::DoPayloadWrite() {
[email protected]4b559b4d2011-04-14 17:37:141402 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
[email protected]d518cd92010-09-29 12:27:441403 int rv = SSL_write(ssl_, user_write_buf_->data(), user_write_buf_len_);
1404
[email protected]1d872d32011-05-19 02:45:331405 if (rv >= 0) {
[email protected]267a0d66d2011-06-01 21:15:191406 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_SENT, rv,
1407 user_write_buf_->data());
[email protected]d518cd92010-09-29 12:27:441408 return rv;
[email protected]1d872d32011-05-19 02:45:331409 }
[email protected]d518cd92010-09-29 12:27:441410
1411 int err = SSL_get_error(ssl_, rv);
[email protected]109805a2010-12-07 18:17:061412 return MapOpenSSLError(err, err_tracer);
[email protected]d518cd92010-09-29 12:27:441413}
1414
[email protected]7e5dd49f2010-12-08 18:33:491415} // namespace net