move SK_DISABLE_DITHER_32BIT_GRADIENT from SkUserConfig.h to skia.gyp, so we can...
[chromium-blink-merge.git] / net / socket / ssl_client_socket_win.cc
blob37e5309c786d3e25078626b49f5afefa972f1ccb
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/base/x509_util.h"
31 #include "net/socket/client_socket_handle.h"
33 #pragma comment(lib, "secur32.lib")
35 namespace net {
37 //-----------------------------------------------------------------------------
39 // TODO(wtc): See http://msdn.microsoft.com/en-us/library/aa377188(VS.85).aspx
40 // for the other error codes we may need to map.
41 static int MapSecurityError(SECURITY_STATUS err) {
42 // There are numerous security error codes, but these are the ones we thus
43 // far find interesting.
44 switch (err) {
45 case SEC_E_WRONG_PRINCIPAL: // Schannel - server certificate error.
46 case CERT_E_CN_NO_MATCH: // CryptoAPI
47 return ERR_CERT_COMMON_NAME_INVALID;
48 case SEC_E_UNTRUSTED_ROOT: // Schannel - server certificate error or
49 // unknown_ca alert.
50 case CERT_E_UNTRUSTEDROOT: // CryptoAPI
51 return ERR_CERT_AUTHORITY_INVALID;
52 case SEC_E_CERT_EXPIRED: // Schannel - server certificate error or
53 // certificate_expired alert.
54 case CERT_E_EXPIRED: // CryptoAPI
55 return ERR_CERT_DATE_INVALID;
56 case CRYPT_E_NO_REVOCATION_CHECK:
57 return ERR_CERT_NO_REVOCATION_MECHANISM;
58 case CRYPT_E_REVOCATION_OFFLINE:
59 return ERR_CERT_UNABLE_TO_CHECK_REVOCATION;
60 case CRYPT_E_REVOKED: // CryptoAPI and Schannel server certificate error,
61 // or certificate_revoked alert.
62 return ERR_CERT_REVOKED;
64 // We received one of the following alert messages from the server:
65 // bad_certificate
66 // unsupported_certificate
67 // certificate_unknown
68 case SEC_E_CERT_UNKNOWN:
69 case CERT_E_ROLE:
70 return ERR_CERT_INVALID;
72 // We received one of the following alert messages from the server:
73 // decode_error
74 // export_restriction
75 // handshake_failure
76 // illegal_parameter
77 // record_overflow
78 // unexpected_message
79 // and all other TLS alerts not explicitly specified elsewhere.
80 case SEC_E_ILLEGAL_MESSAGE:
81 // We received one of the following alert messages from the server:
82 // decrypt_error
83 // decryption_failed
84 case SEC_E_DECRYPT_FAILURE:
85 // We received one of the following alert messages from the server:
86 // bad_record_mac
87 // decompression_failure
88 case SEC_E_MESSAGE_ALTERED:
89 // TODO(rsleevi): Add SEC_E_INTERNAL_ERROR, which corresponds to an
90 // internal_error alert message being received. However, it is also used
91 // by Schannel for authentication errors that happen locally, so it has
92 // been omitted to prevent masking them as protocol errors.
93 return ERR_SSL_PROTOCOL_ERROR;
95 case SEC_E_LOGON_DENIED: // Received a access_denied alert.
96 return ERR_BAD_SSL_CLIENT_AUTH_CERT;
98 case SEC_E_UNSUPPORTED_FUNCTION: // Received a protocol_version alert.
99 case SEC_E_ALGORITHM_MISMATCH: // Received an insufficient_security alert.
100 return ERR_SSL_VERSION_OR_CIPHER_MISMATCH;
102 case SEC_E_NO_CREDENTIALS:
103 return ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY;
104 case SEC_E_INVALID_HANDLE:
105 case SEC_E_INVALID_TOKEN:
106 LOG(ERROR) << "Unexpected error " << err;
107 return ERR_UNEXPECTED;
108 case SEC_E_OK:
109 return OK;
110 default:
111 LOG(WARNING) << "Unknown error " << err << " mapped to net::ERR_FAILED";
112 return ERR_FAILED;
116 //-----------------------------------------------------------------------------
118 // A bitmask consisting of these bit flags encodes which versions of the SSL
119 // protocol (SSL 3.0 and TLS 1.0) are enabled.
120 // TODO(wtc): support TLS 1.1 and TLS 1.2 on Windows Vista and later.
121 enum {
122 SSL3 = 1 << 0,
123 TLS1 = 1 << 1,
124 SSL_VERSION_MASKS = 1 << 2 // The number of SSL version bitmasks.
127 // CredHandleClass simply gives a default constructor and a destructor to
128 // SSPI's CredHandle type (a C struct).
129 class CredHandleClass : public CredHandle {
130 public:
131 CredHandleClass() {
132 SecInvalidateHandle(this);
135 ~CredHandleClass() {
136 if (SecIsValidHandle(this)) {
137 SECURITY_STATUS status = FreeCredentialsHandle(this);
138 DCHECK(status == SEC_E_OK);
143 // A table of CredHandles.
144 class CredHandleTable {
145 public:
146 CredHandleTable() {}
148 ~CredHandleTable() {
149 STLDeleteContainerPairSecondPointers(client_cert_creds_.begin(),
150 client_cert_creds_.end());
153 int GetHandle(PCCERT_CONTEXT client_cert,
154 int ssl_version_mask,
155 CredHandle** handle_ptr) {
156 DCHECK(0 < ssl_version_mask &&
157 ssl_version_mask < arraysize(anonymous_creds_));
158 CredHandleClass* handle;
159 base::AutoLock lock(lock_);
160 if (client_cert) {
161 CredHandleMapKey key = std::make_pair(client_cert, ssl_version_mask);
162 CredHandleMap::const_iterator it = client_cert_creds_.find(key);
163 if (it == client_cert_creds_.end()) {
164 handle = new CredHandleClass;
165 client_cert_creds_[key] = handle;
166 } else {
167 handle = it->second;
169 } else {
170 handle = &anonymous_creds_[ssl_version_mask];
172 if (!SecIsValidHandle(handle)) {
173 int result = InitializeHandle(handle, client_cert, ssl_version_mask);
174 if (result != OK)
175 return result;
177 *handle_ptr = handle;
178 return OK;
181 private:
182 // CredHandleMapKey is a std::pair consisting of these two components:
183 // PCCERT_CONTEXT client_cert
184 // int ssl_version_mask
185 typedef std::pair<PCCERT_CONTEXT, int> CredHandleMapKey;
187 typedef std::map<CredHandleMapKey, CredHandleClass*> CredHandleMap;
189 // Returns OK on success or a network error code on failure.
190 static int InitializeHandle(CredHandle* handle,
191 PCCERT_CONTEXT client_cert,
192 int ssl_version_mask);
194 base::Lock lock_;
196 // Anonymous (no client certificate) CredHandles for all possible
197 // combinations of SSL versions. Defined as an array for fast lookup.
198 CredHandleClass anonymous_creds_[SSL_VERSION_MASKS];
200 // CredHandles that use a client certificate.
201 CredHandleMap client_cert_creds_;
204 static base::LazyInstance<CredHandleTable> g_cred_handle_table =
205 LAZY_INSTANCE_INITIALIZER;
207 // static
208 int CredHandleTable::InitializeHandle(CredHandle* handle,
209 PCCERT_CONTEXT client_cert,
210 int ssl_version_mask) {
211 SCHANNEL_CRED schannel_cred = {0};
212 schannel_cred.dwVersion = SCHANNEL_CRED_VERSION;
213 if (client_cert) {
214 schannel_cred.cCreds = 1;
215 schannel_cred.paCred = &client_cert;
216 // Schannel will make its own copy of client_cert.
219 // The global system registry settings take precedence over the value of
220 // schannel_cred.grbitEnabledProtocols.
221 schannel_cred.grbitEnabledProtocols = 0;
222 if (ssl_version_mask & SSL3)
223 schannel_cred.grbitEnabledProtocols |= SP_PROT_SSL3;
224 if (ssl_version_mask & TLS1)
225 schannel_cred.grbitEnabledProtocols |= SP_PROT_TLS1;
227 // The default session lifetime is 36000000 milliseconds (ten hours). Set
228 // schannel_cred.dwSessionLifespan to change the number of milliseconds that
229 // Schannel keeps the session in its session cache.
231 // We can set the key exchange algorithms (RSA or DH) in
232 // schannel_cred.{cSupportedAlgs,palgSupportedAlgs}.
234 // Although SCH_CRED_AUTO_CRED_VALIDATION is convenient, we have to use
235 // SCH_CRED_MANUAL_CRED_VALIDATION for three reasons.
236 // 1. SCH_CRED_AUTO_CRED_VALIDATION doesn't allow us to get the certificate
237 // context if the certificate validation fails.
238 // 2. SCH_CRED_AUTO_CRED_VALIDATION returns only one error even if the
239 // certificate has multiple errors.
240 // 3. SCH_CRED_AUTO_CRED_VALIDATION doesn't allow us to ignore untrusted CA
241 // and expired certificate errors. There are only flags to ignore the
242 // name mismatch and unable-to-check-revocation errors.
244 // We specify SCH_CRED_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT to cause the TLS
245 // certificate status request extension (commonly known as OCSP stapling)
246 // to be sent on Vista or later. This flag matches the
247 // CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT flag that we pass to the
248 // CertGetCertificateChain calls. Note: we specify this flag even when
249 // revocation checking is disabled to avoid doubling the number of
250 // credentials handles we need to acquire.
252 // TODO(wtc): Look into undocumented or poorly documented flags:
253 // SCH_CRED_RESTRICTED_ROOTS
254 // SCH_CRED_REVOCATION_CHECK_CACHE_ONLY
255 // SCH_CRED_CACHE_ONLY_URL_RETRIEVAL
256 // SCH_CRED_MEMORY_STORE_CERT
257 schannel_cred.dwFlags |= SCH_CRED_NO_DEFAULT_CREDS |
258 SCH_CRED_MANUAL_CRED_VALIDATION |
259 SCH_CRED_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT;
260 TimeStamp expiry;
261 SECURITY_STATUS status;
263 status = AcquireCredentialsHandle(
264 NULL, // Not used
265 UNISP_NAME, // Microsoft Unified Security Protocol Provider
266 SECPKG_CRED_OUTBOUND,
267 NULL, // Not used
268 &schannel_cred,
269 NULL, // Not used
270 NULL, // Not used
271 handle,
272 &expiry); // Optional
273 if (status != SEC_E_OK)
274 LOG(ERROR) << "AcquireCredentialsHandle failed: " << status;
275 return MapSecurityError(status);
278 // For the SSL sockets to share SSL sessions by session resumption handshakes,
279 // they need to use the same CredHandle. The GetCredHandle function creates
280 // and stores a shared CredHandle in *handle_ptr. On success, GetCredHandle
281 // returns OK. On failure, GetCredHandle returns a network error code and
282 // leaves *handle_ptr unchanged.
284 // The versions of the SSL protocol enabled are a property of the CredHandle.
285 // So we need a separate CredHandle for each combination of SSL versions.
286 // Most of the time Chromium will use only one or two combinations of SSL
287 // versions (for example, SSL3 | TLS1 for normal use, plus SSL3 when visiting
288 // TLS-intolerant servers). These CredHandles are initialized only when
289 // needed.
291 static int GetCredHandle(PCCERT_CONTEXT client_cert,
292 int ssl_version_mask,
293 CredHandle** handle_ptr) {
294 if (ssl_version_mask <= 0 || ssl_version_mask >= SSL_VERSION_MASKS) {
295 NOTREACHED();
296 return ERR_UNEXPECTED;
298 return g_cred_handle_table.Get().GetHandle(client_cert,
299 ssl_version_mask,
300 handle_ptr);
303 //-----------------------------------------------------------------------------
305 // This callback is intended to be used with CertFindChainInStore. In addition
306 // to filtering by extended/enhanced key usage, we do not show expired
307 // certificates and require digital signature usage in the key usage
308 // extension.
310 // This matches our behavior on Mac OS X and that of NSS. It also matches the
311 // default behavior of IE8. See http://support.microsoft.com/kb/890326 and
312 // 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
313 static BOOL WINAPI ClientCertFindCallback(PCCERT_CONTEXT cert_context,
314 void* find_arg) {
315 // Verify the certificate's KU is good.
316 BYTE key_usage;
317 if (CertGetIntendedKeyUsage(X509_ASN_ENCODING, cert_context->pCertInfo,
318 &key_usage, 1)) {
319 if (!(key_usage & CERT_DIGITAL_SIGNATURE_KEY_USAGE))
320 return FALSE;
321 } else {
322 DWORD err = GetLastError();
323 // If |err| is non-zero, it's an actual error. Otherwise the extension
324 // just isn't present, and we treat it as if everything was allowed.
325 if (err) {
326 DLOG(ERROR) << "CertGetIntendedKeyUsage failed: " << err;
327 return FALSE;
331 // Verify the current time is within the certificate's validity period.
332 if (CertVerifyTimeValidity(NULL, cert_context->pCertInfo) != 0)
333 return FALSE;
335 // Verify private key metadata is associated with this certificate.
336 DWORD size = 0;
337 if (!CertGetCertificateContextProperty(
338 cert_context, CERT_KEY_PROV_INFO_PROP_ID, NULL, &size)) {
339 return FALSE;
342 return TRUE;
345 static bool IsCertificateChainIdentical(const X509Certificate* a,
346 const X509Certificate* b) {
347 DCHECK(a);
348 DCHECK(b);
349 const X509Certificate::OSCertHandles& a_intermediates =
350 a->GetIntermediateCertificates();
351 const X509Certificate::OSCertHandles& b_intermediates =
352 b->GetIntermediateCertificates();
353 if (a_intermediates.size() != b_intermediates.size() || !a->Equals(b))
354 return false;
355 for (size_t i = 0; i < a_intermediates.size(); ++i) {
356 if (!X509Certificate::IsSameOSCert(a_intermediates[i], b_intermediates[i]))
357 return false;
359 return true;
362 //-----------------------------------------------------------------------------
364 // Size of recv_buffer_
366 // Ciphertext is decrypted one SSL record at a time, so recv_buffer_ needs to
367 // have room for a full SSL record, with the header and trailer. Here is the
368 // breakdown of the size:
369 // 5: SSL record header
370 // 16K: SSL record maximum size
371 // 64: >= SSL record trailer (16 or 20 have been observed)
372 static const int kRecvBufferSize = (5 + 16*1024 + 64);
374 SSLClientSocketWin::SSLClientSocketWin(ClientSocketHandle* transport_socket,
375 const HostPortPair& host_and_port,
376 const SSLConfig& ssl_config,
377 const SSLClientSocketContext& context)
378 : transport_(transport_socket),
379 host_and_port_(host_and_port),
380 ssl_config_(ssl_config),
381 user_read_buf_len_(0),
382 user_write_buf_len_(0),
383 next_state_(STATE_NONE),
384 cert_verifier_(context.cert_verifier),
385 creds_(NULL),
386 isc_status_(SEC_E_OK),
387 payload_send_buffer_len_(0),
388 bytes_sent_(0),
389 decrypted_ptr_(NULL),
390 bytes_decrypted_(0),
391 received_ptr_(NULL),
392 bytes_received_(0),
393 writing_first_token_(false),
394 ignore_ok_result_(false),
395 renegotiating_(false),
396 need_more_data_(false),
397 net_log_(transport_socket->socket()->NetLog()) {
398 memset(&stream_sizes_, 0, sizeof(stream_sizes_));
399 memset(in_buffers_, 0, sizeof(in_buffers_));
400 memset(&send_buffer_, 0, sizeof(send_buffer_));
401 memset(&ctxt_, 0, sizeof(ctxt_));
404 SSLClientSocketWin::~SSLClientSocketWin() {
405 Disconnect();
408 bool SSLClientSocketWin::GetSSLInfo(SSLInfo* ssl_info) {
409 ssl_info->Reset();
410 if (!server_cert_)
411 return false;
413 ssl_info->cert = server_cert_verify_result_.verified_cert;
414 ssl_info->cert_status = server_cert_verify_result_.cert_status;
415 ssl_info->public_key_hashes = server_cert_verify_result_.public_key_hashes;
416 ssl_info->is_issued_by_known_root =
417 server_cert_verify_result_.is_issued_by_known_root;
418 ssl_info->client_cert_sent =
419 ssl_config_.send_client_cert && ssl_config_.client_cert;
420 ssl_info->channel_id_sent = WasChannelIDSent();
421 SecPkgContext_ConnectionInfo connection_info;
422 SECURITY_STATUS status = QueryContextAttributes(
423 &ctxt_, SECPKG_ATTR_CONNECTION_INFO, &connection_info);
424 if (status == SEC_E_OK) {
425 // TODO(wtc): compute the overall security strength, taking into account
426 // dwExchStrength and dwHashStrength. dwExchStrength needs to be
427 // normalized.
428 ssl_info->security_bits = connection_info.dwCipherStrength;
429 // TODO(wtc): connection_info.dwProtocol is the negotiated version.
430 // Save it in ssl_info->connection_status.
432 // SecPkgContext_CipherInfo comes from CNG and is available on Vista or
433 // later only. On XP, the next QueryContextAttributes call fails with
434 // SEC_E_UNSUPPORTED_FUNCTION (0x80090302), so ssl_info->connection_status
435 // won't contain the cipher suite. If this is a problem, we can build the
436 // cipher suite from the aiCipher, aiHash, and aiExch fields of
437 // SecPkgContext_ConnectionInfo based on Appendix C of RFC 5246.
438 SecPkgContext_CipherInfo cipher_info = { SECPKGCONTEXT_CIPHERINFO_V1 };
439 status = QueryContextAttributes(
440 &ctxt_, SECPKG_ATTR_CIPHER_INFO, &cipher_info);
441 if (status == SEC_E_OK) {
442 // TODO(wtc): find out what the cipher_info.dwBaseCipherSuite field is.
443 ssl_info->connection_status |=
444 (cipher_info.dwCipherSuite & SSL_CONNECTION_CIPHERSUITE_MASK) <<
445 SSL_CONNECTION_CIPHERSUITE_SHIFT;
446 // SChannel doesn't support TLS compression, so cipher_info doesn't have
447 // any field related to the compression method.
450 if (ssl_config_.version_fallback)
451 ssl_info->connection_status |= SSL_CONNECTION_VERSION_FALLBACK;
453 return true;
456 void SSLClientSocketWin::GetSSLCertRequestInfo(
457 SSLCertRequestInfo* cert_request_info) {
458 cert_request_info->host_and_port = host_and_port_.ToString();
459 cert_request_info->client_certs.clear();
461 // Get the certificate_authorities field of the CertificateRequest message.
462 // Schannel doesn't return the certificate_types field of the
463 // CertificateRequest message to us, so we can't filter the client
464 // certificates properly. :-(
465 SecPkgContext_IssuerListInfoEx issuer_list;
466 SECURITY_STATUS status = QueryContextAttributes(
467 &ctxt_, SECPKG_ATTR_ISSUER_LIST_EX, &issuer_list);
468 if (status != SEC_E_OK) {
469 DLOG(ERROR) << "QueryContextAttributes (issuer list) failed: " << status;
470 return;
473 // Client certificates of the user are in the "MY" system certificate store.
474 HCERTSTORE my_cert_store = CertOpenSystemStore(NULL, L"MY");
475 if (!my_cert_store) {
476 LOG(ERROR) << "Could not open the \"MY\" system certificate store: "
477 << GetLastError();
478 FreeContextBuffer(issuer_list.aIssuers);
479 return;
482 // Enumerate the client certificates.
483 CERT_CHAIN_FIND_BY_ISSUER_PARA find_by_issuer_para;
484 memset(&find_by_issuer_para, 0, sizeof(find_by_issuer_para));
485 find_by_issuer_para.cbSize = sizeof(find_by_issuer_para);
486 find_by_issuer_para.pszUsageIdentifier = szOID_PKIX_KP_CLIENT_AUTH;
487 find_by_issuer_para.cIssuer = issuer_list.cIssuers;
488 find_by_issuer_para.rgIssuer = issuer_list.aIssuers;
489 find_by_issuer_para.pfnFindCallback = ClientCertFindCallback;
491 PCCERT_CHAIN_CONTEXT chain_context = NULL;
492 DWORD find_flags = CERT_CHAIN_FIND_BY_ISSUER_CACHE_ONLY_FLAG |
493 CERT_CHAIN_FIND_BY_ISSUER_CACHE_ONLY_URL_FLAG;
495 for (;;) {
496 // Find a certificate chain.
497 chain_context = CertFindChainInStore(my_cert_store,
498 X509_ASN_ENCODING,
499 find_flags,
500 CERT_CHAIN_FIND_BY_ISSUER,
501 &find_by_issuer_para,
502 chain_context);
503 if (!chain_context) {
504 DWORD err = GetLastError();
505 if (err != CRYPT_E_NOT_FOUND)
506 DLOG(ERROR) << "CertFindChainInStore failed: " << err;
507 break;
510 // Get the leaf certificate.
511 PCCERT_CONTEXT cert_context =
512 chain_context->rgpChain[0]->rgpElement[0]->pCertContext;
513 // Copy the certificate into a NULL store, so that the "MY" store can be
514 // closed before returning from this function.
515 PCCERT_CONTEXT cert_context2 = NULL;
516 BOOL ok = CertAddCertificateContextToStore(NULL, cert_context,
517 CERT_STORE_ADD_USE_EXISTING,
518 &cert_context2);
519 if (!ok) {
520 NOTREACHED();
521 continue;
524 // Grab the intermediates, if any.
525 X509Certificate::OSCertHandles intermediates;
526 for (DWORD i = 1; i < chain_context->rgpChain[0]->cElement; ++i) {
527 PCCERT_CONTEXT chain_intermediate =
528 chain_context->rgpChain[0]->rgpElement[i]->pCertContext;
529 PCCERT_CONTEXT copied_intermediate = NULL;
530 ok = CertAddCertificateContextToStore(NULL, chain_intermediate,
531 CERT_STORE_ADD_USE_EXISTING,
532 &copied_intermediate);
533 if (ok)
534 intermediates.push_back(copied_intermediate);
536 scoped_refptr<X509Certificate> cert = X509Certificate::CreateFromHandle(
537 cert_context2, intermediates);
538 cert_request_info->client_certs.push_back(cert);
539 CertFreeCertificateContext(cert_context2);
540 for (size_t i = 0; i < intermediates.size(); ++i)
541 CertFreeCertificateContext(intermediates[i]);
544 std::sort(cert_request_info->client_certs.begin(),
545 cert_request_info->client_certs.end(),
546 x509_util::ClientCertSorter());
548 FreeContextBuffer(issuer_list.aIssuers);
550 BOOL ok = CertCloseStore(my_cert_store, CERT_CLOSE_STORE_CHECK_FLAG);
551 DCHECK(ok);
554 int SSLClientSocketWin::ExportKeyingMaterial(const base::StringPiece& label,
555 bool has_context,
556 const base::StringPiece& context,
557 unsigned char* out,
558 unsigned int outlen) {
559 return ERR_NOT_IMPLEMENTED;
562 int SSLClientSocketWin::GetTLSUniqueChannelBinding(std::string* out) {
563 return ERR_NOT_IMPLEMENTED;
566 SSLClientSocket::NextProtoStatus
567 SSLClientSocketWin::GetNextProto(std::string* proto,
568 std::string* server_protos) {
569 proto->clear();
570 server_protos->clear();
571 return kNextProtoUnsupported;
574 ServerBoundCertService* SSLClientSocketWin::GetServerBoundCertService() const {
575 return NULL;
578 int SSLClientSocketWin::Connect(const CompletionCallback& callback) {
579 DCHECK(transport_.get());
580 DCHECK(next_state_ == STATE_NONE);
581 DCHECK(user_connect_callback_.is_null());
583 net_log_.BeginEvent(NetLog::TYPE_SSL_CONNECT);
585 int rv = InitializeSSLContext();
586 if (rv != OK) {
587 net_log_.EndEvent(NetLog::TYPE_SSL_CONNECT);
588 return rv;
591 writing_first_token_ = true;
592 next_state_ = STATE_HANDSHAKE_WRITE;
593 rv = DoLoop(OK);
594 if (rv == ERR_IO_PENDING) {
595 user_connect_callback_ = callback;
596 } else {
597 net_log_.EndEvent(NetLog::TYPE_SSL_CONNECT);
599 return rv;
602 int SSLClientSocketWin::InitializeSSLContext() {
603 // If ssl_config_.version_max > SSL_PROTOCOL_VERSION_TLS1, it means the
604 // SSLConfigService::SetDefaultVersionMax(SSL_PROTOCOL_VERSION_TLS1) call
605 // in ClientSocketFactory::UseSystemSSL() is not effective.
606 DCHECK_LE(ssl_config_.version_max, SSL_PROTOCOL_VERSION_TLS1);
607 int ssl_version_mask = 0;
608 if (ssl_config_.version_min == SSL_PROTOCOL_VERSION_SSL3)
609 ssl_version_mask |= SSL3;
610 if (ssl_config_.version_min <= SSL_PROTOCOL_VERSION_TLS1 &&
611 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1) {
612 ssl_version_mask |= TLS1;
614 // If we pass 0 to GetCredHandle, we will let Schannel select the protocols,
615 // rather than enabling no protocols. So we have to fail here.
616 if (ssl_version_mask == 0)
617 return ERR_NO_SSL_VERSIONS_ENABLED;
618 PCCERT_CONTEXT cert_context = NULL;
619 if (ssl_config_.client_cert)
620 cert_context = ssl_config_.client_cert->os_cert_handle();
621 int result = GetCredHandle(cert_context, ssl_version_mask, &creds_);
622 if (result != OK)
623 return result;
625 memset(&ctxt_, 0, sizeof(ctxt_));
627 SecBufferDesc buffer_desc;
628 DWORD out_flags;
629 DWORD flags = ISC_REQ_SEQUENCE_DETECT |
630 ISC_REQ_REPLAY_DETECT |
631 ISC_REQ_CONFIDENTIALITY |
632 ISC_RET_EXTENDED_ERROR |
633 ISC_REQ_ALLOCATE_MEMORY |
634 ISC_REQ_STREAM;
636 send_buffer_.pvBuffer = NULL;
637 send_buffer_.BufferType = SECBUFFER_TOKEN;
638 send_buffer_.cbBuffer = 0;
640 buffer_desc.cBuffers = 1;
641 buffer_desc.pBuffers = &send_buffer_;
642 buffer_desc.ulVersion = SECBUFFER_VERSION;
644 TimeStamp expiry;
645 SECURITY_STATUS status;
647 status = InitializeSecurityContext(
648 creds_,
649 NULL, // NULL on the first call
650 const_cast<wchar_t*>(ASCIIToWide(host_and_port_.host()).c_str()),
651 flags,
652 0, // Reserved
653 0, // Not used with Schannel.
654 NULL, // NULL on the first call
655 0, // Reserved
656 &ctxt_, // Receives the new context handle
657 &buffer_desc,
658 &out_flags,
659 &expiry);
660 if (status != SEC_I_CONTINUE_NEEDED) {
661 LOG(ERROR) << "InitializeSecurityContext failed: " << status;
662 if (status == SEC_E_INVALID_HANDLE) {
663 // The only handle we passed to this InitializeSecurityContext call is
664 // creds_, so print its contents to figure out why it's invalid.
665 if (creds_) {
666 LOG(ERROR) << "creds_->dwLower = " << creds_->dwLower
667 << "; creds_->dwUpper = " << creds_->dwUpper;
668 } else {
669 LOG(ERROR) << "creds_ is NULL";
672 return MapSecurityError(status);
675 return OK;
679 void SSLClientSocketWin::Disconnect() {
680 // TODO(wtc): Send SSL close_notify alert.
681 next_state_ = STATE_NONE;
683 // Shut down anything that may call us back.
684 verifier_.reset();
685 transport_->socket()->Disconnect();
687 if (send_buffer_.pvBuffer)
688 FreeSendBuffer();
689 if (SecIsValidHandle(&ctxt_)) {
690 DeleteSecurityContext(&ctxt_);
691 SecInvalidateHandle(&ctxt_);
693 if (server_cert_)
694 server_cert_ = NULL;
696 // TODO(wtc): reset more members?
697 bytes_decrypted_ = 0;
698 bytes_received_ = 0;
699 writing_first_token_ = false;
700 renegotiating_ = false;
701 need_more_data_ = false;
704 bool SSLClientSocketWin::IsConnected() const {
705 // Ideally, we should also check if we have received the close_notify alert
706 // message from the server, and return false in that case. We're not doing
707 // that, so this function may return a false positive. Since the upper
708 // layer (HttpNetworkTransaction) needs to handle a persistent connection
709 // closed by the server when we send a request anyway, a false positive in
710 // exchange for simpler code is a good trade-off.
711 return completed_handshake() && transport_->socket()->IsConnected();
714 bool SSLClientSocketWin::IsConnectedAndIdle() const {
715 // Unlike IsConnected, this method doesn't return a false positive.
717 // Strictly speaking, we should check if we have received the close_notify
718 // alert message from the server, and return false in that case. Although
719 // the close_notify alert message means EOF in the SSL layer, it is just
720 // bytes to the transport layer below, so
721 // transport_->socket()->IsConnectedAndIdle() returns the desired false
722 // when we receive close_notify.
723 return completed_handshake() && transport_->socket()->IsConnectedAndIdle();
726 int SSLClientSocketWin::GetPeerAddress(IPEndPoint* address) const {
727 return transport_->socket()->GetPeerAddress(address);
730 int SSLClientSocketWin::GetLocalAddress(IPEndPoint* address) const {
731 return transport_->socket()->GetLocalAddress(address);
734 void SSLClientSocketWin::SetSubresourceSpeculation() {
735 if (transport_.get() && transport_->socket()) {
736 transport_->socket()->SetSubresourceSpeculation();
737 } else {
738 NOTREACHED();
742 void SSLClientSocketWin::SetOmniboxSpeculation() {
743 if (transport_.get() && transport_->socket()) {
744 transport_->socket()->SetOmniboxSpeculation();
745 } else {
746 NOTREACHED();
750 bool SSLClientSocketWin::WasEverUsed() const {
751 if (transport_.get() && transport_->socket()) {
752 return transport_->socket()->WasEverUsed();
754 NOTREACHED();
755 return false;
758 bool SSLClientSocketWin::UsingTCPFastOpen() const {
759 if (transport_.get() && transport_->socket()) {
760 return transport_->socket()->UsingTCPFastOpen();
762 NOTREACHED();
763 return false;
766 int64 SSLClientSocketWin::NumBytesRead() const {
767 if (transport_.get() && transport_->socket()) {
768 return transport_->socket()->NumBytesRead();
770 NOTREACHED();
771 return -1;
774 base::TimeDelta SSLClientSocketWin::GetConnectTimeMicros() const {
775 if (transport_.get() && transport_->socket()) {
776 return transport_->socket()->GetConnectTimeMicros();
778 NOTREACHED();
779 return base::TimeDelta::FromMicroseconds(-1);
782 int SSLClientSocketWin::Read(IOBuffer* buf, int buf_len,
783 const CompletionCallback& callback) {
784 DCHECK(completed_handshake());
785 DCHECK(user_read_callback_.is_null());
787 // If we have surplus decrypted plaintext, satisfy the Read with it without
788 // reading more ciphertext from the transport socket.
789 if (bytes_decrypted_ != 0) {
790 int len = std::min(buf_len, bytes_decrypted_);
791 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, len,
792 decrypted_ptr_);
793 memcpy(buf->data(), decrypted_ptr_, len);
794 decrypted_ptr_ += len;
795 bytes_decrypted_ -= len;
796 if (bytes_decrypted_ == 0) {
797 decrypted_ptr_ = NULL;
798 if (bytes_received_ != 0) {
799 memmove(recv_buffer_.get(), received_ptr_, bytes_received_);
800 received_ptr_ = recv_buffer_.get();
803 return len;
806 DCHECK(!user_read_buf_);
807 // http://crbug.com/16371: We're seeing |buf->data()| return NULL. See if the
808 // user is passing in an IOBuffer with a NULL |data_|.
809 CHECK(buf);
810 CHECK(buf->data());
811 user_read_buf_ = buf;
812 user_read_buf_len_ = buf_len;
814 int rv = DoPayloadRead();
815 if (rv == ERR_IO_PENDING) {
816 user_read_callback_ = callback;
817 } else {
818 user_read_buf_ = NULL;
819 user_read_buf_len_ = 0;
821 return rv;
824 int SSLClientSocketWin::Write(IOBuffer* buf, int buf_len,
825 const CompletionCallback& callback) {
826 DCHECK(completed_handshake());
827 DCHECK(user_write_callback_.is_null());
829 DCHECK(!user_write_buf_);
830 user_write_buf_ = buf;
831 user_write_buf_len_ = buf_len;
833 int rv = DoPayloadEncrypt();
834 if (rv != OK)
835 return rv;
837 rv = DoPayloadWrite();
838 if (rv == ERR_IO_PENDING) {
839 user_write_callback_ = callback;
840 } else {
841 user_write_buf_ = NULL;
842 user_write_buf_len_ = 0;
844 return rv;
847 bool SSLClientSocketWin::SetReceiveBufferSize(int32 size) {
848 return transport_->socket()->SetReceiveBufferSize(size);
851 bool SSLClientSocketWin::SetSendBufferSize(int32 size) {
852 return transport_->socket()->SetSendBufferSize(size);
855 void SSLClientSocketWin::OnHandshakeIOComplete(int result) {
856 int rv = DoLoop(result);
858 // The SSL handshake has some round trips. We need to notify the caller of
859 // success or any error, other than waiting for IO.
860 if (rv != ERR_IO_PENDING) {
861 // If there is no connect callback available to call, we are renegotiating
862 // (which occurs because we are in the middle of a Read when the
863 // renegotiation process starts). So we complete the Read here.
864 if (user_connect_callback_.is_null()) {
865 CompletionCallback c = user_read_callback_;
866 user_read_callback_.Reset();
867 user_read_buf_ = NULL;
868 user_read_buf_len_ = 0;
869 c.Run(rv);
870 return;
872 net_log_.EndEvent(NetLog::TYPE_SSL_CONNECT);
873 CompletionCallback c = user_connect_callback_;
874 user_connect_callback_.Reset();
875 c.Run(rv);
879 void SSLClientSocketWin::OnReadComplete(int result) {
880 DCHECK(completed_handshake());
882 result = DoPayloadReadComplete(result);
883 if (result > 0)
884 result = DoPayloadDecrypt();
885 if (result != ERR_IO_PENDING) {
886 DCHECK(!user_read_callback_.is_null());
887 CompletionCallback c = user_read_callback_;
888 user_read_callback_.Reset();
889 user_read_buf_ = NULL;
890 user_read_buf_len_ = 0;
891 c.Run(result);
895 void SSLClientSocketWin::OnWriteComplete(int result) {
896 DCHECK(completed_handshake());
898 int rv = DoPayloadWriteComplete(result);
899 if (rv != ERR_IO_PENDING) {
900 DCHECK(!user_write_callback_.is_null());
901 CompletionCallback c = user_write_callback_;
902 user_write_callback_.Reset();
903 user_write_buf_ = NULL;
904 user_write_buf_len_ = 0;
905 c.Run(rv);
910 int SSLClientSocketWin::DoLoop(int last_io_result) {
911 DCHECK(next_state_ != STATE_NONE);
912 int rv = last_io_result;
913 do {
914 State state = next_state_;
915 next_state_ = STATE_NONE;
916 switch (state) {
917 case STATE_HANDSHAKE_READ:
918 rv = DoHandshakeRead();
919 break;
920 case STATE_HANDSHAKE_READ_COMPLETE:
921 rv = DoHandshakeReadComplete(rv);
922 break;
923 case STATE_HANDSHAKE_WRITE:
924 rv = DoHandshakeWrite();
925 break;
926 case STATE_HANDSHAKE_WRITE_COMPLETE:
927 rv = DoHandshakeWriteComplete(rv);
928 break;
929 case STATE_VERIFY_CERT:
930 rv = DoVerifyCert();
931 break;
932 case STATE_VERIFY_CERT_COMPLETE:
933 rv = DoVerifyCertComplete(rv);
934 break;
935 case STATE_COMPLETED_RENEGOTIATION:
936 rv = DoCompletedRenegotiation(rv);
937 break;
938 case STATE_COMPLETED_HANDSHAKE:
939 next_state_ = STATE_COMPLETED_HANDSHAKE;
940 // This is the end of our state machine, so return.
941 return rv;
942 default:
943 rv = ERR_UNEXPECTED;
944 LOG(DFATAL) << "unexpected state " << state;
945 break;
947 } while (rv != ERR_IO_PENDING && next_state_ != STATE_NONE);
948 return rv;
951 int SSLClientSocketWin::DoHandshakeRead() {
952 next_state_ = STATE_HANDSHAKE_READ_COMPLETE;
954 if (!recv_buffer_.get())
955 recv_buffer_.reset(new char[kRecvBufferSize]);
957 int buf_len = kRecvBufferSize - bytes_received_;
959 if (buf_len <= 0) {
960 LOG(DFATAL) << "Receive buffer is too small!";
961 return ERR_UNEXPECTED;
964 DCHECK(!transport_read_buf_);
965 transport_read_buf_ = new IOBuffer(buf_len);
967 return transport_->socket()->Read(
968 transport_read_buf_, buf_len,
969 base::Bind(&SSLClientSocketWin::OnHandshakeIOComplete,
970 base::Unretained(this)));
973 int SSLClientSocketWin::DoHandshakeReadComplete(int result) {
974 if (result < 0) {
975 transport_read_buf_ = NULL;
976 return result;
979 if (transport_read_buf_) {
980 // A transition to STATE_HANDSHAKE_READ_COMPLETE is set in multiple places,
981 // not only in DoHandshakeRead(), so we may not have a transport_read_buf_.
982 DCHECK_LE(result, kRecvBufferSize - bytes_received_);
983 char* buf = recv_buffer_.get() + bytes_received_;
984 memcpy(buf, transport_read_buf_->data(), result);
985 transport_read_buf_ = NULL;
988 if (result == 0 && !ignore_ok_result_)
989 return ERR_SSL_PROTOCOL_ERROR; // Incomplete response :(
991 ignore_ok_result_ = false;
993 bytes_received_ += result;
995 // Process the contents of recv_buffer_.
996 TimeStamp expiry;
997 DWORD out_flags;
999 DWORD flags = ISC_REQ_SEQUENCE_DETECT |
1000 ISC_REQ_REPLAY_DETECT |
1001 ISC_REQ_CONFIDENTIALITY |
1002 ISC_RET_EXTENDED_ERROR |
1003 ISC_REQ_ALLOCATE_MEMORY |
1004 ISC_REQ_STREAM;
1006 if (ssl_config_.send_client_cert)
1007 flags |= ISC_REQ_USE_SUPPLIED_CREDS;
1009 SecBufferDesc in_buffer_desc, out_buffer_desc;
1011 in_buffer_desc.cBuffers = 2;
1012 in_buffer_desc.pBuffers = in_buffers_;
1013 in_buffer_desc.ulVersion = SECBUFFER_VERSION;
1015 in_buffers_[0].pvBuffer = recv_buffer_.get();
1016 in_buffers_[0].cbBuffer = bytes_received_;
1017 in_buffers_[0].BufferType = SECBUFFER_TOKEN;
1019 in_buffers_[1].pvBuffer = NULL;
1020 in_buffers_[1].cbBuffer = 0;
1021 in_buffers_[1].BufferType = SECBUFFER_EMPTY;
1023 out_buffer_desc.cBuffers = 1;
1024 out_buffer_desc.pBuffers = &send_buffer_;
1025 out_buffer_desc.ulVersion = SECBUFFER_VERSION;
1027 send_buffer_.pvBuffer = NULL;
1028 send_buffer_.BufferType = SECBUFFER_TOKEN;
1029 send_buffer_.cbBuffer = 0;
1031 isc_status_ = InitializeSecurityContext(
1032 creds_,
1033 &ctxt_,
1034 NULL,
1035 flags,
1038 &in_buffer_desc,
1040 NULL,
1041 &out_buffer_desc,
1042 &out_flags,
1043 &expiry);
1045 if (isc_status_ == SEC_E_INVALID_TOKEN) {
1046 // Peer sent us an SSL record type that's invalid during SSL handshake.
1047 // TODO(wtc): move this to MapSecurityError after sufficient testing.
1048 LOG(ERROR) << "InitializeSecurityContext failed: " << isc_status_;
1049 return ERR_SSL_PROTOCOL_ERROR;
1052 if (send_buffer_.cbBuffer != 0 &&
1053 (isc_status_ == SEC_E_OK ||
1054 isc_status_ == SEC_I_CONTINUE_NEEDED ||
1055 (FAILED(isc_status_) && (out_flags & ISC_RET_EXTENDED_ERROR)))) {
1056 next_state_ = STATE_HANDSHAKE_WRITE;
1057 return OK;
1059 return DidCallInitializeSecurityContext();
1062 int SSLClientSocketWin::DidCallInitializeSecurityContext() {
1063 if (isc_status_ == SEC_E_INCOMPLETE_MESSAGE) {
1064 next_state_ = STATE_HANDSHAKE_READ;
1065 return OK;
1068 if (isc_status_ == SEC_E_OK) {
1069 if (in_buffers_[1].BufferType == SECBUFFER_EXTRA) {
1070 // Save this data for later.
1071 memmove(recv_buffer_.get(),
1072 recv_buffer_.get() + (bytes_received_ - in_buffers_[1].cbBuffer),
1073 in_buffers_[1].cbBuffer);
1074 bytes_received_ = in_buffers_[1].cbBuffer;
1075 } else {
1076 bytes_received_ = 0;
1078 return DidCompleteHandshake();
1081 if (FAILED(isc_status_)) {
1082 LOG(ERROR) << "InitializeSecurityContext failed: " << isc_status_;
1083 if (isc_status_ == SEC_E_INTERNAL_ERROR) {
1084 // "The Local Security Authority cannot be contacted". This happens
1085 // when the user denies access to the private key for SSL client auth.
1086 return ERR_SSL_CLIENT_AUTH_PRIVATE_KEY_ACCESS_DENIED;
1088 int result = MapSecurityError(isc_status_);
1089 // We told Schannel to not verify the server certificate
1090 // (SCH_CRED_MANUAL_CRED_VALIDATION), so any certificate error returned by
1091 // InitializeSecurityContext must be referring to the bad or missing
1092 // client certificate.
1093 if (IsCertificateError(result)) {
1094 // TODO(wtc): Add fine-grained error codes for client certificate errors
1095 // reported by the server using the following SSL/TLS alert messages:
1096 // access_denied
1097 // bad_certificate
1098 // unsupported_certificate
1099 // certificate_expired
1100 // certificate_revoked
1101 // certificate_unknown
1102 // unknown_ca
1103 return ERR_BAD_SSL_CLIENT_AUTH_CERT;
1105 return result;
1108 if (isc_status_ == SEC_I_INCOMPLETE_CREDENTIALS)
1109 return ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
1111 if (isc_status_ == SEC_I_NO_RENEGOTIATION) {
1112 // Received a no_renegotiation alert message. Although this is just a
1113 // warning, SChannel doesn't seem to allow us to continue after this
1114 // point, so we have to return an error. See http://crbug.com/36835.
1115 return ERR_SSL_NO_RENEGOTIATION;
1118 DCHECK(isc_status_ == SEC_I_CONTINUE_NEEDED);
1119 if (in_buffers_[1].BufferType == SECBUFFER_EXTRA) {
1120 memmove(recv_buffer_.get(),
1121 recv_buffer_.get() + (bytes_received_ - in_buffers_[1].cbBuffer),
1122 in_buffers_[1].cbBuffer);
1123 bytes_received_ = in_buffers_[1].cbBuffer;
1124 next_state_ = STATE_HANDSHAKE_READ_COMPLETE;
1125 ignore_ok_result_ = true; // OK doesn't mean EOF.
1126 return OK;
1129 bytes_received_ = 0;
1130 next_state_ = STATE_HANDSHAKE_READ;
1131 return OK;
1134 int SSLClientSocketWin::DoHandshakeWrite() {
1135 next_state_ = STATE_HANDSHAKE_WRITE_COMPLETE;
1137 // We should have something to send.
1138 DCHECK(send_buffer_.pvBuffer);
1139 DCHECK(send_buffer_.cbBuffer > 0);
1140 DCHECK(!transport_write_buf_);
1142 const char* buf = static_cast<char*>(send_buffer_.pvBuffer) + bytes_sent_;
1143 int buf_len = send_buffer_.cbBuffer - bytes_sent_;
1144 transport_write_buf_ = new IOBuffer(buf_len);
1145 memcpy(transport_write_buf_->data(), buf, buf_len);
1147 return transport_->socket()->Write(
1148 transport_write_buf_, buf_len,
1149 base::Bind(&SSLClientSocketWin::OnHandshakeIOComplete,
1150 base::Unretained(this)));
1153 int SSLClientSocketWin::DoHandshakeWriteComplete(int result) {
1154 DCHECK(transport_write_buf_);
1155 transport_write_buf_ = NULL;
1156 if (result < 0)
1157 return result;
1159 DCHECK(result != 0);
1161 bytes_sent_ += result;
1162 DCHECK(bytes_sent_ <= static_cast<int>(send_buffer_.cbBuffer));
1164 if (bytes_sent_ >= static_cast<int>(send_buffer_.cbBuffer)) {
1165 bool overflow = (bytes_sent_ > static_cast<int>(send_buffer_.cbBuffer));
1166 FreeSendBuffer();
1167 bytes_sent_ = 0;
1168 if (overflow) { // Bug!
1169 LOG(DFATAL) << "overflow";
1170 return ERR_UNEXPECTED;
1172 if (writing_first_token_) {
1173 writing_first_token_ = false;
1174 DCHECK(bytes_received_ == 0);
1175 next_state_ = STATE_HANDSHAKE_READ;
1176 return OK;
1178 return DidCallInitializeSecurityContext();
1181 // Send the remaining bytes.
1182 next_state_ = STATE_HANDSHAKE_WRITE;
1183 return OK;
1186 // Set server_cert_status_ and return OK or a network error.
1187 int SSLClientSocketWin::DoVerifyCert() {
1188 next_state_ = STATE_VERIFY_CERT_COMPLETE;
1190 DCHECK(server_cert_);
1191 CertStatus cert_status;
1192 if (ssl_config_.IsAllowedBadCert(server_cert_, &cert_status)) {
1193 VLOG(1) << "Received an expected bad cert with status: " << cert_status;
1194 server_cert_verify_result_.Reset();
1195 server_cert_verify_result_.cert_status = cert_status;
1196 server_cert_verify_result_.verified_cert = server_cert_;
1197 return OK;
1200 int flags = 0;
1201 if (ssl_config_.rev_checking_enabled)
1202 flags |= CertVerifier::VERIFY_REV_CHECKING_ENABLED;
1203 if (ssl_config_.verify_ev_cert)
1204 flags |= CertVerifier::VERIFY_EV_CERT;
1205 if (ssl_config_.cert_io_enabled)
1206 flags |= CertVerifier::VERIFY_CERT_IO_ENABLED;
1207 verifier_.reset(new SingleRequestCertVerifier(cert_verifier_));
1208 return verifier_->Verify(
1209 server_cert_, host_and_port_.host(), flags,
1210 NULL /* no CRL set */,
1211 &server_cert_verify_result_,
1212 base::Bind(&SSLClientSocketWin::OnHandshakeIOComplete,
1213 base::Unretained(this)),
1214 net_log_);
1217 int SSLClientSocketWin::DoVerifyCertComplete(int result) {
1218 DCHECK(verifier_.get());
1219 verifier_.reset();
1221 if (result == OK)
1222 LogConnectionTypeMetrics();
1223 if (renegotiating_) {
1224 DidCompleteRenegotiation();
1225 return result;
1228 // The initial handshake has completed.
1229 next_state_ = STATE_COMPLETED_HANDSHAKE;
1230 return result;
1233 int SSLClientSocketWin::DoPayloadRead() {
1234 DCHECK(recv_buffer_.get());
1236 int buf_len = kRecvBufferSize - bytes_received_;
1238 if (buf_len <= 0) {
1239 NOTREACHED() << "Receive buffer is too small!";
1240 return ERR_FAILED;
1243 int rv;
1244 // If bytes_received_, we have some data from a previous read still ready
1245 // for decoding. Otherwise, we need to issue a real read.
1246 if (!bytes_received_ || need_more_data_) {
1247 DCHECK(!transport_read_buf_);
1248 transport_read_buf_ = new IOBuffer(buf_len);
1250 rv = transport_->socket()->Read(
1251 transport_read_buf_, buf_len,
1252 base::Bind(&SSLClientSocketWin::OnReadComplete,
1253 base::Unretained(this)));
1254 if (rv != ERR_IO_PENDING)
1255 rv = DoPayloadReadComplete(rv);
1256 if (rv <= 0)
1257 return rv;
1260 // Decode what we've read. If there is not enough data to decode yet,
1261 // this may return ERR_IO_PENDING still.
1262 return DoPayloadDecrypt();
1265 // result is the number of bytes that have been read; it should not be
1266 // less than zero; a value of zero means that no additional bytes have
1267 // been read.
1268 int SSLClientSocketWin::DoPayloadReadComplete(int result) {
1269 DCHECK(completed_handshake());
1271 // If IO Pending, there is nothing to do here.
1272 if (result == ERR_IO_PENDING)
1273 return result;
1275 // We completed a Read, so reset the need_more_data_ flag.
1276 need_more_data_ = false;
1278 // Check for error
1279 if (result <= 0) {
1280 transport_read_buf_ = NULL;
1281 if (result == 0 && bytes_received_ != 0) {
1282 // TODO(wtc): Unless we have received the close_notify alert, we need
1283 // to return an error code indicating that the SSL connection ended
1284 // uncleanly, a potential truncation attack. See
1285 // http://crbug.com/18586.
1286 return ERR_SSL_PROTOCOL_ERROR;
1288 return result;
1291 // Transfer the data from transport_read_buf_ to recv_buffer_.
1292 if (transport_read_buf_) {
1293 DCHECK_LE(result, kRecvBufferSize - bytes_received_);
1294 char* buf = recv_buffer_.get() + bytes_received_;
1295 memcpy(buf, transport_read_buf_->data(), result);
1296 transport_read_buf_ = NULL;
1299 bytes_received_ += result;
1301 return result;
1304 int SSLClientSocketWin::DoPayloadDecrypt() {
1305 // Process the contents of recv_buffer_.
1306 int len = 0; // the number of bytes we've copied to the user buffer.
1307 while (bytes_received_) {
1308 SecBuffer buffers[4];
1309 buffers[0].pvBuffer = recv_buffer_.get();
1310 buffers[0].cbBuffer = bytes_received_;
1311 buffers[0].BufferType = SECBUFFER_DATA;
1313 buffers[1].BufferType = SECBUFFER_EMPTY;
1314 buffers[2].BufferType = SECBUFFER_EMPTY;
1315 buffers[3].BufferType = SECBUFFER_EMPTY;
1317 SecBufferDesc buffer_desc;
1318 buffer_desc.cBuffers = 4;
1319 buffer_desc.pBuffers = buffers;
1320 buffer_desc.ulVersion = SECBUFFER_VERSION;
1322 SECURITY_STATUS status;
1323 status = DecryptMessage(&ctxt_, &buffer_desc, 0, NULL);
1325 if (status == SEC_E_INCOMPLETE_MESSAGE) {
1326 need_more_data_ = true;
1327 return DoPayloadRead();
1330 if (status == SEC_I_CONTEXT_EXPIRED) {
1331 // Received the close_notify alert.
1332 bytes_received_ = 0;
1333 return OK;
1336 if (status != SEC_E_OK && status != SEC_I_RENEGOTIATE) {
1337 DCHECK(status != SEC_E_MESSAGE_ALTERED);
1338 LOG(ERROR) << "DecryptMessage failed: " << status;
1339 return MapSecurityError(status);
1342 // The received ciphertext was decrypted in place in recv_buffer_. Remember
1343 // the location and length of the decrypted plaintext and any unused
1344 // ciphertext.
1345 decrypted_ptr_ = NULL;
1346 bytes_decrypted_ = 0;
1347 received_ptr_ = NULL;
1348 bytes_received_ = 0;
1349 for (int i = 1; i < 4; i++) {
1350 switch (buffers[i].BufferType) {
1351 case SECBUFFER_DATA:
1352 DCHECK(!decrypted_ptr_ && bytes_decrypted_ == 0);
1353 decrypted_ptr_ = static_cast<char*>(buffers[i].pvBuffer);
1354 bytes_decrypted_ = buffers[i].cbBuffer;
1355 break;
1356 case SECBUFFER_EXTRA:
1357 DCHECK(!received_ptr_ && bytes_received_ == 0);
1358 received_ptr_ = static_cast<char*>(buffers[i].pvBuffer);
1359 bytes_received_ = buffers[i].cbBuffer;
1360 break;
1361 default:
1362 break;
1366 DCHECK(len == 0);
1367 if (bytes_decrypted_ != 0) {
1368 len = std::min(user_read_buf_len_, bytes_decrypted_);
1369 memcpy(user_read_buf_->data(), decrypted_ptr_, len);
1370 decrypted_ptr_ += len;
1371 bytes_decrypted_ -= len;
1373 if (bytes_decrypted_ == 0) {
1374 decrypted_ptr_ = NULL;
1375 if (bytes_received_ != 0) {
1376 memmove(recv_buffer_.get(), received_ptr_, bytes_received_);
1377 received_ptr_ = recv_buffer_.get();
1381 if (status == SEC_I_RENEGOTIATE) {
1382 if (bytes_received_ != 0) {
1383 // The server requested renegotiation, but there are some data yet to
1384 // be decrypted. The Platform SDK WebClient.c sample doesn't handle
1385 // this, so we don't know how to handle this. Assume this cannot
1386 // happen.
1387 LOG(ERROR) << "DecryptMessage returned SEC_I_RENEGOTIATE with a buffer "
1388 << "of type SECBUFFER_EXTRA.";
1389 return ERR_SSL_RENEGOTIATION_REQUESTED;
1391 if (len != 0) {
1392 // The server requested renegotiation, but there are some decrypted
1393 // data. We can't start renegotiation until we have returned all
1394 // decrypted data to the caller.
1396 // This hasn't happened during testing. Assume this cannot happen even
1397 // though we know how to handle this.
1398 LOG(ERROR) << "DecryptMessage returned SEC_I_RENEGOTIATE with a buffer "
1399 << "of type SECBUFFER_DATA.";
1400 return ERR_SSL_RENEGOTIATION_REQUESTED;
1402 // Jump to the handshake sequence. Will come back when the rehandshake is
1403 // done.
1404 renegotiating_ = true;
1405 ignore_ok_result_ = true; // OK doesn't mean EOF.
1406 // If renegotiation handshake occurred, we need to go back into the
1407 // handshake state machine.
1408 next_state_ = STATE_HANDSHAKE_READ_COMPLETE;
1409 return DoLoop(OK);
1412 // We've already copied data into the user buffer, so quit now.
1413 // TODO(mbelshe): We really should keep decoding as long as we can. This
1414 // break out is causing us to return pretty small chunks of data up to the
1415 // application, even though more is already buffered and ready to be
1416 // decoded.
1417 if (len)
1418 break;
1421 // If we decrypted 0 bytes, don't report 0 bytes read, which would be
1422 // mistaken for EOF. Continue decrypting or read more.
1423 if (len == 0)
1424 return DoPayloadRead();
1425 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, len,
1426 user_read_buf_->data());
1427 return len;
1430 int SSLClientSocketWin::DoPayloadEncrypt() {
1431 DCHECK(completed_handshake());
1432 DCHECK(user_write_buf_);
1433 DCHECK(user_write_buf_len_ > 0);
1435 ULONG message_len = std::min(
1436 stream_sizes_.cbMaximumMessage, static_cast<ULONG>(user_write_buf_len_));
1437 ULONG alloc_len =
1438 message_len + stream_sizes_.cbHeader + stream_sizes_.cbTrailer;
1439 user_write_buf_len_ = message_len;
1441 payload_send_buffer_.reset(new char[alloc_len]);
1442 memcpy(&payload_send_buffer_[stream_sizes_.cbHeader],
1443 user_write_buf_->data(), message_len);
1444 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_SENT, message_len,
1445 user_write_buf_->data());
1447 SecBuffer buffers[4];
1448 buffers[0].pvBuffer = payload_send_buffer_.get();
1449 buffers[0].cbBuffer = stream_sizes_.cbHeader;
1450 buffers[0].BufferType = SECBUFFER_STREAM_HEADER;
1452 buffers[1].pvBuffer = &payload_send_buffer_[stream_sizes_.cbHeader];
1453 buffers[1].cbBuffer = message_len;
1454 buffers[1].BufferType = SECBUFFER_DATA;
1456 buffers[2].pvBuffer = &payload_send_buffer_[stream_sizes_.cbHeader +
1457 message_len];
1458 buffers[2].cbBuffer = stream_sizes_.cbTrailer;
1459 buffers[2].BufferType = SECBUFFER_STREAM_TRAILER;
1461 buffers[3].BufferType = SECBUFFER_EMPTY;
1463 SecBufferDesc buffer_desc;
1464 buffer_desc.cBuffers = 4;
1465 buffer_desc.pBuffers = buffers;
1466 buffer_desc.ulVersion = SECBUFFER_VERSION;
1468 SECURITY_STATUS status = EncryptMessage(&ctxt_, 0, &buffer_desc, 0);
1470 if (FAILED(status)) {
1471 LOG(ERROR) << "EncryptMessage failed: " << status;
1472 return MapSecurityError(status);
1475 payload_send_buffer_len_ = buffers[0].cbBuffer +
1476 buffers[1].cbBuffer +
1477 buffers[2].cbBuffer;
1478 DCHECK(bytes_sent_ == 0);
1479 return OK;
1482 int SSLClientSocketWin::DoPayloadWrite() {
1483 DCHECK(completed_handshake());
1485 // We should have something to send.
1486 DCHECK(payload_send_buffer_.get());
1487 DCHECK(payload_send_buffer_len_ > 0);
1488 DCHECK(!transport_write_buf_);
1490 const char* buf = payload_send_buffer_.get() + bytes_sent_;
1491 int buf_len = payload_send_buffer_len_ - bytes_sent_;
1492 transport_write_buf_ = new IOBuffer(buf_len);
1493 memcpy(transport_write_buf_->data(), buf, buf_len);
1495 int rv = transport_->socket()->Write(
1496 transport_write_buf_, buf_len,
1497 base::Bind(&SSLClientSocketWin::OnWriteComplete,
1498 base::Unretained(this)));
1499 if (rv != ERR_IO_PENDING)
1500 rv = DoPayloadWriteComplete(rv);
1501 return rv;
1504 int SSLClientSocketWin::DoPayloadWriteComplete(int result) {
1505 DCHECK(transport_write_buf_);
1506 transport_write_buf_ = NULL;
1507 if (result < 0)
1508 return result;
1510 DCHECK(result != 0);
1512 bytes_sent_ += result;
1513 DCHECK(bytes_sent_ <= payload_send_buffer_len_);
1515 if (bytes_sent_ >= payload_send_buffer_len_) {
1516 bool overflow = (bytes_sent_ > payload_send_buffer_len_);
1517 payload_send_buffer_.reset();
1518 payload_send_buffer_len_ = 0;
1519 bytes_sent_ = 0;
1520 if (overflow) { // Bug!
1521 LOG(DFATAL) << "overflow";
1522 return ERR_UNEXPECTED;
1524 // Done
1525 return user_write_buf_len_;
1528 // Send the remaining bytes.
1529 return DoPayloadWrite();
1532 int SSLClientSocketWin::DoCompletedRenegotiation(int result) {
1533 // The user had a read in progress, which was usurped by the renegotiation.
1534 // Restart the read sequence.
1535 next_state_ = STATE_COMPLETED_HANDSHAKE;
1536 if (result != OK)
1537 return result;
1538 return DoPayloadRead();
1541 int SSLClientSocketWin::DidCompleteHandshake() {
1542 SECURITY_STATUS status = QueryContextAttributes(
1543 &ctxt_, SECPKG_ATTR_STREAM_SIZES, &stream_sizes_);
1544 if (status != SEC_E_OK) {
1545 LOG(ERROR) << "QueryContextAttributes (stream sizes) failed: " << status;
1546 return MapSecurityError(status);
1548 DCHECK(!server_cert_ || renegotiating_);
1549 PCCERT_CONTEXT server_cert_handle = NULL;
1550 status = QueryContextAttributes(
1551 &ctxt_, SECPKG_ATTR_REMOTE_CERT_CONTEXT, &server_cert_handle);
1552 if (status != SEC_E_OK) {
1553 LOG(ERROR) << "QueryContextAttributes (remote cert) failed: " << status;
1554 return MapSecurityError(status);
1557 X509Certificate::OSCertHandles intermediates;
1558 PCCERT_CONTEXT intermediate = NULL;
1559 // In testing, enumerating the store returned from SChannel appears to
1560 // enumerate certificates in reverse of the order they were added, meaning
1561 // that issuer certificates appear before the subject certificates. This is
1562 // likely because the default Windows memory store is implemented as a
1563 // linked-list. Reverse the list, so that intermediates are ordered from
1564 // subject to issuer.
1565 // Note that the store also includes the end-entity (server) certificate,
1566 // so exclude this certificate from the set of |intermediates|.
1567 while ((intermediate = CertEnumCertificatesInStore(
1568 server_cert_handle->hCertStore, intermediate))) {
1569 if (!X509Certificate::IsSameOSCert(server_cert_handle, intermediate))
1570 intermediates.push_back(CertDuplicateCertificateContext(intermediate));
1572 std::reverse(intermediates.begin(), intermediates.end());
1574 scoped_refptr<X509Certificate> new_server_cert(
1575 X509Certificate::CreateFromHandle(server_cert_handle, intermediates));
1576 net_log_.AddEvent(
1577 NetLog::TYPE_SSL_CERTIFICATES_RECEIVED,
1578 base::Bind(&NetLogX509CertificateCallback,
1579 base::Unretained(new_server_cert.get())));
1580 if (renegotiating_ && IsCertificateChainIdentical(server_cert_,
1581 new_server_cert)) {
1582 // We already verified the server certificate. Either it is good or the
1583 // user has accepted the certificate error.
1584 DidCompleteRenegotiation();
1585 } else {
1586 server_cert_ = new_server_cert;
1587 next_state_ = STATE_VERIFY_CERT;
1589 CertFreeCertificateContext(server_cert_handle);
1590 for (size_t i = 0; i < intermediates.size(); ++i)
1591 CertFreeCertificateContext(intermediates[i]);
1592 return OK;
1595 // Called when a renegotiation is completed. |result| is the verification
1596 // result of the server certificate received during renegotiation.
1597 void SSLClientSocketWin::DidCompleteRenegotiation() {
1598 DCHECK(user_connect_callback_.is_null());
1599 DCHECK(!user_read_callback_.is_null());
1600 renegotiating_ = false;
1601 next_state_ = STATE_COMPLETED_RENEGOTIATION;
1604 void SSLClientSocketWin::LogConnectionTypeMetrics() const {
1605 UpdateConnectionTypeHistograms(CONNECTION_SSL);
1606 if (server_cert_verify_result_.has_md5)
1607 UpdateConnectionTypeHistograms(CONNECTION_SSL_MD5);
1608 if (server_cert_verify_result_.has_md2)
1609 UpdateConnectionTypeHistograms(CONNECTION_SSL_MD2);
1610 if (server_cert_verify_result_.has_md4)
1611 UpdateConnectionTypeHistograms(CONNECTION_SSL_MD4);
1612 if (server_cert_verify_result_.has_md5_ca)
1613 UpdateConnectionTypeHistograms(CONNECTION_SSL_MD5_CA);
1614 if (server_cert_verify_result_.has_md2_ca)
1615 UpdateConnectionTypeHistograms(CONNECTION_SSL_MD2_CA);
1618 void SSLClientSocketWin::FreeSendBuffer() {
1619 SECURITY_STATUS status = FreeContextBuffer(send_buffer_.pvBuffer);
1620 DCHECK(status == SEC_E_OK);
1621 memset(&send_buffer_, 0, sizeof(send_buffer_));
1624 } // namespace net