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. 4 5 #include "net/cert/test_root_certs.h" 6 7 #include <windows.h> 8 #include <wincrypt.h> 9 10 #include "base/basictypes.h" 11 #include "base/lazy_instance.h" 12 #include "base/logging.h" 13 #include "base/win/win_util.h" 14 #include "base/win/windows_version.h" 15 #include "net/cert/x509_certificate.h" 16 17 namespace net { 18 19 namespace { 20 21 // Provides a CertDllOpenStoreProv callback provider function, to be called 22 // by CertOpenStore when the CERT_STORE_PROV_SYSTEM_W store is opened. See 23 // http://msdn.microsoft.com/en-us/library/aa376043(VS.85).aspx. 24 BOOL WINAPI InterceptedOpenStoreW(LPCSTR store_provider, 25 DWORD encoding, 26 HCRYPTPROV crypt_provider, 27 DWORD flags, 28 const void* extra, 29 HCERTSTORE memory_store, 30 PCERT_STORE_PROV_INFO store_info); 31 32 // CryptoAPIInjector is used to inject a store provider function for system 33 // certificate stores before the one provided internally by Crypt32.dll. 34 // Once injected, there is no way to remove, so every call to open a system 35 // store will be redirected to the injected function. 36 struct CryptoAPIInjector { 37 // The previous default function for opening system stores. For most 38 // configurations, this should point to Crypt32's internal 39 // I_CertDllOpenSystemStoreProvW function. 40 PFN_CERT_DLL_OPEN_STORE_PROV_FUNC original_function; 41 42 // The handle that CryptoAPI uses to ensure the DLL implementing 43 // |original_function| remains loaded in memory. 44 HCRYPTOIDFUNCADDR original_handle; 45 46 private: 47 friend struct base::DefaultLazyInstanceTraits<CryptoAPIInjector>; 48 49 CryptoAPIInjector() 50 : original_function(NULL), 51 original_handle(NULL) { 52 HCRYPTOIDFUNCSET registered_functions = 53 CryptInitOIDFunctionSet(CRYPT_OID_OPEN_STORE_PROV_FUNC, 0); 54 55 // Preserve the original handler function in |original_function|. If other 56 // functions are overridden, they will also need to be preserved. 57 BOOL ok = CryptGetOIDFunctionAddress( 58 registered_functions, 0, CERT_STORE_PROV_SYSTEM_W, 0, 59 reinterpret_cast<void**>(&original_function), &original_handle); 60 DCHECK(ok); 61 62 // For now, intercept only the numeric form of the system store 63 // function, CERT_STORE_PROV_SYSTEM_W (0x0A), which is what Crypt32 64 // functionality uses exclusively. Depending on the machine that tests 65 // are being run on, it may prove necessary to also intercept 66 // sz_CERT_STORE_PROV_SYSTEM_[A/W] and CERT_STORE_PROV_SYSTEM_A, based 67 // on whether or not any third-party CryptoAPI modules have been 68 // installed. 69 const CRYPT_OID_FUNC_ENTRY kFunctionToIntercept = 70 { CERT_STORE_PROV_SYSTEM_W, &InterceptedOpenStoreW }; 71 72 // Inject kFunctionToIntercept at the front of the linked list that 73 // crypt32 uses when CertOpenStore is called, replacing the existing 74 // registered function. 75 ok = CryptInstallOIDFunctionAddress(NULL, 0, 76 CRYPT_OID_OPEN_STORE_PROV_FUNC, 1, 77 &kFunctionToIntercept, 78 CRYPT_INSTALL_OID_FUNC_BEFORE_FLAG); 79 DCHECK(ok); 80 } 81 82 // This is never called, because this object is intentionally leaked. 83 // Certificate verification happens on a non-joinable worker thread, which 84 // may still be running when ~AtExitManager is called, so the LazyInstance 85 // must be leaky. 86 ~CryptoAPIInjector() { 87 original_function = NULL; 88 CryptFreeOIDFunctionAddress(original_handle, NULL); 89 } 90 }; 91 92 base::LazyInstance<CryptoAPIInjector>::Leaky 93 g_capi_injector = LAZY_INSTANCE_INITIALIZER; 94 95 BOOL WINAPI InterceptedOpenStoreW(LPCSTR store_provider, 96 DWORD encoding, 97 HCRYPTPROV crypt_provider, 98 DWORD flags, 99 const void* store_name, 100 HCERTSTORE memory_store, 101 PCERT_STORE_PROV_INFO store_info) { 102 // If the high word is all zeroes, then |store_provider| is a numeric ID. 103 // Otherwise, it's a pointer to a null-terminated ASCII string. See the 104 // documentation for CryptGetOIDFunctionAddress for more information. 105 uint32 store_as_uint = reinterpret_cast<uint32>(store_provider); 106 if (store_as_uint > 0xFFFF || store_provider != CERT_STORE_PROV_SYSTEM_W || 107 !g_capi_injector.Get().original_function) 108 return FALSE; 109 110 BOOL ok = g_capi_injector.Get().original_function(store_provider, encoding, 111 crypt_provider, flags, 112 store_name, memory_store, 113 store_info); 114 // Only the Root store should have certificates injected. If 115 // CERT_SYSTEM_STORE_RELOCATE_FLAG is set, then |store_name| points to a 116 // CERT_SYSTEM_STORE_RELOCATE_PARA structure, rather than a 117 // NULL-terminated wide string, so check before making a string 118 // comparison. 119 if (!ok || TestRootCerts::GetInstance()->IsEmpty() || 120 (flags & CERT_SYSTEM_STORE_RELOCATE_FLAG) || 121 lstrcmpiW(reinterpret_cast<LPCWSTR>(store_name), L"root")) 122 return ok; 123 124 // The result of CertOpenStore with CERT_STORE_PROV_SYSTEM_W is documented 125 // to be a collection store, and that appears to hold for |memory_store|. 126 // Attempting to add an individual certificate to |memory_store| causes 127 // the request to be forwarded to the first physical store in the 128 // collection that accepts modifications, which will cause a secure 129 // confirmation dialog to be displayed, confirming the user wishes to 130 // trust the certificate. However, appending a store to the collection 131 // will merely modify the temporary collection store, and will not persist 132 // any changes to the underlying physical store. When the |memory_store| is 133 // searched to see if a certificate is in the Root store, all the 134 // underlying stores in the collection will be searched, and any certificate 135 // in temporary_roots() will be found and seen as trusted. 136 return CertAddStoreToCollection( 137 memory_store, TestRootCerts::GetInstance()->temporary_roots(), 0, 0); 138 } 139 140 } // namespace 141 142 bool TestRootCerts::Add(X509Certificate* certificate) { 143 // Ensure that the default CryptoAPI functionality has been intercepted. 144 // If a test certificate is never added, then no interception should 145 // happen. 146 g_capi_injector.Get(); 147 148 BOOL ok = CertAddCertificateContextToStore( 149 temporary_roots_, certificate->os_cert_handle(), 150 CERT_STORE_ADD_NEW, NULL); 151 if (!ok) { 152 // If the certificate is already added, return successfully. 153 return GetLastError() == CRYPT_E_EXISTS; 154 } 155 156 empty_ = false; 157 return true; 158 } 159 160 void TestRootCerts::Clear() { 161 empty_ = true; 162 163 PCCERT_CONTEXT prev_cert = NULL; 164 while (prev_cert = CertEnumCertificatesInStore(temporary_roots_, NULL)) 165 CertDeleteCertificateFromStore(prev_cert); 166 } 167 168 bool TestRootCerts::IsEmpty() const { 169 return empty_; 170 } 171 172 HCERTCHAINENGINE TestRootCerts::GetChainEngine() const { 173 if (IsEmpty()) 174 return NULL; // Default chain engine will suffice. 175 176 // Windows versions before 7 don't accept the struct size for later versions. 177 // We report the size of the old struct since we don't need the new members. 178 static const DWORD kSizeofCertChainEngineConfig = 179 SIZEOF_STRUCT_WITH_SPECIFIED_LAST_MEMBER( 180 CERT_CHAIN_ENGINE_CONFIG, CycleDetectionModulus); 181 182 // Each HCERTCHAINENGINE caches both the configured system stores and 183 // information about each chain that has been built. In order to ensure 184 // that changes to |temporary_roots_| are properly propagated and that the 185 // various caches are flushed, when at least one certificate is added, 186 // return a new chain engine for every call. Each chain engine creation 187 // should re-open the root store, ensuring the most recent changes are 188 // visible. 189 CERT_CHAIN_ENGINE_CONFIG engine_config = { 190 kSizeofCertChainEngineConfig 191 }; 192 engine_config.dwFlags = 193 CERT_CHAIN_ENABLE_CACHE_AUTO_UPDATE | 194 CERT_CHAIN_ENABLE_SHARE_STORE; 195 HCERTCHAINENGINE chain_engine = NULL; 196 BOOL ok = CertCreateCertificateChainEngine(&engine_config, &chain_engine); 197 DCHECK(ok); 198 return chain_engine; 199 } 200 201 TestRootCerts::~TestRootCerts() { 202 CertCloseStore(temporary_roots_, 0); 203 } 204 205 void TestRootCerts::Init() { 206 empty_ = true; 207 temporary_roots_ = CertOpenStore( 208 CERT_STORE_PROV_MEMORY, 0, NULL, 209 CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG, NULL); 210 DCHECK(temporary_roots_); 211 } 212 213 } // namespace net 214