1 | /* $Id: SUPHardenedVerifyImage-win.cpp 52453 2014-08-22 06:42:01Z vboxsync $ */
|
---|
2 | /** @file
|
---|
3 | * VirtualBox Support Library/Driver - Hardened Image Verification, Windows.
|
---|
4 | */
|
---|
5 |
|
---|
6 | /*
|
---|
7 | * Copyright (C) 2006-2014 Oracle Corporation
|
---|
8 | *
|
---|
9 | * This file is part of VirtualBox Open Source Edition (OSE), as
|
---|
10 | * available from http://www.virtualbox.org. This file is free software;
|
---|
11 | * you can redistribute it and/or modify it under the terms of the GNU
|
---|
12 | * General Public License (GPL) as published by the Free Software
|
---|
13 | * Foundation, in version 2 as it comes in the "COPYING" file of the
|
---|
14 | * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
|
---|
15 | * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
|
---|
16 | *
|
---|
17 | * The contents of this file may alternatively be used under the terms
|
---|
18 | * of the Common Development and Distribution License Version 1.0
|
---|
19 | * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
|
---|
20 | * VirtualBox OSE distribution, in which case the provisions of the
|
---|
21 | * CDDL are applicable instead of those of the GPL.
|
---|
22 | *
|
---|
23 | * You may elect to license modified versions of this file under the
|
---|
24 | * terms and conditions of either the GPL or the CDDL or both.
|
---|
25 | */
|
---|
26 |
|
---|
27 | /*******************************************************************************
|
---|
28 | * Header Files *
|
---|
29 | *******************************************************************************/
|
---|
30 | #ifdef IN_RING0
|
---|
31 | # define IPRT_NT_MAP_TO_ZW
|
---|
32 | # include <iprt/nt/nt.h>
|
---|
33 | # include <ntimage.h>
|
---|
34 | #else
|
---|
35 | # include <iprt/nt/nt-and-windows.h>
|
---|
36 | # include "Wintrust.h"
|
---|
37 | # include "Softpub.h"
|
---|
38 | # include "mscat.h"
|
---|
39 | # ifndef LOAD_LIBRARY_SEARCH_APPLICATION_DIR
|
---|
40 | # define LOAD_LIBRARY_SEARCH_SYSTEM32 0x800
|
---|
41 | # endif
|
---|
42 | #endif
|
---|
43 |
|
---|
44 | #include <VBox/sup.h>
|
---|
45 | #include <VBox/err.h>
|
---|
46 | #include <iprt/ctype.h>
|
---|
47 | #include <iprt/ldr.h>
|
---|
48 | #include <iprt/log.h>
|
---|
49 | #include <iprt/path.h>
|
---|
50 | #include <iprt/string.h>
|
---|
51 | #include <iprt/crypto/pkcs7.h>
|
---|
52 | #include <iprt/crypto/store.h>
|
---|
53 |
|
---|
54 | #ifdef IN_RING0
|
---|
55 | # include "SUPDrvInternal.h"
|
---|
56 | #else
|
---|
57 | # include "SUPLibInternal.h"
|
---|
58 | #endif
|
---|
59 | #include "win/SUPHardenedVerify-win.h"
|
---|
60 |
|
---|
61 |
|
---|
62 | /*******************************************************************************
|
---|
63 | * Defined Constants And Macros *
|
---|
64 | *******************************************************************************/
|
---|
65 | /** The size of static hash (output) buffers.
|
---|
66 | * Avoids dynamic allocations and cleanups for of small buffers as well as extra
|
---|
67 | * calls for getting the appropriate buffer size. The largest digest in regular
|
---|
68 | * use by current windows version is SHA-512, we double this and hope it's
|
---|
69 | * enough a good while. */
|
---|
70 | #define SUPHARDNTVI_MAX_CAT_HASH_SIZE 128
|
---|
71 |
|
---|
72 |
|
---|
73 | #if defined(VBOX_PERMIT_EVEN_MORE) && !defined(VBOX_PERMIT_MORE)
|
---|
74 | # error "VBOX_PERMIT_EVEN_MORE without VBOX_PERMIT_MORE!"
|
---|
75 | #endif
|
---|
76 |
|
---|
77 |
|
---|
78 | /*******************************************************************************
|
---|
79 | * Structures and Typedefs *
|
---|
80 | *******************************************************************************/
|
---|
81 |
|
---|
82 | #ifdef IN_RING3
|
---|
83 | typedef LONG (WINAPI * PFNWINVERIFYTRUST)(HWND hwnd, GUID const *pgActionID, PVOID pWVTData);
|
---|
84 | typedef BOOL (WINAPI * PFNCRYPTCATADMINACQUIRECONTEXT)(HCATADMIN *phCatAdmin, const GUID *pGuidSubsystem, DWORD dwFlags);
|
---|
85 | typedef BOOL (WINAPI * PFNCRYPTCATADMINACQUIRECONTEXT2)(HCATADMIN *phCatAdmin, const GUID *pGuidSubsystem, PCWSTR pwszHashAlgorithm,
|
---|
86 | struct _CERT_STRONG_SIGN_PARA const *pStrongHashPolicy, DWORD dwFlags);
|
---|
87 | typedef BOOL (WINAPI * PFNCRYPTCATADMINCALCHASHFROMFILEHANDLE)(HANDLE hFile, DWORD *pcbHash, BYTE *pbHash, DWORD dwFlags);
|
---|
88 | typedef BOOL (WINAPI * PFNCRYPTCATADMINCALCHASHFROMFILEHANDLE2)(HCATADMIN hCatAdmin, HANDLE hFile, DWORD *pcbHash,
|
---|
89 | BYTE *pbHash, DWORD dwFlags);
|
---|
90 | typedef HCATINFO (WINAPI *PFNCRYPTCATADMINENUMCATALOGFROMHASH)(HCATADMIN hCatAdmin, BYTE *pbHash, DWORD cbHash,
|
---|
91 | DWORD dwFlags, HCATINFO *phPrevCatInfo);
|
---|
92 | typedef BOOL (WINAPI * PFNCRYPTCATADMINRELEASECATALOGCONTEXT)(HCATADMIN hCatAdmin, HCATINFO hCatInfo, DWORD dwFlags);
|
---|
93 | typedef BOOL (WINAPI * PFNCRYPTCATDADMINRELEASECONTEXT)(HCATADMIN hCatAdmin, DWORD dwFlags);
|
---|
94 | typedef BOOL (WINAPI * PFNCRYPTCATCATALOGINFOFROMCONTEXT)(HCATINFO hCatInfo, CATALOG_INFO *psCatInfo, DWORD dwFlags);
|
---|
95 |
|
---|
96 | typedef HCERTSTORE (WINAPI *PFNCERTOPENSTORE)(PCSTR pszStoreProvider, DWORD dwEncodingType, HCRYPTPROV_LEGACY hCryptProv,
|
---|
97 | DWORD dwFlags, const void *pvParam);
|
---|
98 | typedef BOOL (WINAPI *PFNCERTCLOSESTORE)(HCERTSTORE hCertStore, DWORD dwFlags);
|
---|
99 | typedef PCCERT_CONTEXT (WINAPI *PFNCERTENUMCERTIFICATESINSTORE)(HCERTSTORE hCertStore, PCCERT_CONTEXT pPrevCertContext);
|
---|
100 | #endif
|
---|
101 |
|
---|
102 |
|
---|
103 | /*******************************************************************************
|
---|
104 | * Global Variables *
|
---|
105 | *******************************************************************************/
|
---|
106 | /** The build certificate. */
|
---|
107 | static RTCRX509CERTIFICATE g_BuildX509Cert;
|
---|
108 |
|
---|
109 | /** Store for root software publisher certificates. */
|
---|
110 | static RTCRSTORE g_hSpcRootStore = NIL_RTCRSTORE;
|
---|
111 | /** Store for root NT kernel certificates. */
|
---|
112 | static RTCRSTORE g_hNtKernelRootStore = NIL_RTCRSTORE;
|
---|
113 |
|
---|
114 | /** Store containing SPC, NT kernel signing, and timestamp root certificates. */
|
---|
115 | static RTCRSTORE g_hSpcAndNtKernelRootStore = NIL_RTCRSTORE;
|
---|
116 | /** Store for supplemental certificates for use with
|
---|
117 | * g_hSpcAndNtKernelRootStore. */
|
---|
118 | static RTCRSTORE g_hSpcAndNtKernelSuppStore = NIL_RTCRSTORE;
|
---|
119 |
|
---|
120 | /** The full \\SystemRoot\\System32 path. */
|
---|
121 | SUPSYSROOTDIRBUF g_System32NtPath;
|
---|
122 | /** The full \\SystemRoot\\WinSxS path. */
|
---|
123 | SUPSYSROOTDIRBUF g_WinSxSNtPath;
|
---|
124 | #ifdef IN_RING3
|
---|
125 | /** The full 'Program Files' path. */
|
---|
126 | SUPSYSROOTDIRBUF g_ProgramFilesNtPath;
|
---|
127 | # ifdef RT_ARCH_AMD64
|
---|
128 | /** The full 'Program Files (x86)' path. */
|
---|
129 | SUPSYSROOTDIRBUF g_ProgramFilesX86NtPath;
|
---|
130 | # endif
|
---|
131 | /** The full 'Common Files' path. */
|
---|
132 | SUPSYSROOTDIRBUF g_CommonFilesNtPath;
|
---|
133 | # ifdef RT_ARCH_AMD64
|
---|
134 | /** The full 'Common Files (x86)' path. */
|
---|
135 | SUPSYSROOTDIRBUF g_CommonFilesX86NtPath;
|
---|
136 | # endif
|
---|
137 | #endif /* IN_RING3 */
|
---|
138 |
|
---|
139 | /** The TrustedInstaller SID (Vista+). */
|
---|
140 | static union
|
---|
141 | {
|
---|
142 | SID Sid;
|
---|
143 | uint8_t abPadding[SECURITY_MAX_SID_SIZE];
|
---|
144 | } g_TrustedInstallerSid;
|
---|
145 |
|
---|
146 | /** Set after we've retrived other SPC root certificates from the system. */
|
---|
147 | static bool g_fHaveOtherRoots = false;
|
---|
148 |
|
---|
149 | #if defined(IN_RING3) && !defined(IN_SUP_HARDENED_R3)
|
---|
150 | /** Combined windows NT version number. See SUP_MAKE_NT_VER_COMBINED and
|
---|
151 | * SUP_MAKE_NT_VER_SIMPLE. */
|
---|
152 | uint32_t g_uNtVerCombined;
|
---|
153 | #endif
|
---|
154 |
|
---|
155 | #ifdef IN_RING3
|
---|
156 | /** Timestamp hack working around issues with old DLLs that we ship.
|
---|
157 | * See supHardenedWinVerifyImageByHandle() for details. */
|
---|
158 | static uint64_t g_uBuildTimestampHack = 0;
|
---|
159 | #endif
|
---|
160 |
|
---|
161 | #ifdef IN_RING3
|
---|
162 | /** Pointer to WinVerifyTrust. */
|
---|
163 | PFNWINVERIFYTRUST g_pfnWinVerifyTrust;
|
---|
164 | /** Pointer to CryptCATAdminAcquireContext. */
|
---|
165 | PFNCRYPTCATADMINACQUIRECONTEXT g_pfnCryptCATAdminAcquireContext;
|
---|
166 | /** Pointer to CryptCATAdminAcquireContext2 if available. */
|
---|
167 | PFNCRYPTCATADMINACQUIRECONTEXT2 g_pfnCryptCATAdminAcquireContext2;
|
---|
168 | /** Pointer to CryptCATAdminCalcHashFromFileHandle. */
|
---|
169 | PFNCRYPTCATADMINCALCHASHFROMFILEHANDLE g_pfnCryptCATAdminCalcHashFromFileHandle;
|
---|
170 | /** Pointer to CryptCATAdminCalcHashFromFileHandle2. */
|
---|
171 | PFNCRYPTCATADMINCALCHASHFROMFILEHANDLE2 g_pfnCryptCATAdminCalcHashFromFileHandle2;
|
---|
172 | /** Pointer to CryptCATAdminEnumCatalogFromHash. */
|
---|
173 | PFNCRYPTCATADMINENUMCATALOGFROMHASH g_pfnCryptCATAdminEnumCatalogFromHash;
|
---|
174 | /** Pointer to CryptCATAdminReleaseCatalogContext. */
|
---|
175 | PFNCRYPTCATADMINRELEASECATALOGCONTEXT g_pfnCryptCATAdminReleaseCatalogContext;
|
---|
176 | /** Pointer to CryptCATAdminReleaseContext. */
|
---|
177 | PFNCRYPTCATDADMINRELEASECONTEXT g_pfnCryptCATAdminReleaseContext;
|
---|
178 | /** Pointer to CryptCATCatalogInfoFromContext. */
|
---|
179 | PFNCRYPTCATCATALOGINFOFROMCONTEXT g_pfnCryptCATCatalogInfoFromContext;
|
---|
180 |
|
---|
181 | /** Where we store the TLS entry for detecting WinVerifyTrustRecursion. */
|
---|
182 | static uint32_t g_iTlsWinVerifyTrustRecursion = UINT32_MAX;
|
---|
183 | /** Fallback WinVerifyTrust recursion protection. */
|
---|
184 | static uint32_t volatile g_idActiveThread = UINT32_MAX;
|
---|
185 |
|
---|
186 | #endif
|
---|
187 |
|
---|
188 |
|
---|
189 | /*******************************************************************************
|
---|
190 | * Internal Functions *
|
---|
191 | *******************************************************************************/
|
---|
192 | #ifdef IN_RING3
|
---|
193 | static int supR3HardNtViCallWinVerifyTrust(HANDLE hFile, PCRTUTF16 pwszName, uint32_t fFlags, PRTERRINFO pErrInfo,
|
---|
194 | PFNWINVERIFYTRUST pfnWinVerifyTrust);
|
---|
195 | static int supR3HardNtViCallWinVerifyTrustCatFile(HANDLE hFile, PCRTUTF16 pwszName, uint32_t fFlags, PRTERRINFO pErrInfo,
|
---|
196 | PFNWINVERIFYTRUST pfnWinVerifyTrust);
|
---|
197 | #endif
|
---|
198 |
|
---|
199 |
|
---|
200 |
|
---|
201 |
|
---|
202 | /** @copydoc RTLDRREADER::pfnRead */
|
---|
203 | static DECLCALLBACK(int) supHardNtViRdrRead(PRTLDRREADER pReader, void *pvBuf, size_t cb, RTFOFF off)
|
---|
204 | {
|
---|
205 | PSUPHNTVIRDR pNtViRdr = (PSUPHNTVIRDR)pReader;
|
---|
206 | Assert(pNtViRdr->Core.uMagic == RTLDRREADER_MAGIC);
|
---|
207 |
|
---|
208 | if ((ULONG)cb != cb)
|
---|
209 | return VERR_OUT_OF_RANGE;
|
---|
210 |
|
---|
211 |
|
---|
212 | /*
|
---|
213 | * For some reason I'm getting occational read error in an XP VM with
|
---|
214 | * STATUS_FAILED_DRIVER_ENTRY. Redoing the call again works in the
|
---|
215 | * debugger, so try do that automatically.
|
---|
216 | */
|
---|
217 | for (uint32_t iTry = 0;; iTry++)
|
---|
218 | {
|
---|
219 | LARGE_INTEGER offNt;
|
---|
220 | offNt.QuadPart = off;
|
---|
221 |
|
---|
222 | IO_STATUS_BLOCK Ios = RTNT_IO_STATUS_BLOCK_INITIALIZER;
|
---|
223 | NTSTATUS rcNt = NtReadFile(pNtViRdr->hFile,
|
---|
224 | NULL /*hEvent*/,
|
---|
225 | NULL /*ApcRoutine*/,
|
---|
226 | NULL /*ApcContext*/,
|
---|
227 | &Ios,
|
---|
228 | pvBuf,
|
---|
229 | (ULONG)cb,
|
---|
230 | &offNt,
|
---|
231 | NULL);
|
---|
232 | if (NT_SUCCESS(rcNt))
|
---|
233 | rcNt = Ios.Status;
|
---|
234 | if (NT_SUCCESS(rcNt))
|
---|
235 | {
|
---|
236 | if (Ios.Information == cb)
|
---|
237 | {
|
---|
238 | pNtViRdr->off = off + cb;
|
---|
239 | return VINF_SUCCESS;
|
---|
240 | }
|
---|
241 | #ifdef IN_RING3
|
---|
242 | supR3HardenedError(VERR_READ_ERROR, false,
|
---|
243 | "supHardNtViRdrRead: Only got %#zx bytes when requesting %#zx bytes at %#llx in '%s'.\n",
|
---|
244 | Ios.Information, off, cb, pNtViRdr->szFilename);
|
---|
245 | #endif
|
---|
246 | pNtViRdr->off = -1;
|
---|
247 | return VERR_READ_ERROR;
|
---|
248 | }
|
---|
249 |
|
---|
250 | /*
|
---|
251 | * Delay a little before we retry?
|
---|
252 | */
|
---|
253 | #ifdef IN_RING3
|
---|
254 | if (iTry == 0)
|
---|
255 | NtYieldExecution();
|
---|
256 | else if (iTry >= 1)
|
---|
257 | {
|
---|
258 | LARGE_INTEGER Time;
|
---|
259 | Time.QuadPart = -1000000 / 100; /* 1ms in 100ns units, relative time. */
|
---|
260 | NtDelayExecution(TRUE, &Time);
|
---|
261 | }
|
---|
262 | #endif
|
---|
263 | /*
|
---|
264 | * Before we give up, we'll try split up the request in case the
|
---|
265 | * kernel is low on memory or similar. For simplicity reasons, we do
|
---|
266 | * this in a recursion fashion.
|
---|
267 | */
|
---|
268 | if (iTry >= 2)
|
---|
269 | {
|
---|
270 | if (cb >= _8K)
|
---|
271 | {
|
---|
272 | size_t const cbBlock = RT_ALIGN_Z(cb / 4, 512);
|
---|
273 | while (cb > 0)
|
---|
274 | {
|
---|
275 | size_t cbThisRead = RT_MIN(cb, cbBlock);
|
---|
276 | int rc = supHardNtViRdrRead(&pNtViRdr->Core, pvBuf, cbThisRead, off);
|
---|
277 | if (RT_FAILURE(rc))
|
---|
278 | return rc;
|
---|
279 | off += cbThisRead;
|
---|
280 | cb -= cbThisRead;
|
---|
281 | pvBuf = (uint8_t *)pvBuf + cbThisRead;
|
---|
282 | }
|
---|
283 | return VINF_SUCCESS;
|
---|
284 | }
|
---|
285 |
|
---|
286 | #ifdef IN_RING3
|
---|
287 | supR3HardenedError(VERR_READ_ERROR, false, "supHardNtViRdrRead: Error %#x reading %#zx bytes at %#llx in '%s'.\n",
|
---|
288 | rcNt, off, cb, pNtViRdr->szFilename);
|
---|
289 | #endif
|
---|
290 | pNtViRdr->off = -1;
|
---|
291 | return VERR_READ_ERROR;
|
---|
292 | }
|
---|
293 | }
|
---|
294 | }
|
---|
295 |
|
---|
296 |
|
---|
297 | /** @copydoc RTLDRREADER::pfnTell */
|
---|
298 | static DECLCALLBACK(RTFOFF) supHardNtViRdrTell(PRTLDRREADER pReader)
|
---|
299 | {
|
---|
300 | PSUPHNTVIRDR pNtViRdr = (PSUPHNTVIRDR)pReader;
|
---|
301 | Assert(pNtViRdr->Core.uMagic == RTLDRREADER_MAGIC);
|
---|
302 | return pNtViRdr->off;
|
---|
303 | }
|
---|
304 |
|
---|
305 |
|
---|
306 | /** @copydoc RTLDRREADER::pfnSize */
|
---|
307 | static DECLCALLBACK(RTFOFF) supHardNtViRdrSize(PRTLDRREADER pReader)
|
---|
308 | {
|
---|
309 | PSUPHNTVIRDR pNtViRdr = (PSUPHNTVIRDR)pReader;
|
---|
310 | Assert(pNtViRdr->Core.uMagic == RTLDRREADER_MAGIC);
|
---|
311 | return pNtViRdr->cbFile;
|
---|
312 | }
|
---|
313 |
|
---|
314 |
|
---|
315 | /** @copydoc RTLDRREADER::pfnLogName */
|
---|
316 | static DECLCALLBACK(const char *) supHardNtViRdrLogName(PRTLDRREADER pReader)
|
---|
317 | {
|
---|
318 | PSUPHNTVIRDR pNtViRdr = (PSUPHNTVIRDR)pReader;
|
---|
319 | return pNtViRdr->szFilename;
|
---|
320 | }
|
---|
321 |
|
---|
322 |
|
---|
323 | /** @copydoc RTLDRREADER::pfnMap */
|
---|
324 | static DECLCALLBACK(int) supHardNtViRdrMap(PRTLDRREADER pReader, const void **ppvBits)
|
---|
325 | {
|
---|
326 | return VERR_NOT_SUPPORTED;
|
---|
327 | }
|
---|
328 |
|
---|
329 |
|
---|
330 | /** @copydoc RTLDRREADER::pfnUnmap */
|
---|
331 | static DECLCALLBACK(int) supHardNtViRdrUnmap(PRTLDRREADER pReader, const void *pvBits)
|
---|
332 | {
|
---|
333 | return VERR_NOT_SUPPORTED;
|
---|
334 | }
|
---|
335 |
|
---|
336 |
|
---|
337 | /** @copydoc RTLDRREADER::pfnDestroy */
|
---|
338 | static DECLCALLBACK(int) supHardNtViRdrDestroy(PRTLDRREADER pReader)
|
---|
339 | {
|
---|
340 | PSUPHNTVIRDR pNtViRdr = (PSUPHNTVIRDR)pReader;
|
---|
341 | Assert(pNtViRdr->Core.uMagic == RTLDRREADER_MAGIC);
|
---|
342 |
|
---|
343 | pNtViRdr->Core.uMagic = ~RTLDRREADER_MAGIC;
|
---|
344 | pNtViRdr->hFile = NULL;
|
---|
345 |
|
---|
346 | RTMemFree(pNtViRdr);
|
---|
347 | return VINF_SUCCESS;
|
---|
348 | }
|
---|
349 |
|
---|
350 |
|
---|
351 | /**
|
---|
352 | * Creates a loader reader instance for the given NT file handle.
|
---|
353 | *
|
---|
354 | * @returns iprt status code.
|
---|
355 | * @param hFile Native NT file handle.
|
---|
356 | * @param pwszName Optional file name.
|
---|
357 | * @param fFlags Flags, SUPHNTVI_F_XXX.
|
---|
358 | * @param ppNtViRdr Where to store the reader instance on success.
|
---|
359 | */
|
---|
360 | DECLHIDDEN(int) supHardNtViRdrCreate(HANDLE hFile, PCRTUTF16 pwszName, uint32_t fFlags, PSUPHNTVIRDR *ppNtViRdr)
|
---|
361 | {
|
---|
362 | /*
|
---|
363 | * Try determine the size of the file.
|
---|
364 | */
|
---|
365 | IO_STATUS_BLOCK Ios = RTNT_IO_STATUS_BLOCK_INITIALIZER;
|
---|
366 | FILE_STANDARD_INFORMATION StdInfo;
|
---|
367 | NTSTATUS rcNt = NtQueryInformationFile(hFile, &Ios, &StdInfo, sizeof(StdInfo), FileStandardInformation);
|
---|
368 | if (!NT_SUCCESS(rcNt) || !NT_SUCCESS(Ios.Status))
|
---|
369 | return VERR_LDRVI_FILE_LENGTH_ERROR;
|
---|
370 |
|
---|
371 | /*
|
---|
372 | * Calc the file name length and allocate memory for the reader instance.
|
---|
373 | */
|
---|
374 | size_t cchFilename = 0;
|
---|
375 | if (pwszName)
|
---|
376 | cchFilename = RTUtf16CalcUtf8Len(pwszName);
|
---|
377 |
|
---|
378 | int rc = VERR_NO_MEMORY;
|
---|
379 | PSUPHNTVIRDR pNtViRdr = (PSUPHNTVIRDR)RTMemAllocZ(sizeof(*pNtViRdr) + cchFilename);
|
---|
380 | if (!pNtViRdr)
|
---|
381 | return VERR_NO_MEMORY;
|
---|
382 |
|
---|
383 | /*
|
---|
384 | * Initialize the structure.
|
---|
385 | */
|
---|
386 | if (cchFilename)
|
---|
387 | {
|
---|
388 | char *pszName = &pNtViRdr->szFilename[0];
|
---|
389 | rc = RTUtf16ToUtf8Ex(pwszName, RTSTR_MAX, &pszName, cchFilename + 1, NULL);
|
---|
390 | AssertStmt(RT_SUCCESS(rc), pNtViRdr->szFilename[0] = '\0');
|
---|
391 | }
|
---|
392 | else
|
---|
393 | pNtViRdr->szFilename[0] = '\0';
|
---|
394 |
|
---|
395 | pNtViRdr->Core.uMagic = RTLDRREADER_MAGIC;
|
---|
396 | pNtViRdr->Core.pfnRead = supHardNtViRdrRead;
|
---|
397 | pNtViRdr->Core.pfnTell = supHardNtViRdrTell;
|
---|
398 | pNtViRdr->Core.pfnSize = supHardNtViRdrSize;
|
---|
399 | pNtViRdr->Core.pfnLogName = supHardNtViRdrLogName;
|
---|
400 | pNtViRdr->Core.pfnMap = supHardNtViRdrMap;
|
---|
401 | pNtViRdr->Core.pfnUnmap = supHardNtViRdrUnmap;
|
---|
402 | pNtViRdr->Core.pfnDestroy = supHardNtViRdrDestroy;
|
---|
403 | pNtViRdr->hFile = hFile;
|
---|
404 | pNtViRdr->off = 0;
|
---|
405 | pNtViRdr->cbFile = StdInfo.EndOfFile.QuadPart;
|
---|
406 | pNtViRdr->fFlags = fFlags;
|
---|
407 | *ppNtViRdr = pNtViRdr;
|
---|
408 | return VINF_SUCCESS;
|
---|
409 | }
|
---|
410 |
|
---|
411 |
|
---|
412 | /**
|
---|
413 | * Checks if the file is owned by TrustedInstaller on Vista and later.
|
---|
414 | *
|
---|
415 | * @returns true if owned by TrustedInstaller of pre-Vista, false if not.
|
---|
416 | *
|
---|
417 | * @param hFile The handle to the file.
|
---|
418 | * @param pwszName The name of the file.
|
---|
419 | */
|
---|
420 | static bool supHardNtViCheckIsOwnedByTrustedInstaller(HANDLE hFile, PCRTUTF16 pwszName)
|
---|
421 | {
|
---|
422 | if (g_uNtVerCombined < SUP_NT_VER_VISTA)
|
---|
423 | return true;
|
---|
424 |
|
---|
425 | /*
|
---|
426 | * Get the ownership information.
|
---|
427 | */
|
---|
428 | union
|
---|
429 | {
|
---|
430 | SECURITY_DESCRIPTOR_RELATIVE Rel;
|
---|
431 | SECURITY_DESCRIPTOR Abs;
|
---|
432 | uint8_t abView[256];
|
---|
433 | } uBuf;
|
---|
434 | ULONG cbActual;
|
---|
435 | NTSTATUS rcNt = NtQuerySecurityObject(hFile, OWNER_SECURITY_INFORMATION, &uBuf.Abs, sizeof(uBuf), &cbActual);
|
---|
436 | if (!NT_SUCCESS(rcNt))
|
---|
437 | {
|
---|
438 | SUP_DPRINTF(("NtQuerySecurityObject failed with rcNt=%#x on '%ls'\n", rcNt, pwszName));
|
---|
439 | return false;
|
---|
440 | }
|
---|
441 |
|
---|
442 | /*
|
---|
443 | * Check the owner.
|
---|
444 | */
|
---|
445 | PSID pOwner = uBuf.Rel.Control & SE_SELF_RELATIVE ? &uBuf.abView[uBuf.Rel.Owner] : uBuf.Abs.Owner;
|
---|
446 | Assert((uintptr_t)pOwner - (uintptr_t)&uBuf < sizeof(uBuf) - sizeof(SID));
|
---|
447 | if (RtlEqualSid(pOwner, &g_TrustedInstallerSid))
|
---|
448 | return true;
|
---|
449 |
|
---|
450 | SUP_DPRINTF(("%ls: Owner is not trusted installer (%.*Rhxs)\n",
|
---|
451 | pwszName, ((uint8_t *)pOwner)[1] /*SubAuthorityCount*/ * sizeof(ULONG) + 8, pOwner));
|
---|
452 | return false;
|
---|
453 | }
|
---|
454 |
|
---|
455 |
|
---|
456 | /**
|
---|
457 | * Simple case insensitive UTF-16 / ASCII path compare.
|
---|
458 | *
|
---|
459 | * @returns true if equal, false if not.
|
---|
460 | * @param pwszLeft The UTF-16 path string.
|
---|
461 | * @param pszRight The ascii string.
|
---|
462 | */
|
---|
463 | static bool supHardViUtf16PathIsEqual(PCRTUTF16 pwszLeft, const char *pszRight)
|
---|
464 | {
|
---|
465 | for (;;)
|
---|
466 | {
|
---|
467 | RTUTF16 wc = *pwszLeft++;
|
---|
468 | uint8_t b = *pszRight++;
|
---|
469 | if (b != wc)
|
---|
470 | {
|
---|
471 | if (wc >= 0x80)
|
---|
472 | return false;
|
---|
473 | wc = RT_C_TO_LOWER(wc);
|
---|
474 | if (wc != b)
|
---|
475 | {
|
---|
476 | b = RT_C_TO_LOWER(b);
|
---|
477 | if (wc != b)
|
---|
478 | {
|
---|
479 | if (wc == '/')
|
---|
480 | wc = '\\';
|
---|
481 | if (b == '/')
|
---|
482 | b = '\\';
|
---|
483 | if (wc != b)
|
---|
484 | return false;
|
---|
485 | }
|
---|
486 | }
|
---|
487 | }
|
---|
488 | if (!b)
|
---|
489 | return true;
|
---|
490 | }
|
---|
491 | }
|
---|
492 |
|
---|
493 |
|
---|
494 | /**
|
---|
495 | * Simple case insensitive UTF-16 / ASCII ends-with path predicate.
|
---|
496 | *
|
---|
497 | * @returns true if equal, false if not.
|
---|
498 | * @param pwsz The UTF-16 path string.
|
---|
499 | * @param pszSuffix The ascii suffix string.
|
---|
500 | */
|
---|
501 | static bool supHardViUtf16PathEndsWith(PCRTUTF16 pwsz, const char *pszSuffix)
|
---|
502 | {
|
---|
503 | size_t cwc = RTUtf16Len(pwsz);
|
---|
504 | size_t cchSuffix = strlen(pszSuffix);
|
---|
505 | if (cwc >= cchSuffix)
|
---|
506 | return supHardViUtf16PathIsEqual(pwsz + cwc - cchSuffix, pszSuffix);
|
---|
507 | return false;
|
---|
508 | }
|
---|
509 |
|
---|
510 |
|
---|
511 | /**
|
---|
512 | * Simple case insensitive UTF-16 / ASCII starts-with path predicate.
|
---|
513 | *
|
---|
514 | * @returns true if starts with given string, false if not.
|
---|
515 | * @param pwsz The UTF-16 path string.
|
---|
516 | * @param pszPrefix The ascii prefix string.
|
---|
517 | */
|
---|
518 | static bool supHardViUtf16PathStartsWithAscii(PCRTUTF16 pwszLeft, const char *pszRight)
|
---|
519 | {
|
---|
520 | for (;;)
|
---|
521 | {
|
---|
522 | RTUTF16 wc = *pwszLeft++;
|
---|
523 | uint8_t b = *pszRight++;
|
---|
524 | if (b != wc)
|
---|
525 | {
|
---|
526 | if (!b)
|
---|
527 | return true;
|
---|
528 | if (wc >= 0x80 || wc == 0)
|
---|
529 | return false;
|
---|
530 | wc = RT_C_TO_LOWER(wc);
|
---|
531 | if (wc != b)
|
---|
532 | {
|
---|
533 | b = RT_C_TO_LOWER(b);
|
---|
534 | if (wc != b)
|
---|
535 | {
|
---|
536 | if (wc == '/')
|
---|
537 | wc = '\\';
|
---|
538 | if (b == '/')
|
---|
539 | b = '\\';
|
---|
540 | if (wc != b)
|
---|
541 | return false;
|
---|
542 | }
|
---|
543 | }
|
---|
544 | }
|
---|
545 | }
|
---|
546 | }
|
---|
547 |
|
---|
548 |
|
---|
549 | /**
|
---|
550 | * Simple case insensitive UNICODE_STRING starts-with path predicate.
|
---|
551 | *
|
---|
552 | * @returns true if starts with given string, false if not.
|
---|
553 | * @param pwszLeft The path to check.
|
---|
554 | * @param cwcLeft The length of @a pwszLeft
|
---|
555 | * @param pwszRight The starts-with path.
|
---|
556 | * @param cwcRight The length of @a pwszRight.
|
---|
557 | * @param fCheckSlash Check for a slash following the prefix.
|
---|
558 | */
|
---|
559 | DECLHIDDEN(bool) supHardViUtf16PathStartsWithEx(PCRTUTF16 pwszLeft, uint32_t cwcLeft,
|
---|
560 | PCRTUTF16 pwszRight, uint32_t cwcRight, bool fCheckSlash)
|
---|
561 | {
|
---|
562 | if (cwcLeft < cwcRight || !cwcRight || !pwszRight)
|
---|
563 | return false;
|
---|
564 |
|
---|
565 | /* See if we can get away with a case sensitive compare first. */
|
---|
566 | if (memcmp(pwszLeft, pwszRight, cwcRight * sizeof(RTUTF16)) == 0)
|
---|
567 | pwszLeft += cwcRight;
|
---|
568 | else
|
---|
569 | {
|
---|
570 | /* No luck, do a slow case insensitive comapre. */
|
---|
571 | uint32_t cLeft = cwcRight;
|
---|
572 | while (cLeft-- > 0)
|
---|
573 | {
|
---|
574 | RTUTF16 wcLeft = *pwszLeft++;
|
---|
575 | RTUTF16 wcRight = *pwszRight++;
|
---|
576 | if (wcLeft != wcRight)
|
---|
577 | {
|
---|
578 | wcLeft = wcLeft < 0x80 ? wcLeft == '/' ? '\\' : RT_C_TO_LOWER(wcLeft) : wcLeft;
|
---|
579 | wcRight = wcRight < 0x80 ? wcRight == '/' ? '\\' : RT_C_TO_LOWER(wcRight) : wcRight;
|
---|
580 | if (wcLeft != wcRight)
|
---|
581 | return false;
|
---|
582 | }
|
---|
583 | }
|
---|
584 | }
|
---|
585 |
|
---|
586 | /* Check for slash following the prefix, if request. */
|
---|
587 | if ( !fCheckSlash
|
---|
588 | || *pwszLeft == '\\'
|
---|
589 | || *pwszLeft == '/')
|
---|
590 | return true;
|
---|
591 | return false;
|
---|
592 | }
|
---|
593 |
|
---|
594 |
|
---|
595 | /**
|
---|
596 | * Simple case insensitive UNICODE_STRING starts-with path predicate.
|
---|
597 | *
|
---|
598 | * @returns true if starts with given string, false if not.
|
---|
599 | * @param pUniStrLeft The path to check.
|
---|
600 | * @param pUniStrRight The starts-with path.
|
---|
601 | * @param fCheckSlash Check for a slash following the prefix.
|
---|
602 | */
|
---|
603 | DECLHIDDEN(bool) supHardViUniStrPathStartsWithUniStr(UNICODE_STRING const *pUniStrLeft, UNICODE_STRING const *pUniStrRight,
|
---|
604 | bool fCheckSlash)
|
---|
605 | {
|
---|
606 | return supHardViUtf16PathStartsWithEx(pUniStrLeft->Buffer, pUniStrLeft->Length / sizeof(WCHAR),
|
---|
607 | pUniStrRight->Buffer, pUniStrRight->Length / sizeof(WCHAR), fCheckSlash);
|
---|
608 | }
|
---|
609 |
|
---|
610 |
|
---|
611 |
|
---|
612 | /**
|
---|
613 | * Counts slashes in the given UTF-8 path string.
|
---|
614 | *
|
---|
615 | * @returns Number of slashes.
|
---|
616 | * @param pwsz The UTF-16 path string.
|
---|
617 | */
|
---|
618 | static uint32_t supHardViUtf16PathCountSlashes(PCRTUTF16 pwsz)
|
---|
619 | {
|
---|
620 | uint32_t cSlashes = 0;
|
---|
621 | RTUTF16 wc;
|
---|
622 | while ((wc = *pwsz++) != '\0')
|
---|
623 | if (wc == '/' || wc == '\\')
|
---|
624 | cSlashes++;
|
---|
625 | return cSlashes;
|
---|
626 | }
|
---|
627 |
|
---|
628 |
|
---|
629 | #ifdef VBOX_PERMIT_MORE
|
---|
630 | /**
|
---|
631 | * Checks if the path goes into %windir%\apppatch\.
|
---|
632 | *
|
---|
633 | * @returns true if apppatch, false if not.
|
---|
634 | * @param pwszPath The path to examine.
|
---|
635 | */
|
---|
636 | DECLHIDDEN(bool) supHardViIsAppPatchDir(PCRTUTF16 pwszPath, uint32_t cwcName)
|
---|
637 | {
|
---|
638 | uint32_t cwcWinDir = (g_System32NtPath.UniStr.Length - sizeof(L"System32")) / sizeof(WCHAR);
|
---|
639 |
|
---|
640 | if (cwcName <= cwcWinDir + sizeof("AppPatch"))
|
---|
641 | return false;
|
---|
642 |
|
---|
643 | if (memcmp(pwszPath, g_System32NtPath.UniStr.Buffer, cwcWinDir * sizeof(WCHAR)))
|
---|
644 | return false;
|
---|
645 |
|
---|
646 | if (!supHardViUtf16PathStartsWithAscii(&pwszPath[cwcWinDir], "\\AppPatch\\"))
|
---|
647 | return false;
|
---|
648 |
|
---|
649 | return g_uNtVerCombined >= SUP_NT_VER_VISTA;
|
---|
650 | }
|
---|
651 | #else
|
---|
652 | # error should not get here..
|
---|
653 | #endif
|
---|
654 |
|
---|
655 |
|
---|
656 |
|
---|
657 | /**
|
---|
658 | * Checks if the unsigned DLL is fine or not.
|
---|
659 | *
|
---|
660 | * @returns VINF_LDRVI_NOT_SIGNED or @a rc.
|
---|
661 | * @param hLdrMod The loader module handle.
|
---|
662 | * @param pwszName The NT name of the DLL/EXE.
|
---|
663 | * @param fFlags Flags.
|
---|
664 | * @param hFile The file handle.
|
---|
665 | * @param rc The status code..
|
---|
666 | */
|
---|
667 | static int supHardNtViCheckIfNotSignedOk(RTLDRMOD hLdrMod, PCRTUTF16 pwszName, uint32_t fFlags, HANDLE hFile, int rc)
|
---|
668 | {
|
---|
669 | if (fFlags & (SUPHNTVI_F_REQUIRE_BUILD_CERT | SUPHNTVI_F_REQUIRE_KERNEL_CODE_SIGNING))
|
---|
670 | return rc;
|
---|
671 |
|
---|
672 | /*
|
---|
673 | * Version macros.
|
---|
674 | */
|
---|
675 | uint32_t const uNtVer = g_uNtVerCombined;
|
---|
676 | #define IS_XP() ( uNtVer >= SUP_MAKE_NT_VER_SIMPLE(5, 1) && uNtVer < SUP_MAKE_NT_VER_SIMPLE(5, 2) )
|
---|
677 | #define IS_W2K3() ( uNtVer >= SUP_MAKE_NT_VER_SIMPLE(5, 2) && uNtVer < SUP_MAKE_NT_VER_SIMPLE(5, 3) )
|
---|
678 | #define IS_VISTA() ( uNtVer >= SUP_MAKE_NT_VER_SIMPLE(6, 0) && uNtVer < SUP_MAKE_NT_VER_SIMPLE(6, 1) )
|
---|
679 | #define IS_W70() ( uNtVer >= SUP_MAKE_NT_VER_SIMPLE(6, 1) && uNtVer < SUP_MAKE_NT_VER_SIMPLE(6, 2) )
|
---|
680 | #define IS_W80() ( uNtVer >= SUP_MAKE_NT_VER_SIMPLE(6, 2) && uNtVer < SUP_MAKE_NT_VER_SIMPLE(6, 3) )
|
---|
681 | #define IS_W81() ( uNtVer >= SUP_MAKE_NT_VER_SIMPLE(6, 3) && uNtVer < SUP_MAKE_NT_VER_SIMPLE(6, 4) )
|
---|
682 |
|
---|
683 | /*
|
---|
684 | * The System32 directory.
|
---|
685 | *
|
---|
686 | * System32 is full of unsigned DLLs shipped by microsoft, graphics
|
---|
687 | * hardware vendors, input device/method vendors and whatnot else that
|
---|
688 | * actually needs to be loaded into a process for it to work correctly.
|
---|
689 | * We have to ASSUME that anything our process attempts to load from
|
---|
690 | * System32 is trustworthy and that the Windows system with the help of
|
---|
691 | * anti-virus software make sure there is nothing evil lurking in System32
|
---|
692 | * or being loaded from it.
|
---|
693 | *
|
---|
694 | * A small measure of protection is to list DLLs we know should be signed
|
---|
695 | * and decline loading unsigned versions of them, assuming they have been
|
---|
696 | * replaced by an adversary with evil intentions.
|
---|
697 | */
|
---|
698 | PCRTUTF16 pwsz;
|
---|
699 | uint32_t cwcName = (uint32_t)RTUtf16Len(pwszName);
|
---|
700 | uint32_t cwcOther = g_System32NtPath.UniStr.Length / sizeof(WCHAR);
|
---|
701 | if (supHardViUtf16PathStartsWithEx(pwszName, cwcName, g_System32NtPath.UniStr.Buffer, cwcOther, true /*fCheckSlash*/))
|
---|
702 | {
|
---|
703 | pwsz = pwszName + cwcOther + 1;
|
---|
704 |
|
---|
705 | /* Must be owned by trusted installer. (This test is superfuous, thus no relaxation here.) */
|
---|
706 | if ( !(fFlags & SUPHNTVI_F_TRUSTED_INSTALLER_OWNER)
|
---|
707 | && !supHardNtViCheckIsOwnedByTrustedInstaller(hFile, pwszName))
|
---|
708 | return rc;
|
---|
709 |
|
---|
710 | /* Core DLLs. */
|
---|
711 | if (supHardViUtf16PathIsEqual(pwsz, "ntdll.dll"))
|
---|
712 | return uNtVer < SUP_NT_VER_VISTA ? VINF_LDRVI_NOT_SIGNED : rc;
|
---|
713 | if (supHardViUtf16PathIsEqual(pwsz, "kernel32.dll"))
|
---|
714 | return uNtVer < SUP_NT_VER_W81 ? VINF_LDRVI_NOT_SIGNED : rc;
|
---|
715 | if (supHardViUtf16PathIsEqual(pwsz, "kernelbase.dll"))
|
---|
716 | return IS_W80() || IS_W70() ? VINF_LDRVI_NOT_SIGNED : rc;
|
---|
717 | if (supHardViUtf16PathIsEqual(pwsz, "apisetschema.dll"))
|
---|
718 | return IS_W70() ? VINF_LDRVI_NOT_SIGNED : rc;
|
---|
719 | if (supHardViUtf16PathIsEqual(pwsz, "apphelp.dll"))
|
---|
720 | return uNtVer < SUP_MAKE_NT_VER_SIMPLE(6, 4) ? VINF_LDRVI_NOT_SIGNED : rc;
|
---|
721 | #ifdef VBOX_PERMIT_MORE
|
---|
722 | if (uNtVer >= SUP_NT_VER_W70) /* hard limit: user32.dll is unwanted prior to w7. */
|
---|
723 | {
|
---|
724 | if (supHardViUtf16PathIsEqual(pwsz, "sfc.dll"))
|
---|
725 | return uNtVer < SUP_MAKE_NT_VER_SIMPLE(6, 4) ? VINF_LDRVI_NOT_SIGNED : rc;
|
---|
726 | if (supHardViUtf16PathIsEqual(pwsz, "sfc_os.dll"))
|
---|
727 | return uNtVer < SUP_MAKE_NT_VER_SIMPLE(6, 4) ? VINF_LDRVI_NOT_SIGNED : rc;
|
---|
728 | if (supHardViUtf16PathIsEqual(pwsz, "user32.dll"))
|
---|
729 | return uNtVer < SUP_NT_VER_W81 ? VINF_LDRVI_NOT_SIGNED : rc;
|
---|
730 | }
|
---|
731 | #endif
|
---|
732 |
|
---|
733 | #ifndef IN_RING0
|
---|
734 | /* Check that this DLL isn't supposed to be signed on this windows
|
---|
735 | version. If it should, it's likely to be a fake. */
|
---|
736 | /** @todo list of signed dlls for various windows versions. */
|
---|
737 | return VINF_LDRVI_NOT_SIGNED;
|
---|
738 | #else
|
---|
739 | return rc;
|
---|
740 | #endif /* IN_RING0 */
|
---|
741 | }
|
---|
742 |
|
---|
743 |
|
---|
744 | #ifndef IN_RING0
|
---|
745 | /*
|
---|
746 | * The WinSxS white list.
|
---|
747 | *
|
---|
748 | * Just like with System32 there are potentially a number of DLLs that
|
---|
749 | * could be required from WinSxS.
|
---|
750 | */
|
---|
751 | cwcOther = g_WinSxSNtPath.UniStr.Length / sizeof(WCHAR);
|
---|
752 | if (supHardViUtf16PathStartsWithEx(pwszName, cwcName, g_WinSxSNtPath.UniStr.Buffer, cwcOther, true /*fCheckSlash*/))
|
---|
753 | {
|
---|
754 | pwsz = pwszName + cwcOther + 1;
|
---|
755 | cwcName -= cwcOther + 1;
|
---|
756 |
|
---|
757 | /* The WinSxS layout means everything worth loading is exactly one level down. */
|
---|
758 | uint32_t cSlashes = supHardViUtf16PathCountSlashes(pwsz);
|
---|
759 | if (cSlashes != 1)
|
---|
760 | return rc;
|
---|
761 |
|
---|
762 | /* Must be owned by trusted installer. */
|
---|
763 | if ( !(fFlags & SUPHNTVI_F_TRUSTED_INSTALLER_OWNER)
|
---|
764 | && !supHardNtViCheckIsOwnedByTrustedInstaller(hFile, pwszName))
|
---|
765 | return rc;
|
---|
766 | return VINF_LDRVI_NOT_SIGNED;
|
---|
767 | }
|
---|
768 | #endif /* !IN_RING0 */
|
---|
769 |
|
---|
770 |
|
---|
771 | #ifdef VBOX_PERMIT_MORE
|
---|
772 | /*
|
---|
773 | * AppPatch whitelist.
|
---|
774 | */
|
---|
775 | if (supHardViIsAppPatchDir(pwszName, cwcName))
|
---|
776 | {
|
---|
777 | cwcOther = g_System32NtPath.UniStr.Length / sizeof(WCHAR); /* ASSUMES System32 is called System32. */
|
---|
778 | pwsz = pwszName + cwcOther + 1;
|
---|
779 |
|
---|
780 | if ( !(fFlags & SUPHNTVI_F_TRUSTED_INSTALLER_OWNER)
|
---|
781 | && !supHardNtViCheckIsOwnedByTrustedInstaller(hFile, pwszName))
|
---|
782 | return rc;
|
---|
783 |
|
---|
784 | # ifndef VBOX_PERMIT_EVEN_MORE
|
---|
785 | if (supHardViUtf16PathIsEqual(pwsz, "acres.dll"))
|
---|
786 | return VINF_LDRVI_NOT_SIGNED;
|
---|
787 |
|
---|
788 | # ifdef RT_ARCH_AMD64
|
---|
789 | if (supHardViUtf16PathIsEqual(pwsz, "AppPatch64\\AcGenral.dll"))
|
---|
790 | return VINF_LDRVI_NOT_SIGNED;
|
---|
791 | # elif defined(RT_ARCH_X86)
|
---|
792 | if (supHardViUtf16PathIsEqual(pwsz, "AcGenral.dll"))
|
---|
793 | return VINF_LDRVI_NOT_SIGNED;
|
---|
794 | # endif
|
---|
795 | # endif /* !VBOX_PERMIT_EVEN_MORE */
|
---|
796 |
|
---|
797 | # ifdef IN_RING0
|
---|
798 | return rc;
|
---|
799 | # else
|
---|
800 | return VINF_LDRVI_NOT_SIGNED;
|
---|
801 | # endif
|
---|
802 | }
|
---|
803 | #endif /* VBOX_PERMIT_MORE */
|
---|
804 |
|
---|
805 |
|
---|
806 | #ifndef IN_RING0
|
---|
807 | # if defined(VBOX_PERMIT_MORE) && !defined(VBOX_PERMIT_EVEN_MORE)
|
---|
808 | /*
|
---|
809 | * Program files and common files.
|
---|
810 | * Permit anything that's signed and correctly installed.
|
---|
811 | */
|
---|
812 | if ( supHardViUtf16PathStartsWithEx(pwszName, cwcName,
|
---|
813 | g_ProgramFilesNtPath.UniStr.Buffer, g_ProgramFilesNtPath.UniStr.Length,
|
---|
814 | true /*fCheckSlash*/)
|
---|
815 | || supHardViUtf16PathStartsWithEx(pwszName, cwcName,
|
---|
816 | g_CommonFilesNtPath.UniStr.Buffer, g_CommonFilesNtPath.UniStr.Length,
|
---|
817 | true /*fCheckSlash*/)
|
---|
818 | # ifdef RT_ARCH_AMD64
|
---|
819 | || supHardViUtf16PathStartsWithEx(pwszName, cwcName,
|
---|
820 | g_ProgramFilesX86NtPath.UniStr.Buffer, g_ProgramFilesX86NtPath.UniStr.Length,
|
---|
821 | true /*fCheckSlash*/)
|
---|
822 | || supHardViUtf16PathStartsWithEx(pwszName, cwcName,
|
---|
823 | g_CommonFilesX86NtPath.UniStr.Buffer, g_CommonFilesX86NtPath.UniStr.Length,
|
---|
824 | true /*fCheckSlash*/)
|
---|
825 | # endif
|
---|
826 | )
|
---|
827 | {
|
---|
828 | if ( !(fFlags & SUPHNTVI_F_TRUSTED_INSTALLER_OWNER)
|
---|
829 | && !supHardNtViCheckIsOwnedByTrustedInstaller(hFile, pwszName))
|
---|
830 | return rc;
|
---|
831 | return VINF_LDRVI_NOT_SIGNED;
|
---|
832 | }
|
---|
833 |
|
---|
834 | # elif defined(VBOX_PERMIT_MORE) && defined(VBOX_PERMIT_EVEN_MORE)
|
---|
835 | /*
|
---|
836 | * Anything that's owned by the trusted installer.
|
---|
837 | */
|
---|
838 | if ( (fFlags & SUPHNTVI_F_TRUSTED_INSTALLER_OWNER)
|
---|
839 | || supHardNtViCheckIsOwnedByTrustedInstaller(hFile, pwszName))
|
---|
840 | return VINF_LDRVI_NOT_SIGNED;
|
---|
841 |
|
---|
842 | # endif
|
---|
843 | #endif /* !IN_RING0 */
|
---|
844 |
|
---|
845 | /*
|
---|
846 | * Not permitted.
|
---|
847 | */
|
---|
848 | return rc;
|
---|
849 | }
|
---|
850 |
|
---|
851 |
|
---|
852 | /**
|
---|
853 | * @callback_method_impl{RTCRPKCS7VERIFYCERTCALLBACK,
|
---|
854 | * Standard code signing. Use this for Microsoft SPC.}
|
---|
855 | */
|
---|
856 | static DECLCALLBACK(int) supHardNtViCertVerifyCallback(PCRTCRX509CERTIFICATE pCert, RTCRX509CERTPATHS hCertPaths,
|
---|
857 | void *pvUser, PRTERRINFO pErrInfo)
|
---|
858 | {
|
---|
859 | PSUPHNTVIRDR pNtViRdr = (PSUPHNTVIRDR)pvUser;
|
---|
860 | Assert(pNtViRdr->Core.uMagic == RTLDRREADER_MAGIC);
|
---|
861 |
|
---|
862 | /*
|
---|
863 | * If there is no certificate path build & validator associated with this
|
---|
864 | * callback, it must be because of the build certificate. We trust the
|
---|
865 | * build certificate without any second thoughts.
|
---|
866 | */
|
---|
867 | if (hCertPaths == NIL_RTCRX509CERTPATHS)
|
---|
868 | {
|
---|
869 | if (RTCrX509Certificate_Compare(pCert, &g_BuildX509Cert) == 0) /* healthy paranoia */
|
---|
870 | return VINF_SUCCESS;
|
---|
871 | return RTErrInfoSetF(pErrInfo, VERR_SUP_VP_NOT_BUILD_CERT_IPE, "Not valid kernel code signature.");
|
---|
872 | }
|
---|
873 |
|
---|
874 | /*
|
---|
875 | * Standard code signing capabilites required.
|
---|
876 | */
|
---|
877 | int rc = RTCrPkcs7VerifyCertCallbackCodeSigning(pCert, hCertPaths, NULL, pErrInfo);
|
---|
878 | if (RT_SUCCESS(rc))
|
---|
879 | {
|
---|
880 | /*
|
---|
881 | * If kernel signing, a valid certificate path must be anchored by the
|
---|
882 | * microsoft kernel signing root certificate.
|
---|
883 | */
|
---|
884 | if (pNtViRdr->fFlags & SUPHNTVI_F_REQUIRE_KERNEL_CODE_SIGNING)
|
---|
885 | {
|
---|
886 | uint32_t cPaths = RTCrX509CertPathsGetPathCount(hCertPaths);
|
---|
887 | uint32_t cFound = 0;
|
---|
888 | uint32_t cValid = 0;
|
---|
889 | for (uint32_t iPath = 0; iPath < cPaths; iPath++)
|
---|
890 | {
|
---|
891 | bool fTrusted;
|
---|
892 | PCRTCRX509NAME pSubject;
|
---|
893 | PCRTCRX509SUBJECTPUBLICKEYINFO pPublicKeyInfo;
|
---|
894 | int rcVerify;
|
---|
895 | rc = RTCrX509CertPathsQueryPathInfo(hCertPaths, iPath, &fTrusted, NULL /*pcNodes*/, &pSubject, &pPublicKeyInfo,
|
---|
896 | NULL, NULL /*pCertCtx*/, &rcVerify);
|
---|
897 | AssertRCBreak(rc);
|
---|
898 |
|
---|
899 | if (RT_SUCCESS(rcVerify))
|
---|
900 | {
|
---|
901 | Assert(fTrusted);
|
---|
902 | cValid++;
|
---|
903 |
|
---|
904 | /*
|
---|
905 | * Search the kernel signing root store for a matching anchor.
|
---|
906 | */
|
---|
907 | RTCRSTORECERTSEARCH Search;
|
---|
908 | rc = RTCrStoreCertFindBySubjectOrAltSubjectByRfc5280(g_hNtKernelRootStore, pSubject, &Search);
|
---|
909 | AssertRCBreak(rc);
|
---|
910 |
|
---|
911 | PCRTCRCERTCTX pCertCtx;
|
---|
912 | while ((pCertCtx = RTCrStoreCertSearchNext(g_hNtKernelRootStore, &Search)) != NULL)
|
---|
913 | {
|
---|
914 | PCRTCRX509SUBJECTPUBLICKEYINFO pCertPubKeyInfo = NULL;
|
---|
915 | if (pCertCtx->pCert)
|
---|
916 | pCertPubKeyInfo = &pCertCtx->pCert->TbsCertificate.SubjectPublicKeyInfo;
|
---|
917 | else if (pCertCtx->pTaInfo)
|
---|
918 | pCertPubKeyInfo = &pCertCtx->pTaInfo->PubKey;
|
---|
919 | else
|
---|
920 | pCertPubKeyInfo = NULL;
|
---|
921 | if ( pCertPubKeyInfo
|
---|
922 | && RTCrX509SubjectPublicKeyInfo_Compare(pCertPubKeyInfo, pPublicKeyInfo) == 0)
|
---|
923 | cFound++;
|
---|
924 | RTCrCertCtxRelease(pCertCtx);
|
---|
925 | }
|
---|
926 |
|
---|
927 | int rc2 = RTCrStoreCertSearchDestroy(g_hNtKernelRootStore, &Search); AssertRC(rc2);
|
---|
928 | }
|
---|
929 | }
|
---|
930 | if (RT_SUCCESS(rc) && cFound == 0)
|
---|
931 | rc = RTErrInfoSetF(pErrInfo, VERR_SUP_VP_NOT_VALID_KERNEL_CODE_SIGNATURE, "Not valid kernel code signature.");
|
---|
932 | if (RT_SUCCESS(rc) && cValid < 2 && g_fHaveOtherRoots)
|
---|
933 | rc = RTErrInfoSetF(pErrInfo, VERR_SUP_VP_UNEXPECTED_VALID_PATH_COUNT,
|
---|
934 | "Expected at least %u valid paths, not %u.", 2, cValid);
|
---|
935 | }
|
---|
936 | }
|
---|
937 |
|
---|
938 | /*
|
---|
939 | * More requirements? NT5 build lab?
|
---|
940 | */
|
---|
941 |
|
---|
942 | return rc;
|
---|
943 | }
|
---|
944 |
|
---|
945 |
|
---|
946 | static DECLCALLBACK(int) supHardNtViCallback(RTLDRMOD hLdrMod, RTLDRSIGNATURETYPE enmSignature,
|
---|
947 | void const *pvSignature, size_t cbSignature,
|
---|
948 | PRTERRINFO pErrInfo, void *pvUser)
|
---|
949 | {
|
---|
950 | /*
|
---|
951 | * Check out the input.
|
---|
952 | */
|
---|
953 | PSUPHNTVIRDR pNtViRdr = (PSUPHNTVIRDR)pvUser;
|
---|
954 | Assert(pNtViRdr->Core.uMagic == RTLDRREADER_MAGIC);
|
---|
955 |
|
---|
956 | AssertReturn(cbSignature == sizeof(RTCRPKCS7CONTENTINFO), VERR_INTERNAL_ERROR_5);
|
---|
957 | PCRTCRPKCS7CONTENTINFO pContentInfo = (PCRTCRPKCS7CONTENTINFO)pvSignature;
|
---|
958 | AssertReturn(RTCrPkcs7ContentInfo_IsSignedData(pContentInfo), VERR_INTERNAL_ERROR_5);
|
---|
959 | AssertReturn(pContentInfo->u.pSignedData->SignerInfos.cItems == 1, VERR_INTERNAL_ERROR_5);
|
---|
960 | PCRTCRPKCS7SIGNERINFO pSignerInfo = &pContentInfo->u.pSignedData->SignerInfos.paItems[0];
|
---|
961 |
|
---|
962 | /*
|
---|
963 | * If special certificate requirements, check them out before validating
|
---|
964 | * the signature.
|
---|
965 | */
|
---|
966 | if (pNtViRdr->fFlags & SUPHNTVI_F_REQUIRE_BUILD_CERT)
|
---|
967 | {
|
---|
968 | if (!RTCrX509Certificate_MatchIssuerAndSerialNumber(&g_BuildX509Cert,
|
---|
969 | &pSignerInfo->IssuerAndSerialNumber.Name,
|
---|
970 | &pSignerInfo->IssuerAndSerialNumber.SerialNumber))
|
---|
971 | return RTErrInfoSet(pErrInfo, VERR_SUP_VP_NOT_SIGNED_WITH_BUILD_CERT, "Not signed with the build certificate.");
|
---|
972 | }
|
---|
973 |
|
---|
974 | /*
|
---|
975 | * Verify the signature.
|
---|
976 | */
|
---|
977 | RTTIMESPEC ValidationTime;
|
---|
978 | RTTimeSpecSetSeconds(&ValidationTime, pNtViRdr->uTimestamp);
|
---|
979 |
|
---|
980 | return RTCrPkcs7VerifySignedData(pContentInfo, 0, g_hSpcAndNtKernelSuppStore, g_hSpcAndNtKernelRootStore, &ValidationTime,
|
---|
981 | supHardNtViCertVerifyCallback, pNtViRdr, pErrInfo);
|
---|
982 | }
|
---|
983 |
|
---|
984 |
|
---|
985 | /**
|
---|
986 | * Verifies the given loader image.
|
---|
987 | *
|
---|
988 | * @returns IPRT status code.
|
---|
989 | * @param hLdrMod File handle to the executable file.
|
---|
990 | * @param pwszName Full NT path to the DLL in question, used for
|
---|
991 | * dealing with unsigned system dlls as well as for
|
---|
992 | * error/logging.
|
---|
993 | * @param pNtViRdr The reader instance /w flags.
|
---|
994 | * @param pfWinVerifyTrust Where to return whether WinVerifyTrust was used.
|
---|
995 | * @param pErrInfo Pointer to error info structure. Optional.
|
---|
996 | */
|
---|
997 | DECLHIDDEN(int) supHardenedWinVerifyImageByLdrMod(RTLDRMOD hLdrMod, PCRTUTF16 pwszName, PSUPHNTVIRDR pNtViRdr,
|
---|
998 | bool *pfWinVerifyTrust, PRTERRINFO pErrInfo)
|
---|
999 | {
|
---|
1000 | if (pfWinVerifyTrust)
|
---|
1001 | *pfWinVerifyTrust = false;
|
---|
1002 |
|
---|
1003 | #ifdef IN_RING3
|
---|
1004 | /* Check that the caller has performed the necessary library initialization. */
|
---|
1005 | if (!RTCrX509Certificate_IsPresent(&g_BuildX509Cert))
|
---|
1006 | return RTErrInfoSet(pErrInfo, VERR_WRONG_ORDER,
|
---|
1007 | "supHardenedWinVerifyImageByHandle: supHardenedWinInitImageVerifier was not called.");
|
---|
1008 | #endif
|
---|
1009 |
|
---|
1010 | /*
|
---|
1011 | * Check the trusted installer bit first, if requested as it's somewhat
|
---|
1012 | * cheaper than the rest. We relax this for system32, like we used to,
|
---|
1013 | * as there are apparently some systems out there where the user, admin,
|
---|
1014 | * or someone has changed the ownership of core windows DLLs like
|
---|
1015 | * user32.dll. Since we need user32.dll and will be checking it's digital
|
---|
1016 | * signature, it's reasonably safe to let this thru.
|
---|
1017 | */
|
---|
1018 | if ( (pNtViRdr->fFlags & SUPHNTVI_F_TRUSTED_INSTALLER_OWNER)
|
---|
1019 | && !supHardNtViCheckIsOwnedByTrustedInstaller(pNtViRdr->hFile, pwszName))
|
---|
1020 | {
|
---|
1021 | if (!supHardViUtf16PathStartsWithEx(pwszName, (uint32_t)RTUtf16Len(pwszName),
|
---|
1022 | g_System32NtPath.UniStr.Buffer, g_System32NtPath.UniStr.Length / sizeof(WCHAR),
|
---|
1023 | true /*fCheckSlash*/))
|
---|
1024 | return RTErrInfoSetF(pErrInfo, VERR_SUP_VP_NOT_OWNED_BY_TRUSTED_INSTALLER,
|
---|
1025 | "supHardenedWinVerifyImageByHandle: TrustedInstaller is not the owner of '%ls'.", pwszName);
|
---|
1026 | SUP_DPRINTF(("%ls: Relaxing the TrustedInstaller requirement for this DLL (it's in system32).\n", pwszName));
|
---|
1027 | }
|
---|
1028 |
|
---|
1029 | /*
|
---|
1030 | * Verify it.
|
---|
1031 | *
|
---|
1032 | * The PKCS #7 SignedData signature is checked in the callback. Any
|
---|
1033 | * signing certificate restrictions are also enforced there.
|
---|
1034 | *
|
---|
1035 | * For the time being, we use the executable timestamp as the
|
---|
1036 | * certificate validation date. We must query that first to avoid
|
---|
1037 | * potential issues re-entering the loader code from the callback.
|
---|
1038 | *
|
---|
1039 | * Update: Save the first timestamp we validate with build cert and
|
---|
1040 | * use this as a minimum timestamp for further build cert
|
---|
1041 | * validations. This works around issues with old DLLs that
|
---|
1042 | * we sign against with our certificate (crt, sdl, qt).
|
---|
1043 | */
|
---|
1044 | int rc = RTLdrQueryProp(hLdrMod, RTLDRPROP_TIMESTAMP_SECONDS, &pNtViRdr->uTimestamp, sizeof(pNtViRdr->uTimestamp));
|
---|
1045 | if (RT_SUCCESS(rc))
|
---|
1046 | {
|
---|
1047 | #ifdef IN_RING3 /* Hack alert! (see above) */
|
---|
1048 | if ( (pNtViRdr->fFlags & SUPHNTVI_F_REQUIRE_KERNEL_CODE_SIGNING)
|
---|
1049 | && (pNtViRdr->fFlags & SUPHNTVI_F_REQUIRE_SIGNATURE_ENFORCEMENT)
|
---|
1050 | && pNtViRdr->uTimestamp < g_uBuildTimestampHack)
|
---|
1051 | pNtViRdr->uTimestamp = g_uBuildTimestampHack;
|
---|
1052 | #endif
|
---|
1053 |
|
---|
1054 | rc = RTLdrVerifySignature(hLdrMod, supHardNtViCallback, pNtViRdr, pErrInfo);
|
---|
1055 |
|
---|
1056 | #ifdef IN_RING3 /* Hack alert! (see above) */
|
---|
1057 | if ((pNtViRdr->fFlags & SUPHNTVI_F_REQUIRE_BUILD_CERT) && g_uBuildTimestampHack == 0 && RT_SUCCESS(rc))
|
---|
1058 | g_uBuildTimestampHack = pNtViRdr->uTimestamp;
|
---|
1059 | #endif
|
---|
1060 |
|
---|
1061 | /*
|
---|
1062 | * Microsoft doesn't sign a whole bunch of DLLs, so we have to
|
---|
1063 | * ASSUME that a bunch of system DLLs are fine.
|
---|
1064 | */
|
---|
1065 | if (rc == VERR_LDRVI_NOT_SIGNED)
|
---|
1066 | rc = supHardNtViCheckIfNotSignedOk(hLdrMod, pwszName, pNtViRdr->fFlags, pNtViRdr->hFile, rc);
|
---|
1067 | if (RT_FAILURE(rc))
|
---|
1068 | RTErrInfoAddF(pErrInfo, rc, ": %ls", pwszName);
|
---|
1069 |
|
---|
1070 | /*
|
---|
1071 | * Check for the signature checking enforcement, if requested to do so.
|
---|
1072 | */
|
---|
1073 | if (RT_SUCCESS(rc) && (pNtViRdr->fFlags & SUPHNTVI_F_REQUIRE_SIGNATURE_ENFORCEMENT))
|
---|
1074 | {
|
---|
1075 | bool fEnforced = false;
|
---|
1076 | int rc2 = RTLdrQueryProp(hLdrMod, RTLDRPROP_SIGNATURE_CHECKS_ENFORCED, &fEnforced, sizeof(fEnforced));
|
---|
1077 | if (RT_FAILURE(rc2))
|
---|
1078 | rc = RTErrInfoSetF(pErrInfo, rc2, "Querying RTLDRPROP_SIGNATURE_CHECKS_ENFORCED failed on %ls: %Rrc.",
|
---|
1079 | pwszName, rc2);
|
---|
1080 | else if (!fEnforced)
|
---|
1081 | rc = RTErrInfoSetF(pErrInfo, VERR_SUP_VP_SIGNATURE_CHECKS_NOT_ENFORCED,
|
---|
1082 | "The image '%ls' was not linked with /IntegrityCheck.", pwszName);
|
---|
1083 | }
|
---|
1084 | }
|
---|
1085 | else
|
---|
1086 | RTErrInfoSetF(pErrInfo, rc, "RTLdrQueryProp/RTLDRPROP_TIMESTAMP_SECONDS failed on %ls: %Rrc", pwszName, rc);
|
---|
1087 |
|
---|
1088 | #ifdef IN_RING3
|
---|
1089 | /*
|
---|
1090 | * Pass it thru WinVerifyTrust when possible.
|
---|
1091 | */
|
---|
1092 | rc = supHardenedWinVerifyImageTrust(pNtViRdr->hFile, pwszName, pNtViRdr->fFlags, rc, pfWinVerifyTrust, pErrInfo);
|
---|
1093 | #endif
|
---|
1094 |
|
---|
1095 | #ifdef IN_SUP_HARDENED_R3
|
---|
1096 | /*
|
---|
1097 | * Hook for the LdrLoadDll code to schedule scanning of imports.
|
---|
1098 | */
|
---|
1099 | if (RT_SUCCESS(rc))
|
---|
1100 | supR3HardenedWinVerifyCacheScheduleImports(hLdrMod, pwszName);
|
---|
1101 | #endif
|
---|
1102 |
|
---|
1103 | return rc;
|
---|
1104 | }
|
---|
1105 |
|
---|
1106 |
|
---|
1107 | /**
|
---|
1108 | * Verifies the given executable image.
|
---|
1109 | *
|
---|
1110 | * @returns IPRT status code.
|
---|
1111 | * @param hFile File handle to the executable file.
|
---|
1112 | * @param pwszName Full NT path to the DLL in question, used for
|
---|
1113 | * dealing with unsigned system dlls as well as for
|
---|
1114 | * error/logging.
|
---|
1115 | * @param fFlags Flags, SUPHNTVI_F_XXX.
|
---|
1116 | * @param pfWinVerifyTrust Where to return whether WinVerifyTrust was used.
|
---|
1117 | * @param pErrInfo Pointer to error info structure. Optional.
|
---|
1118 | */
|
---|
1119 | DECLHIDDEN(int) supHardenedWinVerifyImageByHandle(HANDLE hFile, PCRTUTF16 pwszName, uint32_t fFlags,
|
---|
1120 | bool *pfWinVerifyTrust, PRTERRINFO pErrInfo)
|
---|
1121 | {
|
---|
1122 | /*
|
---|
1123 | * Create a reader instance.
|
---|
1124 | */
|
---|
1125 | PSUPHNTVIRDR pNtViRdr;
|
---|
1126 | int rc = supHardNtViRdrCreate(hFile, pwszName, fFlags, &pNtViRdr);
|
---|
1127 | if (RT_SUCCESS(rc))
|
---|
1128 | {
|
---|
1129 | /*
|
---|
1130 | * Open the image.
|
---|
1131 | */
|
---|
1132 | RTLDRMOD hLdrMod;
|
---|
1133 | RTLDRARCH enmArch = fFlags & SUPHNTVI_F_RC_IMAGE ? RTLDRARCH_X86_32 : RTLDRARCH_HOST;
|
---|
1134 | if (fFlags & SUPHNTVI_F_RESOURCE_IMAGE)
|
---|
1135 | enmArch = RTLDRARCH_WHATEVER;
|
---|
1136 | rc = RTLdrOpenWithReader(&pNtViRdr->Core, RTLDR_O_FOR_VALIDATION, enmArch, &hLdrMod, pErrInfo);
|
---|
1137 | if (RT_SUCCESS(rc))
|
---|
1138 | {
|
---|
1139 | /*
|
---|
1140 | * Verify it.
|
---|
1141 | */
|
---|
1142 | rc = supHardenedWinVerifyImageByLdrMod(hLdrMod, pwszName, pNtViRdr, pfWinVerifyTrust, pErrInfo);
|
---|
1143 | int rc2 = RTLdrClose(hLdrMod); AssertRC(rc2);
|
---|
1144 | }
|
---|
1145 | else
|
---|
1146 | supHardNtViRdrDestroy(&pNtViRdr->Core);
|
---|
1147 | }
|
---|
1148 | SUP_DPRINTF(("supHardenedWinVerifyImageByHandle: -> %d (%ls)%s\n",
|
---|
1149 | rc, pwszName, pfWinVerifyTrust && *pfWinVerifyTrust ? "WinVerifyTrust" : ""));
|
---|
1150 | return rc;
|
---|
1151 | }
|
---|
1152 |
|
---|
1153 |
|
---|
1154 | #ifdef IN_RING3
|
---|
1155 | /**
|
---|
1156 | * supHardenedWinVerifyImageByHandle version without the name.
|
---|
1157 | *
|
---|
1158 | * The name is derived from the handle.
|
---|
1159 | *
|
---|
1160 | * @returns IPRT status code.
|
---|
1161 | * @param hFile File handle to the executable file.
|
---|
1162 | * @param fFlags Flags, SUPHNTVI_F_XXX.
|
---|
1163 | * @param pErrInfo Pointer to error info structure. Optional.
|
---|
1164 | */
|
---|
1165 | DECLHIDDEN(int) supHardenedWinVerifyImageByHandleNoName(HANDLE hFile, uint32_t fFlags, PRTERRINFO pErrInfo)
|
---|
1166 | {
|
---|
1167 | /*
|
---|
1168 | * Determine the NT name and call the verification function.
|
---|
1169 | */
|
---|
1170 | union
|
---|
1171 | {
|
---|
1172 | UNICODE_STRING UniStr;
|
---|
1173 | uint8_t abBuffer[(MAX_PATH + 8 + 1) * 2];
|
---|
1174 | } uBuf;
|
---|
1175 |
|
---|
1176 | ULONG cbIgn;
|
---|
1177 | NTSTATUS rcNt = NtQueryObject(hFile,
|
---|
1178 | ObjectNameInformation,
|
---|
1179 | &uBuf,
|
---|
1180 | sizeof(uBuf) - sizeof(WCHAR),
|
---|
1181 | &cbIgn);
|
---|
1182 | if (NT_SUCCESS(rcNt))
|
---|
1183 | uBuf.UniStr.Buffer[uBuf.UniStr.Length / sizeof(WCHAR)] = '\0';
|
---|
1184 | else
|
---|
1185 | uBuf.UniStr.Buffer = (WCHAR *)L"TODO3";
|
---|
1186 |
|
---|
1187 | return supHardenedWinVerifyImageByHandle(hFile, uBuf.UniStr.Buffer, fFlags, NULL /*pfWinVerifyTrust*/, pErrInfo);
|
---|
1188 | }
|
---|
1189 | #endif /* IN_RING3 */
|
---|
1190 |
|
---|
1191 |
|
---|
1192 | /**
|
---|
1193 | * Retrieves the full official path to the system root or one of it's sub
|
---|
1194 | * directories.
|
---|
1195 | *
|
---|
1196 | * This code is also used by the support driver.
|
---|
1197 | *
|
---|
1198 | * @returns VBox status code.
|
---|
1199 | * @param pvBuf The output buffer. This will contain a
|
---|
1200 | * UNICODE_STRING followed (at the kernel's
|
---|
1201 | * discretion) the string buffer.
|
---|
1202 | * @param cbBuf The size of the buffer @a pvBuf points to.
|
---|
1203 | * @param enmDir Which directory under the system root we're
|
---|
1204 | * interested in.
|
---|
1205 | * @param pErrInfo Pointer to error info structure. Optional.
|
---|
1206 | */
|
---|
1207 | DECLHIDDEN(int) supHardNtGetSystemRootDir(void *pvBuf, uint32_t cbBuf, SUPHARDNTSYSROOTDIR enmDir, PRTERRINFO pErrInfo)
|
---|
1208 | {
|
---|
1209 | HANDLE hFile = RTNT_INVALID_HANDLE_VALUE;
|
---|
1210 | IO_STATUS_BLOCK Ios = RTNT_IO_STATUS_BLOCK_INITIALIZER;
|
---|
1211 |
|
---|
1212 | UNICODE_STRING NtName;
|
---|
1213 | switch (enmDir)
|
---|
1214 | {
|
---|
1215 | case kSupHardNtSysRootDir_System32:
|
---|
1216 | {
|
---|
1217 | static const WCHAR s_wszNameSystem32[] = L"\\SystemRoot\\System32\\";
|
---|
1218 | NtName.Buffer = (PWSTR)s_wszNameSystem32;
|
---|
1219 | NtName.Length = sizeof(s_wszNameSystem32) - sizeof(WCHAR);
|
---|
1220 | NtName.MaximumLength = sizeof(s_wszNameSystem32);
|
---|
1221 | break;
|
---|
1222 | }
|
---|
1223 | case kSupHardNtSysRootDir_WinSxS:
|
---|
1224 | {
|
---|
1225 | static const WCHAR s_wszNameWinSxS[] = L"\\SystemRoot\\WinSxS\\";
|
---|
1226 | NtName.Buffer = (PWSTR)s_wszNameWinSxS;
|
---|
1227 | NtName.Length = sizeof(s_wszNameWinSxS) - sizeof(WCHAR);
|
---|
1228 | NtName.MaximumLength = sizeof(s_wszNameWinSxS);
|
---|
1229 | break;
|
---|
1230 | }
|
---|
1231 | default:
|
---|
1232 | AssertFailed();
|
---|
1233 | return VERR_INVALID_PARAMETER;
|
---|
1234 | }
|
---|
1235 |
|
---|
1236 | OBJECT_ATTRIBUTES ObjAttr;
|
---|
1237 | InitializeObjectAttributes(&ObjAttr, &NtName, OBJ_CASE_INSENSITIVE, NULL /*hRootDir*/, NULL /*pSecDesc*/);
|
---|
1238 |
|
---|
1239 | NTSTATUS rcNt = NtCreateFile(&hFile,
|
---|
1240 | FILE_READ_DATA | SYNCHRONIZE,
|
---|
1241 | &ObjAttr,
|
---|
1242 | &Ios,
|
---|
1243 | NULL /* Allocation Size*/,
|
---|
1244 | FILE_ATTRIBUTE_NORMAL,
|
---|
1245 | FILE_SHARE_READ | FILE_SHARE_WRITE,
|
---|
1246 | FILE_OPEN,
|
---|
1247 | FILE_DIRECTORY_FILE | FILE_OPEN_FOR_BACKUP_INTENT | FILE_SYNCHRONOUS_IO_NONALERT,
|
---|
1248 | NULL /*EaBuffer*/,
|
---|
1249 | 0 /*EaLength*/);
|
---|
1250 | if (NT_SUCCESS(rcNt))
|
---|
1251 | rcNt = Ios.Status;
|
---|
1252 | if (NT_SUCCESS(rcNt))
|
---|
1253 | {
|
---|
1254 | ULONG cbIgn;
|
---|
1255 | rcNt = NtQueryObject(hFile,
|
---|
1256 | ObjectNameInformation,
|
---|
1257 | pvBuf,
|
---|
1258 | cbBuf - sizeof(WCHAR),
|
---|
1259 | &cbIgn);
|
---|
1260 | NtClose(hFile);
|
---|
1261 | if (NT_SUCCESS(rcNt))
|
---|
1262 | {
|
---|
1263 | PUNICODE_STRING pUniStr = (PUNICODE_STRING)pvBuf;
|
---|
1264 | if (pUniStr->Length > 0)
|
---|
1265 | {
|
---|
1266 | /* Make sure it's terminated so it can safely be printed.*/
|
---|
1267 | pUniStr->Buffer[pUniStr->Length / sizeof(WCHAR)] = '\0';
|
---|
1268 | return VINF_SUCCESS;
|
---|
1269 | }
|
---|
1270 |
|
---|
1271 | return RTErrInfoSetF(pErrInfo, VERR_SUP_VP_SYSTEM32_PATH,
|
---|
1272 | "NtQueryObject returned an empty path for '%ls'", NtName.Buffer);
|
---|
1273 | }
|
---|
1274 | return RTErrInfoSetF(pErrInfo, VERR_SUP_VP_SYSTEM32_PATH, "NtQueryObject failed on '%ls' dir: %#x", NtName.Buffer, rcNt);
|
---|
1275 | }
|
---|
1276 | return RTErrInfoSetF(pErrInfo, VERR_SUP_VP_SYSTEM32_PATH, "Failure to open '%ls': %#x", NtName.Buffer, rcNt);
|
---|
1277 | }
|
---|
1278 |
|
---|
1279 |
|
---|
1280 | /**
|
---|
1281 | * Initialize one certificate entry.
|
---|
1282 | *
|
---|
1283 | * @returns VBox status code.
|
---|
1284 | * @param pCert The X.509 certificate representation to init.
|
---|
1285 | * @param pabCert The raw DER encoded certificate.
|
---|
1286 | * @param cbCert The size of the raw certificate.
|
---|
1287 | * @param pErrInfo Where to return extended error info. Optional.
|
---|
1288 | * @param pszErrorTag Error tag.
|
---|
1289 | */
|
---|
1290 | static int supHardNtViCertInit(PRTCRX509CERTIFICATE pCert, unsigned char const *pabCert, unsigned cbCert,
|
---|
1291 | PRTERRINFO pErrInfo, const char *pszErrorTag)
|
---|
1292 | {
|
---|
1293 | AssertReturn(cbCert > 16 && cbCert < _128K,
|
---|
1294 | RTErrInfoSetF(pErrInfo, VERR_INTERNAL_ERROR_3, "%s: cbCert=%#x out of range", pszErrorTag, cbCert));
|
---|
1295 | AssertReturn(!RTCrX509Certificate_IsPresent(pCert),
|
---|
1296 | RTErrInfoSetF(pErrInfo, VERR_WRONG_ORDER, "%s: Certificate already decoded?", pszErrorTag));
|
---|
1297 |
|
---|
1298 | RTASN1CURSORPRIMARY PrimaryCursor;
|
---|
1299 | RTAsn1CursorInitPrimary(&PrimaryCursor, pabCert, cbCert, pErrInfo, &g_RTAsn1DefaultAllocator, RTASN1CURSOR_FLAGS_DER, NULL);
|
---|
1300 | int rc = RTCrX509Certificate_DecodeAsn1(&PrimaryCursor.Cursor, 0, pCert, pszErrorTag);
|
---|
1301 | if (RT_SUCCESS(rc))
|
---|
1302 | rc = RTCrX509Certificate_CheckSanity(pCert, 0, pErrInfo, pszErrorTag);
|
---|
1303 | return rc;
|
---|
1304 | }
|
---|
1305 |
|
---|
1306 |
|
---|
1307 | static int supHardNtViCertStoreAddArray(RTCRSTORE hStore, PCSUPTAENTRY paCerts, unsigned cCerts, PRTERRINFO pErrInfo)
|
---|
1308 | {
|
---|
1309 | for (uint32_t i = 0; i < cCerts; i++)
|
---|
1310 | {
|
---|
1311 | int rc = RTCrStoreCertAddEncoded(hStore, RTCRCERTCTX_F_ENC_TAF_DER, paCerts[i].pch, paCerts[i].cb, pErrInfo);
|
---|
1312 | if (RT_FAILURE(rc))
|
---|
1313 | return rc;
|
---|
1314 | }
|
---|
1315 | return VINF_SUCCESS;
|
---|
1316 | }
|
---|
1317 |
|
---|
1318 |
|
---|
1319 | /**
|
---|
1320 | * Initialize a certificate table.
|
---|
1321 | *
|
---|
1322 | * @param phStore Where to return the store pointer.
|
---|
1323 | * @param paCerts1 Pointer to the first certificate table.
|
---|
1324 | * @param cCerts1 Entries in the first certificate table.
|
---|
1325 | * @param paCerts2 Pointer to the second certificate table.
|
---|
1326 | * @param cCerts2 Entries in the second certificate table.
|
---|
1327 | * @param paCerts3 Pointer to the third certificate table.
|
---|
1328 | * @param cCerts3 Entries in the third certificate table.
|
---|
1329 | * @param pErrInfo Where to return extended error info. Optional.
|
---|
1330 | * @param pszErrorTag Error tag.
|
---|
1331 | */
|
---|
1332 | static int supHardNtViCertStoreInit(PRTCRSTORE phStore,
|
---|
1333 | PCSUPTAENTRY paCerts1, unsigned cCerts1,
|
---|
1334 | PCSUPTAENTRY paCerts2, unsigned cCerts2,
|
---|
1335 | PCSUPTAENTRY paCerts3, unsigned cCerts3,
|
---|
1336 | PRTERRINFO pErrInfo, const char *pszErrorTag)
|
---|
1337 | {
|
---|
1338 | AssertReturn(*phStore == NIL_RTCRSTORE, VERR_WRONG_ORDER);
|
---|
1339 |
|
---|
1340 | int rc = RTCrStoreCreateInMem(phStore, cCerts1 + cCerts2);
|
---|
1341 | if (RT_FAILURE(rc))
|
---|
1342 | return RTErrInfoSetF(pErrInfo, rc, "RTCrStoreCreateMemoryStore failed: %Rrc", rc);
|
---|
1343 |
|
---|
1344 | rc = supHardNtViCertStoreAddArray(*phStore, paCerts1, cCerts1, pErrInfo);
|
---|
1345 | if (RT_SUCCESS(rc))
|
---|
1346 | rc = supHardNtViCertStoreAddArray(*phStore, paCerts2, cCerts2, pErrInfo);
|
---|
1347 | if (RT_SUCCESS(rc))
|
---|
1348 | rc = supHardNtViCertStoreAddArray(*phStore, paCerts3, cCerts3, pErrInfo);
|
---|
1349 | return rc;
|
---|
1350 | }
|
---|
1351 |
|
---|
1352 |
|
---|
1353 |
|
---|
1354 | #ifdef IN_RING3
|
---|
1355 | /**
|
---|
1356 | * Initializes the windows paths.
|
---|
1357 | */
|
---|
1358 | static void supHardenedWinInitImageVerifierWinPaths(void)
|
---|
1359 | {
|
---|
1360 | /*
|
---|
1361 | * Windows paths that we're interested in.
|
---|
1362 | */
|
---|
1363 | static const struct
|
---|
1364 | {
|
---|
1365 | SUPSYSROOTDIRBUF *pNtPath;
|
---|
1366 | WCHAR const *pwszRegValue;
|
---|
1367 | const char *pszLogName;
|
---|
1368 | } s_aPaths[] =
|
---|
1369 | {
|
---|
1370 | { &g_ProgramFilesNtPath, L"ProgramFilesDir", "ProgDir" },
|
---|
1371 | { &g_CommonFilesNtPath, L"CommonFilesDir", "ComDir" },
|
---|
1372 | # ifdef RT_ARCH_AMD64
|
---|
1373 | { &g_ProgramFilesX86NtPath, L"ProgramFilesDir (x86)", "ProgDir32" },
|
---|
1374 | { &g_CommonFilesX86NtPath, L"CommonFilesDir (x86)", "ComDir32" },
|
---|
1375 | # endif
|
---|
1376 | };
|
---|
1377 |
|
---|
1378 | /*
|
---|
1379 | * Open the registry key containing the paths.
|
---|
1380 | */
|
---|
1381 | UNICODE_STRING NtName = RTNT_CONSTANT_UNISTR(L"\\Registry\\Machine\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion");
|
---|
1382 | OBJECT_ATTRIBUTES ObjAttr;
|
---|
1383 | InitializeObjectAttributes(&ObjAttr, &NtName, OBJ_CASE_INSENSITIVE, NULL /*hRootDir*/, NULL /*pSecDesc*/);
|
---|
1384 | HANDLE hKey;
|
---|
1385 | NTSTATUS rcNt = NtOpenKey(&hKey, KEY_QUERY_VALUE, &ObjAttr);
|
---|
1386 | if (NT_SUCCESS(rcNt))
|
---|
1387 | {
|
---|
1388 | /*
|
---|
1389 | * Loop over the paths and resolve their NT paths.
|
---|
1390 | */
|
---|
1391 | for (uint32_t i = 0; i < RT_ELEMENTS(s_aPaths); i++)
|
---|
1392 | {
|
---|
1393 | /*
|
---|
1394 | * Query the value first.
|
---|
1395 | */
|
---|
1396 | UNICODE_STRING ValueName;
|
---|
1397 | ValueName.Buffer = (WCHAR *)s_aPaths[i].pwszRegValue;
|
---|
1398 | ValueName.Length = (USHORT)(RTUtf16Len(s_aPaths[i].pwszRegValue) * sizeof(WCHAR));
|
---|
1399 | ValueName.MaximumLength = ValueName.Length + sizeof(WCHAR);
|
---|
1400 |
|
---|
1401 | union
|
---|
1402 | {
|
---|
1403 | KEY_VALUE_PARTIAL_INFORMATION PartialInfo;
|
---|
1404 | uint8_t abPadding[sizeof(KEY_VALUE_PARTIAL_INFORMATION) + sizeof(WCHAR) * 128];
|
---|
1405 | uint64_t uAlign;
|
---|
1406 | } uBuf;
|
---|
1407 |
|
---|
1408 | ULONG cbActual = 0;
|
---|
1409 | rcNt = NtQueryValueKey(hKey, &ValueName, KeyValuePartialInformation, &uBuf, sizeof(uBuf) - sizeof(WCHAR), &cbActual);
|
---|
1410 | if (NT_SUCCESS(rcNt))
|
---|
1411 | {
|
---|
1412 | /*
|
---|
1413 | * Must be a simple string value, terminate it.
|
---|
1414 | */
|
---|
1415 | if ( uBuf.PartialInfo.Type == REG_EXPAND_SZ
|
---|
1416 | || uBuf.PartialInfo.Type == REG_SZ)
|
---|
1417 | {
|
---|
1418 | /*
|
---|
1419 | * Expand any environment variable references before opening it.
|
---|
1420 | * We use the result buffer as storage for the expaneded path,
|
---|
1421 | * reserving space for the windows name space prefix.
|
---|
1422 | */
|
---|
1423 | UNICODE_STRING Src;
|
---|
1424 | Src.Buffer = (WCHAR *)uBuf.PartialInfo.Data;
|
---|
1425 | Src.Length = uBuf.PartialInfo.DataLength;
|
---|
1426 | if (Src.Length >= sizeof(WCHAR) && Src.Buffer[Src.Length / sizeof(WCHAR) - 1] == '\0')
|
---|
1427 | Src.Length -= sizeof(WCHAR);
|
---|
1428 | Src.MaximumLength = Src.Length + sizeof(WCHAR);
|
---|
1429 | Src.Buffer[uBuf.PartialInfo.DataLength / sizeof(WCHAR)] = '\0';
|
---|
1430 |
|
---|
1431 | s_aPaths[i].pNtPath->awcBuffer[0] = '\\';
|
---|
1432 | s_aPaths[i].pNtPath->awcBuffer[1] = '?';
|
---|
1433 | s_aPaths[i].pNtPath->awcBuffer[2] = '?';
|
---|
1434 | s_aPaths[i].pNtPath->awcBuffer[3] = '\\';
|
---|
1435 | UNICODE_STRING Dst;
|
---|
1436 | Dst.Buffer = &s_aPaths[i].pNtPath->awcBuffer[4];
|
---|
1437 | Dst.MaximumLength = sizeof(s_aPaths[i].pNtPath->awcBuffer) - sizeof(WCHAR) * 5;
|
---|
1438 | Dst.Length = Dst.MaximumLength;
|
---|
1439 |
|
---|
1440 | if (uBuf.PartialInfo.Type == REG_EXPAND_SZ)
|
---|
1441 | rcNt = RtlExpandEnvironmentStrings_U(NULL, &Src, &Dst, NULL);
|
---|
1442 | else
|
---|
1443 | {
|
---|
1444 | memcpy(Dst.Buffer, Src.Buffer, Src.Length);
|
---|
1445 | Dst.Length = Src.Length;
|
---|
1446 | }
|
---|
1447 | if (NT_SUCCESS(rcNt))
|
---|
1448 | {
|
---|
1449 | Dst.Buffer[Dst.Length / sizeof(WCHAR)] = '\0';
|
---|
1450 |
|
---|
1451 | /*
|
---|
1452 | * Include the \\??\\ prefix in the result and open the path.
|
---|
1453 | */
|
---|
1454 | Dst.Buffer -= 4;
|
---|
1455 | Dst.Length += 4 * sizeof(WCHAR);
|
---|
1456 | Dst.MaximumLength += 4 * sizeof(WCHAR);
|
---|
1457 | InitializeObjectAttributes(&ObjAttr, &Dst, OBJ_CASE_INSENSITIVE, NULL /*hRootDir*/, NULL /*pSecDesc*/);
|
---|
1458 | HANDLE hFile = INVALID_HANDLE_VALUE;
|
---|
1459 | IO_STATUS_BLOCK Ios = RTNT_IO_STATUS_BLOCK_INITIALIZER;
|
---|
1460 | NTSTATUS rcNt = NtCreateFile(&hFile,
|
---|
1461 | FILE_READ_DATA | SYNCHRONIZE,
|
---|
1462 | &ObjAttr,
|
---|
1463 | &Ios,
|
---|
1464 | NULL /* Allocation Size*/,
|
---|
1465 | FILE_ATTRIBUTE_NORMAL,
|
---|
1466 | FILE_SHARE_READ | FILE_SHARE_WRITE,
|
---|
1467 | FILE_OPEN,
|
---|
1468 | FILE_DIRECTORY_FILE | FILE_OPEN_FOR_BACKUP_INTENT
|
---|
1469 | | FILE_SYNCHRONOUS_IO_NONALERT,
|
---|
1470 | NULL /*EaBuffer*/,
|
---|
1471 | 0 /*EaLength*/);
|
---|
1472 | if (NT_SUCCESS(rcNt))
|
---|
1473 | rcNt = Ios.Status;
|
---|
1474 | if (NT_SUCCESS(rcNt))
|
---|
1475 | {
|
---|
1476 | /*
|
---|
1477 | * Query the real NT name.
|
---|
1478 | */
|
---|
1479 | ULONG cbIgn;
|
---|
1480 | rcNt = NtQueryObject(hFile,
|
---|
1481 | ObjectNameInformation,
|
---|
1482 | s_aPaths[i].pNtPath,
|
---|
1483 | sizeof(*s_aPaths[i].pNtPath) - sizeof(WCHAR),
|
---|
1484 | &cbIgn);
|
---|
1485 | if (NT_SUCCESS(rcNt))
|
---|
1486 | {
|
---|
1487 | if (s_aPaths[i].pNtPath->UniStr.Length > 0)
|
---|
1488 | {
|
---|
1489 | /* Make sure it's terminated.*/
|
---|
1490 | s_aPaths[i].pNtPath->UniStr.Buffer[s_aPaths[i].pNtPath->UniStr.Length / sizeof(WCHAR)] = '\0';
|
---|
1491 | SUP_DPRINTF(("%s:%*s %ls\n", s_aPaths[i].pszLogName, 9 - strlen(s_aPaths[i].pszLogName), "",
|
---|
1492 | s_aPaths[i].pNtPath->UniStr.Buffer));
|
---|
1493 | }
|
---|
1494 | else
|
---|
1495 | {
|
---|
1496 | SUP_DPRINTF(("%s: NtQueryObject returned empty string\n", s_aPaths[i].pszLogName));
|
---|
1497 | rcNt = STATUS_INVALID_PARAMETER;
|
---|
1498 | }
|
---|
1499 | }
|
---|
1500 | else
|
---|
1501 | SUP_DPRINTF(("%s: NtQueryObject failed: %#x\n", s_aPaths[i].pszLogName, rcNt));
|
---|
1502 | NtClose(hFile);
|
---|
1503 | }
|
---|
1504 | else
|
---|
1505 | SUP_DPRINTF(("%s: NtCreateFile failed: %#x (%ls)\n",
|
---|
1506 | s_aPaths[i].pszLogName, rcNt, Dst.Buffer));
|
---|
1507 | }
|
---|
1508 | else
|
---|
1509 | SUP_DPRINTF(("%s: RtlExpandEnvironmentStrings_U failed: %#x (%ls)\n",
|
---|
1510 | s_aPaths[i].pszLogName, rcNt, Src.Buffer));
|
---|
1511 | }
|
---|
1512 | else
|
---|
1513 | {
|
---|
1514 | SUP_DPRINTF(("%s: type mismatch: %#x\n", s_aPaths[i].pszLogName, uBuf.PartialInfo.Type));
|
---|
1515 | rcNt = STATUS_INVALID_PARAMETER;
|
---|
1516 | }
|
---|
1517 | }
|
---|
1518 | else
|
---|
1519 | SUP_DPRINTF(("%s: NtQueryValueKey failed: %#x\n", s_aPaths[i].pszLogName, rcNt));
|
---|
1520 |
|
---|
1521 | /* Stub the entry on failure. */
|
---|
1522 | if (!NT_SUCCESS(rcNt))
|
---|
1523 | {
|
---|
1524 | s_aPaths[i].pNtPath->UniStr.Length = 0;
|
---|
1525 | s_aPaths[i].pNtPath->UniStr.Buffer = NULL;
|
---|
1526 | }
|
---|
1527 | }
|
---|
1528 | NtClose(hKey);
|
---|
1529 | }
|
---|
1530 | else
|
---|
1531 | {
|
---|
1532 | SUP_DPRINTF(("NtOpenKey(%ls) failed: %#x\n", NtName.Buffer, rcNt));
|
---|
1533 |
|
---|
1534 | /* Stub all the entries on failure. */
|
---|
1535 | for (uint32_t i = 0; i < RT_ELEMENTS(s_aPaths); i++)
|
---|
1536 | {
|
---|
1537 | s_aPaths[i].pNtPath->UniStr.Length = 0;
|
---|
1538 | s_aPaths[i].pNtPath->UniStr.Buffer = NULL;
|
---|
1539 | }
|
---|
1540 | }
|
---|
1541 | }
|
---|
1542 | #endif /* IN_RING3 */
|
---|
1543 |
|
---|
1544 |
|
---|
1545 | /**
|
---|
1546 | * This initializes the certificates globals so we don't have to reparse them
|
---|
1547 | * every time we need to verify an image.
|
---|
1548 | *
|
---|
1549 | * @returns IPRT status code.
|
---|
1550 | * @param pErrInfo Where to return extended error info. Optional.
|
---|
1551 | */
|
---|
1552 | DECLHIDDEN(int) supHardenedWinInitImageVerifier(PRTERRINFO pErrInfo)
|
---|
1553 | {
|
---|
1554 | AssertReturn(!RTCrX509Certificate_IsPresent(&g_BuildX509Cert), VERR_WRONG_ORDER);
|
---|
1555 |
|
---|
1556 | /*
|
---|
1557 | * Get the system root paths.
|
---|
1558 | */
|
---|
1559 | int rc = supHardNtGetSystemRootDir(&g_System32NtPath, sizeof(g_System32NtPath), kSupHardNtSysRootDir_System32, pErrInfo);
|
---|
1560 | if (RT_SUCCESS(rc))
|
---|
1561 | rc = supHardNtGetSystemRootDir(&g_WinSxSNtPath, sizeof(g_WinSxSNtPath), kSupHardNtSysRootDir_WinSxS, pErrInfo);
|
---|
1562 | if (RT_SUCCESS(rc))
|
---|
1563 | {
|
---|
1564 | SUP_DPRINTF(("System32: %ls\n", g_System32NtPath.UniStr.Buffer));
|
---|
1565 | SUP_DPRINTF(("WinSxS: %ls\n", g_WinSxSNtPath.UniStr.Buffer));
|
---|
1566 | #ifdef IN_RING3
|
---|
1567 | supHardenedWinInitImageVerifierWinPaths();
|
---|
1568 | #endif
|
---|
1569 |
|
---|
1570 | /*
|
---|
1571 | * Initialize it, leaving the cleanup to the termination call.
|
---|
1572 | */
|
---|
1573 | rc = supHardNtViCertInit(&g_BuildX509Cert, g_abSUPBuildCert, g_cbSUPBuildCert, pErrInfo, "BuildCertificate");
|
---|
1574 | if (RT_SUCCESS(rc))
|
---|
1575 | rc = supHardNtViCertStoreInit(&g_hSpcRootStore, g_aSUPSpcRootTAs, g_cSUPSpcRootTAs,
|
---|
1576 | NULL, 0, NULL, 0, pErrInfo, "SpcRoot");
|
---|
1577 | if (RT_SUCCESS(rc))
|
---|
1578 | rc = supHardNtViCertStoreInit(&g_hNtKernelRootStore, g_aSUPNtKernelRootTAs, g_cSUPNtKernelRootTAs,
|
---|
1579 | NULL, 0, NULL, 0, pErrInfo, "NtKernelRoot");
|
---|
1580 | if (RT_SUCCESS(rc))
|
---|
1581 | rc = supHardNtViCertStoreInit(&g_hSpcAndNtKernelRootStore,
|
---|
1582 | g_aSUPSpcRootTAs, g_cSUPSpcRootTAs,
|
---|
1583 | g_aSUPNtKernelRootTAs, g_cSUPNtKernelRootTAs,
|
---|
1584 | g_aSUPTimestampTAs, g_cSUPTimestampTAs,
|
---|
1585 | pErrInfo, "SpcAndNtKernelRoot");
|
---|
1586 | if (RT_SUCCESS(rc))
|
---|
1587 | rc = supHardNtViCertStoreInit(&g_hSpcAndNtKernelSuppStore,
|
---|
1588 | NULL, 0, NULL, 0, NULL, 0,
|
---|
1589 | pErrInfo, "SpcAndNtKernelSupplemental");
|
---|
1590 |
|
---|
1591 | #if 0 /* For the time being, always trust the build certificate. It bypasses the timestamp issues of CRT and SDL. */
|
---|
1592 | /* If the build certificate is a test singing certificate, it must be a
|
---|
1593 | trusted root or we'll fail to validate anything. */
|
---|
1594 | if ( RT_SUCCESS(rc)
|
---|
1595 | && RTCrX509Name_Compare(&g_BuildX509Cert.TbsCertificate.Subject, &g_BuildX509Cert.TbsCertificate.Issuer) == 0)
|
---|
1596 | #else
|
---|
1597 | if (RT_SUCCESS(rc))
|
---|
1598 | #endif
|
---|
1599 | rc = RTCrStoreCertAddEncoded(g_hSpcAndNtKernelRootStore, RTCRCERTCTX_F_ENC_X509_DER,
|
---|
1600 | g_abSUPBuildCert, g_cbSUPBuildCert, pErrInfo);
|
---|
1601 |
|
---|
1602 | if (RT_SUCCESS(rc))
|
---|
1603 | {
|
---|
1604 | /*
|
---|
1605 | * Finally initialize known SIDs that we use.
|
---|
1606 | */
|
---|
1607 | SID_IDENTIFIER_AUTHORITY s_NtAuth = SECURITY_NT_AUTHORITY;
|
---|
1608 | NTSTATUS rcNt = RtlInitializeSid(&g_TrustedInstallerSid, &s_NtAuth, SECURITY_SERVICE_ID_RID_COUNT);
|
---|
1609 | if (NT_SUCCESS(rcNt))
|
---|
1610 | {
|
---|
1611 | *RtlSubAuthoritySid(&g_TrustedInstallerSid, 0) = SECURITY_SERVICE_ID_BASE_RID;
|
---|
1612 | *RtlSubAuthoritySid(&g_TrustedInstallerSid, 1) = 956008885;
|
---|
1613 | *RtlSubAuthoritySid(&g_TrustedInstallerSid, 2) = 3418522649;
|
---|
1614 | *RtlSubAuthoritySid(&g_TrustedInstallerSid, 3) = 1831038044;
|
---|
1615 | *RtlSubAuthoritySid(&g_TrustedInstallerSid, 4) = 1853292631;
|
---|
1616 | *RtlSubAuthoritySid(&g_TrustedInstallerSid, 5) = 2271478464;
|
---|
1617 | return VINF_SUCCESS;
|
---|
1618 | }
|
---|
1619 | rc = RTErrConvertFromNtStatus(rcNt);
|
---|
1620 | }
|
---|
1621 | supHardenedWinTermImageVerifier();
|
---|
1622 | }
|
---|
1623 | return rc;
|
---|
1624 | }
|
---|
1625 |
|
---|
1626 |
|
---|
1627 | /**
|
---|
1628 | * Releases resources allocated by supHardenedWinInitImageVerifier.
|
---|
1629 | */
|
---|
1630 | DECLHIDDEN(void) supHardenedWinTermImageVerifier(void)
|
---|
1631 | {
|
---|
1632 | if (RTCrX509Certificate_IsPresent(&g_BuildX509Cert))
|
---|
1633 | RTAsn1VtDelete(&g_BuildX509Cert.SeqCore.Asn1Core);
|
---|
1634 |
|
---|
1635 | RTCrStoreRelease(g_hSpcAndNtKernelSuppStore);
|
---|
1636 | g_hSpcAndNtKernelSuppStore = NIL_RTCRSTORE;
|
---|
1637 | RTCrStoreRelease(g_hSpcAndNtKernelRootStore);
|
---|
1638 | g_hSpcAndNtKernelRootStore = NIL_RTCRSTORE;
|
---|
1639 |
|
---|
1640 | RTCrStoreRelease(g_hNtKernelRootStore);
|
---|
1641 | g_hNtKernelRootStore = NIL_RTCRSTORE;
|
---|
1642 | RTCrStoreRelease(g_hSpcRootStore);
|
---|
1643 | g_hSpcRootStore = NIL_RTCRSTORE;
|
---|
1644 | }
|
---|
1645 |
|
---|
1646 | #ifdef IN_RING3
|
---|
1647 |
|
---|
1648 | /**
|
---|
1649 | * This is a hardcoded list of certificates we thing we might need.
|
---|
1650 | *
|
---|
1651 | * @returns true if wanted, false if not.
|
---|
1652 | * @param pCert The certificate.
|
---|
1653 | */
|
---|
1654 | static bool supR3HardenedWinIsDesiredRootCA(PCRTCRX509CERTIFICATE pCert)
|
---|
1655 | {
|
---|
1656 | /*
|
---|
1657 | * Check that it's a plausible root certificate.
|
---|
1658 | */
|
---|
1659 | if (!RTCrX509Certificate_IsSelfSigned(pCert))
|
---|
1660 | return false;
|
---|
1661 | if (RTAsn1Integer_UnsignedCompareWithU32(&pCert->TbsCertificate.T0.Version, 3) > 0)
|
---|
1662 | {
|
---|
1663 | if ( !(pCert->TbsCertificate.T3.fExtKeyUsage & RTCRX509CERT_KEY_USAGE_F_KEY_CERT_SIGN)
|
---|
1664 | && (pCert->TbsCertificate.T3.fFlags & RTCRX509TBSCERTIFICATE_F_PRESENT_KEY_USAGE) )
|
---|
1665 | return false;
|
---|
1666 | if ( pCert->TbsCertificate.T3.pBasicConstraints
|
---|
1667 | && !pCert->TbsCertificate.T3.pBasicConstraints->CA.fValue)
|
---|
1668 | return false;
|
---|
1669 | }
|
---|
1670 | if (pCert->TbsCertificate.SubjectPublicKeyInfo.SubjectPublicKey.cBits < 256) /* mostly for u64KeyId reading. */
|
---|
1671 | return false;
|
---|
1672 |
|
---|
1673 | /*
|
---|
1674 | * Array of names and key clues of the certificates we want.
|
---|
1675 | */
|
---|
1676 | static struct
|
---|
1677 | {
|
---|
1678 | uint64_t u64KeyId;
|
---|
1679 | const char *pszName;
|
---|
1680 | } const s_aWanted[] =
|
---|
1681 | {
|
---|
1682 | /* SPC */
|
---|
1683 | { UINT64_C(0xffffffffffffffff), "C=US, O=VeriSign, Inc., OU=Class 3 Public Primary Certification Authority" },
|
---|
1684 | { UINT64_C(0xffffffffffffffff), "L=Internet, O=VeriSign, Inc., OU=VeriSign Commercial Software Publishers CA" },
|
---|
1685 | { UINT64_C(0x491857ead79dde00), "C=US, O=The Go Daddy Group, Inc., OU=Go Daddy Class 2 Certification Authority" },
|
---|
1686 |
|
---|
1687 | /* TS */
|
---|
1688 | { UINT64_C(0xffffffffffffffff), "O=Microsoft Trust Network, OU=Microsoft Corporation, OU=Microsoft Time Stamping Service Root, OU=Copyright (c) 1997 Microsoft Corp." },
|
---|
1689 | { UINT64_C(0xffffffffffffffff), "O=VeriSign Trust Network, OU=VeriSign, Inc., OU=VeriSign Time Stamping Service Root, OU=NO LIABILITY ACCEPTED, (c)97 VeriSign, Inc." },
|
---|
1690 | { UINT64_C(0xffffffffffffffff), "C=ZA, ST=Western Cape, L=Durbanville, O=Thawte, OU=Thawte Certification, CN=Thawte Timestamping CA" },
|
---|
1691 |
|
---|
1692 | /* Additional Windows 8.1 list: */
|
---|
1693 | { UINT64_C(0x5ad46780fa5df300), "DC=com, DC=microsoft, CN=Microsoft Root Certificate Authority" },
|
---|
1694 | { UINT64_C(0x3be670c1bd02a900), "OU=Copyright (c) 1997 Microsoft Corp., OU=Microsoft Corporation, CN=Microsoft Root Authority" },
|
---|
1695 | { UINT64_C(0x4d3835aa4180b200), "C=US, ST=Washington, L=Redmond, O=Microsoft Corporation, CN=Microsoft Root Certificate Authority 2011" },
|
---|
1696 | { UINT64_C(0x646e3fe3ba08df00), "C=US, O=MSFT, CN=Microsoft Authenticode(tm) Root Authority" },
|
---|
1697 | { UINT64_C(0xece4e4289e08b900), "C=US, ST=Washington, L=Redmond, O=Microsoft Corporation, CN=Microsoft Root Certificate Authority 2010" },
|
---|
1698 | { UINT64_C(0x59faf1086271bf00), "C=US, ST=Arizona, L=Scottsdale, O=GoDaddy.com, Inc., CN=Go Daddy Root Certificate Authority - G2" },
|
---|
1699 | { UINT64_C(0x3d98ab22bb04a300), "C=IE, O=Baltimore, OU=CyberTrust, CN=Baltimore CyberTrust Root" },
|
---|
1700 | { UINT64_C(0x91e3728b8b40d000), "C=GB, ST=Greater Manchester, L=Salford, O=COMODO CA Limited, CN=COMODO Certification Authority" },
|
---|
1701 | { UINT64_C(0x61a3a33f81aace00), "C=US, ST=UT, L=Salt Lake City, O=The USERTRUST Network, OU=http://www.usertrust.com, CN=UTN-USERFirst-Object" },
|
---|
1702 | { UINT64_C(0x9e5bc2d78b6a3636), "C=ZA, ST=Western Cape, L=Cape Town, O=Thawte Consulting cc, OU=Certification Services Division, CN=Thawte Premium Server CA, [email protected]" },
|
---|
1703 | { UINT64_C(0xf4fd306318ccda00), "C=US, O=GeoTrust Inc., CN=GeoTrust Global CA" },
|
---|
1704 | { UINT64_C(0xa0ee62086758b15d), "C=US, O=Equifax, OU=Equifax Secure Certificate Authority" },
|
---|
1705 | { UINT64_C(0x8ff6fc03c1edbd00), "C=US, ST=Arizona, L=Scottsdale, O=Starfield Technologies, Inc., CN=Starfield Root Certificate Authority - G2" },
|
---|
1706 | { UINT64_C(0xa3ce8d99e60eda00), "C=BE, O=GlobalSign nv-sa, OU=Root CA, CN=GlobalSign Root CA" },
|
---|
1707 | { UINT64_C(0xa671e9fec832b700), "C=US, O=Starfield Technologies, Inc., OU=Starfield Class 2 Certification Authority" },
|
---|
1708 | { UINT64_C(0xa8de7211e13be200), "C=US, O=DigiCert Inc, OU=www.digicert.com, CN=DigiCert Global Root CA" },
|
---|
1709 | { UINT64_C(0x0ff3891b54348328), "C=US, O=Entrust.net, OU=www.entrust.net/CPS incorp. by ref. (limits liab.), OU=(c) 1999 Entrust.net Limited, CN=Entrust.netSecure Server Certification Authority" },
|
---|
1710 | { UINT64_C(0x7ae89c50f0b6a00f), "C=US, O=GTE Corporation, OU=GTE CyberTrust Solutions, Inc., CN=GTE CyberTrust Global Root" },
|
---|
1711 | { UINT64_C(0xd45980fbf0a0ac00), "C=US, O=thawte, Inc., OU=Certification Services Division, OU=(c) 2006 thawte, Inc. - For authorized use only, CN=thawte Primary Root CA" },
|
---|
1712 | { UINT64_C(0x9e5bc2d78b6a3636), "C=ZA, ST=Western Cape, L=Cape Town, O=Thawte Consulting cc, OU=Certification Services Division, CN=Thawte Premium Server CA, [email protected]" },
|
---|
1713 | { UINT64_C(0x7c4fd32ec1b1ce00), "C=PL, O=Unizeto Sp. z o.o., CN=Certum CA" },
|
---|
1714 | { UINT64_C(0xd4fbe673e5ccc600), "C=US, O=DigiCert Inc, OU=www.digicert.com, CN=DigiCert High Assurance EV Root CA" },
|
---|
1715 | { UINT64_C(0x16e64d2a56ccf200), "C=US, ST=Arizona, L=Scottsdale, O=Starfield Technologies, Inc., OU=http://certificates.starfieldtech.com/repository/, CN=Starfield Services Root Certificate Authority" },
|
---|
1716 | { UINT64_C(0x6e2ba21058eedf00), "C=US, ST=UT, L=Salt Lake City, O=The USERTRUST Network, OU=http://www.usertrust.com, CN=UTN - DATACorp SGC" },
|
---|
1717 | { UINT64_C(0xb28612a94b4dad00), "O=Entrust.net, OU=www.entrust.net/CPS_2048 incorp. by ref. (limits liab.), OU=(c) 1999 Entrust.net Limited, CN=Entrust.netCertification Authority (2048)" },
|
---|
1718 | { UINT64_C(0x357a29080824af00), "C=US, O=VeriSign, Inc., OU=VeriSign Trust Network, OU=(c) 2006 VeriSign, Inc. - For authorized use only, CN=VeriSign Class3 Public Primary Certification Authority - G5" },
|
---|
1719 | { UINT64_C(0x466cbc09db88c100), "C=IL, O=StartCom Ltd., OU=Secure Digital Certificate Signing, CN=StartCom Certification Authority" },
|
---|
1720 | { UINT64_C(0x9259c8abe5ca713a), "L=ValiCert Validation Network, O=ValiCert, Inc., OU=ValiCert Class 2 Policy Validation Authority, CN=http://www.valicert.com/, [email protected]" },
|
---|
1721 | { UINT64_C(0x1f78fc529cbacb00), "C=US, O=VeriSign, Inc., OU=VeriSign Trust Network, OU=(c) 1999 VeriSign, Inc. - For authorized use only, CN=VeriSign Class3 Public Primary Certification Authority - G3" },
|
---|
1722 | { UINT64_C(0x8043e4ce150ead00), "C=US, O=DigiCert Inc, OU=www.digicert.com, CN=DigiCert Assured ID Root CA" },
|
---|
1723 | { UINT64_C(0x00f2e6331af7b700), "C=SE, O=AddTrust AB, OU=AddTrust External TTP Network, CN=AddTrust External CA Root" },
|
---|
1724 | };
|
---|
1725 |
|
---|
1726 |
|
---|
1727 | uint64_t const u64KeyId = pCert->TbsCertificate.SubjectPublicKeyInfo.SubjectPublicKey.uBits.pu64[1];
|
---|
1728 | uint32_t i = RT_ELEMENTS(s_aWanted);
|
---|
1729 | while (i-- > 0)
|
---|
1730 | if ( s_aWanted[i].u64KeyId == u64KeyId
|
---|
1731 | || s_aWanted[i].u64KeyId == UINT64_MAX)
|
---|
1732 | if (RTCrX509Name_MatchWithString(&pCert->TbsCertificate.Subject, s_aWanted[i].pszName))
|
---|
1733 | return true;
|
---|
1734 |
|
---|
1735 | #ifdef DEBUG_bird
|
---|
1736 | char szTmp[512];
|
---|
1737 | szTmp[sizeof(szTmp) - 1] = '\0';
|
---|
1738 | RTCrX509Name_FormatAsString(&pCert->TbsCertificate.Issuer, szTmp, sizeof(szTmp) - 1, NULL);
|
---|
1739 | SUP_DPRINTF(("supR3HardenedWinIsDesiredRootCA: %#llx %s\n", u64KeyId, szTmp));
|
---|
1740 | #endif
|
---|
1741 | return false;
|
---|
1742 | }
|
---|
1743 |
|
---|
1744 |
|
---|
1745 | /**
|
---|
1746 | * Loads a module in the system32 directory.
|
---|
1747 | *
|
---|
1748 | * @returns Module handle on success. Won't return on faliure.
|
---|
1749 | * @param pszName The name of the DLL to load.
|
---|
1750 | */
|
---|
1751 | DECLHIDDEN(HMODULE) supR3HardenedWinLoadSystem32Dll(const char *pszName)
|
---|
1752 | {
|
---|
1753 | WCHAR wszName[200+60];
|
---|
1754 | UINT cwcDir = GetSystemDirectoryW(wszName, RT_ELEMENTS(wszName) - 60);
|
---|
1755 | wszName[cwcDir] = '\\';
|
---|
1756 | RTUtf16CopyAscii(&wszName[cwcDir + 1], RT_ELEMENTS(wszName) - cwcDir, pszName);
|
---|
1757 |
|
---|
1758 | DWORD fFlags = 0;
|
---|
1759 | if (g_uNtVerCombined >= SUP_MAKE_NT_VER_SIMPLE(6, 0))
|
---|
1760 | fFlags = LOAD_LIBRARY_SEARCH_SYSTEM32;
|
---|
1761 | HMODULE hMod = LoadLibraryExW(wszName, NULL, fFlags);
|
---|
1762 | if ( hMod == NULL
|
---|
1763 | && fFlags
|
---|
1764 | && g_uNtVerCombined < SUP_MAKE_NT_VER_SIMPLE(6, 2)
|
---|
1765 | && GetLastError() == ERROR_INVALID_PARAMETER)
|
---|
1766 | {
|
---|
1767 | fFlags = 0;
|
---|
1768 | hMod = LoadLibraryExW(wszName, NULL, fFlags);
|
---|
1769 | }
|
---|
1770 | if (hMod == NULL)
|
---|
1771 | supR3HardenedFatal("Error loading '%s': %u [%ls]", pszName, GetLastError(), wszName);
|
---|
1772 | return hMod;
|
---|
1773 | }
|
---|
1774 |
|
---|
1775 |
|
---|
1776 | /**
|
---|
1777 | * Called by supR3HardenedWinResolveVerifyTrustApiAndHookThreadCreation to
|
---|
1778 | * import selected root CAs from the system certificate store.
|
---|
1779 | *
|
---|
1780 | * These certificates permits us to correctly validate third party DLLs.
|
---|
1781 | */
|
---|
1782 | static void supR3HardenedWinRetrieveTrustedRootCAs(void)
|
---|
1783 | {
|
---|
1784 | uint32_t cAdded = 0;
|
---|
1785 |
|
---|
1786 | /*
|
---|
1787 | * Load crypt32.dll and resolve the APIs we need.
|
---|
1788 | */
|
---|
1789 | HMODULE hCrypt32 = supR3HardenedWinLoadSystem32Dll("crypt32.dll");
|
---|
1790 |
|
---|
1791 | #define RESOLVE_CRYPT32_API(a_Name, a_pfnType) \
|
---|
1792 | a_pfnType pfn##a_Name = (a_pfnType)GetProcAddress(hCrypt32, #a_Name); \
|
---|
1793 | if (pfn##a_Name == NULL) supR3HardenedFatal("Error locating '" #a_Name "' in 'crypt32.dll': %u", GetLastError())
|
---|
1794 | RESOLVE_CRYPT32_API(CertOpenStore, PFNCERTOPENSTORE);
|
---|
1795 | RESOLVE_CRYPT32_API(CertCloseStore, PFNCERTCLOSESTORE);
|
---|
1796 | RESOLVE_CRYPT32_API(CertEnumCertificatesInStore, PFNCERTENUMCERTIFICATESINSTORE);
|
---|
1797 | #undef RESOLVE_CRYPT32_API
|
---|
1798 |
|
---|
1799 | /*
|
---|
1800 | * Open the root store and look for the certificates we wish to use.
|
---|
1801 | */
|
---|
1802 | DWORD fOpenStore = CERT_STORE_OPEN_EXISTING_FLAG | CERT_STORE_READONLY_FLAG;
|
---|
1803 | HCERTSTORE hStore = pfnCertOpenStore(CERT_STORE_PROV_SYSTEM_W, PKCS_7_ASN_ENCODING | X509_ASN_ENCODING,
|
---|
1804 | NULL /* hCryptProv = default */, CERT_SYSTEM_STORE_LOCAL_MACHINE | fOpenStore, L"Root");
|
---|
1805 | if (!hStore)
|
---|
1806 | hStore = pfnCertOpenStore(CERT_STORE_PROV_SYSTEM_W, PKCS_7_ASN_ENCODING | X509_ASN_ENCODING,
|
---|
1807 | NULL /* hCryptProv = default */, CERT_SYSTEM_STORE_CURRENT_USER | fOpenStore, L"Root");
|
---|
1808 | if (hStore)
|
---|
1809 | {
|
---|
1810 | PCCERT_CONTEXT pCurCtx = NULL;
|
---|
1811 | while ((pCurCtx = pfnCertEnumCertificatesInStore(hStore, pCurCtx)) != NULL)
|
---|
1812 | {
|
---|
1813 | if (pCurCtx->dwCertEncodingType & X509_ASN_ENCODING)
|
---|
1814 | {
|
---|
1815 | RTERRINFOSTATIC StaticErrInfo;
|
---|
1816 | RTASN1CURSORPRIMARY PrimaryCursor;
|
---|
1817 | RTAsn1CursorInitPrimary(&PrimaryCursor, pCurCtx->pbCertEncoded, pCurCtx->cbCertEncoded,
|
---|
1818 | RTErrInfoInitStatic(&StaticErrInfo),
|
---|
1819 | &g_RTAsn1DefaultAllocator, RTASN1CURSOR_FLAGS_DER, "CurCtx");
|
---|
1820 | RTCRX509CERTIFICATE MyCert;
|
---|
1821 | int rc = RTCrX509Certificate_DecodeAsn1(&PrimaryCursor.Cursor, 0, &MyCert, "Cert");
|
---|
1822 | if (RT_SUCCESS(rc))
|
---|
1823 | {
|
---|
1824 | if (supR3HardenedWinIsDesiredRootCA(&MyCert))
|
---|
1825 | {
|
---|
1826 | rc = RTCrStoreCertAddEncoded(g_hSpcRootStore, RTCRCERTCTX_F_ENC_X509_DER,
|
---|
1827 | pCurCtx->pbCertEncoded, pCurCtx->cbCertEncoded, NULL /*pErrInfo*/);
|
---|
1828 | AssertRC(rc);
|
---|
1829 |
|
---|
1830 | rc = RTCrStoreCertAddEncoded(g_hSpcAndNtKernelRootStore, RTCRCERTCTX_F_ENC_X509_DER,
|
---|
1831 | pCurCtx->pbCertEncoded, pCurCtx->cbCertEncoded, NULL /*pErrInfo*/);
|
---|
1832 | AssertRC(rc);
|
---|
1833 | cAdded++;
|
---|
1834 | }
|
---|
1835 |
|
---|
1836 | RTCrX509Certificate_Delete(&MyCert);
|
---|
1837 | }
|
---|
1838 | /* XP root certificate "C&W HKT SecureNet CA SGC Root" has non-standard validity
|
---|
1839 | timestamps, the UTC formatting isn't Zulu time but specifies timezone offsets.
|
---|
1840 | Ignore these failures and certificates. */
|
---|
1841 | else if (rc != VERR_ASN1_INVALID_UTC_TIME_ENCODING)
|
---|
1842 | AssertMsgFailed(("RTCrX509Certificate_DecodeAsn1 failed: rc=%#x: %s\n", rc, StaticErrInfo.szMsg));
|
---|
1843 | }
|
---|
1844 | }
|
---|
1845 | pfnCertCloseStore(hStore, CERT_CLOSE_STORE_CHECK_FLAG);
|
---|
1846 | g_fHaveOtherRoots = true;
|
---|
1847 | }
|
---|
1848 | SUP_DPRINTF(("supR3HardenedWinRetrieveTrustedRootCAs: cAdded=%u\n", cAdded));
|
---|
1849 | }
|
---|
1850 |
|
---|
1851 |
|
---|
1852 | /**
|
---|
1853 | * Resolves the WinVerifyTrust API after the process has been verified and
|
---|
1854 | * installs a thread creation hook.
|
---|
1855 | *
|
---|
1856 | * The WinVerifyTrust API is used in addition our own Authenticode verification
|
---|
1857 | * code. If the image has the IMAGE_DLLCHARACTERISTICS_FORCE_INTEGRITY flag
|
---|
1858 | * set, it will be checked again by the kernel. All our image has this flag set
|
---|
1859 | * and we require all VBox extensions to have it set as well. In effect, the
|
---|
1860 | * authenticode signature will be checked two or three times.
|
---|
1861 | *
|
---|
1862 | * @param pszProgName The program name.
|
---|
1863 | */
|
---|
1864 | DECLHIDDEN(void) supR3HardenedWinResolveVerifyTrustApiAndHookThreadCreation(const char *pszProgName)
|
---|
1865 | {
|
---|
1866 | # ifdef IN_SUP_HARDENED_R3
|
---|
1867 | /*
|
---|
1868 | * Load our the support library DLL that does the thread hooking as the
|
---|
1869 | * security API may trigger the creation of COM worker threads (or
|
---|
1870 | * whatever they are).
|
---|
1871 | *
|
---|
1872 | * The thread creation hook makes the threads very slippery to debuggers by
|
---|
1873 | * irreversably disabling most (if not all) debug events for them.
|
---|
1874 | */
|
---|
1875 | char szPath[RTPATH_MAX];
|
---|
1876 | supR3HardenedPathSharedLibs(szPath, sizeof(szPath) - sizeof("/VBoxSupLib.DLL"));
|
---|
1877 | suplibHardenedStrCat(szPath, "/VBoxSupLib.DLL");
|
---|
1878 | HMODULE hSupLibMod = (HMODULE)supR3HardenedWinLoadLibrary(szPath, true /*fSystem32Only*/);
|
---|
1879 | if (hSupLibMod == NULL)
|
---|
1880 | supR3HardenedFatal("Error loading '%s': %u", szPath, GetLastError());
|
---|
1881 | # endif
|
---|
1882 |
|
---|
1883 | /*
|
---|
1884 | * Allocate TLS entry for WinVerifyTrust recursion prevention.
|
---|
1885 | */
|
---|
1886 | DWORD iTls = TlsAlloc();
|
---|
1887 | if (iTls != TLS_OUT_OF_INDEXES)
|
---|
1888 | g_iTlsWinVerifyTrustRecursion = iTls;
|
---|
1889 | else
|
---|
1890 | supR3HardenedError(GetLastError(), false /*fFatal*/, "TlsAlloc failed");
|
---|
1891 |
|
---|
1892 | /*
|
---|
1893 | * Resolve it.
|
---|
1894 | */
|
---|
1895 | HMODULE hWintrust = supR3HardenedWinLoadSystem32Dll("Wintrust.dll");
|
---|
1896 | #define RESOLVE_CRYPT_API(a_Name, a_pfnType, a_uMinWinVer) \
|
---|
1897 | do { \
|
---|
1898 | g_pfn##a_Name = (a_pfnType)GetProcAddress(hWintrust, #a_Name); \
|
---|
1899 | if (g_pfn##a_Name == NULL && (a_uMinWinVer) < g_uNtVerCombined) \
|
---|
1900 | supR3HardenedFatal("Error locating '" #a_Name "' in 'Wintrust.dll': %u", GetLastError()); \
|
---|
1901 | } while (0)
|
---|
1902 |
|
---|
1903 | PFNWINVERIFYTRUST pfnWinVerifyTrust = (PFNWINVERIFYTRUST)GetProcAddress(hWintrust, "WinVerifyTrust");
|
---|
1904 | if (!pfnWinVerifyTrust)
|
---|
1905 | supR3HardenedFatal("Error locating 'WinVerifyTrust' in 'Wintrust.dll': %u", GetLastError());
|
---|
1906 |
|
---|
1907 | RESOLVE_CRYPT_API(CryptCATAdminAcquireContext, PFNCRYPTCATADMINACQUIRECONTEXT, 0);
|
---|
1908 | RESOLVE_CRYPT_API(CryptCATAdminCalcHashFromFileHandle, PFNCRYPTCATADMINCALCHASHFROMFILEHANDLE, 0);
|
---|
1909 | RESOLVE_CRYPT_API(CryptCATAdminEnumCatalogFromHash, PFNCRYPTCATADMINENUMCATALOGFROMHASH, 0);
|
---|
1910 | RESOLVE_CRYPT_API(CryptCATAdminReleaseCatalogContext, PFNCRYPTCATADMINRELEASECATALOGCONTEXT, 0);
|
---|
1911 | RESOLVE_CRYPT_API(CryptCATAdminReleaseContext, PFNCRYPTCATDADMINRELEASECONTEXT, 0);
|
---|
1912 | RESOLVE_CRYPT_API(CryptCATCatalogInfoFromContext, PFNCRYPTCATCATALOGINFOFROMCONTEXT, 0);
|
---|
1913 |
|
---|
1914 | RESOLVE_CRYPT_API(CryptCATAdminAcquireContext2, PFNCRYPTCATADMINACQUIRECONTEXT2, SUP_NT_VER_W80);
|
---|
1915 | RESOLVE_CRYPT_API(CryptCATAdminCalcHashFromFileHandle2, PFNCRYPTCATADMINCALCHASHFROMFILEHANDLE2, SUP_NT_VER_W80);
|
---|
1916 |
|
---|
1917 | /*
|
---|
1918 | * Call it on ourselves and ntdll to make sure it loads all the providers
|
---|
1919 | * now, we would otherwise geting into recursive trouble in the
|
---|
1920 | * NtCreateSection hook.
|
---|
1921 | */
|
---|
1922 | # ifdef IN_SUP_HARDENED_R3
|
---|
1923 | RTERRINFOSTATIC ErrInfoStatic;
|
---|
1924 | RTErrInfoInitStatic(&ErrInfoStatic);
|
---|
1925 | int rc = supR3HardNtViCallWinVerifyTrust(NULL, g_SupLibHardenedExeNtPath.UniStr.Buffer, 0,
|
---|
1926 | &ErrInfoStatic.Core, pfnWinVerifyTrust);
|
---|
1927 | if (RT_FAILURE(rc))
|
---|
1928 | supR3HardenedFatalMsg(pszProgName, kSupInitOp_Integrity, rc,
|
---|
1929 | "WinVerifyTrust failed on stub executable: %s", ErrInfoStatic.szMsg);
|
---|
1930 | # endif
|
---|
1931 |
|
---|
1932 | if (g_uNtVerCombined >= SUP_MAKE_NT_VER_SIMPLE(6, 0)) /* ntdll isn't signed on XP, assuming this is the case on W2K3 for now. */
|
---|
1933 | supR3HardNtViCallWinVerifyTrust(NULL, L"\\SystemRoot\\System32\\ntdll.dll", 0, NULL, pfnWinVerifyTrust);
|
---|
1934 | supR3HardNtViCallWinVerifyTrustCatFile(NULL, L"\\SystemRoot\\System32\\ntdll.dll", 0, NULL, pfnWinVerifyTrust);
|
---|
1935 |
|
---|
1936 | g_pfnWinVerifyTrust = pfnWinVerifyTrust;
|
---|
1937 | SUP_DPRINTF(("g_pfnWinVerifyTrust=%p\n", pfnWinVerifyTrust));
|
---|
1938 |
|
---|
1939 | # ifdef IN_SUP_HARDENED_R3
|
---|
1940 | /*
|
---|
1941 | * Load some problematic DLLs into the verifier cache to prevent
|
---|
1942 | * recursion trouble.
|
---|
1943 | */
|
---|
1944 | supR3HardenedWinVerifyCachePreload(L"\\SystemRoot\\System32\\crypt32.dll");
|
---|
1945 | supR3HardenedWinVerifyCachePreload(L"\\SystemRoot\\System32\\Wintrust.dll");
|
---|
1946 | # endif
|
---|
1947 |
|
---|
1948 | /*
|
---|
1949 | * Now, get trusted root CAs so we can verify a broader scope of signatures.
|
---|
1950 | */
|
---|
1951 | supR3HardenedWinRetrieveTrustedRootCAs();
|
---|
1952 | }
|
---|
1953 |
|
---|
1954 |
|
---|
1955 | static int supR3HardNtViNtToWinPath(PCRTUTF16 pwszNtName, PCRTUTF16 *ppwszWinPath,
|
---|
1956 | PRTUTF16 pwszWinPathBuf, size_t cwcWinPathBuf)
|
---|
1957 | {
|
---|
1958 | static const RTUTF16 s_wszPrefix[] = L"\\\\.\\GLOBALROOT";
|
---|
1959 |
|
---|
1960 | if (*pwszNtName != '\\' && *pwszNtName != '/')
|
---|
1961 | return VERR_PATH_DOES_NOT_START_WITH_ROOT;
|
---|
1962 |
|
---|
1963 | size_t cwcNtName = RTUtf16Len(pwszNtName);
|
---|
1964 | if (RT_ELEMENTS(s_wszPrefix) + cwcNtName > cwcWinPathBuf)
|
---|
1965 | return VERR_FILENAME_TOO_LONG;
|
---|
1966 |
|
---|
1967 | memcpy(pwszWinPathBuf, s_wszPrefix, sizeof(s_wszPrefix));
|
---|
1968 | memcpy(&pwszWinPathBuf[sizeof(s_wszPrefix) / sizeof(RTUTF16) - 1], pwszNtName, (cwcNtName + 1) * sizeof(RTUTF16));
|
---|
1969 | *ppwszWinPath = pwszWinPathBuf;
|
---|
1970 | return VINF_SUCCESS;
|
---|
1971 | }
|
---|
1972 |
|
---|
1973 |
|
---|
1974 | /**
|
---|
1975 | * Calls WinVerifyTrust to verify an PE image.
|
---|
1976 | *
|
---|
1977 | * @returns VBox status code.
|
---|
1978 | * @param hFile File handle to the executable file.
|
---|
1979 | * @param pwszName Full NT path to the DLL in question, used for
|
---|
1980 | * dealing with unsigned system dlls as well as for
|
---|
1981 | * error/logging.
|
---|
1982 | * @param fFlags Flags, SUPHNTVI_F_XXX.
|
---|
1983 | * @param pErrInfo Pointer to error info structure. Optional.
|
---|
1984 | * @param pfnWinVerifyTrust Pointer to the API.
|
---|
1985 | */
|
---|
1986 | static int supR3HardNtViCallWinVerifyTrust(HANDLE hFile, PCRTUTF16 pwszName, uint32_t fFlags, PRTERRINFO pErrInfo,
|
---|
1987 | PFNWINVERIFYTRUST pfnWinVerifyTrust)
|
---|
1988 | {
|
---|
1989 | /*
|
---|
1990 | * Convert the name into a Windows name.
|
---|
1991 | */
|
---|
1992 | RTUTF16 wszWinPathBuf[MAX_PATH];
|
---|
1993 | PCRTUTF16 pwszWinPath;
|
---|
1994 | int rc = supR3HardNtViNtToWinPath(pwszName, &pwszWinPath, wszWinPathBuf, RT_ELEMENTS(wszWinPathBuf));
|
---|
1995 | if (RT_FAILURE(rc))
|
---|
1996 | return RTErrInfoSetF(pErrInfo, rc, "Bad path passed to supR3HardNtViCallWinVerifyTrust: rc=%Rrc '%ls'", rc, pwszName);
|
---|
1997 |
|
---|
1998 | /*
|
---|
1999 | * Construct input parameters and call the API.
|
---|
2000 | */
|
---|
2001 | WINTRUST_FILE_INFO FileInfo;
|
---|
2002 | RT_ZERO(FileInfo);
|
---|
2003 | FileInfo.cbStruct = sizeof(FileInfo);
|
---|
2004 | FileInfo.pcwszFilePath = pwszWinPath;
|
---|
2005 | FileInfo.hFile = hFile;
|
---|
2006 |
|
---|
2007 | GUID PolicyActionGuid = WINTRUST_ACTION_GENERIC_VERIFY_V2;
|
---|
2008 |
|
---|
2009 | WINTRUST_DATA TrustData;
|
---|
2010 | RT_ZERO(TrustData);
|
---|
2011 | TrustData.cbStruct = sizeof(TrustData);
|
---|
2012 | TrustData.fdwRevocationChecks = WTD_REVOKE_NONE; /* Keep simple for now. */
|
---|
2013 | TrustData.dwStateAction = WTD_STATEACTION_VERIFY;
|
---|
2014 | TrustData.dwUIChoice = WTD_UI_NONE;
|
---|
2015 | TrustData.dwProvFlags = 0;
|
---|
2016 | if (g_uNtVerCombined >= SUP_MAKE_NT_VER_SIMPLE(6, 0))
|
---|
2017 | TrustData.dwProvFlags = WTD_CACHE_ONLY_URL_RETRIEVAL;
|
---|
2018 | else
|
---|
2019 | TrustData.dwProvFlags = WTD_REVOCATION_CHECK_NONE;
|
---|
2020 | TrustData.dwUnionChoice = WTD_CHOICE_FILE;
|
---|
2021 | TrustData.pFile = &FileInfo;
|
---|
2022 |
|
---|
2023 | HRESULT hrc = pfnWinVerifyTrust(NULL /*hwnd*/, &PolicyActionGuid, &TrustData);
|
---|
2024 | if (hrc == S_OK)
|
---|
2025 | rc = VINF_SUCCESS;
|
---|
2026 | else
|
---|
2027 | {
|
---|
2028 | /*
|
---|
2029 | * Failed. Format a nice error message.
|
---|
2030 | */
|
---|
2031 | # ifdef DEBUG_bird
|
---|
2032 | if (hrc != CERT_E_CHAINING /* Un-updated vistas, XPs, ++ */)
|
---|
2033 | __debugbreak();
|
---|
2034 | # endif
|
---|
2035 | const char *pszErrConst = NULL;
|
---|
2036 | switch (hrc)
|
---|
2037 | {
|
---|
2038 | case TRUST_E_SYSTEM_ERROR: pszErrConst = "TRUST_E_SYSTEM_ERROR"; break;
|
---|
2039 | case TRUST_E_NO_SIGNER_CERT: pszErrConst = "TRUST_E_NO_SIGNER_CERT"; break;
|
---|
2040 | case TRUST_E_COUNTER_SIGNER: pszErrConst = "TRUST_E_COUNTER_SIGNER"; break;
|
---|
2041 | case TRUST_E_CERT_SIGNATURE: pszErrConst = "TRUST_E_CERT_SIGNATURE"; break;
|
---|
2042 | case TRUST_E_TIME_STAMP: pszErrConst = "TRUST_E_TIME_STAMP"; break;
|
---|
2043 | case TRUST_E_BAD_DIGEST: pszErrConst = "TRUST_E_BAD_DIGEST"; break;
|
---|
2044 | case TRUST_E_BASIC_CONSTRAINTS: pszErrConst = "TRUST_E_BASIC_CONSTRAINTS"; break;
|
---|
2045 | case TRUST_E_FINANCIAL_CRITERIA: pszErrConst = "TRUST_E_FINANCIAL_CRITERIA"; break;
|
---|
2046 | case TRUST_E_PROVIDER_UNKNOWN: pszErrConst = "TRUST_E_PROVIDER_UNKNOWN"; break;
|
---|
2047 | case TRUST_E_ACTION_UNKNOWN: pszErrConst = "TRUST_E_ACTION_UNKNOWN"; break;
|
---|
2048 | case TRUST_E_SUBJECT_FORM_UNKNOWN: pszErrConst = "TRUST_E_SUBJECT_FORM_UNKNOWN"; break;
|
---|
2049 | case TRUST_E_SUBJECT_NOT_TRUSTED: pszErrConst = "TRUST_E_SUBJECT_NOT_TRUSTED"; break;
|
---|
2050 | case TRUST_E_NOSIGNATURE: pszErrConst = "TRUST_E_NOSIGNATURE"; break;
|
---|
2051 | case TRUST_E_FAIL: pszErrConst = "TRUST_E_FAIL"; break;
|
---|
2052 | case TRUST_E_EXPLICIT_DISTRUST: pszErrConst = "TRUST_E_EXPLICIT_DISTRUST"; break;
|
---|
2053 | case CERT_E_CHAINING: pszErrConst = "CERT_E_CHAINING"; break;
|
---|
2054 | case CERT_E_REVOCATION_FAILURE: pszErrConst = "CERT_E_REVOCATION_FAILURE"; break;
|
---|
2055 | }
|
---|
2056 | if (pszErrConst)
|
---|
2057 | rc = RTErrInfoSetF(pErrInfo, VERR_LDRVI_UNSUPPORTED_ARCH,
|
---|
2058 | "WinVerifyTrust failed with hrc=%s on '%ls'", pszErrConst, pwszName);
|
---|
2059 | else
|
---|
2060 | rc = RTErrInfoSetF(pErrInfo, VERR_LDRVI_UNSUPPORTED_ARCH,
|
---|
2061 | "WinVerifyTrust failed with hrc=%Rhrc on '%ls'", hrc, pwszName);
|
---|
2062 | SUP_DPRINTF(("supR3HardNtViCallWinVerifyTrust: WinVerifyTrust failed with %#x (%s) on '%ls'\n",
|
---|
2063 | hrc, pszErrConst, pwszName));
|
---|
2064 | }
|
---|
2065 |
|
---|
2066 | /* clean up state data. */
|
---|
2067 | TrustData.dwStateAction = WTD_STATEACTION_CLOSE;
|
---|
2068 | FileInfo.hFile = NULL;
|
---|
2069 | hrc = pfnWinVerifyTrust(NULL /*hwnd*/, &PolicyActionGuid, &TrustData);
|
---|
2070 |
|
---|
2071 | return rc;
|
---|
2072 | }
|
---|
2073 |
|
---|
2074 |
|
---|
2075 | /**
|
---|
2076 | * Calls WinVerifyTrust to verify an PE image via catalog files.
|
---|
2077 | *
|
---|
2078 | * @returns VBox status code.
|
---|
2079 | * @param hFile File handle to the executable file.
|
---|
2080 | * @param pwszName Full NT path to the DLL in question, used for
|
---|
2081 | * dealing with unsigned system dlls as well as for
|
---|
2082 | * error/logging.
|
---|
2083 | * @param fFlags Flags, SUPHNTVI_F_XXX.
|
---|
2084 | * @param pErrInfo Pointer to error info structure. Optional.
|
---|
2085 | * @param pfnWinVerifyTrust Pointer to the API.
|
---|
2086 | */
|
---|
2087 | static int supR3HardNtViCallWinVerifyTrustCatFile(HANDLE hFile, PCRTUTF16 pwszName, uint32_t fFlags, PRTERRINFO pErrInfo,
|
---|
2088 | PFNWINVERIFYTRUST pfnWinVerifyTrust)
|
---|
2089 | {
|
---|
2090 | SUP_DPRINTF(("supR3HardNtViCallWinVerifyTrustCatFile: hFile=%p pwszName=%ls\n", hFile, pwszName));
|
---|
2091 |
|
---|
2092 | /*
|
---|
2093 | * Convert the name into a Windows name.
|
---|
2094 | */
|
---|
2095 | RTUTF16 wszWinPathBuf[MAX_PATH];
|
---|
2096 | PCRTUTF16 pwszWinPath;
|
---|
2097 | int rc = supR3HardNtViNtToWinPath(pwszName, &pwszWinPath, wszWinPathBuf, RT_ELEMENTS(wszWinPathBuf));
|
---|
2098 | if (RT_FAILURE(rc))
|
---|
2099 | return RTErrInfoSetF(pErrInfo, rc, "Bad path passed to supR3HardNtViCallWinVerifyTrustCatFile: rc=%Rrc '%ls'", rc, pwszName);
|
---|
2100 |
|
---|
2101 | /*
|
---|
2102 | * Open the file if we didn't get a handle.
|
---|
2103 | */
|
---|
2104 | HANDLE hFileClose = NULL;
|
---|
2105 | if (hFile == RTNT_INVALID_HANDLE_VALUE || hFile == NULL)
|
---|
2106 | {
|
---|
2107 | hFile = RTNT_INVALID_HANDLE_VALUE;
|
---|
2108 | IO_STATUS_BLOCK Ios = RTNT_IO_STATUS_BLOCK_INITIALIZER;
|
---|
2109 |
|
---|
2110 | UNICODE_STRING NtName;
|
---|
2111 | NtName.Buffer = (PWSTR)pwszName;
|
---|
2112 | NtName.Length = (USHORT)(RTUtf16Len(pwszName) * sizeof(WCHAR));
|
---|
2113 | NtName.MaximumLength = NtName.Length + sizeof(WCHAR);
|
---|
2114 |
|
---|
2115 | OBJECT_ATTRIBUTES ObjAttr;
|
---|
2116 | InitializeObjectAttributes(&ObjAttr, &NtName, OBJ_CASE_INSENSITIVE, NULL /*hRootDir*/, NULL /*pSecDesc*/);
|
---|
2117 |
|
---|
2118 | NTSTATUS rcNt = NtCreateFile(&hFile,
|
---|
2119 | FILE_READ_DATA | READ_CONTROL | SYNCHRONIZE,
|
---|
2120 | &ObjAttr,
|
---|
2121 | &Ios,
|
---|
2122 | NULL /* Allocation Size*/,
|
---|
2123 | FILE_ATTRIBUTE_NORMAL,
|
---|
2124 | FILE_SHARE_READ,
|
---|
2125 | FILE_OPEN,
|
---|
2126 | FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT,
|
---|
2127 | NULL /*EaBuffer*/,
|
---|
2128 | 0 /*EaLength*/);
|
---|
2129 | if (NT_SUCCESS(rcNt))
|
---|
2130 | rcNt = Ios.Status;
|
---|
2131 | if (!NT_SUCCESS(rcNt))
|
---|
2132 | return RTErrInfoSetF(pErrInfo, RTErrConvertFromNtStatus(rcNt),
|
---|
2133 | "NtCreateFile returned %#x opening '%ls'.", rcNt, pwszName);
|
---|
2134 | hFileClose = hFile;
|
---|
2135 | }
|
---|
2136 |
|
---|
2137 | /*
|
---|
2138 | * On Windows 8.0 and later there are more than one digest choice.
|
---|
2139 | */
|
---|
2140 | rc = VERR_LDRVI_NOT_SIGNED;
|
---|
2141 | static struct
|
---|
2142 | {
|
---|
2143 | /** The digest algorithm name. */
|
---|
2144 | const WCHAR *pszAlgorithm;
|
---|
2145 | /** Cached catalog admin handle. */
|
---|
2146 | HCATADMIN volatile hCachedCatAdmin;
|
---|
2147 | } s_aHashes[] =
|
---|
2148 | {
|
---|
2149 | { NULL, NULL },
|
---|
2150 | { L"SHA256", NULL },
|
---|
2151 | };
|
---|
2152 | for (uint32_t i = 0; i < RT_ELEMENTS(s_aHashes); i++)
|
---|
2153 | {
|
---|
2154 | /*
|
---|
2155 | * Another loop for dealing with different trust provider policies
|
---|
2156 | * required for successfully validating different catalog signatures.
|
---|
2157 | */
|
---|
2158 | bool fTryNextPolicy;
|
---|
2159 | uint32_t iPolicy = 0;
|
---|
2160 | static const GUID s_aPolicies[] =
|
---|
2161 | {
|
---|
2162 | DRIVER_ACTION_VERIFY, /* Works with microsoft bits. Most frequently used, thus first. */
|
---|
2163 | WINTRUST_ACTION_GENERIC_VERIFY_V2, /* Works with ATI and other SPC kernel-code signed stuff. */
|
---|
2164 | };
|
---|
2165 | do
|
---|
2166 | {
|
---|
2167 | /*
|
---|
2168 | * Create a context.
|
---|
2169 | */
|
---|
2170 | fTryNextPolicy = false;
|
---|
2171 | bool fFreshContext = false;
|
---|
2172 | BOOL fRc;
|
---|
2173 | HCATADMIN hCatAdmin = ASMAtomicXchgPtr(&s_aHashes[i].hCachedCatAdmin, NULL);
|
---|
2174 | if (hCatAdmin)
|
---|
2175 | {
|
---|
2176 | SUP_DPRINTF(("supR3HardNtViCallWinVerifyTrustCatFile: Cached context %p\n", hCatAdmin));
|
---|
2177 | fFreshContext = false;
|
---|
2178 | fRc = TRUE;
|
---|
2179 | }
|
---|
2180 | else
|
---|
2181 | {
|
---|
2182 | l_fresh_context:
|
---|
2183 | fFreshContext = true;
|
---|
2184 | if (g_pfnCryptCATAdminAcquireContext2)
|
---|
2185 | fRc = g_pfnCryptCATAdminAcquireContext2(&hCatAdmin, &s_aPolicies[iPolicy], s_aHashes[i].pszAlgorithm,
|
---|
2186 | NULL /*pStrongHashPolicy*/, 0 /*dwFlags*/);
|
---|
2187 | else
|
---|
2188 | fRc = g_pfnCryptCATAdminAcquireContext(&hCatAdmin, &s_aPolicies[iPolicy], 0 /*dwFlags*/);
|
---|
2189 | SUP_DPRINTF(("supR3HardNtViCallWinVerifyTrustCatFile: New context %p\n", hCatAdmin));
|
---|
2190 | }
|
---|
2191 | if (fRc)
|
---|
2192 | {
|
---|
2193 | SUP_DPRINTF(("supR3HardNtViCallWinVerifyTrustCatFile: hCatAdmin=%p\n", hCatAdmin));
|
---|
2194 |
|
---|
2195 | /*
|
---|
2196 | * Hash the file.
|
---|
2197 | */
|
---|
2198 | BYTE abHash[SUPHARDNTVI_MAX_CAT_HASH_SIZE];
|
---|
2199 | DWORD cbHash = sizeof(abHash);
|
---|
2200 | if (g_pfnCryptCATAdminCalcHashFromFileHandle2)
|
---|
2201 | fRc = g_pfnCryptCATAdminCalcHashFromFileHandle2(hCatAdmin, hFile, &cbHash, abHash, 0 /*dwFlags*/);
|
---|
2202 | else
|
---|
2203 | fRc = g_pfnCryptCATAdminCalcHashFromFileHandle(hFile, &cbHash, abHash, 0 /*dwFlags*/);
|
---|
2204 | if (fRc)
|
---|
2205 | {
|
---|
2206 | /* Produce a string version of it that we can pass to WinVerifyTrust. */
|
---|
2207 | RTUTF16 wszDigest[SUPHARDNTVI_MAX_CAT_HASH_SIZE * 2 + 1];
|
---|
2208 | int rc2 = RTUtf16PrintHexBytes(wszDigest, RT_ELEMENTS(wszDigest), abHash, cbHash, RTSTRPRINTHEXBYTES_F_UPPER);
|
---|
2209 | if (RT_SUCCESS(rc2))
|
---|
2210 | {
|
---|
2211 | SUP_DPRINTF(("supR3HardNtViCallWinVerifyTrustCatFile: cbHash=%u wszDigest=%ls\n", cbHash, wszDigest));
|
---|
2212 |
|
---|
2213 | /*
|
---|
2214 | * Enumerate catalog information that matches the hash.
|
---|
2215 | */
|
---|
2216 | uint32_t iCat = 0;
|
---|
2217 | HCATINFO hCatInfoPrev = NULL;
|
---|
2218 | do
|
---|
2219 | {
|
---|
2220 | /* Get the next match. */
|
---|
2221 | HCATINFO hCatInfo = g_pfnCryptCATAdminEnumCatalogFromHash(hCatAdmin, abHash, cbHash, 0, &hCatInfoPrev);
|
---|
2222 | if (!hCatInfo)
|
---|
2223 | {
|
---|
2224 | if (!fFreshContext)
|
---|
2225 | {
|
---|
2226 | SUP_DPRINTF(("supR3HardNtViCallWinVerifyTrustCatFile: Retrying with fresh context (CryptCATAdminEnumCatalogFromHash -> %u; iCat=%#x)\n", GetLastError(), iCat));
|
---|
2227 | if (hCatInfoPrev != NULL)
|
---|
2228 | g_pfnCryptCATAdminReleaseCatalogContext(hCatAdmin, hCatInfoPrev, 0 /*dwFlags*/);
|
---|
2229 | g_pfnCryptCATAdminReleaseContext(hCatAdmin, 0 /*dwFlags*/);
|
---|
2230 | goto l_fresh_context;
|
---|
2231 | }
|
---|
2232 | if (iCat == 0)
|
---|
2233 | SUP_DPRINTF(("supR3HardNtViCallWinVerifyTrustCatFile: CryptCATAdminEnumCatalogFromHash failed %u\n", GetLastError()));
|
---|
2234 | break;
|
---|
2235 | }
|
---|
2236 | Assert(hCatInfoPrev == NULL);
|
---|
2237 | hCatInfoPrev = hCatInfo;
|
---|
2238 |
|
---|
2239 | /*
|
---|
2240 | * Call WinVerifyTrust.
|
---|
2241 | */
|
---|
2242 | CATALOG_INFO CatInfo;
|
---|
2243 | CatInfo.cbStruct = sizeof(CatInfo);
|
---|
2244 | CatInfo.wszCatalogFile[0] = '\0';
|
---|
2245 | if (g_pfnCryptCATCatalogInfoFromContext(hCatInfo, &CatInfo, 0 /*dwFlags*/))
|
---|
2246 | {
|
---|
2247 | WINTRUST_CATALOG_INFO WtCatInfo;
|
---|
2248 | RT_ZERO(WtCatInfo);
|
---|
2249 | WtCatInfo.cbStruct = sizeof(WtCatInfo);
|
---|
2250 | WtCatInfo.dwCatalogVersion = 0;
|
---|
2251 | WtCatInfo.pcwszCatalogFilePath = CatInfo.wszCatalogFile;
|
---|
2252 | WtCatInfo.pcwszMemberTag = wszDigest;
|
---|
2253 | WtCatInfo.pcwszMemberFilePath = pwszWinPath;
|
---|
2254 | WtCatInfo.pbCalculatedFileHash = abHash;
|
---|
2255 | WtCatInfo.cbCalculatedFileHash = cbHash;
|
---|
2256 | WtCatInfo.pcCatalogContext = NULL;
|
---|
2257 |
|
---|
2258 | WINTRUST_DATA TrustData;
|
---|
2259 | RT_ZERO(TrustData);
|
---|
2260 | TrustData.cbStruct = sizeof(TrustData);
|
---|
2261 | TrustData.fdwRevocationChecks = WTD_REVOKE_NONE; /* Keep simple for now. */
|
---|
2262 | TrustData.dwStateAction = WTD_STATEACTION_VERIFY;
|
---|
2263 | TrustData.dwUIChoice = WTD_UI_NONE;
|
---|
2264 | TrustData.dwProvFlags = 0;
|
---|
2265 | if (g_uNtVerCombined >= SUP_MAKE_NT_VER_SIMPLE(6, 0))
|
---|
2266 | TrustData.dwProvFlags = WTD_CACHE_ONLY_URL_RETRIEVAL;
|
---|
2267 | else
|
---|
2268 | TrustData.dwProvFlags = WTD_REVOCATION_CHECK_NONE;
|
---|
2269 | TrustData.dwUnionChoice = WTD_CHOICE_CATALOG;
|
---|
2270 | TrustData.pCatalog = &WtCatInfo;
|
---|
2271 |
|
---|
2272 | HRESULT hrc = pfnWinVerifyTrust(NULL /*hwnd*/, &s_aPolicies[iPolicy], &TrustData);
|
---|
2273 | SUP_DPRINTF(("supR3HardNtViCallWinVerifyTrustCatFile: WinVerifyTrust => %#x; cat='%ls'; file='%ls'\n",
|
---|
2274 | hrc, CatInfo.wszCatalogFile, pwszName));
|
---|
2275 |
|
---|
2276 | if (SUCCEEDED(hrc))
|
---|
2277 | rc = VINF_SUCCESS;
|
---|
2278 | else if (hrc == TRUST_E_NOSIGNATURE)
|
---|
2279 | { /* ignore because it's useless. */ }
|
---|
2280 | else if (hrc == ERROR_INVALID_PARAMETER)
|
---|
2281 | { /* This is returned if the given file isn't found in the catalog, it seems. */ }
|
---|
2282 | else
|
---|
2283 | {
|
---|
2284 | rc = RTErrInfoSetF(pErrInfo, VERR_SUP_VP_WINTRUST_CAT_FAILURE,
|
---|
2285 | "WinVerifyTrust failed with hrc=%#x on '%ls' and .cat-file='%ls'.",
|
---|
2286 | hrc, pwszWinPath, CatInfo.wszCatalogFile);
|
---|
2287 | fTryNextPolicy |= (hrc == CERT_E_UNTRUSTEDROOT);
|
---|
2288 | }
|
---|
2289 |
|
---|
2290 | /* clean up state data. */
|
---|
2291 | TrustData.dwStateAction = WTD_STATEACTION_CLOSE;
|
---|
2292 | hrc = pfnWinVerifyTrust(NULL /*hwnd*/, &s_aPolicies[iPolicy], &TrustData);
|
---|
2293 | Assert(SUCCEEDED(hrc));
|
---|
2294 | }
|
---|
2295 | else
|
---|
2296 | {
|
---|
2297 | rc = RTErrInfoSetF(pErrInfo, RTErrConvertFromWin32(GetLastError()),
|
---|
2298 | "CryptCATCatalogInfoFromContext failed: %d [file=%s]",
|
---|
2299 | GetLastError(), pwszName);
|
---|
2300 | SUP_DPRINTF(("supR3HardNtViCallWinVerifyTrustCatFile: CryptCATCatalogInfoFromContext failed\n"));
|
---|
2301 | }
|
---|
2302 | iCat++;
|
---|
2303 | } while (rc == VERR_LDRVI_NOT_SIGNED && iCat < 128);
|
---|
2304 |
|
---|
2305 | if (hCatInfoPrev != NULL)
|
---|
2306 | if (!g_pfnCryptCATAdminReleaseCatalogContext(hCatAdmin, hCatInfoPrev, 0 /*dwFlags*/))
|
---|
2307 | AssertFailed();
|
---|
2308 | }
|
---|
2309 | else
|
---|
2310 | rc = RTErrInfoSetF(pErrInfo, rc2, "RTUtf16PrintHexBytes failed: %Rrc", rc);
|
---|
2311 | }
|
---|
2312 | else
|
---|
2313 | rc = RTErrInfoSetF(pErrInfo, RTErrConvertFromWin32(GetLastError()),
|
---|
2314 | "CryptCATAdminCalcHashFromFileHandle[2] failed: %d [file=%s]", GetLastError(), pwszName);
|
---|
2315 |
|
---|
2316 | if (!ASMAtomicCmpXchgPtr(&s_aHashes[i].hCachedCatAdmin, hCatAdmin, NULL))
|
---|
2317 | if (!g_pfnCryptCATAdminReleaseContext(hCatAdmin, 0 /*dwFlags*/))
|
---|
2318 | AssertFailed();
|
---|
2319 | }
|
---|
2320 | else
|
---|
2321 | rc = RTErrInfoSetF(pErrInfo, RTErrConvertFromWin32(GetLastError()),
|
---|
2322 | "CryptCATAdminAcquireContext[2] failed: %d [file=%s]", GetLastError(), pwszName);
|
---|
2323 | iPolicy++;
|
---|
2324 | } while ( fTryNextPolicy
|
---|
2325 | && iPolicy < RT_ELEMENTS(s_aPolicies));
|
---|
2326 |
|
---|
2327 | /*
|
---|
2328 | * Only repeat if we've got g_pfnCryptCATAdminAcquireContext2 and can specify the hash algorithm.
|
---|
2329 | */
|
---|
2330 | if (!g_pfnCryptCATAdminAcquireContext2)
|
---|
2331 | break;
|
---|
2332 | if (rc != VERR_LDRVI_NOT_SIGNED)
|
---|
2333 | break;
|
---|
2334 | }
|
---|
2335 |
|
---|
2336 | if (hFileClose != NULL)
|
---|
2337 | NtClose(hFileClose);
|
---|
2338 |
|
---|
2339 | return rc;
|
---|
2340 | }
|
---|
2341 |
|
---|
2342 |
|
---|
2343 | /**
|
---|
2344 | * Verifies the given image using WinVerifyTrust in some way.
|
---|
2345 | *
|
---|
2346 | * This is used by supHardenedWinVerifyImageByLdrMod as well as
|
---|
2347 | * supR3HardenedScreenImage.
|
---|
2348 | *
|
---|
2349 | * @returns IPRT status code.
|
---|
2350 | * @param hFile Handle of the file to verify.
|
---|
2351 | * @param pwszName Full NT path to the DLL in question, used for
|
---|
2352 | * dealing with unsigned system dlls as well as for
|
---|
2353 | * error/logging.
|
---|
2354 | * @param pfWinVerifyTrust Where to return whether WinVerifyTrust was
|
---|
2355 | * actually used.
|
---|
2356 | * @param pErrInfo Pointer to error info structure. Optional.
|
---|
2357 | */
|
---|
2358 | DECLHIDDEN(int) supHardenedWinVerifyImageTrust(HANDLE hFile, PCRTUTF16 pwszName, uint32_t fFlags, int rc,
|
---|
2359 | bool *pfWinVerifyTrust, PRTERRINFO pErrInfo)
|
---|
2360 | {
|
---|
2361 | if (pfWinVerifyTrust)
|
---|
2362 | *pfWinVerifyTrust = false;
|
---|
2363 |
|
---|
2364 | /*
|
---|
2365 | * Call the windows verify trust API if we've resolved it and aren't in
|
---|
2366 | * some obvious recursion.
|
---|
2367 | */
|
---|
2368 | if (g_pfnWinVerifyTrust != NULL)
|
---|
2369 | {
|
---|
2370 | /* Check for recursion. */
|
---|
2371 | bool fNoRecursion;
|
---|
2372 | if (g_iTlsWinVerifyTrustRecursion != UINT32_MAX)
|
---|
2373 | {
|
---|
2374 | fNoRecursion = TlsGetValue(g_iTlsWinVerifyTrustRecursion) == 0;
|
---|
2375 | if (fNoRecursion)
|
---|
2376 | TlsSetValue(g_iTlsWinVerifyTrustRecursion, (void *)1);
|
---|
2377 | }
|
---|
2378 | else
|
---|
2379 | {
|
---|
2380 | uint32_t const idCurrentThread = GetCurrentThreadId();
|
---|
2381 | fNoRecursion = ASMAtomicCmpXchgU32(&g_idActiveThread, idCurrentThread, UINT32_MAX);
|
---|
2382 | }
|
---|
2383 | if (fNoRecursion)
|
---|
2384 | {
|
---|
2385 | /* We can call WinVerifyTrust. */
|
---|
2386 | if (pfWinVerifyTrust)
|
---|
2387 | *pfWinVerifyTrust = true;
|
---|
2388 |
|
---|
2389 | if (rc != VERR_LDRVI_NOT_SIGNED)
|
---|
2390 | {
|
---|
2391 | if (rc == VINF_LDRVI_NOT_SIGNED)
|
---|
2392 | {
|
---|
2393 | if (fFlags & SUPHNTVI_F_ALLOW_CAT_FILE_VERIFICATION)
|
---|
2394 | {
|
---|
2395 | int rc2 = supR3HardNtViCallWinVerifyTrustCatFile(hFile, pwszName, fFlags, pErrInfo, g_pfnWinVerifyTrust);
|
---|
2396 | SUP_DPRINTF(("supR3HardNtViCallWinVerifyTrustCatFile -> %d (org %d)\n", rc2, rc));
|
---|
2397 | rc = rc2;
|
---|
2398 | }
|
---|
2399 | else
|
---|
2400 | {
|
---|
2401 | AssertFailed();
|
---|
2402 | rc = VERR_LDRVI_NOT_SIGNED;
|
---|
2403 | }
|
---|
2404 | }
|
---|
2405 | else if (RT_SUCCESS(rc))
|
---|
2406 | {
|
---|
2407 | /** @todo having trouble with a 32-bit windows box when letting these calls thru */
|
---|
2408 | rc = supR3HardNtViCallWinVerifyTrust(hFile, pwszName, fFlags, pErrInfo, g_pfnWinVerifyTrust);
|
---|
2409 | }
|
---|
2410 | else
|
---|
2411 | {
|
---|
2412 | int rc2 = supR3HardNtViCallWinVerifyTrust(hFile, pwszName, fFlags, pErrInfo, g_pfnWinVerifyTrust);
|
---|
2413 | AssertMsg(RT_FAILURE_NP(rc2),
|
---|
2414 | ("rc=%Rrc, rc2=%Rrc %s", rc, rc2, pErrInfo ? pErrInfo->pszMsg : "<no-err-info>"));
|
---|
2415 | }
|
---|
2416 | }
|
---|
2417 |
|
---|
2418 | /* Unwind recursion. */
|
---|
2419 | if (g_iTlsWinVerifyTrustRecursion != UINT32_MAX)
|
---|
2420 | TlsSetValue(g_iTlsWinVerifyTrustRecursion, (void *)0);
|
---|
2421 | else
|
---|
2422 | ASMAtomicWriteU32(&g_idActiveThread, UINT32_MAX);
|
---|
2423 | }
|
---|
2424 | else
|
---|
2425 | SUP_DPRINTF(("Detected WinVerifyTrust recursion: rc=%Rrc '%ls'.\n", rc, pwszName));
|
---|
2426 | }
|
---|
2427 | return rc;
|
---|
2428 | }
|
---|
2429 |
|
---|
2430 |
|
---|
2431 | /**
|
---|
2432 | * Checks if WinVerifyTrust is callable on the current thread.
|
---|
2433 | *
|
---|
2434 | * Used by the main code to figure whether it makes sense to try revalidate an
|
---|
2435 | * image that hasn't passed thru WinVerifyTrust yet.
|
---|
2436 | *
|
---|
2437 | * @returns true if callable on current thread, false if not.
|
---|
2438 | */
|
---|
2439 | DECLHIDDEN(bool) supHardenedWinIsWinVerifyTrustCallable(void)
|
---|
2440 | {
|
---|
2441 | return g_pfnWinVerifyTrust != NULL
|
---|
2442 | && ( g_iTlsWinVerifyTrustRecursion != UINT32_MAX
|
---|
2443 | ? (uintptr_t)TlsGetValue(g_iTlsWinVerifyTrustRecursion) == 0
|
---|
2444 | : g_idActiveThread != GetCurrentThreadId() );
|
---|
2445 | }
|
---|
2446 |
|
---|
2447 |
|
---|
2448 |
|
---|
2449 | /**
|
---|
2450 | * Initializes g_uNtVerCombined and g_NtVerInfo.
|
---|
2451 | * Called from suplibHardenedWindowsMain and suplibOsInit.
|
---|
2452 | */
|
---|
2453 | DECLHIDDEN(void) supR3HardenedWinInitVersion(void)
|
---|
2454 | {
|
---|
2455 | /*
|
---|
2456 | * Get the windows version. Use RtlGetVersion as GetVersionExW and
|
---|
2457 | * GetVersion might not be telling the whole truth (8.0 on 8.1 depending on
|
---|
2458 | * the application manifest).
|
---|
2459 | */
|
---|
2460 | OSVERSIONINFOEXW NtVerInfo;
|
---|
2461 |
|
---|
2462 | RT_ZERO(NtVerInfo);
|
---|
2463 | NtVerInfo.dwOSVersionInfoSize = sizeof(RTL_OSVERSIONINFOEXW);
|
---|
2464 | if (!NT_SUCCESS(RtlGetVersion((PRTL_OSVERSIONINFOW)&NtVerInfo)))
|
---|
2465 | {
|
---|
2466 | RT_ZERO(NtVerInfo);
|
---|
2467 | PPEB pPeb = NtCurrentPeb();
|
---|
2468 | NtVerInfo.dwMajorVersion = pPeb->OSMajorVersion;
|
---|
2469 | NtVerInfo.dwMinorVersion = pPeb->OSMinorVersion;
|
---|
2470 | NtVerInfo.dwBuildNumber = pPeb->OSPlatformId;
|
---|
2471 | }
|
---|
2472 |
|
---|
2473 | g_uNtVerCombined = SUP_MAKE_NT_VER_COMBINED(NtVerInfo.dwMajorVersion, NtVerInfo.dwMinorVersion, NtVerInfo.dwBuildNumber,
|
---|
2474 | NtVerInfo.wServicePackMajor, NtVerInfo.wServicePackMinor);
|
---|
2475 | }
|
---|
2476 |
|
---|
2477 | #endif /* IN_RING3 */
|
---|
2478 |
|
---|