VirtualBox

source: vbox/trunk/src/VBox/HostDrivers/Support/win/SUPHardenedVerifyImage-win.cpp@ 52213

Last change on this file since 52213 was 52213, checked in by vboxsync, 10 years ago

SUP,IPRT: Implemented forwarder support in RTLdr and cleaned up some the ordinal mess. Resolved imports when doing the process verification/purification runs other than SUPHARDNTVPKIND_CHILD_PURIFICATION. This is necessary since 32-bit windows combine .text with .rdata, and we don't want to overwrite the import table after it has been snapped. Include read-only sections in the verfication runs.

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

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette