VirtualBox

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

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

SUP: relax trusted installer for winsxs too.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 111.1 KB
Line 
1/* $Id: SUPHardenedVerifyImage-win.cpp 52690 2014-09-10 19:54:42Z 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 and a little for WinSxS, like we used to, as
1069 * there are apparently some systems out there where the user, admin, or
1070 * someone has changed the ownership of core windows DLLs like user32.dll
1071 * and comctl32.dll. Since we need user32.dll and will be checking it's
1072 * digital signature, it's reasonably safe to let this thru. (The report
1073 * was of SECURITY_BUILTIN_DOMAIN_RID + DOMAIN_ALIAS_RID_ADMINS
1074 * owning user32.dll, see public ticket 13187, VBoxStartup.3.log.)
1075 *
1076 * We've also had problems with graphics driver components like ig75icd64.dll
1077 * and atig6pxx.dll not being owned by TrustedInstaller, with the result
1078 * that 3D got broken (mod by zero issue in test build 5). These were also
1079 * SECURITY_BUILTIN_DOMAIN_RID + DOMAIN_ALIAS_RID_ADMINS.
1080 *
1081 * In one report by 'thor' the WinSxS resident comctl32.dll was owned by
1082 * SECURITY_BUILTIN_DOMAIN_RID + DOMAIN_ALIAS_RID_ADMINS (with 4.3.16).
1083 */
1084 if ( (pNtViRdr->fFlags & SUPHNTVI_F_TRUSTED_INSTALLER_OWNER)
1085 && !supHardNtViCheckIsOwnedByTrustedInstallerOrSimilar(pNtViRdr->hFile, pwszName))
1086 {
1087 if (supHardViUtf16PathStartsWithEx(pwszName, (uint32_t)RTUtf16Len(pwszName),
1088 g_System32NtPath.UniStr.Buffer, g_System32NtPath.UniStr.Length / sizeof(WCHAR),
1089 true /*fCheckSlash*/))
1090 SUP_DPRINTF(("%ls: Relaxing the TrustedInstaller requirement for this DLL (it's in system32).\n", pwszName));
1091 else if (supHardViUtf16PathStartsWithEx(pwszName, (uint32_t)RTUtf16Len(pwszName),
1092 g_WinSxSNtPath.UniStr.Buffer, g_WinSxSNtPath.UniStr.Length / sizeof(WCHAR),
1093 true /*fCheckSlash*/))
1094 SUP_DPRINTF(("%ls: Relaxing the TrustedInstaller requirement for this DLL (it's in WinSxS).\n", pwszName));
1095 else
1096 return RTErrInfoSetF(pErrInfo, VERR_SUP_VP_NOT_OWNED_BY_TRUSTED_INSTALLER,
1097 "supHardenedWinVerifyImageByHandle: TrustedInstaller is not the owner of '%ls'.", pwszName);
1098 }
1099
1100 /*
1101 * Verify it.
1102 *
1103 * The PKCS #7 SignedData signature is checked in the callback. Any
1104 * signing certificate restrictions are also enforced there.
1105 *
1106 * For the time being, we use the executable timestamp as the
1107 * certificate validation date. We must query that first to avoid
1108 * potential issues re-entering the loader code from the callback.
1109 *
1110 * Update: Save the first timestamp we validate with build cert and
1111 * use this as a minimum timestamp for further build cert
1112 * validations. This works around issues with old DLLs that
1113 * we sign against with our certificate (crt, sdl, qt).
1114 */
1115 int rc = RTLdrQueryProp(hLdrMod, RTLDRPROP_TIMESTAMP_SECONDS, &pNtViRdr->uTimestamp, sizeof(pNtViRdr->uTimestamp));
1116 if (RT_SUCCESS(rc))
1117 {
1118#ifdef IN_RING3 /* Hack alert! (see above) */
1119 if ( (pNtViRdr->fFlags & SUPHNTVI_F_REQUIRE_KERNEL_CODE_SIGNING)
1120 && (pNtViRdr->fFlags & SUPHNTVI_F_REQUIRE_SIGNATURE_ENFORCEMENT)
1121 && pNtViRdr->uTimestamp < g_uBuildTimestampHack)
1122 pNtViRdr->uTimestamp = g_uBuildTimestampHack;
1123#endif
1124
1125 rc = RTLdrVerifySignature(hLdrMod, supHardNtViCallback, pNtViRdr, pErrInfo);
1126
1127#ifdef IN_RING3 /* Hack alert! (see above) */
1128 if ((pNtViRdr->fFlags & SUPHNTVI_F_REQUIRE_BUILD_CERT) && g_uBuildTimestampHack == 0 && RT_SUCCESS(rc))
1129 g_uBuildTimestampHack = pNtViRdr->uTimestamp;
1130#endif
1131
1132 /*
1133 * Microsoft doesn't sign a whole bunch of DLLs, so we have to
1134 * ASSUME that a bunch of system DLLs are fine.
1135 */
1136 if (rc == VERR_LDRVI_NOT_SIGNED)
1137 rc = supHardNtViCheckIfNotSignedOk(hLdrMod, pwszName, pNtViRdr->fFlags, pNtViRdr->hFile, rc);
1138 if (RT_FAILURE(rc))
1139 RTErrInfoAddF(pErrInfo, rc, ": %ls", pwszName);
1140
1141 /*
1142 * Check for the signature checking enforcement, if requested to do so.
1143 */
1144 if (RT_SUCCESS(rc) && (pNtViRdr->fFlags & SUPHNTVI_F_REQUIRE_SIGNATURE_ENFORCEMENT))
1145 {
1146 bool fEnforced = false;
1147 int rc2 = RTLdrQueryProp(hLdrMod, RTLDRPROP_SIGNATURE_CHECKS_ENFORCED, &fEnforced, sizeof(fEnforced));
1148 if (RT_FAILURE(rc2))
1149 rc = RTErrInfoSetF(pErrInfo, rc2, "Querying RTLDRPROP_SIGNATURE_CHECKS_ENFORCED failed on %ls: %Rrc.",
1150 pwszName, rc2);
1151 else if (!fEnforced)
1152 rc = RTErrInfoSetF(pErrInfo, VERR_SUP_VP_SIGNATURE_CHECKS_NOT_ENFORCED,
1153 "The image '%ls' was not linked with /IntegrityCheck.", pwszName);
1154 }
1155 }
1156 else
1157 RTErrInfoSetF(pErrInfo, rc, "RTLdrQueryProp/RTLDRPROP_TIMESTAMP_SECONDS failed on %ls: %Rrc", pwszName, rc);
1158
1159#ifdef IN_RING3
1160 /*
1161 * Pass it thru WinVerifyTrust when possible.
1162 */
1163 if (!fAvoidWinVerifyTrust)
1164 rc = supHardenedWinVerifyImageTrust(pNtViRdr->hFile, pwszName, pNtViRdr->fFlags, rc, pfWinVerifyTrust, pErrInfo);
1165#endif
1166
1167#ifdef IN_SUP_HARDENED_R3
1168 /*
1169 * Hook for the LdrLoadDll code to schedule scanning of imports.
1170 */
1171 if (RT_SUCCESS(rc))
1172 supR3HardenedWinVerifyCacheScheduleImports(hLdrMod, pwszName);
1173#endif
1174
1175 return rc;
1176}
1177
1178
1179/**
1180 * Verifies the given executable image.
1181 *
1182 * @returns IPRT status code.
1183 * @param hFile File handle to the executable file.
1184 * @param pwszName Full NT path to the DLL in question, used for
1185 * dealing with unsigned system dlls as well as for
1186 * error/logging.
1187 * @param fFlags Flags, SUPHNTVI_F_XXX.
1188 * @param fAvoidWinVerifyTrust Whether to avoid WinVerifyTrust because of
1189 * deadlock or other loader related dangers.
1190 * @param pfWinVerifyTrust Where to return whether WinVerifyTrust was used.
1191 * @param pErrInfo Pointer to error info structure. Optional.
1192 */
1193DECLHIDDEN(int) supHardenedWinVerifyImageByHandle(HANDLE hFile, PCRTUTF16 pwszName, uint32_t fFlags, bool fAvoidWinVerifyTrust,
1194 bool *pfWinVerifyTrust, PRTERRINFO pErrInfo)
1195{
1196 /*
1197 * Create a reader instance.
1198 */
1199 PSUPHNTVIRDR pNtViRdr;
1200 int rc = supHardNtViRdrCreate(hFile, pwszName, fFlags, &pNtViRdr);
1201 if (RT_SUCCESS(rc))
1202 {
1203 /*
1204 * Open the image.
1205 */
1206 RTLDRMOD hLdrMod;
1207 RTLDRARCH enmArch = fFlags & SUPHNTVI_F_RC_IMAGE ? RTLDRARCH_X86_32 : RTLDRARCH_HOST;
1208 if (fFlags & SUPHNTVI_F_RESOURCE_IMAGE)
1209 enmArch = RTLDRARCH_WHATEVER;
1210 rc = RTLdrOpenWithReader(&pNtViRdr->Core, RTLDR_O_FOR_VALIDATION, enmArch, &hLdrMod, pErrInfo);
1211 if (RT_SUCCESS(rc))
1212 {
1213 /*
1214 * Verify it.
1215 */
1216 rc = supHardenedWinVerifyImageByLdrMod(hLdrMod, pwszName, pNtViRdr, fAvoidWinVerifyTrust, pfWinVerifyTrust, pErrInfo);
1217 int rc2 = RTLdrClose(hLdrMod); AssertRC(rc2);
1218 }
1219 else
1220 supHardNtViRdrDestroy(&pNtViRdr->Core);
1221 }
1222 SUP_DPRINTF(("supHardenedWinVerifyImageByHandle: -> %d (%ls)%s\n",
1223 rc, pwszName, pfWinVerifyTrust && *pfWinVerifyTrust ? "WinVerifyTrust" : ""));
1224 return rc;
1225}
1226
1227
1228#ifdef IN_RING3
1229/**
1230 * supHardenedWinVerifyImageByHandle version without the name.
1231 *
1232 * The name is derived from the handle.
1233 *
1234 * @returns IPRT status code.
1235 * @param hFile File handle to the executable file.
1236 * @param fFlags Flags, SUPHNTVI_F_XXX.
1237 * @param pErrInfo Pointer to error info structure. Optional.
1238 */
1239DECLHIDDEN(int) supHardenedWinVerifyImageByHandleNoName(HANDLE hFile, uint32_t fFlags, PRTERRINFO pErrInfo)
1240{
1241 /*
1242 * Determine the NT name and call the verification function.
1243 */
1244 union
1245 {
1246 UNICODE_STRING UniStr;
1247 uint8_t abBuffer[(MAX_PATH + 8 + 1) * 2];
1248 } uBuf;
1249
1250 ULONG cbIgn;
1251 NTSTATUS rcNt = NtQueryObject(hFile,
1252 ObjectNameInformation,
1253 &uBuf,
1254 sizeof(uBuf) - sizeof(WCHAR),
1255 &cbIgn);
1256 if (NT_SUCCESS(rcNt))
1257 uBuf.UniStr.Buffer[uBuf.UniStr.Length / sizeof(WCHAR)] = '\0';
1258 else
1259 uBuf.UniStr.Buffer = (WCHAR *)L"TODO3";
1260
1261 return supHardenedWinVerifyImageByHandle(hFile, uBuf.UniStr.Buffer, fFlags, false /*fAvoidWinVerifyTrust*/,
1262 NULL /*pfWinVerifyTrust*/, pErrInfo);
1263}
1264#endif /* IN_RING3 */
1265
1266
1267/**
1268 * Retrieves the full official path to the system root or one of it's sub
1269 * directories.
1270 *
1271 * This code is also used by the support driver.
1272 *
1273 * @returns VBox status code.
1274 * @param pvBuf The output buffer. This will contain a
1275 * UNICODE_STRING followed (at the kernel's
1276 * discretion) the string buffer.
1277 * @param cbBuf The size of the buffer @a pvBuf points to.
1278 * @param enmDir Which directory under the system root we're
1279 * interested in.
1280 * @param pErrInfo Pointer to error info structure. Optional.
1281 */
1282DECLHIDDEN(int) supHardNtGetSystemRootDir(void *pvBuf, uint32_t cbBuf, SUPHARDNTSYSROOTDIR enmDir, PRTERRINFO pErrInfo)
1283{
1284 HANDLE hFile = RTNT_INVALID_HANDLE_VALUE;
1285 IO_STATUS_BLOCK Ios = RTNT_IO_STATUS_BLOCK_INITIALIZER;
1286
1287 UNICODE_STRING NtName;
1288 switch (enmDir)
1289 {
1290 case kSupHardNtSysRootDir_System32:
1291 {
1292 static const WCHAR s_wszNameSystem32[] = L"\\SystemRoot\\System32\\";
1293 NtName.Buffer = (PWSTR)s_wszNameSystem32;
1294 NtName.Length = sizeof(s_wszNameSystem32) - sizeof(WCHAR);
1295 NtName.MaximumLength = sizeof(s_wszNameSystem32);
1296 break;
1297 }
1298 case kSupHardNtSysRootDir_WinSxS:
1299 {
1300 static const WCHAR s_wszNameWinSxS[] = L"\\SystemRoot\\WinSxS\\";
1301 NtName.Buffer = (PWSTR)s_wszNameWinSxS;
1302 NtName.Length = sizeof(s_wszNameWinSxS) - sizeof(WCHAR);
1303 NtName.MaximumLength = sizeof(s_wszNameWinSxS);
1304 break;
1305 }
1306 default:
1307 AssertFailed();
1308 return VERR_INVALID_PARAMETER;
1309 }
1310
1311 OBJECT_ATTRIBUTES ObjAttr;
1312 InitializeObjectAttributes(&ObjAttr, &NtName, OBJ_CASE_INSENSITIVE, NULL /*hRootDir*/, NULL /*pSecDesc*/);
1313
1314 NTSTATUS rcNt = NtCreateFile(&hFile,
1315 FILE_READ_DATA | SYNCHRONIZE,
1316 &ObjAttr,
1317 &Ios,
1318 NULL /* Allocation Size*/,
1319 FILE_ATTRIBUTE_NORMAL,
1320 FILE_SHARE_READ | FILE_SHARE_WRITE,
1321 FILE_OPEN,
1322 FILE_DIRECTORY_FILE | FILE_OPEN_FOR_BACKUP_INTENT | FILE_SYNCHRONOUS_IO_NONALERT,
1323 NULL /*EaBuffer*/,
1324 0 /*EaLength*/);
1325 if (NT_SUCCESS(rcNt))
1326 rcNt = Ios.Status;
1327 if (NT_SUCCESS(rcNt))
1328 {
1329 ULONG cbIgn;
1330 rcNt = NtQueryObject(hFile,
1331 ObjectNameInformation,
1332 pvBuf,
1333 cbBuf - sizeof(WCHAR),
1334 &cbIgn);
1335 NtClose(hFile);
1336 if (NT_SUCCESS(rcNt))
1337 {
1338 PUNICODE_STRING pUniStr = (PUNICODE_STRING)pvBuf;
1339 if (pUniStr->Length > 0)
1340 {
1341 /* Make sure it's terminated so it can safely be printed.*/
1342 pUniStr->Buffer[pUniStr->Length / sizeof(WCHAR)] = '\0';
1343 return VINF_SUCCESS;
1344 }
1345
1346 return RTErrInfoSetF(pErrInfo, VERR_SUP_VP_SYSTEM32_PATH,
1347 "NtQueryObject returned an empty path for '%ls'", NtName.Buffer);
1348 }
1349 return RTErrInfoSetF(pErrInfo, VERR_SUP_VP_SYSTEM32_PATH, "NtQueryObject failed on '%ls' dir: %#x", NtName.Buffer, rcNt);
1350 }
1351 return RTErrInfoSetF(pErrInfo, VERR_SUP_VP_SYSTEM32_PATH, "Failure to open '%ls': %#x", NtName.Buffer, rcNt);
1352}
1353
1354
1355/**
1356 * Initialize one certificate entry.
1357 *
1358 * @returns VBox status code.
1359 * @param pCert The X.509 certificate representation to init.
1360 * @param pabCert The raw DER encoded certificate.
1361 * @param cbCert The size of the raw certificate.
1362 * @param pErrInfo Where to return extended error info. Optional.
1363 * @param pszErrorTag Error tag.
1364 */
1365static int supHardNtViCertInit(PRTCRX509CERTIFICATE pCert, unsigned char const *pabCert, unsigned cbCert,
1366 PRTERRINFO pErrInfo, const char *pszErrorTag)
1367{
1368 AssertReturn(cbCert > 16 && cbCert < _128K,
1369 RTErrInfoSetF(pErrInfo, VERR_INTERNAL_ERROR_3, "%s: cbCert=%#x out of range", pszErrorTag, cbCert));
1370 AssertReturn(!RTCrX509Certificate_IsPresent(pCert),
1371 RTErrInfoSetF(pErrInfo, VERR_WRONG_ORDER, "%s: Certificate already decoded?", pszErrorTag));
1372
1373 RTASN1CURSORPRIMARY PrimaryCursor;
1374 RTAsn1CursorInitPrimary(&PrimaryCursor, pabCert, cbCert, pErrInfo, &g_RTAsn1DefaultAllocator, RTASN1CURSOR_FLAGS_DER, NULL);
1375 int rc = RTCrX509Certificate_DecodeAsn1(&PrimaryCursor.Cursor, 0, pCert, pszErrorTag);
1376 if (RT_SUCCESS(rc))
1377 rc = RTCrX509Certificate_CheckSanity(pCert, 0, pErrInfo, pszErrorTag);
1378 return rc;
1379}
1380
1381
1382static int supHardNtViCertStoreAddArray(RTCRSTORE hStore, PCSUPTAENTRY paCerts, unsigned cCerts, PRTERRINFO pErrInfo)
1383{
1384 for (uint32_t i = 0; i < cCerts; i++)
1385 {
1386 int rc = RTCrStoreCertAddEncoded(hStore, RTCRCERTCTX_F_ENC_TAF_DER, paCerts[i].pch, paCerts[i].cb, pErrInfo);
1387 if (RT_FAILURE(rc))
1388 return rc;
1389 }
1390 return VINF_SUCCESS;
1391}
1392
1393
1394/**
1395 * Initialize a certificate table.
1396 *
1397 * @param phStore Where to return the store pointer.
1398 * @param paCerts1 Pointer to the first certificate table.
1399 * @param cCerts1 Entries in the first certificate table.
1400 * @param paCerts2 Pointer to the second certificate table.
1401 * @param cCerts2 Entries in the second certificate table.
1402 * @param paCerts3 Pointer to the third certificate table.
1403 * @param cCerts3 Entries in the third certificate table.
1404 * @param pErrInfo Where to return extended error info. Optional.
1405 * @param pszErrorTag Error tag.
1406 */
1407static int supHardNtViCertStoreInit(PRTCRSTORE phStore,
1408 PCSUPTAENTRY paCerts1, unsigned cCerts1,
1409 PCSUPTAENTRY paCerts2, unsigned cCerts2,
1410 PCSUPTAENTRY paCerts3, unsigned cCerts3,
1411 PRTERRINFO pErrInfo, const char *pszErrorTag)
1412{
1413 AssertReturn(*phStore == NIL_RTCRSTORE, VERR_WRONG_ORDER);
1414
1415 int rc = RTCrStoreCreateInMem(phStore, cCerts1 + cCerts2);
1416 if (RT_FAILURE(rc))
1417 return RTErrInfoSetF(pErrInfo, rc, "RTCrStoreCreateMemoryStore failed: %Rrc", rc);
1418
1419 rc = supHardNtViCertStoreAddArray(*phStore, paCerts1, cCerts1, pErrInfo);
1420 if (RT_SUCCESS(rc))
1421 rc = supHardNtViCertStoreAddArray(*phStore, paCerts2, cCerts2, pErrInfo);
1422 if (RT_SUCCESS(rc))
1423 rc = supHardNtViCertStoreAddArray(*phStore, paCerts3, cCerts3, pErrInfo);
1424 return rc;
1425}
1426
1427
1428
1429#ifdef IN_RING3
1430/**
1431 * Initializes the windows paths.
1432 */
1433static void supHardenedWinInitImageVerifierWinPaths(void)
1434{
1435 /*
1436 * Windows paths that we're interested in.
1437 */
1438 static const struct
1439 {
1440 SUPSYSROOTDIRBUF *pNtPath;
1441 WCHAR const *pwszRegValue;
1442 const char *pszLogName;
1443 } s_aPaths[] =
1444 {
1445 { &g_ProgramFilesNtPath, L"ProgramFilesDir", "ProgDir" },
1446 { &g_CommonFilesNtPath, L"CommonFilesDir", "ComDir" },
1447# ifdef RT_ARCH_AMD64
1448 { &g_ProgramFilesX86NtPath, L"ProgramFilesDir (x86)", "ProgDir32" },
1449 { &g_CommonFilesX86NtPath, L"CommonFilesDir (x86)", "ComDir32" },
1450# endif
1451 };
1452
1453 /*
1454 * Open the registry key containing the paths.
1455 */
1456 UNICODE_STRING NtName = RTNT_CONSTANT_UNISTR(L"\\Registry\\Machine\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion");
1457 OBJECT_ATTRIBUTES ObjAttr;
1458 InitializeObjectAttributes(&ObjAttr, &NtName, OBJ_CASE_INSENSITIVE, NULL /*hRootDir*/, NULL /*pSecDesc*/);
1459 HANDLE hKey;
1460 NTSTATUS rcNt = NtOpenKey(&hKey, KEY_QUERY_VALUE, &ObjAttr);
1461 if (NT_SUCCESS(rcNt))
1462 {
1463 /*
1464 * Loop over the paths and resolve their NT paths.
1465 */
1466 for (uint32_t i = 0; i < RT_ELEMENTS(s_aPaths); i++)
1467 {
1468 /*
1469 * Query the value first.
1470 */
1471 UNICODE_STRING ValueName;
1472 ValueName.Buffer = (WCHAR *)s_aPaths[i].pwszRegValue;
1473 ValueName.Length = (USHORT)(RTUtf16Len(s_aPaths[i].pwszRegValue) * sizeof(WCHAR));
1474 ValueName.MaximumLength = ValueName.Length + sizeof(WCHAR);
1475
1476 union
1477 {
1478 KEY_VALUE_PARTIAL_INFORMATION PartialInfo;
1479 uint8_t abPadding[sizeof(KEY_VALUE_PARTIAL_INFORMATION) + sizeof(WCHAR) * 128];
1480 uint64_t uAlign;
1481 } uBuf;
1482
1483 ULONG cbActual = 0;
1484 rcNt = NtQueryValueKey(hKey, &ValueName, KeyValuePartialInformation, &uBuf, sizeof(uBuf) - sizeof(WCHAR), &cbActual);
1485 if (NT_SUCCESS(rcNt))
1486 {
1487 /*
1488 * Must be a simple string value, terminate it.
1489 */
1490 if ( uBuf.PartialInfo.Type == REG_EXPAND_SZ
1491 || uBuf.PartialInfo.Type == REG_SZ)
1492 {
1493 /*
1494 * Expand any environment variable references before opening it.
1495 * We use the result buffer as storage for the expaneded path,
1496 * reserving space for the windows name space prefix.
1497 */
1498 UNICODE_STRING Src;
1499 Src.Buffer = (WCHAR *)uBuf.PartialInfo.Data;
1500 Src.Length = uBuf.PartialInfo.DataLength;
1501 if (Src.Length >= sizeof(WCHAR) && Src.Buffer[Src.Length / sizeof(WCHAR) - 1] == '\0')
1502 Src.Length -= sizeof(WCHAR);
1503 Src.MaximumLength = Src.Length + sizeof(WCHAR);
1504 Src.Buffer[uBuf.PartialInfo.DataLength / sizeof(WCHAR)] = '\0';
1505
1506 s_aPaths[i].pNtPath->awcBuffer[0] = '\\';
1507 s_aPaths[i].pNtPath->awcBuffer[1] = '?';
1508 s_aPaths[i].pNtPath->awcBuffer[2] = '?';
1509 s_aPaths[i].pNtPath->awcBuffer[3] = '\\';
1510 UNICODE_STRING Dst;
1511 Dst.Buffer = &s_aPaths[i].pNtPath->awcBuffer[4];
1512 Dst.MaximumLength = sizeof(s_aPaths[i].pNtPath->awcBuffer) - sizeof(WCHAR) * 5;
1513 Dst.Length = Dst.MaximumLength;
1514
1515 if (uBuf.PartialInfo.Type == REG_EXPAND_SZ)
1516 rcNt = RtlExpandEnvironmentStrings_U(NULL, &Src, &Dst, NULL);
1517 else
1518 {
1519 memcpy(Dst.Buffer, Src.Buffer, Src.Length);
1520 Dst.Length = Src.Length;
1521 }
1522 if (NT_SUCCESS(rcNt))
1523 {
1524 Dst.Buffer[Dst.Length / sizeof(WCHAR)] = '\0';
1525
1526 /*
1527 * Include the \\??\\ prefix in the result and open the path.
1528 */
1529 Dst.Buffer -= 4;
1530 Dst.Length += 4 * sizeof(WCHAR);
1531 Dst.MaximumLength += 4 * sizeof(WCHAR);
1532 InitializeObjectAttributes(&ObjAttr, &Dst, OBJ_CASE_INSENSITIVE, NULL /*hRootDir*/, NULL /*pSecDesc*/);
1533 HANDLE hFile = INVALID_HANDLE_VALUE;
1534 IO_STATUS_BLOCK Ios = RTNT_IO_STATUS_BLOCK_INITIALIZER;
1535 NTSTATUS rcNt = NtCreateFile(&hFile,
1536 FILE_READ_DATA | SYNCHRONIZE,
1537 &ObjAttr,
1538 &Ios,
1539 NULL /* Allocation Size*/,
1540 FILE_ATTRIBUTE_NORMAL,
1541 FILE_SHARE_READ | FILE_SHARE_WRITE,
1542 FILE_OPEN,
1543 FILE_DIRECTORY_FILE | FILE_OPEN_FOR_BACKUP_INTENT
1544 | FILE_SYNCHRONOUS_IO_NONALERT,
1545 NULL /*EaBuffer*/,
1546 0 /*EaLength*/);
1547 if (NT_SUCCESS(rcNt))
1548 rcNt = Ios.Status;
1549 if (NT_SUCCESS(rcNt))
1550 {
1551 /*
1552 * Query the real NT name.
1553 */
1554 ULONG cbIgn;
1555 rcNt = NtQueryObject(hFile,
1556 ObjectNameInformation,
1557 s_aPaths[i].pNtPath,
1558 sizeof(*s_aPaths[i].pNtPath) - sizeof(WCHAR),
1559 &cbIgn);
1560 if (NT_SUCCESS(rcNt))
1561 {
1562 if (s_aPaths[i].pNtPath->UniStr.Length > 0)
1563 {
1564 /* Make sure it's terminated.*/
1565 s_aPaths[i].pNtPath->UniStr.Buffer[s_aPaths[i].pNtPath->UniStr.Length / sizeof(WCHAR)] = '\0';
1566 SUP_DPRINTF(("%s:%*s %ls\n", s_aPaths[i].pszLogName, 9 - strlen(s_aPaths[i].pszLogName), "",
1567 s_aPaths[i].pNtPath->UniStr.Buffer));
1568 }
1569 else
1570 {
1571 SUP_DPRINTF(("%s: NtQueryObject returned empty string\n", s_aPaths[i].pszLogName));
1572 rcNt = STATUS_INVALID_PARAMETER;
1573 }
1574 }
1575 else
1576 SUP_DPRINTF(("%s: NtQueryObject failed: %#x\n", s_aPaths[i].pszLogName, rcNt));
1577 NtClose(hFile);
1578 }
1579 else
1580 SUP_DPRINTF(("%s: NtCreateFile failed: %#x (%ls)\n",
1581 s_aPaths[i].pszLogName, rcNt, Dst.Buffer));
1582 }
1583 else
1584 SUP_DPRINTF(("%s: RtlExpandEnvironmentStrings_U failed: %#x (%ls)\n",
1585 s_aPaths[i].pszLogName, rcNt, Src.Buffer));
1586 }
1587 else
1588 {
1589 SUP_DPRINTF(("%s: type mismatch: %#x\n", s_aPaths[i].pszLogName, uBuf.PartialInfo.Type));
1590 rcNt = STATUS_INVALID_PARAMETER;
1591 }
1592 }
1593 else
1594 SUP_DPRINTF(("%s: NtQueryValueKey failed: %#x\n", s_aPaths[i].pszLogName, rcNt));
1595
1596 /* Stub the entry on failure. */
1597 if (!NT_SUCCESS(rcNt))
1598 {
1599 s_aPaths[i].pNtPath->UniStr.Length = 0;
1600 s_aPaths[i].pNtPath->UniStr.Buffer = NULL;
1601 }
1602 }
1603 NtClose(hKey);
1604 }
1605 else
1606 {
1607 SUP_DPRINTF(("NtOpenKey(%ls) failed: %#x\n", NtName.Buffer, rcNt));
1608
1609 /* Stub all the entries on failure. */
1610 for (uint32_t i = 0; i < RT_ELEMENTS(s_aPaths); i++)
1611 {
1612 s_aPaths[i].pNtPath->UniStr.Length = 0;
1613 s_aPaths[i].pNtPath->UniStr.Buffer = NULL;
1614 }
1615 }
1616}
1617#endif /* IN_RING3 */
1618
1619
1620/**
1621 * This initializes the certificates globals so we don't have to reparse them
1622 * every time we need to verify an image.
1623 *
1624 * @returns IPRT status code.
1625 * @param pErrInfo Where to return extended error info. Optional.
1626 */
1627DECLHIDDEN(int) supHardenedWinInitImageVerifier(PRTERRINFO pErrInfo)
1628{
1629 AssertReturn(!RTCrX509Certificate_IsPresent(&g_BuildX509Cert), VERR_WRONG_ORDER);
1630
1631 /*
1632 * Get the system root paths.
1633 */
1634 int rc = supHardNtGetSystemRootDir(&g_System32NtPath, sizeof(g_System32NtPath), kSupHardNtSysRootDir_System32, pErrInfo);
1635 if (RT_SUCCESS(rc))
1636 rc = supHardNtGetSystemRootDir(&g_WinSxSNtPath, sizeof(g_WinSxSNtPath), kSupHardNtSysRootDir_WinSxS, pErrInfo);
1637 if (RT_SUCCESS(rc))
1638 {
1639 SUP_DPRINTF(("System32: %ls\n", g_System32NtPath.UniStr.Buffer));
1640 SUP_DPRINTF(("WinSxS: %ls\n", g_WinSxSNtPath.UniStr.Buffer));
1641#ifdef IN_RING3
1642 supHardenedWinInitImageVerifierWinPaths();
1643#endif
1644
1645 /*
1646 * Initialize it, leaving the cleanup to the termination call.
1647 */
1648 rc = supHardNtViCertInit(&g_BuildX509Cert, g_abSUPBuildCert, g_cbSUPBuildCert, pErrInfo, "BuildCertificate");
1649 if (RT_SUCCESS(rc))
1650 rc = supHardNtViCertStoreInit(&g_hSpcRootStore, g_aSUPSpcRootTAs, g_cSUPSpcRootTAs,
1651 NULL, 0, NULL, 0, pErrInfo, "SpcRoot");
1652 if (RT_SUCCESS(rc))
1653 rc = supHardNtViCertStoreInit(&g_hNtKernelRootStore, g_aSUPNtKernelRootTAs, g_cSUPNtKernelRootTAs,
1654 NULL, 0, NULL, 0, pErrInfo, "NtKernelRoot");
1655 if (RT_SUCCESS(rc))
1656 rc = supHardNtViCertStoreInit(&g_hSpcAndNtKernelRootStore,
1657 g_aSUPSpcRootTAs, g_cSUPSpcRootTAs,
1658 g_aSUPNtKernelRootTAs, g_cSUPNtKernelRootTAs,
1659 g_aSUPTimestampTAs, g_cSUPTimestampTAs,
1660 pErrInfo, "SpcAndNtKernelRoot");
1661 if (RT_SUCCESS(rc))
1662 rc = supHardNtViCertStoreInit(&g_hSpcAndNtKernelSuppStore,
1663 NULL, 0, NULL, 0, NULL, 0,
1664 pErrInfo, "SpcAndNtKernelSupplemental");
1665
1666#if 0 /* For the time being, always trust the build certificate. It bypasses the timestamp issues of CRT and SDL. */
1667 /* If the build certificate is a test singing certificate, it must be a
1668 trusted root or we'll fail to validate anything. */
1669 if ( RT_SUCCESS(rc)
1670 && RTCrX509Name_Compare(&g_BuildX509Cert.TbsCertificate.Subject, &g_BuildX509Cert.TbsCertificate.Issuer) == 0)
1671#else
1672 if (RT_SUCCESS(rc))
1673#endif
1674 rc = RTCrStoreCertAddEncoded(g_hSpcAndNtKernelRootStore, RTCRCERTCTX_F_ENC_X509_DER,
1675 g_abSUPBuildCert, g_cbSUPBuildCert, pErrInfo);
1676
1677 if (RT_SUCCESS(rc))
1678 {
1679 /*
1680 * Finally initialize known SIDs that we use.
1681 */
1682 SID_IDENTIFIER_AUTHORITY s_NtAuth = SECURITY_NT_AUTHORITY;
1683 NTSTATUS rcNt = RtlInitializeSid(&g_TrustedInstallerSid, &s_NtAuth, SECURITY_SERVICE_ID_RID_COUNT);
1684 if (NT_SUCCESS(rcNt))
1685 {
1686 *RtlSubAuthoritySid(&g_TrustedInstallerSid, 0) = SECURITY_SERVICE_ID_BASE_RID;
1687 *RtlSubAuthoritySid(&g_TrustedInstallerSid, 1) = 956008885;
1688 *RtlSubAuthoritySid(&g_TrustedInstallerSid, 2) = 3418522649;
1689 *RtlSubAuthoritySid(&g_TrustedInstallerSid, 3) = 1831038044;
1690 *RtlSubAuthoritySid(&g_TrustedInstallerSid, 4) = 1853292631;
1691 *RtlSubAuthoritySid(&g_TrustedInstallerSid, 5) = 2271478464;
1692
1693 if (NT_SUCCESS(rcNt))
1694 rcNt = RtlInitializeSid(&g_LocalSystemSid, &s_NtAuth, 1);
1695 if (NT_SUCCESS(rcNt))
1696 {
1697 *RtlSubAuthoritySid(&g_LocalSystemSid, 0) = SECURITY_LOCAL_SYSTEM_RID;
1698 return VINF_SUCCESS;
1699 }
1700 }
1701 rc = RTErrConvertFromNtStatus(rcNt);
1702 }
1703 supHardenedWinTermImageVerifier();
1704 }
1705 return rc;
1706}
1707
1708
1709/**
1710 * Releases resources allocated by supHardenedWinInitImageVerifier.
1711 */
1712DECLHIDDEN(void) supHardenedWinTermImageVerifier(void)
1713{
1714 if (RTCrX509Certificate_IsPresent(&g_BuildX509Cert))
1715 RTAsn1VtDelete(&g_BuildX509Cert.SeqCore.Asn1Core);
1716
1717 RTCrStoreRelease(g_hSpcAndNtKernelSuppStore);
1718 g_hSpcAndNtKernelSuppStore = NIL_RTCRSTORE;
1719 RTCrStoreRelease(g_hSpcAndNtKernelRootStore);
1720 g_hSpcAndNtKernelRootStore = NIL_RTCRSTORE;
1721
1722 RTCrStoreRelease(g_hNtKernelRootStore);
1723 g_hNtKernelRootStore = NIL_RTCRSTORE;
1724 RTCrStoreRelease(g_hSpcRootStore);
1725 g_hSpcRootStore = NIL_RTCRSTORE;
1726}
1727
1728#ifdef IN_RING3
1729
1730/**
1731 * This is a hardcoded list of certificates we thing we might need.
1732 *
1733 * @returns true if wanted, false if not.
1734 * @param pCert The certificate.
1735 */
1736static bool supR3HardenedWinIsDesiredRootCA(PCRTCRX509CERTIFICATE pCert)
1737{
1738 char szSubject[512];
1739 szSubject[sizeof(szSubject) - 1] = '\0';
1740 RTCrX509Name_FormatAsString(&pCert->TbsCertificate.Subject, szSubject, sizeof(szSubject) - 1, NULL);
1741
1742 /*
1743 * Check that it's a plausible root certificate.
1744 */
1745 if (!RTCrX509Certificate_IsSelfSigned(pCert))
1746 {
1747 SUP_DPRINTF(("supR3HardenedWinIsDesiredRootCA: skipping - not-self-signed: %s\n", szSubject));
1748 return false;
1749 }
1750
1751 if (RTAsn1Integer_UnsignedCompareWithU32(&pCert->TbsCertificate.T0.Version, 3) > 0)
1752 {
1753 if ( !(pCert->TbsCertificate.T3.fExtKeyUsage & RTCRX509CERT_KEY_USAGE_F_KEY_CERT_SIGN)
1754 && (pCert->TbsCertificate.T3.fFlags & RTCRX509TBSCERTIFICATE_F_PRESENT_KEY_USAGE) )
1755 {
1756 SUP_DPRINTF(("supR3HardenedWinIsDesiredRootCA: skipping - non-cert-sign: %s\n", szSubject));
1757 return false;
1758 }
1759 if ( pCert->TbsCertificate.T3.pBasicConstraints
1760 && !pCert->TbsCertificate.T3.pBasicConstraints->CA.fValue)
1761 {
1762 SUP_DPRINTF(("supR3HardenedWinIsDesiredRootCA: skipping - non-CA: %s\n", szSubject));
1763 return false;
1764 }
1765 }
1766 if (pCert->TbsCertificate.SubjectPublicKeyInfo.SubjectPublicKey.cBits < 256) /* mostly for u64KeyId reading. */
1767 {
1768 SUP_DPRINTF(("supR3HardenedWinIsDesiredRootCA: skipping - key too small: %u bits %s\n",
1769 pCert->TbsCertificate.SubjectPublicKeyInfo.SubjectPublicKey.cBits, szSubject));
1770 return false;
1771 }
1772 uint64_t const u64KeyId = pCert->TbsCertificate.SubjectPublicKeyInfo.SubjectPublicKey.uBits.pu64[1];
1773
1774# if 0
1775 /*
1776 * Whitelist - Array of names and key clues of the certificates we want.
1777 */
1778 static struct
1779 {
1780 uint64_t u64KeyId;
1781 const char *pszName;
1782 } const s_aWanted[] =
1783 {
1784 /* SPC */
1785 { UINT64_C(0xffffffffffffffff), "C=US, O=VeriSign, Inc., OU=Class 3 Public Primary Certification Authority" },
1786 { UINT64_C(0xffffffffffffffff), "L=Internet, O=VeriSign, Inc., OU=VeriSign Commercial Software Publishers CA" },
1787 { UINT64_C(0x491857ead79dde00), "C=US, O=The Go Daddy Group, Inc., OU=Go Daddy Class 2 Certification Authority" },
1788
1789 /* TS */
1790 { UINT64_C(0xffffffffffffffff), "O=Microsoft Trust Network, OU=Microsoft Corporation, OU=Microsoft Time Stamping Service Root, OU=Copyright (c) 1997 Microsoft Corp." },
1791 { UINT64_C(0xffffffffffffffff), "O=VeriSign Trust Network, OU=VeriSign, Inc., OU=VeriSign Time Stamping Service Root, OU=NO LIABILITY ACCEPTED, (c)97 VeriSign, Inc." },
1792 { UINT64_C(0xffffffffffffffff), "C=ZA, ST=Western Cape, L=Durbanville, O=Thawte, OU=Thawte Certification, CN=Thawte Timestamping CA" },
1793
1794 /* Additional Windows 8.1 list: */
1795 { UINT64_C(0x5ad46780fa5df300), "DC=com, DC=microsoft, CN=Microsoft Root Certificate Authority" },
1796 { UINT64_C(0x3be670c1bd02a900), "OU=Copyright (c) 1997 Microsoft Corp., OU=Microsoft Corporation, CN=Microsoft Root Authority" },
1797 { UINT64_C(0x4d3835aa4180b200), "C=US, ST=Washington, L=Redmond, O=Microsoft Corporation, CN=Microsoft Root Certificate Authority 2011" },
1798 { UINT64_C(0x646e3fe3ba08df00), "C=US, O=MSFT, CN=Microsoft Authenticode(tm) Root Authority" },
1799 { UINT64_C(0xece4e4289e08b900), "C=US, ST=Washington, L=Redmond, O=Microsoft Corporation, CN=Microsoft Root Certificate Authority 2010" },
1800 { UINT64_C(0x59faf1086271bf00), "C=US, ST=Arizona, L=Scottsdale, O=GoDaddy.com, Inc., CN=Go Daddy Root Certificate Authority - G2" },
1801 { UINT64_C(0x3d98ab22bb04a300), "C=IE, O=Baltimore, OU=CyberTrust, CN=Baltimore CyberTrust Root" },
1802 { UINT64_C(0x91e3728b8b40d000), "C=GB, ST=Greater Manchester, L=Salford, O=COMODO CA Limited, CN=COMODO Certification Authority" },
1803 { UINT64_C(0x61a3a33f81aace00), "C=US, ST=UT, L=Salt Lake City, O=The USERTRUST Network, OU=http://www.usertrust.com, CN=UTN-USERFirst-Object" },
1804 { 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]" },
1805 { UINT64_C(0xf4fd306318ccda00), "C=US, O=GeoTrust Inc., CN=GeoTrust Global CA" },
1806 { UINT64_C(0xa0ee62086758b15d), "C=US, O=Equifax, OU=Equifax Secure Certificate Authority" },
1807 { UINT64_C(0x8ff6fc03c1edbd00), "C=US, ST=Arizona, L=Scottsdale, O=Starfield Technologies, Inc., CN=Starfield Root Certificate Authority - G2" },
1808 { UINT64_C(0xa3ce8d99e60eda00), "C=BE, O=GlobalSign nv-sa, OU=Root CA, CN=GlobalSign Root CA" },
1809 { UINT64_C(0xa671e9fec832b700), "C=US, O=Starfield Technologies, Inc., OU=Starfield Class 2 Certification Authority" },
1810 { UINT64_C(0xa8de7211e13be200), "C=US, O=DigiCert Inc, OU=www.digicert.com, CN=DigiCert Global Root CA" },
1811 { 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" },
1812 { UINT64_C(0x7ae89c50f0b6a00f), "C=US, O=GTE Corporation, OU=GTE CyberTrust Solutions, Inc., CN=GTE CyberTrust Global Root" },
1813 { 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" },
1814 { 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]" },
1815 { UINT64_C(0x7c4fd32ec1b1ce00), "C=PL, O=Unizeto Sp. z o.o., CN=Certum CA" },
1816 { UINT64_C(0xd4fbe673e5ccc600), "C=US, O=DigiCert Inc, OU=www.digicert.com, CN=DigiCert High Assurance EV Root CA" },
1817 { 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" },
1818 { UINT64_C(0x6e2ba21058eedf00), "C=US, ST=UT, L=Salt Lake City, O=The USERTRUST Network, OU=http://www.usertrust.com, CN=UTN - DATACorp SGC" },
1819 { 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)" },
1820 { 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" },
1821 { UINT64_C(0x466cbc09db88c100), "C=IL, O=StartCom Ltd., OU=Secure Digital Certificate Signing, CN=StartCom Certification Authority" },
1822 { UINT64_C(0x9259c8abe5ca713a), "L=ValiCert Validation Network, O=ValiCert, Inc., OU=ValiCert Class 2 Policy Validation Authority, CN=http://www.valicert.com/, [email protected]" },
1823 { 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" },
1824 { UINT64_C(0x8043e4ce150ead00), "C=US, O=DigiCert Inc, OU=www.digicert.com, CN=DigiCert Assured ID Root CA" },
1825 { UINT64_C(0x00f2e6331af7b700), "C=SE, O=AddTrust AB, OU=AddTrust External TTP Network, CN=AddTrust External CA Root" },
1826 };
1827
1828
1829 uint32_t i = RT_ELEMENTS(s_aWanted);
1830 while (i-- > 0)
1831 if ( s_aWanted[i].u64KeyId == u64KeyId
1832 || s_aWanted[i].u64KeyId == UINT64_MAX)
1833 if (RTCrX509Name_MatchWithString(&pCert->TbsCertificate.Subject, s_aWanted[i].pszName))
1834 {
1835 SUP_DPRINTF(("supR3HardenedWinIsDesiredRootCA: Adding %#llx %s\n", u64KeyId, szSubject));
1836 return true;
1837 }
1838
1839 SUP_DPRINTF(("supR3HardenedWinIsDesiredRootCA: skipping %#llx %s\n", u64KeyId, szSubject));
1840 return false;
1841# else
1842 /*
1843 * Blacklist approach.
1844 */
1845 static struct
1846 {
1847 uint64_t u64KeyId;
1848 const char *pszName;
1849 } const s_aUnwanted[] =
1850 {
1851 { UINT64_C(0xffffffffffffffff), "C=US, O=U.S. Robots and Mechanical Men, Inc., OU=V.I.K.I." }, /* dummy entry */
1852 };
1853
1854 uint32_t i = RT_ELEMENTS(s_aUnwanted);
1855 while (i-- > 0)
1856 if ( s_aUnwanted[i].u64KeyId == u64KeyId
1857 || s_aUnwanted[i].u64KeyId == UINT64_MAX)
1858 if (RTCrX509Name_MatchWithString(&pCert->TbsCertificate.Subject, s_aUnwanted[i].pszName))
1859 {
1860 SUP_DPRINTF(("supR3HardenedWinIsDesiredRootCA: skipping - blacklisted: %#llx %s\n", u64KeyId, szSubject));
1861 return false;
1862 }
1863
1864 SUP_DPRINTF(("supR3HardenedWinIsDesiredRootCA: Adding %#llx %s\n", u64KeyId, szSubject));
1865 return true;
1866# endif
1867}
1868
1869
1870/**
1871 * Loads a module in the system32 directory.
1872 *
1873 * @returns Module handle on success. Won't return on faliure.
1874 * @param pszName The name of the DLL to load.
1875 */
1876DECLHIDDEN(HMODULE) supR3HardenedWinLoadSystem32Dll(const char *pszName)
1877{
1878 WCHAR wszName[200+60];
1879 UINT cwcDir = GetSystemDirectoryW(wszName, RT_ELEMENTS(wszName) - 60);
1880 wszName[cwcDir] = '\\';
1881 RTUtf16CopyAscii(&wszName[cwcDir + 1], RT_ELEMENTS(wszName) - cwcDir, pszName);
1882
1883 DWORD fFlags = 0;
1884 if (g_uNtVerCombined >= SUP_MAKE_NT_VER_SIMPLE(6, 0))
1885 fFlags = LOAD_LIBRARY_SEARCH_SYSTEM32;
1886 HMODULE hMod = LoadLibraryExW(wszName, NULL, fFlags);
1887 if ( hMod == NULL
1888 && fFlags
1889 && g_uNtVerCombined < SUP_MAKE_NT_VER_SIMPLE(6, 2)
1890 && GetLastError() == ERROR_INVALID_PARAMETER)
1891 {
1892 fFlags = 0;
1893 hMod = LoadLibraryExW(wszName, NULL, fFlags);
1894 }
1895 if (hMod == NULL)
1896 supR3HardenedFatal("Error loading '%s': %u [%ls]", pszName, GetLastError(), wszName);
1897 return hMod;
1898}
1899
1900
1901/**
1902 * Called by supR3HardenedWinResolveVerifyTrustApiAndHookThreadCreation to
1903 * import selected root CAs from the system certificate store.
1904 *
1905 * These certificates permits us to correctly validate third party DLLs.
1906 */
1907static void supR3HardenedWinRetrieveTrustedRootCAs(void)
1908{
1909 uint32_t cAdded = 0;
1910
1911 /*
1912 * Load crypt32.dll and resolve the APIs we need.
1913 */
1914 HMODULE hCrypt32 = supR3HardenedWinLoadSystem32Dll("crypt32.dll");
1915
1916#define RESOLVE_CRYPT32_API(a_Name, a_pfnType) \
1917 a_pfnType pfn##a_Name = (a_pfnType)GetProcAddress(hCrypt32, #a_Name); \
1918 if (pfn##a_Name == NULL) supR3HardenedFatal("Error locating '" #a_Name "' in 'crypt32.dll': %u", GetLastError())
1919 RESOLVE_CRYPT32_API(CertOpenStore, PFNCERTOPENSTORE);
1920 RESOLVE_CRYPT32_API(CertCloseStore, PFNCERTCLOSESTORE);
1921 RESOLVE_CRYPT32_API(CertEnumCertificatesInStore, PFNCERTENUMCERTIFICATESINSTORE);
1922#undef RESOLVE_CRYPT32_API
1923
1924 /*
1925 * Open the root store and look for the certificates we wish to use.
1926 */
1927 DWORD fOpenStore = CERT_STORE_OPEN_EXISTING_FLAG | CERT_STORE_READONLY_FLAG;
1928 HCERTSTORE hStore = pfnCertOpenStore(CERT_STORE_PROV_SYSTEM_W, PKCS_7_ASN_ENCODING | X509_ASN_ENCODING,
1929 NULL /* hCryptProv = default */, CERT_SYSTEM_STORE_LOCAL_MACHINE | fOpenStore, L"Root");
1930 if (!hStore)
1931 hStore = pfnCertOpenStore(CERT_STORE_PROV_SYSTEM_W, PKCS_7_ASN_ENCODING | X509_ASN_ENCODING,
1932 NULL /* hCryptProv = default */, CERT_SYSTEM_STORE_CURRENT_USER | fOpenStore, L"Root");
1933 if (hStore)
1934 {
1935 PCCERT_CONTEXT pCurCtx = NULL;
1936 while ((pCurCtx = pfnCertEnumCertificatesInStore(hStore, pCurCtx)) != NULL)
1937 {
1938 if (pCurCtx->dwCertEncodingType & X509_ASN_ENCODING)
1939 {
1940 RTERRINFOSTATIC StaticErrInfo;
1941 RTASN1CURSORPRIMARY PrimaryCursor;
1942 RTAsn1CursorInitPrimary(&PrimaryCursor, pCurCtx->pbCertEncoded, pCurCtx->cbCertEncoded,
1943 RTErrInfoInitStatic(&StaticErrInfo),
1944 &g_RTAsn1DefaultAllocator, RTASN1CURSOR_FLAGS_DER, "CurCtx");
1945 RTCRX509CERTIFICATE MyCert;
1946 int rc = RTCrX509Certificate_DecodeAsn1(&PrimaryCursor.Cursor, 0, &MyCert, "Cert");
1947 if (RT_SUCCESS(rc))
1948 {
1949 if (supR3HardenedWinIsDesiredRootCA(&MyCert))
1950 {
1951 rc = RTCrStoreCertAddEncoded(g_hSpcRootStore, RTCRCERTCTX_F_ENC_X509_DER,
1952 pCurCtx->pbCertEncoded, pCurCtx->cbCertEncoded, NULL /*pErrInfo*/);
1953 AssertRC(rc);
1954
1955 rc = RTCrStoreCertAddEncoded(g_hSpcAndNtKernelRootStore, RTCRCERTCTX_F_ENC_X509_DER,
1956 pCurCtx->pbCertEncoded, pCurCtx->cbCertEncoded, NULL /*pErrInfo*/);
1957 AssertRC(rc);
1958 cAdded++;
1959 }
1960
1961 RTCrX509Certificate_Delete(&MyCert);
1962 }
1963 /* XP root certificate "C&W HKT SecureNet CA SGC Root" has non-standard validity
1964 timestamps, the UTC formatting isn't Zulu time but specifies timezone offsets.
1965 Ignore these failures and certificates. */
1966 else if (rc != VERR_ASN1_INVALID_UTC_TIME_ENCODING)
1967 AssertMsgFailed(("RTCrX509Certificate_DecodeAsn1 failed: rc=%#x: %s\n", rc, StaticErrInfo.szMsg));
1968 }
1969 }
1970 pfnCertCloseStore(hStore, CERT_CLOSE_STORE_CHECK_FLAG);
1971 g_fHaveOtherRoots = true;
1972 }
1973 SUP_DPRINTF(("supR3HardenedWinRetrieveTrustedRootCAs: cAdded=%u\n", cAdded));
1974}
1975
1976
1977/**
1978 * Resolves the WinVerifyTrust API after the process has been verified and
1979 * installs a thread creation hook.
1980 *
1981 * The WinVerifyTrust API is used in addition our own Authenticode verification
1982 * code. If the image has the IMAGE_DLLCHARACTERISTICS_FORCE_INTEGRITY flag
1983 * set, it will be checked again by the kernel. All our image has this flag set
1984 * and we require all VBox extensions to have it set as well. In effect, the
1985 * authenticode signature will be checked two or three times.
1986 *
1987 * @param pszProgName The program name.
1988 */
1989DECLHIDDEN(void) supR3HardenedWinResolveVerifyTrustApiAndHookThreadCreation(const char *pszProgName)
1990{
1991# ifdef IN_SUP_HARDENED_R3
1992 /*
1993 * Load our the support library DLL that does the thread hooking as the
1994 * security API may trigger the creation of COM worker threads (or
1995 * whatever they are).
1996 *
1997 * The thread creation hook makes the threads very slippery to debuggers by
1998 * irreversably disabling most (if not all) debug events for them.
1999 */
2000 char szPath[RTPATH_MAX];
2001 supR3HardenedPathSharedLibs(szPath, sizeof(szPath) - sizeof("/VBoxSupLib.DLL"));
2002 suplibHardenedStrCat(szPath, "/VBoxSupLib.DLL");
2003 HMODULE hSupLibMod = (HMODULE)supR3HardenedWinLoadLibrary(szPath, true /*fSystem32Only*/);
2004 if (hSupLibMod == NULL)
2005 supR3HardenedFatal("Error loading '%s': %u", szPath, GetLastError());
2006# endif
2007
2008 /*
2009 * Allocate TLS entry for WinVerifyTrust recursion prevention.
2010 */
2011 DWORD iTls = TlsAlloc();
2012 if (iTls != TLS_OUT_OF_INDEXES)
2013 g_iTlsWinVerifyTrustRecursion = iTls;
2014 else
2015 supR3HardenedError(GetLastError(), false /*fFatal*/, "TlsAlloc failed");
2016
2017 /*
2018 * Resolve it.
2019 */
2020 HMODULE hWintrust = supR3HardenedWinLoadSystem32Dll("Wintrust.dll");
2021#define RESOLVE_CRYPT_API(a_Name, a_pfnType, a_uMinWinVer) \
2022 do { \
2023 g_pfn##a_Name = (a_pfnType)GetProcAddress(hWintrust, #a_Name); \
2024 if (g_pfn##a_Name == NULL && (a_uMinWinVer) < g_uNtVerCombined) \
2025 supR3HardenedFatal("Error locating '" #a_Name "' in 'Wintrust.dll': %u", GetLastError()); \
2026 } while (0)
2027
2028 PFNWINVERIFYTRUST pfnWinVerifyTrust = (PFNWINVERIFYTRUST)GetProcAddress(hWintrust, "WinVerifyTrust");
2029 if (!pfnWinVerifyTrust)
2030 supR3HardenedFatal("Error locating 'WinVerifyTrust' in 'Wintrust.dll': %u", GetLastError());
2031
2032 RESOLVE_CRYPT_API(CryptCATAdminAcquireContext, PFNCRYPTCATADMINACQUIRECONTEXT, 0);
2033 RESOLVE_CRYPT_API(CryptCATAdminCalcHashFromFileHandle, PFNCRYPTCATADMINCALCHASHFROMFILEHANDLE, 0);
2034 RESOLVE_CRYPT_API(CryptCATAdminEnumCatalogFromHash, PFNCRYPTCATADMINENUMCATALOGFROMHASH, 0);
2035 RESOLVE_CRYPT_API(CryptCATAdminReleaseCatalogContext, PFNCRYPTCATADMINRELEASECATALOGCONTEXT, 0);
2036 RESOLVE_CRYPT_API(CryptCATAdminReleaseContext, PFNCRYPTCATDADMINRELEASECONTEXT, 0);
2037 RESOLVE_CRYPT_API(CryptCATCatalogInfoFromContext, PFNCRYPTCATCATALOGINFOFROMCONTEXT, 0);
2038
2039 RESOLVE_CRYPT_API(CryptCATAdminAcquireContext2, PFNCRYPTCATADMINACQUIRECONTEXT2, SUP_NT_VER_W80);
2040 RESOLVE_CRYPT_API(CryptCATAdminCalcHashFromFileHandle2, PFNCRYPTCATADMINCALCHASHFROMFILEHANDLE2, SUP_NT_VER_W80);
2041
2042 /*
2043 * Call it on ourselves and ntdll to make sure it loads all the providers
2044 * now, we would otherwise geting into recursive trouble in the
2045 * NtCreateSection hook.
2046 */
2047# ifdef IN_SUP_HARDENED_R3
2048 RTERRINFOSTATIC ErrInfoStatic;
2049 RTErrInfoInitStatic(&ErrInfoStatic);
2050 int rc = supR3HardNtViCallWinVerifyTrust(NULL, g_SupLibHardenedExeNtPath.UniStr.Buffer, 0,
2051 &ErrInfoStatic.Core, pfnWinVerifyTrust);
2052 if (RT_FAILURE(rc))
2053 supR3HardenedFatalMsg(pszProgName, kSupInitOp_Integrity, rc,
2054 "WinVerifyTrust failed on stub executable: %s", ErrInfoStatic.szMsg);
2055# endif
2056
2057 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. */
2058 supR3HardNtViCallWinVerifyTrust(NULL, L"\\SystemRoot\\System32\\ntdll.dll", 0, NULL, pfnWinVerifyTrust);
2059 supR3HardNtViCallWinVerifyTrustCatFile(NULL, L"\\SystemRoot\\System32\\ntdll.dll", 0, NULL, pfnWinVerifyTrust);
2060
2061 g_pfnWinVerifyTrust = pfnWinVerifyTrust;
2062 SUP_DPRINTF(("g_pfnWinVerifyTrust=%p\n", pfnWinVerifyTrust));
2063
2064# ifdef IN_SUP_HARDENED_R3
2065 /*
2066 * Load some problematic DLLs into the verifier cache to prevent
2067 * recursion trouble.
2068 */
2069 supR3HardenedWinVerifyCachePreload(L"\\SystemRoot\\System32\\crypt32.dll");
2070 supR3HardenedWinVerifyCachePreload(L"\\SystemRoot\\System32\\Wintrust.dll");
2071# endif
2072
2073 /*
2074 * Now, get trusted root CAs so we can verify a broader scope of signatures.
2075 */
2076 supR3HardenedWinRetrieveTrustedRootCAs();
2077}
2078
2079
2080static int supR3HardNtViNtToWinPath(PCRTUTF16 pwszNtName, PCRTUTF16 *ppwszWinPath,
2081 PRTUTF16 pwszWinPathBuf, size_t cwcWinPathBuf)
2082{
2083 static const RTUTF16 s_wszPrefix[] = L"\\\\.\\GLOBALROOT";
2084
2085 if (*pwszNtName != '\\' && *pwszNtName != '/')
2086 return VERR_PATH_DOES_NOT_START_WITH_ROOT;
2087
2088 size_t cwcNtName = RTUtf16Len(pwszNtName);
2089 if (RT_ELEMENTS(s_wszPrefix) + cwcNtName > cwcWinPathBuf)
2090 return VERR_FILENAME_TOO_LONG;
2091
2092 memcpy(pwszWinPathBuf, s_wszPrefix, sizeof(s_wszPrefix));
2093 memcpy(&pwszWinPathBuf[sizeof(s_wszPrefix) / sizeof(RTUTF16) - 1], pwszNtName, (cwcNtName + 1) * sizeof(RTUTF16));
2094 *ppwszWinPath = pwszWinPathBuf;
2095 return VINF_SUCCESS;
2096}
2097
2098
2099/**
2100 * Calls WinVerifyTrust to verify an PE image.
2101 *
2102 * @returns VBox status code.
2103 * @param hFile File handle to the executable file.
2104 * @param pwszName Full NT path to the DLL in question, used for
2105 * dealing with unsigned system dlls as well as for
2106 * error/logging.
2107 * @param fFlags Flags, SUPHNTVI_F_XXX.
2108 * @param pErrInfo Pointer to error info structure. Optional.
2109 * @param pfnWinVerifyTrust Pointer to the API.
2110 */
2111static int supR3HardNtViCallWinVerifyTrust(HANDLE hFile, PCRTUTF16 pwszName, uint32_t fFlags, PRTERRINFO pErrInfo,
2112 PFNWINVERIFYTRUST pfnWinVerifyTrust)
2113{
2114 /*
2115 * Convert the name into a Windows name.
2116 */
2117 RTUTF16 wszWinPathBuf[MAX_PATH];
2118 PCRTUTF16 pwszWinPath;
2119 int rc = supR3HardNtViNtToWinPath(pwszName, &pwszWinPath, wszWinPathBuf, RT_ELEMENTS(wszWinPathBuf));
2120 if (RT_FAILURE(rc))
2121 return RTErrInfoSetF(pErrInfo, rc, "Bad path passed to supR3HardNtViCallWinVerifyTrust: rc=%Rrc '%ls'", rc, pwszName);
2122
2123 /*
2124 * Construct input parameters and call the API.
2125 */
2126 WINTRUST_FILE_INFO FileInfo;
2127 RT_ZERO(FileInfo);
2128 FileInfo.cbStruct = sizeof(FileInfo);
2129 FileInfo.pcwszFilePath = pwszWinPath;
2130 FileInfo.hFile = hFile;
2131
2132 GUID PolicyActionGuid = WINTRUST_ACTION_GENERIC_VERIFY_V2;
2133
2134 WINTRUST_DATA TrustData;
2135 RT_ZERO(TrustData);
2136 TrustData.cbStruct = sizeof(TrustData);
2137 TrustData.fdwRevocationChecks = WTD_REVOKE_NONE; /* Keep simple for now. */
2138 TrustData.dwStateAction = WTD_STATEACTION_VERIFY;
2139 TrustData.dwUIChoice = WTD_UI_NONE;
2140 TrustData.dwProvFlags = 0;
2141 if (g_uNtVerCombined >= SUP_MAKE_NT_VER_SIMPLE(6, 0))
2142 TrustData.dwProvFlags = WTD_CACHE_ONLY_URL_RETRIEVAL;
2143 else
2144 TrustData.dwProvFlags = WTD_REVOCATION_CHECK_NONE;
2145 TrustData.dwUnionChoice = WTD_CHOICE_FILE;
2146 TrustData.pFile = &FileInfo;
2147
2148 HRESULT hrc = pfnWinVerifyTrust(NULL /*hwnd*/, &PolicyActionGuid, &TrustData);
2149 if (hrc == S_OK)
2150 rc = VINF_SUCCESS;
2151 else
2152 {
2153 /*
2154 * Failed. Format a nice error message.
2155 */
2156# ifdef DEBUG_bird
2157 if (hrc != CERT_E_CHAINING /* Un-updated vistas, XPs, ++ */)
2158 __debugbreak();
2159# endif
2160 const char *pszErrConst = NULL;
2161 switch (hrc)
2162 {
2163 case TRUST_E_SYSTEM_ERROR: pszErrConst = "TRUST_E_SYSTEM_ERROR"; break;
2164 case TRUST_E_NO_SIGNER_CERT: pszErrConst = "TRUST_E_NO_SIGNER_CERT"; break;
2165 case TRUST_E_COUNTER_SIGNER: pszErrConst = "TRUST_E_COUNTER_SIGNER"; break;
2166 case TRUST_E_CERT_SIGNATURE: pszErrConst = "TRUST_E_CERT_SIGNATURE"; break;
2167 case TRUST_E_TIME_STAMP: pszErrConst = "TRUST_E_TIME_STAMP"; break;
2168 case TRUST_E_BAD_DIGEST: pszErrConst = "TRUST_E_BAD_DIGEST"; break;
2169 case TRUST_E_BASIC_CONSTRAINTS: pszErrConst = "TRUST_E_BASIC_CONSTRAINTS"; break;
2170 case TRUST_E_FINANCIAL_CRITERIA: pszErrConst = "TRUST_E_FINANCIAL_CRITERIA"; break;
2171 case TRUST_E_PROVIDER_UNKNOWN: pszErrConst = "TRUST_E_PROVIDER_UNKNOWN"; break;
2172 case TRUST_E_ACTION_UNKNOWN: pszErrConst = "TRUST_E_ACTION_UNKNOWN"; break;
2173 case TRUST_E_SUBJECT_FORM_UNKNOWN: pszErrConst = "TRUST_E_SUBJECT_FORM_UNKNOWN"; break;
2174 case TRUST_E_SUBJECT_NOT_TRUSTED: pszErrConst = "TRUST_E_SUBJECT_NOT_TRUSTED"; break;
2175 case TRUST_E_NOSIGNATURE: pszErrConst = "TRUST_E_NOSIGNATURE"; break;
2176 case TRUST_E_FAIL: pszErrConst = "TRUST_E_FAIL"; break;
2177 case TRUST_E_EXPLICIT_DISTRUST: pszErrConst = "TRUST_E_EXPLICIT_DISTRUST"; break;
2178 case CERT_E_CHAINING: pszErrConst = "CERT_E_CHAINING"; break;
2179 case CERT_E_REVOCATION_FAILURE: pszErrConst = "CERT_E_REVOCATION_FAILURE"; break;
2180 }
2181 if (pszErrConst)
2182 rc = RTErrInfoSetF(pErrInfo, VERR_LDRVI_UNSUPPORTED_ARCH,
2183 "WinVerifyTrust failed with hrc=%s on '%ls'", pszErrConst, pwszName);
2184 else
2185 rc = RTErrInfoSetF(pErrInfo, VERR_LDRVI_UNSUPPORTED_ARCH,
2186 "WinVerifyTrust failed with hrc=%Rhrc on '%ls'", hrc, pwszName);
2187 SUP_DPRINTF(("supR3HardNtViCallWinVerifyTrust: WinVerifyTrust failed with %#x (%s) on '%ls'\n",
2188 hrc, pszErrConst, pwszName));
2189 }
2190
2191 /* clean up state data. */
2192 TrustData.dwStateAction = WTD_STATEACTION_CLOSE;
2193 FileInfo.hFile = NULL;
2194 hrc = pfnWinVerifyTrust(NULL /*hwnd*/, &PolicyActionGuid, &TrustData);
2195
2196 return rc;
2197}
2198
2199
2200/**
2201 * Calls WinVerifyTrust to verify an PE image via catalog files.
2202 *
2203 * @returns VBox status code.
2204 * @param hFile File handle to the executable file.
2205 * @param pwszName Full NT path to the DLL in question, used for
2206 * dealing with unsigned system dlls as well as for
2207 * error/logging.
2208 * @param fFlags Flags, SUPHNTVI_F_XXX.
2209 * @param pErrInfo Pointer to error info structure. Optional.
2210 * @param pfnWinVerifyTrust Pointer to the API.
2211 */
2212static int supR3HardNtViCallWinVerifyTrustCatFile(HANDLE hFile, PCRTUTF16 pwszName, uint32_t fFlags, PRTERRINFO pErrInfo,
2213 PFNWINVERIFYTRUST pfnWinVerifyTrust)
2214{
2215 SUP_DPRINTF(("supR3HardNtViCallWinVerifyTrustCatFile: hFile=%p pwszName=%ls\n", hFile, pwszName));
2216
2217 /*
2218 * Convert the name into a Windows name.
2219 */
2220 RTUTF16 wszWinPathBuf[MAX_PATH];
2221 PCRTUTF16 pwszWinPath;
2222 int rc = supR3HardNtViNtToWinPath(pwszName, &pwszWinPath, wszWinPathBuf, RT_ELEMENTS(wszWinPathBuf));
2223 if (RT_FAILURE(rc))
2224 return RTErrInfoSetF(pErrInfo, rc, "Bad path passed to supR3HardNtViCallWinVerifyTrustCatFile: rc=%Rrc '%ls'", rc, pwszName);
2225
2226 /*
2227 * Open the file if we didn't get a handle.
2228 */
2229 HANDLE hFileClose = NULL;
2230 if (hFile == RTNT_INVALID_HANDLE_VALUE || hFile == NULL)
2231 {
2232 hFile = RTNT_INVALID_HANDLE_VALUE;
2233 IO_STATUS_BLOCK Ios = RTNT_IO_STATUS_BLOCK_INITIALIZER;
2234
2235 UNICODE_STRING NtName;
2236 NtName.Buffer = (PWSTR)pwszName;
2237 NtName.Length = (USHORT)(RTUtf16Len(pwszName) * sizeof(WCHAR));
2238 NtName.MaximumLength = NtName.Length + sizeof(WCHAR);
2239
2240 OBJECT_ATTRIBUTES ObjAttr;
2241 InitializeObjectAttributes(&ObjAttr, &NtName, OBJ_CASE_INSENSITIVE, NULL /*hRootDir*/, NULL /*pSecDesc*/);
2242
2243 NTSTATUS rcNt = NtCreateFile(&hFile,
2244 FILE_READ_DATA | READ_CONTROL | SYNCHRONIZE,
2245 &ObjAttr,
2246 &Ios,
2247 NULL /* Allocation Size*/,
2248 FILE_ATTRIBUTE_NORMAL,
2249 FILE_SHARE_READ,
2250 FILE_OPEN,
2251 FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT,
2252 NULL /*EaBuffer*/,
2253 0 /*EaLength*/);
2254 if (NT_SUCCESS(rcNt))
2255 rcNt = Ios.Status;
2256 if (!NT_SUCCESS(rcNt))
2257 return RTErrInfoSetF(pErrInfo, RTErrConvertFromNtStatus(rcNt),
2258 "NtCreateFile returned %#x opening '%ls'.", rcNt, pwszName);
2259 hFileClose = hFile;
2260 }
2261
2262 /*
2263 * On Windows 8.0 and later there are more than one digest choice.
2264 */
2265 rc = VERR_LDRVI_NOT_SIGNED;
2266 static struct
2267 {
2268 /** The digest algorithm name. */
2269 const WCHAR *pszAlgorithm;
2270 /** Cached catalog admin handle. */
2271 HCATADMIN volatile hCachedCatAdmin;
2272 } s_aHashes[] =
2273 {
2274 { NULL, NULL },
2275 { L"SHA256", NULL },
2276 };
2277 for (uint32_t i = 0; i < RT_ELEMENTS(s_aHashes); i++)
2278 {
2279 /*
2280 * Another loop for dealing with different trust provider policies
2281 * required for successfully validating different catalog signatures.
2282 */
2283 bool fTryNextPolicy;
2284 uint32_t iPolicy = 0;
2285 static const GUID s_aPolicies[] =
2286 {
2287 DRIVER_ACTION_VERIFY, /* Works with microsoft bits. Most frequently used, thus first. */
2288 WINTRUST_ACTION_GENERIC_VERIFY_V2, /* Works with ATI and other SPC kernel-code signed stuff. */
2289 };
2290 do
2291 {
2292 /*
2293 * Create a context.
2294 */
2295 fTryNextPolicy = false;
2296 bool fFreshContext = false;
2297 BOOL fRc;
2298 HCATADMIN hCatAdmin = ASMAtomicXchgPtr(&s_aHashes[i].hCachedCatAdmin, NULL);
2299 if (hCatAdmin)
2300 {
2301 SUP_DPRINTF(("supR3HardNtViCallWinVerifyTrustCatFile: Cached context %p\n", hCatAdmin));
2302 fFreshContext = false;
2303 fRc = TRUE;
2304 }
2305 else
2306 {
2307l_fresh_context:
2308 fFreshContext = true;
2309 if (g_pfnCryptCATAdminAcquireContext2)
2310 fRc = g_pfnCryptCATAdminAcquireContext2(&hCatAdmin, &s_aPolicies[iPolicy], s_aHashes[i].pszAlgorithm,
2311 NULL /*pStrongHashPolicy*/, 0 /*dwFlags*/);
2312 else
2313 fRc = g_pfnCryptCATAdminAcquireContext(&hCatAdmin, &s_aPolicies[iPolicy], 0 /*dwFlags*/);
2314 SUP_DPRINTF(("supR3HardNtViCallWinVerifyTrustCatFile: New context %p\n", hCatAdmin));
2315 }
2316 if (fRc)
2317 {
2318 SUP_DPRINTF(("supR3HardNtViCallWinVerifyTrustCatFile: hCatAdmin=%p\n", hCatAdmin));
2319
2320 /*
2321 * Hash the file.
2322 */
2323 BYTE abHash[SUPHARDNTVI_MAX_CAT_HASH_SIZE];
2324 DWORD cbHash = sizeof(abHash);
2325 if (g_pfnCryptCATAdminCalcHashFromFileHandle2)
2326 fRc = g_pfnCryptCATAdminCalcHashFromFileHandle2(hCatAdmin, hFile, &cbHash, abHash, 0 /*dwFlags*/);
2327 else
2328 fRc = g_pfnCryptCATAdminCalcHashFromFileHandle(hFile, &cbHash, abHash, 0 /*dwFlags*/);
2329 if (fRc)
2330 {
2331 /* Produce a string version of it that we can pass to WinVerifyTrust. */
2332 RTUTF16 wszDigest[SUPHARDNTVI_MAX_CAT_HASH_SIZE * 2 + 1];
2333 int rc2 = RTUtf16PrintHexBytes(wszDigest, RT_ELEMENTS(wszDigest), abHash, cbHash, RTSTRPRINTHEXBYTES_F_UPPER);
2334 if (RT_SUCCESS(rc2))
2335 {
2336 SUP_DPRINTF(("supR3HardNtViCallWinVerifyTrustCatFile: cbHash=%u wszDigest=%ls\n", cbHash, wszDigest));
2337
2338 /*
2339 * Enumerate catalog information that matches the hash.
2340 */
2341 uint32_t iCat = 0;
2342 HCATINFO hCatInfoPrev = NULL;
2343 do
2344 {
2345 /* Get the next match. */
2346 HCATINFO hCatInfo = g_pfnCryptCATAdminEnumCatalogFromHash(hCatAdmin, abHash, cbHash, 0, &hCatInfoPrev);
2347 if (!hCatInfo)
2348 {
2349 if (!fFreshContext)
2350 {
2351 SUP_DPRINTF(("supR3HardNtViCallWinVerifyTrustCatFile: Retrying with fresh context (CryptCATAdminEnumCatalogFromHash -> %u; iCat=%#x)\n", GetLastError(), iCat));
2352 if (hCatInfoPrev != NULL)
2353 g_pfnCryptCATAdminReleaseCatalogContext(hCatAdmin, hCatInfoPrev, 0 /*dwFlags*/);
2354 g_pfnCryptCATAdminReleaseContext(hCatAdmin, 0 /*dwFlags*/);
2355 goto l_fresh_context;
2356 }
2357 if (iCat == 0)
2358 SUP_DPRINTF(("supR3HardNtViCallWinVerifyTrustCatFile: CryptCATAdminEnumCatalogFromHash failed %u\n", GetLastError()));
2359 break;
2360 }
2361 Assert(hCatInfoPrev == NULL);
2362 hCatInfoPrev = hCatInfo;
2363
2364 /*
2365 * Call WinVerifyTrust.
2366 */
2367 CATALOG_INFO CatInfo;
2368 CatInfo.cbStruct = sizeof(CatInfo);
2369 CatInfo.wszCatalogFile[0] = '\0';
2370 if (g_pfnCryptCATCatalogInfoFromContext(hCatInfo, &CatInfo, 0 /*dwFlags*/))
2371 {
2372 WINTRUST_CATALOG_INFO WtCatInfo;
2373 RT_ZERO(WtCatInfo);
2374 WtCatInfo.cbStruct = sizeof(WtCatInfo);
2375 WtCatInfo.dwCatalogVersion = 0;
2376 WtCatInfo.pcwszCatalogFilePath = CatInfo.wszCatalogFile;
2377 WtCatInfo.pcwszMemberTag = wszDigest;
2378 WtCatInfo.pcwszMemberFilePath = pwszWinPath;
2379 WtCatInfo.pbCalculatedFileHash = abHash;
2380 WtCatInfo.cbCalculatedFileHash = cbHash;
2381 WtCatInfo.pcCatalogContext = NULL;
2382
2383 WINTRUST_DATA TrustData;
2384 RT_ZERO(TrustData);
2385 TrustData.cbStruct = sizeof(TrustData);
2386 TrustData.fdwRevocationChecks = WTD_REVOKE_NONE; /* Keep simple for now. */
2387 TrustData.dwStateAction = WTD_STATEACTION_VERIFY;
2388 TrustData.dwUIChoice = WTD_UI_NONE;
2389 TrustData.dwProvFlags = 0;
2390 if (g_uNtVerCombined >= SUP_MAKE_NT_VER_SIMPLE(6, 0))
2391 TrustData.dwProvFlags = WTD_CACHE_ONLY_URL_RETRIEVAL;
2392 else
2393 TrustData.dwProvFlags = WTD_REVOCATION_CHECK_NONE;
2394 TrustData.dwUnionChoice = WTD_CHOICE_CATALOG;
2395 TrustData.pCatalog = &WtCatInfo;
2396
2397 HRESULT hrc = pfnWinVerifyTrust(NULL /*hwnd*/, &s_aPolicies[iPolicy], &TrustData);
2398 SUP_DPRINTF(("supR3HardNtViCallWinVerifyTrustCatFile: WinVerifyTrust => %#x; cat='%ls'; file='%ls'\n",
2399 hrc, CatInfo.wszCatalogFile, pwszName));
2400
2401 if (SUCCEEDED(hrc))
2402 rc = VINF_SUCCESS;
2403 else if (hrc == TRUST_E_NOSIGNATURE)
2404 { /* ignore because it's useless. */ }
2405 else if (hrc == ERROR_INVALID_PARAMETER)
2406 { /* This is returned if the given file isn't found in the catalog, it seems. */ }
2407 else
2408 {
2409 rc = RTErrInfoSetF(pErrInfo, VERR_SUP_VP_WINTRUST_CAT_FAILURE,
2410 "WinVerifyTrust failed with hrc=%#x on '%ls' and .cat-file='%ls'.",
2411 hrc, pwszWinPath, CatInfo.wszCatalogFile);
2412 fTryNextPolicy |= (hrc == CERT_E_UNTRUSTEDROOT);
2413 }
2414
2415 /* clean up state data. */
2416 TrustData.dwStateAction = WTD_STATEACTION_CLOSE;
2417 hrc = pfnWinVerifyTrust(NULL /*hwnd*/, &s_aPolicies[iPolicy], &TrustData);
2418 Assert(SUCCEEDED(hrc));
2419 }
2420 else
2421 {
2422 rc = RTErrInfoSetF(pErrInfo, RTErrConvertFromWin32(GetLastError()),
2423 "CryptCATCatalogInfoFromContext failed: %d [file=%s]",
2424 GetLastError(), pwszName);
2425 SUP_DPRINTF(("supR3HardNtViCallWinVerifyTrustCatFile: CryptCATCatalogInfoFromContext failed\n"));
2426 }
2427 iCat++;
2428 } while (rc == VERR_LDRVI_NOT_SIGNED && iCat < 128);
2429
2430 if (hCatInfoPrev != NULL)
2431 if (!g_pfnCryptCATAdminReleaseCatalogContext(hCatAdmin, hCatInfoPrev, 0 /*dwFlags*/))
2432 AssertFailed();
2433 }
2434 else
2435 rc = RTErrInfoSetF(pErrInfo, rc2, "RTUtf16PrintHexBytes failed: %Rrc", rc);
2436 }
2437 else
2438 rc = RTErrInfoSetF(pErrInfo, RTErrConvertFromWin32(GetLastError()),
2439 "CryptCATAdminCalcHashFromFileHandle[2] failed: %d [file=%s]", GetLastError(), pwszName);
2440
2441 if (!ASMAtomicCmpXchgPtr(&s_aHashes[i].hCachedCatAdmin, hCatAdmin, NULL))
2442 if (!g_pfnCryptCATAdminReleaseContext(hCatAdmin, 0 /*dwFlags*/))
2443 AssertFailed();
2444 }
2445 else
2446 rc = RTErrInfoSetF(pErrInfo, RTErrConvertFromWin32(GetLastError()),
2447 "CryptCATAdminAcquireContext[2] failed: %d [file=%s]", GetLastError(), pwszName);
2448 iPolicy++;
2449 } while ( fTryNextPolicy
2450 && iPolicy < RT_ELEMENTS(s_aPolicies));
2451
2452 /*
2453 * Only repeat if we've got g_pfnCryptCATAdminAcquireContext2 and can specify the hash algorithm.
2454 */
2455 if (!g_pfnCryptCATAdminAcquireContext2)
2456 break;
2457 if (rc != VERR_LDRVI_NOT_SIGNED)
2458 break;
2459 }
2460
2461 if (hFileClose != NULL)
2462 NtClose(hFileClose);
2463
2464 return rc;
2465}
2466
2467
2468/**
2469 * Verifies the given image using WinVerifyTrust in some way.
2470 *
2471 * This is used by supHardenedWinVerifyImageByLdrMod as well as
2472 * supR3HardenedScreenImage.
2473 *
2474 * @returns IPRT status code.
2475 * @param hFile Handle of the file to verify.
2476 * @param pwszName Full NT path to the DLL in question, used for
2477 * dealing with unsigned system dlls as well as for
2478 * error/logging.
2479 * @param pfWinVerifyTrust Where to return whether WinVerifyTrust was
2480 * actually used.
2481 * @param pErrInfo Pointer to error info structure. Optional.
2482 */
2483DECLHIDDEN(int) supHardenedWinVerifyImageTrust(HANDLE hFile, PCRTUTF16 pwszName, uint32_t fFlags, int rc,
2484 bool *pfWinVerifyTrust, PRTERRINFO pErrInfo)
2485{
2486 if (pfWinVerifyTrust)
2487 *pfWinVerifyTrust = false;
2488
2489 /*
2490 * Call the windows verify trust API if we've resolved it and aren't in
2491 * some obvious recursion.
2492 */
2493 if (g_pfnWinVerifyTrust != NULL)
2494 {
2495 /* Check for recursion. */
2496 bool fNoRecursion;
2497 if (g_iTlsWinVerifyTrustRecursion != UINT32_MAX)
2498 {
2499 fNoRecursion = TlsGetValue(g_iTlsWinVerifyTrustRecursion) == 0;
2500 if (fNoRecursion)
2501 TlsSetValue(g_iTlsWinVerifyTrustRecursion, (void *)1);
2502 }
2503 else
2504 {
2505 uint32_t const idCurrentThread = GetCurrentThreadId();
2506 fNoRecursion = ASMAtomicCmpXchgU32(&g_idActiveThread, idCurrentThread, UINT32_MAX);
2507 }
2508 if (fNoRecursion)
2509 {
2510 /* We can call WinVerifyTrust. */
2511 if (pfWinVerifyTrust)
2512 *pfWinVerifyTrust = true;
2513
2514 if (rc != VERR_LDRVI_NOT_SIGNED)
2515 {
2516 if (rc == VINF_LDRVI_NOT_SIGNED)
2517 {
2518 if (fFlags & SUPHNTVI_F_ALLOW_CAT_FILE_VERIFICATION)
2519 {
2520 int rc2 = supR3HardNtViCallWinVerifyTrustCatFile(hFile, pwszName, fFlags, pErrInfo, g_pfnWinVerifyTrust);
2521 SUP_DPRINTF(("supR3HardNtViCallWinVerifyTrustCatFile -> %d (org %d)\n", rc2, rc));
2522 rc = rc2;
2523 }
2524 else
2525 {
2526 AssertFailed();
2527 rc = VERR_LDRVI_NOT_SIGNED;
2528 }
2529 }
2530 else if (RT_SUCCESS(rc))
2531 {
2532 /** @todo having trouble with a 32-bit windows box when letting these calls thru */
2533 rc = supR3HardNtViCallWinVerifyTrust(hFile, pwszName, fFlags, pErrInfo, g_pfnWinVerifyTrust);
2534 }
2535 else
2536 {
2537 int rc2 = supR3HardNtViCallWinVerifyTrust(hFile, pwszName, fFlags, pErrInfo, g_pfnWinVerifyTrust);
2538 AssertMsg(RT_FAILURE_NP(rc2),
2539 ("rc=%Rrc, rc2=%Rrc %s", rc, rc2, pErrInfo ? pErrInfo->pszMsg : "<no-err-info>"));
2540 }
2541 }
2542
2543 /* Unwind recursion. */
2544 if (g_iTlsWinVerifyTrustRecursion != UINT32_MAX)
2545 TlsSetValue(g_iTlsWinVerifyTrustRecursion, (void *)0);
2546 else
2547 ASMAtomicWriteU32(&g_idActiveThread, UINT32_MAX);
2548 }
2549 else
2550 SUP_DPRINTF(("Detected WinVerifyTrust recursion: rc=%Rrc '%ls'.\n", rc, pwszName));
2551 }
2552 return rc;
2553}
2554
2555
2556/**
2557 * Checks if WinVerifyTrust is callable on the current thread.
2558 *
2559 * Used by the main code to figure whether it makes sense to try revalidate an
2560 * image that hasn't passed thru WinVerifyTrust yet.
2561 *
2562 * @returns true if callable on current thread, false if not.
2563 */
2564DECLHIDDEN(bool) supHardenedWinIsWinVerifyTrustCallable(void)
2565{
2566 return g_pfnWinVerifyTrust != NULL
2567 && ( g_iTlsWinVerifyTrustRecursion != UINT32_MAX
2568 ? (uintptr_t)TlsGetValue(g_iTlsWinVerifyTrustRecursion) == 0
2569 : g_idActiveThread != GetCurrentThreadId() );
2570}
2571
2572
2573
2574/**
2575 * Initializes g_uNtVerCombined and g_NtVerInfo.
2576 * Called from suplibHardenedWindowsMain and suplibOsInit.
2577 */
2578DECLHIDDEN(void) supR3HardenedWinInitVersion(void)
2579{
2580 /*
2581 * Get the windows version. Use RtlGetVersion as GetVersionExW and
2582 * GetVersion might not be telling the whole truth (8.0 on 8.1 depending on
2583 * the application manifest).
2584 */
2585 OSVERSIONINFOEXW NtVerInfo;
2586
2587 RT_ZERO(NtVerInfo);
2588 NtVerInfo.dwOSVersionInfoSize = sizeof(RTL_OSVERSIONINFOEXW);
2589 if (!NT_SUCCESS(RtlGetVersion((PRTL_OSVERSIONINFOW)&NtVerInfo)))
2590 {
2591 RT_ZERO(NtVerInfo);
2592 PPEB pPeb = NtCurrentPeb();
2593 NtVerInfo.dwMajorVersion = pPeb->OSMajorVersion;
2594 NtVerInfo.dwMinorVersion = pPeb->OSMinorVersion;
2595 NtVerInfo.dwBuildNumber = pPeb->OSPlatformId;
2596 }
2597
2598 g_uNtVerCombined = SUP_MAKE_NT_VER_COMBINED(NtVerInfo.dwMajorVersion, NtVerInfo.dwMinorVersion, NtVerInfo.dwBuildNumber,
2599 NtVerInfo.wServicePackMajor, NtVerInfo.wServicePackMinor);
2600}
2601
2602#endif /* IN_RING3 */
2603
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