VirtualBox

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

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

SUP: Fixed comctl32.dll resolving (generic winsxs) and fixed a crash log statement in LdrLoadDll when the search path is used for flags instead of an actual string pointer.

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