VirtualBox

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

最後變更 在這個檔案從52523是 52500,由 vboxsync 提交於 11 年 前

supR3HardenedWinIsDesiredRootCA: Changed to blacklisting, added more logging.

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

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