VirtualBox

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

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

IPRT: Added support for microsoft timestamp counter signatures. This required making the PKCS #7 code accept some of the CMS (RFC-5652) stuff.

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