1 // Copyright 2012 The Chromium Authors
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 "crypto/scoped_capi_types.h"
6 #include "net/cert/test_root_certs.h"
7
8 #include <stdint.h>
9
10 #include "base/check.h"
11 #include "base/lazy_instance.h"
12 #include "base/numerics/safe_conversions.h"
13 #include "base/win/win_util.h"
14 #include "net/cert/x509_certificate.h"
15 #include "third_party/boringssl/src/include/openssl/pool.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::LazyInstanceTraitsBase<CryptoAPIInjector>;
48
CryptoAPIInjectornet::__anon62ee99870111::CryptoAPIInjector49 CryptoAPIInjector() : original_function(nullptr), original_handle(nullptr) {
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,
69 reinterpret_cast<void*>(&InterceptedOpenStoreW)};
70
71 // Inject kFunctionToIntercept at the front of the linked list that
72 // crypt32 uses when CertOpenStore is called, replacing the existing
73 // registered function.
74 ok = CryptInstallOIDFunctionAddress(
75 nullptr, 0, CRYPT_OID_OPEN_STORE_PROV_FUNC, 1, &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.
~CryptoAPIInjectornet::__anon62ee99870111::CryptoAPIInjector84 ~CryptoAPIInjector() {
85 original_function = nullptr;
86 CryptFreeOIDFunctionAddress(original_handle, NULL);
87 }
88 };
89
90 base::LazyInstance<CryptoAPIInjector>::Leaky
91 g_capi_injector = LAZY_INSTANCE_INITIALIZER;
92
InterceptedOpenStoreW(LPCSTR store_provider,DWORD encoding,HCRYPTPROV crypt_provider,DWORD flags,const void * store_name,HCERTSTORE memory_store,PCERT_STORE_PROV_INFO store_info)93 BOOL WINAPI InterceptedOpenStoreW(LPCSTR store_provider,
94 DWORD encoding,
95 HCRYPTPROV crypt_provider,
96 DWORD flags,
97 const void* store_name,
98 HCERTSTORE memory_store,
99 PCERT_STORE_PROV_INFO store_info) {
100 // If the high word is all zeroes, then |store_provider| is a numeric ID.
101 // Otherwise, it's a pointer to a null-terminated ASCII string. See the
102 // documentation for CryptGetOIDFunctionAddress for more information.
103 uintptr_t store_as_uintptr = reinterpret_cast<uintptr_t>(store_provider);
104 if (store_as_uintptr > 0xFFFF || store_provider != CERT_STORE_PROV_SYSTEM_W ||
105 !g_capi_injector.Get().original_function)
106 return FALSE;
107
108 BOOL ok = g_capi_injector.Get().original_function(store_provider, encoding,
109 crypt_provider, flags,
110 store_name, memory_store,
111 store_info);
112 // Only the Root store should have certificates injected. If
113 // CERT_SYSTEM_STORE_RELOCATE_FLAG is set, then |store_name| points to a
114 // CERT_SYSTEM_STORE_RELOCATE_PARA structure, rather than a
115 // NULL-terminated wide string, so check before making a string
116 // comparison.
117 if (!ok || TestRootCerts::GetInstance()->IsEmpty() ||
118 (flags & CERT_SYSTEM_STORE_RELOCATE_FLAG) ||
119 lstrcmpiW(reinterpret_cast<LPCWSTR>(store_name), L"root"))
120 return ok;
121
122 // The result of CertOpenStore with CERT_STORE_PROV_SYSTEM_W is documented
123 // to be a collection store, and that appears to hold for |memory_store|.
124 // Attempting to add an individual certificate to |memory_store| causes
125 // the request to be forwarded to the first physical store in the
126 // collection that accepts modifications, which will cause a secure
127 // confirmation dialog to be displayed, confirming the user wishes to
128 // trust the certificate. However, appending a store to the collection
129 // will merely modify the temporary collection store, and will not persist
130 // any changes to the underlying physical store. When the |memory_store| is
131 // searched to see if a certificate is in the Root store, all the
132 // underlying stores in the collection will be searched, and any certificate
133 // in temporary_roots() will be found and seen as trusted.
134 return CertAddStoreToCollection(
135 memory_store, TestRootCerts::GetInstance()->temporary_roots(), 0, 0);
136 }
137
138 } // namespace
139
AddImpl(X509Certificate * certificate)140 bool TestRootCerts::AddImpl(X509Certificate* certificate) {
141 // Ensure that the default CryptoAPI functionality has been intercepted.
142 // If a test certificate is never added, then no interception should
143 // happen.
144 g_capi_injector.Get();
145
146 BOOL ok = CertAddEncodedCertificateToStore(
147 temporary_roots_, X509_ASN_ENCODING,
148 reinterpret_cast<const BYTE*>(
149 CRYPTO_BUFFER_data(certificate->cert_buffer())),
150 base::checked_cast<DWORD>(CRYPTO_BUFFER_len(certificate->cert_buffer())),
151 CERT_STORE_ADD_NEW, nullptr);
152 if (!ok) {
153 // If the certificate is already added, return successfully.
154 return GetLastError() == static_cast<DWORD>(CRYPT_E_EXISTS);
155 }
156
157 return true;
158 }
159
ClearImpl()160 void TestRootCerts::ClearImpl() {
161 for (PCCERT_CONTEXT prev_cert =
162 CertEnumCertificatesInStore(temporary_roots_, nullptr);
163 prev_cert;
164 prev_cert = CertEnumCertificatesInStore(temporary_roots_, nullptr))
165 CertDeleteCertificateFromStore(prev_cert);
166 }
167
GetChainEngine() const168 crypto::ScopedHCERTCHAINENGINE TestRootCerts::GetChainEngine() const {
169 if (IsEmpty()) {
170 // Default chain engine will suffice.
171 return crypto::ScopedHCERTCHAINENGINE();
172 }
173
174 // Windows versions before 8 don't accept the struct size for later versions.
175 // We report the size of the old struct since we don't need the new members.
176 static const DWORD kSizeofCertChainEngineConfig =
177 SIZEOF_STRUCT_WITH_SPECIFIED_LAST_MEMBER(CERT_CHAIN_ENGINE_CONFIG,
178 hExclusiveTrustedPeople);
179
180 // Each HCERTCHAINENGINE caches both the configured system stores and
181 // information about each chain that has been built. In order to ensure
182 // that changes to |temporary_roots_| are properly propagated and that the
183 // various caches are flushed, when at least one certificate is added,
184 // return a new chain engine for every call. Each chain engine creation
185 // should re-open the root store, ensuring the most recent changes are
186 // visible.
187 CERT_CHAIN_ENGINE_CONFIG engine_config = {
188 kSizeofCertChainEngineConfig
189 };
190 engine_config.dwFlags =
191 CERT_CHAIN_ENABLE_CACHE_AUTO_UPDATE |
192 CERT_CHAIN_ENABLE_SHARE_STORE;
193 crypto::ScopedHCERTCHAINENGINE chain_engine;
194 BOOL ok = CertCreateCertificateChainEngine(
195 &engine_config,
196 crypto::ScopedHCERTCHAINENGINE::Receiver(chain_engine).get());
197 DCHECK(ok);
198 return chain_engine;
199 }
200
~TestRootCerts()201 TestRootCerts::~TestRootCerts() {
202 CertCloseStore(temporary_roots_, 0);
203 }
204
Init()205 void TestRootCerts::Init() {
206 temporary_roots_ =
207 CertOpenStore(CERT_STORE_PROV_MEMORY, 0, NULL,
208 CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG, nullptr);
209 DCHECK(temporary_roots_);
210 }
211
212 } // namespace net
213