VirtualBox

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

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

SUP: Need per thread recursion counters for WinVerifyTrust or we risk deadlocking. This is new after hooking LdrLoadDll.

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

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