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

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: 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 // FIXME!!! The handshake state machine *cannot* handle things happening
969 // in parallel.
Ryan Sleevi 2015/06/12 23:37:20 ?
davidben 2015/06/15 21:28:24 Oops. Removed. Remnant of when I was toying with a
970 DCHECK(private_key_);
971 DCHECK_NE(kNoPendingResult, signature_result_);
972 GotoState(STATE_HANDSHAKE);
973 return ERR_IO_PENDING;
974 }
931 975
932 OpenSSLErrorInfo error_info; 976 OpenSSLErrorInfo error_info;
933 net_error = MapOpenSSLErrorWithDetails(ssl_error, err_tracer, &error_info); 977 net_error = MapOpenSSLErrorWithDetails(ssl_error, err_tracer, &error_info);
934 if (net_error == ERR_IO_PENDING) { 978 if (net_error == ERR_IO_PENDING) {
935 // If not done, stay in this state 979 // If not done, stay in this state
936 GotoState(STATE_HANDSHAKE); 980 GotoState(STATE_HANDSHAKE);
937 return ERR_IO_PENDING; 981 return ERR_IO_PENDING;
938 } 982 }
939 983
940 LOG(ERROR) << "handshake failed; returned " << rv << ", SSL error code " 984 LOG(ERROR) << "handshake failed; returned " << rv << ", SSL error code "
(...skipping 308 matching lines...) Expand 10 before | Expand all | Expand 10 after
1249 } 1293 }
1250 } 1294 }
1251 1295
1252 void SSLClientSocketOpenSSL::OnSendComplete(int result) { 1296 void SSLClientSocketOpenSSL::OnSendComplete(int result) {
1253 if (next_handshake_state_ == STATE_HANDSHAKE) { 1297 if (next_handshake_state_ == STATE_HANDSHAKE) {
1254 // In handshake phase. 1298 // In handshake phase.
1255 OnHandshakeIOComplete(result); 1299 OnHandshakeIOComplete(result);
1256 return; 1300 return;
1257 } 1301 }
1258 1302
1259 // OnSendComplete may need to call DoPayloadRead while the renegotiation 1303 // OnSendComplete may need to run the Read state machine while a
1260 // handshake is in progress. 1304 // renegotiation handshake is in progress.
1261 int rv_read = ERR_IO_PENDING; 1305 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 } 1306 }
1286 1307
1287 void SSLClientSocketOpenSSL::OnRecvComplete(int result) { 1308 void SSLClientSocketOpenSSL::OnRecvComplete(int result) {
1288 if (next_handshake_state_ == STATE_HANDSHAKE) { 1309 if (next_handshake_state_ == STATE_HANDSHAKE) {
1289 // In handshake phase. 1310 // In handshake phase.
1290 OnHandshakeIOComplete(result); 1311 OnHandshakeIOComplete(result);
1291 return; 1312 return;
1292 } 1313 }
1293 1314
1294 // Network layer received some data, check if client requested to read 1315 // 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; 1393 return rv;
1373 } 1394 }
1374 1395
1375 int SSLClientSocketOpenSSL::DoPayloadRead() { 1396 int SSLClientSocketOpenSSL::DoPayloadRead() {
1376 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE); 1397 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1377 1398
1378 DCHECK_LT(0, user_read_buf_len_); 1399 DCHECK_LT(0, user_read_buf_len_);
1379 DCHECK(user_read_buf_.get()); 1400 DCHECK(user_read_buf_.get());
1380 1401
1381 int rv; 1402 int rv;
1382 if (pending_read_error_ != kNoPendingReadResult) { 1403 if (pending_read_error_ != kNoPendingResult) {
1383 rv = pending_read_error_; 1404 rv = pending_read_error_;
1384 pending_read_error_ = kNoPendingReadResult; 1405 pending_read_error_ = kNoPendingResult;
1385 if (rv == 0) { 1406 if (rv == 0) {
1386 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, 1407 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED,
1387 rv, user_read_buf_->data()); 1408 rv, user_read_buf_->data());
1388 } else { 1409 } else {
1389 net_log_.AddEvent( 1410 net_log_.AddEvent(
1390 NetLog::TYPE_SSL_READ_ERROR, 1411 NetLog::TYPE_SSL_READ_ERROR,
1391 CreateNetLogOpenSSLErrorCallback(rv, pending_read_ssl_error_, 1412 CreateNetLogOpenSSLErrorCallback(rv, pending_read_ssl_error_,
1392 pending_read_error_info_)); 1413 pending_read_error_info_));
1393 } 1414 }
1394 pending_read_ssl_error_ = SSL_ERROR_NONE; 1415 pending_read_ssl_error_ = SSL_ERROR_NONE;
(...skipping 21 matching lines...) Expand all
1416 // 1437 //
1417 // TransportReadComplete converts the first to an ERR_CONNECTION_CLOSED 1438 // TransportReadComplete converts the first to an ERR_CONNECTION_CLOSED
1418 // error, so it does not occur. The second and third are distinguished by 1439 // error, so it does not occur. The second and third are distinguished by
1419 // SSL_ERROR_ZERO_RETURN. 1440 // SSL_ERROR_ZERO_RETURN.
1420 pending_read_ssl_error_ = SSL_get_error(ssl_, ssl_ret); 1441 pending_read_ssl_error_ = SSL_get_error(ssl_, ssl_ret);
1421 if (pending_read_ssl_error_ == SSL_ERROR_ZERO_RETURN) { 1442 if (pending_read_ssl_error_ == SSL_ERROR_ZERO_RETURN) {
1422 pending_read_error_ = 0; 1443 pending_read_error_ = 0;
1423 } else if (pending_read_ssl_error_ == SSL_ERROR_WANT_X509_LOOKUP && 1444 } else if (pending_read_ssl_error_ == SSL_ERROR_WANT_X509_LOOKUP &&
1424 !ssl_config_.send_client_cert) { 1445 !ssl_config_.send_client_cert) {
1425 pending_read_error_ = ERR_SSL_CLIENT_AUTH_CERT_NEEDED; 1446 pending_read_error_ = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
1447 } else if (pending_read_ssl_error_ ==
1448 SSL_ERROR_WANT_PRIVATE_KEY_OPERATION) {
1449 DCHECK(private_key_);
1450 DCHECK_NE(kNoPendingResult, signature_result_);
1451 pending_read_error_ = ERR_IO_PENDING;
1426 } else { 1452 } else {
1427 pending_read_error_ = MapOpenSSLErrorWithDetails( 1453 pending_read_error_ = MapOpenSSLErrorWithDetails(
1428 pending_read_ssl_error_, err_tracer, &pending_read_error_info_); 1454 pending_read_ssl_error_, err_tracer, &pending_read_error_info_);
1429 } 1455 }
1430 1456
1431 // Many servers do not reliably send a close_notify alert when shutting down 1457 // 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 1458 // 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 1459 // 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. 1460 // graceful EOF, instead of treating it as an error as it should be.
1435 if (pending_read_error_ == ERR_CONNECTION_CLOSED) 1461 if (pending_read_error_ == ERR_CONNECTION_CLOSED)
1436 pending_read_error_ = 0; 1462 pending_read_error_ = 0;
1437 } 1463 }
1438 1464
1439 if (total_bytes_read > 0) { 1465 if (total_bytes_read > 0) {
1440 // Return any bytes read to the caller. The error will be deferred to the 1466 // Return any bytes read to the caller. The error will be deferred to the
1441 // next call of DoPayloadRead. 1467 // next call of DoPayloadRead.
1442 rv = total_bytes_read; 1468 rv = total_bytes_read;
1443 1469
1444 // Do not treat insufficient data as an error to return in the next call to 1470 // 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() 1471 // DoPayloadRead() - instead, let the call fall through to check SSL_read()
1446 // again. This is because DoTransportIO() may complete in between the next 1472 // 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 1473 // 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. 1474 // subsequent invocations to see if a complete record may now be read.
1449 if (pending_read_error_ == ERR_IO_PENDING) 1475 if (pending_read_error_ == ERR_IO_PENDING)
1450 pending_read_error_ = kNoPendingReadResult; 1476 pending_read_error_ = kNoPendingResult;
1451 } else { 1477 } else {
1452 // No bytes were returned. Return the pending read error immediately. 1478 // No bytes were returned. Return the pending read error immediately.
1453 DCHECK_NE(kNoPendingReadResult, pending_read_error_); 1479 DCHECK_NE(kNoPendingResult, pending_read_error_);
1454 rv = pending_read_error_; 1480 rv = pending_read_error_;
1455 pending_read_error_ = kNoPendingReadResult; 1481 pending_read_error_ = kNoPendingResult;
1456 } 1482 }
1457 1483
1458 if (rv >= 0) { 1484 if (rv >= 0) {
1459 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, rv, 1485 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, rv,
1460 user_read_buf_->data()); 1486 user_read_buf_->data());
1461 } else if (rv != ERR_IO_PENDING) { 1487 } else if (rv != ERR_IO_PENDING) {
1462 net_log_.AddEvent( 1488 net_log_.AddEvent(
1463 NetLog::TYPE_SSL_READ_ERROR, 1489 NetLog::TYPE_SSL_READ_ERROR,
1464 CreateNetLogOpenSSLErrorCallback(rv, pending_read_ssl_error_, 1490 CreateNetLogOpenSSLErrorCallback(rv, pending_read_ssl_error_,
1465 pending_read_error_info_)); 1491 pending_read_error_info_));
1466 pending_read_ssl_error_ = SSL_ERROR_NONE; 1492 pending_read_ssl_error_ = SSL_ERROR_NONE;
1467 pending_read_error_info_ = OpenSSLErrorInfo(); 1493 pending_read_error_info_ = OpenSSLErrorInfo();
1468 } 1494 }
1469 return rv; 1495 return rv;
1470 } 1496 }
1471 1497
1472 int SSLClientSocketOpenSSL::DoPayloadWrite() { 1498 int SSLClientSocketOpenSSL::DoPayloadWrite() {
1473 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE); 1499 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
1474 int rv = SSL_write(ssl_, user_write_buf_->data(), user_write_buf_len_); 1500 int rv = SSL_write(ssl_, user_write_buf_->data(), user_write_buf_len_);
1475 1501
1476 if (rv >= 0) { 1502 if (rv >= 0) {
1477 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_SENT, rv, 1503 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_SENT, rv,
1478 user_write_buf_->data()); 1504 user_write_buf_->data());
1479 return rv; 1505 return rv;
1480 } 1506 }
1481 1507
1482 int ssl_error = SSL_get_error(ssl_, rv); 1508 int ssl_error = SSL_get_error(ssl_, rv);
1509 if (ssl_error == SSL_ERROR_WANT_PRIVATE_KEY_OPERATION)
1510 return ERR_IO_PENDING;
1483 OpenSSLErrorInfo error_info; 1511 OpenSSLErrorInfo error_info;
1484 int net_error = MapOpenSSLErrorWithDetails(ssl_error, err_tracer, 1512 int net_error = MapOpenSSLErrorWithDetails(ssl_error, err_tracer,
1485 &error_info); 1513 &error_info);
1486 1514
1487 if (net_error != ERR_IO_PENDING) { 1515 if (net_error != ERR_IO_PENDING) {
1488 net_log_.AddEvent( 1516 net_log_.AddEvent(
1489 NetLog::TYPE_SSL_WRITE_ERROR, 1517 NetLog::TYPE_SSL_WRITE_ERROR,
1490 CreateNetLogOpenSSLErrorCallback(net_error, ssl_error, error_info)); 1518 CreateNetLogOpenSSLErrorCallback(net_error, ssl_error, error_info));
1491 } 1519 }
1492 return net_error; 1520 return net_error;
1493 } 1521 }
1494 1522
1523 void SSLClientSocketOpenSSL::RunReadWriteLoops() {
1524 int rv_read = ERR_IO_PENDING;
1525 int rv_write = ERR_IO_PENDING;
1526 bool network_moved;
1527 do {
1528 if (user_read_buf_.get())
1529 rv_read = DoPayloadRead();
1530 if (user_write_buf_.get())
1531 rv_write = DoPayloadWrite();
1532 network_moved = DoTransportIO();
1533 } while (rv_read == ERR_IO_PENDING && rv_write == ERR_IO_PENDING &&
1534 (user_read_buf_.get() || user_write_buf_.get()) && network_moved);
1535
1536 // Performing the Read callback may cause |this| to be deleted. If this
1537 // happens, the Write callback should not be invoked. Guard against this by
1538 // holding a WeakPtr to |this| and ensuring it's still valid.
1539 base::WeakPtr<SSLClientSocketOpenSSL> guard(weak_factory_.GetWeakPtr());
1540 if (user_read_buf_.get() && rv_read != ERR_IO_PENDING)
1541 DoReadCallback(rv_read);
1542
1543 if (!guard.get())
1544 return;
1545
1546 if (user_write_buf_.get() && rv_write != ERR_IO_PENDING)
1547 DoWriteCallback(rv_write);
1548 }
1549
1495 int SSLClientSocketOpenSSL::BufferSend(void) { 1550 int SSLClientSocketOpenSSL::BufferSend(void) {
1496 if (transport_send_busy_) 1551 if (transport_send_busy_)
1497 return ERR_IO_PENDING; 1552 return ERR_IO_PENDING;
1498 1553
1499 size_t buffer_read_offset; 1554 size_t buffer_read_offset;
1500 uint8_t* read_buf; 1555 uint8_t* read_buf;
1501 size_t max_read; 1556 size_t max_read;
1502 int status = BIO_zero_copy_get_read_buf(transport_bio_, &read_buf, 1557 int status = BIO_zero_copy_get_read_buf(transport_bio_, &read_buf,
1503 &buffer_read_offset, &max_read); 1558 &buffer_read_offset, &max_read);
1504 DCHECK_EQ(status, 1); // Should never fail. 1559 DCHECK_EQ(status, 1); // Should never fail.
(...skipping 163 matching lines...) Expand 10 before | Expand all | Expand 10 after
1668 } 1723 }
1669 1724
1670 ScopedX509Stack chain = OSCertHandlesToOpenSSL( 1725 ScopedX509Stack chain = OSCertHandlesToOpenSSL(
1671 ssl_config_.client_cert->GetIntermediateCertificates()); 1726 ssl_config_.client_cert->GetIntermediateCertificates());
1672 if (!chain) { 1727 if (!chain) {
1673 LOG(WARNING) << "Failed to import intermediate certificates"; 1728 LOG(WARNING) << "Failed to import intermediate certificates";
1674 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT); 1729 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT);
1675 return -1; 1730 return -1;
1676 } 1731 }
1677 1732
1678 // TODO(davidben): With Linux client auth support, this should be 1733 if (!SSL_use_certificate(ssl_, leaf_x509.get()) ||
1679 // conditioned on OS_ANDROID and then, with https://crbug.com/394131, 1734 !SSL_set1_chain(ssl_, chain.get())) {
1680 // removed altogether. OpenSSLClientKeyStore is mostly an artifact of the 1735 LOG(WARNING) << "Failed to set client certificate";
1681 // net/ client auth API lacking a private key handle. 1736 return -1;
1737 }
1738
1682 #if defined(USE_OPENSSL_CERTS) 1739 #if defined(USE_OPENSSL_CERTS)
1683 crypto::ScopedEVP_PKEY privkey = 1740 crypto::ScopedEVP_PKEY privkey =
1684 OpenSSLClientKeyStore::GetInstance()->FetchClientCertPrivateKey( 1741 OpenSSLClientKeyStore::GetInstance()->FetchClientCertPrivateKey(
1685 ssl_config_.client_cert.get()); 1742 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) { 1743 if (!privkey) {
1691 // Could not find the private key. Fail the handshake and surface an 1744 // Could not find the private key. Fail the handshake and surface an
1692 // appropriate error to the caller. 1745 // appropriate error to the caller.
1693 LOG(WARNING) << "Client cert found without private key"; 1746 LOG(WARNING) << "Client cert found without private key";
1694 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY); 1747 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY);
1695 return -1; 1748 return -1;
1696 } 1749 }
1750 if (!SSL_use_PrivateKey(ssl_, privkey.get())) {
1751 LOG(WARNING) << "Failed to set private key";
1752 return -1;
1753 }
1754 #else // !USE_OPENSSL_CERTS
1755 // TODO(davidben): Move Android to the SSLPrivateKey codepath and disable
1756 // client auth on NaCl altogether.
1757 //
1758 // TODO(davidben): Lift this call up to the embedder so we can actually test
1759 // this code. https://crbug.com/394131
1760 private_key_ = FetchClientCertPrivateKey(
1761 ssl_config_.client_cert.get(),
1762 base::WorkerPool::GetTaskRunner(true /* task_is_slow */));
1763 if (!private_key_) {
1764 // Could not find the private key. Fail the handshake and surface an
1765 // appropriate error to the caller.
1766 LOG(WARNING) << "Client cert found without private key";
1767 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY);
1768 return -1;
1769 }
1697 1770
1698 if (!SSL_use_certificate(ssl_, leaf_x509.get()) || 1771 static const SSL_PRIVATE_KEY_METHOD kPrivateKeyMethod = {
1699 !SSL_use_PrivateKey(ssl_, privkey.get()) || 1772 &SSLClientSocketOpenSSL::PrivateKeyTypeCallback,
1700 !SSL_set1_chain(ssl_, chain.get())) { 1773 &SSLClientSocketOpenSSL::PrivateKeySupportsDigestCallback,
1701 LOG(WARNING) << "Failed to set client certificate"; 1774 &SSLClientSocketOpenSSL::PrivateKeyMaxSignatureLenCallback,
1702 return -1; 1775 &SSLClientSocketOpenSSL::PrivateKeySignCallback,
1703 } 1776 &SSLClientSocketOpenSSL::PrivateKeySignCompleteCallback,
1777 };
1778 SSL_set_private_key_method(ssl_, &kPrivateKeyMethod);
1779 #endif // USE_OPENSSL_CERTS
1704 1780
1705 int cert_count = 1 + sk_X509_num(chain.get()); 1781 int cert_count = 1 + sk_X509_num(chain.get());
1706 net_log_.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED, 1782 net_log_.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED,
1707 NetLog::IntegerCallback("cert_count", cert_count)); 1783 NetLog::IntegerCallback("cert_count", cert_count));
1708 return 1; 1784 return 1;
1709 } 1785 }
1710 #endif // defined(OS_IOS) 1786 #endif // defined(OS_IOS)
1711 1787
1712 // Send no client certificate. 1788 // Send no client certificate.
1713 net_log_.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED, 1789 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; 1991 return ssl_config_.renego_allowed_default;
1916 1992
1917 NextProto next_proto = NextProtoFromString(npn_proto_); 1993 NextProto next_proto = NextProtoFromString(npn_proto_);
1918 for (NextProto allowed : ssl_config_.renego_allowed_for_protos) { 1994 for (NextProto allowed : ssl_config_.renego_allowed_for_protos) {
1919 if (next_proto == allowed) 1995 if (next_proto == allowed)
1920 return true; 1996 return true;
1921 } 1997 }
1922 return false; 1998 return false;
1923 } 1999 }
1924 2000
2001 // static
2002 int SSLClientSocketOpenSSL::PrivateKeyTypeCallback(SSL* ssl) {
2003 SSLClientSocketOpenSSL* socket =
2004 SSLContext::GetInstance()->GetClientSocketFromSSL(ssl);
2005
2006 switch (socket->private_key_->GetType()) {
2007 case SSLPrivateKey::Type::RSA:
2008 return EVP_PKEY_RSA;
2009 case SSLPrivateKey::Type::ECDSA:
2010 return EVP_PKEY_EC;
2011 default:
2012 NOTREACHED();
2013 return EVP_PKEY_NONE;
Ryan Sleevi 2015/06/12 23:37:19 remove the default, and move the return outside th
davidben 2015/06/15 21:28:24 Done.
2014 }
2015 }
2016
2017 // static
2018 int SSLClientSocketOpenSSL::PrivateKeySupportsDigestCallback(SSL* ssl,
2019 const EVP_MD* md) {
2020 SSLClientSocketOpenSSL* socket =
2021 SSLContext::GetInstance()->GetClientSocketFromSSL(ssl);
2022
2023 SSLPrivateKey::Hash hash;
2024 return EVP_MDToPrivateKeyHash(md, &hash) &&
2025 socket->private_key_->SupportsHash(hash);
2026 }
2027
2028 // static
2029 size_t SSLClientSocketOpenSSL::PrivateKeyMaxSignatureLenCallback(SSL* ssl) {
2030 SSLClientSocketOpenSSL* socket =
2031 SSLContext::GetInstance()->GetClientSocketFromSSL(ssl);
2032
2033 return socket->private_key_->GetMaxSignatureLength();
2034 }
2035
2036 // static
2037 ssl_private_key_result_t SSLClientSocketOpenSSL::PrivateKeySignCallback(
2038 SSL* ssl,
2039 uint8_t* out,
2040 size_t* out_len,
2041 size_t max_out,
2042 const EVP_MD* md,
2043 const uint8_t* in,
2044 size_t in_len) {
2045 SSLClientSocketOpenSSL* socket =
2046 SSLContext::GetInstance()->GetClientSocketFromSSL(ssl);
2047
2048 DCHECK_EQ(kNoPendingResult, socket->signature_result_);
2049 DCHECK(socket->signature_.empty());
2050 DCHECK(socket->private_key_);
2051
2052 socket->net_log_.BeginEvent(NetLog::TYPE_SSL_PRIVATE_KEY_OPERATION);
2053
2054 SSLPrivateKey::Hash hash;
2055 if (!EVP_MDToPrivateKeyHash(md, &hash)) {
2056 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED);
2057 return ssl_private_key_failure;
2058 }
2059
2060 socket->signature_result_ = ERR_IO_PENDING;
2061 socket->private_key_->SignDigest(
2062 hash, base::StringPiece(reinterpret_cast<const char*>(in), in_len),
2063 base::Bind(&SSLClientSocketOpenSSL::OnPrivateKeySignComplete,
2064 socket->weak_factory_.GetWeakPtr()));
2065 return ssl_private_key_retry;
2066 }
2067
2068 // static
2069 ssl_private_key_result_t SSLClientSocketOpenSSL::PrivateKeySignCompleteCallback(
2070 SSL* ssl,
2071 uint8_t* out,
2072 size_t* out_len,
2073 size_t max_out) {
2074 SSLClientSocketOpenSSL* socket =
2075 SSLContext::GetInstance()->GetClientSocketFromSSL(ssl);
2076
2077 DCHECK_NE(kNoPendingResult, socket->signature_result_);
2078 DCHECK(socket->private_key_);
2079
2080 if (socket->signature_result_ == ERR_IO_PENDING)
2081 return ssl_private_key_retry;
2082 if (socket->signature_result_ != OK) {
2083 OpenSSLPutNetError(FROM_HERE, socket->signature_result_);
2084 return ssl_private_key_failure;
2085 }
2086 if (socket->signature_.size() > max_out) {
2087 LOG(ERROR) << "Buffer too small";
2088 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED);
2089 return ssl_private_key_failure;
2090 }
2091 memcpy(out, vector_as_array(&socket->signature_), socket->signature_.size());
2092 *out_len = socket->signature_.size();
2093 socket->signature_.clear();
2094 return ssl_private_key_success;
2095 }
2096
2097 void SSLClientSocketOpenSSL::OnPrivateKeySignComplete(
2098 Error error,
2099 const std::vector<uint8_t>& signature) {
2100 DCHECK_EQ(ERR_IO_PENDING, signature_result_);
2101 DCHECK(signature_.empty());
2102 DCHECK(private_key_);
2103
2104 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_PRIVATE_KEY_OPERATION,
2105 error);
2106
2107 signature_result_ = error;
2108 if (signature_result_ == OK)
2109 signature_ = signature;
2110
2111 if (next_handshake_state_ == STATE_HANDSHAKE) {
2112 OnHandshakeIOComplete(signature_result_);
2113 return;
2114 }
2115
2116 // Either Read or Write may be blocked on an asynchronous private
2117 // key operation during a renegotiation.
2118 RunReadWriteLoops();
2119 }
2120
1925 scoped_refptr<X509Certificate> 2121 scoped_refptr<X509Certificate>
1926 SSLClientSocketOpenSSL::GetUnverifiedServerCertificateChain() const { 2122 SSLClientSocketOpenSSL::GetUnverifiedServerCertificateChain() const {
1927 return server_cert_; 2123 return server_cert_;
1928 } 2124 }
1929 2125
1930 } // namespace net 2126 } // namespace net
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698