blob: ab4ba6c96e77989c976f2107a298d97d025348b5 [file] [log] [blame]
[email protected]d518cd92010-09-29 12:27:441// Copyright (c) 2010 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5// OpenSSL binding for SSLClientSocket. The class layout and general principle
6// of operation is derived from SSLClientSocketNSS.
7
8#include "net/socket/ssl_client_socket_openssl.h"
9
10#include <openssl/ssl.h>
11#include <openssl/err.h>
12
[email protected]fbef13932010-11-23 12:38:5313#include "base/lock.h"
[email protected]835d7c82010-10-14 04:38:3814#include "base/metrics/histogram.h"
[email protected]313834722010-11-17 09:57:1815#include "base/openssl_util.h"
[email protected]fbef13932010-11-23 12:38:5316#include "base/singleton.h"
[email protected]313834722010-11-17 09:57:1817#include "net/base/cert_verifier.h"
[email protected]d518cd92010-09-29 12:27:4418#include "net/base/net_errors.h"
[email protected]0c6523f2010-12-10 10:56:2419#include "net/base/openssl_private_key_store.h"
[email protected]718c9672010-12-02 10:04:1020#include "net/base/ssl_cert_request_info.h"
[email protected]d518cd92010-09-29 12:27:4421#include "net/base/ssl_connection_status_flags.h"
22#include "net/base/ssl_info.h"
[email protected]109805a2010-12-07 18:17:0623#include "net/socket/ssl_error_params.h"
[email protected]d518cd92010-09-29 12:27:4424
25namespace net {
26
27namespace {
28
29// Enable this to see logging for state machine state transitions.
30#if 0
[email protected]3b112772010-10-04 10:54:4931#define GotoState(s) do { DVLOG(2) << (void *)this << " " << __FUNCTION__ << \
[email protected]d518cd92010-09-29 12:27:4432 " jump to state " << s; \
33 next_handshake_state_ = s; } while (0)
34#else
35#define GotoState(s) next_handshake_state_ = s
36#endif
37
38const size_t kMaxRecvBufferSize = 4096;
[email protected]fbef13932010-11-23 12:38:5339const int kSessionCacheTimeoutSeconds = 60 * 60;
40const size_t kSessionCacheMaxEntires = 1024;
[email protected]d518cd92010-09-29 12:27:4441
[email protected]109805a2010-12-07 18:17:0642// This method doesn't seemed to have made it into the OpenSSL headers.
43unsigned long SSL_CIPHER_get_id(const SSL_CIPHER* cipher) { return cipher->id; }
44
45// Used for encoding the |connection_status| field of an SSLInfo object.
46int EncodeSSLConnectionStatus(int cipher_suite,
47 int compression,
48 int version) {
49 return ((cipher_suite & SSL_CONNECTION_CIPHERSUITE_MASK) <<
50 SSL_CONNECTION_CIPHERSUITE_SHIFT) |
51 ((compression & SSL_CONNECTION_COMPRESSION_MASK) <<
52 SSL_CONNECTION_COMPRESSION_SHIFT) |
53 ((version & SSL_CONNECTION_VERSION_MASK) <<
54 SSL_CONNECTION_VERSION_SHIFT);
55}
56
57// Returns the net SSL version number (see ssl_connection_status_flags.h) for
58// this SSL connection.
59int GetNetSSLVersion(SSL* ssl) {
[email protected]7e5dd49f2010-12-08 18:33:4960 switch (SSL_version(ssl)) {
[email protected]109805a2010-12-07 18:17:0661 case SSL2_VERSION:
62 return SSL_CONNECTION_VERSION_SSL2;
63 case SSL3_VERSION:
64 return SSL_CONNECTION_VERSION_SSL3;
65 case TLS1_VERSION:
66 return SSL_CONNECTION_VERSION_TLS1;
67 case 0x0302:
68 return SSL_CONNECTION_VERSION_TLS1_1;
69 case 0x0303:
70 return SSL_CONNECTION_VERSION_TLS1_2;
71 default:
72 return SSL_CONNECTION_VERSION_UNKNOWN;
73 }
74}
75
76int MapOpenSSLErrorSSL() {
77 // Walk down the error stack to find the SSLerr generated reason.
78 unsigned long error_code;
79 do {
80 error_code = ERR_get_error();
81 if (error_code == 0)
82 return ERR_SSL_PROTOCOL_ERROR;
83 } while (ERR_GET_LIB(error_code) != ERR_LIB_SSL);
84
85 DVLOG(1) << "OpenSSL SSL error, reason: " << ERR_GET_REASON(error_code)
86 << ", name: " << ERR_error_string(error_code, NULL);
87 switch (ERR_GET_REASON(error_code)) {
88 case SSL_R_READ_TIMEOUT_EXPIRED:
89 return ERR_TIMED_OUT;
90 case SSL_R_BAD_RESPONSE_ARGUMENT:
91 return ERR_INVALID_ARGUMENT;
92 case SSL_R_UNKNOWN_CERTIFICATE_TYPE:
93 case SSL_R_UNKNOWN_CIPHER_TYPE:
94 case SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE:
95 case SSL_R_UNKNOWN_PKEY_TYPE:
96 case SSL_R_UNKNOWN_REMOTE_ERROR_TYPE:
97 case SSL_R_UNKNOWN_SSL_VERSION:
98 return ERR_NOT_IMPLEMENTED;
[email protected]109805a2010-12-07 18:17:0699 case SSL_R_UNSUPPORTED_SSL_VERSION:
100 case SSL_R_NO_CIPHER_MATCH:
101 case SSL_R_NO_SHARED_CIPHER:
102 case SSL_R_TLSV1_ALERT_INSUFFICIENT_SECURITY:
103 case SSL_R_TLSV1_ALERT_PROTOCOL_VERSION:
104 return ERR_SSL_VERSION_OR_CIPHER_MISMATCH;
105 case SSL_R_SSLV3_ALERT_BAD_CERTIFICATE:
106 case SSL_R_SSLV3_ALERT_UNSUPPORTED_CERTIFICATE:
107 case SSL_R_SSLV3_ALERT_CERTIFICATE_REVOKED:
108 case SSL_R_SSLV3_ALERT_CERTIFICATE_EXPIRED:
109 case SSL_R_SSLV3_ALERT_CERTIFICATE_UNKNOWN:
110 case SSL_R_TLSV1_ALERT_ACCESS_DENIED:
111 case SSL_R_TLSV1_ALERT_UNKNOWN_CA:
112 return ERR_BAD_SSL_CLIENT_AUTH_CERT;
113 case SSL_R_BAD_DECOMPRESSION:
114 case SSL_R_SSLV3_ALERT_DECOMPRESSION_FAILURE:
115 return ERR_SSL_DECOMPRESSION_FAILURE_ALERT;
116 case SSL_R_SSLV3_ALERT_BAD_RECORD_MAC:
117 return ERR_SSL_BAD_RECORD_MAC_ALERT;
118 case SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED:
119 return ERR_SSL_UNSAFE_NEGOTIATION;
120 case SSL_R_WRONG_NUMBER_OF_KEY_BITS:
121 return ERR_SSL_WEAK_SERVER_EPHEMERAL_DH_KEY;
[email protected]aa4bb6892010-12-08 10:52:02122 // SSL_R_UNKNOWN_PROTOCOL is reported if premature application data is
123 // received (see http://crbug.com/42538), and also if all the protocol
124 // versions supported by the server were disabled in this socket instance.
125 // Mapped to ERR_SSL_PROTOCOL_ERROR for compatibility with other SSL sockets
126 // in the former scenario.
127 case SSL_R_UNKNOWN_PROTOCOL:
[email protected]109805a2010-12-07 18:17:06128 case SSL_R_SSL_HANDSHAKE_FAILURE:
129 case SSL_R_DECRYPTION_FAILED:
130 case SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC:
131 case SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG:
132 case SSL_R_DIGEST_CHECK_FAILED:
133 case SSL_R_DUPLICATE_COMPRESSION_ID:
134 case SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER:
135 case SSL_R_ENCRYPTED_LENGTH_TOO_LONG:
136 case SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST:
137 case SSL_R_EXCESSIVE_MESSAGE_SIZE:
138 case SSL_R_EXTRA_DATA_IN_MESSAGE:
139 case SSL_R_GOT_A_FIN_BEFORE_A_CCS:
140 case SSL_R_ILLEGAL_PADDING:
141 case SSL_R_INVALID_CHALLENGE_LENGTH:
142 case SSL_R_INVALID_COMMAND:
143 case SSL_R_INVALID_PURPOSE:
144 case SSL_R_INVALID_STATUS_RESPONSE:
145 case SSL_R_INVALID_TICKET_KEYS_LENGTH:
146 case SSL_R_KEY_ARG_TOO_LONG:
147 case SSL_R_READ_WRONG_PACKET_TYPE:
148 case SSL_R_SSLV3_ALERT_UNEXPECTED_MESSAGE:
149 // TODO(joth): SSL_R_SSLV3_ALERT_HANDSHAKE_FAILURE may be returned from the
150 // server after receiving ClientHello if there's no common supported cipher.
151 // Ideally we'd map that specific case to ERR_SSL_VERSION_OR_CIPHER_MISMATCH
152 // to match the NSS implementation. See also http://goo.gl/oMtZW
153 case SSL_R_SSLV3_ALERT_HANDSHAKE_FAILURE:
154 case SSL_R_SSLV3_ALERT_NO_CERTIFICATE:
155 case SSL_R_SSLV3_ALERT_ILLEGAL_PARAMETER:
156 case SSL_R_TLSV1_ALERT_DECODE_ERROR:
157 case SSL_R_TLSV1_ALERT_DECRYPTION_FAILED:
158 case SSL_R_TLSV1_ALERT_DECRYPT_ERROR:
159 case SSL_R_TLSV1_ALERT_EXPORT_RESTRICTION:
160 case SSL_R_TLSV1_ALERT_INTERNAL_ERROR:
161 case SSL_R_TLSV1_ALERT_NO_RENEGOTIATION:
162 case SSL_R_TLSV1_ALERT_RECORD_OVERFLOW:
163 case SSL_R_TLSV1_ALERT_USER_CANCELLED:
164 return ERR_SSL_PROTOCOL_ERROR;
165 default:
166 LOG(WARNING) << "Unmapped error reason: " << ERR_GET_REASON(error_code);
167 return ERR_FAILED;
168 }
169}
170
171// Converts an OpenSSL error code into a net error code, walking the OpenSSL
172// error stack if needed. Note that |tracer| is not currently used in the
173// implementation, but is passed in anyway as this ensures the caller will clear
174// any residual codes left on the error stack.
175int MapOpenSSLError(int err, const base::OpenSSLErrStackTracer& tracer) {
[email protected]d518cd92010-09-29 12:27:44176 switch (err) {
177 case SSL_ERROR_WANT_READ:
178 case SSL_ERROR_WANT_WRITE:
179 return ERR_IO_PENDING;
[email protected]170e76c2010-10-04 15:04:20180 case SSL_ERROR_SYSCALL:
[email protected]abc7e06d2010-10-06 15:40:35181 DVLOG(1) << "OpenSSL SYSCALL error, errno " << errno;
[email protected]170e76c2010-10-04 15:04:20182 return ERR_SSL_PROTOCOL_ERROR;
[email protected]109805a2010-12-07 18:17:06183 case SSL_ERROR_SSL:
184 return MapOpenSSLErrorSSL();
[email protected]d518cd92010-09-29 12:27:44185 default:
186 // TODO(joth): Implement full mapping.
187 LOG(WARNING) << "Unknown OpenSSL error " << err;
[email protected]d518cd92010-09-29 12:27:44188 return ERR_SSL_PROTOCOL_ERROR;
189 }
190}
191
[email protected]313834722010-11-17 09:57:18192// We do certificate verification after handshake, so we disable the default
193// by registering a no-op verify function.
194int NoOpVerifyCallback(X509_STORE_CTX*, void *) {
195 DVLOG(3) << "skipping cert verify";
196 return 1;
197}
198
[email protected]fbef13932010-11-23 12:38:53199// OpenSSL manages a cache of SSL_SESSION, this class provides the application
200// side policy for that cache about session re-use: we retain one session per
201// unique HostPortPair.
202class SSLSessionCache {
203 public:
204 SSLSessionCache() {}
205
206 void OnSessionAdded(const HostPortPair& host_and_port, SSL_SESSION* session) {
207 // Declare the session cleaner-upper before the lock, so any call into
208 // OpenSSL to free the session will happen after the lock is released.
209 base::ScopedOpenSSL<SSL_SESSION, SSL_SESSION_free> session_to_free;
210 AutoLock lock(lock_);
211
212 DCHECK_EQ(0U, session_map_.count(session));
213 std::pair<HostPortMap::iterator, bool> res =
214 host_port_map_.insert(std::make_pair(host_and_port, session));
215 if (!res.second) { // Already exists: replace old entry.
216 session_to_free.reset(res.first->second);
217 session_map_.erase(session_to_free.get());
218 res.first->second = session;
219 }
220 DVLOG(2) << "Adding session " << session << " => "
221 << host_and_port.ToString() << ", new entry = " << res.second;
222 DCHECK(host_port_map_[host_and_port] == session);
223 session_map_[session] = res.first;
224 DCHECK_EQ(host_port_map_.size(), session_map_.size());
225 DCHECK_LE(host_port_map_.size(), kSessionCacheMaxEntires);
[email protected]313834722010-11-17 09:57:18226 }
[email protected]fbef13932010-11-23 12:38:53227
228 void OnSessionRemoved(SSL_SESSION* session) {
229 // Declare the session cleaner-upper before the lock, so any call into
230 // OpenSSL to free the session will happen after the lock is released.
231 base::ScopedOpenSSL<SSL_SESSION, SSL_SESSION_free> session_to_free;
232 AutoLock lock(lock_);
233
234 SessionMap::iterator it = session_map_.find(session);
235 if (it == session_map_.end())
236 return;
237 DVLOG(2) << "Remove session " << session << " => "
238 << it->second->first.ToString();
239 DCHECK(it->second->second == session);
240 host_port_map_.erase(it->second);
241 session_map_.erase(it);
242 session_to_free.reset(session);
243 DCHECK_EQ(host_port_map_.size(), session_map_.size());
[email protected]313834722010-11-17 09:57:18244 }
[email protected]fbef13932010-11-23 12:38:53245
246 // Looks up the host:port in the cache, and if a session is found it is added
247 // to |ssl|, returning true on success.
248 bool SetSSLSession(SSL* ssl, const HostPortPair& host_and_port) {
249 AutoLock lock(lock_);
250 HostPortMap::iterator it = host_port_map_.find(host_and_port);
251 if (it == host_port_map_.end())
252 return false;
253 DVLOG(2) << "Lookup session: " << it->second << " => "
254 << host_and_port.ToString();
255 SSL_SESSION* session = it->second;
256 DCHECK(session);
257 DCHECK(session_map_[session] == it);
258 // Ideally we'd release |lock_| before calling into OpenSSL here, however
259 // that opens a small risk |session| will go out of scope before it is used.
260 // Alternatively we would take a temporary local refcount on |session|,
261 // except OpenSSL does not provide a public API for adding a ref (c.f.
262 // SSL_SESSION_free which decrements the ref).
263 return SSL_set_session(ssl, session) == 1;
264 }
265
266 private:
267 // A pair of maps to allow bi-directional lookups between host:port and an
[email protected]109805a2010-12-07 18:17:06268 // associated session.
[email protected]fbef13932010-11-23 12:38:53269 // TODO(joth): When client certificates are implemented we should key the
270 // cache on the client certificate used in addition to the host-port pair.
271 typedef std::map<HostPortPair, SSL_SESSION*> HostPortMap;
272 typedef std::map<SSL_SESSION*, HostPortMap::iterator> SessionMap;
273 HostPortMap host_port_map_;
274 SessionMap session_map_;
275
276 // Protects access to both the above maps.
277 Lock lock_;
278
279 DISALLOW_COPY_AND_ASSIGN(SSLSessionCache);
[email protected]313834722010-11-17 09:57:18280};
281
[email protected]fbef13932010-11-23 12:38:53282class SSLContext {
283 public:
[email protected]b29af7d2010-12-14 11:52:47284 static SSLContext* GetInstance() { return Singleton<SSLContext>::get(); }
[email protected]fbef13932010-11-23 12:38:53285 SSL_CTX* ssl_ctx() { return ssl_ctx_.get(); }
286 SSLSessionCache* session_cache() { return &session_cache_; }
287
288 SSLClientSocketOpenSSL* GetClientSocketFromSSL(SSL* ssl) {
289 DCHECK(ssl);
290 SSLClientSocketOpenSSL* socket = static_cast<SSLClientSocketOpenSSL*>(
291 SSL_get_ex_data(ssl, ssl_socket_data_index_));
292 DCHECK(socket);
293 return socket;
294 }
295
296 bool SetClientSocketForSSL(SSL* ssl, SSLClientSocketOpenSSL* socket) {
297 return SSL_set_ex_data(ssl, ssl_socket_data_index_, socket) != 0;
298 }
299
300 private:
301 friend struct DefaultSingletonTraits<SSLContext>;
302
303 SSLContext() {
304 base::EnsureOpenSSLInit();
305 ssl_socket_data_index_ = SSL_get_ex_new_index(0, 0, 0, 0, 0);
306 DCHECK_NE(ssl_socket_data_index_, -1);
307 ssl_ctx_.reset(SSL_CTX_new(SSLv23_client_method()));
308 SSL_CTX_set_cert_verify_callback(ssl_ctx_.get(), NoOpVerifyCallback, NULL);
309 SSL_CTX_set_session_cache_mode(ssl_ctx_.get(), SSL_SESS_CACHE_CLIENT);
310 SSL_CTX_sess_set_new_cb(ssl_ctx_.get(), NewSessionCallbackStatic);
311 SSL_CTX_sess_set_remove_cb(ssl_ctx_.get(), RemoveSessionCallbackStatic);
312 SSL_CTX_set_timeout(ssl_ctx_.get(), kSessionCacheTimeoutSeconds);
313 SSL_CTX_sess_set_cache_size(ssl_ctx_.get(), kSessionCacheMaxEntires);
[email protected]718c9672010-12-02 10:04:10314 SSL_CTX_set_client_cert_cb(ssl_ctx_.get(), ClientCertCallback);
[email protected]ea4a1c6a2010-12-09 13:33:28315#if defined(OPENSSL_NPN_NEGOTIATED)
316 // TODO(kristianm): Only select this if ssl_config_.next_proto is not empty.
317 // It would be better if the callback were not a global setting,
318 // but that is an OpenSSL issue.
319 SSL_CTX_set_next_proto_select_cb(ssl_ctx_.get(), SelectNextProtoCallback,
320 NULL);
321#endif
[email protected]fbef13932010-11-23 12:38:53322 }
323
324 static int NewSessionCallbackStatic(SSL* ssl, SSL_SESSION* session) {
[email protected]b29af7d2010-12-14 11:52:47325 return GetInstance()->NewSessionCallback(ssl, session);
[email protected]fbef13932010-11-23 12:38:53326 }
327
328 int NewSessionCallback(SSL* ssl, SSL_SESSION* session) {
329 SSLClientSocketOpenSSL* socket = GetClientSocketFromSSL(ssl);
330 session_cache_.OnSessionAdded(socket->host_and_port(), session);
331 return 1; // 1 => We took ownership of |session|.
332 }
333
334 static void RemoveSessionCallbackStatic(SSL_CTX* ctx, SSL_SESSION* session) {
[email protected]b29af7d2010-12-14 11:52:47335 return GetInstance()->RemoveSessionCallback(ctx, session);
[email protected]fbef13932010-11-23 12:38:53336 }
337
338 void RemoveSessionCallback(SSL_CTX* ctx, SSL_SESSION* session) {
339 DCHECK(ctx == ssl_ctx());
340 session_cache_.OnSessionRemoved(session);
341 }
342
[email protected]718c9672010-12-02 10:04:10343 static int ClientCertCallback(SSL* ssl, X509** x509, EVP_PKEY** pkey) {
[email protected]b29af7d2010-12-14 11:52:47344 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
[email protected]718c9672010-12-02 10:04:10345 CHECK(socket);
346 return socket->ClientCertRequestCallback(ssl, x509, pkey);
347 }
348
[email protected]ea4a1c6a2010-12-09 13:33:28349 static int SelectNextProtoCallback(SSL* ssl,
350 unsigned char** out, unsigned char* outlen,
351 const unsigned char* in,
352 unsigned int inlen, void* arg) {
[email protected]b29af7d2010-12-14 11:52:47353 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
[email protected]ea4a1c6a2010-12-09 13:33:28354 return socket->SelectNextProtoCallback(out, outlen, in, inlen);
355 }
356
[email protected]fbef13932010-11-23 12:38:53357 // This is the index used with SSL_get_ex_data to retrieve the owner
358 // SSLClientSocketOpenSSL object from an SSL instance.
359 int ssl_socket_data_index_;
360
361 base::ScopedOpenSSL<SSL_CTX, SSL_CTX_free> ssl_ctx_;
362 SSLSessionCache session_cache_;
363};
[email protected]313834722010-11-17 09:57:18364
[email protected]fb10e2282010-12-01 17:08:48365// Utility to construct the appropriate set & clear masks for use the OpenSSL
366// options and mode configuration functions. (SSL_set_options etc)
367struct SslSetClearMask {
368 SslSetClearMask() : set_mask(0), clear_mask(0) {}
369 void ConfigureFlag(long flag, bool state) {
370 (state ? set_mask : clear_mask) |= flag;
371 // Make sure we haven't got any intersection in the set & clear options.
372 DCHECK_EQ(0, set_mask & clear_mask) << flag << ":" << state;
373 }
374 long set_mask;
375 long clear_mask;
376};
377
[email protected]3b112772010-10-04 10:54:49378} // namespace
[email protected]d518cd92010-09-29 12:27:44379
380SSLClientSocketOpenSSL::SSLClientSocketOpenSSL(
381 ClientSocketHandle* transport_socket,
[email protected]055d7f22010-11-15 12:03:12382 const HostPortPair& host_and_port,
[email protected]d518cd92010-09-29 12:27:44383 const SSLConfig& ssl_config)
384 : ALLOW_THIS_IN_INITIALIZER_LIST(buffer_send_callback_(
385 this, &SSLClientSocketOpenSSL::BufferSendComplete)),
386 ALLOW_THIS_IN_INITIALIZER_LIST(buffer_recv_callback_(
387 this, &SSLClientSocketOpenSSL::BufferRecvComplete)),
388 transport_send_busy_(false),
389 transport_recv_busy_(false),
390 user_connect_callback_(NULL),
391 user_read_callback_(NULL),
392 user_write_callback_(NULL),
[email protected]fbef13932010-11-23 12:38:53393 completed_handshake_(false),
[email protected]d518cd92010-09-29 12:27:44394 client_auth_cert_needed_(false),
[email protected]170e76c2010-10-04 15:04:20395 ALLOW_THIS_IN_INITIALIZER_LIST(handshake_io_callback_(
396 this, &SSLClientSocketOpenSSL::OnHandshakeIOComplete)),
[email protected]d518cd92010-09-29 12:27:44397 ssl_(NULL),
398 transport_bio_(NULL),
399 transport_(transport_socket),
[email protected]055d7f22010-11-15 12:03:12400 host_and_port_(host_and_port),
[email protected]d518cd92010-09-29 12:27:44401 ssl_config_(ssl_config),
[email protected]fbef13932010-11-23 12:38:53402 trying_cached_session_(false),
[email protected]ea4a1c6a2010-12-09 13:33:28403 npn_status_(kNextProtoUnsupported),
[email protected]d518cd92010-09-29 12:27:44404 net_log_(transport_socket->socket()->NetLog()) {
405}
406
407SSLClientSocketOpenSSL::~SSLClientSocketOpenSSL() {
408 Disconnect();
409}
410
[email protected]d518cd92010-09-29 12:27:44411bool SSLClientSocketOpenSSL::Init() {
[email protected]9e733f32010-10-04 18:19:08412 DCHECK(!ssl_);
413 DCHECK(!transport_bio_);
414
[email protected]b29af7d2010-12-14 11:52:47415 SSLContext* context = SSLContext::GetInstance();
[email protected]fbef13932010-11-23 12:38:53416 base::OpenSSLErrStackTracer err_tracer(FROM_HERE);
[email protected]d518cd92010-09-29 12:27:44417
[email protected]fbef13932010-11-23 12:38:53418 ssl_ = SSL_new(context->ssl_ctx());
419 if (!ssl_ || !context->SetClientSocketForSSL(ssl_, this))
[email protected]d518cd92010-09-29 12:27:44420 return false;
[email protected]fbef13932010-11-23 12:38:53421
422 if (!SSL_set_tlsext_host_name(ssl_, host_and_port_.host().c_str()))
423 return false;
424
425 trying_cached_session_ =
426 context->session_cache()->SetSSLSession(ssl_, host_and_port_);
[email protected]d518cd92010-09-29 12:27:44427
428 BIO* ssl_bio = NULL;
[email protected]fbef13932010-11-23 12:38:53429 // 0 => use default buffer sizes.
430 if (!BIO_new_bio_pair(&ssl_bio, 0, &transport_bio_, 0))
[email protected]d518cd92010-09-29 12:27:44431 return false;
[email protected]d518cd92010-09-29 12:27:44432 DCHECK(ssl_bio);
433 DCHECK(transport_bio_);
434
435 SSL_set_bio(ssl_, ssl_bio, ssl_bio);
436
[email protected]9e733f32010-10-04 18:19:08437 // OpenSSL defaults some options to on, others to off. To avoid ambiguity,
438 // set everything we care about to an absolute value.
[email protected]fb10e2282010-12-01 17:08:48439 SslSetClearMask options;
440 options.ConfigureFlag(SSL_OP_NO_SSLv2, true);
441 options.ConfigureFlag(SSL_OP_NO_SSLv3, !ssl_config_.ssl3_enabled);
442 options.ConfigureFlag(SSL_OP_NO_TLSv1, !ssl_config_.tls1_enabled);
443
444#if defined(SSL_OP_NO_COMPRESSION)
445 // If TLS was disabled also disable compression, to provide maximum site
446 // compatibility in the case of protocol fallback. See http://crbug.com/31628
447 options.ConfigureFlag(SSL_OP_NO_COMPRESSION, !ssl_config_.tls1_enabled);
448#endif
[email protected]9e733f32010-10-04 18:19:08449
450 // TODO(joth): Set this conditionally, see http://crbug.com/55410
[email protected]fb10e2282010-12-01 17:08:48451 options.ConfigureFlag(SSL_OP_LEGACY_SERVER_CONNECT, true);
[email protected]9e733f32010-10-04 18:19:08452
[email protected]fb10e2282010-12-01 17:08:48453 SSL_set_options(ssl_, options.set_mask);
454 SSL_clear_options(ssl_, options.clear_mask);
[email protected]9e733f32010-10-04 18:19:08455
[email protected]fb10e2282010-12-01 17:08:48456 // Same as above, this time for the SSL mode.
457 SslSetClearMask mode;
[email protected]9e733f32010-10-04 18:19:08458
[email protected]fb10e2282010-12-01 17:08:48459#if defined(SSL_MODE_HANDSHAKE_CUTTHROUGH)
460 mode.ConfigureFlag(SSL_MODE_HANDSHAKE_CUTTHROUGH,
461 ssl_config_.false_start_enabled &&
462 !SSLConfigService::IsKnownFalseStartIncompatibleServer(
463 host_and_port_.host()));
464#endif
465
466#if defined(SSL_MODE_RELEASE_BUFFERS)
467 mode.ConfigureFlag(SSL_MODE_RELEASE_BUFFERS, true);
468#endif
469
470#if defined(SSL_MODE_SMALL_BUFFERS)
471 mode.ConfigureFlag(SSL_MODE_SMALL_BUFFERS, true);
472#endif
473
474 SSL_set_mode(ssl_, mode.set_mask);
475 SSL_clear_mode(ssl_, mode.clear_mask);
[email protected]109805a2010-12-07 18:17:06476
477 // Removing ciphers by ID from OpenSSL is a bit involved as we must use the
478 // textual name with SSL_set_cipher_list because there is no public API to
479 // directly remove a cipher by ID.
480 STACK_OF(SSL_CIPHER)* ciphers = SSL_get_ciphers(ssl_);
481 DCHECK(ciphers);
482 // See SSLConfig::disabled_cipher_suites for description of the suites
483 // disabled by default.
484 std::string command("DEFAULT:!NULL:!aNULL:!IDEA:!FZA");
485 // Walk through all the installed ciphers, seeing if any need to be
486 // appended to the cipher removal |command|.
487 for (int i = 0; i < sk_SSL_CIPHER_num(ciphers); ++i) {
488 const SSL_CIPHER* cipher = sk_SSL_CIPHER_value(ciphers, i);
489 const uint16 id = SSL_CIPHER_get_id(cipher);
490 // Remove any ciphers with a strength of less than 80 bits. Note the NSS
491 // implementation uses "effective" bits here but OpenSSL does not provide
492 // this detail. This only impacts Triple DES: reports 112 vs. 168 bits,
493 // both of which are greater than 80 anyway.
494 bool disable = SSL_CIPHER_get_bits(cipher, NULL) < 80;
495 if (!disable) {
496 disable = std::find(ssl_config_.disabled_cipher_suites.begin(),
497 ssl_config_.disabled_cipher_suites.end(), id) !=
498 ssl_config_.disabled_cipher_suites.end();
499 }
500 if (disable) {
501 const char* name = SSL_CIPHER_get_name(cipher);
502 DVLOG(3) << "Found cipher to remove: '" << name << "', ID: " << id
503 << " strength: " << SSL_CIPHER_get_bits(cipher, NULL);
504 command.append(":!");
505 command.append(name);
506 }
507 }
508 int rv = SSL_set_cipher_list(ssl_, command.c_str());
509 // If this fails (rv = 0) it means there are no ciphers enabled on this SSL.
510 // This will almost certainly result in the socket failing to complete the
511 // handshake at which point the appropriate error is bubbled up to the client.
512 LOG_IF(WARNING, rv != 1) << "SSL_set_cipher_list('" << command << "') "
513 "returned " << rv;
[email protected]d518cd92010-09-29 12:27:44514 return true;
515}
516
[email protected]5ac981e182010-12-06 17:56:27517int SSLClientSocketOpenSSL::ClientCertRequestCallback(SSL* ssl,
518 X509** x509,
519 EVP_PKEY** pkey) {
520 DVLOG(3) << "OpenSSL ClientCertRequestCallback called";
521 DCHECK(ssl == ssl_);
522 DCHECK(*x509 == NULL);
523 DCHECK(*pkey == NULL);
524
525 if (!ssl_config_.send_client_cert) {
526 client_auth_cert_needed_ = true;
527 return -1; // Suspends handshake.
528 }
529
530 // Second pass: a client certificate should have been selected.
531 if (ssl_config_.client_cert) {
[email protected]0c6523f2010-12-10 10:56:24532 EVP_PKEY* privkey = OpenSSLPrivateKeyStore::GetInstance()->FetchPrivateKey(
533 X509_PUBKEY_get(X509_get_X509_PUBKEY(
534 ssl_config_.client_cert->os_cert_handle())));
535 if (privkey) {
536 // TODO(joth): (copied from NSS) We should wait for server certificate
537 // verification before sending our credentials. See http://crbug.com/13934
538 *x509 = X509Certificate::DupOSCertHandle(
539 ssl_config_.client_cert->os_cert_handle());
540 *pkey = privkey;
541 return 1;
542 }
543 LOG(WARNING) << "Client cert found without private key";
[email protected]5ac981e182010-12-06 17:56:27544 }
545
546 // Send no client certificate.
547 return 0;
548}
549
[email protected]d518cd92010-09-29 12:27:44550// SSLClientSocket methods
551
552void SSLClientSocketOpenSSL::GetSSLInfo(SSLInfo* ssl_info) {
[email protected]170e76c2010-10-04 15:04:20553 ssl_info->Reset();
554 if (!server_cert_)
555 return;
556
[email protected]170e76c2010-10-04 15:04:20557 ssl_info->cert = server_cert_;
558 ssl_info->cert_status = server_cert_verify_result_.cert_status;
[email protected]2907525c2010-10-08 15:53:52559
560 const SSL_CIPHER* cipher = SSL_get_current_cipher(ssl_);
561 CHECK(cipher);
562 ssl_info->security_bits = SSL_CIPHER_get_bits(cipher, NULL);
[email protected]2907525c2010-10-08 15:53:52563 const COMP_METHOD* compression = SSL_get_current_compression(ssl_);
[email protected]109805a2010-12-07 18:17:06564
565 ssl_info->connection_status = EncodeSSLConnectionStatus(
566 SSL_CIPHER_get_id(cipher),
567 compression ? compression->type : 0,
568 GetNetSSLVersion(ssl_));
[email protected]9e733f32010-10-04 18:19:08569
570 bool peer_supports_renego_ext = !!SSL_get_secure_renegotiation_support(ssl_);
571 if (!peer_supports_renego_ext)
572 ssl_info->connection_status |= SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION;
[email protected]109805a2010-12-07 18:17:06573 UMA_HISTOGRAM_ENUMERATION("Net.RenegotiationExtensionSupported",
574 implicit_cast<int>(peer_supports_renego_ext), 2);
[email protected]9e733f32010-10-04 18:19:08575
576 if (ssl_config_.ssl3_fallback)
577 ssl_info->connection_status |= SSL_CONNECTION_SSL3_FALLBACK;
[email protected]109805a2010-12-07 18:17:06578
579 DVLOG(3) << "Encoded connection status: cipher suite = "
580 << SSLConnectionStatusToCipherSuite(ssl_info->connection_status)
581 << " compression = "
582 << SSLConnectionStatusToCompression(ssl_info->connection_status)
583 << " version = "
584 << SSLConnectionStatusToVersion(ssl_info->connection_status);
[email protected]d518cd92010-09-29 12:27:44585}
586
587void SSLClientSocketOpenSSL::GetSSLCertRequestInfo(
588 SSLCertRequestInfo* cert_request_info) {
[email protected]718c9672010-12-02 10:04:10589 cert_request_info->host_and_port = host_and_port_.ToString();
590 cert_request_info->client_certs = client_certs_;
[email protected]d518cd92010-09-29 12:27:44591}
592
593SSLClientSocket::NextProtoStatus SSLClientSocketOpenSSL::GetNextProto(
594 std::string* proto) {
[email protected]ea4a1c6a2010-12-09 13:33:28595 *proto = npn_proto_;
596 return npn_status_;
[email protected]d518cd92010-09-29 12:27:44597}
598
599void SSLClientSocketOpenSSL::DoReadCallback(int rv) {
600 // Since Run may result in Read being called, clear |user_read_callback_|
601 // up front.
602 CompletionCallback* c = user_read_callback_;
603 user_read_callback_ = NULL;
604 user_read_buf_ = NULL;
605 user_read_buf_len_ = 0;
606 c->Run(rv);
607}
608
609void SSLClientSocketOpenSSL::DoWriteCallback(int rv) {
610 // Since Run may result in Write being called, clear |user_write_callback_|
611 // up front.
612 CompletionCallback* c = user_write_callback_;
613 user_write_callback_ = NULL;
614 user_write_buf_ = NULL;
615 user_write_buf_len_ = 0;
616 c->Run(rv);
617}
618
619// ClientSocket methods
620
621int SSLClientSocketOpenSSL::Connect(CompletionCallback* callback) {
622 net_log_.BeginEvent(NetLog::TYPE_SSL_CONNECT, NULL);
623
[email protected]d518cd92010-09-29 12:27:44624 // Set up new ssl object.
625 if (!Init()) {
626 net_log_.EndEvent(NetLog::TYPE_SSL_CONNECT, NULL);
627 return ERR_UNEXPECTED;
628 }
629
630 // Set SSL to client mode. Handshake happens in the loop below.
631 SSL_set_connect_state(ssl_);
632
633 GotoState(STATE_HANDSHAKE);
634 int rv = DoHandshakeLoop(net::OK);
635 if (rv == ERR_IO_PENDING) {
636 user_connect_callback_ = callback;
637 } else {
638 net_log_.EndEvent(NetLog::TYPE_SSL_CONNECT, NULL);
639 }
640
641 return rv > OK ? OK : rv;
642}
643
644void SSLClientSocketOpenSSL::Disconnect() {
[email protected]170e76c2010-10-04 15:04:20645 if (ssl_) {
646 SSL_free(ssl_);
647 ssl_ = NULL;
648 }
649 if (transport_bio_) {
650 BIO_free_all(transport_bio_);
651 transport_bio_ = NULL;
652 }
653
654 // Shut down anything that may call us back (through buffer_send_callback_,
655 // buffer_recv_callback, or handshake_io_callback_).
656 verifier_.reset();
657 transport_->socket()->Disconnect();
658
[email protected]d518cd92010-09-29 12:27:44659 // Null all callbacks, delete all buffers.
660 transport_send_busy_ = false;
661 send_buffer_ = NULL;
662 transport_recv_busy_ = false;
663 recv_buffer_ = NULL;
664
665 user_connect_callback_ = NULL;
666 user_read_callback_ = NULL;
667 user_write_callback_ = NULL;
668 user_read_buf_ = NULL;
669 user_read_buf_len_ = 0;
670 user_write_buf_ = NULL;
671 user_write_buf_len_ = 0;
672
[email protected]170e76c2010-10-04 15:04:20673 server_cert_verify_result_.Reset();
[email protected]d518cd92010-09-29 12:27:44674 completed_handshake_ = false;
[email protected]fbef13932010-11-23 12:38:53675
676 client_certs_.clear();
677 client_auth_cert_needed_ = false;
[email protected]d518cd92010-09-29 12:27:44678}
679
680int SSLClientSocketOpenSSL::DoHandshakeLoop(int last_io_result) {
681 bool network_moved;
682 int rv = last_io_result;
683 do {
684 // Default to STATE_NONE for next state.
685 // (This is a quirk carried over from the windows
686 // implementation. It makes reading the logs a bit harder.)
687 // State handlers can and often do call GotoState just
688 // to stay in the current state.
689 State state = next_handshake_state_;
690 GotoState(STATE_NONE);
691 switch (state) {
692 case STATE_NONE:
693 // we're just pumping data between the buffer and the network
694 break;
695 case STATE_HANDSHAKE:
696 rv = DoHandshake();
697 break;
[email protected]d518cd92010-09-29 12:27:44698 case STATE_VERIFY_CERT:
699 DCHECK(rv == OK);
700 rv = DoVerifyCert(rv);
701 break;
702 case STATE_VERIFY_CERT_COMPLETE:
703 rv = DoVerifyCertComplete(rv);
704 break;
[email protected]d518cd92010-09-29 12:27:44705 default:
706 rv = ERR_UNEXPECTED;
707 NOTREACHED() << "unexpected state" << state;
708 break;
709 }
710
711 // To avoid getting an ERR_IO_PENDING here after handshake complete.
712 if (next_handshake_state_ == STATE_NONE)
713 break;
714
715 // Do the actual network I/O.
716 network_moved = DoTransportIO();
717 } while ((rv != ERR_IO_PENDING || network_moved) &&
718 next_handshake_state_ != STATE_NONE);
719 return rv;
720}
721
722int SSLClientSocketOpenSSL::DoHandshake() {
[email protected]fbef13932010-11-23 12:38:53723 base::OpenSSLErrStackTracer err_tracer(FROM_HERE);
[email protected]d518cd92010-09-29 12:27:44724 int net_error = net::OK;
725 int rv = SSL_do_handshake(ssl_);
726
[email protected]718c9672010-12-02 10:04:10727 if (client_auth_cert_needed_) {
728 net_error = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
729 // If the handshake already succeeded (because the server requests but
730 // doesn't require a client cert), we need to invalidate the SSL session
731 // so that we won't try to resume the non-client-authenticated session in
732 // the next handshake. This will cause the server to ask for a client
733 // cert again.
734 if (rv == 1) {
735 // Remove from session cache but don't clear this connection.
736 SSL_SESSION* session = SSL_get_session(ssl_);
737 if (session) {
738 int rv = SSL_CTX_remove_session(SSL_get_SSL_CTX(ssl_), session);
739 LOG_IF(WARNING, !rv) << "Couldn't invalidate SSL session: " << session;
740 }
741 }
742 } else if (rv == 1) {
[email protected]fbef13932010-11-23 12:38:53743 if (trying_cached_session_ && logging::DEBUG_MODE) {
744 DVLOG(2) << "Result of session reuse for " << host_and_port_.ToString()
745 << " is: " << (SSL_session_reused(ssl_) ? "Success" : "Fail");
746 }
[email protected]d518cd92010-09-29 12:27:44747 // SSL handshake is completed. Let's verify the certificate.
[email protected]abc7e06d2010-10-06 15:40:35748 const bool got_cert = !!UpdateServerCert();
749 DCHECK(got_cert);
750 GotoState(STATE_VERIFY_CERT);
[email protected]d518cd92010-09-29 12:27:44751 } else {
752 int ssl_error = SSL_get_error(ssl_, rv);
[email protected]109805a2010-12-07 18:17:06753 net_error = MapOpenSSLError(ssl_error, err_tracer);
[email protected]d518cd92010-09-29 12:27:44754
755 // If not done, stay in this state
[email protected]170e76c2010-10-04 15:04:20756 if (net_error == ERR_IO_PENDING) {
757 GotoState(STATE_HANDSHAKE);
758 } else {
759 LOG(ERROR) << "handshake failed; returned " << rv
760 << ", SSL error code " << ssl_error
761 << ", net_error " << net_error;
[email protected]109805a2010-12-07 18:17:06762 net_log_.AddEvent(
763 NetLog::TYPE_SSL_HANDSHAKE_ERROR,
764 make_scoped_refptr(new SSLErrorParams(net_error, ssl_error)));
[email protected]170e76c2010-10-04 15:04:20765 }
766 }
767 return net_error;
768}
769
[email protected]ea4a1c6a2010-12-09 13:33:28770int SSLClientSocketOpenSSL::SelectNextProtoCallback(unsigned char** out,
771 unsigned char* outlen,
772 const unsigned char* in,
773 unsigned int inlen) {
774#if defined(OPENSSL_NPN_NEGOTIATED)
775 if (ssl_config_.next_protos.empty()) {
[email protected]32e1dee2010-12-09 18:36:24776 *out = reinterpret_cast<uint8*>(const_cast<char*>("http/1.1"));
[email protected]ea4a1c6a2010-12-09 13:33:28777 *outlen = 8;
778 npn_status_ = SSLClientSocket::kNextProtoUnsupported;
779 return SSL_TLSEXT_ERR_OK;
780 }
781
782 int status = SSL_select_next_proto(
783 out, outlen, in, inlen,
784 reinterpret_cast<const unsigned char*>(ssl_config_.next_protos.data()),
785 ssl_config_.next_protos.size());
786
787 npn_proto_.assign(reinterpret_cast<const char*>(*out), *outlen);
788 switch (status) {
789 case OPENSSL_NPN_UNSUPPORTED:
790 npn_status_ = SSLClientSocket::kNextProtoUnsupported;
791 break;
792 case OPENSSL_NPN_NEGOTIATED:
793 npn_status_ = SSLClientSocket::kNextProtoNegotiated;
794 break;
795 case OPENSSL_NPN_NO_OVERLAP:
796 npn_status_ = SSLClientSocket::kNextProtoNoOverlap;
797 break;
798 default:
799 NOTREACHED() << status;
800 break;
801 }
[email protected]32e1dee2010-12-09 18:36:24802 DVLOG(2) << "next protocol: '" << npn_proto_ << "' status: " << npn_status_;
[email protected]ea4a1c6a2010-12-09 13:33:28803#endif
804 return SSL_TLSEXT_ERR_OK;
805}
806
[email protected]170e76c2010-10-04 15:04:20807int SSLClientSocketOpenSSL::DoVerifyCert(int result) {
808 DCHECK(server_cert_);
809 GotoState(STATE_VERIFY_CERT_COMPLETE);
810 int flags = 0;
811
812 if (ssl_config_.rev_checking_enabled)
813 flags |= X509Certificate::VERIFY_REV_CHECKING_ENABLED;
814 if (ssl_config_.verify_ev_cert)
815 flags |= X509Certificate::VERIFY_EV_CERT;
816 verifier_.reset(new CertVerifier);
[email protected]055d7f22010-11-15 12:03:12817 return verifier_->Verify(server_cert_, host_and_port_.host(), flags,
[email protected]170e76c2010-10-04 15:04:20818 &server_cert_verify_result_,
819 &handshake_io_callback_);
820}
821
822int SSLClientSocketOpenSSL::DoVerifyCertComplete(int result) {
823 verifier_.reset();
824
825 if (result == OK) {
826 // TODO(joth): Work out if we need to remember the intermediate CA certs
827 // when the server sends them to us, and do so here.
[email protected]2907525c2010-10-08 15:53:52828 } else {
829 DVLOG(1) << "DoVerifyCertComplete error " << ErrorToString(result)
830 << " (" << result << ")";
[email protected]d518cd92010-09-29 12:27:44831 }
832
[email protected]170e76c2010-10-04 15:04:20833 // If we have been explicitly told to accept this certificate, override the
834 // result of verifier_.Verify.
835 // Eventually, we should cache the cert verification results so that we don't
836 // need to call verifier_.Verify repeatedly. But for now we need to do this.
837 // Alternatively, we could use the cert's status that we stored along with
838 // the cert in the allowed_bad_certs vector.
839 if (IsCertificateError(result) &&
840 ssl_config_.IsAllowedBadCert(server_cert_)) {
[email protected]b30a3f52010-10-16 01:05:46841 VLOG(1) << "accepting bad SSL certificate, as user told us to";
[email protected]170e76c2010-10-04 15:04:20842 result = OK;
843 }
844
845 completed_handshake_ = true;
[email protected]170e76c2010-10-04 15:04:20846 // Exit DoHandshakeLoop and return the result to the caller to Connect.
847 DCHECK_EQ(STATE_NONE, next_handshake_state_);
848 return result;
849}
850
[email protected]170e76c2010-10-04 15:04:20851X509Certificate* SSLClientSocketOpenSSL::UpdateServerCert() {
852 if (server_cert_)
853 return server_cert_;
854
[email protected]313834722010-11-17 09:57:18855 base::ScopedOpenSSL<X509, X509_free> cert(SSL_get_peer_certificate(ssl_));
[email protected]2907525c2010-10-08 15:53:52856 if (!cert.get()) {
[email protected]170e76c2010-10-04 15:04:20857 LOG(WARNING) << "SSL_get_peer_certificate returned NULL";
858 return NULL;
859 }
860
[email protected]2907525c2010-10-08 15:53:52861 // Unlike SSL_get_peer_certificate, SSL_get_peer_cert_chain does not
862 // increment the reference so sk_X509_free does not need to be called.
863 STACK_OF(X509)* chain = SSL_get_peer_cert_chain(ssl_);
864 X509Certificate::OSCertHandles intermediates;
865 if (chain) {
866 for (int i = 0; i < sk_X509_num(chain); ++i)
867 intermediates.push_back(sk_X509_value(chain, i));
868 }
869 server_cert_ = X509Certificate::CreateFromHandle(
870 cert.get(), X509Certificate::SOURCE_FROM_NETWORK, intermediates);
[email protected]170e76c2010-10-04 15:04:20871 DCHECK(server_cert_);
[email protected]170e76c2010-10-04 15:04:20872
873 return server_cert_;
[email protected]d518cd92010-09-29 12:27:44874}
875
876bool SSLClientSocketOpenSSL::DoTransportIO() {
877 bool network_moved = false;
878 int nsent = BufferSend();
879 int nreceived = BufferRecv();
880 network_moved = (nsent > 0 || nreceived >= 0);
881 return network_moved;
882}
883
884int SSLClientSocketOpenSSL::BufferSend(void) {
885 if (transport_send_busy_)
886 return ERR_IO_PENDING;
887
888 if (!send_buffer_) {
889 // Get a fresh send buffer out of the send BIO.
890 size_t max_read = BIO_ctrl_pending(transport_bio_);
891 if (max_read > 0) {
892 send_buffer_ = new DrainableIOBuffer(new IOBuffer(max_read), max_read);
893 int read_bytes = BIO_read(transport_bio_, send_buffer_->data(), max_read);
894 DCHECK_GT(read_bytes, 0);
895 CHECK_EQ(static_cast<int>(max_read), read_bytes);
896 }
897 }
898
899 int rv = 0;
900 while (send_buffer_) {
901 rv = transport_->socket()->Write(send_buffer_,
902 send_buffer_->BytesRemaining(),
903 &buffer_send_callback_);
904 if (rv == ERR_IO_PENDING) {
905 transport_send_busy_ = true;
906 return rv;
907 }
908 TransportWriteComplete(rv);
909 }
910 return rv;
911}
912
913void SSLClientSocketOpenSSL::BufferSendComplete(int result) {
914 transport_send_busy_ = false;
915 TransportWriteComplete(result);
916 OnSendComplete(result);
917}
918
919void SSLClientSocketOpenSSL::TransportWriteComplete(int result) {
[email protected]abc7e06d2010-10-06 15:40:35920 DCHECK(ERR_IO_PENDING != result);
[email protected]d518cd92010-09-29 12:27:44921 if (result < 0) {
922 // Got a socket write error; close the BIO to indicate this upward.
[email protected]abc7e06d2010-10-06 15:40:35923 DVLOG(1) << "TransportWriteComplete error " << result;
[email protected]d518cd92010-09-29 12:27:44924 (void)BIO_shutdown_wr(transport_bio_);
925 send_buffer_ = NULL;
926 } else {
927 DCHECK(send_buffer_);
928 send_buffer_->DidConsume(result);
929 DCHECK_GE(send_buffer_->BytesRemaining(), 0);
930 if (send_buffer_->BytesRemaining() <= 0)
931 send_buffer_ = NULL;
932 }
933}
934
935int SSLClientSocketOpenSSL::BufferRecv(void) {
936 if (transport_recv_busy_)
937 return ERR_IO_PENDING;
938
939 size_t max_write = BIO_ctrl_get_write_guarantee(transport_bio_);
940 if (max_write > kMaxRecvBufferSize)
941 max_write = kMaxRecvBufferSize;
942
943 if (!max_write)
944 return ERR_IO_PENDING;
945
946 recv_buffer_ = new IOBuffer(max_write);
947 int rv = transport_->socket()->Read(recv_buffer_, max_write,
948 &buffer_recv_callback_);
949 if (rv == ERR_IO_PENDING) {
950 transport_recv_busy_ = true;
951 } else {
952 TransportReadComplete(rv);
953 }
954 return rv;
955}
956
957void SSLClientSocketOpenSSL::BufferRecvComplete(int result) {
958 TransportReadComplete(result);
959 OnRecvComplete(result);
960}
961
962void SSLClientSocketOpenSSL::TransportReadComplete(int result) {
[email protected]abc7e06d2010-10-06 15:40:35963 DCHECK(ERR_IO_PENDING != result);
964 if (result <= 0) {
965 DVLOG(1) << "TransportReadComplete result " << result;
966 // Received 0 (end of file) or an error. Either way, bubble it up to the
967 // SSL layer via the BIO. TODO(joth): consider stashing the error code, to
968 // relay up to the SSL socket client (i.e. via DoReadCallback).
969 BIO_set_mem_eof_return(transport_bio_, 0);
970 (void)BIO_shutdown_wr(transport_bio_);
971 } else {
972 DCHECK(recv_buffer_);
[email protected]d518cd92010-09-29 12:27:44973 int ret = BIO_write(transport_bio_, recv_buffer_->data(), result);
974 // A write into a memory BIO should always succeed.
975 CHECK_EQ(result, ret);
[email protected]d518cd92010-09-29 12:27:44976 }
977 recv_buffer_ = NULL;
978 transport_recv_busy_ = false;
979}
980
981void SSLClientSocketOpenSSL::DoConnectCallback(int rv) {
982 CompletionCallback* c = user_connect_callback_;
983 user_connect_callback_ = NULL;
984 c->Run(rv > OK ? OK : rv);
985}
986
987void SSLClientSocketOpenSSL::OnHandshakeIOComplete(int result) {
988 int rv = DoHandshakeLoop(result);
989 if (rv != ERR_IO_PENDING) {
990 net_log_.EndEvent(NetLog::TYPE_SSL_CONNECT, NULL);
991 DoConnectCallback(rv);
992 }
993}
994
995void SSLClientSocketOpenSSL::OnSendComplete(int result) {
996 if (next_handshake_state_ != STATE_NONE) {
997 // In handshake phase.
998 OnHandshakeIOComplete(result);
999 return;
1000 }
1001
1002 // OnSendComplete may need to call DoPayloadRead while the renegotiation
1003 // handshake is in progress.
1004 int rv_read = ERR_IO_PENDING;
1005 int rv_write = ERR_IO_PENDING;
1006 bool network_moved;
1007 do {
1008 if (user_read_buf_)
1009 rv_read = DoPayloadRead();
1010 if (user_write_buf_)
1011 rv_write = DoPayloadWrite();
1012 network_moved = DoTransportIO();
1013 } while (rv_read == ERR_IO_PENDING &&
1014 rv_write == ERR_IO_PENDING &&
1015 network_moved);
1016
1017 if (user_read_buf_ && rv_read != ERR_IO_PENDING)
1018 DoReadCallback(rv_read);
1019 if (user_write_buf_ && rv_write != ERR_IO_PENDING)
1020 DoWriteCallback(rv_write);
1021}
1022
1023void SSLClientSocketOpenSSL::OnRecvComplete(int result) {
1024 if (next_handshake_state_ != STATE_NONE) {
1025 // In handshake phase.
1026 OnHandshakeIOComplete(result);
1027 return;
1028 }
1029
1030 // Network layer received some data, check if client requested to read
1031 // decrypted data.
1032 if (!user_read_buf_)
1033 return;
1034
1035 int rv = DoReadLoop(result);
1036 if (rv != ERR_IO_PENDING)
1037 DoReadCallback(rv);
1038}
1039
1040bool SSLClientSocketOpenSSL::IsConnected() const {
1041 bool ret = completed_handshake_ && transport_->socket()->IsConnected();
1042 return ret;
1043}
1044
1045bool SSLClientSocketOpenSSL::IsConnectedAndIdle() const {
1046 bool ret = completed_handshake_ && transport_->socket()->IsConnectedAndIdle();
1047 return ret;
1048}
1049
1050int SSLClientSocketOpenSSL::GetPeerAddress(AddressList* addressList) const {
1051 return transport_->socket()->GetPeerAddress(addressList);
1052}
1053
1054const BoundNetLog& SSLClientSocketOpenSSL::NetLog() const {
1055 return net_log_;
1056}
1057
1058void SSLClientSocketOpenSSL::SetSubresourceSpeculation() {
1059 if (transport_.get() && transport_->socket()) {
1060 transport_->socket()->SetSubresourceSpeculation();
1061 } else {
1062 NOTREACHED();
1063 }
1064}
1065
1066void SSLClientSocketOpenSSL::SetOmniboxSpeculation() {
1067 if (transport_.get() && transport_->socket()) {
1068 transport_->socket()->SetOmniboxSpeculation();
1069 } else {
1070 NOTREACHED();
1071 }
1072}
1073
1074bool SSLClientSocketOpenSSL::WasEverUsed() const {
1075 if (transport_.get() && transport_->socket())
1076 return transport_->socket()->WasEverUsed();
1077
1078 NOTREACHED();
1079 return false;
1080}
1081
[email protected]7f7e92392010-10-26 18:29:291082bool SSLClientSocketOpenSSL::UsingTCPFastOpen() const {
1083 if (transport_.get() && transport_->socket())
1084 return transport_->socket()->UsingTCPFastOpen();
1085
1086 NOTREACHED();
1087 return false;
1088}
1089
[email protected]d518cd92010-09-29 12:27:441090// Socket methods
1091
1092int SSLClientSocketOpenSSL::Read(IOBuffer* buf,
1093 int buf_len,
1094 CompletionCallback* callback) {
1095 user_read_buf_ = buf;
1096 user_read_buf_len_ = buf_len;
1097
1098 int rv = DoReadLoop(OK);
1099
1100 if (rv == ERR_IO_PENDING) {
1101 user_read_callback_ = callback;
1102 } else {
1103 user_read_buf_ = NULL;
1104 user_read_buf_len_ = 0;
1105 }
1106
1107 return rv;
1108}
1109
1110int SSLClientSocketOpenSSL::DoReadLoop(int result) {
1111 if (result < 0)
1112 return result;
1113
1114 bool network_moved;
1115 int rv;
1116 do {
1117 rv = DoPayloadRead();
1118 network_moved = DoTransportIO();
1119 } while (rv == ERR_IO_PENDING && network_moved);
1120
1121 return rv;
1122}
1123
1124int SSLClientSocketOpenSSL::Write(IOBuffer* buf,
1125 int buf_len,
1126 CompletionCallback* callback) {
1127 user_write_buf_ = buf;
1128 user_write_buf_len_ = buf_len;
1129
1130 int rv = DoWriteLoop(OK);
1131
1132 if (rv == ERR_IO_PENDING) {
1133 user_write_callback_ = callback;
1134 } else {
1135 user_write_buf_ = NULL;
1136 user_write_buf_len_ = 0;
1137 }
1138
1139 return rv;
1140}
1141
1142int SSLClientSocketOpenSSL::DoWriteLoop(int result) {
1143 if (result < 0)
1144 return result;
1145
1146 bool network_moved;
1147 int rv;
1148 do {
1149 rv = DoPayloadWrite();
1150 network_moved = DoTransportIO();
1151 } while (rv == ERR_IO_PENDING && network_moved);
1152
1153 return rv;
1154}
1155
1156bool SSLClientSocketOpenSSL::SetReceiveBufferSize(int32 size) {
1157 return transport_->socket()->SetReceiveBufferSize(size);
1158}
1159
1160bool SSLClientSocketOpenSSL::SetSendBufferSize(int32 size) {
1161 return transport_->socket()->SetSendBufferSize(size);
1162}
1163
1164int SSLClientSocketOpenSSL::DoPayloadRead() {
[email protected]fbef13932010-11-23 12:38:531165 base::OpenSSLErrStackTracer err_tracer(FROM_HERE);
[email protected]d518cd92010-09-29 12:27:441166 int rv = SSL_read(ssl_, user_read_buf_->data(), user_read_buf_len_);
1167 // We don't need to invalidate the non-client-authenticated SSL session
1168 // because the server will renegotiate anyway.
1169 if (client_auth_cert_needed_)
1170 return ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
1171
1172 if (rv >= 0)
1173 return rv;
1174
1175 int err = SSL_get_error(ssl_, rv);
[email protected]109805a2010-12-07 18:17:061176 return MapOpenSSLError(err, err_tracer);
[email protected]d518cd92010-09-29 12:27:441177}
1178
1179int SSLClientSocketOpenSSL::DoPayloadWrite() {
[email protected]fbef13932010-11-23 12:38:531180 base::OpenSSLErrStackTracer err_tracer(FROM_HERE);
[email protected]d518cd92010-09-29 12:27:441181 int rv = SSL_write(ssl_, user_write_buf_->data(), user_write_buf_len_);
1182
1183 if (rv >= 0)
1184 return rv;
1185
1186 int err = SSL_get_error(ssl_, rv);
[email protected]109805a2010-12-07 18:17:061187 return MapOpenSSLError(err, err_tracer);
[email protected]d518cd92010-09-29 12:27:441188}
1189
[email protected]7e5dd49f2010-12-08 18:33:491190} // namespace net