client_cert_store_win.cc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. // Copyright 2013 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.
  4. #include "net/ssl/client_cert_store_win.h"
  5. #include <algorithm>
  6. #include <functional>
  7. #include <memory>
  8. #include <string>
  9. #define SECURITY_WIN32 // Needs to be defined before including security.h
  10. #include <windows.h>
  11. #include <security.h>
  12. #include "base/bind.h"
  13. #include "base/callback.h"
  14. #include "base/callback_helpers.h"
  15. #include "base/logging.h"
  16. #include "base/numerics/safe_conversions.h"
  17. #include "base/scoped_generic.h"
  18. #include "base/task/single_thread_task_runner.h"
  19. #include "base/task/task_runner_util.h"
  20. #include "base/threading/thread_task_runner_handle.h"
  21. #include "base/win/wincrypt_shim.h"
  22. #include "net/cert/x509_util.h"
  23. #include "net/cert/x509_util_win.h"
  24. #include "net/ssl/ssl_platform_key_util.h"
  25. #include "net/ssl/ssl_platform_key_win.h"
  26. #include "net/ssl/ssl_private_key.h"
  27. #include "third_party/boringssl/src/include/openssl/pool.h"
  28. namespace net {
  29. namespace {
  30. using ScopedHCERTSTOREWithChecks = base::ScopedGeneric<
  31. HCERTSTORE,
  32. crypto::CAPITraitsWithFlags<HCERTSTORE,
  33. CertCloseStore,
  34. CERT_CLOSE_STORE_CHECK_FLAG>>;
  35. class ClientCertIdentityWin : public ClientCertIdentity {
  36. public:
  37. ClientCertIdentityWin(
  38. scoped_refptr<net::X509Certificate> cert,
  39. crypto::ScopedPCCERT_CONTEXT cert_context,
  40. scoped_refptr<base::SingleThreadTaskRunner> key_task_runner)
  41. : ClientCertIdentity(std::move(cert)),
  42. cert_context_(std::move(cert_context)),
  43. key_task_runner_(std::move(key_task_runner)) {}
  44. void AcquirePrivateKey(base::OnceCallback<void(scoped_refptr<SSLPrivateKey>)>
  45. private_key_callback) override {
  46. base::PostTaskAndReplyWithResult(
  47. key_task_runner_.get(), FROM_HERE,
  48. base::BindOnce(&FetchClientCertPrivateKey,
  49. base::Unretained(certificate()), cert_context_.get()),
  50. std::move(private_key_callback));
  51. }
  52. private:
  53. crypto::ScopedPCCERT_CONTEXT cert_context_;
  54. scoped_refptr<base::SingleThreadTaskRunner> key_task_runner_;
  55. };
  56. // Callback required by Windows API function CertFindChainInStore(). In addition
  57. // to filtering by extended/enhanced key usage, we do not show expired
  58. // certificates and require digital signature usage in the key usage extension.
  59. //
  60. // This matches our behavior on Mac OS X and that of NSS. It also matches the
  61. // default behavior of IE8. See http://support.microsoft.com/kb/890326 and
  62. // http://blogs.msdn.com/b/askie/archive/2009/06/09/my-expired-client-certifica
  63. // tes-no-longer-display-when-connecting-to-my-web-server-using-ie8.aspx
  64. static BOOL WINAPI ClientCertFindCallback(PCCERT_CONTEXT cert_context,
  65. void* find_arg) {
  66. // Verify the certificate key usage is appropriate or not specified.
  67. BYTE key_usage;
  68. if (CertGetIntendedKeyUsage(X509_ASN_ENCODING, cert_context->pCertInfo,
  69. &key_usage, 1)) {
  70. if (!(key_usage & CERT_DIGITAL_SIGNATURE_KEY_USAGE))
  71. return FALSE;
  72. } else {
  73. DWORD err = GetLastError();
  74. // If |err| is non-zero, it's an actual error. Otherwise the extension
  75. // just isn't present, and we treat it as if everything was allowed.
  76. if (err) {
  77. DLOG(ERROR) << "CertGetIntendedKeyUsage failed: " << err;
  78. return FALSE;
  79. }
  80. }
  81. // Verify the current time is within the certificate's validity period.
  82. if (CertVerifyTimeValidity(nullptr, cert_context->pCertInfo) != 0)
  83. return FALSE;
  84. // Verify private key metadata is associated with this certificate.
  85. // TODO(ppi): Is this really needed? Isn't it equivalent to leaving
  86. // CERT_CHAIN_FIND_BY_ISSUER_NO_KEY_FLAG not set in |find_flags| argument of
  87. // CertFindChainInStore()?
  88. DWORD size = 0;
  89. if (!CertGetCertificateContextProperty(
  90. cert_context, CERT_KEY_PROV_INFO_PROP_ID, nullptr, &size)) {
  91. return FALSE;
  92. }
  93. return TRUE;
  94. }
  95. ClientCertIdentityList GetClientCertsImpl(HCERTSTORE cert_store,
  96. const SSLCertRequestInfo& request) {
  97. ClientCertIdentityList selected_identities;
  98. scoped_refptr<base::SingleThreadTaskRunner> current_thread =
  99. base::ThreadTaskRunnerHandle::Get();
  100. const size_t auth_count = request.cert_authorities.size();
  101. std::vector<CERT_NAME_BLOB> issuers(auth_count);
  102. for (size_t i = 0; i < auth_count; ++i) {
  103. issuers[i].cbData = static_cast<DWORD>(request.cert_authorities[i].size());
  104. issuers[i].pbData = reinterpret_cast<BYTE*>(
  105. const_cast<char*>(request.cert_authorities[i].data()));
  106. }
  107. // Enumerate the client certificates.
  108. CERT_CHAIN_FIND_BY_ISSUER_PARA find_by_issuer_para;
  109. memset(&find_by_issuer_para, 0, sizeof(find_by_issuer_para));
  110. find_by_issuer_para.cbSize = sizeof(find_by_issuer_para);
  111. find_by_issuer_para.pszUsageIdentifier = szOID_PKIX_KP_CLIENT_AUTH;
  112. find_by_issuer_para.cIssuer = static_cast<DWORD>(auth_count);
  113. find_by_issuer_para.rgIssuer =
  114. reinterpret_cast<CERT_NAME_BLOB*>(issuers.data());
  115. find_by_issuer_para.pfnFindCallback = ClientCertFindCallback;
  116. PCCERT_CHAIN_CONTEXT chain_context = nullptr;
  117. DWORD find_flags = CERT_CHAIN_FIND_BY_ISSUER_CACHE_ONLY_FLAG |
  118. CERT_CHAIN_FIND_BY_ISSUER_CACHE_ONLY_URL_FLAG;
  119. for (;;) {
  120. // Find a certificate chain.
  121. chain_context = CertFindChainInStore(cert_store,
  122. X509_ASN_ENCODING,
  123. find_flags,
  124. CERT_CHAIN_FIND_BY_ISSUER,
  125. &find_by_issuer_para,
  126. chain_context);
  127. if (!chain_context) {
  128. if (GetLastError() != static_cast<DWORD>(CRYPT_E_NOT_FOUND))
  129. DPLOG(ERROR) << "CertFindChainInStore failed: ";
  130. break;
  131. }
  132. // Get the leaf certificate.
  133. PCCERT_CONTEXT cert_context =
  134. chain_context->rgpChain[0]->rgpElement[0]->pCertContext;
  135. // Copy the certificate, so that it is valid after |cert_store| is closed.
  136. crypto::ScopedPCCERT_CONTEXT cert_context2;
  137. PCCERT_CONTEXT raw = nullptr;
  138. BOOL ok = CertAddCertificateContextToStore(
  139. nullptr, cert_context, CERT_STORE_ADD_USE_EXISTING, &raw);
  140. if (!ok) {
  141. NOTREACHED();
  142. continue;
  143. }
  144. cert_context2.reset(raw);
  145. // Grab the intermediates, if any.
  146. std::vector<crypto::ScopedPCCERT_CONTEXT> intermediates_storage;
  147. std::vector<PCCERT_CONTEXT> intermediates;
  148. for (DWORD i = 1; i < chain_context->rgpChain[0]->cElement; ++i) {
  149. PCCERT_CONTEXT chain_intermediate =
  150. chain_context->rgpChain[0]->rgpElement[i]->pCertContext;
  151. PCCERT_CONTEXT copied_intermediate = nullptr;
  152. ok = CertAddCertificateContextToStore(nullptr, chain_intermediate,
  153. CERT_STORE_ADD_USE_EXISTING,
  154. &copied_intermediate);
  155. if (ok) {
  156. intermediates.push_back(copied_intermediate);
  157. intermediates_storage.emplace_back(copied_intermediate);
  158. }
  159. }
  160. // Drop the self-signed root, if any. Match Internet Explorer in not sending
  161. // it. Although the root's signature is irrelevant for authentication, some
  162. // servers reject chains if the root is explicitly sent and has a weak
  163. // signature algorithm. See https://crbug.com/607264.
  164. //
  165. // The leaf or a intermediate may also have a weak signature algorithm but,
  166. // in that case, assume it is a configuration error.
  167. if (!intermediates.empty() &&
  168. x509_util::IsSelfSigned(intermediates.back())) {
  169. intermediates.pop_back();
  170. intermediates_storage.pop_back();
  171. }
  172. // Allow UTF-8 inside PrintableStrings in client certificates. See
  173. // crbug.com/770323.
  174. X509Certificate::UnsafeCreateOptions options;
  175. options.printable_string_is_utf8 = true;
  176. scoped_refptr<X509Certificate> cert =
  177. x509_util::CreateX509CertificateFromCertContexts(
  178. cert_context2.get(), intermediates, options);
  179. if (cert) {
  180. selected_identities.push_back(std::make_unique<ClientCertIdentityWin>(
  181. std::move(cert),
  182. std::move(cert_context2), // Takes ownership of |cert_context2|.
  183. current_thread)); // The key must be acquired on the same thread, as
  184. // the PCCERT_CONTEXT may not be thread safe.
  185. }
  186. }
  187. std::sort(selected_identities.begin(), selected_identities.end(),
  188. ClientCertIdentitySorter());
  189. return selected_identities;
  190. }
  191. } // namespace
  192. ClientCertStoreWin::ClientCertStoreWin() = default;
  193. ClientCertStoreWin::ClientCertStoreWin(
  194. base::RepeatingCallback<crypto::ScopedHCERTSTORE()> cert_store_callback)
  195. : cert_store_callback_(std::move(cert_store_callback)) {
  196. DCHECK(!cert_store_callback_.is_null());
  197. }
  198. ClientCertStoreWin::~ClientCertStoreWin() = default;
  199. void ClientCertStoreWin::GetClientCerts(const SSLCertRequestInfo& request,
  200. ClientCertListCallback callback) {
  201. base::PostTaskAndReplyWithResult(
  202. GetSSLPlatformKeyTaskRunner().get(), FROM_HERE,
  203. // Caller is responsible for keeping the |request| alive
  204. // until the callback is run, so std::cref is safe.
  205. base::BindOnce(&ClientCertStoreWin::GetClientCertsWithCertStore,
  206. std::cref(request), cert_store_callback_),
  207. std::move(callback));
  208. }
  209. // static
  210. ClientCertIdentityList ClientCertStoreWin::GetClientCertsWithCertStore(
  211. const SSLCertRequestInfo& request,
  212. const base::RepeatingCallback<crypto::ScopedHCERTSTORE()>&
  213. cert_store_callback) {
  214. ScopedHCERTSTOREWithChecks cert_store;
  215. if (cert_store_callback.is_null()) {
  216. // Always open a new instance of the "MY" store, to ensure that there
  217. // are no previously cached certificates being reused after they're
  218. // no longer available (some smartcard providers fail to update the "MY"
  219. // store handles and instead interpose CertOpenSystemStore). To help confirm
  220. // this, use `ScopedHCERTSTOREWithChecks` and `CERT_CLOSE_STORE_CHECK_FLAG`
  221. // to DCHECK that `cert_store` is not inadvertently ref-counted.
  222. cert_store.reset(CertOpenSystemStore(NULL, L"MY"));
  223. } else {
  224. cert_store.reset(cert_store_callback.Run().release());
  225. }
  226. if (!cert_store.is_valid()) {
  227. PLOG(ERROR) << "Could not open certificate store: ";
  228. return ClientCertIdentityList();
  229. }
  230. return GetClientCertsImpl(cert_store.get(), request);
  231. }
  232. bool ClientCertStoreWin::SelectClientCertsForTesting(
  233. const CertificateList& input_certs,
  234. const SSLCertRequestInfo& request,
  235. ClientCertIdentityList* selected_identities) {
  236. ScopedHCERTSTOREWithChecks test_store(
  237. CertOpenStore(CERT_STORE_PROV_MEMORY, 0, NULL, 0, nullptr));
  238. if (!test_store.is_valid())
  239. return false;
  240. // Add available certificates to the test store.
  241. for (const auto& input_cert : input_certs) {
  242. // Add the certificate to the test store.
  243. PCCERT_CONTEXT cert = nullptr;
  244. if (!CertAddEncodedCertificateToStore(
  245. test_store.get(), X509_ASN_ENCODING,
  246. reinterpret_cast<const BYTE*>(
  247. CRYPTO_BUFFER_data(input_cert->cert_buffer())),
  248. base::checked_cast<DWORD>(
  249. CRYPTO_BUFFER_len(input_cert->cert_buffer())),
  250. CERT_STORE_ADD_NEW, &cert)) {
  251. return false;
  252. }
  253. // Hold the reference to the certificate (since we requested a copy).
  254. crypto::ScopedPCCERT_CONTEXT scoped_cert(cert);
  255. // Add dummy private key data to the certificate - otherwise the certificate
  256. // would be discarded by the filtering routines.
  257. CRYPT_KEY_PROV_INFO private_key_data;
  258. memset(&private_key_data, 0, sizeof(private_key_data));
  259. if (!CertSetCertificateContextProperty(cert,
  260. CERT_KEY_PROV_INFO_PROP_ID,
  261. 0, &private_key_data)) {
  262. return false;
  263. }
  264. }
  265. *selected_identities = GetClientCertsImpl(test_store.get(), request);
  266. return true;
  267. }
  268. } // namespace net