VirtualBox

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

Last change on this file since 87742 was 86610, checked in by vboxsync, 4 years ago

SUPHArdNt,IPRT: Recognize WHQL/attestation signatures from MS. Corrected RTCRX509TBSCERTIFICATE::T3::fExtKeyUsage type (32 -> 64 bit) as it has been to small for a while now. bugref:3103

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