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