Home | History | Annotate | Download | only in cert
      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   for (PCCERT_CONTEXT prev_cert =
    164            CertEnumCertificatesInStore(temporary_roots_, NULL);
    165        prev_cert;
    166        prev_cert = CertEnumCertificatesInStore(temporary_roots_, NULL))
    167     CertDeleteCertificateFromStore(prev_cert);
    168 }
    169 
    170 bool TestRootCerts::IsEmpty() const {
    171   return empty_;
    172 }
    173 
    174 HCERTCHAINENGINE TestRootCerts::GetChainEngine() const {
    175   if (IsEmpty())
    176     return NULL;  // Default chain engine will suffice.
    177 
    178   // Windows versions before 7 don't accept the struct size for later versions.
    179   // We report the size of the old struct since we don't need the new members.
    180   static const DWORD kSizeofCertChainEngineConfig =
    181       SIZEOF_STRUCT_WITH_SPECIFIED_LAST_MEMBER(
    182           CERT_CHAIN_ENGINE_CONFIG, CycleDetectionModulus);
    183 
    184   // Each HCERTCHAINENGINE caches both the configured system stores and
    185   // information about each chain that has been built. In order to ensure
    186   // that changes to |temporary_roots_| are properly propagated and that the
    187   // various caches are flushed, when at least one certificate is added,
    188   // return a new chain engine for every call. Each chain engine creation
    189   // should re-open the root store, ensuring the most recent changes are
    190   // visible.
    191   CERT_CHAIN_ENGINE_CONFIG engine_config = {
    192     kSizeofCertChainEngineConfig
    193   };
    194   engine_config.dwFlags =
    195       CERT_CHAIN_ENABLE_CACHE_AUTO_UPDATE |
    196       CERT_CHAIN_ENABLE_SHARE_STORE;
    197   HCERTCHAINENGINE chain_engine = NULL;
    198   BOOL ok = CertCreateCertificateChainEngine(&engine_config, &chain_engine);
    199   DCHECK(ok);
    200   return chain_engine;
    201 }
    202 
    203 TestRootCerts::~TestRootCerts() {
    204   CertCloseStore(temporary_roots_, 0);
    205 }
    206 
    207 void TestRootCerts::Init() {
    208   empty_ = true;
    209   temporary_roots_ = CertOpenStore(
    210       CERT_STORE_PROV_MEMORY, 0, NULL,
    211       CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG, NULL);
    212   DCHECK(temporary_roots_);
    213 }
    214 
    215 }  // namespace net
    216