Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(13)

Side by Side Diff: net/socket/ssl_client_socket_openssl.cc

Issue 1178193002: Sign CertificateVerify messages on a background thread. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: rsleevi comments Created 5 years, 6 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 // OpenSSL binding for SSLClientSocket. The class layout and general principle 5 // OpenSSL binding for SSLClientSocket. The class layout and general principle
6 // of operation is derived from SSLClientSocketNSS. 6 // of operation is derived from SSLClientSocketNSS.
7 7
8 #include "net/socket/ssl_client_socket_openssl.h" 8 #include "net/socket/ssl_client_socket_openssl.h"
9 9
10 #include <errno.h> 10 #include <errno.h>
11 #include <openssl/bio.h> 11 #include <openssl/bio.h>
12 #include <openssl/err.h> 12 #include <openssl/err.h>
13 #include <openssl/mem.h> 13 #include <openssl/mem.h>
14 #include <openssl/ssl.h> 14 #include <openssl/ssl.h>
15 #include <string.h> 15 #include <string.h>
16 16
17 #include "base/bind.h" 17 #include "base/bind.h"
18 #include "base/callback_helpers.h" 18 #include "base/callback_helpers.h"
19 #include "base/environment.h" 19 #include "base/environment.h"
20 #include "base/memory/singleton.h" 20 #include "base/memory/singleton.h"
21 #include "base/metrics/histogram.h" 21 #include "base/metrics/histogram.h"
22 #include "base/profiler/scoped_tracker.h" 22 #include "base/profiler/scoped_tracker.h"
23 #include "base/stl_util.h"
23 #include "base/strings/string_piece.h" 24 #include "base/strings/string_piece.h"
24 #include "base/synchronization/lock.h" 25 #include "base/synchronization/lock.h"
25 #include "base/threading/thread_local.h" 26 #include "base/threading/thread_local.h"
27 #include "base/threading/worker_pool.h"
26 #include "base/values.h" 28 #include "base/values.h"
27 #include "crypto/ec_private_key.h" 29 #include "crypto/ec_private_key.h"
28 #include "crypto/openssl_util.h" 30 #include "crypto/openssl_util.h"
29 #include "crypto/scoped_openssl_types.h" 31 #include "crypto/scoped_openssl_types.h"
30 #include "net/base/net_errors.h" 32 #include "net/base/net_errors.h"
31 #include "net/cert/cert_policy_enforcer.h" 33 #include "net/cert/cert_policy_enforcer.h"
32 #include "net/cert/cert_verifier.h" 34 #include "net/cert/cert_verifier.h"
33 #include "net/cert/ct_ev_whitelist.h" 35 #include "net/cert/ct_ev_whitelist.h"
34 #include "net/cert/ct_verifier.h" 36 #include "net/cert/ct_verifier.h"
35 #include "net/cert/x509_certificate_net_log_param.h" 37 #include "net/cert/x509_certificate_net_log_param.h"
36 #include "net/cert/x509_util_openssl.h" 38 #include "net/cert/x509_util_openssl.h"
37 #include "net/http/transport_security_state.h" 39 #include "net/http/transport_security_state.h"
38 #include "net/ssl/scoped_openssl_types.h" 40 #include "net/ssl/scoped_openssl_types.h"
39 #include "net/ssl/ssl_cert_request_info.h" 41 #include "net/ssl/ssl_cert_request_info.h"
40 #include "net/ssl/ssl_client_session_cache_openssl.h" 42 #include "net/ssl/ssl_client_session_cache_openssl.h"
41 #include "net/ssl/ssl_connection_status_flags.h" 43 #include "net/ssl/ssl_connection_status_flags.h"
42 #include "net/ssl/ssl_failure_state.h" 44 #include "net/ssl/ssl_failure_state.h"
43 #include "net/ssl/ssl_info.h" 45 #include "net/ssl/ssl_info.h"
46 #include "net/ssl/ssl_private_key.h"
44 47
45 #if defined(OS_WIN) 48 #if defined(OS_WIN)
46 #include "base/win/windows_version.h" 49 #include "base/win/windows_version.h"
47 #endif 50 #endif
48 51
49 #if defined(USE_OPENSSL_CERTS) 52 #if defined(USE_OPENSSL_CERTS)
50 #include "net/ssl/openssl_client_key_store.h" 53 #include "net/ssl/openssl_client_key_store.h"
51 #else 54 #else
52 #include "net/ssl/openssl_platform_key.h" 55 #include "net/ssl/ssl_platform_key.h"
53 #endif 56 #endif
54 57
55 namespace net { 58 namespace net {
56 59
57 namespace { 60 namespace {
58 61
59 // Enable this to see logging for state machine state transitions. 62 // Enable this to see logging for state machine state transitions.
60 #if 0 63 #if 0
61 #define GotoState(s) do { DVLOG(2) << (void *)this << " " << __FUNCTION__ << \ 64 #define GotoState(s) do { DVLOG(2) << (void *)this << " " << __FUNCTION__ << \
62 " jump to state " << s; \ 65 " jump to state " << s; \
63 next_handshake_state_ = s; } while (0) 66 next_handshake_state_ = s; } while (0)
64 #else 67 #else
65 #define GotoState(s) next_handshake_state_ = s 68 #define GotoState(s) next_handshake_state_ = s
66 #endif 69 #endif
67 70
68 // This constant can be any non-negative/non-zero value (eg: it does not 71 // This constant can be any non-negative/non-zero value (eg: it does not
69 // overlap with any value of the net::Error range, including net::OK). 72 // overlap with any value of the net::Error range, including net::OK).
70 const int kNoPendingReadResult = 1; 73 const int kNoPendingResult = 1;
71 74
72 // If a client doesn't have a list of protocols that it supports, but 75 // If a client doesn't have a list of protocols that it supports, but
73 // the server supports NPN, choosing "http/1.1" is the best answer. 76 // the server supports NPN, choosing "http/1.1" is the best answer.
74 const char kDefaultSupportedNPNProtocol[] = "http/1.1"; 77 const char kDefaultSupportedNPNProtocol[] = "http/1.1";
75 78
76 // Default size of the internal BoringSSL buffers. 79 // Default size of the internal BoringSSL buffers.
77 const int KDefaultOpenSSLBufferSize = 17 * 1024; 80 const int KDefaultOpenSSLBufferSize = 17 * 1024;
78 81
79 void FreeX509Stack(STACK_OF(X509)* ptr) { 82 void FreeX509Stack(STACK_OF(X509)* ptr) {
80 sk_X509_pop_free(ptr, X509_free); 83 sk_X509_pop_free(ptr, X509_free);
(...skipping 56 matching lines...) Expand 10 before | Expand all | Expand 10 after
137 sk_X509_push(stack.get(), x509.release()); 140 sk_X509_push(stack.get(), x509.release());
138 } 141 }
139 return stack.Pass(); 142 return stack.Pass();
140 } 143 }
141 144
142 int LogErrorCallback(const char* str, size_t len, void* context) { 145 int LogErrorCallback(const char* str, size_t len, void* context) {
143 LOG(ERROR) << base::StringPiece(str, len); 146 LOG(ERROR) << base::StringPiece(str, len);
144 return 1; 147 return 1;
145 } 148 }
146 149
150 bool EVP_MDToPrivateKeyHash(const EVP_MD* md, SSLPrivateKey::Hash* hash) {
151 switch (EVP_MD_type(md)) {
152 case NID_md5_sha1:
153 *hash = SSLPrivateKey::Hash::MD5_SHA1;
154 return true;
155 case NID_md5:
156 *hash = SSLPrivateKey::Hash::MD5;
157 return true;
158 case NID_sha1:
159 *hash = SSLPrivateKey::Hash::SHA1;
160 return true;
161 case NID_sha224:
162 *hash = SSLPrivateKey::Hash::SHA224;
163 return true;
164 case NID_sha256:
165 *hash = SSLPrivateKey::Hash::SHA256;
166 return true;
167 case NID_sha384:
168 *hash = SSLPrivateKey::Hash::SHA384;
169 return true;
170 case NID_sha512:
171 *hash = SSLPrivateKey::Hash::SHA512;
172 return true;
173 default:
174 return false;
175 }
176 }
177
147 } // namespace 178 } // namespace
148 179
149 class SSLClientSocketOpenSSL::SSLContext { 180 class SSLClientSocketOpenSSL::SSLContext {
150 public: 181 public:
151 static SSLContext* GetInstance() { return Singleton<SSLContext>::get(); } 182 static SSLContext* GetInstance() { return Singleton<SSLContext>::get(); }
152 SSL_CTX* ssl_ctx() { return ssl_ctx_.get(); } 183 SSL_CTX* ssl_ctx() { return ssl_ctx_.get(); }
153 SSLClientSessionCacheOpenSSL* session_cache() { return &session_cache_; } 184 SSLClientSessionCacheOpenSSL* session_cache() { return &session_cache_; }
154 185
155 SSLClientSocketOpenSSL* GetClientSocketFromSSL(const SSL* ssl) { 186 SSLClientSocketOpenSSL* GetClientSocketFromSSL(const SSL* ssl) {
156 DCHECK(ssl); 187 DCHECK(ssl);
(...skipping 185 matching lines...) Expand 10 before | Expand all | Expand 10 after
342 return SSL_PROTOCOL_VERSION_TLS1_2; 373 return SSL_PROTOCOL_VERSION_TLS1_2;
343 } 374 }
344 375
345 SSLClientSocketOpenSSL::SSLClientSocketOpenSSL( 376 SSLClientSocketOpenSSL::SSLClientSocketOpenSSL(
346 scoped_ptr<ClientSocketHandle> transport_socket, 377 scoped_ptr<ClientSocketHandle> transport_socket,
347 const HostPortPair& host_and_port, 378 const HostPortPair& host_and_port,
348 const SSLConfig& ssl_config, 379 const SSLConfig& ssl_config,
349 const SSLClientSocketContext& context) 380 const SSLClientSocketContext& context)
350 : transport_send_busy_(false), 381 : transport_send_busy_(false),
351 transport_recv_busy_(false), 382 transport_recv_busy_(false),
352 pending_read_error_(kNoPendingReadResult), 383 pending_read_error_(kNoPendingResult),
353 pending_read_ssl_error_(SSL_ERROR_NONE), 384 pending_read_ssl_error_(SSL_ERROR_NONE),
354 transport_read_error_(OK), 385 transport_read_error_(OK),
355 transport_write_error_(OK), 386 transport_write_error_(OK),
356 server_cert_chain_(new PeerCertificateChain(NULL)), 387 server_cert_chain_(new PeerCertificateChain(NULL)),
357 completed_connect_(false), 388 completed_connect_(false),
358 was_ever_used_(false), 389 was_ever_used_(false),
359 cert_verifier_(context.cert_verifier), 390 cert_verifier_(context.cert_verifier),
360 cert_transparency_verifier_(context.cert_transparency_verifier), 391 cert_transparency_verifier_(context.cert_transparency_verifier),
361 channel_id_service_(context.channel_id_service), 392 channel_id_service_(context.channel_id_service),
362 ssl_(NULL), 393 ssl_(NULL),
363 transport_bio_(NULL), 394 transport_bio_(NULL),
364 transport_(transport_socket.Pass()), 395 transport_(transport_socket.Pass()),
365 host_and_port_(host_and_port), 396 host_and_port_(host_and_port),
366 ssl_config_(ssl_config), 397 ssl_config_(ssl_config),
367 ssl_session_cache_shard_(context.ssl_session_cache_shard), 398 ssl_session_cache_shard_(context.ssl_session_cache_shard),
368 next_handshake_state_(STATE_NONE), 399 next_handshake_state_(STATE_NONE),
369 npn_status_(kNextProtoUnsupported), 400 npn_status_(kNextProtoUnsupported),
370 channel_id_sent_(false), 401 channel_id_sent_(false),
371 handshake_completed_(false), 402 handshake_completed_(false),
372 certificate_verified_(false), 403 certificate_verified_(false),
373 ssl_failure_state_(SSL_FAILURE_NONE), 404 ssl_failure_state_(SSL_FAILURE_NONE),
405 signature_result_(kNoPendingResult),
374 transport_security_state_(context.transport_security_state), 406 transport_security_state_(context.transport_security_state),
375 policy_enforcer_(context.cert_policy_enforcer), 407 policy_enforcer_(context.cert_policy_enforcer),
376 net_log_(transport_->socket()->NetLog()), 408 net_log_(transport_->socket()->NetLog()),
377 weak_factory_(this) { 409 weak_factory_(this) {
378 DCHECK(cert_verifier_); 410 DCHECK(cert_verifier_);
379 } 411 }
380 412
381 SSLClientSocketOpenSSL::~SSLClientSocketOpenSSL() { 413 SSLClientSocketOpenSSL::~SSLClientSocketOpenSSL() {
382 Disconnect(); 414 Disconnect();
383 } 415 }
(...skipping 101 matching lines...) Expand 10 before | Expand all | Expand 10 after
485 recv_buffer_ = NULL; 517 recv_buffer_ = NULL;
486 518
487 user_connect_callback_.Reset(); 519 user_connect_callback_.Reset();
488 user_read_callback_.Reset(); 520 user_read_callback_.Reset();
489 user_write_callback_.Reset(); 521 user_write_callback_.Reset();
490 user_read_buf_ = NULL; 522 user_read_buf_ = NULL;
491 user_read_buf_len_ = 0; 523 user_read_buf_len_ = 0;
492 user_write_buf_ = NULL; 524 user_write_buf_ = NULL;
493 user_write_buf_len_ = 0; 525 user_write_buf_len_ = 0;
494 526
495 pending_read_error_ = kNoPendingReadResult; 527 pending_read_error_ = kNoPendingResult;
496 pending_read_ssl_error_ = SSL_ERROR_NONE; 528 pending_read_ssl_error_ = SSL_ERROR_NONE;
497 pending_read_error_info_ = OpenSSLErrorInfo(); 529 pending_read_error_info_ = OpenSSLErrorInfo();
498 530
499 transport_read_error_ = OK; 531 transport_read_error_ = OK;
500 transport_write_error_ = OK; 532 transport_write_error_ = OK;
501 533
502 server_cert_verify_result_.Reset(); 534 server_cert_verify_result_.Reset();
503 completed_connect_ = false; 535 completed_connect_ = false;
504 536
505 cert_authorities_.clear(); 537 cert_authorities_.clear();
506 cert_key_types_.clear(); 538 cert_key_types_.clear();
507 539
508 start_cert_verification_time_ = base::TimeTicks(); 540 start_cert_verification_time_ = base::TimeTicks();
509 541
510 npn_status_ = kNextProtoUnsupported; 542 npn_status_ = kNextProtoUnsupported;
511 npn_proto_.clear(); 543 npn_proto_.clear();
512 544
513 channel_id_sent_ = false; 545 channel_id_sent_ = false;
514 handshake_completed_ = false; 546 handshake_completed_ = false;
515 certificate_verified_ = false; 547 certificate_verified_ = false;
516 channel_id_request_.Cancel(); 548 channel_id_request_.Cancel();
517 ssl_failure_state_ = SSL_FAILURE_NONE; 549 ssl_failure_state_ = SSL_FAILURE_NONE;
550
551 private_key_.reset();
552 signature_result_ = kNoPendingResult;
553 signature_.clear();
518 } 554 }
519 555
520 bool SSLClientSocketOpenSSL::IsConnected() const { 556 bool SSLClientSocketOpenSSL::IsConnected() const {
521 // If the handshake has not yet completed. 557 // If the handshake has not yet completed.
522 if (!completed_connect_) 558 if (!completed_connect_)
523 return false; 559 return false;
524 // If an asynchronous operation is still pending. 560 // If an asynchronous operation is still pending.
525 if (user_read_buf_.get() || user_write_buf_.get()) 561 if (user_read_buf_.get() || user_write_buf_.get())
526 return true; 562 return true;
527 563
(...skipping 393 matching lines...) Expand 10 before | Expand all | Expand 10 after
921 if (ssl_error == SSL_ERROR_WANT_CHANNEL_ID_LOOKUP) { 957 if (ssl_error == SSL_ERROR_WANT_CHANNEL_ID_LOOKUP) {
922 // The server supports channel ID. Stop to look one up before returning to 958 // The server supports channel ID. Stop to look one up before returning to
923 // the handshake. 959 // the handshake.
924 GotoState(STATE_CHANNEL_ID_LOOKUP); 960 GotoState(STATE_CHANNEL_ID_LOOKUP);
925 return OK; 961 return OK;
926 } 962 }
927 if (ssl_error == SSL_ERROR_WANT_X509_LOOKUP && 963 if (ssl_error == SSL_ERROR_WANT_X509_LOOKUP &&
928 !ssl_config_.send_client_cert) { 964 !ssl_config_.send_client_cert) {
929 return ERR_SSL_CLIENT_AUTH_CERT_NEEDED; 965 return ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
930 } 966 }
967 if (ssl_error == SSL_ERROR_WANT_PRIVATE_KEY_OPERATION) {
968 DCHECK(private_key_);
969 DCHECK_NE(kNoPendingResult, signature_result_);
970 GotoState(STATE_HANDSHAKE);
971 return ERR_IO_PENDING;
972 }
931 973
932 OpenSSLErrorInfo error_info; 974 OpenSSLErrorInfo error_info;
933 net_error = MapOpenSSLErrorWithDetails(ssl_error, err_tracer, &error_info); 975 net_error = MapOpenSSLErrorWithDetails(ssl_error, err_tracer, &error_info);
934 if (net_error == ERR_IO_PENDING) { 976 if (net_error == ERR_IO_PENDING) {
935 // If not done, stay in this state 977 // If not done, stay in this state
936 GotoState(STATE_HANDSHAKE); 978 GotoState(STATE_HANDSHAKE);
937 return ERR_IO_PENDING; 979 return ERR_IO_PENDING;
938 } 980 }
939 981
940 LOG(ERROR) << "handshake failed; returned " << rv << ", SSL error code " 982 LOG(ERROR) << "handshake failed; returned " << rv << ", SSL error code "
(...skipping 308 matching lines...) Expand 10 before | Expand all | Expand 10 after
1249 } 1291 }
1250 } 1292 }
1251 1293
1252 void SSLClientSocketOpenSSL::OnSendComplete(int result) { 1294 void SSLClientSocketOpenSSL::OnSendComplete(int result) {
1253 if (next_handshake_state_ == STATE_HANDSHAKE) { 1295 if (next_handshake_state_ == STATE_HANDSHAKE) {
1254 // In handshake phase. 1296 // In handshake phase.
1255 OnHandshakeIOComplete(result); 1297 OnHandshakeIOComplete(result);
1256 return; 1298 return;
1257 } 1299 }
1258 1300
1259 // OnSendComplete may need to call DoPayloadRead while the renegotiation 1301 // OnSendComplete may need to run the Read state machine while a
1260 // handshake is in progress. 1302 // renegotiation handshake is in progress.
Ryan Sleevi 2015/06/15 22:55:22 I find this comment less clear then the original (
davidben 2015/06/17 20:47:02 The problem is the original comment is wrong. We n
1261 int rv_read = ERR_IO_PENDING; 1303 RunReadWriteLoops();
1262 int rv_write = ERR_IO_PENDING;
1263 bool network_moved;
1264 do {
1265 if (user_read_buf_.get())
1266 rv_read = DoPayloadRead();
1267 if (user_write_buf_.get())
1268 rv_write = DoPayloadWrite();
1269 network_moved = DoTransportIO();
1270 } while (rv_read == ERR_IO_PENDING && rv_write == ERR_IO_PENDING &&
1271 (user_read_buf_.get() || user_write_buf_.get()) && network_moved);
1272
1273 // Performing the Read callback may cause |this| to be deleted. If this
1274 // happens, the Write callback should not be invoked. Guard against this by
1275 // holding a WeakPtr to |this| and ensuring it's still valid.
1276 base::WeakPtr<SSLClientSocketOpenSSL> guard(weak_factory_.GetWeakPtr());
1277 if (user_read_buf_.get() && rv_read != ERR_IO_PENDING)
1278 DoReadCallback(rv_read);
1279
1280 if (!guard.get())
1281 return;
1282
1283 if (user_write_buf_.get() && rv_write != ERR_IO_PENDING)
1284 DoWriteCallback(rv_write);
1285 } 1304 }
1286 1305
1287 void SSLClientSocketOpenSSL::OnRecvComplete(int result) { 1306 void SSLClientSocketOpenSSL::OnRecvComplete(int result) {
1288 if (next_handshake_state_ == STATE_HANDSHAKE) { 1307 if (next_handshake_state_ == STATE_HANDSHAKE) {
1289 // In handshake phase. 1308 // In handshake phase.
1290 OnHandshakeIOComplete(result); 1309 OnHandshakeIOComplete(result);
1291 return; 1310 return;
1292 } 1311 }
1293 1312
1294 // Network layer received some data, check if client requested to read 1313 // Network layer received some data, check if client requested to read
(...skipping 77 matching lines...) Expand 10 before | Expand all | Expand 10 after
1372 return rv; 1391 return rv;
1373 } 1392 }
1374 1393
1375 int SSLClientSocketOpenSSL::DoPayloadRead() { 1394 int SSLClientSocketOpenSSL::DoPayloadRead() {
1376 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE); 1395 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1377 1396
1378 DCHECK_LT(0, user_read_buf_len_); 1397 DCHECK_LT(0, user_read_buf_len_);
1379 DCHECK(user_read_buf_.get()); 1398 DCHECK(user_read_buf_.get());
1380 1399
1381 int rv; 1400 int rv;
1382 if (pending_read_error_ != kNoPendingReadResult) { 1401 if (pending_read_error_ != kNoPendingResult) {
1383 rv = pending_read_error_; 1402 rv = pending_read_error_;
1384 pending_read_error_ = kNoPendingReadResult; 1403 pending_read_error_ = kNoPendingResult;
1385 if (rv == 0) { 1404 if (rv == 0) {
1386 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, 1405 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED,
1387 rv, user_read_buf_->data()); 1406 rv, user_read_buf_->data());
1388 } else { 1407 } else {
1389 net_log_.AddEvent( 1408 net_log_.AddEvent(
1390 NetLog::TYPE_SSL_READ_ERROR, 1409 NetLog::TYPE_SSL_READ_ERROR,
1391 CreateNetLogOpenSSLErrorCallback(rv, pending_read_ssl_error_, 1410 CreateNetLogOpenSSLErrorCallback(rv, pending_read_ssl_error_,
1392 pending_read_error_info_)); 1411 pending_read_error_info_));
1393 } 1412 }
1394 pending_read_ssl_error_ = SSL_ERROR_NONE; 1413 pending_read_ssl_error_ = SSL_ERROR_NONE;
(...skipping 21 matching lines...) Expand all
1416 // 1435 //
1417 // TransportReadComplete converts the first to an ERR_CONNECTION_CLOSED 1436 // TransportReadComplete converts the first to an ERR_CONNECTION_CLOSED
1418 // error, so it does not occur. The second and third are distinguished by 1437 // error, so it does not occur. The second and third are distinguished by
1419 // SSL_ERROR_ZERO_RETURN. 1438 // SSL_ERROR_ZERO_RETURN.
1420 pending_read_ssl_error_ = SSL_get_error(ssl_, ssl_ret); 1439 pending_read_ssl_error_ = SSL_get_error(ssl_, ssl_ret);
1421 if (pending_read_ssl_error_ == SSL_ERROR_ZERO_RETURN) { 1440 if (pending_read_ssl_error_ == SSL_ERROR_ZERO_RETURN) {
1422 pending_read_error_ = 0; 1441 pending_read_error_ = 0;
1423 } else if (pending_read_ssl_error_ == SSL_ERROR_WANT_X509_LOOKUP && 1442 } else if (pending_read_ssl_error_ == SSL_ERROR_WANT_X509_LOOKUP &&
1424 !ssl_config_.send_client_cert) { 1443 !ssl_config_.send_client_cert) {
1425 pending_read_error_ = ERR_SSL_CLIENT_AUTH_CERT_NEEDED; 1444 pending_read_error_ = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
1445 } else if (pending_read_ssl_error_ ==
1446 SSL_ERROR_WANT_PRIVATE_KEY_OPERATION) {
1447 DCHECK(private_key_);
1448 DCHECK_NE(kNoPendingResult, signature_result_);
1449 pending_read_error_ = ERR_IO_PENDING;
1426 } else { 1450 } else {
1427 pending_read_error_ = MapOpenSSLErrorWithDetails( 1451 pending_read_error_ = MapOpenSSLErrorWithDetails(
1428 pending_read_ssl_error_, err_tracer, &pending_read_error_info_); 1452 pending_read_ssl_error_, err_tracer, &pending_read_error_info_);
1429 } 1453 }
1430 1454
1431 // Many servers do not reliably send a close_notify alert when shutting down 1455 // Many servers do not reliably send a close_notify alert when shutting down
1432 // a connection, and instead terminate the TCP connection. This is reported 1456 // a connection, and instead terminate the TCP connection. This is reported
1433 // as ERR_CONNECTION_CLOSED. Because of this, map the unclean shutdown to a 1457 // as ERR_CONNECTION_CLOSED. Because of this, map the unclean shutdown to a
1434 // graceful EOF, instead of treating it as an error as it should be. 1458 // graceful EOF, instead of treating it as an error as it should be.
1435 if (pending_read_error_ == ERR_CONNECTION_CLOSED) 1459 if (pending_read_error_ == ERR_CONNECTION_CLOSED)
1436 pending_read_error_ = 0; 1460 pending_read_error_ = 0;
1437 } 1461 }
1438 1462
1439 if (total_bytes_read > 0) { 1463 if (total_bytes_read > 0) {
1440 // Return any bytes read to the caller. The error will be deferred to the 1464 // Return any bytes read to the caller. The error will be deferred to the
1441 // next call of DoPayloadRead. 1465 // next call of DoPayloadRead.
1442 rv = total_bytes_read; 1466 rv = total_bytes_read;
1443 1467
1444 // Do not treat insufficient data as an error to return in the next call to 1468 // Do not treat insufficient data as an error to return in the next call to
1445 // DoPayloadRead() - instead, let the call fall through to check SSL_read() 1469 // DoPayloadRead() - instead, let the call fall through to check SSL_read()
1446 // again. This is because DoTransportIO() may complete in between the next 1470 // again. This is because DoTransportIO() may complete in between the next
1447 // call to DoPayloadRead(), and thus it is important to check SSL_read() on 1471 // call to DoPayloadRead(), and thus it is important to check SSL_read() on
1448 // subsequent invocations to see if a complete record may now be read. 1472 // subsequent invocations to see if a complete record may now be read.
1449 if (pending_read_error_ == ERR_IO_PENDING) 1473 if (pending_read_error_ == ERR_IO_PENDING)
1450 pending_read_error_ = kNoPendingReadResult; 1474 pending_read_error_ = kNoPendingResult;
1451 } else { 1475 } else {
1452 // No bytes were returned. Return the pending read error immediately. 1476 // No bytes were returned. Return the pending read error immediately.
1453 DCHECK_NE(kNoPendingReadResult, pending_read_error_); 1477 DCHECK_NE(kNoPendingResult, pending_read_error_);
1454 rv = pending_read_error_; 1478 rv = pending_read_error_;
1455 pending_read_error_ = kNoPendingReadResult; 1479 pending_read_error_ = kNoPendingResult;
1456 } 1480 }
1457 1481
1458 if (rv >= 0) { 1482 if (rv >= 0) {
1459 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, rv, 1483 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, rv,
1460 user_read_buf_->data()); 1484 user_read_buf_->data());
1461 } else if (rv != ERR_IO_PENDING) { 1485 } else if (rv != ERR_IO_PENDING) {
1462 net_log_.AddEvent( 1486 net_log_.AddEvent(
1463 NetLog::TYPE_SSL_READ_ERROR, 1487 NetLog::TYPE_SSL_READ_ERROR,
1464 CreateNetLogOpenSSLErrorCallback(rv, pending_read_ssl_error_, 1488 CreateNetLogOpenSSLErrorCallback(rv, pending_read_ssl_error_,
1465 pending_read_error_info_)); 1489 pending_read_error_info_));
1466 pending_read_ssl_error_ = SSL_ERROR_NONE; 1490 pending_read_ssl_error_ = SSL_ERROR_NONE;
1467 pending_read_error_info_ = OpenSSLErrorInfo(); 1491 pending_read_error_info_ = OpenSSLErrorInfo();
1468 } 1492 }
1469 return rv; 1493 return rv;
1470 } 1494 }
1471 1495
1472 int SSLClientSocketOpenSSL::DoPayloadWrite() { 1496 int SSLClientSocketOpenSSL::DoPayloadWrite() {
1473 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE); 1497 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1474 int rv = SSL_write(ssl_, user_write_buf_->data(), user_write_buf_len_); 1498 int rv = SSL_write(ssl_, user_write_buf_->data(), user_write_buf_len_);
1475 1499
1476 if (rv >= 0) { 1500 if (rv >= 0) {
1477 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_SENT, rv, 1501 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_SENT, rv,
1478 user_write_buf_->data()); 1502 user_write_buf_->data());
1479 return rv; 1503 return rv;
1480 } 1504 }
1481 1505
1482 int ssl_error = SSL_get_error(ssl_, rv); 1506 int ssl_error = SSL_get_error(ssl_, rv);
1507 if (ssl_error == SSL_ERROR_WANT_PRIVATE_KEY_OPERATION)
1508 return ERR_IO_PENDING;
1483 OpenSSLErrorInfo error_info; 1509 OpenSSLErrorInfo error_info;
1484 int net_error = MapOpenSSLErrorWithDetails(ssl_error, err_tracer, 1510 int net_error = MapOpenSSLErrorWithDetails(ssl_error, err_tracer,
1485 &error_info); 1511 &error_info);
1486 1512
1487 if (net_error != ERR_IO_PENDING) { 1513 if (net_error != ERR_IO_PENDING) {
1488 net_log_.AddEvent( 1514 net_log_.AddEvent(
1489 NetLog::TYPE_SSL_WRITE_ERROR, 1515 NetLog::TYPE_SSL_WRITE_ERROR,
1490 CreateNetLogOpenSSLErrorCallback(net_error, ssl_error, error_info)); 1516 CreateNetLogOpenSSLErrorCallback(net_error, ssl_error, error_info));
1491 } 1517 }
1492 return net_error; 1518 return net_error;
1493 } 1519 }
1494 1520
1521 void SSLClientSocketOpenSSL::RunReadWriteLoops() {
1522 int rv_read = ERR_IO_PENDING;
1523 int rv_write = ERR_IO_PENDING;
1524 bool network_moved;
1525 do {
1526 if (user_read_buf_.get())
1527 rv_read = DoPayloadRead();
1528 if (user_write_buf_.get())
1529 rv_write = DoPayloadWrite();
1530 network_moved = DoTransportIO();
1531 } while (rv_read == ERR_IO_PENDING && rv_write == ERR_IO_PENDING &&
1532 (user_read_buf_.get() || user_write_buf_.get()) && network_moved);
1533
1534 // Performing the Read callback may cause |this| to be deleted. If this
1535 // happens, the Write callback should not be invoked. Guard against this by
1536 // holding a WeakPtr to |this| and ensuring it's still valid.
1537 base::WeakPtr<SSLClientSocketOpenSSL> guard(weak_factory_.GetWeakPtr());
1538 if (user_read_buf_.get() && rv_read != ERR_IO_PENDING)
1539 DoReadCallback(rv_read);
1540
1541 if (!guard.get())
1542 return;
1543
1544 if (user_write_buf_.get() && rv_write != ERR_IO_PENDING)
1545 DoWriteCallback(rv_write);
1546 }
1547
1495 int SSLClientSocketOpenSSL::BufferSend(void) { 1548 int SSLClientSocketOpenSSL::BufferSend(void) {
1496 if (transport_send_busy_) 1549 if (transport_send_busy_)
1497 return ERR_IO_PENDING; 1550 return ERR_IO_PENDING;
1498 1551
1499 size_t buffer_read_offset; 1552 size_t buffer_read_offset;
1500 uint8_t* read_buf; 1553 uint8_t* read_buf;
1501 size_t max_read; 1554 size_t max_read;
1502 int status = BIO_zero_copy_get_read_buf(transport_bio_, &read_buf, 1555 int status = BIO_zero_copy_get_read_buf(transport_bio_, &read_buf,
1503 &buffer_read_offset, &max_read); 1556 &buffer_read_offset, &max_read);
1504 DCHECK_EQ(status, 1); // Should never fail. 1557 DCHECK_EQ(status, 1); // Should never fail.
(...skipping 163 matching lines...) Expand 10 before | Expand all | Expand 10 after
1668 } 1721 }
1669 1722
1670 ScopedX509Stack chain = OSCertHandlesToOpenSSL( 1723 ScopedX509Stack chain = OSCertHandlesToOpenSSL(
1671 ssl_config_.client_cert->GetIntermediateCertificates()); 1724 ssl_config_.client_cert->GetIntermediateCertificates());
1672 if (!chain) { 1725 if (!chain) {
1673 LOG(WARNING) << "Failed to import intermediate certificates"; 1726 LOG(WARNING) << "Failed to import intermediate certificates";
1674 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT); 1727 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT);
1675 return -1; 1728 return -1;
1676 } 1729 }
1677 1730
1678 // TODO(davidben): With Linux client auth support, this should be 1731 if (!SSL_use_certificate(ssl_, leaf_x509.get()) ||
1679 // conditioned on OS_ANDROID and then, with https://crbug.com/394131, 1732 !SSL_set1_chain(ssl_, chain.get())) {
1680 // removed altogether. OpenSSLClientKeyStore is mostly an artifact of the 1733 LOG(WARNING) << "Failed to set client certificate";
1681 // net/ client auth API lacking a private key handle. 1734 return -1;
1735 }
1736
1682 #if defined(USE_OPENSSL_CERTS) 1737 #if defined(USE_OPENSSL_CERTS)
1683 crypto::ScopedEVP_PKEY privkey = 1738 crypto::ScopedEVP_PKEY privkey =
1684 OpenSSLClientKeyStore::GetInstance()->FetchClientCertPrivateKey( 1739 OpenSSLClientKeyStore::GetInstance()->FetchClientCertPrivateKey(
1685 ssl_config_.client_cert.get()); 1740 ssl_config_.client_cert.get());
1686 #else // !defined(USE_OPENSSL_CERTS)
1687 crypto::ScopedEVP_PKEY privkey =
1688 FetchClientCertPrivateKey(ssl_config_.client_cert.get());
1689 #endif // defined(USE_OPENSSL_CERTS)
1690 if (!privkey) { 1741 if (!privkey) {
1691 // Could not find the private key. Fail the handshake and surface an 1742 // Could not find the private key. Fail the handshake and surface an
1692 // appropriate error to the caller. 1743 // appropriate error to the caller.
1693 LOG(WARNING) << "Client cert found without private key"; 1744 LOG(WARNING) << "Client cert found without private key";
1694 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY); 1745 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY);
1695 return -1; 1746 return -1;
1696 } 1747 }
1748 if (!SSL_use_PrivateKey(ssl_, privkey.get())) {
1749 LOG(WARNING) << "Failed to set private key";
1750 return -1;
1751 }
1752 #else // !USE_OPENSSL_CERTS
1753 // TODO(davidben): Move Android to the SSLPrivateKey codepath and disable
1754 // client auth on NaCl altogether.
1755 //
1756 // TODO(davidben): Lift this call up to the embedder so we can actually test
1757 // this code. https://crbug.com/394131
1758 private_key_ = FetchClientCertPrivateKey(
1759 ssl_config_.client_cert.get(),
1760 base::WorkerPool::GetTaskRunner(true /* task_is_slow */));
Ryan Sleevi 2015/06/15 22:55:22 Per our chat, doesn't this need to be explicitly s
davidben 2015/06/17 20:47:02 Done.
1761 if (!private_key_) {
1762 // Could not find the private key. Fail the handshake and surface an
1763 // appropriate error to the caller.
1764 LOG(WARNING) << "Client cert found without private key";
1765 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY);
1766 return -1;
1767 }
1697 1768
1698 if (!SSL_use_certificate(ssl_, leaf_x509.get()) || 1769 static const SSL_PRIVATE_KEY_METHOD kPrivateKeyMethod = {
1699 !SSL_use_PrivateKey(ssl_, privkey.get()) || 1770 &SSLClientSocketOpenSSL::PrivateKeyTypeCallback,
1700 !SSL_set1_chain(ssl_, chain.get())) { 1771 &SSLClientSocketOpenSSL::PrivateKeySupportsDigestCallback,
1701 LOG(WARNING) << "Failed to set client certificate"; 1772 &SSLClientSocketOpenSSL::PrivateKeyMaxSignatureLenCallback,
1702 return -1; 1773 &SSLClientSocketOpenSSL::PrivateKeySignCallback,
1703 } 1774 &SSLClientSocketOpenSSL::PrivateKeySignCompleteCallback,
1775 };
1776 SSL_set_private_key_method(ssl_, &kPrivateKeyMethod);
1777 #endif // USE_OPENSSL_CERTS
1704 1778
1705 int cert_count = 1 + sk_X509_num(chain.get()); 1779 int cert_count = 1 + sk_X509_num(chain.get());
1706 net_log_.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED, 1780 net_log_.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED,
1707 NetLog::IntegerCallback("cert_count", cert_count)); 1781 NetLog::IntegerCallback("cert_count", cert_count));
1708 return 1; 1782 return 1;
1709 } 1783 }
1710 #endif // defined(OS_IOS) 1784 #endif // defined(OS_IOS)
1711 1785
1712 // Send no client certificate. 1786 // Send no client certificate.
1713 net_log_.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED, 1787 net_log_.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED,
(...skipping 201 matching lines...) Expand 10 before | Expand all | Expand 10 after
1915 return ssl_config_.renego_allowed_default; 1989 return ssl_config_.renego_allowed_default;
1916 1990
1917 NextProto next_proto = NextProtoFromString(npn_proto_); 1991 NextProto next_proto = NextProtoFromString(npn_proto_);
1918 for (NextProto allowed : ssl_config_.renego_allowed_for_protos) { 1992 for (NextProto allowed : ssl_config_.renego_allowed_for_protos) {
1919 if (next_proto == allowed) 1993 if (next_proto == allowed)
1920 return true; 1994 return true;
1921 } 1995 }
1922 return false; 1996 return false;
1923 } 1997 }
1924 1998
1999 // static
2000 int SSLClientSocketOpenSSL::PrivateKeyTypeCallback(SSL* ssl) {
2001 SSLClientSocketOpenSSL* socket =
2002 SSLContext::GetInstance()->GetClientSocketFromSSL(ssl);
2003
2004 switch (socket->private_key_->GetType()) {
2005 case SSLPrivateKey::Type::RSA:
2006 return EVP_PKEY_RSA;
2007 case SSLPrivateKey::Type::ECDSA:
2008 return EVP_PKEY_EC;
2009 }
2010 NOTREACHED();
2011 return EVP_PKEY_NONE;
2012 }
2013
2014 // static
2015 int SSLClientSocketOpenSSL::PrivateKeySupportsDigestCallback(SSL* ssl,
2016 const EVP_MD* md) {
2017 SSLClientSocketOpenSSL* socket =
2018 SSLContext::GetInstance()->GetClientSocketFromSSL(ssl);
2019
2020 SSLPrivateKey::Hash hash;
2021 return EVP_MDToPrivateKeyHash(md, &hash) &&
2022 socket->private_key_->SupportsHash(hash);
2023 }
2024
2025 // static
2026 size_t SSLClientSocketOpenSSL::PrivateKeyMaxSignatureLenCallback(SSL* ssl) {
2027 SSLClientSocketOpenSSL* socket =
2028 SSLContext::GetInstance()->GetClientSocketFromSSL(ssl);
2029
2030 return socket->private_key_->GetMaxSignatureLength();
2031 }
2032
2033 // static
2034 ssl_private_key_result_t SSLClientSocketOpenSSL::PrivateKeySignCallback(
2035 SSL* ssl,
2036 uint8_t* out,
2037 size_t* out_len,
2038 size_t max_out,
2039 const EVP_MD* md,
2040 const uint8_t* in,
2041 size_t in_len) {
2042 SSLClientSocketOpenSSL* socket =
2043 SSLContext::GetInstance()->GetClientSocketFromSSL(ssl);
2044
2045 DCHECK_EQ(kNoPendingResult, socket->signature_result_);
2046 DCHECK(socket->signature_.empty());
2047 DCHECK(socket->private_key_);
2048
2049 socket->net_log_.BeginEvent(NetLog::TYPE_SSL_PRIVATE_KEY_OPERATION);
2050
2051 SSLPrivateKey::Hash hash;
2052 if (!EVP_MDToPrivateKeyHash(md, &hash)) {
2053 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED);
2054 return ssl_private_key_failure;
2055 }
2056
2057 socket->signature_result_ = ERR_IO_PENDING;
2058 socket->private_key_->SignDigest(
2059 hash, base::StringPiece(reinterpret_cast<const char*>(in), in_len),
2060 base::Bind(&SSLClientSocketOpenSSL::OnPrivateKeySignComplete,
2061 socket->weak_factory_.GetWeakPtr()));
2062 return ssl_private_key_retry;
2063 }
2064
2065 // static
2066 ssl_private_key_result_t SSLClientSocketOpenSSL::PrivateKeySignCompleteCallback(
2067 SSL* ssl,
2068 uint8_t* out,
2069 size_t* out_len,
2070 size_t max_out) {
2071 SSLClientSocketOpenSSL* socket =
2072 SSLContext::GetInstance()->GetClientSocketFromSSL(ssl);
2073
2074 DCHECK_NE(kNoPendingResult, socket->signature_result_);
2075 DCHECK(socket->private_key_);
2076
2077 if (socket->signature_result_ == ERR_IO_PENDING)
2078 return ssl_private_key_retry;
2079 if (socket->signature_result_ != OK) {
2080 OpenSSLPutNetError(FROM_HERE, socket->signature_result_);
2081 return ssl_private_key_failure;
2082 }
2083 if (socket->signature_.size() > max_out) {
2084 LOG(ERROR) << "Buffer too small";
2085 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED);
2086 return ssl_private_key_failure;
2087 }
2088 memcpy(out, vector_as_array(&socket->signature_), socket->signature_.size());
2089 *out_len = socket->signature_.size();
2090 socket->signature_.clear();
2091 return ssl_private_key_success;
2092 }
2093
2094 void SSLClientSocketOpenSSL::OnPrivateKeySignComplete(
2095 Error error,
2096 const std::vector<uint8_t>& signature) {
2097 DCHECK_EQ(ERR_IO_PENDING, signature_result_);
2098 DCHECK(signature_.empty());
2099 DCHECK(private_key_);
2100
2101 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_PRIVATE_KEY_OPERATION,
2102 error);
2103
2104 signature_result_ = error;
2105 if (signature_result_ == OK)
2106 signature_ = signature;
2107
2108 if (next_handshake_state_ == STATE_HANDSHAKE) {
2109 OnHandshakeIOComplete(signature_result_);
2110 return;
2111 }
2112
2113 // Either Read or Write may be blocked on an asynchronous private
2114 // key operation during a renegotiation.
2115 RunReadWriteLoops();
2116 }
2117
1925 scoped_refptr<X509Certificate> 2118 scoped_refptr<X509Certificate>
1926 SSLClientSocketOpenSSL::GetUnverifiedServerCertificateChain() const { 2119 SSLClientSocketOpenSSL::GetUnverifiedServerCertificateChain() const {
1927 return server_cert_; 2120 return server_cert_;
1928 } 2121 }
1929 2122
1930 } // namespace net 2123 } // namespace net
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698