roll skia to 4276
[chromium-blink-merge.git] / net / socket / ssl_client_socket_win.cc
blobce24192b2f43cc11354fe5176d17b7fa8a60e156
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
3 // found in the LICENSE file.
5 #include "net/socket/ssl_client_socket_win.h"
7 #include <schnlsp.h>
9 #include <algorithm>
10 #include <map>
12 #include "base/bind.h"
13 #include "base/compiler_specific.h"
14 #include "base/lazy_instance.h"
15 #include "base/stl_util.h"
16 #include "base/string_util.h"
17 #include "base/synchronization/lock.h"
18 #include "base/utf_string_conversions.h"
19 #include "net/base/cert_verifier.h"
20 #include "net/base/connection_type_histograms.h"
21 #include "net/base/host_port_pair.h"
22 #include "net/base/io_buffer.h"
23 #include "net/base/net_log.h"
24 #include "net/base/net_errors.h"
25 #include "net/base/single_request_cert_verifier.h"
26 #include "net/base/ssl_cert_request_info.h"
27 #include "net/base/ssl_connection_status_flags.h"
28 #include "net/base/ssl_info.h"
29 #include "net/base/x509_certificate_net_log_param.h"
30 #include "net/socket/client_socket_handle.h"
32 #pragma comment(lib, "secur32.lib")
34 namespace net {
36 //-----------------------------------------------------------------------------
38 // TODO(wtc): See http://msdn.microsoft.com/en-us/library/aa377188(VS.85).aspx
39 // for the other error codes we may need to map.
40 static int MapSecurityError(SECURITY_STATUS err) {
41 // There are numerous security error codes, but these are the ones we thus
42 // far find interesting.
43 switch (err) {
44 case SEC_E_WRONG_PRINCIPAL: // Schannel - server certificate error.
45 case CERT_E_CN_NO_MATCH: // CryptoAPI
46 return ERR_CERT_COMMON_NAME_INVALID;
47 case SEC_E_UNTRUSTED_ROOT: // Schannel - server certificate error or
48 // unknown_ca alert.
49 case CERT_E_UNTRUSTEDROOT: // CryptoAPI
50 return ERR_CERT_AUTHORITY_INVALID;
51 case SEC_E_CERT_EXPIRED: // Schannel - server certificate error or
52 // certificate_expired alert.
53 case CERT_E_EXPIRED: // CryptoAPI
54 return ERR_CERT_DATE_INVALID;
55 case CRYPT_E_NO_REVOCATION_CHECK:
56 return ERR_CERT_NO_REVOCATION_MECHANISM;
57 case CRYPT_E_REVOCATION_OFFLINE:
58 return ERR_CERT_UNABLE_TO_CHECK_REVOCATION;
59 case CRYPT_E_REVOKED: // CryptoAPI and Schannel server certificate error,
60 // or certificate_revoked alert.
61 return ERR_CERT_REVOKED;
63 // We received one of the following alert messages from the server:
64 // bad_certificate
65 // unsupported_certificate
66 // certificate_unknown
67 case SEC_E_CERT_UNKNOWN:
68 case CERT_E_ROLE:
69 return ERR_CERT_INVALID;
71 // We received one of the following alert messages from the server:
72 // decode_error
73 // export_restriction
74 // handshake_failure
75 // illegal_parameter
76 // record_overflow
77 // unexpected_message
78 // and all other TLS alerts not explicitly specified elsewhere.
79 case SEC_E_ILLEGAL_MESSAGE:
80 // We received one of the following alert messages from the server:
81 // decrypt_error
82 // decryption_failed
83 case SEC_E_DECRYPT_FAILURE:
84 // We received one of the following alert messages from the server:
85 // bad_record_mac
86 // decompression_failure
87 case SEC_E_MESSAGE_ALTERED:
88 // TODO(rsleevi): Add SEC_E_INTERNAL_ERROR, which corresponds to an
89 // internal_error alert message being received. However, it is also used
90 // by Schannel for authentication errors that happen locally, so it has
91 // been omitted to prevent masking them as protocol errors.
92 return ERR_SSL_PROTOCOL_ERROR;
94 case SEC_E_LOGON_DENIED: // Received a access_denied alert.
95 return ERR_BAD_SSL_CLIENT_AUTH_CERT;
97 case SEC_E_UNSUPPORTED_FUNCTION: // Received a protocol_version alert.
98 case SEC_E_ALGORITHM_MISMATCH: // Received an insufficient_security alert.
99 return ERR_SSL_VERSION_OR_CIPHER_MISMATCH;
101 case SEC_E_NO_CREDENTIALS:
102 return ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY;
103 case SEC_E_INVALID_HANDLE:
104 case SEC_E_INVALID_TOKEN:
105 LOG(ERROR) << "Unexpected error " << err;
106 return ERR_UNEXPECTED;
107 case SEC_E_OK:
108 return OK;
109 default:
110 LOG(WARNING) << "Unknown error " << err << " mapped to net::ERR_FAILED";
111 return ERR_FAILED;
115 //-----------------------------------------------------------------------------
117 // A bitmask consisting of these bit flags encodes which versions of the SSL
118 // protocol (SSL 3.0 and TLS 1.0) are enabled.
119 // TODO(wtc): support TLS 1.1 and TLS 1.2 on Windows Vista and later.
120 enum {
121 SSL3 = 1 << 0,
122 TLS1 = 1 << 1,
123 SSL_VERSION_MASKS = 1 << 2 // The number of SSL version bitmasks.
126 // CredHandleClass simply gives a default constructor and a destructor to
127 // SSPI's CredHandle type (a C struct).
128 class CredHandleClass : public CredHandle {
129 public:
130 CredHandleClass() {
131 SecInvalidateHandle(this);
134 ~CredHandleClass() {
135 if (SecIsValidHandle(this)) {
136 SECURITY_STATUS status = FreeCredentialsHandle(this);
137 DCHECK(status == SEC_E_OK);
142 // A table of CredHandles.
143 class CredHandleTable {
144 public:
145 CredHandleTable() {}
147 ~CredHandleTable() {
148 STLDeleteContainerPairSecondPointers(client_cert_creds_.begin(),
149 client_cert_creds_.end());
152 int GetHandle(PCCERT_CONTEXT client_cert,
153 int ssl_version_mask,
154 CredHandle** handle_ptr) {
155 DCHECK(0 < ssl_version_mask &&
156 ssl_version_mask < arraysize(anonymous_creds_));
157 CredHandleClass* handle;
158 base::AutoLock lock(lock_);
159 if (client_cert) {
160 CredHandleMapKey key = std::make_pair(client_cert, ssl_version_mask);
161 CredHandleMap::const_iterator it = client_cert_creds_.find(key);
162 if (it == client_cert_creds_.end()) {
163 handle = new CredHandleClass;
164 client_cert_creds_[key] = handle;
165 } else {
166 handle = it->second;
168 } else {
169 handle = &anonymous_creds_[ssl_version_mask];
171 if (!SecIsValidHandle(handle)) {
172 int result = InitializeHandle(handle, client_cert, ssl_version_mask);
173 if (result != OK)
174 return result;
176 *handle_ptr = handle;
177 return OK;
180 private:
181 // CredHandleMapKey is a std::pair consisting of these two components:
182 // PCCERT_CONTEXT client_cert
183 // int ssl_version_mask
184 typedef std::pair<PCCERT_CONTEXT, int> CredHandleMapKey;
186 typedef std::map<CredHandleMapKey, CredHandleClass*> CredHandleMap;
188 // Returns OK on success or a network error code on failure.
189 static int InitializeHandle(CredHandle* handle,
190 PCCERT_CONTEXT client_cert,
191 int ssl_version_mask);
193 base::Lock lock_;
195 // Anonymous (no client certificate) CredHandles for all possible
196 // combinations of SSL versions. Defined as an array for fast lookup.
197 CredHandleClass anonymous_creds_[SSL_VERSION_MASKS];
199 // CredHandles that use a client certificate.
200 CredHandleMap client_cert_creds_;
203 static base::LazyInstance<CredHandleTable> g_cred_handle_table =
204 LAZY_INSTANCE_INITIALIZER;
206 // static
207 int CredHandleTable::InitializeHandle(CredHandle* handle,
208 PCCERT_CONTEXT client_cert,
209 int ssl_version_mask) {
210 SCHANNEL_CRED schannel_cred = {0};
211 schannel_cred.dwVersion = SCHANNEL_CRED_VERSION;
212 if (client_cert) {
213 schannel_cred.cCreds = 1;
214 schannel_cred.paCred = &client_cert;
215 // Schannel will make its own copy of client_cert.
218 // The global system registry settings take precedence over the value of
219 // schannel_cred.grbitEnabledProtocols.
220 schannel_cred.grbitEnabledProtocols = 0;
221 if (ssl_version_mask & SSL3)
222 schannel_cred.grbitEnabledProtocols |= SP_PROT_SSL3;
223 if (ssl_version_mask & TLS1)
224 schannel_cred.grbitEnabledProtocols |= SP_PROT_TLS1;
226 // The default session lifetime is 36000000 milliseconds (ten hours). Set
227 // schannel_cred.dwSessionLifespan to change the number of milliseconds that
228 // Schannel keeps the session in its session cache.
230 // We can set the key exchange algorithms (RSA or DH) in
231 // schannel_cred.{cSupportedAlgs,palgSupportedAlgs}.
233 // Although SCH_CRED_AUTO_CRED_VALIDATION is convenient, we have to use
234 // SCH_CRED_MANUAL_CRED_VALIDATION for three reasons.
235 // 1. SCH_CRED_AUTO_CRED_VALIDATION doesn't allow us to get the certificate
236 // context if the certificate validation fails.
237 // 2. SCH_CRED_AUTO_CRED_VALIDATION returns only one error even if the
238 // certificate has multiple errors.
239 // 3. SCH_CRED_AUTO_CRED_VALIDATION doesn't allow us to ignore untrusted CA
240 // and expired certificate errors. There are only flags to ignore the
241 // name mismatch and unable-to-check-revocation errors.
243 // We specify SCH_CRED_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT to cause the TLS
244 // certificate status request extension (commonly known as OCSP stapling)
245 // to be sent on Vista or later. This flag matches the
246 // CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT flag that we pass to the
247 // CertGetCertificateChain calls. Note: we specify this flag even when
248 // revocation checking is disabled to avoid doubling the number of
249 // credentials handles we need to acquire.
251 // TODO(wtc): Look into undocumented or poorly documented flags:
252 // SCH_CRED_RESTRICTED_ROOTS
253 // SCH_CRED_REVOCATION_CHECK_CACHE_ONLY
254 // SCH_CRED_CACHE_ONLY_URL_RETRIEVAL
255 // SCH_CRED_MEMORY_STORE_CERT
256 schannel_cred.dwFlags |= SCH_CRED_NO_DEFAULT_CREDS |
257 SCH_CRED_MANUAL_CRED_VALIDATION |
258 SCH_CRED_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT;
259 TimeStamp expiry;
260 SECURITY_STATUS status;
262 status = AcquireCredentialsHandle(
263 NULL, // Not used
264 UNISP_NAME, // Microsoft Unified Security Protocol Provider
265 SECPKG_CRED_OUTBOUND,
266 NULL, // Not used
267 &schannel_cred,
268 NULL, // Not used
269 NULL, // Not used
270 handle,
271 &expiry); // Optional
272 if (status != SEC_E_OK)
273 LOG(ERROR) << "AcquireCredentialsHandle failed: " << status;
274 return MapSecurityError(status);
277 // For the SSL sockets to share SSL sessions by session resumption handshakes,
278 // they need to use the same CredHandle. The GetCredHandle function creates
279 // and stores a shared CredHandle in *handle_ptr. On success, GetCredHandle
280 // returns OK. On failure, GetCredHandle returns a network error code and
281 // leaves *handle_ptr unchanged.
283 // The versions of the SSL protocol enabled are a property of the CredHandle.
284 // So we need a separate CredHandle for each combination of SSL versions.
285 // Most of the time Chromium will use only one or two combinations of SSL
286 // versions (for example, SSL3 | TLS1 for normal use, plus SSL3 when visiting
287 // TLS-intolerant servers). These CredHandles are initialized only when
288 // needed.
290 static int GetCredHandle(PCCERT_CONTEXT client_cert,
291 int ssl_version_mask,
292 CredHandle** handle_ptr) {
293 if (ssl_version_mask <= 0 || ssl_version_mask >= SSL_VERSION_MASKS) {
294 NOTREACHED();
295 return ERR_UNEXPECTED;
297 return g_cred_handle_table.Get().GetHandle(client_cert,
298 ssl_version_mask,
299 handle_ptr);
302 //-----------------------------------------------------------------------------
304 // This callback is intended to be used with CertFindChainInStore. In addition
305 // to filtering by extended/enhanced key usage, we do not show expired
306 // certificates and require digital signature usage in the key usage
307 // extension.
309 // This matches our behavior on Mac OS X and that of NSS. It also matches the
310 // default behavior of IE8. See http://support.microsoft.com/kb/890326 and
311 // http://blogs.msdn.com/b/askie/archive/2009/06/09/my-expired-client-certificates-no-longer-display-when-connecting-to-my-web-server-using-ie8.aspx
312 static BOOL WINAPI ClientCertFindCallback(PCCERT_CONTEXT cert_context,
313 void* find_arg) {
314 // Verify the certificate's KU is good.
315 BYTE key_usage;
316 if (CertGetIntendedKeyUsage(X509_ASN_ENCODING, cert_context->pCertInfo,
317 &key_usage, 1)) {
318 if (!(key_usage & CERT_DIGITAL_SIGNATURE_KEY_USAGE))
319 return FALSE;
320 } else {
321 DWORD err = GetLastError();
322 // If |err| is non-zero, it's an actual error. Otherwise the extension
323 // just isn't present, and we treat it as if everything was allowed.
324 if (err) {
325 DLOG(ERROR) << "CertGetIntendedKeyUsage failed: " << err;
326 return FALSE;
330 // Verify the current time is within the certificate's validity period.
331 if (CertVerifyTimeValidity(NULL, cert_context->pCertInfo) != 0)
332 return FALSE;
334 // Verify private key metadata is associated with this certificate.
335 DWORD size = 0;
336 if (!CertGetCertificateContextProperty(
337 cert_context, CERT_KEY_PROV_INFO_PROP_ID, NULL, &size)) {
338 return FALSE;
341 return TRUE;
344 static bool IsCertificateChainIdentical(const X509Certificate* a,
345 const X509Certificate* b) {
346 DCHECK(a);
347 DCHECK(b);
348 const X509Certificate::OSCertHandles& a_intermediates =
349 a->GetIntermediateCertificates();
350 const X509Certificate::OSCertHandles& b_intermediates =
351 b->GetIntermediateCertificates();
352 if (a_intermediates.size() != b_intermediates.size() || !a->Equals(b))
353 return false;
354 for (size_t i = 0; i < a_intermediates.size(); ++i) {
355 if (!X509Certificate::IsSameOSCert(a_intermediates[i], b_intermediates[i]))
356 return false;
358 return true;
361 //-----------------------------------------------------------------------------
363 // Size of recv_buffer_
365 // Ciphertext is decrypted one SSL record at a time, so recv_buffer_ needs to
366 // have room for a full SSL record, with the header and trailer. Here is the
367 // breakdown of the size:
368 // 5: SSL record header
369 // 16K: SSL record maximum size
370 // 64: >= SSL record trailer (16 or 20 have been observed)
371 static const int kRecvBufferSize = (5 + 16*1024 + 64);
373 SSLClientSocketWin::SSLClientSocketWin(ClientSocketHandle* transport_socket,
374 const HostPortPair& host_and_port,
375 const SSLConfig& ssl_config,
376 const SSLClientSocketContext& context)
377 : transport_(transport_socket),
378 host_and_port_(host_and_port),
379 ssl_config_(ssl_config),
380 user_read_buf_len_(0),
381 user_write_buf_len_(0),
382 next_state_(STATE_NONE),
383 cert_verifier_(context.cert_verifier),
384 creds_(NULL),
385 isc_status_(SEC_E_OK),
386 payload_send_buffer_len_(0),
387 bytes_sent_(0),
388 decrypted_ptr_(NULL),
389 bytes_decrypted_(0),
390 received_ptr_(NULL),
391 bytes_received_(0),
392 writing_first_token_(false),
393 ignore_ok_result_(false),
394 renegotiating_(false),
395 need_more_data_(false),
396 net_log_(transport_socket->socket()->NetLog()) {
397 memset(&stream_sizes_, 0, sizeof(stream_sizes_));
398 memset(in_buffers_, 0, sizeof(in_buffers_));
399 memset(&send_buffer_, 0, sizeof(send_buffer_));
400 memset(&ctxt_, 0, sizeof(ctxt_));
403 SSLClientSocketWin::~SSLClientSocketWin() {
404 Disconnect();
407 void SSLClientSocketWin::GetSSLInfo(SSLInfo* ssl_info) {
408 ssl_info->Reset();
409 if (!server_cert_)
410 return;
412 ssl_info->cert = server_cert_verify_result_.verified_cert;
413 ssl_info->cert_status = server_cert_verify_result_.cert_status;
414 ssl_info->public_key_hashes = server_cert_verify_result_.public_key_hashes;
415 ssl_info->is_issued_by_known_root =
416 server_cert_verify_result_.is_issued_by_known_root;
417 ssl_info->client_cert_sent = WasDomainBoundCertSent() ||
418 (ssl_config_.send_client_cert && ssl_config_.client_cert);
419 SecPkgContext_ConnectionInfo connection_info;
420 SECURITY_STATUS status = QueryContextAttributes(
421 &ctxt_, SECPKG_ATTR_CONNECTION_INFO, &connection_info);
422 if (status == SEC_E_OK) {
423 // TODO(wtc): compute the overall security strength, taking into account
424 // dwExchStrength and dwHashStrength. dwExchStrength needs to be
425 // normalized.
426 ssl_info->security_bits = connection_info.dwCipherStrength;
427 // TODO(wtc): connection_info.dwProtocol is the negotiated version.
428 // Save it in ssl_info->connection_status.
430 // SecPkgContext_CipherInfo comes from CNG and is available on Vista or
431 // later only. On XP, the next QueryContextAttributes call fails with
432 // SEC_E_UNSUPPORTED_FUNCTION (0x80090302), so ssl_info->connection_status
433 // won't contain the cipher suite. If this is a problem, we can build the
434 // cipher suite from the aiCipher, aiHash, and aiExch fields of
435 // SecPkgContext_ConnectionInfo based on Appendix C of RFC 5246.
436 SecPkgContext_CipherInfo cipher_info = { SECPKGCONTEXT_CIPHERINFO_V1 };
437 status = QueryContextAttributes(
438 &ctxt_, SECPKG_ATTR_CIPHER_INFO, &cipher_info);
439 if (status == SEC_E_OK) {
440 // TODO(wtc): find out what the cipher_info.dwBaseCipherSuite field is.
441 ssl_info->connection_status |=
442 (cipher_info.dwCipherSuite & SSL_CONNECTION_CIPHERSUITE_MASK) <<
443 SSL_CONNECTION_CIPHERSUITE_SHIFT;
444 // SChannel doesn't support TLS compression, so cipher_info doesn't have
445 // any field related to the compression method.
448 if (ssl_config_.version_fallback)
449 ssl_info->connection_status |= SSL_CONNECTION_VERSION_FALLBACK;
452 void SSLClientSocketWin::GetSSLCertRequestInfo(
453 SSLCertRequestInfo* cert_request_info) {
454 cert_request_info->host_and_port = host_and_port_.ToString();
455 cert_request_info->client_certs.clear();
457 // Get the certificate_authorities field of the CertificateRequest message.
458 // Schannel doesn't return the certificate_types field of the
459 // CertificateRequest message to us, so we can't filter the client
460 // certificates properly. :-(
461 SecPkgContext_IssuerListInfoEx issuer_list;
462 SECURITY_STATUS status = QueryContextAttributes(
463 &ctxt_, SECPKG_ATTR_ISSUER_LIST_EX, &issuer_list);
464 if (status != SEC_E_OK) {
465 DLOG(ERROR) << "QueryContextAttributes (issuer list) failed: " << status;
466 return;
469 // Client certificates of the user are in the "MY" system certificate store.
470 HCERTSTORE my_cert_store = CertOpenSystemStore(NULL, L"MY");
471 if (!my_cert_store) {
472 LOG(ERROR) << "Could not open the \"MY\" system certificate store: "
473 << GetLastError();
474 FreeContextBuffer(issuer_list.aIssuers);
475 return;
478 // Enumerate the client certificates.
479 CERT_CHAIN_FIND_BY_ISSUER_PARA find_by_issuer_para;
480 memset(&find_by_issuer_para, 0, sizeof(find_by_issuer_para));
481 find_by_issuer_para.cbSize = sizeof(find_by_issuer_para);
482 find_by_issuer_para.pszUsageIdentifier = szOID_PKIX_KP_CLIENT_AUTH;
483 find_by_issuer_para.cIssuer = issuer_list.cIssuers;
484 find_by_issuer_para.rgIssuer = issuer_list.aIssuers;
485 find_by_issuer_para.pfnFindCallback = ClientCertFindCallback;
487 PCCERT_CHAIN_CONTEXT chain_context = NULL;
488 DWORD find_flags = CERT_CHAIN_FIND_BY_ISSUER_CACHE_ONLY_FLAG |
489 CERT_CHAIN_FIND_BY_ISSUER_CACHE_ONLY_URL_FLAG;
491 for (;;) {
492 // Find a certificate chain.
493 chain_context = CertFindChainInStore(my_cert_store,
494 X509_ASN_ENCODING,
495 find_flags,
496 CERT_CHAIN_FIND_BY_ISSUER,
497 &find_by_issuer_para,
498 chain_context);
499 if (!chain_context) {
500 DWORD err = GetLastError();
501 if (err != CRYPT_E_NOT_FOUND)
502 DLOG(ERROR) << "CertFindChainInStore failed: " << err;
503 break;
506 // Get the leaf certificate.
507 PCCERT_CONTEXT cert_context =
508 chain_context->rgpChain[0]->rgpElement[0]->pCertContext;
509 // Copy the certificate into a NULL store, so that the "MY" store can be
510 // closed before returning from this function.
511 PCCERT_CONTEXT cert_context2 = NULL;
512 BOOL ok = CertAddCertificateContextToStore(NULL, cert_context,
513 CERT_STORE_ADD_USE_EXISTING,
514 &cert_context2);
515 if (!ok) {
516 NOTREACHED();
517 continue;
520 // Grab the intermediates, if any.
521 X509Certificate::OSCertHandles intermediates;
522 for (DWORD i = 1; i < chain_context->rgpChain[0]->cElement; ++i) {
523 PCCERT_CONTEXT chain_intermediate =
524 chain_context->rgpChain[0]->rgpElement[i]->pCertContext;
525 PCCERT_CONTEXT copied_intermediate = NULL;
526 ok = CertAddCertificateContextToStore(NULL, chain_intermediate,
527 CERT_STORE_ADD_USE_EXISTING,
528 &copied_intermediate);
529 if (ok)
530 intermediates.push_back(copied_intermediate);
532 scoped_refptr<X509Certificate> cert = X509Certificate::CreateFromHandle(
533 cert_context2, intermediates);
534 cert_request_info->client_certs.push_back(cert);
535 CertFreeCertificateContext(cert_context2);
536 for (size_t i = 0; i < intermediates.size(); ++i)
537 CertFreeCertificateContext(intermediates[i]);
540 FreeContextBuffer(issuer_list.aIssuers);
542 BOOL ok = CertCloseStore(my_cert_store, CERT_CLOSE_STORE_CHECK_FLAG);
543 DCHECK(ok);
546 int SSLClientSocketWin::ExportKeyingMaterial(const base::StringPiece& label,
547 bool has_context,
548 const base::StringPiece& context,
549 unsigned char* out,
550 unsigned int outlen) {
551 return ERR_NOT_IMPLEMENTED;
554 SSLClientSocket::NextProtoStatus
555 SSLClientSocketWin::GetNextProto(std::string* proto,
556 std::string* server_protos) {
557 proto->clear();
558 server_protos->clear();
559 return kNextProtoUnsupported;
562 ServerBoundCertService* SSLClientSocketWin::GetServerBoundCertService() const {
563 return NULL;
566 int SSLClientSocketWin::Connect(const CompletionCallback& callback) {
567 DCHECK(transport_.get());
568 DCHECK(next_state_ == STATE_NONE);
569 DCHECK(user_connect_callback_.is_null());
571 net_log_.BeginEvent(NetLog::TYPE_SSL_CONNECT);
573 int rv = InitializeSSLContext();
574 if (rv != OK) {
575 net_log_.EndEvent(NetLog::TYPE_SSL_CONNECT);
576 return rv;
579 writing_first_token_ = true;
580 next_state_ = STATE_HANDSHAKE_WRITE;
581 rv = DoLoop(OK);
582 if (rv == ERR_IO_PENDING) {
583 user_connect_callback_ = callback;
584 } else {
585 net_log_.EndEvent(NetLog::TYPE_SSL_CONNECT);
587 return rv;
590 int SSLClientSocketWin::InitializeSSLContext() {
591 // If ssl_config_.version_max > SSL_PROTOCOL_VERSION_TLS1, it means the
592 // SSLConfigService::SetDefaultVersionMax(SSL_PROTOCOL_VERSION_TLS1) call
593 // in ClientSocketFactory::UseSystemSSL() is not effective.
594 DCHECK_LE(ssl_config_.version_max, SSL_PROTOCOL_VERSION_TLS1);
595 int ssl_version_mask = 0;
596 if (ssl_config_.version_min == SSL_PROTOCOL_VERSION_SSL3)
597 ssl_version_mask |= SSL3;
598 if (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1 &&
599 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1) {
600 ssl_version_mask |= TLS1;
602 // If we pass 0 to GetCredHandle, we will let Schannel select the protocols,
603 // rather than enabling no protocols. So we have to fail here.
604 if (ssl_version_mask == 0)
605 return ERR_NO_SSL_VERSIONS_ENABLED;
606 PCCERT_CONTEXT cert_context = NULL;
607 if (ssl_config_.client_cert)
608 cert_context = ssl_config_.client_cert->os_cert_handle();
609 int result = GetCredHandle(cert_context, ssl_version_mask, &creds_);
610 if (result != OK)
611 return result;
613 memset(&ctxt_, 0, sizeof(ctxt_));
615 SecBufferDesc buffer_desc;
616 DWORD out_flags;
617 DWORD flags = ISC_REQ_SEQUENCE_DETECT |
618 ISC_REQ_REPLAY_DETECT |
619 ISC_REQ_CONFIDENTIALITY |
620 ISC_RET_EXTENDED_ERROR |
621 ISC_REQ_ALLOCATE_MEMORY |
622 ISC_REQ_STREAM;
624 send_buffer_.pvBuffer = NULL;
625 send_buffer_.BufferType = SECBUFFER_TOKEN;
626 send_buffer_.cbBuffer = 0;
628 buffer_desc.cBuffers = 1;
629 buffer_desc.pBuffers = &send_buffer_;
630 buffer_desc.ulVersion = SECBUFFER_VERSION;
632 TimeStamp expiry;
633 SECURITY_STATUS status;
635 status = InitializeSecurityContext(
636 creds_,
637 NULL, // NULL on the first call
638 const_cast<wchar_t*>(ASCIIToWide(host_and_port_.host()).c_str()),
639 flags,
640 0, // Reserved
641 0, // Not used with Schannel.
642 NULL, // NULL on the first call
643 0, // Reserved
644 &ctxt_, // Receives the new context handle
645 &buffer_desc,
646 &out_flags,
647 &expiry);
648 if (status != SEC_I_CONTINUE_NEEDED) {
649 LOG(ERROR) << "InitializeSecurityContext failed: " << status;
650 if (status == SEC_E_INVALID_HANDLE) {
651 // The only handle we passed to this InitializeSecurityContext call is
652 // creds_, so print its contents to figure out why it's invalid.
653 if (creds_) {
654 LOG(ERROR) << "creds_->dwLower = " << creds_->dwLower
655 << "; creds_->dwUpper = " << creds_->dwUpper;
656 } else {
657 LOG(ERROR) << "creds_ is NULL";
660 return MapSecurityError(status);
663 return OK;
667 void SSLClientSocketWin::Disconnect() {
668 // TODO(wtc): Send SSL close_notify alert.
669 next_state_ = STATE_NONE;
671 // Shut down anything that may call us back.
672 verifier_.reset();
673 transport_->socket()->Disconnect();
675 if (send_buffer_.pvBuffer)
676 FreeSendBuffer();
677 if (SecIsValidHandle(&ctxt_)) {
678 DeleteSecurityContext(&ctxt_);
679 SecInvalidateHandle(&ctxt_);
681 if (server_cert_)
682 server_cert_ = NULL;
684 // TODO(wtc): reset more members?
685 bytes_decrypted_ = 0;
686 bytes_received_ = 0;
687 writing_first_token_ = false;
688 renegotiating_ = false;
689 need_more_data_ = false;
692 bool SSLClientSocketWin::IsConnected() const {
693 // Ideally, we should also check if we have received the close_notify alert
694 // message from the server, and return false in that case. We're not doing
695 // that, so this function may return a false positive. Since the upper
696 // layer (HttpNetworkTransaction) needs to handle a persistent connection
697 // closed by the server when we send a request anyway, a false positive in
698 // exchange for simpler code is a good trade-off.
699 return completed_handshake() && transport_->socket()->IsConnected();
702 bool SSLClientSocketWin::IsConnectedAndIdle() const {
703 // Unlike IsConnected, this method doesn't return a false positive.
705 // Strictly speaking, we should check if we have received the close_notify
706 // alert message from the server, and return false in that case. Although
707 // the close_notify alert message means EOF in the SSL layer, it is just
708 // bytes to the transport layer below, so
709 // transport_->socket()->IsConnectedAndIdle() returns the desired false
710 // when we receive close_notify.
711 return completed_handshake() && transport_->socket()->IsConnectedAndIdle();
714 int SSLClientSocketWin::GetPeerAddress(IPEndPoint* address) const {
715 return transport_->socket()->GetPeerAddress(address);
718 int SSLClientSocketWin::GetLocalAddress(IPEndPoint* address) const {
719 return transport_->socket()->GetLocalAddress(address);
722 void SSLClientSocketWin::SetSubresourceSpeculation() {
723 if (transport_.get() && transport_->socket()) {
724 transport_->socket()->SetSubresourceSpeculation();
725 } else {
726 NOTREACHED();
730 void SSLClientSocketWin::SetOmniboxSpeculation() {
731 if (transport_.get() && transport_->socket()) {
732 transport_->socket()->SetOmniboxSpeculation();
733 } else {
734 NOTREACHED();
738 bool SSLClientSocketWin::WasEverUsed() const {
739 if (transport_.get() && transport_->socket()) {
740 return transport_->socket()->WasEverUsed();
742 NOTREACHED();
743 return false;
746 bool SSLClientSocketWin::UsingTCPFastOpen() const {
747 if (transport_.get() && transport_->socket()) {
748 return transport_->socket()->UsingTCPFastOpen();
750 NOTREACHED();
751 return false;
754 int64 SSLClientSocketWin::NumBytesRead() const {
755 if (transport_.get() && transport_->socket()) {
756 return transport_->socket()->NumBytesRead();
758 NOTREACHED();
759 return -1;
762 base::TimeDelta SSLClientSocketWin::GetConnectTimeMicros() const {
763 if (transport_.get() && transport_->socket()) {
764 return transport_->socket()->GetConnectTimeMicros();
766 NOTREACHED();
767 return base::TimeDelta::FromMicroseconds(-1);
770 int SSLClientSocketWin::Read(IOBuffer* buf, int buf_len,
771 const CompletionCallback& callback) {
772 DCHECK(completed_handshake());
773 DCHECK(user_read_callback_.is_null());
775 // If we have surplus decrypted plaintext, satisfy the Read with it without
776 // reading more ciphertext from the transport socket.
777 if (bytes_decrypted_ != 0) {
778 int len = std::min(buf_len, bytes_decrypted_);
779 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, len,
780 decrypted_ptr_);
781 memcpy(buf->data(), decrypted_ptr_, len);
782 decrypted_ptr_ += len;
783 bytes_decrypted_ -= len;
784 if (bytes_decrypted_ == 0) {
785 decrypted_ptr_ = NULL;
786 if (bytes_received_ != 0) {
787 memmove(recv_buffer_.get(), received_ptr_, bytes_received_);
788 received_ptr_ = recv_buffer_.get();
791 return len;
794 DCHECK(!user_read_buf_);
795 // http://crbug.com/16371: We're seeing |buf->data()| return NULL. See if the
796 // user is passing in an IOBuffer with a NULL |data_|.
797 CHECK(buf);
798 CHECK(buf->data());
799 user_read_buf_ = buf;
800 user_read_buf_len_ = buf_len;
802 int rv = DoPayloadRead();
803 if (rv == ERR_IO_PENDING) {
804 user_read_callback_ = callback;
805 } else {
806 user_read_buf_ = NULL;
807 user_read_buf_len_ = 0;
809 return rv;
812 int SSLClientSocketWin::Write(IOBuffer* buf, int buf_len,
813 const CompletionCallback& callback) {
814 DCHECK(completed_handshake());
815 DCHECK(user_write_callback_.is_null());
817 DCHECK(!user_write_buf_);
818 user_write_buf_ = buf;
819 user_write_buf_len_ = buf_len;
821 int rv = DoPayloadEncrypt();
822 if (rv != OK)
823 return rv;
825 rv = DoPayloadWrite();
826 if (rv == ERR_IO_PENDING) {
827 user_write_callback_ = callback;
828 } else {
829 user_write_buf_ = NULL;
830 user_write_buf_len_ = 0;
832 return rv;
835 bool SSLClientSocketWin::SetReceiveBufferSize(int32 size) {
836 return transport_->socket()->SetReceiveBufferSize(size);
839 bool SSLClientSocketWin::SetSendBufferSize(int32 size) {
840 return transport_->socket()->SetSendBufferSize(size);
843 void SSLClientSocketWin::OnHandshakeIOComplete(int result) {
844 int rv = DoLoop(result);
846 // The SSL handshake has some round trips. We need to notify the caller of
847 // success or any error, other than waiting for IO.
848 if (rv != ERR_IO_PENDING) {
849 // If there is no connect callback available to call, we are renegotiating
850 // (which occurs because we are in the middle of a Read when the
851 // renegotiation process starts). So we complete the Read here.
852 if (user_connect_callback_.is_null()) {
853 CompletionCallback c = user_read_callback_;
854 user_read_callback_.Reset();
855 user_read_buf_ = NULL;
856 user_read_buf_len_ = 0;
857 c.Run(rv);
858 return;
860 net_log_.EndEvent(NetLog::TYPE_SSL_CONNECT);
861 CompletionCallback c = user_connect_callback_;
862 user_connect_callback_.Reset();
863 c.Run(rv);
867 void SSLClientSocketWin::OnReadComplete(int result) {
868 DCHECK(completed_handshake());
870 result = DoPayloadReadComplete(result);
871 if (result > 0)
872 result = DoPayloadDecrypt();
873 if (result != ERR_IO_PENDING) {
874 DCHECK(!user_read_callback_.is_null());
875 CompletionCallback c = user_read_callback_;
876 user_read_callback_.Reset();
877 user_read_buf_ = NULL;
878 user_read_buf_len_ = 0;
879 c.Run(result);
883 void SSLClientSocketWin::OnWriteComplete(int result) {
884 DCHECK(completed_handshake());
886 int rv = DoPayloadWriteComplete(result);
887 if (rv != ERR_IO_PENDING) {
888 DCHECK(!user_write_callback_.is_null());
889 CompletionCallback c = user_write_callback_;
890 user_write_callback_.Reset();
891 user_write_buf_ = NULL;
892 user_write_buf_len_ = 0;
893 c.Run(rv);
898 int SSLClientSocketWin::DoLoop(int last_io_result) {
899 DCHECK(next_state_ != STATE_NONE);
900 int rv = last_io_result;
901 do {
902 State state = next_state_;
903 next_state_ = STATE_NONE;
904 switch (state) {
905 case STATE_HANDSHAKE_READ:
906 rv = DoHandshakeRead();
907 break;
908 case STATE_HANDSHAKE_READ_COMPLETE:
909 rv = DoHandshakeReadComplete(rv);
910 break;
911 case STATE_HANDSHAKE_WRITE:
912 rv = DoHandshakeWrite();
913 break;
914 case STATE_HANDSHAKE_WRITE_COMPLETE:
915 rv = DoHandshakeWriteComplete(rv);
916 break;
917 case STATE_VERIFY_CERT:
918 rv = DoVerifyCert();
919 break;
920 case STATE_VERIFY_CERT_COMPLETE:
921 rv = DoVerifyCertComplete(rv);
922 break;
923 case STATE_COMPLETED_RENEGOTIATION:
924 rv = DoCompletedRenegotiation(rv);
925 break;
926 case STATE_COMPLETED_HANDSHAKE:
927 next_state_ = STATE_COMPLETED_HANDSHAKE;
928 // This is the end of our state machine, so return.
929 return rv;
930 default:
931 rv = ERR_UNEXPECTED;
932 LOG(DFATAL) << "unexpected state " << state;
933 break;
935 } while (rv != ERR_IO_PENDING && next_state_ != STATE_NONE);
936 return rv;
939 int SSLClientSocketWin::DoHandshakeRead() {
940 next_state_ = STATE_HANDSHAKE_READ_COMPLETE;
942 if (!recv_buffer_.get())
943 recv_buffer_.reset(new char[kRecvBufferSize]);
945 int buf_len = kRecvBufferSize - bytes_received_;
947 if (buf_len <= 0) {
948 LOG(DFATAL) << "Receive buffer is too small!";
949 return ERR_UNEXPECTED;
952 DCHECK(!transport_read_buf_);
953 transport_read_buf_ = new IOBuffer(buf_len);
955 return transport_->socket()->Read(
956 transport_read_buf_, buf_len,
957 base::Bind(&SSLClientSocketWin::OnHandshakeIOComplete,
958 base::Unretained(this)));
961 int SSLClientSocketWin::DoHandshakeReadComplete(int result) {
962 if (result < 0) {
963 transport_read_buf_ = NULL;
964 return result;
967 if (transport_read_buf_) {
968 // A transition to STATE_HANDSHAKE_READ_COMPLETE is set in multiple places,
969 // not only in DoHandshakeRead(), so we may not have a transport_read_buf_.
970 DCHECK_LE(result, kRecvBufferSize - bytes_received_);
971 char* buf = recv_buffer_.get() + bytes_received_;
972 memcpy(buf, transport_read_buf_->data(), result);
973 transport_read_buf_ = NULL;
976 if (result == 0 && !ignore_ok_result_)
977 return ERR_SSL_PROTOCOL_ERROR; // Incomplete response :(
979 ignore_ok_result_ = false;
981 bytes_received_ += result;
983 // Process the contents of recv_buffer_.
984 TimeStamp expiry;
985 DWORD out_flags;
987 DWORD flags = ISC_REQ_SEQUENCE_DETECT |
988 ISC_REQ_REPLAY_DETECT |
989 ISC_REQ_CONFIDENTIALITY |
990 ISC_RET_EXTENDED_ERROR |
991 ISC_REQ_ALLOCATE_MEMORY |
992 ISC_REQ_STREAM;
994 if (ssl_config_.send_client_cert)
995 flags |= ISC_REQ_USE_SUPPLIED_CREDS;
997 SecBufferDesc in_buffer_desc, out_buffer_desc;
999 in_buffer_desc.cBuffers = 2;
1000 in_buffer_desc.pBuffers = in_buffers_;
1001 in_buffer_desc.ulVersion = SECBUFFER_VERSION;
1003 in_buffers_[0].pvBuffer = recv_buffer_.get();
1004 in_buffers_[0].cbBuffer = bytes_received_;
1005 in_buffers_[0].BufferType = SECBUFFER_TOKEN;
1007 in_buffers_[1].pvBuffer = NULL;
1008 in_buffers_[1].cbBuffer = 0;
1009 in_buffers_[1].BufferType = SECBUFFER_EMPTY;
1011 out_buffer_desc.cBuffers = 1;
1012 out_buffer_desc.pBuffers = &send_buffer_;
1013 out_buffer_desc.ulVersion = SECBUFFER_VERSION;
1015 send_buffer_.pvBuffer = NULL;
1016 send_buffer_.BufferType = SECBUFFER_TOKEN;
1017 send_buffer_.cbBuffer = 0;
1019 isc_status_ = InitializeSecurityContext(
1020 creds_,
1021 &ctxt_,
1022 NULL,
1023 flags,
1026 &in_buffer_desc,
1028 NULL,
1029 &out_buffer_desc,
1030 &out_flags,
1031 &expiry);
1033 if (isc_status_ == SEC_E_INVALID_TOKEN) {
1034 // Peer sent us an SSL record type that's invalid during SSL handshake.
1035 // TODO(wtc): move this to MapSecurityError after sufficient testing.
1036 LOG(ERROR) << "InitializeSecurityContext failed: " << isc_status_;
1037 return ERR_SSL_PROTOCOL_ERROR;
1040 if (send_buffer_.cbBuffer != 0 &&
1041 (isc_status_ == SEC_E_OK ||
1042 isc_status_ == SEC_I_CONTINUE_NEEDED ||
1043 (FAILED(isc_status_) && (out_flags & ISC_RET_EXTENDED_ERROR)))) {
1044 next_state_ = STATE_HANDSHAKE_WRITE;
1045 return OK;
1047 return DidCallInitializeSecurityContext();
1050 int SSLClientSocketWin::DidCallInitializeSecurityContext() {
1051 if (isc_status_ == SEC_E_INCOMPLETE_MESSAGE) {
1052 next_state_ = STATE_HANDSHAKE_READ;
1053 return OK;
1056 if (isc_status_ == SEC_E_OK) {
1057 if (in_buffers_[1].BufferType == SECBUFFER_EXTRA) {
1058 // Save this data for later.
1059 memmove(recv_buffer_.get(),
1060 recv_buffer_.get() + (bytes_received_ - in_buffers_[1].cbBuffer),
1061 in_buffers_[1].cbBuffer);
1062 bytes_received_ = in_buffers_[1].cbBuffer;
1063 } else {
1064 bytes_received_ = 0;
1066 return DidCompleteHandshake();
1069 if (FAILED(isc_status_)) {
1070 LOG(ERROR) << "InitializeSecurityContext failed: " << isc_status_;
1071 if (isc_status_ == SEC_E_INTERNAL_ERROR) {
1072 // "The Local Security Authority cannot be contacted". This happens
1073 // when the user denies access to the private key for SSL client auth.
1074 return ERR_SSL_CLIENT_AUTH_PRIVATE_KEY_ACCESS_DENIED;
1076 int result = MapSecurityError(isc_status_);
1077 // We told Schannel to not verify the server certificate
1078 // (SCH_CRED_MANUAL_CRED_VALIDATION), so any certificate error returned by
1079 // InitializeSecurityContext must be referring to the bad or missing
1080 // client certificate.
1081 if (IsCertificateError(result)) {
1082 // TODO(wtc): Add fine-grained error codes for client certificate errors
1083 // reported by the server using the following SSL/TLS alert messages:
1084 // access_denied
1085 // bad_certificate
1086 // unsupported_certificate
1087 // certificate_expired
1088 // certificate_revoked
1089 // certificate_unknown
1090 // unknown_ca
1091 return ERR_BAD_SSL_CLIENT_AUTH_CERT;
1093 return result;
1096 if (isc_status_ == SEC_I_INCOMPLETE_CREDENTIALS)
1097 return ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
1099 if (isc_status_ == SEC_I_NO_RENEGOTIATION) {
1100 // Received a no_renegotiation alert message. Although this is just a
1101 // warning, SChannel doesn't seem to allow us to continue after this
1102 // point, so we have to return an error. See http://crbug.com/36835.
1103 return ERR_SSL_NO_RENEGOTIATION;
1106 DCHECK(isc_status_ == SEC_I_CONTINUE_NEEDED);
1107 if (in_buffers_[1].BufferType == SECBUFFER_EXTRA) {
1108 memmove(recv_buffer_.get(),
1109 recv_buffer_.get() + (bytes_received_ - in_buffers_[1].cbBuffer),
1110 in_buffers_[1].cbBuffer);
1111 bytes_received_ = in_buffers_[1].cbBuffer;
1112 next_state_ = STATE_HANDSHAKE_READ_COMPLETE;
1113 ignore_ok_result_ = true; // OK doesn't mean EOF.
1114 return OK;
1117 bytes_received_ = 0;
1118 next_state_ = STATE_HANDSHAKE_READ;
1119 return OK;
1122 int SSLClientSocketWin::DoHandshakeWrite() {
1123 next_state_ = STATE_HANDSHAKE_WRITE_COMPLETE;
1125 // We should have something to send.
1126 DCHECK(send_buffer_.pvBuffer);
1127 DCHECK(send_buffer_.cbBuffer > 0);
1128 DCHECK(!transport_write_buf_);
1130 const char* buf = static_cast<char*>(send_buffer_.pvBuffer) + bytes_sent_;
1131 int buf_len = send_buffer_.cbBuffer - bytes_sent_;
1132 transport_write_buf_ = new IOBuffer(buf_len);
1133 memcpy(transport_write_buf_->data(), buf, buf_len);
1135 return transport_->socket()->Write(
1136 transport_write_buf_, buf_len,
1137 base::Bind(&SSLClientSocketWin::OnHandshakeIOComplete,
1138 base::Unretained(this)));
1141 int SSLClientSocketWin::DoHandshakeWriteComplete(int result) {
1142 DCHECK(transport_write_buf_);
1143 transport_write_buf_ = NULL;
1144 if (result < 0)
1145 return result;
1147 DCHECK(result != 0);
1149 bytes_sent_ += result;
1150 DCHECK(bytes_sent_ <= static_cast<int>(send_buffer_.cbBuffer));
1152 if (bytes_sent_ >= static_cast<int>(send_buffer_.cbBuffer)) {
1153 bool overflow = (bytes_sent_ > static_cast<int>(send_buffer_.cbBuffer));
1154 FreeSendBuffer();
1155 bytes_sent_ = 0;
1156 if (overflow) { // Bug!
1157 LOG(DFATAL) << "overflow";
1158 return ERR_UNEXPECTED;
1160 if (writing_first_token_) {
1161 writing_first_token_ = false;
1162 DCHECK(bytes_received_ == 0);
1163 next_state_ = STATE_HANDSHAKE_READ;
1164 return OK;
1166 return DidCallInitializeSecurityContext();
1169 // Send the remaining bytes.
1170 next_state_ = STATE_HANDSHAKE_WRITE;
1171 return OK;
1174 // Set server_cert_status_ and return OK or a network error.
1175 int SSLClientSocketWin::DoVerifyCert() {
1176 next_state_ = STATE_VERIFY_CERT_COMPLETE;
1178 DCHECK(server_cert_);
1179 CertStatus cert_status;
1180 if (ssl_config_.IsAllowedBadCert(server_cert_, &cert_status)) {
1181 VLOG(1) << "Received an expected bad cert with status: " << cert_status;
1182 server_cert_verify_result_.Reset();
1183 server_cert_verify_result_.cert_status = cert_status;
1184 server_cert_verify_result_.verified_cert = server_cert_;
1185 return OK;
1188 int flags = 0;
1189 if (ssl_config_.rev_checking_enabled)
1190 flags |= X509Certificate::VERIFY_REV_CHECKING_ENABLED;
1191 if (ssl_config_.verify_ev_cert)
1192 flags |= X509Certificate::VERIFY_EV_CERT;
1193 if (ssl_config_.cert_io_enabled)
1194 flags |= X509Certificate::VERIFY_CERT_IO_ENABLED;
1195 verifier_.reset(new SingleRequestCertVerifier(cert_verifier_));
1196 return verifier_->Verify(
1197 server_cert_, host_and_port_.host(), flags,
1198 NULL /* no CRL set */,
1199 &server_cert_verify_result_,
1200 base::Bind(&SSLClientSocketWin::OnHandshakeIOComplete,
1201 base::Unretained(this)),
1202 net_log_);
1205 int SSLClientSocketWin::DoVerifyCertComplete(int result) {
1206 DCHECK(verifier_.get());
1207 verifier_.reset();
1209 if (result == OK)
1210 LogConnectionTypeMetrics();
1211 if (renegotiating_) {
1212 DidCompleteRenegotiation();
1213 return result;
1216 // The initial handshake has completed.
1217 next_state_ = STATE_COMPLETED_HANDSHAKE;
1218 return result;
1221 int SSLClientSocketWin::DoPayloadRead() {
1222 DCHECK(recv_buffer_.get());
1224 int buf_len = kRecvBufferSize - bytes_received_;
1226 if (buf_len <= 0) {
1227 NOTREACHED() << "Receive buffer is too small!";
1228 return ERR_FAILED;
1231 int rv;
1232 // If bytes_received_, we have some data from a previous read still ready
1233 // for decoding. Otherwise, we need to issue a real read.
1234 if (!bytes_received_ || need_more_data_) {
1235 DCHECK(!transport_read_buf_);
1236 transport_read_buf_ = new IOBuffer(buf_len);
1238 rv = transport_->socket()->Read(
1239 transport_read_buf_, buf_len,
1240 base::Bind(&SSLClientSocketWin::OnReadComplete,
1241 base::Unretained(this)));
1242 if (rv != ERR_IO_PENDING)
1243 rv = DoPayloadReadComplete(rv);
1244 if (rv <= 0)
1245 return rv;
1248 // Decode what we've read. If there is not enough data to decode yet,
1249 // this may return ERR_IO_PENDING still.
1250 return DoPayloadDecrypt();
1253 // result is the number of bytes that have been read; it should not be
1254 // less than zero; a value of zero means that no additional bytes have
1255 // been read.
1256 int SSLClientSocketWin::DoPayloadReadComplete(int result) {
1257 DCHECK(completed_handshake());
1259 // If IO Pending, there is nothing to do here.
1260 if (result == ERR_IO_PENDING)
1261 return result;
1263 // We completed a Read, so reset the need_more_data_ flag.
1264 need_more_data_ = false;
1266 // Check for error
1267 if (result <= 0) {
1268 transport_read_buf_ = NULL;
1269 if (result == 0 && bytes_received_ != 0) {
1270 // TODO(wtc): Unless we have received the close_notify alert, we need
1271 // to return an error code indicating that the SSL connection ended
1272 // uncleanly, a potential truncation attack. See
1273 // http://crbug.com/18586.
1274 return ERR_SSL_PROTOCOL_ERROR;
1276 return result;
1279 // Transfer the data from transport_read_buf_ to recv_buffer_.
1280 if (transport_read_buf_) {
1281 DCHECK_LE(result, kRecvBufferSize - bytes_received_);
1282 char* buf = recv_buffer_.get() + bytes_received_;
1283 memcpy(buf, transport_read_buf_->data(), result);
1284 transport_read_buf_ = NULL;
1287 bytes_received_ += result;
1289 return result;
1292 int SSLClientSocketWin::DoPayloadDecrypt() {
1293 // Process the contents of recv_buffer_.
1294 int len = 0; // the number of bytes we've copied to the user buffer.
1295 while (bytes_received_) {
1296 SecBuffer buffers[4];
1297 buffers[0].pvBuffer = recv_buffer_.get();
1298 buffers[0].cbBuffer = bytes_received_;
1299 buffers[0].BufferType = SECBUFFER_DATA;
1301 buffers[1].BufferType = SECBUFFER_EMPTY;
1302 buffers[2].BufferType = SECBUFFER_EMPTY;
1303 buffers[3].BufferType = SECBUFFER_EMPTY;
1305 SecBufferDesc buffer_desc;
1306 buffer_desc.cBuffers = 4;
1307 buffer_desc.pBuffers = buffers;
1308 buffer_desc.ulVersion = SECBUFFER_VERSION;
1310 SECURITY_STATUS status;
1311 status = DecryptMessage(&ctxt_, &buffer_desc, 0, NULL);
1313 if (status == SEC_E_INCOMPLETE_MESSAGE) {
1314 need_more_data_ = true;
1315 return DoPayloadRead();
1318 if (status == SEC_I_CONTEXT_EXPIRED) {
1319 // Received the close_notify alert.
1320 bytes_received_ = 0;
1321 return OK;
1324 if (status != SEC_E_OK && status != SEC_I_RENEGOTIATE) {
1325 DCHECK(status != SEC_E_MESSAGE_ALTERED);
1326 LOG(ERROR) << "DecryptMessage failed: " << status;
1327 return MapSecurityError(status);
1330 // The received ciphertext was decrypted in place in recv_buffer_. Remember
1331 // the location and length of the decrypted plaintext and any unused
1332 // ciphertext.
1333 decrypted_ptr_ = NULL;
1334 bytes_decrypted_ = 0;
1335 received_ptr_ = NULL;
1336 bytes_received_ = 0;
1337 for (int i = 1; i < 4; i++) {
1338 switch (buffers[i].BufferType) {
1339 case SECBUFFER_DATA:
1340 DCHECK(!decrypted_ptr_ && bytes_decrypted_ == 0);
1341 decrypted_ptr_ = static_cast<char*>(buffers[i].pvBuffer);
1342 bytes_decrypted_ = buffers[i].cbBuffer;
1343 break;
1344 case SECBUFFER_EXTRA:
1345 DCHECK(!received_ptr_ && bytes_received_ == 0);
1346 received_ptr_ = static_cast<char*>(buffers[i].pvBuffer);
1347 bytes_received_ = buffers[i].cbBuffer;
1348 break;
1349 default:
1350 break;
1354 DCHECK(len == 0);
1355 if (bytes_decrypted_ != 0) {
1356 len = std::min(user_read_buf_len_, bytes_decrypted_);
1357 memcpy(user_read_buf_->data(), decrypted_ptr_, len);
1358 decrypted_ptr_ += len;
1359 bytes_decrypted_ -= len;
1361 if (bytes_decrypted_ == 0) {
1362 decrypted_ptr_ = NULL;
1363 if (bytes_received_ != 0) {
1364 memmove(recv_buffer_.get(), received_ptr_, bytes_received_);
1365 received_ptr_ = recv_buffer_.get();
1369 if (status == SEC_I_RENEGOTIATE) {
1370 if (bytes_received_ != 0) {
1371 // The server requested renegotiation, but there are some data yet to
1372 // be decrypted. The Platform SDK WebClient.c sample doesn't handle
1373 // this, so we don't know how to handle this. Assume this cannot
1374 // happen.
1375 LOG(ERROR) << "DecryptMessage returned SEC_I_RENEGOTIATE with a buffer "
1376 << "of type SECBUFFER_EXTRA.";
1377 return ERR_SSL_RENEGOTIATION_REQUESTED;
1379 if (len != 0) {
1380 // The server requested renegotiation, but there are some decrypted
1381 // data. We can't start renegotiation until we have returned all
1382 // decrypted data to the caller.
1384 // This hasn't happened during testing. Assume this cannot happen even
1385 // though we know how to handle this.
1386 LOG(ERROR) << "DecryptMessage returned SEC_I_RENEGOTIATE with a buffer "
1387 << "of type SECBUFFER_DATA.";
1388 return ERR_SSL_RENEGOTIATION_REQUESTED;
1390 // Jump to the handshake sequence. Will come back when the rehandshake is
1391 // done.
1392 renegotiating_ = true;
1393 ignore_ok_result_ = true; // OK doesn't mean EOF.
1394 // If renegotiation handshake occurred, we need to go back into the
1395 // handshake state machine.
1396 next_state_ = STATE_HANDSHAKE_READ_COMPLETE;
1397 return DoLoop(OK);
1400 // We've already copied data into the user buffer, so quit now.
1401 // TODO(mbelshe): We really should keep decoding as long as we can. This
1402 // break out is causing us to return pretty small chunks of data up to the
1403 // application, even though more is already buffered and ready to be
1404 // decoded.
1405 if (len)
1406 break;
1409 // If we decrypted 0 bytes, don't report 0 bytes read, which would be
1410 // mistaken for EOF. Continue decrypting or read more.
1411 if (len == 0)
1412 return DoPayloadRead();
1413 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, len,
1414 user_read_buf_->data());
1415 return len;
1418 int SSLClientSocketWin::DoPayloadEncrypt() {
1419 DCHECK(completed_handshake());
1420 DCHECK(user_write_buf_);
1421 DCHECK(user_write_buf_len_ > 0);
1423 ULONG message_len = std::min(
1424 stream_sizes_.cbMaximumMessage, static_cast<ULONG>(user_write_buf_len_));
1425 ULONG alloc_len =
1426 message_len + stream_sizes_.cbHeader + stream_sizes_.cbTrailer;
1427 user_write_buf_len_ = message_len;
1429 payload_send_buffer_.reset(new char[alloc_len]);
1430 memcpy(&payload_send_buffer_[stream_sizes_.cbHeader],
1431 user_write_buf_->data(), message_len);
1432 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_SENT, message_len,
1433 user_write_buf_->data());
1435 SecBuffer buffers[4];
1436 buffers[0].pvBuffer = payload_send_buffer_.get();
1437 buffers[0].cbBuffer = stream_sizes_.cbHeader;
1438 buffers[0].BufferType = SECBUFFER_STREAM_HEADER;
1440 buffers[1].pvBuffer = &payload_send_buffer_[stream_sizes_.cbHeader];
1441 buffers[1].cbBuffer = message_len;
1442 buffers[1].BufferType = SECBUFFER_DATA;
1444 buffers[2].pvBuffer = &payload_send_buffer_[stream_sizes_.cbHeader +
1445 message_len];
1446 buffers[2].cbBuffer = stream_sizes_.cbTrailer;
1447 buffers[2].BufferType = SECBUFFER_STREAM_TRAILER;
1449 buffers[3].BufferType = SECBUFFER_EMPTY;
1451 SecBufferDesc buffer_desc;
1452 buffer_desc.cBuffers = 4;
1453 buffer_desc.pBuffers = buffers;
1454 buffer_desc.ulVersion = SECBUFFER_VERSION;
1456 SECURITY_STATUS status = EncryptMessage(&ctxt_, 0, &buffer_desc, 0);
1458 if (FAILED(status)) {
1459 LOG(ERROR) << "EncryptMessage failed: " << status;
1460 return MapSecurityError(status);
1463 payload_send_buffer_len_ = buffers[0].cbBuffer +
1464 buffers[1].cbBuffer +
1465 buffers[2].cbBuffer;
1466 DCHECK(bytes_sent_ == 0);
1467 return OK;
1470 int SSLClientSocketWin::DoPayloadWrite() {
1471 DCHECK(completed_handshake());
1473 // We should have something to send.
1474 DCHECK(payload_send_buffer_.get());
1475 DCHECK(payload_send_buffer_len_ > 0);
1476 DCHECK(!transport_write_buf_);
1478 const char* buf = payload_send_buffer_.get() + bytes_sent_;
1479 int buf_len = payload_send_buffer_len_ - bytes_sent_;
1480 transport_write_buf_ = new IOBuffer(buf_len);
1481 memcpy(transport_write_buf_->data(), buf, buf_len);
1483 int rv = transport_->socket()->Write(
1484 transport_write_buf_, buf_len,
1485 base::Bind(&SSLClientSocketWin::OnWriteComplete,
1486 base::Unretained(this)));
1487 if (rv != ERR_IO_PENDING)
1488 rv = DoPayloadWriteComplete(rv);
1489 return rv;
1492 int SSLClientSocketWin::DoPayloadWriteComplete(int result) {
1493 DCHECK(transport_write_buf_);
1494 transport_write_buf_ = NULL;
1495 if (result < 0)
1496 return result;
1498 DCHECK(result != 0);
1500 bytes_sent_ += result;
1501 DCHECK(bytes_sent_ <= payload_send_buffer_len_);
1503 if (bytes_sent_ >= payload_send_buffer_len_) {
1504 bool overflow = (bytes_sent_ > payload_send_buffer_len_);
1505 payload_send_buffer_.reset();
1506 payload_send_buffer_len_ = 0;
1507 bytes_sent_ = 0;
1508 if (overflow) { // Bug!
1509 LOG(DFATAL) << "overflow";
1510 return ERR_UNEXPECTED;
1512 // Done
1513 return user_write_buf_len_;
1516 // Send the remaining bytes.
1517 return DoPayloadWrite();
1520 int SSLClientSocketWin::DoCompletedRenegotiation(int result) {
1521 // The user had a read in progress, which was usurped by the renegotiation.
1522 // Restart the read sequence.
1523 next_state_ = STATE_COMPLETED_HANDSHAKE;
1524 if (result != OK)
1525 return result;
1526 return DoPayloadRead();
1529 int SSLClientSocketWin::DidCompleteHandshake() {
1530 SECURITY_STATUS status = QueryContextAttributes(
1531 &ctxt_, SECPKG_ATTR_STREAM_SIZES, &stream_sizes_);
1532 if (status != SEC_E_OK) {
1533 LOG(ERROR) << "QueryContextAttributes (stream sizes) failed: " << status;
1534 return MapSecurityError(status);
1536 DCHECK(!server_cert_ || renegotiating_);
1537 PCCERT_CONTEXT server_cert_handle = NULL;
1538 status = QueryContextAttributes(
1539 &ctxt_, SECPKG_ATTR_REMOTE_CERT_CONTEXT, &server_cert_handle);
1540 if (status != SEC_E_OK) {
1541 LOG(ERROR) << "QueryContextAttributes (remote cert) failed: " << status;
1542 return MapSecurityError(status);
1545 X509Certificate::OSCertHandles intermediates;
1546 PCCERT_CONTEXT intermediate = NULL;
1547 // In testing, enumerating the store returned from SChannel appears to
1548 // enumerate certificates in reverse of the order they were added, meaning
1549 // that issuer certificates appear before the subject certificates. This is
1550 // likely because the default Windows memory store is implemented as a
1551 // linked-list. Reverse the list, so that intermediates are ordered from
1552 // subject to issuer.
1553 // Note that the store also includes the end-entity (server) certificate,
1554 // so exclude this certificate from the set of |intermediates|.
1555 while ((intermediate = CertEnumCertificatesInStore(
1556 server_cert_handle->hCertStore, intermediate))) {
1557 if (!X509Certificate::IsSameOSCert(server_cert_handle, intermediate))
1558 intermediates.push_back(CertDuplicateCertificateContext(intermediate));
1560 std::reverse(intermediates.begin(), intermediates.end());
1562 scoped_refptr<X509Certificate> new_server_cert(
1563 X509Certificate::CreateFromHandle(server_cert_handle, intermediates));
1564 net_log_.AddEvent(
1565 NetLog::TYPE_SSL_CERTIFICATES_RECEIVED,
1566 base::Bind(&NetLogX509CertificateCallback,
1567 base::Unretained(new_server_cert.get())));
1568 if (renegotiating_ && IsCertificateChainIdentical(server_cert_,
1569 new_server_cert)) {
1570 // We already verified the server certificate. Either it is good or the
1571 // user has accepted the certificate error.
1572 DidCompleteRenegotiation();
1573 } else {
1574 server_cert_ = new_server_cert;
1575 next_state_ = STATE_VERIFY_CERT;
1577 CertFreeCertificateContext(server_cert_handle);
1578 for (size_t i = 0; i < intermediates.size(); ++i)
1579 CertFreeCertificateContext(intermediates[i]);
1580 return OK;
1583 // Called when a renegotiation is completed. |result| is the verification
1584 // result of the server certificate received during renegotiation.
1585 void SSLClientSocketWin::DidCompleteRenegotiation() {
1586 DCHECK(user_connect_callback_.is_null());
1587 DCHECK(!user_read_callback_.is_null());
1588 renegotiating_ = false;
1589 next_state_ = STATE_COMPLETED_RENEGOTIATION;
1592 void SSLClientSocketWin::LogConnectionTypeMetrics() const {
1593 UpdateConnectionTypeHistograms(CONNECTION_SSL);
1594 if (server_cert_verify_result_.has_md5)
1595 UpdateConnectionTypeHistograms(CONNECTION_SSL_MD5);
1596 if (server_cert_verify_result_.has_md2)
1597 UpdateConnectionTypeHistograms(CONNECTION_SSL_MD2);
1598 if (server_cert_verify_result_.has_md4)
1599 UpdateConnectionTypeHistograms(CONNECTION_SSL_MD4);
1600 if (server_cert_verify_result_.has_md5_ca)
1601 UpdateConnectionTypeHistograms(CONNECTION_SSL_MD5_CA);
1602 if (server_cert_verify_result_.has_md2_ca)
1603 UpdateConnectionTypeHistograms(CONNECTION_SSL_MD2_CA);
1606 void SSLClientSocketWin::FreeSendBuffer() {
1607 SECURITY_STATUS status = FreeContextBuffer(send_buffer_.pvBuffer);
1608 DCHECK(status == SEC_E_OK);
1609 memset(&send_buffer_, 0, sizeof(send_buffer_));
1612 } // namespace net