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