VirtualBox

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

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

SUP: some cleanups.

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