VirtualBox

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

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

SUP: Fix deadlock problem when mounting ISO on vista. (Never all WinVerifyTrust while holding the loader semaphore.)

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