blob: 395c0676f440234fa8ba3dc86c84fc77ef08cbcf [file] [log] [blame]
[email protected]3b63f8f42011-03-28 01:54:151// Copyright (c) 2011 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
10#include <openssl/ssl.h>
11#include <openssl/err.h>
12
[email protected]3b63f8f42011-03-28 01:54:1513#include "base/memory/singleton.h"
[email protected]835d7c82010-10-14 04:38:3814#include "base/metrics/histogram.h"
[email protected]20305ec2011-01-21 04:55:5215#include "base/synchronization/lock.h"
[email protected]4b559b4d2011-04-14 17:37:1416#include "crypto/openssl_util.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.
[email protected]4b559b4d2011-04-14 17:37:14175int MapOpenSSLError(int err, const crypto::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.
[email protected]4b559b4d2011-04-14 17:37:14209 crypto::ScopedOpenSSL<SSL_SESSION, SSL_SESSION_free> session_to_free;
[email protected]20305ec2011-01-21 04:55:52210 base::AutoLock lock(lock_);
[email protected]fbef13932010-11-23 12:38:53211
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.
[email protected]4b559b4d2011-04-14 17:37:14231 crypto::ScopedOpenSSL<SSL_SESSION, SSL_SESSION_free> session_to_free;
[email protected]20305ec2011-01-21 04:55:52232 base::AutoLock lock(lock_);
[email protected]fbef13932010-11-23 12:38:53233
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) {
[email protected]20305ec2011-01-21 04:55:52249 base::AutoLock lock(lock_);
[email protected]fbef13932010-11-23 12:38:53250 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.
[email protected]20305ec2011-01-21 04:55:52277 base::Lock lock_;
[email protected]fbef13932010-11-23 12:38:53278
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() {
[email protected]4b559b4d2011-04-14 17:37:14304 crypto::EnsureOpenSSLInit();
[email protected]fbef13932010-11-23 12:38:53305 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
[email protected]4b559b4d2011-04-14 17:37:14361 crypto::ScopedOpenSSL<SSL_CTX, SSL_CTX_free> ssl_ctx_;
[email protected]fbef13932010-11-23 12:38:53362 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]822581d2010-12-16 17:27:15383 const SSLConfig& ssl_config,
384 CertVerifier* cert_verifier)
[email protected]d518cd92010-09-29 12:27:44385 : ALLOW_THIS_IN_INITIALIZER_LIST(buffer_send_callback_(
386 this, &SSLClientSocketOpenSSL::BufferSendComplete)),
387 ALLOW_THIS_IN_INITIALIZER_LIST(buffer_recv_callback_(
388 this, &SSLClientSocketOpenSSL::BufferRecvComplete)),
389 transport_send_busy_(false),
390 transport_recv_busy_(false),
391 user_connect_callback_(NULL),
392 user_read_callback_(NULL),
393 user_write_callback_(NULL),
[email protected]fbef13932010-11-23 12:38:53394 completed_handshake_(false),
[email protected]d518cd92010-09-29 12:27:44395 client_auth_cert_needed_(false),
[email protected]822581d2010-12-16 17:27:15396 cert_verifier_(cert_verifier),
[email protected]170e76c2010-10-04 15:04:20397 ALLOW_THIS_IN_INITIALIZER_LIST(handshake_io_callback_(
398 this, &SSLClientSocketOpenSSL::OnHandshakeIOComplete)),
[email protected]d518cd92010-09-29 12:27:44399 ssl_(NULL),
400 transport_bio_(NULL),
401 transport_(transport_socket),
[email protected]055d7f22010-11-15 12:03:12402 host_and_port_(host_and_port),
[email protected]d518cd92010-09-29 12:27:44403 ssl_config_(ssl_config),
[email protected]fbef13932010-11-23 12:38:53404 trying_cached_session_(false),
[email protected]ea4a1c6a2010-12-09 13:33:28405 npn_status_(kNextProtoUnsupported),
[email protected]d518cd92010-09-29 12:27:44406 net_log_(transport_socket->socket()->NetLog()) {
407}
408
409SSLClientSocketOpenSSL::~SSLClientSocketOpenSSL() {
410 Disconnect();
411}
412
[email protected]d518cd92010-09-29 12:27:44413bool SSLClientSocketOpenSSL::Init() {
[email protected]9e733f32010-10-04 18:19:08414 DCHECK(!ssl_);
415 DCHECK(!transport_bio_);
416
[email protected]b29af7d2010-12-14 11:52:47417 SSLContext* context = SSLContext::GetInstance();
[email protected]4b559b4d2011-04-14 17:37:14418 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
[email protected]d518cd92010-09-29 12:27:44419
[email protected]fbef13932010-11-23 12:38:53420 ssl_ = SSL_new(context->ssl_ctx());
421 if (!ssl_ || !context->SetClientSocketForSSL(ssl_, this))
[email protected]d518cd92010-09-29 12:27:44422 return false;
[email protected]fbef13932010-11-23 12:38:53423
424 if (!SSL_set_tlsext_host_name(ssl_, host_and_port_.host().c_str()))
425 return false;
426
427 trying_cached_session_ =
428 context->session_cache()->SetSSLSession(ssl_, host_and_port_);
[email protected]d518cd92010-09-29 12:27:44429
430 BIO* ssl_bio = NULL;
[email protected]fbef13932010-11-23 12:38:53431 // 0 => use default buffer sizes.
432 if (!BIO_new_bio_pair(&ssl_bio, 0, &transport_bio_, 0))
[email protected]d518cd92010-09-29 12:27:44433 return false;
[email protected]d518cd92010-09-29 12:27:44434 DCHECK(ssl_bio);
435 DCHECK(transport_bio_);
436
437 SSL_set_bio(ssl_, ssl_bio, ssl_bio);
438
[email protected]9e733f32010-10-04 18:19:08439 // OpenSSL defaults some options to on, others to off. To avoid ambiguity,
440 // set everything we care about to an absolute value.
[email protected]fb10e2282010-12-01 17:08:48441 SslSetClearMask options;
442 options.ConfigureFlag(SSL_OP_NO_SSLv2, true);
443 options.ConfigureFlag(SSL_OP_NO_SSLv3, !ssl_config_.ssl3_enabled);
444 options.ConfigureFlag(SSL_OP_NO_TLSv1, !ssl_config_.tls1_enabled);
445
446#if defined(SSL_OP_NO_COMPRESSION)
447 // If TLS was disabled also disable compression, to provide maximum site
448 // compatibility in the case of protocol fallback. See http://crbug.com/31628
449 options.ConfigureFlag(SSL_OP_NO_COMPRESSION, !ssl_config_.tls1_enabled);
450#endif
[email protected]9e733f32010-10-04 18:19:08451
452 // TODO(joth): Set this conditionally, see http://crbug.com/55410
[email protected]fb10e2282010-12-01 17:08:48453 options.ConfigureFlag(SSL_OP_LEGACY_SERVER_CONNECT, true);
[email protected]9e733f32010-10-04 18:19:08454
[email protected]fb10e2282010-12-01 17:08:48455 SSL_set_options(ssl_, options.set_mask);
456 SSL_clear_options(ssl_, options.clear_mask);
[email protected]9e733f32010-10-04 18:19:08457
[email protected]fb10e2282010-12-01 17:08:48458 // Same as above, this time for the SSL mode.
459 SslSetClearMask mode;
[email protected]9e733f32010-10-04 18:19:08460
[email protected]fb10e2282010-12-01 17:08:48461#if defined(SSL_MODE_HANDSHAKE_CUTTHROUGH)
462 mode.ConfigureFlag(SSL_MODE_HANDSHAKE_CUTTHROUGH,
463 ssl_config_.false_start_enabled &&
464 !SSLConfigService::IsKnownFalseStartIncompatibleServer(
465 host_and_port_.host()));
466#endif
467
468#if defined(SSL_MODE_RELEASE_BUFFERS)
469 mode.ConfigureFlag(SSL_MODE_RELEASE_BUFFERS, true);
470#endif
471
472#if defined(SSL_MODE_SMALL_BUFFERS)
473 mode.ConfigureFlag(SSL_MODE_SMALL_BUFFERS, true);
474#endif
475
476 SSL_set_mode(ssl_, mode.set_mask);
477 SSL_clear_mode(ssl_, mode.clear_mask);
[email protected]109805a2010-12-07 18:17:06478
479 // Removing ciphers by ID from OpenSSL is a bit involved as we must use the
480 // textual name with SSL_set_cipher_list because there is no public API to
481 // directly remove a cipher by ID.
482 STACK_OF(SSL_CIPHER)* ciphers = SSL_get_ciphers(ssl_);
483 DCHECK(ciphers);
484 // See SSLConfig::disabled_cipher_suites for description of the suites
485 // disabled by default.
486 std::string command("DEFAULT:!NULL:!aNULL:!IDEA:!FZA");
487 // Walk through all the installed ciphers, seeing if any need to be
488 // appended to the cipher removal |command|.
489 for (int i = 0; i < sk_SSL_CIPHER_num(ciphers); ++i) {
490 const SSL_CIPHER* cipher = sk_SSL_CIPHER_value(ciphers, i);
491 const uint16 id = SSL_CIPHER_get_id(cipher);
492 // Remove any ciphers with a strength of less than 80 bits. Note the NSS
493 // implementation uses "effective" bits here but OpenSSL does not provide
494 // this detail. This only impacts Triple DES: reports 112 vs. 168 bits,
495 // both of which are greater than 80 anyway.
496 bool disable = SSL_CIPHER_get_bits(cipher, NULL) < 80;
497 if (!disable) {
498 disable = std::find(ssl_config_.disabled_cipher_suites.begin(),
499 ssl_config_.disabled_cipher_suites.end(), id) !=
500 ssl_config_.disabled_cipher_suites.end();
501 }
502 if (disable) {
503 const char* name = SSL_CIPHER_get_name(cipher);
504 DVLOG(3) << "Found cipher to remove: '" << name << "', ID: " << id
505 << " strength: " << SSL_CIPHER_get_bits(cipher, NULL);
506 command.append(":!");
507 command.append(name);
508 }
509 }
510 int rv = SSL_set_cipher_list(ssl_, command.c_str());
511 // If this fails (rv = 0) it means there are no ciphers enabled on this SSL.
512 // This will almost certainly result in the socket failing to complete the
513 // handshake at which point the appropriate error is bubbled up to the client.
514 LOG_IF(WARNING, rv != 1) << "SSL_set_cipher_list('" << command << "') "
515 "returned " << rv;
[email protected]d518cd92010-09-29 12:27:44516 return true;
517}
518
[email protected]5ac981e182010-12-06 17:56:27519int SSLClientSocketOpenSSL::ClientCertRequestCallback(SSL* ssl,
520 X509** x509,
521 EVP_PKEY** pkey) {
522 DVLOG(3) << "OpenSSL ClientCertRequestCallback called";
523 DCHECK(ssl == ssl_);
524 DCHECK(*x509 == NULL);
525 DCHECK(*pkey == NULL);
526
527 if (!ssl_config_.send_client_cert) {
528 client_auth_cert_needed_ = true;
529 return -1; // Suspends handshake.
530 }
531
532 // Second pass: a client certificate should have been selected.
533 if (ssl_config_.client_cert) {
[email protected]0c6523f2010-12-10 10:56:24534 EVP_PKEY* privkey = OpenSSLPrivateKeyStore::GetInstance()->FetchPrivateKey(
535 X509_PUBKEY_get(X509_get_X509_PUBKEY(
536 ssl_config_.client_cert->os_cert_handle())));
537 if (privkey) {
538 // TODO(joth): (copied from NSS) We should wait for server certificate
539 // verification before sending our credentials. See http://crbug.com/13934
540 *x509 = X509Certificate::DupOSCertHandle(
541 ssl_config_.client_cert->os_cert_handle());
542 *pkey = privkey;
543 return 1;
544 }
545 LOG(WARNING) << "Client cert found without private key";
[email protected]5ac981e182010-12-06 17:56:27546 }
547
548 // Send no client certificate.
549 return 0;
550}
551
[email protected]d518cd92010-09-29 12:27:44552// SSLClientSocket methods
553
554void SSLClientSocketOpenSSL::GetSSLInfo(SSLInfo* ssl_info) {
[email protected]170e76c2010-10-04 15:04:20555 ssl_info->Reset();
556 if (!server_cert_)
557 return;
558
[email protected]170e76c2010-10-04 15:04:20559 ssl_info->cert = server_cert_;
560 ssl_info->cert_status = server_cert_verify_result_.cert_status;
[email protected]1f522492011-04-13 22:06:38561 ssl_info->is_issued_by_known_root =
562 server_cert_verify_result_.is_issued_by_known_root;
563 ssl_info->public_key_hashes =
564 server_cert_verify_result_.public_key_hashes;
[email protected]2907525c2010-10-08 15:53:52565
566 const SSL_CIPHER* cipher = SSL_get_current_cipher(ssl_);
567 CHECK(cipher);
568 ssl_info->security_bits = SSL_CIPHER_get_bits(cipher, NULL);
[email protected]2907525c2010-10-08 15:53:52569 const COMP_METHOD* compression = SSL_get_current_compression(ssl_);
[email protected]109805a2010-12-07 18:17:06570
571 ssl_info->connection_status = EncodeSSLConnectionStatus(
572 SSL_CIPHER_get_id(cipher),
573 compression ? compression->type : 0,
574 GetNetSSLVersion(ssl_));
[email protected]9e733f32010-10-04 18:19:08575
576 bool peer_supports_renego_ext = !!SSL_get_secure_renegotiation_support(ssl_);
577 if (!peer_supports_renego_ext)
578 ssl_info->connection_status |= SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION;
[email protected]109805a2010-12-07 18:17:06579 UMA_HISTOGRAM_ENUMERATION("Net.RenegotiationExtensionSupported",
580 implicit_cast<int>(peer_supports_renego_ext), 2);
[email protected]9e733f32010-10-04 18:19:08581
582 if (ssl_config_.ssl3_fallback)
583 ssl_info->connection_status |= SSL_CONNECTION_SSL3_FALLBACK;
[email protected]109805a2010-12-07 18:17:06584
585 DVLOG(3) << "Encoded connection status: cipher suite = "
586 << SSLConnectionStatusToCipherSuite(ssl_info->connection_status)
587 << " compression = "
588 << SSLConnectionStatusToCompression(ssl_info->connection_status)
589 << " version = "
590 << SSLConnectionStatusToVersion(ssl_info->connection_status);
[email protected]d518cd92010-09-29 12:27:44591}
592
593void SSLClientSocketOpenSSL::GetSSLCertRequestInfo(
594 SSLCertRequestInfo* cert_request_info) {
[email protected]718c9672010-12-02 10:04:10595 cert_request_info->host_and_port = host_and_port_.ToString();
596 cert_request_info->client_certs = client_certs_;
[email protected]d518cd92010-09-29 12:27:44597}
598
599SSLClientSocket::NextProtoStatus SSLClientSocketOpenSSL::GetNextProto(
600 std::string* proto) {
[email protected]ea4a1c6a2010-12-09 13:33:28601 *proto = npn_proto_;
602 return npn_status_;
[email protected]d518cd92010-09-29 12:27:44603}
604
605void SSLClientSocketOpenSSL::DoReadCallback(int rv) {
606 // Since Run may result in Read being called, clear |user_read_callback_|
607 // up front.
608 CompletionCallback* c = user_read_callback_;
609 user_read_callback_ = NULL;
610 user_read_buf_ = NULL;
611 user_read_buf_len_ = 0;
612 c->Run(rv);
613}
614
615void SSLClientSocketOpenSSL::DoWriteCallback(int rv) {
616 // Since Run may result in Write being called, clear |user_write_callback_|
617 // up front.
618 CompletionCallback* c = user_write_callback_;
619 user_write_callback_ = NULL;
620 user_write_buf_ = NULL;
621 user_write_buf_len_ = 0;
622 c->Run(rv);
623}
624
625// ClientSocket methods
626
627int SSLClientSocketOpenSSL::Connect(CompletionCallback* callback) {
628 net_log_.BeginEvent(NetLog::TYPE_SSL_CONNECT, NULL);
629
[email protected]d518cd92010-09-29 12:27:44630 // Set up new ssl object.
631 if (!Init()) {
[email protected]d7fd1782011-02-08 19:16:43632 int result = ERR_UNEXPECTED;
633 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, result);
634 return result;
[email protected]d518cd92010-09-29 12:27:44635 }
636
637 // Set SSL to client mode. Handshake happens in the loop below.
638 SSL_set_connect_state(ssl_);
639
640 GotoState(STATE_HANDSHAKE);
641 int rv = DoHandshakeLoop(net::OK);
642 if (rv == ERR_IO_PENDING) {
643 user_connect_callback_ = callback;
644 } else {
[email protected]d7fd1782011-02-08 19:16:43645 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
[email protected]d518cd92010-09-29 12:27:44646 }
647
648 return rv > OK ? OK : rv;
649}
650
651void SSLClientSocketOpenSSL::Disconnect() {
[email protected]170e76c2010-10-04 15:04:20652 if (ssl_) {
653 SSL_free(ssl_);
654 ssl_ = NULL;
655 }
656 if (transport_bio_) {
657 BIO_free_all(transport_bio_);
658 transport_bio_ = NULL;
659 }
660
661 // Shut down anything that may call us back (through buffer_send_callback_,
662 // buffer_recv_callback, or handshake_io_callback_).
663 verifier_.reset();
664 transport_->socket()->Disconnect();
665
[email protected]d518cd92010-09-29 12:27:44666 // Null all callbacks, delete all buffers.
667 transport_send_busy_ = false;
668 send_buffer_ = NULL;
669 transport_recv_busy_ = false;
670 recv_buffer_ = NULL;
671
672 user_connect_callback_ = NULL;
673 user_read_callback_ = NULL;
674 user_write_callback_ = NULL;
675 user_read_buf_ = NULL;
676 user_read_buf_len_ = 0;
677 user_write_buf_ = NULL;
678 user_write_buf_len_ = 0;
679
[email protected]170e76c2010-10-04 15:04:20680 server_cert_verify_result_.Reset();
[email protected]d518cd92010-09-29 12:27:44681 completed_handshake_ = false;
[email protected]fbef13932010-11-23 12:38:53682
683 client_certs_.clear();
684 client_auth_cert_needed_ = false;
[email protected]d518cd92010-09-29 12:27:44685}
686
687int SSLClientSocketOpenSSL::DoHandshakeLoop(int last_io_result) {
688 bool network_moved;
689 int rv = last_io_result;
690 do {
691 // Default to STATE_NONE for next state.
692 // (This is a quirk carried over from the windows
693 // implementation. It makes reading the logs a bit harder.)
694 // State handlers can and often do call GotoState just
695 // to stay in the current state.
696 State state = next_handshake_state_;
697 GotoState(STATE_NONE);
698 switch (state) {
699 case STATE_NONE:
700 // we're just pumping data between the buffer and the network
701 break;
702 case STATE_HANDSHAKE:
703 rv = DoHandshake();
704 break;
[email protected]d518cd92010-09-29 12:27:44705 case STATE_VERIFY_CERT:
706 DCHECK(rv == OK);
707 rv = DoVerifyCert(rv);
708 break;
709 case STATE_VERIFY_CERT_COMPLETE:
710 rv = DoVerifyCertComplete(rv);
711 break;
[email protected]d518cd92010-09-29 12:27:44712 default:
713 rv = ERR_UNEXPECTED;
714 NOTREACHED() << "unexpected state" << state;
715 break;
716 }
717
718 // To avoid getting an ERR_IO_PENDING here after handshake complete.
719 if (next_handshake_state_ == STATE_NONE)
720 break;
721
722 // Do the actual network I/O.
723 network_moved = DoTransportIO();
724 } while ((rv != ERR_IO_PENDING || network_moved) &&
725 next_handshake_state_ != STATE_NONE);
726 return rv;
727}
728
729int SSLClientSocketOpenSSL::DoHandshake() {
[email protected]4b559b4d2011-04-14 17:37:14730 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
[email protected]d518cd92010-09-29 12:27:44731 int net_error = net::OK;
732 int rv = SSL_do_handshake(ssl_);
733
[email protected]718c9672010-12-02 10:04:10734 if (client_auth_cert_needed_) {
735 net_error = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
736 // If the handshake already succeeded (because the server requests but
737 // doesn't require a client cert), we need to invalidate the SSL session
738 // so that we won't try to resume the non-client-authenticated session in
739 // the next handshake. This will cause the server to ask for a client
740 // cert again.
741 if (rv == 1) {
742 // Remove from session cache but don't clear this connection.
743 SSL_SESSION* session = SSL_get_session(ssl_);
744 if (session) {
745 int rv = SSL_CTX_remove_session(SSL_get_SSL_CTX(ssl_), session);
746 LOG_IF(WARNING, !rv) << "Couldn't invalidate SSL session: " << session;
747 }
748 }
749 } else if (rv == 1) {
[email protected]fbef13932010-11-23 12:38:53750 if (trying_cached_session_ && logging::DEBUG_MODE) {
751 DVLOG(2) << "Result of session reuse for " << host_and_port_.ToString()
752 << " is: " << (SSL_session_reused(ssl_) ? "Success" : "Fail");
753 }
[email protected]d518cd92010-09-29 12:27:44754 // SSL handshake is completed. Let's verify the certificate.
[email protected]abc7e06d2010-10-06 15:40:35755 const bool got_cert = !!UpdateServerCert();
756 DCHECK(got_cert);
757 GotoState(STATE_VERIFY_CERT);
[email protected]d518cd92010-09-29 12:27:44758 } else {
759 int ssl_error = SSL_get_error(ssl_, rv);
[email protected]109805a2010-12-07 18:17:06760 net_error = MapOpenSSLError(ssl_error, err_tracer);
[email protected]d518cd92010-09-29 12:27:44761
762 // If not done, stay in this state
[email protected]170e76c2010-10-04 15:04:20763 if (net_error == ERR_IO_PENDING) {
764 GotoState(STATE_HANDSHAKE);
765 } else {
766 LOG(ERROR) << "handshake failed; returned " << rv
767 << ", SSL error code " << ssl_error
768 << ", net_error " << net_error;
[email protected]109805a2010-12-07 18:17:06769 net_log_.AddEvent(
770 NetLog::TYPE_SSL_HANDSHAKE_ERROR,
771 make_scoped_refptr(new SSLErrorParams(net_error, ssl_error)));
[email protected]170e76c2010-10-04 15:04:20772 }
773 }
774 return net_error;
775}
776
[email protected]ea4a1c6a2010-12-09 13:33:28777int SSLClientSocketOpenSSL::SelectNextProtoCallback(unsigned char** out,
778 unsigned char* outlen,
779 const unsigned char* in,
780 unsigned int inlen) {
781#if defined(OPENSSL_NPN_NEGOTIATED)
782 if (ssl_config_.next_protos.empty()) {
[email protected]32e1dee2010-12-09 18:36:24783 *out = reinterpret_cast<uint8*>(const_cast<char*>("http/1.1"));
[email protected]ea4a1c6a2010-12-09 13:33:28784 *outlen = 8;
785 npn_status_ = SSLClientSocket::kNextProtoUnsupported;
786 return SSL_TLSEXT_ERR_OK;
787 }
788
789 int status = SSL_select_next_proto(
790 out, outlen, in, inlen,
791 reinterpret_cast<const unsigned char*>(ssl_config_.next_protos.data()),
792 ssl_config_.next_protos.size());
793
794 npn_proto_.assign(reinterpret_cast<const char*>(*out), *outlen);
795 switch (status) {
796 case OPENSSL_NPN_UNSUPPORTED:
797 npn_status_ = SSLClientSocket::kNextProtoUnsupported;
798 break;
799 case OPENSSL_NPN_NEGOTIATED:
800 npn_status_ = SSLClientSocket::kNextProtoNegotiated;
801 break;
802 case OPENSSL_NPN_NO_OVERLAP:
803 npn_status_ = SSLClientSocket::kNextProtoNoOverlap;
804 break;
805 default:
806 NOTREACHED() << status;
807 break;
808 }
[email protected]32e1dee2010-12-09 18:36:24809 DVLOG(2) << "next protocol: '" << npn_proto_ << "' status: " << npn_status_;
[email protected]ea4a1c6a2010-12-09 13:33:28810#endif
811 return SSL_TLSEXT_ERR_OK;
812}
813
[email protected]170e76c2010-10-04 15:04:20814int SSLClientSocketOpenSSL::DoVerifyCert(int result) {
815 DCHECK(server_cert_);
816 GotoState(STATE_VERIFY_CERT_COMPLETE);
817 int flags = 0;
818
819 if (ssl_config_.rev_checking_enabled)
820 flags |= X509Certificate::VERIFY_REV_CHECKING_ENABLED;
821 if (ssl_config_.verify_ev_cert)
822 flags |= X509Certificate::VERIFY_EV_CERT;
[email protected]822581d2010-12-16 17:27:15823 verifier_.reset(new SingleRequestCertVerifier(cert_verifier_));
[email protected]055d7f22010-11-15 12:03:12824 return verifier_->Verify(server_cert_, host_and_port_.host(), flags,
[email protected]170e76c2010-10-04 15:04:20825 &server_cert_verify_result_,
826 &handshake_io_callback_);
827}
828
829int SSLClientSocketOpenSSL::DoVerifyCertComplete(int result) {
830 verifier_.reset();
831
832 if (result == OK) {
833 // TODO(joth): Work out if we need to remember the intermediate CA certs
834 // when the server sends them to us, and do so here.
[email protected]2907525c2010-10-08 15:53:52835 } else {
836 DVLOG(1) << "DoVerifyCertComplete error " << ErrorToString(result)
837 << " (" << result << ")";
[email protected]d518cd92010-09-29 12:27:44838 }
839
[email protected]170e76c2010-10-04 15:04:20840 // If we have been explicitly told to accept this certificate, override the
841 // result of verifier_.Verify.
842 // Eventually, we should cache the cert verification results so that we don't
843 // need to call verifier_.Verify repeatedly. But for now we need to do this.
844 // Alternatively, we could use the cert's status that we stored along with
845 // the cert in the allowed_bad_certs vector.
846 if (IsCertificateError(result) &&
847 ssl_config_.IsAllowedBadCert(server_cert_)) {
[email protected]b30a3f52010-10-16 01:05:46848 VLOG(1) << "accepting bad SSL certificate, as user told us to";
[email protected]170e76c2010-10-04 15:04:20849 result = OK;
850 }
851
852 completed_handshake_ = true;
[email protected]170e76c2010-10-04 15:04:20853 // Exit DoHandshakeLoop and return the result to the caller to Connect.
854 DCHECK_EQ(STATE_NONE, next_handshake_state_);
855 return result;
856}
857
[email protected]170e76c2010-10-04 15:04:20858X509Certificate* SSLClientSocketOpenSSL::UpdateServerCert() {
859 if (server_cert_)
860 return server_cert_;
861
[email protected]4b559b4d2011-04-14 17:37:14862 crypto::ScopedOpenSSL<X509, X509_free> cert(SSL_get_peer_certificate(ssl_));
[email protected]2907525c2010-10-08 15:53:52863 if (!cert.get()) {
[email protected]170e76c2010-10-04 15:04:20864 LOG(WARNING) << "SSL_get_peer_certificate returned NULL";
865 return NULL;
866 }
867
[email protected]2907525c2010-10-08 15:53:52868 // Unlike SSL_get_peer_certificate, SSL_get_peer_cert_chain does not
869 // increment the reference so sk_X509_free does not need to be called.
870 STACK_OF(X509)* chain = SSL_get_peer_cert_chain(ssl_);
871 X509Certificate::OSCertHandles intermediates;
872 if (chain) {
873 for (int i = 0; i < sk_X509_num(chain); ++i)
874 intermediates.push_back(sk_X509_value(chain, i));
875 }
876 server_cert_ = X509Certificate::CreateFromHandle(
877 cert.get(), X509Certificate::SOURCE_FROM_NETWORK, intermediates);
[email protected]170e76c2010-10-04 15:04:20878 DCHECK(server_cert_);
[email protected]170e76c2010-10-04 15:04:20879
880 return server_cert_;
[email protected]d518cd92010-09-29 12:27:44881}
882
883bool SSLClientSocketOpenSSL::DoTransportIO() {
884 bool network_moved = false;
885 int nsent = BufferSend();
886 int nreceived = BufferRecv();
887 network_moved = (nsent > 0 || nreceived >= 0);
888 return network_moved;
889}
890
891int SSLClientSocketOpenSSL::BufferSend(void) {
892 if (transport_send_busy_)
893 return ERR_IO_PENDING;
894
895 if (!send_buffer_) {
896 // Get a fresh send buffer out of the send BIO.
897 size_t max_read = BIO_ctrl_pending(transport_bio_);
898 if (max_read > 0) {
899 send_buffer_ = new DrainableIOBuffer(new IOBuffer(max_read), max_read);
900 int read_bytes = BIO_read(transport_bio_, send_buffer_->data(), max_read);
901 DCHECK_GT(read_bytes, 0);
902 CHECK_EQ(static_cast<int>(max_read), read_bytes);
903 }
904 }
905
906 int rv = 0;
907 while (send_buffer_) {
908 rv = transport_->socket()->Write(send_buffer_,
909 send_buffer_->BytesRemaining(),
910 &buffer_send_callback_);
911 if (rv == ERR_IO_PENDING) {
912 transport_send_busy_ = true;
913 return rv;
914 }
915 TransportWriteComplete(rv);
916 }
917 return rv;
918}
919
920void SSLClientSocketOpenSSL::BufferSendComplete(int result) {
921 transport_send_busy_ = false;
922 TransportWriteComplete(result);
923 OnSendComplete(result);
924}
925
926void SSLClientSocketOpenSSL::TransportWriteComplete(int result) {
[email protected]abc7e06d2010-10-06 15:40:35927 DCHECK(ERR_IO_PENDING != result);
[email protected]d518cd92010-09-29 12:27:44928 if (result < 0) {
929 // Got a socket write error; close the BIO to indicate this upward.
[email protected]abc7e06d2010-10-06 15:40:35930 DVLOG(1) << "TransportWriteComplete error " << result;
[email protected]d518cd92010-09-29 12:27:44931 (void)BIO_shutdown_wr(transport_bio_);
932 send_buffer_ = NULL;
933 } else {
934 DCHECK(send_buffer_);
935 send_buffer_->DidConsume(result);
936 DCHECK_GE(send_buffer_->BytesRemaining(), 0);
937 if (send_buffer_->BytesRemaining() <= 0)
938 send_buffer_ = NULL;
939 }
940}
941
942int SSLClientSocketOpenSSL::BufferRecv(void) {
943 if (transport_recv_busy_)
944 return ERR_IO_PENDING;
945
946 size_t max_write = BIO_ctrl_get_write_guarantee(transport_bio_);
947 if (max_write > kMaxRecvBufferSize)
948 max_write = kMaxRecvBufferSize;
949
950 if (!max_write)
951 return ERR_IO_PENDING;
952
953 recv_buffer_ = new IOBuffer(max_write);
954 int rv = transport_->socket()->Read(recv_buffer_, max_write,
955 &buffer_recv_callback_);
956 if (rv == ERR_IO_PENDING) {
957 transport_recv_busy_ = true;
958 } else {
959 TransportReadComplete(rv);
960 }
961 return rv;
962}
963
964void SSLClientSocketOpenSSL::BufferRecvComplete(int result) {
965 TransportReadComplete(result);
966 OnRecvComplete(result);
967}
968
969void SSLClientSocketOpenSSL::TransportReadComplete(int result) {
[email protected]abc7e06d2010-10-06 15:40:35970 DCHECK(ERR_IO_PENDING != result);
971 if (result <= 0) {
972 DVLOG(1) << "TransportReadComplete result " << result;
973 // Received 0 (end of file) or an error. Either way, bubble it up to the
974 // SSL layer via the BIO. TODO(joth): consider stashing the error code, to
975 // relay up to the SSL socket client (i.e. via DoReadCallback).
976 BIO_set_mem_eof_return(transport_bio_, 0);
977 (void)BIO_shutdown_wr(transport_bio_);
978 } else {
979 DCHECK(recv_buffer_);
[email protected]d518cd92010-09-29 12:27:44980 int ret = BIO_write(transport_bio_, recv_buffer_->data(), result);
981 // A write into a memory BIO should always succeed.
982 CHECK_EQ(result, ret);
[email protected]d518cd92010-09-29 12:27:44983 }
984 recv_buffer_ = NULL;
985 transport_recv_busy_ = false;
986}
987
988void SSLClientSocketOpenSSL::DoConnectCallback(int rv) {
989 CompletionCallback* c = user_connect_callback_;
990 user_connect_callback_ = NULL;
991 c->Run(rv > OK ? OK : rv);
992}
993
994void SSLClientSocketOpenSSL::OnHandshakeIOComplete(int result) {
995 int rv = DoHandshakeLoop(result);
996 if (rv != ERR_IO_PENDING) {
[email protected]d7fd1782011-02-08 19:16:43997 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
[email protected]d518cd92010-09-29 12:27:44998 DoConnectCallback(rv);
999 }
1000}
1001
1002void SSLClientSocketOpenSSL::OnSendComplete(int result) {
1003 if (next_handshake_state_ != STATE_NONE) {
1004 // In handshake phase.
1005 OnHandshakeIOComplete(result);
1006 return;
1007 }
1008
1009 // OnSendComplete may need to call DoPayloadRead while the renegotiation
1010 // handshake is in progress.
1011 int rv_read = ERR_IO_PENDING;
1012 int rv_write = ERR_IO_PENDING;
1013 bool network_moved;
1014 do {
1015 if (user_read_buf_)
1016 rv_read = DoPayloadRead();
1017 if (user_write_buf_)
1018 rv_write = DoPayloadWrite();
1019 network_moved = DoTransportIO();
1020 } while (rv_read == ERR_IO_PENDING &&
1021 rv_write == ERR_IO_PENDING &&
1022 network_moved);
1023
1024 if (user_read_buf_ && rv_read != ERR_IO_PENDING)
1025 DoReadCallback(rv_read);
1026 if (user_write_buf_ && rv_write != ERR_IO_PENDING)
1027 DoWriteCallback(rv_write);
1028}
1029
1030void SSLClientSocketOpenSSL::OnRecvComplete(int result) {
1031 if (next_handshake_state_ != STATE_NONE) {
1032 // In handshake phase.
1033 OnHandshakeIOComplete(result);
1034 return;
1035 }
1036
1037 // Network layer received some data, check if client requested to read
1038 // decrypted data.
1039 if (!user_read_buf_)
1040 return;
1041
1042 int rv = DoReadLoop(result);
1043 if (rv != ERR_IO_PENDING)
1044 DoReadCallback(rv);
1045}
1046
1047bool SSLClientSocketOpenSSL::IsConnected() const {
1048 bool ret = completed_handshake_ && transport_->socket()->IsConnected();
1049 return ret;
1050}
1051
1052bool SSLClientSocketOpenSSL::IsConnectedAndIdle() const {
1053 bool ret = completed_handshake_ && transport_->socket()->IsConnectedAndIdle();
1054 return ret;
1055}
1056
1057int SSLClientSocketOpenSSL::GetPeerAddress(AddressList* addressList) const {
1058 return transport_->socket()->GetPeerAddress(addressList);
1059}
1060
1061const BoundNetLog& SSLClientSocketOpenSSL::NetLog() const {
1062 return net_log_;
1063}
1064
1065void SSLClientSocketOpenSSL::SetSubresourceSpeculation() {
1066 if (transport_.get() && transport_->socket()) {
1067 transport_->socket()->SetSubresourceSpeculation();
1068 } else {
1069 NOTREACHED();
1070 }
1071}
1072
1073void SSLClientSocketOpenSSL::SetOmniboxSpeculation() {
1074 if (transport_.get() && transport_->socket()) {
1075 transport_->socket()->SetOmniboxSpeculation();
1076 } else {
1077 NOTREACHED();
1078 }
1079}
1080
1081bool SSLClientSocketOpenSSL::WasEverUsed() const {
1082 if (transport_.get() && transport_->socket())
1083 return transport_->socket()->WasEverUsed();
1084
1085 NOTREACHED();
1086 return false;
1087}
1088
[email protected]7f7e92392010-10-26 18:29:291089bool SSLClientSocketOpenSSL::UsingTCPFastOpen() const {
1090 if (transport_.get() && transport_->socket())
1091 return transport_->socket()->UsingTCPFastOpen();
1092
1093 NOTREACHED();
1094 return false;
1095}
1096
[email protected]d518cd92010-09-29 12:27:441097// Socket methods
1098
1099int SSLClientSocketOpenSSL::Read(IOBuffer* buf,
1100 int buf_len,
1101 CompletionCallback* callback) {
1102 user_read_buf_ = buf;
1103 user_read_buf_len_ = buf_len;
1104
1105 int rv = DoReadLoop(OK);
1106
1107 if (rv == ERR_IO_PENDING) {
1108 user_read_callback_ = callback;
1109 } else {
1110 user_read_buf_ = NULL;
1111 user_read_buf_len_ = 0;
1112 }
1113
1114 return rv;
1115}
1116
1117int SSLClientSocketOpenSSL::DoReadLoop(int result) {
1118 if (result < 0)
1119 return result;
1120
1121 bool network_moved;
1122 int rv;
1123 do {
1124 rv = DoPayloadRead();
1125 network_moved = DoTransportIO();
1126 } while (rv == ERR_IO_PENDING && network_moved);
1127
1128 return rv;
1129}
1130
1131int SSLClientSocketOpenSSL::Write(IOBuffer* buf,
1132 int buf_len,
1133 CompletionCallback* callback) {
1134 user_write_buf_ = buf;
1135 user_write_buf_len_ = buf_len;
1136
1137 int rv = DoWriteLoop(OK);
1138
1139 if (rv == ERR_IO_PENDING) {
1140 user_write_callback_ = callback;
1141 } else {
1142 user_write_buf_ = NULL;
1143 user_write_buf_len_ = 0;
1144 }
1145
1146 return rv;
1147}
1148
1149int SSLClientSocketOpenSSL::DoWriteLoop(int result) {
1150 if (result < 0)
1151 return result;
1152
1153 bool network_moved;
1154 int rv;
1155 do {
1156 rv = DoPayloadWrite();
1157 network_moved = DoTransportIO();
1158 } while (rv == ERR_IO_PENDING && network_moved);
1159
1160 return rv;
1161}
1162
1163bool SSLClientSocketOpenSSL::SetReceiveBufferSize(int32 size) {
1164 return transport_->socket()->SetReceiveBufferSize(size);
1165}
1166
1167bool SSLClientSocketOpenSSL::SetSendBufferSize(int32 size) {
1168 return transport_->socket()->SetSendBufferSize(size);
1169}
1170
1171int SSLClientSocketOpenSSL::DoPayloadRead() {
[email protected]4b559b4d2011-04-14 17:37:141172 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
[email protected]d518cd92010-09-29 12:27:441173 int rv = SSL_read(ssl_, user_read_buf_->data(), user_read_buf_len_);
1174 // We don't need to invalidate the non-client-authenticated SSL session
1175 // because the server will renegotiate anyway.
1176 if (client_auth_cert_needed_)
1177 return ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
1178
1179 if (rv >= 0)
1180 return rv;
1181
1182 int err = SSL_get_error(ssl_, rv);
[email protected]109805a2010-12-07 18:17:061183 return MapOpenSSLError(err, err_tracer);
[email protected]d518cd92010-09-29 12:27:441184}
1185
1186int SSLClientSocketOpenSSL::DoPayloadWrite() {
[email protected]4b559b4d2011-04-14 17:37:141187 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
[email protected]d518cd92010-09-29 12:27:441188 int rv = SSL_write(ssl_, user_write_buf_->data(), user_write_buf_len_);
1189
1190 if (rv >= 0)
1191 return rv;
1192
1193 int err = SSL_get_error(ssl_, rv);
[email protected]109805a2010-12-07 18:17:061194 return MapOpenSSLError(err, err_tracer);
[email protected]d518cd92010-09-29 12:27:441195}
1196
[email protected]7e5dd49f2010-12-08 18:33:491197} // namespace net