blob: a2e3a1974b31c3d4972db78155ab964e836c90e2 [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]0f7804ec2011-10-07 20:04:1813#include "base/bind.h"
[email protected]3b63f8f42011-03-28 01:54:1514#include "base/memory/singleton.h"
[email protected]835d7c82010-10-14 04:38:3815#include "base/metrics/histogram.h"
[email protected]20305ec2011-01-21 04:55:5216#include "base/synchronization/lock.h"
[email protected]4b559b4d2011-04-14 17:37:1417#include "crypto/openssl_util.h"
[email protected]313834722010-11-17 09:57:1818#include "net/base/cert_verifier.h"
[email protected]d518cd92010-09-29 12:27:4419#include "net/base/net_errors.h"
[email protected]0c6523f2010-12-10 10:56:2420#include "net/base/openssl_private_key_store.h"
[email protected]718c9672010-12-02 10:04:1021#include "net/base/ssl_cert_request_info.h"
[email protected]d518cd92010-09-29 12:27:4422#include "net/base/ssl_connection_status_flags.h"
23#include "net/base/ssl_info.h"
[email protected]59468382011-11-04 02:22:0424#include "net/base/x509_certificate_net_log_param.h"
[email protected]109805a2010-12-07 18:17:0625#include "net/socket/ssl_error_params.h"
[email protected]d518cd92010-09-29 12:27:4426
27namespace net {
28
29namespace {
30
31// Enable this to see logging for state machine state transitions.
32#if 0
[email protected]3b112772010-10-04 10:54:4933#define GotoState(s) do { DVLOG(2) << (void *)this << " " << __FUNCTION__ << \
[email protected]d518cd92010-09-29 12:27:4434 " jump to state " << s; \
35 next_handshake_state_ = s; } while (0)
36#else
37#define GotoState(s) next_handshake_state_ = s
38#endif
39
40const size_t kMaxRecvBufferSize = 4096;
[email protected]fbef13932010-11-23 12:38:5341const int kSessionCacheTimeoutSeconds = 60 * 60;
42const size_t kSessionCacheMaxEntires = 1024;
[email protected]d518cd92010-09-29 12:27:4443
[email protected]109805a2010-12-07 18:17:0644// This method doesn't seemed to have made it into the OpenSSL headers.
45unsigned long SSL_CIPHER_get_id(const SSL_CIPHER* cipher) { return cipher->id; }
46
47// Used for encoding the |connection_status| field of an SSLInfo object.
48int EncodeSSLConnectionStatus(int cipher_suite,
49 int compression,
50 int version) {
51 return ((cipher_suite & SSL_CONNECTION_CIPHERSUITE_MASK) <<
52 SSL_CONNECTION_CIPHERSUITE_SHIFT) |
53 ((compression & SSL_CONNECTION_COMPRESSION_MASK) <<
54 SSL_CONNECTION_COMPRESSION_SHIFT) |
55 ((version & SSL_CONNECTION_VERSION_MASK) <<
56 SSL_CONNECTION_VERSION_SHIFT);
57}
58
59// Returns the net SSL version number (see ssl_connection_status_flags.h) for
60// this SSL connection.
61int GetNetSSLVersion(SSL* ssl) {
[email protected]7e5dd49f2010-12-08 18:33:4962 switch (SSL_version(ssl)) {
[email protected]109805a2010-12-07 18:17:0663 case SSL2_VERSION:
64 return SSL_CONNECTION_VERSION_SSL2;
65 case SSL3_VERSION:
66 return SSL_CONNECTION_VERSION_SSL3;
67 case TLS1_VERSION:
68 return SSL_CONNECTION_VERSION_TLS1;
69 case 0x0302:
70 return SSL_CONNECTION_VERSION_TLS1_1;
71 case 0x0303:
72 return SSL_CONNECTION_VERSION_TLS1_2;
73 default:
74 return SSL_CONNECTION_VERSION_UNKNOWN;
75 }
76}
77
78int MapOpenSSLErrorSSL() {
79 // Walk down the error stack to find the SSLerr generated reason.
80 unsigned long error_code;
81 do {
82 error_code = ERR_get_error();
83 if (error_code == 0)
84 return ERR_SSL_PROTOCOL_ERROR;
85 } while (ERR_GET_LIB(error_code) != ERR_LIB_SSL);
86
87 DVLOG(1) << "OpenSSL SSL error, reason: " << ERR_GET_REASON(error_code)
88 << ", name: " << ERR_error_string(error_code, NULL);
89 switch (ERR_GET_REASON(error_code)) {
90 case SSL_R_READ_TIMEOUT_EXPIRED:
91 return ERR_TIMED_OUT;
92 case SSL_R_BAD_RESPONSE_ARGUMENT:
93 return ERR_INVALID_ARGUMENT;
94 case SSL_R_UNKNOWN_CERTIFICATE_TYPE:
95 case SSL_R_UNKNOWN_CIPHER_TYPE:
96 case SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE:
97 case SSL_R_UNKNOWN_PKEY_TYPE:
98 case SSL_R_UNKNOWN_REMOTE_ERROR_TYPE:
99 case SSL_R_UNKNOWN_SSL_VERSION:
100 return ERR_NOT_IMPLEMENTED;
[email protected]109805a2010-12-07 18:17:06101 case SSL_R_UNSUPPORTED_SSL_VERSION:
102 case SSL_R_NO_CIPHER_MATCH:
103 case SSL_R_NO_SHARED_CIPHER:
104 case SSL_R_TLSV1_ALERT_INSUFFICIENT_SECURITY:
105 case SSL_R_TLSV1_ALERT_PROTOCOL_VERSION:
106 return ERR_SSL_VERSION_OR_CIPHER_MISMATCH;
107 case SSL_R_SSLV3_ALERT_BAD_CERTIFICATE:
108 case SSL_R_SSLV3_ALERT_UNSUPPORTED_CERTIFICATE:
109 case SSL_R_SSLV3_ALERT_CERTIFICATE_REVOKED:
110 case SSL_R_SSLV3_ALERT_CERTIFICATE_EXPIRED:
111 case SSL_R_SSLV3_ALERT_CERTIFICATE_UNKNOWN:
112 case SSL_R_TLSV1_ALERT_ACCESS_DENIED:
113 case SSL_R_TLSV1_ALERT_UNKNOWN_CA:
114 return ERR_BAD_SSL_CLIENT_AUTH_CERT;
115 case SSL_R_BAD_DECOMPRESSION:
116 case SSL_R_SSLV3_ALERT_DECOMPRESSION_FAILURE:
117 return ERR_SSL_DECOMPRESSION_FAILURE_ALERT;
118 case SSL_R_SSLV3_ALERT_BAD_RECORD_MAC:
119 return ERR_SSL_BAD_RECORD_MAC_ALERT;
120 case SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED:
121 return ERR_SSL_UNSAFE_NEGOTIATION;
122 case SSL_R_WRONG_NUMBER_OF_KEY_BITS:
123 return ERR_SSL_WEAK_SERVER_EPHEMERAL_DH_KEY;
[email protected]aa4bb6892010-12-08 10:52:02124 // SSL_R_UNKNOWN_PROTOCOL is reported if premature application data is
125 // received (see http://crbug.com/42538), and also if all the protocol
126 // versions supported by the server were disabled in this socket instance.
127 // Mapped to ERR_SSL_PROTOCOL_ERROR for compatibility with other SSL sockets
128 // in the former scenario.
129 case SSL_R_UNKNOWN_PROTOCOL:
[email protected]109805a2010-12-07 18:17:06130 case SSL_R_SSL_HANDSHAKE_FAILURE:
131 case SSL_R_DECRYPTION_FAILED:
132 case SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC:
133 case SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG:
134 case SSL_R_DIGEST_CHECK_FAILED:
135 case SSL_R_DUPLICATE_COMPRESSION_ID:
136 case SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER:
137 case SSL_R_ENCRYPTED_LENGTH_TOO_LONG:
138 case SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST:
139 case SSL_R_EXCESSIVE_MESSAGE_SIZE:
140 case SSL_R_EXTRA_DATA_IN_MESSAGE:
141 case SSL_R_GOT_A_FIN_BEFORE_A_CCS:
142 case SSL_R_ILLEGAL_PADDING:
143 case SSL_R_INVALID_CHALLENGE_LENGTH:
144 case SSL_R_INVALID_COMMAND:
145 case SSL_R_INVALID_PURPOSE:
146 case SSL_R_INVALID_STATUS_RESPONSE:
147 case SSL_R_INVALID_TICKET_KEYS_LENGTH:
148 case SSL_R_KEY_ARG_TOO_LONG:
149 case SSL_R_READ_WRONG_PACKET_TYPE:
150 case SSL_R_SSLV3_ALERT_UNEXPECTED_MESSAGE:
151 // TODO(joth): SSL_R_SSLV3_ALERT_HANDSHAKE_FAILURE may be returned from the
152 // server after receiving ClientHello if there's no common supported cipher.
153 // Ideally we'd map that specific case to ERR_SSL_VERSION_OR_CIPHER_MISMATCH
154 // to match the NSS implementation. See also http://goo.gl/oMtZW
155 case SSL_R_SSLV3_ALERT_HANDSHAKE_FAILURE:
156 case SSL_R_SSLV3_ALERT_NO_CERTIFICATE:
157 case SSL_R_SSLV3_ALERT_ILLEGAL_PARAMETER:
158 case SSL_R_TLSV1_ALERT_DECODE_ERROR:
159 case SSL_R_TLSV1_ALERT_DECRYPTION_FAILED:
160 case SSL_R_TLSV1_ALERT_DECRYPT_ERROR:
161 case SSL_R_TLSV1_ALERT_EXPORT_RESTRICTION:
162 case SSL_R_TLSV1_ALERT_INTERNAL_ERROR:
163 case SSL_R_TLSV1_ALERT_NO_RENEGOTIATION:
164 case SSL_R_TLSV1_ALERT_RECORD_OVERFLOW:
165 case SSL_R_TLSV1_ALERT_USER_CANCELLED:
166 return ERR_SSL_PROTOCOL_ERROR;
167 default:
168 LOG(WARNING) << "Unmapped error reason: " << ERR_GET_REASON(error_code);
169 return ERR_FAILED;
170 }
171}
172
173// Converts an OpenSSL error code into a net error code, walking the OpenSSL
174// error stack if needed. Note that |tracer| is not currently used in the
175// implementation, but is passed in anyway as this ensures the caller will clear
176// any residual codes left on the error stack.
[email protected]4b559b4d2011-04-14 17:37:14177int MapOpenSSLError(int err, const crypto::OpenSSLErrStackTracer& tracer) {
[email protected]d518cd92010-09-29 12:27:44178 switch (err) {
179 case SSL_ERROR_WANT_READ:
180 case SSL_ERROR_WANT_WRITE:
181 return ERR_IO_PENDING;
[email protected]170e76c2010-10-04 15:04:20182 case SSL_ERROR_SYSCALL:
[email protected]abc7e06d2010-10-06 15:40:35183 DVLOG(1) << "OpenSSL SYSCALL error, errno " << errno;
[email protected]170e76c2010-10-04 15:04:20184 return ERR_SSL_PROTOCOL_ERROR;
[email protected]109805a2010-12-07 18:17:06185 case SSL_ERROR_SSL:
186 return MapOpenSSLErrorSSL();
[email protected]d518cd92010-09-29 12:27:44187 default:
188 // TODO(joth): Implement full mapping.
189 LOG(WARNING) << "Unknown OpenSSL error " << err;
[email protected]d518cd92010-09-29 12:27:44190 return ERR_SSL_PROTOCOL_ERROR;
191 }
192}
193
[email protected]313834722010-11-17 09:57:18194// We do certificate verification after handshake, so we disable the default
195// by registering a no-op verify function.
196int NoOpVerifyCallback(X509_STORE_CTX*, void *) {
197 DVLOG(3) << "skipping cert verify";
198 return 1;
199}
200
[email protected]fbef13932010-11-23 12:38:53201// OpenSSL manages a cache of SSL_SESSION, this class provides the application
202// side policy for that cache about session re-use: we retain one session per
203// unique HostPortPair.
204class SSLSessionCache {
205 public:
206 SSLSessionCache() {}
207
208 void OnSessionAdded(const HostPortPair& host_and_port, SSL_SESSION* session) {
209 // Declare the session cleaner-upper before the lock, so any call into
210 // OpenSSL to free the session will happen after the lock is released.
[email protected]4b559b4d2011-04-14 17:37:14211 crypto::ScopedOpenSSL<SSL_SESSION, SSL_SESSION_free> session_to_free;
[email protected]20305ec2011-01-21 04:55:52212 base::AutoLock lock(lock_);
[email protected]fbef13932010-11-23 12:38:53213
214 DCHECK_EQ(0U, session_map_.count(session));
215 std::pair<HostPortMap::iterator, bool> res =
216 host_port_map_.insert(std::make_pair(host_and_port, session));
217 if (!res.second) { // Already exists: replace old entry.
218 session_to_free.reset(res.first->second);
219 session_map_.erase(session_to_free.get());
220 res.first->second = session;
221 }
222 DVLOG(2) << "Adding session " << session << " => "
223 << host_and_port.ToString() << ", new entry = " << res.second;
224 DCHECK(host_port_map_[host_and_port] == session);
225 session_map_[session] = res.first;
226 DCHECK_EQ(host_port_map_.size(), session_map_.size());
227 DCHECK_LE(host_port_map_.size(), kSessionCacheMaxEntires);
[email protected]313834722010-11-17 09:57:18228 }
[email protected]fbef13932010-11-23 12:38:53229
230 void OnSessionRemoved(SSL_SESSION* session) {
231 // Declare the session cleaner-upper before the lock, so any call into
232 // OpenSSL to free the session will happen after the lock is released.
[email protected]4b559b4d2011-04-14 17:37:14233 crypto::ScopedOpenSSL<SSL_SESSION, SSL_SESSION_free> session_to_free;
[email protected]20305ec2011-01-21 04:55:52234 base::AutoLock lock(lock_);
[email protected]fbef13932010-11-23 12:38:53235
236 SessionMap::iterator it = session_map_.find(session);
237 if (it == session_map_.end())
238 return;
239 DVLOG(2) << "Remove session " << session << " => "
240 << it->second->first.ToString();
241 DCHECK(it->second->second == session);
242 host_port_map_.erase(it->second);
243 session_map_.erase(it);
244 session_to_free.reset(session);
245 DCHECK_EQ(host_port_map_.size(), session_map_.size());
[email protected]313834722010-11-17 09:57:18246 }
[email protected]fbef13932010-11-23 12:38:53247
248 // Looks up the host:port in the cache, and if a session is found it is added
249 // to |ssl|, returning true on success.
250 bool SetSSLSession(SSL* ssl, const HostPortPair& host_and_port) {
[email protected]20305ec2011-01-21 04:55:52251 base::AutoLock lock(lock_);
[email protected]fbef13932010-11-23 12:38:53252 HostPortMap::iterator it = host_port_map_.find(host_and_port);
253 if (it == host_port_map_.end())
254 return false;
255 DVLOG(2) << "Lookup session: " << it->second << " => "
256 << host_and_port.ToString();
257 SSL_SESSION* session = it->second;
258 DCHECK(session);
259 DCHECK(session_map_[session] == it);
260 // Ideally we'd release |lock_| before calling into OpenSSL here, however
261 // that opens a small risk |session| will go out of scope before it is used.
262 // Alternatively we would take a temporary local refcount on |session|,
263 // except OpenSSL does not provide a public API for adding a ref (c.f.
264 // SSL_SESSION_free which decrements the ref).
265 return SSL_set_session(ssl, session) == 1;
266 }
267
268 private:
269 // A pair of maps to allow bi-directional lookups between host:port and an
[email protected]109805a2010-12-07 18:17:06270 // associated session.
[email protected]fbef13932010-11-23 12:38:53271 // TODO(joth): When client certificates are implemented we should key the
272 // cache on the client certificate used in addition to the host-port pair.
273 typedef std::map<HostPortPair, SSL_SESSION*> HostPortMap;
274 typedef std::map<SSL_SESSION*, HostPortMap::iterator> SessionMap;
275 HostPortMap host_port_map_;
276 SessionMap session_map_;
277
278 // Protects access to both the above maps.
[email protected]20305ec2011-01-21 04:55:52279 base::Lock lock_;
[email protected]fbef13932010-11-23 12:38:53280
281 DISALLOW_COPY_AND_ASSIGN(SSLSessionCache);
[email protected]313834722010-11-17 09:57:18282};
283
[email protected]fbef13932010-11-23 12:38:53284class SSLContext {
285 public:
[email protected]b29af7d2010-12-14 11:52:47286 static SSLContext* GetInstance() { return Singleton<SSLContext>::get(); }
[email protected]fbef13932010-11-23 12:38:53287 SSL_CTX* ssl_ctx() { return ssl_ctx_.get(); }
288 SSLSessionCache* session_cache() { return &session_cache_; }
289
290 SSLClientSocketOpenSSL* GetClientSocketFromSSL(SSL* ssl) {
291 DCHECK(ssl);
292 SSLClientSocketOpenSSL* socket = static_cast<SSLClientSocketOpenSSL*>(
293 SSL_get_ex_data(ssl, ssl_socket_data_index_));
294 DCHECK(socket);
295 return socket;
296 }
297
298 bool SetClientSocketForSSL(SSL* ssl, SSLClientSocketOpenSSL* socket) {
299 return SSL_set_ex_data(ssl, ssl_socket_data_index_, socket) != 0;
300 }
301
302 private:
303 friend struct DefaultSingletonTraits<SSLContext>;
304
305 SSLContext() {
[email protected]4b559b4d2011-04-14 17:37:14306 crypto::EnsureOpenSSLInit();
[email protected]fbef13932010-11-23 12:38:53307 ssl_socket_data_index_ = SSL_get_ex_new_index(0, 0, 0, 0, 0);
308 DCHECK_NE(ssl_socket_data_index_, -1);
309 ssl_ctx_.reset(SSL_CTX_new(SSLv23_client_method()));
310 SSL_CTX_set_cert_verify_callback(ssl_ctx_.get(), NoOpVerifyCallback, NULL);
311 SSL_CTX_set_session_cache_mode(ssl_ctx_.get(), SSL_SESS_CACHE_CLIENT);
312 SSL_CTX_sess_set_new_cb(ssl_ctx_.get(), NewSessionCallbackStatic);
313 SSL_CTX_sess_set_remove_cb(ssl_ctx_.get(), RemoveSessionCallbackStatic);
314 SSL_CTX_set_timeout(ssl_ctx_.get(), kSessionCacheTimeoutSeconds);
315 SSL_CTX_sess_set_cache_size(ssl_ctx_.get(), kSessionCacheMaxEntires);
[email protected]718c9672010-12-02 10:04:10316 SSL_CTX_set_client_cert_cb(ssl_ctx_.get(), ClientCertCallback);
[email protected]ea4a1c6a2010-12-09 13:33:28317#if defined(OPENSSL_NPN_NEGOTIATED)
318 // TODO(kristianm): Only select this if ssl_config_.next_proto is not empty.
319 // It would be better if the callback were not a global setting,
320 // but that is an OpenSSL issue.
321 SSL_CTX_set_next_proto_select_cb(ssl_ctx_.get(), SelectNextProtoCallback,
322 NULL);
323#endif
[email protected]fbef13932010-11-23 12:38:53324 }
325
326 static int NewSessionCallbackStatic(SSL* ssl, SSL_SESSION* session) {
[email protected]b29af7d2010-12-14 11:52:47327 return GetInstance()->NewSessionCallback(ssl, session);
[email protected]fbef13932010-11-23 12:38:53328 }
329
330 int NewSessionCallback(SSL* ssl, SSL_SESSION* session) {
331 SSLClientSocketOpenSSL* socket = GetClientSocketFromSSL(ssl);
332 session_cache_.OnSessionAdded(socket->host_and_port(), session);
333 return 1; // 1 => We took ownership of |session|.
334 }
335
336 static void RemoveSessionCallbackStatic(SSL_CTX* ctx, SSL_SESSION* session) {
[email protected]b29af7d2010-12-14 11:52:47337 return GetInstance()->RemoveSessionCallback(ctx, session);
[email protected]fbef13932010-11-23 12:38:53338 }
339
340 void RemoveSessionCallback(SSL_CTX* ctx, SSL_SESSION* session) {
341 DCHECK(ctx == ssl_ctx());
342 session_cache_.OnSessionRemoved(session);
343 }
344
[email protected]718c9672010-12-02 10:04:10345 static int ClientCertCallback(SSL* ssl, X509** x509, EVP_PKEY** pkey) {
[email protected]b29af7d2010-12-14 11:52:47346 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
[email protected]718c9672010-12-02 10:04:10347 CHECK(socket);
348 return socket->ClientCertRequestCallback(ssl, x509, pkey);
349 }
350
[email protected]ea4a1c6a2010-12-09 13:33:28351 static int SelectNextProtoCallback(SSL* ssl,
352 unsigned char** out, unsigned char* outlen,
353 const unsigned char* in,
354 unsigned int inlen, void* arg) {
[email protected]b29af7d2010-12-14 11:52:47355 SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl);
[email protected]ea4a1c6a2010-12-09 13:33:28356 return socket->SelectNextProtoCallback(out, outlen, in, inlen);
357 }
358
[email protected]fbef13932010-11-23 12:38:53359 // This is the index used with SSL_get_ex_data to retrieve the owner
360 // SSLClientSocketOpenSSL object from an SSL instance.
361 int ssl_socket_data_index_;
362
[email protected]4b559b4d2011-04-14 17:37:14363 crypto::ScopedOpenSSL<SSL_CTX, SSL_CTX_free> ssl_ctx_;
[email protected]fbef13932010-11-23 12:38:53364 SSLSessionCache session_cache_;
365};
[email protected]313834722010-11-17 09:57:18366
[email protected]fb10e2282010-12-01 17:08:48367// Utility to construct the appropriate set & clear masks for use the OpenSSL
368// options and mode configuration functions. (SSL_set_options etc)
369struct SslSetClearMask {
370 SslSetClearMask() : set_mask(0), clear_mask(0) {}
371 void ConfigureFlag(long flag, bool state) {
372 (state ? set_mask : clear_mask) |= flag;
373 // Make sure we haven't got any intersection in the set & clear options.
374 DCHECK_EQ(0, set_mask & clear_mask) << flag << ":" << state;
375 }
376 long set_mask;
377 long clear_mask;
378};
379
[email protected]3b112772010-10-04 10:54:49380} // namespace
[email protected]d518cd92010-09-29 12:27:44381
382SSLClientSocketOpenSSL::SSLClientSocketOpenSSL(
383 ClientSocketHandle* transport_socket,
[email protected]055d7f22010-11-15 12:03:12384 const HostPortPair& host_and_port,
[email protected]822581d2010-12-16 17:27:15385 const SSLConfig& ssl_config,
[email protected]feb79bcd2011-07-21 16:55:17386 const SSLClientSocketContext& context)
[email protected]d518cd92010-09-29 12:27:44387 : ALLOW_THIS_IN_INITIALIZER_LIST(buffer_send_callback_(
388 this, &SSLClientSocketOpenSSL::BufferSendComplete)),
389 ALLOW_THIS_IN_INITIALIZER_LIST(buffer_recv_callback_(
390 this, &SSLClientSocketOpenSSL::BufferRecvComplete)),
391 transport_send_busy_(false),
392 transport_recv_busy_(false),
393 user_connect_callback_(NULL),
394 user_read_callback_(NULL),
395 user_write_callback_(NULL),
[email protected]fbef13932010-11-23 12:38:53396 completed_handshake_(false),
[email protected]d518cd92010-09-29 12:27:44397 client_auth_cert_needed_(false),
[email protected]feb79bcd2011-07-21 16:55:17398 cert_verifier_(context.cert_verifier),
[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]17a60a52011-10-28 01:18:10565 ssl_info->client_cert_sent =
566 ssl_config_.send_client_cert && ssl_config_.client_cert;
[email protected]2907525c2010-10-08 15:53:52567
568 const SSL_CIPHER* cipher = SSL_get_current_cipher(ssl_);
569 CHECK(cipher);
570 ssl_info->security_bits = SSL_CIPHER_get_bits(cipher, NULL);
[email protected]2907525c2010-10-08 15:53:52571 const COMP_METHOD* compression = SSL_get_current_compression(ssl_);
[email protected]109805a2010-12-07 18:17:06572
573 ssl_info->connection_status = EncodeSSLConnectionStatus(
574 SSL_CIPHER_get_id(cipher),
575 compression ? compression->type : 0,
576 GetNetSSLVersion(ssl_));
[email protected]9e733f32010-10-04 18:19:08577
578 bool peer_supports_renego_ext = !!SSL_get_secure_renegotiation_support(ssl_);
579 if (!peer_supports_renego_ext)
580 ssl_info->connection_status |= SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION;
[email protected]109805a2010-12-07 18:17:06581 UMA_HISTOGRAM_ENUMERATION("Net.RenegotiationExtensionSupported",
582 implicit_cast<int>(peer_supports_renego_ext), 2);
[email protected]9e733f32010-10-04 18:19:08583
584 if (ssl_config_.ssl3_fallback)
585 ssl_info->connection_status |= SSL_CONNECTION_SSL3_FALLBACK;
[email protected]109805a2010-12-07 18:17:06586
587 DVLOG(3) << "Encoded connection status: cipher suite = "
588 << SSLConnectionStatusToCipherSuite(ssl_info->connection_status)
589 << " compression = "
590 << SSLConnectionStatusToCompression(ssl_info->connection_status)
591 << " version = "
592 << SSLConnectionStatusToVersion(ssl_info->connection_status);
[email protected]d518cd92010-09-29 12:27:44593}
594
595void SSLClientSocketOpenSSL::GetSSLCertRequestInfo(
596 SSLCertRequestInfo* cert_request_info) {
[email protected]718c9672010-12-02 10:04:10597 cert_request_info->host_and_port = host_and_port_.ToString();
598 cert_request_info->client_certs = client_certs_;
[email protected]d518cd92010-09-29 12:27:44599}
600
[email protected]b0ff3f82011-07-23 05:12:39601int SSLClientSocketOpenSSL::ExportKeyingMaterial(
602 const base::StringPiece& label, const base::StringPiece& context,
603 unsigned char *out, unsigned int outlen) {
604 return ERR_NOT_IMPLEMENTED;
605}
606
[email protected]d518cd92010-09-29 12:27:44607SSLClientSocket::NextProtoStatus SSLClientSocketOpenSSL::GetNextProto(
608 std::string* proto) {
[email protected]ea4a1c6a2010-12-09 13:33:28609 *proto = npn_proto_;
610 return npn_status_;
[email protected]d518cd92010-09-29 12:27:44611}
612
613void SSLClientSocketOpenSSL::DoReadCallback(int rv) {
614 // Since Run may result in Read being called, clear |user_read_callback_|
615 // up front.
[email protected]f1f3f0f82011-10-01 20:38:10616 OldCompletionCallback* c = user_read_callback_;
[email protected]d518cd92010-09-29 12:27:44617 user_read_callback_ = NULL;
618 user_read_buf_ = NULL;
619 user_read_buf_len_ = 0;
620 c->Run(rv);
621}
622
623void SSLClientSocketOpenSSL::DoWriteCallback(int rv) {
624 // Since Run may result in Write being called, clear |user_write_callback_|
625 // up front.
[email protected]f1f3f0f82011-10-01 20:38:10626 OldCompletionCallback* c = user_write_callback_;
[email protected]d518cd92010-09-29 12:27:44627 user_write_callback_ = NULL;
628 user_write_buf_ = NULL;
629 user_write_buf_len_ = 0;
630 c->Run(rv);
631}
632
[email protected]3268023f2011-05-05 00:08:10633// StreamSocket methods
[email protected]d518cd92010-09-29 12:27:44634
[email protected]f1f3f0f82011-10-01 20:38:10635int SSLClientSocketOpenSSL::Connect(OldCompletionCallback* callback) {
[email protected]d518cd92010-09-29 12:27:44636 net_log_.BeginEvent(NetLog::TYPE_SSL_CONNECT, NULL);
637
[email protected]d518cd92010-09-29 12:27:44638 // Set up new ssl object.
639 if (!Init()) {
[email protected]d7fd1782011-02-08 19:16:43640 int result = ERR_UNEXPECTED;
641 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, result);
642 return result;
[email protected]d518cd92010-09-29 12:27:44643 }
644
645 // Set SSL to client mode. Handshake happens in the loop below.
646 SSL_set_connect_state(ssl_);
647
648 GotoState(STATE_HANDSHAKE);
649 int rv = DoHandshakeLoop(net::OK);
650 if (rv == ERR_IO_PENDING) {
651 user_connect_callback_ = callback;
652 } else {
[email protected]d7fd1782011-02-08 19:16:43653 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
[email protected]d518cd92010-09-29 12:27:44654 }
655
656 return rv > OK ? OK : rv;
657}
658
659void SSLClientSocketOpenSSL::Disconnect() {
[email protected]170e76c2010-10-04 15:04:20660 if (ssl_) {
661 SSL_free(ssl_);
662 ssl_ = NULL;
663 }
664 if (transport_bio_) {
665 BIO_free_all(transport_bio_);
666 transport_bio_ = NULL;
667 }
668
[email protected]0f7804ec2011-10-07 20:04:18669 // Shut down anything that may call us back.
[email protected]170e76c2010-10-04 15:04:20670 verifier_.reset();
671 transport_->socket()->Disconnect();
672
[email protected]d518cd92010-09-29 12:27:44673 // Null all callbacks, delete all buffers.
674 transport_send_busy_ = false;
675 send_buffer_ = NULL;
676 transport_recv_busy_ = false;
677 recv_buffer_ = NULL;
678
679 user_connect_callback_ = NULL;
680 user_read_callback_ = NULL;
681 user_write_callback_ = NULL;
682 user_read_buf_ = NULL;
683 user_read_buf_len_ = 0;
684 user_write_buf_ = NULL;
685 user_write_buf_len_ = 0;
686
[email protected]170e76c2010-10-04 15:04:20687 server_cert_verify_result_.Reset();
[email protected]d518cd92010-09-29 12:27:44688 completed_handshake_ = false;
[email protected]fbef13932010-11-23 12:38:53689
690 client_certs_.clear();
691 client_auth_cert_needed_ = false;
[email protected]d518cd92010-09-29 12:27:44692}
693
694int SSLClientSocketOpenSSL::DoHandshakeLoop(int last_io_result) {
695 bool network_moved;
696 int rv = last_io_result;
697 do {
698 // Default to STATE_NONE for next state.
699 // (This is a quirk carried over from the windows
700 // implementation. It makes reading the logs a bit harder.)
701 // State handlers can and often do call GotoState just
702 // to stay in the current state.
703 State state = next_handshake_state_;
704 GotoState(STATE_NONE);
705 switch (state) {
706 case STATE_NONE:
707 // we're just pumping data between the buffer and the network
708 break;
709 case STATE_HANDSHAKE:
710 rv = DoHandshake();
711 break;
[email protected]d518cd92010-09-29 12:27:44712 case STATE_VERIFY_CERT:
713 DCHECK(rv == OK);
714 rv = DoVerifyCert(rv);
715 break;
716 case STATE_VERIFY_CERT_COMPLETE:
717 rv = DoVerifyCertComplete(rv);
718 break;
[email protected]d518cd92010-09-29 12:27:44719 default:
720 rv = ERR_UNEXPECTED;
721 NOTREACHED() << "unexpected state" << state;
722 break;
723 }
724
725 // To avoid getting an ERR_IO_PENDING here after handshake complete.
726 if (next_handshake_state_ == STATE_NONE)
727 break;
728
729 // Do the actual network I/O.
730 network_moved = DoTransportIO();
731 } while ((rv != ERR_IO_PENDING || network_moved) &&
732 next_handshake_state_ != STATE_NONE);
733 return rv;
734}
735
736int SSLClientSocketOpenSSL::DoHandshake() {
[email protected]4b559b4d2011-04-14 17:37:14737 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
[email protected]d518cd92010-09-29 12:27:44738 int net_error = net::OK;
739 int rv = SSL_do_handshake(ssl_);
740
[email protected]718c9672010-12-02 10:04:10741 if (client_auth_cert_needed_) {
742 net_error = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
743 // If the handshake already succeeded (because the server requests but
744 // doesn't require a client cert), we need to invalidate the SSL session
745 // so that we won't try to resume the non-client-authenticated session in
746 // the next handshake. This will cause the server to ask for a client
747 // cert again.
748 if (rv == 1) {
749 // Remove from session cache but don't clear this connection.
750 SSL_SESSION* session = SSL_get_session(ssl_);
751 if (session) {
752 int rv = SSL_CTX_remove_session(SSL_get_SSL_CTX(ssl_), session);
753 LOG_IF(WARNING, !rv) << "Couldn't invalidate SSL session: " << session;
754 }
755 }
756 } else if (rv == 1) {
[email protected]fbef13932010-11-23 12:38:53757 if (trying_cached_session_ && logging::DEBUG_MODE) {
758 DVLOG(2) << "Result of session reuse for " << host_and_port_.ToString()
759 << " is: " << (SSL_session_reused(ssl_) ? "Success" : "Fail");
760 }
[email protected]d518cd92010-09-29 12:27:44761 // SSL handshake is completed. Let's verify the certificate.
[email protected]abc7e06d2010-10-06 15:40:35762 const bool got_cert = !!UpdateServerCert();
763 DCHECK(got_cert);
[email protected]59468382011-11-04 02:22:04764 if (net_log_.IsLoggingBytes()) {
765 net_log_.AddEvent(
766 NetLog::TYPE_SSL_CERTIFICATES_RECEIVED,
767 make_scoped_refptr(new X509CertificateNetLogParam(server_cert_)));
768 }
[email protected]abc7e06d2010-10-06 15:40:35769 GotoState(STATE_VERIFY_CERT);
[email protected]d518cd92010-09-29 12:27:44770 } else {
771 int ssl_error = SSL_get_error(ssl_, rv);
[email protected]109805a2010-12-07 18:17:06772 net_error = MapOpenSSLError(ssl_error, err_tracer);
[email protected]d518cd92010-09-29 12:27:44773
774 // If not done, stay in this state
[email protected]170e76c2010-10-04 15:04:20775 if (net_error == ERR_IO_PENDING) {
776 GotoState(STATE_HANDSHAKE);
777 } else {
778 LOG(ERROR) << "handshake failed; returned " << rv
779 << ", SSL error code " << ssl_error
780 << ", net_error " << net_error;
[email protected]109805a2010-12-07 18:17:06781 net_log_.AddEvent(
782 NetLog::TYPE_SSL_HANDSHAKE_ERROR,
783 make_scoped_refptr(new SSLErrorParams(net_error, ssl_error)));
[email protected]170e76c2010-10-04 15:04:20784 }
785 }
786 return net_error;
787}
788
[email protected]ea4a1c6a2010-12-09 13:33:28789int SSLClientSocketOpenSSL::SelectNextProtoCallback(unsigned char** out,
790 unsigned char* outlen,
791 const unsigned char* in,
792 unsigned int inlen) {
793#if defined(OPENSSL_NPN_NEGOTIATED)
794 if (ssl_config_.next_protos.empty()) {
[email protected]32e1dee2010-12-09 18:36:24795 *out = reinterpret_cast<uint8*>(const_cast<char*>("http/1.1"));
[email protected]ea4a1c6a2010-12-09 13:33:28796 *outlen = 8;
797 npn_status_ = SSLClientSocket::kNextProtoUnsupported;
798 return SSL_TLSEXT_ERR_OK;
799 }
800
801 int status = SSL_select_next_proto(
802 out, outlen, in, inlen,
803 reinterpret_cast<const unsigned char*>(ssl_config_.next_protos.data()),
804 ssl_config_.next_protos.size());
805
806 npn_proto_.assign(reinterpret_cast<const char*>(*out), *outlen);
807 switch (status) {
808 case OPENSSL_NPN_UNSUPPORTED:
809 npn_status_ = SSLClientSocket::kNextProtoUnsupported;
810 break;
811 case OPENSSL_NPN_NEGOTIATED:
812 npn_status_ = SSLClientSocket::kNextProtoNegotiated;
813 break;
814 case OPENSSL_NPN_NO_OVERLAP:
815 npn_status_ = SSLClientSocket::kNextProtoNoOverlap;
816 break;
817 default:
818 NOTREACHED() << status;
819 break;
820 }
[email protected]32e1dee2010-12-09 18:36:24821 DVLOG(2) << "next protocol: '" << npn_proto_ << "' status: " << npn_status_;
[email protected]ea4a1c6a2010-12-09 13:33:28822#endif
823 return SSL_TLSEXT_ERR_OK;
824}
825
[email protected]170e76c2010-10-04 15:04:20826int SSLClientSocketOpenSSL::DoVerifyCert(int result) {
827 DCHECK(server_cert_);
828 GotoState(STATE_VERIFY_CERT_COMPLETE);
[email protected]170e76c2010-10-04 15:04:20829
[email protected]70d66502011-09-23 00:55:08830 CertStatus cert_status;
[email protected]4dc832e2011-04-28 22:04:24831 if (ssl_config_.IsAllowedBadCert(server_cert_, &cert_status)) {
832 VLOG(1) << "Received an expected bad cert with status: " << cert_status;
833 server_cert_verify_result_.Reset();
834 server_cert_verify_result_.cert_status = cert_status;
[email protected]eb8414e2011-07-30 08:47:47835 server_cert_verify_result_.verified_cert = server_cert_;
[email protected]4dc832e2011-04-28 22:04:24836 return OK;
837 }
838
839 int flags = 0;
[email protected]170e76c2010-10-04 15:04:20840 if (ssl_config_.rev_checking_enabled)
841 flags |= X509Certificate::VERIFY_REV_CHECKING_ENABLED;
842 if (ssl_config_.verify_ev_cert)
843 flags |= X509Certificate::VERIFY_EV_CERT;
[email protected]822581d2010-12-16 17:27:15844 verifier_.reset(new SingleRequestCertVerifier(cert_verifier_));
[email protected]0f7804ec2011-10-07 20:04:18845 return verifier_->Verify(
846 server_cert_, host_and_port_.host(), flags,
[email protected]a642e33d2011-10-25 19:50:49847 NULL /* no CRL set */,
[email protected]0f7804ec2011-10-07 20:04:18848 &server_cert_verify_result_,
849 base::Bind(&SSLClientSocketOpenSSL::OnHandshakeIOComplete,
[email protected]8420c6f2011-10-19 13:54:57850 base::Unretained(this)),
851 net_log_);
[email protected]170e76c2010-10-04 15:04:20852}
853
854int SSLClientSocketOpenSSL::DoVerifyCertComplete(int result) {
855 verifier_.reset();
856
857 if (result == OK) {
858 // TODO(joth): Work out if we need to remember the intermediate CA certs
859 // when the server sends them to us, and do so here.
[email protected]2907525c2010-10-08 15:53:52860 } else {
861 DVLOG(1) << "DoVerifyCertComplete error " << ErrorToString(result)
862 << " (" << result << ")";
[email protected]d518cd92010-09-29 12:27:44863 }
864
[email protected]170e76c2010-10-04 15:04:20865 completed_handshake_ = true;
[email protected]170e76c2010-10-04 15:04:20866 // Exit DoHandshakeLoop and return the result to the caller to Connect.
867 DCHECK_EQ(STATE_NONE, next_handshake_state_);
868 return result;
869}
870
[email protected]170e76c2010-10-04 15:04:20871X509Certificate* SSLClientSocketOpenSSL::UpdateServerCert() {
872 if (server_cert_)
873 return server_cert_;
874
[email protected]4b559b4d2011-04-14 17:37:14875 crypto::ScopedOpenSSL<X509, X509_free> cert(SSL_get_peer_certificate(ssl_));
[email protected]2907525c2010-10-08 15:53:52876 if (!cert.get()) {
[email protected]170e76c2010-10-04 15:04:20877 LOG(WARNING) << "SSL_get_peer_certificate returned NULL";
878 return NULL;
879 }
880
[email protected]2907525c2010-10-08 15:53:52881 // Unlike SSL_get_peer_certificate, SSL_get_peer_cert_chain does not
882 // increment the reference so sk_X509_free does not need to be called.
883 STACK_OF(X509)* chain = SSL_get_peer_cert_chain(ssl_);
884 X509Certificate::OSCertHandles intermediates;
885 if (chain) {
886 for (int i = 0; i < sk_X509_num(chain); ++i)
887 intermediates.push_back(sk_X509_value(chain, i));
888 }
[email protected]72f508122011-07-19 05:12:17889 server_cert_ = X509Certificate::CreateFromHandle(cert.get(), intermediates);
[email protected]170e76c2010-10-04 15:04:20890 DCHECK(server_cert_);
[email protected]170e76c2010-10-04 15:04:20891
892 return server_cert_;
[email protected]d518cd92010-09-29 12:27:44893}
894
895bool SSLClientSocketOpenSSL::DoTransportIO() {
896 bool network_moved = false;
897 int nsent = BufferSend();
898 int nreceived = BufferRecv();
899 network_moved = (nsent > 0 || nreceived >= 0);
900 return network_moved;
901}
902
903int SSLClientSocketOpenSSL::BufferSend(void) {
904 if (transport_send_busy_)
905 return ERR_IO_PENDING;
906
907 if (!send_buffer_) {
908 // Get a fresh send buffer out of the send BIO.
909 size_t max_read = BIO_ctrl_pending(transport_bio_);
910 if (max_read > 0) {
911 send_buffer_ = new DrainableIOBuffer(new IOBuffer(max_read), max_read);
912 int read_bytes = BIO_read(transport_bio_, send_buffer_->data(), max_read);
913 DCHECK_GT(read_bytes, 0);
914 CHECK_EQ(static_cast<int>(max_read), read_bytes);
915 }
916 }
917
918 int rv = 0;
919 while (send_buffer_) {
920 rv = transport_->socket()->Write(send_buffer_,
921 send_buffer_->BytesRemaining(),
922 &buffer_send_callback_);
923 if (rv == ERR_IO_PENDING) {
924 transport_send_busy_ = true;
925 return rv;
926 }
927 TransportWriteComplete(rv);
928 }
929 return rv;
930}
931
932void SSLClientSocketOpenSSL::BufferSendComplete(int result) {
933 transport_send_busy_ = false;
934 TransportWriteComplete(result);
935 OnSendComplete(result);
936}
937
938void SSLClientSocketOpenSSL::TransportWriteComplete(int result) {
[email protected]abc7e06d2010-10-06 15:40:35939 DCHECK(ERR_IO_PENDING != result);
[email protected]d518cd92010-09-29 12:27:44940 if (result < 0) {
941 // Got a socket write error; close the BIO to indicate this upward.
[email protected]abc7e06d2010-10-06 15:40:35942 DVLOG(1) << "TransportWriteComplete error " << result;
[email protected]d518cd92010-09-29 12:27:44943 (void)BIO_shutdown_wr(transport_bio_);
944 send_buffer_ = NULL;
945 } else {
946 DCHECK(send_buffer_);
947 send_buffer_->DidConsume(result);
948 DCHECK_GE(send_buffer_->BytesRemaining(), 0);
949 if (send_buffer_->BytesRemaining() <= 0)
950 send_buffer_ = NULL;
951 }
952}
953
954int SSLClientSocketOpenSSL::BufferRecv(void) {
955 if (transport_recv_busy_)
956 return ERR_IO_PENDING;
957
958 size_t max_write = BIO_ctrl_get_write_guarantee(transport_bio_);
959 if (max_write > kMaxRecvBufferSize)
960 max_write = kMaxRecvBufferSize;
961
962 if (!max_write)
963 return ERR_IO_PENDING;
964
965 recv_buffer_ = new IOBuffer(max_write);
966 int rv = transport_->socket()->Read(recv_buffer_, max_write,
967 &buffer_recv_callback_);
968 if (rv == ERR_IO_PENDING) {
969 transport_recv_busy_ = true;
970 } else {
971 TransportReadComplete(rv);
972 }
973 return rv;
974}
975
976void SSLClientSocketOpenSSL::BufferRecvComplete(int result) {
977 TransportReadComplete(result);
978 OnRecvComplete(result);
979}
980
981void SSLClientSocketOpenSSL::TransportReadComplete(int result) {
[email protected]abc7e06d2010-10-06 15:40:35982 DCHECK(ERR_IO_PENDING != result);
983 if (result <= 0) {
984 DVLOG(1) << "TransportReadComplete result " << result;
985 // Received 0 (end of file) or an error. Either way, bubble it up to the
986 // SSL layer via the BIO. TODO(joth): consider stashing the error code, to
987 // relay up to the SSL socket client (i.e. via DoReadCallback).
988 BIO_set_mem_eof_return(transport_bio_, 0);
989 (void)BIO_shutdown_wr(transport_bio_);
990 } else {
991 DCHECK(recv_buffer_);
[email protected]d518cd92010-09-29 12:27:44992 int ret = BIO_write(transport_bio_, recv_buffer_->data(), result);
993 // A write into a memory BIO should always succeed.
994 CHECK_EQ(result, ret);
[email protected]d518cd92010-09-29 12:27:44995 }
996 recv_buffer_ = NULL;
997 transport_recv_busy_ = false;
998}
999
1000void SSLClientSocketOpenSSL::DoConnectCallback(int rv) {
[email protected]f1f3f0f82011-10-01 20:38:101001 OldCompletionCallback* c = user_connect_callback_;
[email protected]d518cd92010-09-29 12:27:441002 user_connect_callback_ = NULL;
1003 c->Run(rv > OK ? OK : rv);
1004}
1005
1006void SSLClientSocketOpenSSL::OnHandshakeIOComplete(int result) {
1007 int rv = DoHandshakeLoop(result);
1008 if (rv != ERR_IO_PENDING) {
[email protected]d7fd1782011-02-08 19:16:431009 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
[email protected]d518cd92010-09-29 12:27:441010 DoConnectCallback(rv);
1011 }
1012}
1013
1014void SSLClientSocketOpenSSL::OnSendComplete(int result) {
1015 if (next_handshake_state_ != STATE_NONE) {
1016 // In handshake phase.
1017 OnHandshakeIOComplete(result);
1018 return;
1019 }
1020
1021 // OnSendComplete may need to call DoPayloadRead while the renegotiation
1022 // handshake is in progress.
1023 int rv_read = ERR_IO_PENDING;
1024 int rv_write = ERR_IO_PENDING;
1025 bool network_moved;
1026 do {
1027 if (user_read_buf_)
1028 rv_read = DoPayloadRead();
1029 if (user_write_buf_)
1030 rv_write = DoPayloadWrite();
1031 network_moved = DoTransportIO();
1032 } while (rv_read == ERR_IO_PENDING &&
1033 rv_write == ERR_IO_PENDING &&
1034 network_moved);
1035
1036 if (user_read_buf_ && rv_read != ERR_IO_PENDING)
1037 DoReadCallback(rv_read);
1038 if (user_write_buf_ && rv_write != ERR_IO_PENDING)
1039 DoWriteCallback(rv_write);
1040}
1041
1042void SSLClientSocketOpenSSL::OnRecvComplete(int result) {
1043 if (next_handshake_state_ != STATE_NONE) {
1044 // In handshake phase.
1045 OnHandshakeIOComplete(result);
1046 return;
1047 }
1048
1049 // Network layer received some data, check if client requested to read
1050 // decrypted data.
1051 if (!user_read_buf_)
1052 return;
1053
1054 int rv = DoReadLoop(result);
1055 if (rv != ERR_IO_PENDING)
1056 DoReadCallback(rv);
1057}
1058
1059bool SSLClientSocketOpenSSL::IsConnected() const {
1060 bool ret = completed_handshake_ && transport_->socket()->IsConnected();
1061 return ret;
1062}
1063
1064bool SSLClientSocketOpenSSL::IsConnectedAndIdle() const {
1065 bool ret = completed_handshake_ && transport_->socket()->IsConnectedAndIdle();
1066 return ret;
1067}
1068
1069int SSLClientSocketOpenSSL::GetPeerAddress(AddressList* addressList) const {
1070 return transport_->socket()->GetPeerAddress(addressList);
1071}
1072
[email protected]e7f74da2011-04-19 23:49:351073int SSLClientSocketOpenSSL::GetLocalAddress(IPEndPoint* addressList) const {
1074 return transport_->socket()->GetLocalAddress(addressList);
1075}
1076
[email protected]d518cd92010-09-29 12:27:441077const BoundNetLog& SSLClientSocketOpenSSL::NetLog() const {
1078 return net_log_;
1079}
1080
1081void SSLClientSocketOpenSSL::SetSubresourceSpeculation() {
1082 if (transport_.get() && transport_->socket()) {
1083 transport_->socket()->SetSubresourceSpeculation();
1084 } else {
1085 NOTREACHED();
1086 }
1087}
1088
1089void SSLClientSocketOpenSSL::SetOmniboxSpeculation() {
1090 if (transport_.get() && transport_->socket()) {
1091 transport_->socket()->SetOmniboxSpeculation();
1092 } else {
1093 NOTREACHED();
1094 }
1095}
1096
1097bool SSLClientSocketOpenSSL::WasEverUsed() const {
1098 if (transport_.get() && transport_->socket())
1099 return transport_->socket()->WasEverUsed();
1100
1101 NOTREACHED();
1102 return false;
1103}
1104
[email protected]7f7e92392010-10-26 18:29:291105bool SSLClientSocketOpenSSL::UsingTCPFastOpen() const {
1106 if (transport_.get() && transport_->socket())
1107 return transport_->socket()->UsingTCPFastOpen();
1108
1109 NOTREACHED();
1110 return false;
1111}
1112
[email protected]1e71d3072011-07-05 11:34:471113int64 SSLClientSocketOpenSSL::NumBytesRead() const {
1114 if (transport_.get() && transport_->socket())
1115 return transport_->socket()->NumBytesRead();
1116
1117 NOTREACHED();
1118 return -1;
1119}
1120
1121base::TimeDelta SSLClientSocketOpenSSL::GetConnectTimeMicros() const {
1122 if (transport_.get() && transport_->socket())
1123 return transport_->socket()->GetConnectTimeMicros();
1124
1125 NOTREACHED();
1126 return base::TimeDelta::FromMicroseconds(-1);
1127}
1128
[email protected]d518cd92010-09-29 12:27:441129// Socket methods
1130
1131int SSLClientSocketOpenSSL::Read(IOBuffer* buf,
1132 int buf_len,
[email protected]f1f3f0f82011-10-01 20:38:101133 OldCompletionCallback* callback) {
[email protected]d518cd92010-09-29 12:27:441134 user_read_buf_ = buf;
1135 user_read_buf_len_ = buf_len;
1136
1137 int rv = DoReadLoop(OK);
1138
1139 if (rv == ERR_IO_PENDING) {
1140 user_read_callback_ = callback;
1141 } else {
1142 user_read_buf_ = NULL;
1143 user_read_buf_len_ = 0;
1144 }
1145
1146 return rv;
1147}
1148
1149int SSLClientSocketOpenSSL::DoReadLoop(int result) {
1150 if (result < 0)
1151 return result;
1152
1153 bool network_moved;
1154 int rv;
1155 do {
1156 rv = DoPayloadRead();
1157 network_moved = DoTransportIO();
1158 } while (rv == ERR_IO_PENDING && network_moved);
1159
1160 return rv;
1161}
1162
1163int SSLClientSocketOpenSSL::Write(IOBuffer* buf,
1164 int buf_len,
[email protected]f1f3f0f82011-10-01 20:38:101165 OldCompletionCallback* callback) {
[email protected]d518cd92010-09-29 12:27:441166 user_write_buf_ = buf;
1167 user_write_buf_len_ = buf_len;
1168
1169 int rv = DoWriteLoop(OK);
1170
1171 if (rv == ERR_IO_PENDING) {
1172 user_write_callback_ = callback;
1173 } else {
1174 user_write_buf_ = NULL;
1175 user_write_buf_len_ = 0;
1176 }
1177
1178 return rv;
1179}
1180
1181int SSLClientSocketOpenSSL::DoWriteLoop(int result) {
1182 if (result < 0)
1183 return result;
1184
1185 bool network_moved;
1186 int rv;
1187 do {
1188 rv = DoPayloadWrite();
1189 network_moved = DoTransportIO();
1190 } while (rv == ERR_IO_PENDING && network_moved);
1191
1192 return rv;
1193}
1194
1195bool SSLClientSocketOpenSSL::SetReceiveBufferSize(int32 size) {
1196 return transport_->socket()->SetReceiveBufferSize(size);
1197}
1198
1199bool SSLClientSocketOpenSSL::SetSendBufferSize(int32 size) {
1200 return transport_->socket()->SetSendBufferSize(size);
1201}
1202
1203int SSLClientSocketOpenSSL::DoPayloadRead() {
[email protected]4b559b4d2011-04-14 17:37:141204 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
[email protected]d518cd92010-09-29 12:27:441205 int rv = SSL_read(ssl_, user_read_buf_->data(), user_read_buf_len_);
1206 // We don't need to invalidate the non-client-authenticated SSL session
1207 // because the server will renegotiate anyway.
1208 if (client_auth_cert_needed_)
1209 return ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
1210
[email protected]1d872d32011-05-19 02:45:331211 if (rv >= 0) {
[email protected]267a0d66d2011-06-01 21:15:191212 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, rv,
1213 user_read_buf_->data());
[email protected]d518cd92010-09-29 12:27:441214 return rv;
[email protected]1d872d32011-05-19 02:45:331215 }
[email protected]d518cd92010-09-29 12:27:441216
1217 int err = SSL_get_error(ssl_, rv);
[email protected]109805a2010-12-07 18:17:061218 return MapOpenSSLError(err, err_tracer);
[email protected]d518cd92010-09-29 12:27:441219}
1220
1221int SSLClientSocketOpenSSL::DoPayloadWrite() {
[email protected]4b559b4d2011-04-14 17:37:141222 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
[email protected]d518cd92010-09-29 12:27:441223 int rv = SSL_write(ssl_, user_write_buf_->data(), user_write_buf_len_);
1224
[email protected]1d872d32011-05-19 02:45:331225 if (rv >= 0) {
[email protected]267a0d66d2011-06-01 21:15:191226 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_SENT, rv,
1227 user_write_buf_->data());
[email protected]d518cd92010-09-29 12:27:441228 return rv;
[email protected]1d872d32011-05-19 02:45:331229 }
[email protected]d518cd92010-09-29 12:27:441230
1231 int err = SSL_get_error(ssl_, rv);
[email protected]109805a2010-12-07 18:17:061232 return MapOpenSSLError(err, err_tracer);
[email protected]d518cd92010-09-29 12:27:441233}
1234
[email protected]7e5dd49f2010-12-08 18:33:491235} // namespace net