VirtualBox

source: vbox/trunk/src/VBox/HostDrivers/Support/win/SUPR3HardenedMain-win.cpp@ 67978

Last change on this file since 67978 was 67978, checked in by vboxsync, 7 years ago

Oops

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 272.9 KB
Line 
1/* $Id: SUPR3HardenedMain-win.cpp 67978 2017-07-14 15:11:25Z vboxsync $ */
2/** @file
3 * VirtualBox Support Library - Hardened main(), windows bits.
4 */
5
6/*
7 * Copyright (C) 2006-2016 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 *
17 * The contents of this file may alternatively be used under the terms
18 * of the Common Development and Distribution License Version 1.0
19 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
20 * VirtualBox OSE distribution, in which case the provisions of the
21 * CDDL are applicable instead of those of the GPL.
22 *
23 * You may elect to license modified versions of this file under the
24 * terms and conditions of either the GPL or the CDDL or both.
25 */
26
27
28/*********************************************************************************************************************************
29* Header Files *
30*********************************************************************************************************************************/
31#include <iprt/nt/nt-and-windows.h>
32#include <AccCtrl.h>
33#include <AclApi.h>
34#ifndef PROCESS_SET_LIMITED_INFORMATION
35# define PROCESS_SET_LIMITED_INFORMATION 0x2000
36#endif
37#ifndef LOAD_LIBRARY_SEARCH_APPLICATION_DIR
38# define LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR UINT32_C(0x100)
39# define LOAD_LIBRARY_SEARCH_APPLICATION_DIR UINT32_C(0x200)
40# define LOAD_LIBRARY_SEARCH_USER_DIRS UINT32_C(0x400)
41# define LOAD_LIBRARY_SEARCH_SYSTEM32 UINT32_C(0x800)
42#endif
43
44#include <VBox/sup.h>
45#include <VBox/err.h>
46#include <VBox/dis.h>
47#include <iprt/ctype.h>
48#include <iprt/string.h>
49#include <iprt/initterm.h>
50#include <iprt/param.h>
51#include <iprt/path.h>
52#include <iprt/thread.h>
53#include <iprt/zero.h>
54
55#include "SUPLibInternal.h"
56#include "win/SUPHardenedVerify-win.h"
57#include "../SUPDrvIOC.h"
58
59#ifndef IMAGE_SCN_TYPE_NOLOAD
60# define IMAGE_SCN_TYPE_NOLOAD 0x00000002
61#endif
62
63
64/*********************************************************************************************************************************
65* Defined Constants And Macros *
66*********************************************************************************************************************************/
67/** The first argument of a respawed stub when respawned for the first time.
68 * This just needs to be unique enough to avoid most confusion with real
69 * executable names, there are other checks in place to make sure we've respanwed. */
70#define SUPR3_RESPAWN_1_ARG0 "60eaff78-4bdd-042d-2e72-669728efd737-suplib-2ndchild"
71
72/** The first argument of a respawed stub when respawned for the second time.
73 * This just needs to be unique enough to avoid most confusion with real
74 * executable names, there are other checks in place to make sure we've respanwed. */
75#define SUPR3_RESPAWN_2_ARG0 "60eaff78-4bdd-042d-2e72-669728efd737-suplib-3rdchild"
76
77/** Unconditional assertion. */
78#define SUPR3HARDENED_ASSERT(a_Expr) \
79 do { \
80 if (!(a_Expr)) \
81 supR3HardenedFatal("%s: %s\n", __FUNCTION__, #a_Expr); \
82 } while (0)
83
84/** Unconditional assertion of NT_SUCCESS. */
85#define SUPR3HARDENED_ASSERT_NT_SUCCESS(a_Expr) \
86 do { \
87 NTSTATUS rcNtAssert = (a_Expr); \
88 if (!NT_SUCCESS(rcNtAssert)) \
89 supR3HardenedFatal("%s: %s -> %#x\n", __FUNCTION__, #a_Expr, rcNtAssert); \
90 } while (0)
91
92/** Unconditional assertion of a WIN32 API returning non-FALSE. */
93#define SUPR3HARDENED_ASSERT_WIN32_SUCCESS(a_Expr) \
94 do { \
95 BOOL fRcAssert = (a_Expr); \
96 if (fRcAssert == FALSE) \
97 supR3HardenedFatal("%s: %s -> %#x\n", __FUNCTION__, #a_Expr, RtlGetLastWin32Error()); \
98 } while (0)
99
100
101/*********************************************************************************************************************************
102* Structures and Typedefs *
103*********************************************************************************************************************************/
104/**
105 * Security descriptor cleanup structure.
106 */
107typedef struct MYSECURITYCLEANUP
108{
109 union
110 {
111 SID Sid;
112 uint8_t abPadding[SECURITY_MAX_SID_SIZE];
113 } Everyone, Owner, User, Login;
114 union
115 {
116 ACL AclHdr;
117 uint8_t abPadding[1024];
118 } Acl;
119 PSECURITY_DESCRIPTOR pSecDesc;
120} MYSECURITYCLEANUP;
121/** Pointer to security cleanup structure. */
122typedef MYSECURITYCLEANUP *PMYSECURITYCLEANUP;
123
124
125/**
126 * Image verifier cache entry.
127 */
128typedef struct VERIFIERCACHEENTRY
129{
130 /** Pointer to the next entry with the same hash value. */
131 struct VERIFIERCACHEENTRY * volatile pNext;
132 /** Next entry in the WinVerifyTrust todo list. */
133 struct VERIFIERCACHEENTRY * volatile pNextTodoWvt;
134
135 /** The file handle. */
136 HANDLE hFile;
137 /** If fIndexNumber is set, this is an file system internal file identifier. */
138 LARGE_INTEGER IndexNumber;
139 /** The path hash value. */
140 uint32_t uHash;
141 /** The verification result. */
142 int rc;
143 /** Used for shutting up load and error messages after a while so they don't
144 * flood the log file and fill up the disk. */
145 uint32_t volatile cHits;
146 /** The validation flags (for WinVerifyTrust retry). */
147 uint32_t fFlags;
148 /** Whether IndexNumber is valid */
149 bool fIndexNumberValid;
150 /** Whether verified by WinVerifyTrust. */
151 bool volatile fWinVerifyTrust;
152 /** cwcPath * sizeof(RTUTF16). */
153 uint16_t cbPath;
154 /** The full path of this entry (variable size). */
155 RTUTF16 wszPath[1];
156} VERIFIERCACHEENTRY;
157/** Pointer to an image verifier path entry. */
158typedef VERIFIERCACHEENTRY *PVERIFIERCACHEENTRY;
159
160
161/**
162 * Name of an import DLL that we need to check out.
163 */
164typedef struct VERIFIERCACHEIMPORT
165{
166 /** Pointer to the next DLL in the list. */
167 struct VERIFIERCACHEIMPORT * volatile pNext;
168 /** The length of pwszAltSearchDir if available. */
169 uint32_t cwcAltSearchDir;
170 /** This points the directory containing the DLL needing it, this will be
171 * NULL for a System32 DLL. */
172 PWCHAR pwszAltSearchDir;
173 /** The name of the import DLL (variable length). */
174 char szName[1];
175} VERIFIERCACHEIMPORT;
176/** Pointer to a import DLL that needs checking out. */
177typedef VERIFIERCACHEIMPORT *PVERIFIERCACHEIMPORT;
178
179
180/**
181 * Child requests.
182 */
183typedef enum SUPR3WINCHILDREQ
184{
185 /** Perform child purification and close full access handles (must be zero). */
186 kSupR3WinChildReq_PurifyChildAndCloseHandles = 0,
187 /** Close the events, we're good on our own from here on. */
188 kSupR3WinChildReq_CloseEvents,
189 /** Reporting error. */
190 kSupR3WinChildReq_Error,
191 /** End of valid requests. */
192 kSupR3WinChildReq_End
193} SUPR3WINCHILDREQ;
194
195/**
196 * Child process parameters.
197 */
198typedef struct SUPR3WINPROCPARAMS
199{
200 /** The event semaphore the child will be waiting on. */
201 HANDLE hEvtChild;
202 /** The event semaphore the parent will be waiting on. */
203 HANDLE hEvtParent;
204
205 /** The address of the NTDLL. This is only valid during the very early
206 * initialization as we abuse for thread creation protection. */
207 uintptr_t uNtDllAddr;
208
209 /** The requested operation (set by the child). */
210 SUPR3WINCHILDREQ enmRequest;
211 /** The last status. */
212 int32_t rc;
213 /** The init operation the error relates to if message, kSupInitOp_Invalid if
214 * not message. */
215 SUPINITOP enmWhat;
216 /** Where if message. */
217 char szWhere[80];
218 /** Error message / path name string space. */
219 char szErrorMsg[16384+1024];
220} SUPR3WINPROCPARAMS;
221
222
223/**
224 * Child process data structure for use during child process init setup and
225 * purification.
226 */
227typedef struct SUPR3HARDNTCHILD
228{
229 /** Process handle. */
230 HANDLE hProcess;
231 /** Primary thread handle. */
232 HANDLE hThread;
233 /** Handle to the parent process, if we're the middle (stub) process. */
234 HANDLE hParent;
235 /** The event semaphore the child will be waiting on. */
236 HANDLE hEvtChild;
237 /** The event semaphore the parent will be waiting on. */
238 HANDLE hEvtParent;
239 /** The address of NTDLL in the child. */
240 uintptr_t uNtDllAddr;
241 /** The address of NTDLL in this process. */
242 uintptr_t uNtDllParentAddr;
243 /** Which respawn number this is (1 = stub, 2 = VM). */
244 int iWhich;
245 /** The basic process info. */
246 PROCESS_BASIC_INFORMATION BasicInfo;
247 /** The probable size of the PEB. */
248 size_t cbPeb;
249 /** The pristine process environment block. */
250 PEB Peb;
251 /** The child process parameters. */
252 SUPR3WINPROCPARAMS ProcParams;
253} SUPR3HARDNTCHILD;
254/** Pointer to a child process data structure. */
255typedef SUPR3HARDNTCHILD *PSUPR3HARDNTCHILD;
256
257
258/*********************************************************************************************************************************
259* Global Variables *
260*********************************************************************************************************************************/
261/** Process parameters. Specified by parent if VM process, see
262 * supR3HardenedVmProcessInit. */
263static SUPR3WINPROCPARAMS g_ProcParams = { NULL, NULL, 0, (SUPR3WINCHILDREQ)0, 0 };
264/** Set if supR3HardenedEarlyProcessInit was invoked. */
265bool g_fSupEarlyProcessInit = false;
266/** Set if the stub device has been opened (stub process only). */
267bool g_fSupStubOpened = false;
268
269/** @name Global variables initialized by suplibHardenedWindowsMain.
270 * @{ */
271/** Combined windows NT version number. See SUP_MAKE_NT_VER_COMBINED. */
272uint32_t g_uNtVerCombined = 0;
273/** Count calls to the special main function for linking santity checks. */
274static uint32_t volatile g_cSuplibHardenedWindowsMainCalls;
275/** The UTF-16 windows path to the executable. */
276RTUTF16 g_wszSupLibHardenedExePath[1024];
277/** The NT path of the executable. */
278SUPSYSROOTDIRBUF g_SupLibHardenedExeNtPath;
279/** The NT path of the application binary directory. */
280SUPSYSROOTDIRBUF g_SupLibHardenedAppBinNtPath;
281/** The offset into g_SupLibHardenedExeNtPath of the executable name (WCHAR,
282 * not byte). This also gives the length of the exectuable directory path,
283 * including a trailing slash. */
284static uint32_t g_offSupLibHardenedExeNtName;
285/** Set if we need to use the LOAD_LIBRARY_SEARCH_USER_DIRS option. */
286bool g_fSupLibHardenedDllSearchUserDirs = false;
287/** @} */
288
289/** @name Hook related variables.
290 * @{ */
291/** Pointer to the bit of assembly code that will perform the original
292 * NtCreateSection operation. */
293static NTSTATUS (NTAPI * g_pfnNtCreateSectionReal)(PHANDLE, ACCESS_MASK, POBJECT_ATTRIBUTES,
294 PLARGE_INTEGER, ULONG, ULONG, HANDLE);
295/** Pointer to the NtCreateSection function in NtDll (for patching purposes). */
296static uint8_t *g_pbNtCreateSection;
297/** The patched NtCreateSection bytes (for restoring). */
298static uint8_t g_abNtCreateSectionPatch[16];
299/** Pointer to the bit of assembly code that will perform the original
300 * LdrLoadDll operation. */
301static NTSTATUS (NTAPI * g_pfnLdrLoadDllReal)(PWSTR, PULONG, PUNICODE_STRING, PHANDLE);
302/** Pointer to the LdrLoadDll function in NtDll (for patching purposes). */
303static uint8_t *g_pbLdrLoadDll;
304/** The patched LdrLoadDll bytes (for restoring). */
305static uint8_t g_abLdrLoadDllPatch[16];
306
307/** The hash table of verifier cache . */
308static PVERIFIERCACHEENTRY volatile g_apVerifierCache[128];
309/** Queue of cached images which needs WinVerifyTrust to check them. */
310static PVERIFIERCACHEENTRY volatile g_pVerifierCacheTodoWvt = NULL;
311/** Queue of cached images which needs their imports checked. */
312static PVERIFIERCACHEIMPORT volatile g_pVerifierCacheTodoImports = NULL;
313
314/** The windows path to dir \\SystemRoot\\System32 directory (technically
315 * this whatever \\KnownDlls\\KnownDllPath points to). */
316SUPSYSROOTDIRBUF g_System32WinPath;
317/** @ */
318
319/** Positive if the DLL notification callback has been registered, counts
320 * registration attempts as negative. */
321static int g_cDllNotificationRegistered = 0;
322/** The registration cookie of the DLL notification callback. */
323static PVOID g_pvDllNotificationCookie = NULL;
324
325/** Static error info structure used during init. */
326static RTERRINFOSTATIC g_ErrInfoStatic;
327
328/** In the assembly file. */
329extern "C" uint8_t g_abSupHardReadWriteExecPage[PAGE_SIZE];
330
331/** Whether we've patched our own LdrInitializeThunk or not. We do this to
332 * disable thread creation. */
333static bool g_fSupInitThunkSelfPatched;
334/** The backup of our own LdrInitializeThunk code, for enabling and disabling
335 * thread creation in this process. */
336static uint8_t g_abLdrInitThunkSelfBackup[16];
337
338/** Mask of adversaries that we've detected (SUPHARDNT_ADVERSARY_XXX). */
339static uint32_t g_fSupAdversaries = 0;
340/** @name SUPHARDNT_ADVERSARY_XXX - Adversaries
341 * @{ */
342/** Symantec endpoint protection or similar including SysPlant.sys. */
343#define SUPHARDNT_ADVERSARY_SYMANTEC_SYSPLANT RT_BIT_32(0)
344/** Symantec Norton 360. */
345#define SUPHARDNT_ADVERSARY_SYMANTEC_N360 RT_BIT_32(1)
346/** Avast! */
347#define SUPHARDNT_ADVERSARY_AVAST RT_BIT_32(2)
348/** TrendMicro OfficeScan and probably others. */
349#define SUPHARDNT_ADVERSARY_TRENDMICRO RT_BIT_32(3)
350/** TrendMicro potentially buggy sakfile.sys. */
351#define SUPHARDNT_ADVERSARY_TRENDMICRO_SAKFILE RT_BIT_32(4)
352/** McAfee. */
353#define SUPHARDNT_ADVERSARY_MCAFEE RT_BIT_32(5)
354/** Kaspersky or OEMs of it. */
355#define SUPHARDNT_ADVERSARY_KASPERSKY RT_BIT_32(6)
356/** Malwarebytes Anti-Malware (MBAM). */
357#define SUPHARDNT_ADVERSARY_MBAM RT_BIT_32(7)
358/** AVG Internet Security. */
359#define SUPHARDNT_ADVERSARY_AVG RT_BIT_32(8)
360/** Panda Security. */
361#define SUPHARDNT_ADVERSARY_PANDA RT_BIT_32(9)
362/** Microsoft Security Essentials. */
363#define SUPHARDNT_ADVERSARY_MSE RT_BIT_32(10)
364/** Comodo. */
365#define SUPHARDNT_ADVERSARY_COMODO RT_BIT_32(11)
366/** Check Point's Zone Alarm (may include Kaspersky). */
367#define SUPHARDNT_ADVERSARY_ZONE_ALARM RT_BIT_32(12)
368/** Digital guardian, old problematic version. */
369#define SUPHARDNT_ADVERSARY_DIGITAL_GUARDIAN_OLD RT_BIT_32(13)
370/** Digital guardian, new version. */
371#define SUPHARDNT_ADVERSARY_DIGITAL_GUARDIAN_NEW RT_BIT_32(14)
372/** Cylance protect or something (from googling, no available sample copy). */
373#define SUPHARDNT_ADVERSARY_CYLANCE RT_BIT_32(15)
374/** BeyondTrust / PowerBroker / something (googling, no available sample copy). */
375#define SUPHARDNT_ADVERSARY_BEYONDTRUST RT_BIT_32(16)
376/** Avecto / Defendpoint / Privilege Guard (details from support guy, hoping to get sample copy). */
377#define SUPHARDNT_ADVERSARY_AVECTO RT_BIT_32(17)
378/** Unknown adversary detected while waiting on child. */
379#define SUPHARDNT_ADVERSARY_UNKNOWN RT_BIT_32(31)
380/** @} */
381
382
383/*********************************************************************************************************************************
384* Internal Functions *
385*********************************************************************************************************************************/
386static NTSTATUS supR3HardenedScreenImage(HANDLE hFile, bool fImage, bool fIgnoreArch, PULONG pfAccess, PULONG pfProtect,
387 bool *pfCallRealApi, const char *pszCaller, bool fAvoidWinVerifyTrust,
388 bool *pfQuiet);
389static void supR3HardenedWinRegisterDllNotificationCallback(void);
390static void supR3HardenedWinReInstallHooks(bool fFirst);
391DECLASM(void) supR3HardenedEarlyProcessInitThunk(void);
392
393
394#if 0 /* unused */
395
396/**
397 * Simple wide char search routine.
398 *
399 * @returns Pointer to the first location of @a wcNeedle in @a pwszHaystack.
400 * NULL if not found.
401 * @param pwszHaystack Pointer to the string that should be searched.
402 * @param wcNeedle The character to search for.
403 */
404static PRTUTF16 suplibHardenedWStrChr(PCRTUTF16 pwszHaystack, RTUTF16 wcNeedle)
405{
406 for (;;)
407 {
408 RTUTF16 wcCur = *pwszHaystack;
409 if (wcCur == wcNeedle)
410 return (PRTUTF16)pwszHaystack;
411 if (wcCur == '\0')
412 return NULL;
413 pwszHaystack++;
414 }
415}
416
417
418/**
419 * Simple wide char string length routine.
420 *
421 * @returns The number of characters in the given string. (Excludes the
422 * terminator.)
423 * @param pwsz The string.
424 */
425static size_t suplibHardenedWStrLen(PCRTUTF16 pwsz)
426{
427 PCRTUTF16 pwszCur = pwsz;
428 while (*pwszCur != '\0')
429 pwszCur++;
430 return pwszCur - pwsz;
431}
432
433#endif /* unused */
434
435
436/**
437 * Our version of GetTickCount.
438 * @returns Millisecond timestamp.
439 */
440static uint64_t supR3HardenedWinGetMilliTS(void)
441{
442 PKUSER_SHARED_DATA pUserSharedData = (PKUSER_SHARED_DATA)(uintptr_t)0x7ffe0000;
443
444 /* use interrupt time */
445 LARGE_INTEGER Time;
446 do
447 {
448 Time.HighPart = pUserSharedData->InterruptTime.High1Time;
449 Time.LowPart = pUserSharedData->InterruptTime.LowPart;
450 } while (pUserSharedData->InterruptTime.High2Time != Time.HighPart);
451
452 return (uint64_t)Time.QuadPart / 10000;
453}
454
455
456
457/**
458 * Wrapper around LoadLibraryEx that deals with the UTF-8 to UTF-16 conversion
459 * and supplies the right flags.
460 *
461 * @returns Module handle on success, NULL on failure.
462 * @param pszName The full path to the DLL.
463 * @param fSystem32Only Whether to only look for imports in the system32
464 * directory. If set to false, the application
465 * directory is also searched.
466 * @param fMainFlags The main flags (giving the location), if the DLL
467 * being loaded is loaded from the app bin
468 * directory and import other DLLs from there. Pass
469 * 0 (= SUPSECMAIN_FLAGS_LOC_APP_BIN) if not
470 * applicable. Ignored if @a fSystem32Only is set.
471 *
472 * This is only needed to load VBoxRT.dll when
473 * executing a testcase from the testcase/ subdir.
474 */
475DECLHIDDEN(void *) supR3HardenedWinLoadLibrary(const char *pszName, bool fSystem32Only, uint32_t fMainFlags)
476{
477 WCHAR wszPath[RTPATH_MAX];
478 PRTUTF16 pwszPath = wszPath;
479 int rc = RTStrToUtf16Ex(pszName, RTSTR_MAX, &pwszPath, RT_ELEMENTS(wszPath), NULL);
480 if (RT_SUCCESS(rc))
481 {
482 while (*pwszPath)
483 {
484 if (*pwszPath == '/')
485 *pwszPath = '\\';
486 pwszPath++;
487 }
488
489 DWORD fFlags = 0;
490 if (g_uNtVerCombined >= SUP_MAKE_NT_VER_SIMPLE(6, 0))
491 {
492 fFlags |= LOAD_LIBRARY_SEARCH_SYSTEM32;
493 if (!fSystem32Only)
494 {
495 fFlags |= LOAD_LIBRARY_SEARCH_APPLICATION_DIR;
496 if (g_fSupLibHardenedDllSearchUserDirs)
497 fFlags |= LOAD_LIBRARY_SEARCH_USER_DIRS;
498 if ((fMainFlags & SUPSECMAIN_FLAGS_LOC_MASK) != SUPSECMAIN_FLAGS_LOC_APP_BIN)
499 fFlags |= LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR;
500 }
501 }
502
503 void *pvRet = (void *)LoadLibraryExW(wszPath, NULL /*hFile*/, fFlags);
504
505 /* Vista, W7, W2K8R might not work without KB2533623, so retry with no flags. */
506 if ( !pvRet
507 && fFlags
508 && g_uNtVerCombined < SUP_MAKE_NT_VER_SIMPLE(6, 2)
509 && RtlGetLastWin32Error() == ERROR_INVALID_PARAMETER)
510 pvRet = (void *)LoadLibraryExW(wszPath, NULL /*hFile*/, 0);
511
512 return pvRet;
513 }
514 supR3HardenedFatal("RTStrToUtf16Ex failed on '%s': %Rrc", pszName, rc);
515 /* not reached */
516}
517
518
519/**
520 * Gets the internal index number of the file.
521 *
522 * @returns True if we got an index number, false if not.
523 * @param hFile The file in question.
524 * @param pIndexNumber where to return the index number.
525 */
526static bool supR3HardenedWinVerifyCacheGetIndexNumber(HANDLE hFile, PLARGE_INTEGER pIndexNumber)
527{
528 IO_STATUS_BLOCK Ios = RTNT_IO_STATUS_BLOCK_INITIALIZER;
529 NTSTATUS rcNt = NtQueryInformationFile(hFile, &Ios, pIndexNumber, sizeof(*pIndexNumber), FileInternalInformation);
530 if (NT_SUCCESS(rcNt))
531 rcNt = Ios.Status;
532#ifdef DEBUG_bird
533 if (!NT_SUCCESS(rcNt))
534 __debugbreak();
535#endif
536 return NT_SUCCESS(rcNt) && pIndexNumber->QuadPart != 0;
537}
538
539
540/**
541 * Calculates the hash value for the given UTF-16 path string.
542 *
543 * @returns Hash value.
544 * @param pUniStr String to hash.
545 */
546static uint32_t supR3HardenedWinVerifyCacheHashPath(PCUNICODE_STRING pUniStr)
547{
548 uint32_t uHash = 0;
549 unsigned cwcLeft = pUniStr->Length / sizeof(WCHAR);
550 PRTUTF16 pwc = pUniStr->Buffer;
551
552 while (cwcLeft-- > 0)
553 {
554 RTUTF16 wc = *pwc++;
555 if (wc < 0x80)
556 wc = wc != '/' ? RT_C_TO_LOWER(wc) : '\\';
557 uHash = wc + (uHash << 6) + (uHash << 16) - uHash;
558 }
559 return uHash;
560}
561
562
563/**
564 * Calculates the hash value for a directory + filename combo as if they were
565 * one single string.
566 *
567 * @returns Hash value.
568 * @param pawcDir The directory name.
569 * @param cwcDir The length of the directory name. RTSTR_MAX if
570 * not available.
571 * @param pszName The import name (UTF-8).
572 */
573static uint32_t supR3HardenedWinVerifyCacheHashDirAndFile(PCRTUTF16 pawcDir, uint32_t cwcDir, const char *pszName)
574{
575 uint32_t uHash = 0;
576 while (cwcDir-- > 0)
577 {
578 RTUTF16 wc = *pawcDir++;
579 if (wc < 0x80)
580 wc = wc != '/' ? RT_C_TO_LOWER(wc) : '\\';
581 uHash = wc + (uHash << 6) + (uHash << 16) - uHash;
582 }
583
584 unsigned char ch = '\\';
585 uHash = ch + (uHash << 6) + (uHash << 16) - uHash;
586
587 while ((ch = *pszName++) != '\0')
588 {
589 ch = RT_C_TO_LOWER(ch);
590 uHash = ch + (uHash << 6) + (uHash << 16) - uHash;
591 }
592
593 return uHash;
594}
595
596
597/**
598 * Verify string cache compare function.
599 *
600 * @returns true if the strings match, false if not.
601 * @param pawcLeft The left hand string.
602 * @param pawcRight The right hand string.
603 * @param cwcToCompare The number of chars to compare.
604 */
605static bool supR3HardenedWinVerifyCacheIsMatch(PCRTUTF16 pawcLeft, PCRTUTF16 pawcRight, uint32_t cwcToCompare)
606{
607 /* Try a quick memory compare first. */
608 if (memcmp(pawcLeft, pawcRight, cwcToCompare * sizeof(RTUTF16)) == 0)
609 return true;
610
611 /* Slow char by char compare. */
612 while (cwcToCompare-- > 0)
613 {
614 RTUTF16 wcLeft = *pawcLeft++;
615 RTUTF16 wcRight = *pawcRight++;
616 if (wcLeft != wcRight)
617 {
618 wcLeft = wcLeft != '/' ? RT_C_TO_LOWER(wcLeft) : '\\';
619 wcRight = wcRight != '/' ? RT_C_TO_LOWER(wcRight) : '\\';
620 if (wcLeft != wcRight)
621 return false;
622 }
623 }
624
625 return true;
626}
627
628
629
630/**
631 * Inserts the given verifier result into the cache.
632 *
633 * @param pUniStr The full path of the image.
634 * @param hFile The file handle - must either be entered into
635 * the cache or closed.
636 * @param rc The verifier result.
637 * @param fWinVerifyTrust Whether verified by WinVerifyTrust or not.
638 * @param fFlags The image verification flags.
639 */
640static void supR3HardenedWinVerifyCacheInsert(PCUNICODE_STRING pUniStr, HANDLE hFile, int rc,
641 bool fWinVerifyTrust, uint32_t fFlags)
642{
643 /*
644 * Allocate and initalize a new entry.
645 */
646 PVERIFIERCACHEENTRY pEntry = (PVERIFIERCACHEENTRY)RTMemAllocZ(sizeof(VERIFIERCACHEENTRY) + pUniStr->Length);
647 if (pEntry)
648 {
649 pEntry->pNext = NULL;
650 pEntry->pNextTodoWvt = NULL;
651 pEntry->hFile = hFile;
652 pEntry->uHash = supR3HardenedWinVerifyCacheHashPath(pUniStr);
653 pEntry->rc = rc;
654 pEntry->fFlags = fFlags;
655 pEntry->cHits = 0;
656 pEntry->fWinVerifyTrust = fWinVerifyTrust;
657 pEntry->cbPath = pUniStr->Length;
658 memcpy(pEntry->wszPath, pUniStr->Buffer, pUniStr->Length);
659 pEntry->wszPath[pUniStr->Length / sizeof(WCHAR)] = '\0';
660 pEntry->fIndexNumberValid = supR3HardenedWinVerifyCacheGetIndexNumber(hFile, &pEntry->IndexNumber);
661
662 /*
663 * Try insert it, careful with concurrent code as well as potential duplicates.
664 */
665 uint32_t iHashTab = pEntry->uHash % RT_ELEMENTS(g_apVerifierCache);
666 VERIFIERCACHEENTRY * volatile *ppEntry = &g_apVerifierCache[iHashTab];
667 for (;;)
668 {
669 if (ASMAtomicCmpXchgPtr(ppEntry, pEntry, NULL))
670 {
671 if (!fWinVerifyTrust)
672 do
673 pEntry->pNextTodoWvt = g_pVerifierCacheTodoWvt;
674 while (!ASMAtomicCmpXchgPtr(&g_pVerifierCacheTodoWvt, pEntry, pEntry->pNextTodoWvt));
675
676 SUP_DPRINTF(("supR3HardenedWinVerifyCacheInsert: %ls\n", pUniStr->Buffer));
677 return;
678 }
679
680 PVERIFIERCACHEENTRY pOther = *ppEntry;
681 if (!pOther)
682 continue;
683 if ( pOther->uHash == pEntry->uHash
684 && pOther->cbPath == pEntry->cbPath
685 && supR3HardenedWinVerifyCacheIsMatch(pOther->wszPath, pEntry->wszPath, pEntry->cbPath / sizeof(RTUTF16)))
686 break;
687 ppEntry = &pOther->pNext;
688 }
689
690 /* Duplicate entry (may happen due to races). */
691 RTMemFree(pEntry);
692 }
693 NtClose(hFile);
694}
695
696
697/**
698 * Looks up an entry in the verifier hash table.
699 *
700 * @return Pointer to the entry on if found, NULL if not.
701 * @param pUniStr The full path of the image.
702 * @param hFile The file handle.
703 */
704static PVERIFIERCACHEENTRY supR3HardenedWinVerifyCacheLookup(PCUNICODE_STRING pUniStr, HANDLE hFile)
705{
706 PRTUTF16 const pwszPath = pUniStr->Buffer;
707 uint16_t const cbPath = pUniStr->Length;
708 uint32_t uHash = supR3HardenedWinVerifyCacheHashPath(pUniStr);
709 uint32_t iHashTab = uHash % RT_ELEMENTS(g_apVerifierCache);
710 PVERIFIERCACHEENTRY pCur = g_apVerifierCache[iHashTab];
711 while (pCur)
712 {
713 if ( pCur->uHash == uHash
714 && pCur->cbPath == cbPath
715 && supR3HardenedWinVerifyCacheIsMatch(pCur->wszPath, pwszPath, cbPath / sizeof(RTUTF16)))
716 {
717
718 if (!pCur->fIndexNumberValid)
719 return pCur;
720 LARGE_INTEGER IndexNumber;
721 bool fIndexNumberValid = supR3HardenedWinVerifyCacheGetIndexNumber(hFile, &IndexNumber);
722 if ( fIndexNumberValid
723 && IndexNumber.QuadPart == pCur->IndexNumber.QuadPart)
724 return pCur;
725#ifdef DEBUG_bird
726 __debugbreak();
727#endif
728 }
729 pCur = pCur->pNext;
730 }
731 return NULL;
732}
733
734
735/**
736 * Looks up an import DLL in the verifier hash table.
737 *
738 * @return Pointer to the entry on if found, NULL if not.
739 * @param pawcDir The directory name.
740 * @param cwcDir The length of the directory name.
741 * @param pszName The import name (UTF-8).
742 */
743static PVERIFIERCACHEENTRY supR3HardenedWinVerifyCacheLookupImport(PCRTUTF16 pawcDir, uint32_t cwcDir, const char *pszName)
744{
745 uint32_t uHash = supR3HardenedWinVerifyCacheHashDirAndFile(pawcDir, cwcDir, pszName);
746 uint32_t iHashTab = uHash % RT_ELEMENTS(g_apVerifierCache);
747 uint32_t const cbPath = (uint32_t)((cwcDir + 1 + strlen(pszName)) * sizeof(RTUTF16));
748 PVERIFIERCACHEENTRY pCur = g_apVerifierCache[iHashTab];
749 while (pCur)
750 {
751 if ( pCur->uHash == uHash
752 && pCur->cbPath == cbPath)
753 {
754 if (supR3HardenedWinVerifyCacheIsMatch(pCur->wszPath, pawcDir, cwcDir))
755 {
756 if (pCur->wszPath[cwcDir] == '\\' || pCur->wszPath[cwcDir] == '/')
757 {
758 if (RTUtf16ICmpAscii(&pCur->wszPath[cwcDir + 1], pszName))
759 {
760 return pCur;
761 }
762 }
763 }
764 }
765
766 pCur = pCur->pNext;
767 }
768 return NULL;
769}
770
771
772/**
773 * Schedules the import DLLs for verification and entry into the cache.
774 *
775 * @param hLdrMod The loader module which imports should be
776 * scheduled for verification.
777 * @param pwszName The full NT path of the module.
778 */
779DECLHIDDEN(void) supR3HardenedWinVerifyCacheScheduleImports(RTLDRMOD hLdrMod, PCRTUTF16 pwszName)
780{
781 /*
782 * Any imports?
783 */
784 uint32_t cImports;
785 int rc = RTLdrQueryPropEx(hLdrMod, RTLDRPROP_IMPORT_COUNT, NULL /*pvBits*/, &cImports, sizeof(cImports), NULL);
786 if (RT_SUCCESS(rc))
787 {
788 if (cImports)
789 {
790 /*
791 * Figure out the DLL directory from pwszName.
792 */
793 PCRTUTF16 pawcDir = pwszName;
794 uint32_t cwcDir = 0;
795 uint32_t i = 0;
796 RTUTF16 wc;
797 while ((wc = pawcDir[i++]) != '\0')
798 if ((wc == '\\' || wc == '/' || wc == ':') && cwcDir + 2 != i)
799 cwcDir = i - 1;
800 if ( g_System32NtPath.UniStr.Length / sizeof(WCHAR) == cwcDir
801 && supR3HardenedWinVerifyCacheIsMatch(pawcDir, g_System32NtPath.UniStr.Buffer, cwcDir))
802 pawcDir = NULL;
803
804 /*
805 * Enumerate the imports.
806 */
807 for (i = 0; i < cImports; i++)
808 {
809 union
810 {
811 char szName[256];
812 uint32_t iImport;
813 } uBuf;
814 uBuf.iImport = i;
815 rc = RTLdrQueryPropEx(hLdrMod, RTLDRPROP_IMPORT_MODULE, NULL /*pvBits*/, &uBuf, sizeof(uBuf), NULL);
816 if (RT_SUCCESS(rc))
817 {
818 /*
819 * Skip kernel32, ntdll and API set stuff.
820 */
821 RTStrToLower(uBuf.szName);
822 if ( RTStrCmp(uBuf.szName, "kernel32.dll") == 0
823 || RTStrCmp(uBuf.szName, "kernelbase.dll") == 0
824 || RTStrCmp(uBuf.szName, "ntdll.dll") == 0
825 || RTStrNCmp(uBuf.szName, RT_STR_TUPLE("api-ms-win-")) == 0
826 || RTStrNCmp(uBuf.szName, RT_STR_TUPLE("ext-ms-win-")) == 0
827 )
828 {
829 continue;
830 }
831
832 /*
833 * Skip to the next one if it's already in the cache.
834 */
835 if (supR3HardenedWinVerifyCacheLookupImport(g_System32NtPath.UniStr.Buffer,
836 g_System32NtPath.UniStr.Length / sizeof(WCHAR),
837 uBuf.szName) != NULL)
838 {
839 SUP_DPRINTF(("supR3HardenedWinVerifyCacheScheduleImports: '%s' cached for system32\n", uBuf.szName));
840 continue;
841 }
842 if (supR3HardenedWinVerifyCacheLookupImport(g_SupLibHardenedAppBinNtPath.UniStr.Buffer,
843 g_SupLibHardenedAppBinNtPath.UniStr.Length / sizeof(CHAR),
844 uBuf.szName) != NULL)
845 {
846 SUP_DPRINTF(("supR3HardenedWinVerifyCacheScheduleImports: '%s' cached for appdir\n", uBuf.szName));
847 continue;
848 }
849 if (pawcDir && supR3HardenedWinVerifyCacheLookupImport(pawcDir, cwcDir, uBuf.szName) != NULL)
850 {
851 SUP_DPRINTF(("supR3HardenedWinVerifyCacheScheduleImports: '%s' cached for dll dir\n", uBuf.szName));
852 continue;
853 }
854
855 /* We could skip already scheduled modules, but that'll require serialization and extra work... */
856
857 /*
858 * Add it to the todo list.
859 */
860 SUP_DPRINTF(("supR3HardenedWinVerifyCacheScheduleImports: Import todo: #%u '%s'.\n", i, uBuf.szName));
861 uint32_t cbName = (uint32_t)strlen(uBuf.szName) + 1;
862 uint32_t cbNameAligned = RT_ALIGN_32(cbName, sizeof(RTUTF16));
863 uint32_t cbNeeded = RT_OFFSETOF(VERIFIERCACHEIMPORT, szName[cbNameAligned])
864 + (pawcDir ? (cwcDir + 1) * sizeof(RTUTF16) : 0);
865 PVERIFIERCACHEIMPORT pImport = (PVERIFIERCACHEIMPORT)RTMemAllocZ(cbNeeded);
866 if (pImport)
867 {
868 /* Init it. */
869 memcpy(pImport->szName, uBuf.szName, cbName);
870 if (!pawcDir)
871 {
872 pImport->cwcAltSearchDir = 0;
873 pImport->pwszAltSearchDir = NULL;
874 }
875 else
876 {
877 pImport->cwcAltSearchDir = cwcDir;
878 pImport->pwszAltSearchDir = (PRTUTF16)&pImport->szName[cbNameAligned];
879 memcpy(pImport->pwszAltSearchDir, pawcDir, cwcDir * sizeof(RTUTF16));
880 pImport->pwszAltSearchDir[cwcDir] = '\0';
881 }
882
883 /* Insert it. */
884 do
885 pImport->pNext = g_pVerifierCacheTodoImports;
886 while (!ASMAtomicCmpXchgPtr(&g_pVerifierCacheTodoImports, pImport, pImport->pNext));
887 }
888 }
889 else
890 SUP_DPRINTF(("RTLDRPROP_IMPORT_MODULE failed with rc=%Rrc i=%#x on '%ls'\n", rc, i, pwszName));
891 }
892 }
893 else
894 SUP_DPRINTF(("'%ls' has no imports\n", pwszName));
895 }
896 else
897 SUP_DPRINTF(("RTLDRPROP_IMPORT_COUNT failed with rc=%Rrc on '%ls'\n", rc, pwszName));
898}
899
900
901/**
902 * Processes the list of import todos.
903 */
904static void supR3HardenedWinVerifyCacheProcessImportTodos(void)
905{
906 /*
907 * Work until we've got nothing more todo.
908 */
909 for (;;)
910 {
911 PVERIFIERCACHEIMPORT pTodo = ASMAtomicXchgPtrT(&g_pVerifierCacheTodoImports, NULL, PVERIFIERCACHEIMPORT);
912 if (!pTodo)
913 break;
914 do
915 {
916 PVERIFIERCACHEIMPORT pCur = pTodo;
917 pTodo = pTodo->pNext;
918
919 /*
920 * Not in the cached already?
921 */
922 if ( !supR3HardenedWinVerifyCacheLookupImport(g_System32NtPath.UniStr.Buffer,
923 g_System32NtPath.UniStr.Length / sizeof(WCHAR),
924 pCur->szName)
925 && !supR3HardenedWinVerifyCacheLookupImport(g_SupLibHardenedAppBinNtPath.UniStr.Buffer,
926 g_SupLibHardenedAppBinNtPath.UniStr.Length / sizeof(WCHAR),
927 pCur->szName)
928 && ( pCur->cwcAltSearchDir == 0
929 || !supR3HardenedWinVerifyCacheLookupImport(pCur->pwszAltSearchDir, pCur->cwcAltSearchDir, pCur->szName)) )
930 {
931 /*
932 * Try locate the imported DLL and open it.
933 */
934 SUP_DPRINTF(("supR3HardenedWinVerifyCacheProcessImportTodos: Processing '%s'...\n", pCur->szName));
935
936 NTSTATUS rcNt;
937 NTSTATUS rcNtRedir = 0x22222222;
938 HANDLE hFile = INVALID_HANDLE_VALUE;
939 RTUTF16 wszPath[260 + 260]; /* Assumes we've limited the import name length to 256. */
940 AssertCompile(sizeof(wszPath) > sizeof(g_System32NtPath));
941
942 /*
943 * Check for DLL isolation / redirection / mapping.
944 */
945 size_t cwcName = 260;
946 PRTUTF16 pwszName = &wszPath[0];
947 int rc = RTStrToUtf16Ex(pCur->szName, RTSTR_MAX, &pwszName, cwcName, &cwcName);
948 if (RT_SUCCESS(rc))
949 {
950 UNICODE_STRING UniStrName;
951 UniStrName.Buffer = wszPath;
952 UniStrName.Length = (USHORT)cwcName * sizeof(WCHAR);
953 UniStrName.MaximumLength = UniStrName.Length + sizeof(WCHAR);
954
955 UNICODE_STRING UniStrStatic;
956 UniStrStatic.Buffer = &wszPath[cwcName + 1];
957 UniStrStatic.Length = 0;
958 UniStrStatic.MaximumLength = (USHORT)(sizeof(wszPath) - cwcName * sizeof(WCHAR) - sizeof(WCHAR));
959
960 static UNICODE_STRING const s_DefaultSuffix = RTNT_CONSTANT_UNISTR(L".dll");
961 UNICODE_STRING UniStrDynamic = { 0, 0, NULL };
962 PUNICODE_STRING pUniStrResult = NULL;
963
964 rcNtRedir = RtlDosApplyFileIsolationRedirection_Ustr(1 /*fFlags*/,
965 &UniStrName,
966 (PUNICODE_STRING)&s_DefaultSuffix,
967 &UniStrStatic,
968 &UniStrDynamic,
969 &pUniStrResult,
970 NULL /*pNewFlags*/,
971 NULL /*pcbFilename*/,
972 NULL /*pcbNeeded*/);
973 if (NT_SUCCESS(rcNtRedir))
974 {
975 IO_STATUS_BLOCK Ios = RTNT_IO_STATUS_BLOCK_INITIALIZER;
976 OBJECT_ATTRIBUTES ObjAttr;
977 InitializeObjectAttributes(&ObjAttr, pUniStrResult,
978 OBJ_CASE_INSENSITIVE, NULL /*hRootDir*/, NULL /*pSecDesc*/);
979 rcNt = NtCreateFile(&hFile,
980 FILE_READ_DATA | READ_CONTROL | SYNCHRONIZE,
981 &ObjAttr,
982 &Ios,
983 NULL /* Allocation Size*/,
984 FILE_ATTRIBUTE_NORMAL,
985 FILE_SHARE_READ,
986 FILE_OPEN,
987 FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT,
988 NULL /*EaBuffer*/,
989 0 /*EaLength*/);
990 if (NT_SUCCESS(rcNt))
991 rcNt = Ios.Status;
992 if (NT_SUCCESS(rcNt))
993 {
994 /* For accurate logging. */
995 size_t cwcCopy = RT_MIN(pUniStrResult->Length / sizeof(RTUTF16), RT_ELEMENTS(wszPath) - 1);
996 memcpy(wszPath, pUniStrResult->Buffer, cwcCopy * sizeof(RTUTF16));
997 wszPath[cwcCopy] = '\0';
998 }
999 else
1000 hFile = INVALID_HANDLE_VALUE;
1001 RtlFreeUnicodeString(&UniStrDynamic);
1002 }
1003 }
1004 else
1005 SUP_DPRINTF(("supR3HardenedWinVerifyCacheProcessImportTodos: RTStrToUtf16Ex #1 failed: %Rrc\n", rc));
1006
1007 /*
1008 * If not something that gets remapped, do the half normal searching we need.
1009 */
1010 if (hFile == INVALID_HANDLE_VALUE)
1011 {
1012 struct
1013 {
1014 PRTUTF16 pawcDir;
1015 uint32_t cwcDir;
1016 } Tmp, aDirs[] =
1017 {
1018 { g_System32NtPath.UniStr.Buffer, g_System32NtPath.UniStr.Length / sizeof(WCHAR) },
1019 { g_SupLibHardenedExeNtPath.UniStr.Buffer, g_SupLibHardenedAppBinNtPath.UniStr.Length / sizeof(WCHAR) },
1020 { pCur->pwszAltSearchDir, pCur->cwcAltSearchDir },
1021 };
1022
1023 /* Search System32 first, unless it's a 'V*' or 'm*' name, the latter for msvcrt. */
1024 if ( pCur->szName[0] == 'v'
1025 || pCur->szName[0] == 'V'
1026 || pCur->szName[0] == 'm'
1027 || pCur->szName[0] == 'M')
1028 {
1029 Tmp = aDirs[0];
1030 aDirs[0] = aDirs[1];
1031 aDirs[1] = Tmp;
1032 }
1033
1034 for (uint32_t i = 0; i < RT_ELEMENTS(aDirs); i++)
1035 {
1036 if (aDirs[i].pawcDir && aDirs[i].cwcDir && aDirs[i].cwcDir < RT_ELEMENTS(wszPath) / 3 * 2)
1037 {
1038 memcpy(wszPath, aDirs[i].pawcDir, aDirs[i].cwcDir * sizeof(RTUTF16));
1039 uint32_t cwc = aDirs[i].cwcDir;
1040 wszPath[cwc++] = '\\';
1041 cwcName = RT_ELEMENTS(wszPath) - cwc;
1042 pwszName = &wszPath[cwc];
1043 rc = RTStrToUtf16Ex(pCur->szName, RTSTR_MAX, &pwszName, cwcName, &cwcName);
1044 if (RT_SUCCESS(rc))
1045 {
1046 IO_STATUS_BLOCK Ios = RTNT_IO_STATUS_BLOCK_INITIALIZER;
1047 UNICODE_STRING NtName;
1048 NtName.Buffer = wszPath;
1049 NtName.Length = (USHORT)((cwc + cwcName) * sizeof(WCHAR));
1050 NtName.MaximumLength = NtName.Length + sizeof(WCHAR);
1051 OBJECT_ATTRIBUTES ObjAttr;
1052 InitializeObjectAttributes(&ObjAttr, &NtName, OBJ_CASE_INSENSITIVE, NULL /*hRootDir*/, NULL /*pSecDesc*/);
1053
1054 rcNt = NtCreateFile(&hFile,
1055 FILE_READ_DATA | READ_CONTROL | SYNCHRONIZE,
1056 &ObjAttr,
1057 &Ios,
1058 NULL /* Allocation Size*/,
1059 FILE_ATTRIBUTE_NORMAL,
1060 FILE_SHARE_READ,
1061 FILE_OPEN,
1062 FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT,
1063 NULL /*EaBuffer*/,
1064 0 /*EaLength*/);
1065 if (NT_SUCCESS(rcNt))
1066 rcNt = Ios.Status;
1067 if (NT_SUCCESS(rcNt))
1068 break;
1069 hFile = INVALID_HANDLE_VALUE;
1070 }
1071 else
1072 SUP_DPRINTF(("supR3HardenedWinVerifyCacheProcessImportTodos: RTStrToUtf16Ex #2 failed: %Rrc\n", rc));
1073 }
1074 }
1075 }
1076
1077 /*
1078 * If we successfully opened it, verify it and cache the result.
1079 */
1080 if (hFile != INVALID_HANDLE_VALUE)
1081 {
1082 SUP_DPRINTF(("supR3HardenedWinVerifyCacheProcessImportTodos: '%s' -> '%ls' [rcNtRedir=%#x]\n",
1083 pCur->szName, wszPath, rcNtRedir));
1084
1085 ULONG fAccess = 0;
1086 ULONG fProtect = 0;
1087 bool fCallRealApi = false;
1088 rcNt = supR3HardenedScreenImage(hFile, true /*fImage*/, false /*fIgnoreArch*/, &fAccess, &fProtect,
1089 &fCallRealApi, "Imports", false /*fAvoidWinVerifyTrust*/, NULL /*pfQuiet*/);
1090 NtClose(hFile);
1091 }
1092 else
1093 SUP_DPRINTF(("supR3HardenedWinVerifyCacheProcessImportTodos: Failed to locate '%s'\n", pCur->szName));
1094 }
1095 else
1096 SUP_DPRINTF(("supR3HardenedWinVerifyCacheProcessImportTodos: '%s' is in the cache.\n", pCur->szName));
1097
1098 RTMemFree(pCur);
1099 } while (pTodo);
1100 }
1101}
1102
1103
1104/**
1105 * Processes the list of WinVerifyTrust todos.
1106 */
1107static void supR3HardenedWinVerifyCacheProcessWvtTodos(void)
1108{
1109 PVERIFIERCACHEENTRY pReschedule = NULL;
1110 PVERIFIERCACHEENTRY volatile *ppReschedLastNext = NULL;
1111
1112 /*
1113 * Work until we've got nothing more todo.
1114 */
1115 for (;;)
1116 {
1117 if (!supHardenedWinIsWinVerifyTrustCallable())
1118 break;
1119 PVERIFIERCACHEENTRY pTodo = ASMAtomicXchgPtrT(&g_pVerifierCacheTodoWvt, NULL, PVERIFIERCACHEENTRY);
1120 if (!pTodo)
1121 break;
1122 do
1123 {
1124 PVERIFIERCACHEENTRY pCur = pTodo;
1125 pTodo = pTodo->pNextTodoWvt;
1126 pCur->pNextTodoWvt = NULL;
1127
1128 if ( !pCur->fWinVerifyTrust
1129 && RT_SUCCESS(pCur->rc))
1130 {
1131 bool fWinVerifyTrust = false;
1132 int rc = supHardenedWinVerifyImageTrust(pCur->hFile, pCur->wszPath, pCur->fFlags, pCur->rc,
1133 &fWinVerifyTrust, NULL /* pErrInfo*/);
1134 if (RT_FAILURE(rc) || fWinVerifyTrust)
1135 {
1136 SUP_DPRINTF(("supR3HardenedWinVerifyCacheProcessWvtTodos: %d (was %d) fWinVerifyTrust=%d for '%ls'\n",
1137 rc, pCur->rc, fWinVerifyTrust, pCur->wszPath));
1138 pCur->fWinVerifyTrust = true;
1139 pCur->rc = rc;
1140 }
1141 else
1142 {
1143 /* Retry it at a later time. */
1144 SUP_DPRINTF(("supR3HardenedWinVerifyCacheProcessWvtTodos: %d (was %d) fWinVerifyTrust=%d for '%ls' [rescheduled]\n",
1145 rc, pCur->rc, fWinVerifyTrust, pCur->wszPath));
1146 if (!pReschedule)
1147 ppReschedLastNext = &pCur->pNextTodoWvt;
1148 pCur->pNextTodoWvt = pReschedule;
1149 }
1150 }
1151 /* else: already processed. */
1152 } while (pTodo);
1153 }
1154
1155 /*
1156 * Anything to reschedule.
1157 */
1158 if (pReschedule)
1159 {
1160 do
1161 *ppReschedLastNext = g_pVerifierCacheTodoWvt;
1162 while (!ASMAtomicCmpXchgPtr(&g_pVerifierCacheTodoWvt, pReschedule, *ppReschedLastNext));
1163 }
1164}
1165
1166
1167/**
1168 * Translates VBox status code (from supHardenedWinVerifyImageTrust) to an NT
1169 * status.
1170 *
1171 * @returns NT status.
1172 * @param rc VBox status code.
1173 */
1174static NTSTATUS supR3HardenedScreenImageCalcStatus(int rc)
1175{
1176 /* This seems to be what LdrLoadDll returns when loading a 32-bit DLL into
1177 a 64-bit process. At least here on windows 10 (2015-11-xx).
1178
1179 NtCreateSection probably returns something different, possibly a warning,
1180 we currently don't distinguish between the too, so we stick with the
1181 LdrLoadDll one as it's definitely an error.*/
1182 if (rc == VERR_LDR_ARCH_MISMATCH)
1183 return STATUS_INVALID_IMAGE_FORMAT;
1184
1185 return STATUS_TRUST_FAILURE;
1186}
1187
1188
1189/**
1190 * Screens an image file or file mapped with execute access.
1191 *
1192 * @returns NT status code.
1193 * @param hFile The file handle.
1194 * @param fImage Set if image file mapping being made
1195 * (NtCreateSection thing).
1196 * @param fIgnoreArch Using the DONT_RESOLVE_DLL_REFERENCES flag,
1197 * which also implies that DLL init / term code
1198 * isn't called, so the architecture should be
1199 * ignored.
1200 * @param pfAccess Pointer to the NtCreateSection access flags,
1201 * so we can modify them if necessary.
1202 * @param pfProtect Pointer to the NtCreateSection protection
1203 * flags, so we can modify them if necessary.
1204 * @param pfCallRealApi Whether it's ok to go on to the real API.
1205 * @param pszCaller Who is calling (for debugging / logging).
1206 * @param fAvoidWinVerifyTrust Whether we should avoid WinVerifyTrust.
1207 * @param pfQuiet Where to return whether to be quiet about
1208 * this image in the log (i.e. we've seen it
1209 * lots of times already). Optional.
1210 */
1211static NTSTATUS supR3HardenedScreenImage(HANDLE hFile, bool fImage, bool fIgnoreArch, PULONG pfAccess, PULONG pfProtect,
1212 bool *pfCallRealApi, const char *pszCaller, bool fAvoidWinVerifyTrust, bool *pfQuiet)
1213{
1214 *pfCallRealApi = false;
1215 if (pfQuiet)
1216 *pfQuiet = false;
1217
1218 /*
1219 * Query the name of the file, making sure to zero terminator the
1220 * string. (2nd half of buffer is used for error info, see below.)
1221 */
1222 union
1223 {
1224 UNICODE_STRING UniStr;
1225 uint8_t abBuffer[sizeof(UNICODE_STRING) + 2048 * sizeof(WCHAR)];
1226 } uBuf;
1227 RT_ZERO(uBuf);
1228 ULONG cbNameBuf;
1229 NTSTATUS rcNt = NtQueryObject(hFile, ObjectNameInformation, &uBuf, sizeof(uBuf) - sizeof(WCHAR) - 128, &cbNameBuf);
1230 if (!NT_SUCCESS(rcNt))
1231 {
1232 supR3HardenedError(VINF_SUCCESS, false,
1233 "supR3HardenedScreenImage/%s: NtQueryObject -> %#x (fImage=%d fProtect=%#x fAccess=%#x)\n",
1234 pszCaller, fImage, *pfProtect, *pfAccess);
1235 return rcNt;
1236 }
1237
1238 if (!RTNtPathFindPossible8dot3Name(uBuf.UniStr.Buffer))
1239 cbNameBuf += sizeof(WCHAR);
1240 else
1241 {
1242 uBuf.UniStr.MaximumLength = sizeof(uBuf) - 128;
1243 RTNtPathExpand8dot3Path(&uBuf.UniStr, true /*fPathOnly*/);
1244 cbNameBuf = (uintptr_t)uBuf.UniStr.Buffer + uBuf.UniStr.Length + sizeof(WCHAR) - (uintptr_t)&uBuf.abBuffer[0];
1245 }
1246
1247 /*
1248 * Check the cache.
1249 */
1250 PVERIFIERCACHEENTRY pCacheHit = supR3HardenedWinVerifyCacheLookup(&uBuf.UniStr, hFile);
1251 if (pCacheHit)
1252 {
1253 /* Do hit accounting and figure whether we need to be quiet or not. */
1254 uint32_t cHits = ASMAtomicIncU32(&pCacheHit->cHits);
1255 bool const fQuiet = cHits >= 8 && !RT_IS_POWER_OF_TWO(cHits);
1256 if (pfQuiet)
1257 *pfQuiet = fQuiet;
1258
1259 /* If we haven't done the WinVerifyTrust thing, do it if we can. */
1260 if ( !pCacheHit->fWinVerifyTrust
1261 && RT_SUCCESS(pCacheHit->rc)
1262 && supHardenedWinIsWinVerifyTrustCallable() )
1263 {
1264 if (!fAvoidWinVerifyTrust)
1265 {
1266 SUP_DPRINTF(("supR3HardenedScreenImage/%s: cache hit (%Rrc) on %ls [redoing WinVerifyTrust]\n",
1267 pszCaller, pCacheHit->rc, pCacheHit->wszPath));
1268
1269 bool fWinVerifyTrust = false;
1270 int rc = supHardenedWinVerifyImageTrust(pCacheHit->hFile, pCacheHit->wszPath, pCacheHit->fFlags, pCacheHit->rc,
1271 &fWinVerifyTrust, NULL /* pErrInfo*/);
1272 if (RT_FAILURE(rc) || fWinVerifyTrust)
1273 {
1274 SUP_DPRINTF(("supR3HardenedScreenImage/%s: %d (was %d) fWinVerifyTrust=%d for '%ls'\n",
1275 pszCaller, rc, pCacheHit->rc, fWinVerifyTrust, pCacheHit->wszPath));
1276 pCacheHit->fWinVerifyTrust = true;
1277 pCacheHit->rc = rc;
1278 }
1279 else
1280 SUP_DPRINTF(("supR3HardenedScreenImage/%s: WinVerifyTrust not available, rescheduling %ls\n",
1281 pszCaller, pCacheHit->wszPath));
1282 }
1283 else
1284 SUP_DPRINTF(("supR3HardenedScreenImage/%s: cache hit (%Rrc) on %ls [avoiding WinVerifyTrust]\n",
1285 pszCaller, pCacheHit->rc, pCacheHit->wszPath));
1286 }
1287 else if (!fQuiet || !pCacheHit->fWinVerifyTrust)
1288 SUP_DPRINTF(("supR3HardenedScreenImage/%s: cache hit (%Rrc) on %ls%s\n",
1289 pszCaller, pCacheHit->rc, pCacheHit->wszPath, pCacheHit->fWinVerifyTrust ? "" : " [lacks WinVerifyTrust]"));
1290
1291 /* Return the cached value. */
1292 if (RT_SUCCESS(pCacheHit->rc))
1293 {
1294 *pfCallRealApi = true;
1295 return STATUS_SUCCESS;
1296 }
1297
1298 if (!fQuiet)
1299 supR3HardenedError(VINF_SUCCESS, false,
1300 "supR3HardenedScreenImage/%s: cached rc=%Rrc fImage=%d fProtect=%#x fAccess=%#x cHits=%u %ls\n",
1301 pszCaller, pCacheHit->rc, fImage, *pfProtect, *pfAccess, cHits, uBuf.UniStr.Buffer);
1302 return supR3HardenedScreenImageCalcStatus(pCacheHit->rc);
1303 }
1304
1305 /*
1306 * On XP the loader might hand us handles with just FILE_EXECUTE and
1307 * SYNCHRONIZE, the means reading will fail later on. Also, we need
1308 * READ_CONTROL access to check the file ownership later on, and non
1309 * of the OS versions seems be giving us that. So, in effect we
1310 * more or less always reopen the file here.
1311 */
1312 HANDLE hMyFile = NULL;
1313 rcNt = NtDuplicateObject(NtCurrentProcess(), hFile, NtCurrentProcess(),
1314 &hMyFile,
1315 FILE_READ_DATA | READ_CONTROL | SYNCHRONIZE,
1316 0 /* Handle attributes*/, 0 /* Options */);
1317 if (!NT_SUCCESS(rcNt))
1318 {
1319 if (rcNt == STATUS_ACCESS_DENIED)
1320 {
1321 IO_STATUS_BLOCK Ios = RTNT_IO_STATUS_BLOCK_INITIALIZER;
1322 OBJECT_ATTRIBUTES ObjAttr;
1323 InitializeObjectAttributes(&ObjAttr, &uBuf.UniStr, OBJ_CASE_INSENSITIVE, NULL /*hRootDir*/, NULL /*pSecDesc*/);
1324
1325 rcNt = NtCreateFile(&hMyFile,
1326 FILE_READ_DATA | READ_CONTROL | SYNCHRONIZE,
1327 &ObjAttr,
1328 &Ios,
1329 NULL /* Allocation Size*/,
1330 FILE_ATTRIBUTE_NORMAL,
1331 FILE_SHARE_READ,
1332 FILE_OPEN,
1333 FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT,
1334 NULL /*EaBuffer*/,
1335 0 /*EaLength*/);
1336 if (NT_SUCCESS(rcNt))
1337 rcNt = Ios.Status;
1338 if (!NT_SUCCESS(rcNt))
1339 {
1340 supR3HardenedError(VINF_SUCCESS, false,
1341 "supR3HardenedScreenImage/%s: Failed to duplicate and open the file: rcNt=%#x hFile=%p %ls\n",
1342 pszCaller, rcNt, hFile, uBuf.UniStr.Buffer);
1343 return rcNt;
1344 }
1345
1346 /* Check that we've got the same file. */
1347 LARGE_INTEGER idMyFile, idInFile;
1348 bool fMyValid = supR3HardenedWinVerifyCacheGetIndexNumber(hMyFile, &idMyFile);
1349 bool fInValid = supR3HardenedWinVerifyCacheGetIndexNumber(hFile, &idInFile);
1350 if ( fMyValid
1351 && ( fMyValid != fInValid
1352 || idMyFile.QuadPart != idInFile.QuadPart))
1353 {
1354 supR3HardenedError(VINF_SUCCESS, false,
1355 "supR3HardenedScreenImage/%s: Re-opened has different ID that input: %#llx vx %#llx (%ls)\n",
1356 pszCaller, rcNt, idMyFile.QuadPart, idInFile.QuadPart, uBuf.UniStr.Buffer);
1357 NtClose(hMyFile);
1358 return STATUS_TRUST_FAILURE;
1359 }
1360 }
1361 else
1362 {
1363 SUP_DPRINTF(("supR3HardenedScreenImage/%s: NtDuplicateObject -> %#x\n", pszCaller, rcNt));
1364#ifdef DEBUG
1365
1366 supR3HardenedError(VINF_SUCCESS, false,
1367 "supR3HardenedScreenImage/%s: NtDuplicateObject(,%#x,) failed: %#x\n", pszCaller, hFile, rcNt);
1368#endif
1369 hMyFile = hFile;
1370 }
1371 }
1372
1373 /*
1374 * Special Kludge for Windows XP and W2K3 and their stupid attempts
1375 * at mapping a hidden XML file called c:\Windows\WindowsShell.Manifest
1376 * with executable access. The image bit isn't set, fortunately.
1377 */
1378 if ( !fImage
1379 && uBuf.UniStr.Length > g_System32NtPath.UniStr.Length - sizeof(L"System32") + sizeof(WCHAR)
1380 && memcmp(uBuf.UniStr.Buffer, g_System32NtPath.UniStr.Buffer,
1381 g_System32NtPath.UniStr.Length - sizeof(L"System32") + sizeof(WCHAR)) == 0)
1382 {
1383 PRTUTF16 pwszName = &uBuf.UniStr.Buffer[(g_System32NtPath.UniStr.Length - sizeof(L"System32") + sizeof(WCHAR)) / sizeof(WCHAR)];
1384 if (RTUtf16ICmpAscii(pwszName, "WindowsShell.Manifest") == 0)
1385 {
1386 /*
1387 * Drop all executable access to the mapping and let it continue.
1388 */
1389 SUP_DPRINTF(("supR3HardenedScreenImage/%s: Applying the drop-exec-kludge for '%ls'\n", pszCaller, uBuf.UniStr.Buffer));
1390 if (*pfAccess & SECTION_MAP_EXECUTE)
1391 *pfAccess = (*pfAccess & ~SECTION_MAP_EXECUTE) | SECTION_MAP_READ;
1392 if (*pfProtect & PAGE_EXECUTE)
1393 *pfProtect = (*pfProtect & ~PAGE_EXECUTE) | PAGE_READONLY;
1394 *pfProtect = (*pfProtect & ~UINT32_C(0xf0)) | ((*pfProtect & UINT32_C(0xe0)) >> 4);
1395 if (hMyFile != hFile)
1396 NtClose(hMyFile);
1397 *pfCallRealApi = true;
1398 return STATUS_SUCCESS;
1399 }
1400 }
1401
1402#ifndef VBOX_PERMIT_EVEN_MORE
1403 /*
1404 * Check the path. We don't allow DLLs to be loaded from just anywhere:
1405 * 1. System32 - normal code or cat signing, owner TrustedInstaller.
1406 * 2. WinSxS - normal code or cat signing, owner TrustedInstaller.
1407 * 3. VirtualBox - kernel code signing and integrity checks.
1408 * 4. AppPatchDir - normal code or cat signing, owner TrustedInstaller.
1409 * 5. Program Files - normal code or cat signing, owner TrustedInstaller.
1410 * 6. Common Files - normal code or cat signing, owner TrustedInstaller.
1411 * 7. x86 variations of 4 & 5 - ditto.
1412 */
1413 uint32_t fFlags = 0;
1414 if (supHardViUniStrPathStartsWithUniStr(&uBuf.UniStr, &g_System32NtPath.UniStr, true /*fCheckSlash*/))
1415 fFlags |= SUPHNTVI_F_ALLOW_CAT_FILE_VERIFICATION | SUPHNTVI_F_TRUSTED_INSTALLER_OWNER;
1416 else if (supHardViUniStrPathStartsWithUniStr(&uBuf.UniStr, &g_WinSxSNtPath.UniStr, true /*fCheckSlash*/))
1417 fFlags |= SUPHNTVI_F_ALLOW_CAT_FILE_VERIFICATION | SUPHNTVI_F_TRUSTED_INSTALLER_OWNER;
1418 else if (supHardViUniStrPathStartsWithUniStr(&uBuf.UniStr, &g_SupLibHardenedAppBinNtPath.UniStr, true /*fCheckSlash*/))
1419 fFlags |= SUPHNTVI_F_REQUIRE_KERNEL_CODE_SIGNING | SUPHNTVI_F_REQUIRE_SIGNATURE_ENFORCEMENT;
1420# ifdef VBOX_PERMIT_MORE
1421 else if (supHardViIsAppPatchDir(uBuf.UniStr.Buffer, uBuf.UniStr.Length / sizeof(WCHAR)))
1422 fFlags |= SUPHNTVI_F_ALLOW_CAT_FILE_VERIFICATION | SUPHNTVI_F_TRUSTED_INSTALLER_OWNER;
1423 else if (supHardViUniStrPathStartsWithUniStr(&uBuf.UniStr, &g_ProgramFilesNtPath.UniStr, true /*fCheckSlash*/))
1424 fFlags |= SUPHNTVI_F_ALLOW_CAT_FILE_VERIFICATION | SUPHNTVI_F_TRUSTED_INSTALLER_OWNER;
1425 else if (supHardViUniStrPathStartsWithUniStr(&uBuf.UniStr, &g_CommonFilesNtPath.UniStr, true /*fCheckSlash*/))
1426 fFlags |= SUPHNTVI_F_ALLOW_CAT_FILE_VERIFICATION | SUPHNTVI_F_TRUSTED_INSTALLER_OWNER;
1427# ifdef RT_ARCH_AMD64
1428 else if (supHardViUniStrPathStartsWithUniStr(&uBuf.UniStr, &g_ProgramFilesX86NtPath.UniStr, true /*fCheckSlash*/))
1429 fFlags |= SUPHNTVI_F_ALLOW_CAT_FILE_VERIFICATION | SUPHNTVI_F_TRUSTED_INSTALLER_OWNER;
1430 else if (supHardViUniStrPathStartsWithUniStr(&uBuf.UniStr, &g_CommonFilesX86NtPath.UniStr, true /*fCheckSlash*/))
1431 fFlags |= SUPHNTVI_F_ALLOW_CAT_FILE_VERIFICATION | SUPHNTVI_F_TRUSTED_INSTALLER_OWNER;
1432# endif
1433# endif
1434# ifdef VBOX_PERMIT_VISUAL_STUDIO_PROFILING
1435 /* Hack to allow profiling our code with Visual Studio. */
1436 else if ( uBuf.UniStr.Length > sizeof(L"\\SamplingRuntime.dll")
1437 && memcmp(uBuf.UniStr.Buffer + (uBuf.UniStr.Length - sizeof(L"\\SamplingRuntime.dll") + sizeof(WCHAR)) / sizeof(WCHAR),
1438 L"\\SamplingRuntime.dll", sizeof(L"\\SamplingRuntime.dll") - sizeof(WCHAR)) == 0 )
1439 {
1440 if (hMyFile != hFile)
1441 NtClose(hMyFile);
1442 *pfCallRealApi = true;
1443 return STATUS_SUCCESS;
1444 }
1445# endif
1446 else
1447 {
1448 supR3HardenedError(VINF_SUCCESS, false,
1449 "supR3HardenedScreenImage/%s: Not a trusted location: '%ls' (fImage=%d fProtect=%#x fAccess=%#x)\n",
1450 pszCaller, uBuf.UniStr.Buffer, fImage, *pfAccess, *pfProtect);
1451 if (hMyFile != hFile)
1452 NtClose(hMyFile);
1453 return STATUS_TRUST_FAILURE;
1454 }
1455
1456#else /* VBOX_PERMIT_EVEN_MORE */
1457 /*
1458 * Require trusted installer + some kind of signature on everything, except
1459 * for the VBox bits where we require kernel code signing and special
1460 * integrity checks.
1461 */
1462 uint32_t fFlags = 0;
1463 if (supHardViUniStrPathStartsWithUniStr(&uBuf.UniStr, &g_SupLibHardenedAppBinNtPath.UniStr, true /*fCheckSlash*/))
1464 fFlags |= SUPHNTVI_F_REQUIRE_KERNEL_CODE_SIGNING | SUPHNTVI_F_REQUIRE_SIGNATURE_ENFORCEMENT;
1465 else
1466 fFlags |= SUPHNTVI_F_ALLOW_CAT_FILE_VERIFICATION | SUPHNTVI_F_TRUSTED_INSTALLER_OWNER;
1467#endif /* VBOX_PERMIT_EVEN_MORE */
1468
1469 /*
1470 * Do the verification. For better error message we borrow what's
1471 * left of the path buffer for an RTERRINFO buffer.
1472 */
1473 if (fIgnoreArch)
1474 fFlags |= SUPHNTVI_F_IGNORE_ARCHITECTURE;
1475 RTERRINFO ErrInfo;
1476 RTErrInfoInit(&ErrInfo, (char *)&uBuf.abBuffer[cbNameBuf], sizeof(uBuf) - cbNameBuf);
1477
1478 int rc;
1479 bool fWinVerifyTrust = false;
1480 rc = supHardenedWinVerifyImageByHandle(hMyFile, uBuf.UniStr.Buffer, fFlags, fAvoidWinVerifyTrust, &fWinVerifyTrust, &ErrInfo);
1481 if (RT_FAILURE(rc))
1482 {
1483 supR3HardenedError(VINF_SUCCESS, false,
1484 "supR3HardenedScreenImage/%s: rc=%Rrc fImage=%d fProtect=%#x fAccess=%#x %ls: %s\n",
1485 pszCaller, rc, fImage, *pfAccess, *pfProtect, uBuf.UniStr.Buffer, ErrInfo.pszMsg);
1486 if (hMyFile != hFile)
1487 supR3HardenedWinVerifyCacheInsert(&uBuf.UniStr, hMyFile, rc, fWinVerifyTrust, fFlags);
1488 return supR3HardenedScreenImageCalcStatus(rc);
1489 }
1490
1491 /*
1492 * Insert into the cache.
1493 */
1494 if (hMyFile != hFile)
1495 supR3HardenedWinVerifyCacheInsert(&uBuf.UniStr, hMyFile, rc, fWinVerifyTrust, fFlags);
1496
1497 *pfCallRealApi = true;
1498 return STATUS_SUCCESS;
1499}
1500
1501
1502/**
1503 * Preloads a file into the verify cache if possible.
1504 *
1505 * This is used to avoid known cyclic LoadLibrary issues with WinVerifyTrust.
1506 *
1507 * @param pwszName The name of the DLL to verify.
1508 */
1509DECLHIDDEN(void) supR3HardenedWinVerifyCachePreload(PCRTUTF16 pwszName)
1510{
1511 HANDLE hFile = RTNT_INVALID_HANDLE_VALUE;
1512 IO_STATUS_BLOCK Ios = RTNT_IO_STATUS_BLOCK_INITIALIZER;
1513
1514 UNICODE_STRING UniStr;
1515 UniStr.Buffer = (PWCHAR)pwszName;
1516 UniStr.Length = (USHORT)(RTUtf16Len(pwszName) * sizeof(WCHAR));
1517 UniStr.MaximumLength = UniStr.Length + sizeof(WCHAR);
1518
1519 OBJECT_ATTRIBUTES ObjAttr;
1520 InitializeObjectAttributes(&ObjAttr, &UniStr, OBJ_CASE_INSENSITIVE, NULL /*hRootDir*/, NULL /*pSecDesc*/);
1521
1522 NTSTATUS rcNt = NtCreateFile(&hFile,
1523 FILE_READ_DATA | READ_CONTROL | SYNCHRONIZE,
1524 &ObjAttr,
1525 &Ios,
1526 NULL /* Allocation Size*/,
1527 FILE_ATTRIBUTE_NORMAL,
1528 FILE_SHARE_READ,
1529 FILE_OPEN,
1530 FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT,
1531 NULL /*EaBuffer*/,
1532 0 /*EaLength*/);
1533 if (NT_SUCCESS(rcNt))
1534 rcNt = Ios.Status;
1535 if (!NT_SUCCESS(rcNt))
1536 {
1537 SUP_DPRINTF(("supR3HardenedWinVerifyCachePreload: Error %#x opening '%ls'.\n", rcNt, pwszName));
1538 return;
1539 }
1540
1541 ULONG fAccess = 0;
1542 ULONG fProtect = 0;
1543 bool fCallRealApi;
1544 //SUP_DPRINTF(("supR3HardenedWinVerifyCachePreload: scanning %ls\n", pwszName));
1545 supR3HardenedScreenImage(hFile, false, false /*fIgnoreArch*/, &fAccess, &fProtect, &fCallRealApi, "preload",
1546 false /*fAvoidWinVerifyTrust*/, NULL /*pfQuiet*/);
1547 //SUP_DPRINTF(("supR3HardenedWinVerifyCachePreload: done %ls\n", pwszName));
1548
1549 NtClose(hFile);
1550}
1551
1552
1553
1554/**
1555 * Hook that monitors NtCreateSection calls.
1556 *
1557 * @returns NT status code.
1558 * @param phSection Where to return the section handle.
1559 * @param fAccess The desired access.
1560 * @param pObjAttribs The object attributes (optional).
1561 * @param pcbSection The section size (optional).
1562 * @param fProtect The max section protection.
1563 * @param fAttribs The section attributes.
1564 * @param hFile The file to create a section from (optional).
1565 */
1566static NTSTATUS NTAPI
1567supR3HardenedMonitor_NtCreateSection(PHANDLE phSection, ACCESS_MASK fAccess, POBJECT_ATTRIBUTES pObjAttribs,
1568 PLARGE_INTEGER pcbSection, ULONG fProtect, ULONG fAttribs, HANDLE hFile)
1569{
1570 bool fNeedUncChecking = false;
1571 if ( hFile != NULL
1572 && hFile != INVALID_HANDLE_VALUE)
1573 {
1574 bool const fImage = RT_BOOL(fAttribs & (SEC_IMAGE | SEC_PROTECTED_IMAGE));
1575 bool const fExecMap = RT_BOOL(fAccess & SECTION_MAP_EXECUTE);
1576 bool const fExecProt = RT_BOOL(fProtect & (PAGE_EXECUTE | PAGE_EXECUTE_READ | PAGE_EXECUTE_WRITECOPY
1577 | PAGE_EXECUTE_READWRITE));
1578 if (fImage || fExecMap || fExecProt)
1579 {
1580 fNeedUncChecking = true;
1581 DWORD dwSavedLastError = RtlGetLastWin32Error();
1582
1583 bool fCallRealApi;
1584 //SUP_DPRINTF(("supR3HardenedMonitor_NtCreateSection: 1\n"));
1585 NTSTATUS rcNt = supR3HardenedScreenImage(hFile, fImage, true /*fIgnoreArch*/, &fAccess, &fProtect, &fCallRealApi,
1586 "NtCreateSection", true /*fAvoidWinVerifyTrust*/, NULL /*pfQuiet*/);
1587 //SUP_DPRINTF(("supR3HardenedMonitor_NtCreateSection: 2 rcNt=%#x fCallRealApi=%#x\n", rcNt, fCallRealApi));
1588
1589 RtlRestoreLastWin32Error(dwSavedLastError);
1590
1591 if (!NT_SUCCESS(rcNt))
1592 return rcNt;
1593 Assert(fCallRealApi);
1594 if (!fCallRealApi)
1595 return STATUS_TRUST_FAILURE;
1596
1597 }
1598 }
1599
1600 /*
1601 * Call checked out OK, call the original.
1602 */
1603 NTSTATUS rcNtReal = g_pfnNtCreateSectionReal(phSection, fAccess, pObjAttribs, pcbSection, fProtect, fAttribs, hFile);
1604
1605 /*
1606 * Check that the image that got mapped bear some resemblance to the one that was
1607 * requested. Apparently there are ways to trick the NT cache manager to map a
1608 * file different from hFile into memory using local UNC accesses.
1609 */
1610 if ( NT_SUCCESS(rcNtReal)
1611 && fNeedUncChecking)
1612 {
1613 DWORD dwSavedLastError = RtlGetLastWin32Error();
1614
1615 bool fOkay = false;
1616
1617 /* To get the name of the file backing the section, we unfortunately have to map it. */
1618 SIZE_T cbView = 0;
1619 PVOID pvTmpMap = NULL;
1620 NTSTATUS rcNt = NtMapViewOfSection(*phSection, NtCurrentProcess(), &pvTmpMap, 0, 0, NULL /*poffSection*/, &cbView,
1621 ViewUnmap, MEM_TOP_DOWN, PAGE_EXECUTE);
1622 if (NT_SUCCESS(rcNt))
1623 {
1624 /* Query the name. */
1625 union
1626 {
1627 UNICODE_STRING UniStr;
1628 RTUTF16 awcBuf[512];
1629 } uBuf;
1630 RT_ZERO(uBuf);
1631 SIZE_T cbActual = 0;
1632 NTSTATUS rcNtQuery = NtQueryVirtualMemory(NtCurrentProcess(), pvTmpMap, MemorySectionName,
1633 &uBuf, sizeof(uBuf) - sizeof(RTUTF16), &cbActual);
1634
1635 /* Unmap the view. */
1636 rcNt = NtUnmapViewOfSection(NtCurrentProcess(), pvTmpMap);
1637 if (!NT_SUCCESS(rcNt))
1638 SUP_DPRINTF(("supR3HardenedMonitor_NtCreateSection: NtUnmapViewOfSection failed on %p (hSection=%p, hFile=%p) with %#x!\n",
1639 pvTmpMap, *phSection, hFile, rcNt));
1640
1641 /* Process the name query result. */
1642 if (NT_SUCCESS(rcNtQuery))
1643 {
1644 static UNICODE_STRING const s_UncPrefix = RTNT_CONSTANT_UNISTR(L"\\Device\\Mup");
1645 if (!supHardViUniStrPathStartsWithUniStr(&uBuf.UniStr, &s_UncPrefix, true /*fCheckSlash*/))
1646 fOkay = true;
1647 else
1648 supR3HardenedError(VINF_SUCCESS, false,
1649 "supR3HardenedMonitor_NtCreateSection: Image section with UNC path is not trusted: '%.*ls'\n",
1650 uBuf.UniStr.Length / sizeof(RTUTF16), uBuf.UniStr.Buffer);
1651 }
1652 else
1653 SUP_DPRINTF(("supR3HardenedMonitor_NtCreateSection: NtQueryVirtualMemory failed on %p (hFile=%p) with %#x -> STATUS_TRUST_FAILURE\n",
1654 *phSection, hFile, rcNt));
1655 }
1656 else
1657 SUP_DPRINTF(("supR3HardenedMonitor_NtCreateSection: NtMapViewOfSection failed on %p (hFile=%p) with %#x -> STATUS_TRUST_FAILURE\n",
1658 *phSection, hFile, rcNt));
1659 if (!fOkay)
1660 {
1661 NtClose(*phSection);
1662 *phSection = INVALID_HANDLE_VALUE;
1663 RtlRestoreLastWin32Error(dwSavedLastError);
1664 return STATUS_TRUST_FAILURE;
1665 }
1666
1667 RtlRestoreLastWin32Error(dwSavedLastError);
1668 }
1669 return rcNtReal;
1670}
1671
1672
1673/**
1674 * Helper for supR3HardenedMonitor_LdrLoadDll.
1675 *
1676 * @returns NT status code.
1677 * @param pwszPath The path destination buffer.
1678 * @param cwcPath The size of the path buffer.
1679 * @param pUniStrResult The result string.
1680 * @param pOrgName The orignal name (for errors).
1681 * @param pcwc Where to return the actual length.
1682 */
1683static NTSTATUS supR3HardenedCopyRedirectionResult(WCHAR *pwszPath, size_t cwcPath, PUNICODE_STRING pUniStrResult,
1684 PUNICODE_STRING pOrgName, UINT *pcwc)
1685{
1686 UINT cwc;
1687 *pcwc = cwc = pUniStrResult->Length / sizeof(WCHAR);
1688 if (pUniStrResult->Buffer == pwszPath)
1689 pwszPath[cwc] = '\0';
1690 else
1691 {
1692 if (cwc > cwcPath - 1)
1693 {
1694 supR3HardenedError(VINF_SUCCESS, false,
1695 "supR3HardenedMonitor_LdrLoadDll: Name too long: %.*ls -> %.*ls (RtlDosApplyFileIoslationRedirection_Ustr)\n",
1696 pOrgName->Length / sizeof(WCHAR), pOrgName->Buffer,
1697 pUniStrResult->Length / sizeof(WCHAR), pUniStrResult->Buffer);
1698 return STATUS_NAME_TOO_LONG;
1699 }
1700 memcpy(&pwszPath[0], pUniStrResult->Buffer, pUniStrResult->Length);
1701 pwszPath[cwc] = '\0';
1702 }
1703 return STATUS_SUCCESS;
1704}
1705
1706
1707/**
1708 * Helper for supR3HardenedMonitor_LdrLoadDll that compares the name part of the
1709 * input path against a ASCII name string of a given length.
1710 *
1711 * @returns true if the name part matches
1712 * @param pPath The LdrLoadDll input path.
1713 * @param pszName The name to try match it with.
1714 * @param cchName The name length.
1715 */
1716static bool supR3HardenedIsFilenameMatchDll(PUNICODE_STRING pPath, const char *pszName, size_t cchName)
1717{
1718 if (pPath->Length < cchName * 2)
1719 return false;
1720 PCRTUTF16 pwszTmp = &pPath->Buffer[pPath->Length / sizeof(RTUTF16) - cchName];
1721 if ( pPath->Length != cchName
1722 && pwszTmp[-1] != '\\'
1723 && pwszTmp[-1] != '/')
1724 return false;
1725 return RTUtf16ICmpAscii(pwszTmp, pszName) == 0;
1726}
1727
1728/**
1729 * Checks whether the given unicode string contains a path separator.
1730 *
1731 * @returns true if it contains path separator, false if only a name.
1732 * @param pPath The path to check.
1733 */
1734static bool supR3HardenedContainsPathSep(PUNICODE_STRING pPath)
1735{
1736 size_t cwcLeft = pPath->Length / sizeof(WCHAR);
1737 PCRTUTF16 pwc = pPath->Buffer;
1738 while (cwcLeft-- > 0)
1739 {
1740 RTUTF16 wc = *pwc++;
1741 switch (wc)
1742 {
1743 default:
1744 break;
1745 case '\\':
1746 case '/':
1747 case ':':
1748 return true;
1749 }
1750 }
1751 return false;
1752}
1753
1754
1755/**
1756 * Hooks that intercepts LdrLoadDll calls.
1757 *
1758 * Two purposes:
1759 * -# Enforce our own search path restrictions.
1760 * -# Prevalidate DLLs about to be loaded so we don't upset the loader data
1761 * by doing it from within the NtCreateSection hook (WinVerifyTrust
1762 * seems to be doing harm there on W7/32).
1763 *
1764 * @returns
1765 * @param pwszSearchPath The search path to use.
1766 * @param pfFlags Flags on input. DLL characteristics or something
1767 * on return?
1768 * @param pName The name of the module.
1769 * @param phMod Where the handle of the loaded DLL is to be
1770 * returned to the caller.
1771 */
1772static NTSTATUS NTAPI
1773supR3HardenedMonitor_LdrLoadDll(PWSTR pwszSearchPath, PULONG pfFlags, PUNICODE_STRING pName, PHANDLE phMod)
1774{
1775 DWORD dwSavedLastError = RtlGetLastWin32Error();
1776 PUNICODE_STRING const pOrgName = pName;
1777 NTSTATUS rcNt;
1778
1779 /*
1780 * Make sure the DLL notification callback is registered. If we could, we
1781 * would've done this during early process init, but due to lack of heap
1782 * and uninitialized loader lock, it's not possible that early on.
1783 *
1784 * The callback protects our NtDll hooks from getting unhooked by
1785 * "friendly" fire from the AV crowd.
1786 */
1787 supR3HardenedWinRegisterDllNotificationCallback();
1788
1789 /*
1790 * Process WinVerifyTrust todo before and after.
1791 */
1792 supR3HardenedWinVerifyCacheProcessWvtTodos();
1793
1794 /*
1795 * Reject things we don't want to deal with.
1796 */
1797 if (!pName || pName->Length == 0)
1798 {
1799 supR3HardenedError(VINF_SUCCESS, false, "supR3HardenedMonitor_LdrLoadDll: name is NULL or have a zero length.\n");
1800 SUP_DPRINTF(("supR3HardenedMonitor_LdrLoadDll: returns rcNt=%#x (pName=%p)\n", STATUS_INVALID_PARAMETER, pName));
1801 RtlRestoreLastWin32Error(dwSavedLastError);
1802 return STATUS_INVALID_PARAMETER;
1803 }
1804 PCWCHAR const pawcOrgName = pName->Buffer;
1805 uint32_t const cwcOrgName = pName->Length / sizeof(WCHAR);
1806
1807 /*SUP_DPRINTF(("supR3HardenedMonitor_LdrLoadDll: pName=%.*ls *pfFlags=%#x pwszSearchPath=%p:%ls\n",
1808 (unsigned)pName->Length / sizeof(WCHAR), pName->Buffer, pfFlags ? *pfFlags : UINT32_MAX, pwszSearchPath,
1809 !((uintptr_t)pwszSearchPath & 1) && (uintptr_t)pwszSearchPath >= 0x2000U ? pwszSearchPath : L"<flags>"));*/
1810
1811 /*
1812 * Reject long paths that's close to the 260 limit without looking.
1813 */
1814 if (cwcOrgName > 256)
1815 {
1816 supR3HardenedError(VINF_SUCCESS, false, "supR3HardenedMonitor_LdrLoadDll: too long name: %#x bytes\n", pName->Length);
1817 SUP_DPRINTF(("supR3HardenedMonitor_LdrLoadDll: returns rcNt=%#x\n", STATUS_NAME_TOO_LONG));
1818 RtlRestoreLastWin32Error(dwSavedLastError);
1819 return STATUS_NAME_TOO_LONG;
1820 }
1821
1822 /*
1823 * Reject all UNC-like paths as we cannot trust non-local files at all.
1824 * Note! We may have to relax this to deal with long path specifications and NT pass thrus.
1825 */
1826 if ( cwcOrgName >= 3
1827 && RTPATH_IS_SLASH(pawcOrgName[0])
1828 && RTPATH_IS_SLASH(pawcOrgName[1])
1829 && !RTPATH_IS_SLASH(pawcOrgName[2]))
1830 {
1831 supR3HardenedError(VINF_SUCCESS, false, "supR3HardenedMonitor_LdrLoadDll: rejecting UNC name '%.*ls'\n", cwcOrgName, pawcOrgName);
1832 SUP_DPRINTF(("supR3HardenedMonitor_LdrLoadDll: returns rcNt=%#x\n", STATUS_REDIRECTOR_NOT_STARTED));
1833 RtlRestoreLastWin32Error(dwSavedLastError);
1834 return STATUS_REDIRECTOR_NOT_STARTED;
1835 }
1836
1837 /*
1838 * Reject PGHook.dll as it creates a thread from its DllMain that breaks
1839 * our preconditions respawning the 2nd process, resulting in
1840 * VERR_SUP_VP_THREAD_NOT_ALONE. The DLL is being loaded by a user APC
1841 * scheduled during kernel32.dll load notification from a kernel driver,
1842 * so failing the load attempt should not upset anyone.
1843 */
1844 if (g_enmSupR3HardenedMainState == SUPR3HARDENEDMAINSTATE_WIN_EARLY_STUB_DEVICE_OPENED)
1845 {
1846 static const struct { const char *psz; size_t cch; } s_aUnwantedEarlyDlls[] =
1847 {
1848 { RT_STR_TUPLE("PGHook.dll") },
1849 };
1850 for (unsigned i = 0; i < RT_ELEMENTS(s_aUnwantedEarlyDlls); i++)
1851 if (supR3HardenedIsFilenameMatchDll(pName, s_aUnwantedEarlyDlls[i].psz, s_aUnwantedEarlyDlls[i].cch))
1852 {
1853 SUP_DPRINTF(("supR3HardenedMonitor_LdrLoadDll: Refusing to load '%.*ls' as it is expected to create undesirable threads that will upset our respawn checks (returning STATUS_TOO_MANY_THREADS)\n",
1854 pName->Length / sizeof(RTUTF16), pName->Buffer));
1855 return STATUS_TOO_MANY_THREADS;
1856 }
1857 }
1858
1859 /*
1860 * Resolve the path, copying the result into wszPath
1861 */
1862 NTSTATUS rcNtResolve = STATUS_SUCCESS;
1863 bool fSkipValidation = false;
1864 bool fCheckIfLoaded = false;
1865 WCHAR wszPath[260];
1866 static UNICODE_STRING const s_DefaultSuffix = RTNT_CONSTANT_UNISTR(L".dll");
1867 UNICODE_STRING UniStrStatic = { 0, (USHORT)sizeof(wszPath) - sizeof(WCHAR), wszPath };
1868 UNICODE_STRING UniStrDynamic = { 0, 0, NULL };
1869 PUNICODE_STRING pUniStrResult = NULL;
1870 UNICODE_STRING ResolvedName;
1871
1872 /*
1873 * Process the name a little, checking if it needs a DLL suffix and is pathless.
1874 */
1875 uint32_t offLastSlash = UINT32_MAX;
1876 uint32_t offLastDot = UINT32_MAX;
1877 for (uint32_t i = 0; i < cwcOrgName; i++)
1878 switch (pawcOrgName[i])
1879 {
1880 case '\\':
1881 case '/':
1882 offLastSlash = i;
1883 offLastDot = UINT32_MAX;
1884 break;
1885 case '.':
1886 offLastDot = i;
1887 break;
1888 }
1889 bool const fNeedDllSuffix = offLastDot == UINT32_MAX;
1890 //bool const fTrailingDot = offLastDot == cwcOrgName - 1;
1891
1892 /*
1893 * Absolute path?
1894 */
1895 if ( ( cwcOrgName >= 4
1896 && RT_C_IS_ALPHA(pawcOrgName[0])
1897 && pawcOrgName[1] == ':'
1898 && RTPATH_IS_SLASH(pawcOrgName[2]) )
1899 || ( cwcOrgName >= 1
1900 && RTPATH_IS_SLASH(pawcOrgName[0]) )
1901 )
1902 {
1903 rcNtResolve = RtlDosApplyFileIsolationRedirection_Ustr(1 /*fFlags*/,
1904 pName,
1905 (PUNICODE_STRING)&s_DefaultSuffix,
1906 &UniStrStatic,
1907 &UniStrDynamic,
1908 &pUniStrResult,
1909 NULL /*pNewFlags*/,
1910 NULL /*pcbFilename*/,
1911 NULL /*pcbNeeded*/);
1912 if (NT_SUCCESS(rcNtResolve))
1913 {
1914 UINT cwc;
1915 rcNt = supR3HardenedCopyRedirectionResult(wszPath, RT_ELEMENTS(wszPath), pUniStrResult, pName, &cwc);
1916 RtlFreeUnicodeString(&UniStrDynamic);
1917 if (!NT_SUCCESS(rcNt))
1918 {
1919 SUP_DPRINTF(("supR3HardenedMonitor_LdrLoadDll: returns rcNt=%#x\n", rcNt));
1920 RtlRestoreLastWin32Error(dwSavedLastError);
1921 return rcNt;
1922 }
1923
1924 ResolvedName.Buffer = wszPath;
1925 ResolvedName.Length = (USHORT)(cwc * sizeof(WCHAR));
1926 ResolvedName.MaximumLength = ResolvedName.Length + sizeof(WCHAR);
1927
1928 SUP_DPRINTF(("supR3HardenedMonitor_LdrLoadDll: '%.*ls' -> '%.*ls' [redir]\n",
1929 (unsigned)pName->Length / sizeof(WCHAR), pName->Buffer,
1930 ResolvedName.Length / sizeof(WCHAR), ResolvedName.Buffer, rcNt));
1931 pName = &ResolvedName;
1932 }
1933 else
1934 {
1935 /* Copy the path. */
1936 memcpy(wszPath, pawcOrgName, cwcOrgName * sizeof(WCHAR));
1937 if (!fNeedDllSuffix)
1938 wszPath[cwcOrgName] = '\0';
1939 else
1940 {
1941 if (cwcOrgName + 4 >= RT_ELEMENTS(wszPath))
1942 {
1943 supR3HardenedError(VINF_SUCCESS, false,
1944 "supR3HardenedMonitor_LdrLoadDll: Name too long (abs): %.*ls\n", cwcOrgName, pawcOrgName);
1945 SUP_DPRINTF(("supR3HardenedMonitor_LdrLoadDll: returns rcNt=%#x\n", STATUS_NAME_TOO_LONG));
1946 RtlRestoreLastWin32Error(dwSavedLastError);
1947 return STATUS_NAME_TOO_LONG;
1948 }
1949 memcpy(&wszPath[cwcOrgName], L".dll", 5 * sizeof(WCHAR));
1950 }
1951 }
1952 }
1953 /*
1954 * Not an absolute path. Check if it's one of those special API set DLLs
1955 * or something we're known to use but should be taken from WinSxS.
1956 */
1957 else if ( ( supHardViUtf16PathStartsWithEx(pName->Buffer, pName->Length / sizeof(WCHAR),
1958 L"api-ms-win-", 11, false /*fCheckSlash*/)
1959 || supHardViUtf16PathStartsWithEx(pName->Buffer, pName->Length / sizeof(WCHAR),
1960 L"ext-ms-win-", 11, false /*fCheckSlash*/) )
1961 && !supR3HardenedContainsPathSep(pName))
1962 {
1963 memcpy(wszPath, pName->Buffer, pName->Length);
1964 wszPath[pName->Length / sizeof(WCHAR)] = '\0';
1965 fSkipValidation = true;
1966 }
1967 /*
1968 * Not an absolute path or special API set. There are two alternatives
1969 * now, either there is no path at all or there is a relative path. We
1970 * will resolve it to an absolute path in either case, failing the call
1971 * if we can't.
1972 */
1973 else
1974 {
1975 /*
1976 * Reject relative paths for now as they might be breakout attempts.
1977 */
1978 if (offLastSlash != UINT32_MAX)
1979 {
1980 supR3HardenedError(VINF_SUCCESS, false,
1981 "supR3HardenedMonitor_LdrLoadDll: relative name not permitted: %.*ls\n",
1982 cwcOrgName, pawcOrgName);
1983 SUP_DPRINTF(("supR3HardenedMonitor_LdrLoadDll: returns rcNt=%#x\n", STATUS_OBJECT_NAME_INVALID));
1984 RtlRestoreLastWin32Error(dwSavedLastError);
1985 return STATUS_OBJECT_NAME_INVALID;
1986 }
1987
1988 /*
1989 * Perform dll redirection to WinSxS such. We using an undocumented
1990 * API here, which as always is a bit risky... ASSUMES that the API
1991 * returns a full DOS path.
1992 */
1993 UINT cwc;
1994 rcNtResolve = RtlDosApplyFileIsolationRedirection_Ustr(1 /*fFlags*/,
1995 pName,
1996 (PUNICODE_STRING)&s_DefaultSuffix,
1997 &UniStrStatic,
1998 &UniStrDynamic,
1999 &pUniStrResult,
2000 NULL /*pNewFlags*/,
2001 NULL /*pcbFilename*/,
2002 NULL /*pcbNeeded*/);
2003 if (NT_SUCCESS(rcNtResolve))
2004 {
2005 rcNt = supR3HardenedCopyRedirectionResult(wszPath, RT_ELEMENTS(wszPath), pUniStrResult, pName, &cwc);
2006 RtlFreeUnicodeString(&UniStrDynamic);
2007 if (!NT_SUCCESS(rcNt))
2008 {
2009 SUP_DPRINTF(("supR3HardenedMonitor_LdrLoadDll: returns rcNt=%#x\n", rcNt));
2010 RtlRestoreLastWin32Error(dwSavedLastError);
2011 return rcNt;
2012 }
2013 }
2014 else
2015 {
2016 /*
2017 * Search for the DLL. Only System32 is allowed as the target of
2018 * a search on the API level, all VBox calls will have full paths.
2019 * If the DLL is not in System32, we will resort to check if it's
2020 * refering to an already loaded DLL (fCheckIfLoaded).
2021 */
2022 AssertCompile(sizeof(g_System32WinPath.awcBuffer) <= sizeof(wszPath));
2023 cwc = g_System32WinPath.UniStr.Length / sizeof(RTUTF16); Assert(cwc > 2);
2024 if (cwc + 1 + cwcOrgName + fNeedDllSuffix * 4 >= RT_ELEMENTS(wszPath))
2025 {
2026 supR3HardenedError(VINF_SUCCESS, false,
2027 "supR3HardenedMonitor_LdrLoadDll: Name too long (system32): %.*ls\n", cwcOrgName, pawcOrgName);
2028 SUP_DPRINTF(("supR3HardenedMonitor_LdrLoadDll: returns rcNt=%#x\n", STATUS_NAME_TOO_LONG));
2029 RtlRestoreLastWin32Error(dwSavedLastError);
2030 return STATUS_NAME_TOO_LONG;
2031 }
2032 memcpy(wszPath, g_System32WinPath.UniStr.Buffer, cwc * sizeof(RTUTF16));
2033 wszPath[cwc++] = '\\';
2034 memcpy(&wszPath[cwc], pawcOrgName, cwcOrgName * sizeof(WCHAR));
2035 cwc += cwcOrgName;
2036 if (!fNeedDllSuffix)
2037 wszPath[cwc] = '\0';
2038 else
2039 {
2040 memcpy(&wszPath[cwc], L".dll", 5 * sizeof(WCHAR));
2041 cwc += 4;
2042 }
2043 fCheckIfLoaded = true;
2044 }
2045
2046 ResolvedName.Buffer = wszPath;
2047 ResolvedName.Length = (USHORT)(cwc * sizeof(WCHAR));
2048 ResolvedName.MaximumLength = ResolvedName.Length + sizeof(WCHAR);
2049 pName = &ResolvedName;
2050 }
2051
2052#ifndef IN_SUP_R3_STATIC
2053 /*
2054 * Reject blacklisted DLLs based on input name.
2055 */
2056 for (unsigned i = 0; g_aSupNtViBlacklistedDlls[i].psz != NULL; i++)
2057 if (supR3HardenedIsFilenameMatchDll(pName, g_aSupNtViBlacklistedDlls[i].psz, g_aSupNtViBlacklistedDlls[i].cch))
2058 {
2059 SUP_DPRINTF(("supR3HardenedMonitor_LdrLoadDll: Refusing to load blacklisted DLL: '%.*ls'\n",
2060 pName->Length / sizeof(RTUTF16), pName->Buffer));
2061 RtlRestoreLastWin32Error(dwSavedLastError);
2062 return STATUS_TOO_MANY_THREADS;
2063 }
2064#endif
2065
2066 bool fQuiet = false;
2067 if (!fSkipValidation)
2068 {
2069 /*
2070 * Try open the file. If this fails, never mind, just pass it on to
2071 * the real API as we've replaced any searchable name with a full name
2072 * and the real API can come up with a fitting status code for it.
2073 */
2074 HANDLE hRootDir;
2075 UNICODE_STRING NtPathUniStr;
2076 int rc = RTNtPathFromWinUtf16Ex(&NtPathUniStr, &hRootDir, wszPath, RTSTR_MAX);
2077 if (RT_FAILURE(rc))
2078 {
2079 supR3HardenedError(rc, false,
2080 "supR3HardenedMonitor_LdrLoadDll: RTNtPathFromWinUtf16Ex failed on '%ls': %Rrc\n", wszPath, rc);
2081 SUP_DPRINTF(("supR3HardenedMonitor_LdrLoadDll: returns rcNt=%#x\n", STATUS_OBJECT_NAME_INVALID));
2082 RtlRestoreLastWin32Error(dwSavedLastError);
2083 return STATUS_OBJECT_NAME_INVALID;
2084 }
2085
2086 HANDLE hFile = RTNT_INVALID_HANDLE_VALUE;
2087 IO_STATUS_BLOCK Ios = RTNT_IO_STATUS_BLOCK_INITIALIZER;
2088 OBJECT_ATTRIBUTES ObjAttr;
2089 InitializeObjectAttributes(&ObjAttr, &NtPathUniStr, OBJ_CASE_INSENSITIVE, hRootDir, NULL /*pSecDesc*/);
2090
2091 rcNt = NtCreateFile(&hFile,
2092 FILE_READ_DATA | READ_CONTROL | SYNCHRONIZE,
2093 &ObjAttr,
2094 &Ios,
2095 NULL /* Allocation Size*/,
2096 FILE_ATTRIBUTE_NORMAL,
2097 FILE_SHARE_READ,
2098 FILE_OPEN,
2099 FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT,
2100 NULL /*EaBuffer*/,
2101 0 /*EaLength*/);
2102 if (NT_SUCCESS(rcNt))
2103 rcNt = Ios.Status;
2104 if (NT_SUCCESS(rcNt))
2105 {
2106 ULONG fAccess = 0;
2107 ULONG fProtect = 0;
2108 bool fCallRealApi = false;
2109 rcNt = supR3HardenedScreenImage(hFile, true /*fImage*/, RT_VALID_PTR(pfFlags) && (*pfFlags & 0x2) /*fIgnoreArch*/,
2110 &fAccess, &fProtect, &fCallRealApi,
2111 "LdrLoadDll", false /*fAvoidWinVerifyTrust*/, &fQuiet);
2112 NtClose(hFile);
2113 if (!NT_SUCCESS(rcNt))
2114 {
2115 if (!fQuiet)
2116 {
2117 if (pOrgName != pName)
2118 supR3HardenedError(VINF_SUCCESS, false, "supR3HardenedMonitor_LdrLoadDll: rejecting '%ls': rcNt=%#x\n",
2119 wszPath, rcNt);
2120 else
2121 supR3HardenedError(VINF_SUCCESS, false, "supR3HardenedMonitor_LdrLoadDll: rejecting '%ls' (%.*ls): rcNt=%#x\n",
2122 wszPath, pOrgName->Length / sizeof(WCHAR), pOrgName->Buffer, rcNt);
2123 SUP_DPRINTF(("supR3HardenedMonitor_LdrLoadDll: returns rcNt=%#x '%ls'\n", rcNt, wszPath));
2124 }
2125 RtlRestoreLastWin32Error(dwSavedLastError);
2126 return rcNt;
2127 }
2128
2129 supR3HardenedWinVerifyCacheProcessImportTodos();
2130 }
2131 else
2132 {
2133 DWORD dwErr = RtlGetLastWin32Error();
2134
2135 /*
2136 * Deal with special case where the caller (first case was MS LifeCam)
2137 * is using LoadLibrary instead of GetModuleHandle to find a loaded DLL.
2138 */
2139 NTSTATUS rcNtGetDll = STATUS_SUCCESS;
2140 if ( fCheckIfLoaded
2141 && ( rcNt == STATUS_OBJECT_NAME_NOT_FOUND
2142 || rcNt == STATUS_OBJECT_PATH_NOT_FOUND))
2143 {
2144 rcNtGetDll = LdrGetDllHandle(NULL /*DllPath*/, NULL /*pfFlags*/, pOrgName, phMod);
2145 if (NT_SUCCESS(rcNtGetDll))
2146 {
2147 RTNtPathFree(&NtPathUniStr, &hRootDir);
2148 RtlRestoreLastWin32Error(dwSavedLastError);
2149 return rcNtGetDll;
2150 }
2151 }
2152
2153 SUP_DPRINTF(("supR3HardenedMonitor_LdrLoadDll: error opening '%ls': %u (NtPath=%.*ls; Input=%.*ls; rcNtGetDll=%#x\n",
2154 wszPath, dwErr, NtPathUniStr.Length / sizeof(RTUTF16), NtPathUniStr.Buffer,
2155 pOrgName->Length / sizeof(WCHAR), pOrgName->Buffer, rcNtGetDll));
2156
2157 RTNtPathFree(&NtPathUniStr, &hRootDir);
2158 RtlRestoreLastWin32Error(dwSavedLastError);
2159 SUP_DPRINTF(("supR3HardenedMonitor_LdrLoadDll: returns rcNt=%#x '%ls'\n", rcNt, wszPath));
2160 return rcNt;
2161 }
2162 RTNtPathFree(&NtPathUniStr, &hRootDir);
2163 }
2164
2165 /*
2166 * Screened successfully enough. Call the real thing.
2167 */
2168 if (!fQuiet)
2169 {
2170 if (pOrgName != pName)
2171 SUP_DPRINTF(("supR3HardenedMonitor_LdrLoadDll: pName=%.*ls (Input=%.*ls, rcNtResolve=%#x) *pfFlags=%#x pwszSearchPath=%p:%ls [calling]\n",
2172 (unsigned)pName->Length / sizeof(WCHAR), pName->Buffer,
2173 (unsigned)pOrgName->Length / sizeof(WCHAR), pOrgName->Buffer, rcNtResolve,
2174 pfFlags ? *pfFlags : UINT32_MAX, pwszSearchPath,
2175 !((uintptr_t)pwszSearchPath & 1) && (uintptr_t)pwszSearchPath >= 0x2000U ? pwszSearchPath : L"<flags>"));
2176 else
2177 SUP_DPRINTF(("supR3HardenedMonitor_LdrLoadDll: pName=%.*ls (rcNtResolve=%#x) *pfFlags=%#x pwszSearchPath=%p:%ls [calling]\n",
2178 (unsigned)pName->Length / sizeof(WCHAR), pName->Buffer, rcNtResolve,
2179 pfFlags ? *pfFlags : UINT32_MAX, pwszSearchPath,
2180 !((uintptr_t)pwszSearchPath & 1) && (uintptr_t)pwszSearchPath >= 0x2000U ? pwszSearchPath : L"<flags>"));
2181 }
2182
2183 RtlRestoreLastWin32Error(dwSavedLastError);
2184 rcNt = g_pfnLdrLoadDllReal(pwszSearchPath, pfFlags, pName, phMod);
2185
2186 /*
2187 * Log the result and process pending WinVerifyTrust work if we can.
2188 */
2189 dwSavedLastError = RtlGetLastWin32Error();
2190
2191 if (NT_SUCCESS(rcNt) && phMod)
2192 SUP_DPRINTF(("supR3HardenedMonitor_LdrLoadDll: returns rcNt=%#x hMod=%p '%ls'\n", rcNt, *phMod, wszPath));
2193 else if (!NT_SUCCESS(rcNt) || !fQuiet)
2194 SUP_DPRINTF(("supR3HardenedMonitor_LdrLoadDll: returns rcNt=%#x '%ls'\n", rcNt, wszPath));
2195
2196 supR3HardenedWinVerifyCacheProcessWvtTodos();
2197
2198 RtlRestoreLastWin32Error(dwSavedLastError);
2199
2200 return rcNt;
2201}
2202
2203
2204/**
2205 * DLL load and unload notification callback.
2206 *
2207 * This is a safety against our LdrLoadDll hook being replaced by protection
2208 * software. Though, we prefer the LdrLoadDll hook to this one as it allows us
2209 * to call WinVerifyTrust more freely.
2210 *
2211 * @param ulReason The reason we're called, see
2212 * LDR_DLL_NOTIFICATION_REASON_XXX.
2213 * @param pData Reason specific data. (Format is currently the same for
2214 * both load and unload.)
2215 * @param pvUser User parameter (ignored).
2216 *
2217 * @remarks Vista and later.
2218 * @remarks The loader lock is held when we're called, at least on Windows 7.
2219 */
2220static VOID CALLBACK supR3HardenedDllNotificationCallback(ULONG ulReason, PCLDR_DLL_NOTIFICATION_DATA pData, PVOID pvUser)
2221{
2222 NOREF(pvUser);
2223
2224 /*
2225 * Screen the image on load. We will normally get a verification cache
2226 * hit here because of the LdrLoadDll and NtCreateSection hooks, so it
2227 * should be relatively cheap to recheck. In case our NtDll patches
2228 * got re
2229 *
2230 * This ASSUMES that we get informed after the fact as indicated by the
2231 * available documentation.
2232 */
2233 if (ulReason == LDR_DLL_NOTIFICATION_REASON_LOADED)
2234 {
2235 SUP_DPRINTF(("supR3HardenedDllNotificationCallback: load %p LB %#010x %.*ls [fFlags=%#x]\n",
2236 pData->Loaded.DllBase, pData->Loaded.SizeOfImage,
2237 pData->Loaded.FullDllName->Length / sizeof(WCHAR), pData->Loaded.FullDllName->Buffer,
2238 pData->Loaded.Flags));
2239
2240 /* Convert the windows path to an NT path and open it. */
2241 HANDLE hRootDir;
2242 UNICODE_STRING NtPathUniStr;
2243 int rc = RTNtPathFromWinUtf16Ex(&NtPathUniStr, &hRootDir, pData->Loaded.FullDllName->Buffer,
2244 pData->Loaded.FullDllName->Length / sizeof(WCHAR));
2245 if (RT_FAILURE(rc))
2246 {
2247 supR3HardenedFatal("supR3HardenedDllNotificationCallback: RTNtPathFromWinUtf16Ex failed on '%.*ls': %Rrc\n",
2248 pData->Loaded.FullDllName->Length / sizeof(WCHAR), pData->Loaded.FullDllName->Buffer, rc);
2249 return;
2250 }
2251
2252 HANDLE hFile = RTNT_INVALID_HANDLE_VALUE;
2253 IO_STATUS_BLOCK Ios = RTNT_IO_STATUS_BLOCK_INITIALIZER;
2254 OBJECT_ATTRIBUTES ObjAttr;
2255 InitializeObjectAttributes(&ObjAttr, &NtPathUniStr, OBJ_CASE_INSENSITIVE, hRootDir, NULL /*pSecDesc*/);
2256
2257 NTSTATUS rcNt = NtCreateFile(&hFile,
2258 FILE_READ_DATA | READ_CONTROL | SYNCHRONIZE,
2259 &ObjAttr,
2260 &Ios,
2261 NULL /* Allocation Size*/,
2262 FILE_ATTRIBUTE_NORMAL,
2263 FILE_SHARE_READ,
2264 FILE_OPEN,
2265 FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT,
2266 NULL /*EaBuffer*/,
2267 0 /*EaLength*/);
2268 if (NT_SUCCESS(rcNt))
2269 rcNt = Ios.Status;
2270 if (!NT_SUCCESS(rcNt))
2271 {
2272 supR3HardenedFatal("supR3HardenedDllNotificationCallback: NtCreateFile failed on '%.*ls' / '%.*ls': %#x\n",
2273 pData->Loaded.FullDllName->Length / sizeof(WCHAR), pData->Loaded.FullDllName->Buffer,
2274 NtPathUniStr.Length / sizeof(WCHAR), NtPathUniStr.Buffer, rcNt);
2275 /* not reached */
2276 }
2277
2278 /* Do the screening. */
2279 ULONG fAccess = 0;
2280 ULONG fProtect = 0;
2281 bool fCallRealApi = false;
2282 bool fQuietFailure = false;
2283 rcNt = supR3HardenedScreenImage(hFile, true /*fImage*/, true /*fIgnoreArch*/, &fAccess, &fProtect, &fCallRealApi,
2284 "LdrLoadDll", true /*fAvoidWinVerifyTrust*/, &fQuietFailure);
2285 NtClose(hFile);
2286 if (!NT_SUCCESS(rcNt))
2287 {
2288 supR3HardenedFatal("supR3HardenedDllNotificationCallback: supR3HardenedScreenImage failed on '%.*ls' / '%.*ls': %#x\n",
2289 pData->Loaded.FullDllName->Length / sizeof(WCHAR), pData->Loaded.FullDllName->Buffer,
2290 NtPathUniStr.Length / sizeof(WCHAR), NtPathUniStr.Buffer, rcNt);
2291 /* not reached */
2292 }
2293 RTNtPathFree(&NtPathUniStr, &hRootDir);
2294 }
2295 /*
2296 * Log the unload call.
2297 */
2298 else if (ulReason == LDR_DLL_NOTIFICATION_REASON_UNLOADED)
2299 {
2300 SUP_DPRINTF(("supR3HardenedDllNotificationCallback: Unload %p LB %#010x %.*ls [flags=%#x]\n",
2301 pData->Unloaded.DllBase, pData->Unloaded.SizeOfImage,
2302 pData->Unloaded.FullDllName->Length / sizeof(WCHAR), pData->Unloaded.FullDllName->Buffer,
2303 pData->Unloaded.Flags));
2304 }
2305 /*
2306 * Just log things we don't know and then return without caching anything.
2307 */
2308 else
2309 {
2310 static uint32_t s_cLogEntries = 0;
2311 if (s_cLogEntries++ < 32)
2312 SUP_DPRINTF(("supR3HardenedDllNotificationCallback: ulReason=%u pData=%p\n", ulReason, pData));
2313 return;
2314 }
2315
2316 /*
2317 * Use this opportunity to make sure our NtDll patches are still in place,
2318 * since they may be replaced by indecent protection software solutions.
2319 */
2320 supR3HardenedWinReInstallHooks(false /*fFirstCall */);
2321}
2322
2323
2324/**
2325 * Registers the DLL notification callback if it hasn't already been registered.
2326 */
2327static void supR3HardenedWinRegisterDllNotificationCallback(void)
2328{
2329 /*
2330 * The notification API was added in Vista, so it's an optional (weak) import.
2331 */
2332 if ( LdrRegisterDllNotification != NULL
2333 && g_cDllNotificationRegistered <= 0
2334 && g_cDllNotificationRegistered > -32)
2335 {
2336 NTSTATUS rcNt = LdrRegisterDllNotification(0, supR3HardenedDllNotificationCallback, NULL, &g_pvDllNotificationCookie);
2337 if (NT_SUCCESS(rcNt))
2338 {
2339 SUP_DPRINTF(("Registered Dll notification callback with NTDLL.\n"));
2340 g_cDllNotificationRegistered = 1;
2341 }
2342 else
2343 {
2344 supR3HardenedError(rcNt, false /*fFatal*/, "LdrRegisterDllNotification failed: %#x\n", rcNt);
2345 g_cDllNotificationRegistered--;
2346 }
2347 }
2348}
2349
2350
2351static void supR3HardenedWinHookFailed(const char *pszWhich, uint8_t const *pbPrologue)
2352{
2353 supR3HardenedFatalMsg("supR3HardenedWinInstallHooks", kSupInitOp_Misc, VERR_NO_MEMORY,
2354 "Failed to install %s monitor: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x\n "
2355#ifdef RT_ARCH_X86
2356 "(It is also possible you are running 32-bit VirtualBox under 64-bit windows.)\n"
2357#endif
2358 ,
2359 pszWhich,
2360 pbPrologue[0], pbPrologue[1], pbPrologue[2], pbPrologue[3],
2361 pbPrologue[4], pbPrologue[5], pbPrologue[6], pbPrologue[7],
2362 pbPrologue[8], pbPrologue[9], pbPrologue[10], pbPrologue[11],
2363 pbPrologue[12], pbPrologue[13], pbPrologue[14], pbPrologue[15]);
2364}
2365
2366
2367/**
2368 * IPRT thread that waits for the parent process to terminate and reacts by
2369 * exiting the current process.
2370 *
2371 * @returns VINF_SUCCESS
2372 * @param hSelf The current thread. Ignored.
2373 * @param pvUser The handle of the parent process.
2374 */
2375static DECLCALLBACK(int) supR3HardenedWinParentWatcherThread(RTTHREAD hSelf, void *pvUser)
2376{
2377 HANDLE hProcWait = (HANDLE)pvUser;
2378 NOREF(hSelf);
2379
2380 /*
2381 * Wait for the parent to terminate.
2382 */
2383 NTSTATUS rcNt;
2384 for (;;)
2385 {
2386 rcNt = NtWaitForSingleObject(hProcWait, TRUE /*Alertable*/, NULL /*pTimeout*/);
2387 if ( rcNt == STATUS_WAIT_0
2388 || rcNt == STATUS_ABANDONED_WAIT_0)
2389 break;
2390 if ( rcNt != STATUS_TIMEOUT
2391 && rcNt != STATUS_USER_APC
2392 && rcNt != STATUS_ALERTED)
2393 supR3HardenedFatal("NtWaitForSingleObject returned %#x\n", rcNt);
2394 }
2395
2396 /*
2397 * Proxy the termination code of the child, if it exited already.
2398 */
2399 PROCESS_BASIC_INFORMATION BasicInfo;
2400 NTSTATUS rcNt2 = NtQueryInformationProcess(hProcWait, ProcessBasicInformation, &BasicInfo, sizeof(BasicInfo), NULL);
2401 if ( !NT_SUCCESS(rcNt2)
2402 || BasicInfo.ExitStatus == STATUS_PENDING)
2403 BasicInfo.ExitStatus = RTEXITCODE_FAILURE;
2404
2405 NtClose(hProcWait);
2406 SUP_DPRINTF(("supR3HardenedWinParentWatcherThread: Quitting: ExitCode=%#x rcNt=%#x\n", BasicInfo.ExitStatus, rcNt));
2407 suplibHardenedExit((RTEXITCODE)BasicInfo.ExitStatus);
2408 /* not reached */
2409}
2410
2411
2412/**
2413 * Creates the parent watcher thread that will make sure this process exits when
2414 * the parent does.
2415 *
2416 * This is a necessary evil to make VBoxNetDhcp and VBoxNetNat termination from
2417 * Main work without too much new magic. It also makes Ctrl-C or similar work
2418 * in on the hardened processes in the windows console.
2419 *
2420 * @param hVBoxRT The VBoxRT.dll handle. We use RTThreadCreate to
2421 * spawn the thread to avoid duplicating thread
2422 * creation and thread naming code from IPRT.
2423 */
2424DECLHIDDEN(void) supR3HardenedWinCreateParentWatcherThread(HMODULE hVBoxRT)
2425{
2426 /*
2427 * Resolve runtime methods that we need.
2428 */
2429 PFNRTTHREADCREATE pfnRTThreadCreate = (PFNRTTHREADCREATE)GetProcAddress(hVBoxRT, "RTThreadCreate");
2430 SUPR3HARDENED_ASSERT(pfnRTThreadCreate != NULL);
2431
2432 /*
2433 * Find the parent process ID.
2434 */
2435 PROCESS_BASIC_INFORMATION BasicInfo;
2436 NTSTATUS rcNt = NtQueryInformationProcess(NtCurrentProcess(), ProcessBasicInformation, &BasicInfo, sizeof(BasicInfo), NULL);
2437 if (!NT_SUCCESS(rcNt))
2438 supR3HardenedFatal("supR3HardenedWinCreateParentWatcherThread: NtQueryInformationProcess failed: %#x\n", rcNt);
2439
2440 /*
2441 * Open the parent process for waiting and exitcode query.
2442 */
2443 OBJECT_ATTRIBUTES ObjAttr;
2444 InitializeObjectAttributes(&ObjAttr, NULL, 0, NULL /*hRootDir*/, NULL /*pSecDesc*/);
2445
2446 CLIENT_ID ClientId;
2447 ClientId.UniqueProcess = (HANDLE)BasicInfo.InheritedFromUniqueProcessId;
2448 ClientId.UniqueThread = NULL;
2449
2450 HANDLE hParent;
2451 rcNt = NtOpenProcess(&hParent, SYNCHRONIZE | PROCESS_QUERY_INFORMATION, &ObjAttr, &ClientId);
2452 if (!NT_SUCCESS(rcNt))
2453 supR3HardenedFatalMsg("supR3HardenedWinCreateParentWatcherThread", kSupInitOp_Misc, VERR_GENERAL_FAILURE,
2454 "NtOpenProcess(%p.0) failed: %#x\n", ClientId.UniqueProcess, rcNt);
2455
2456 /*
2457 * Create the thread that should do the waiting.
2458 */
2459 int rc = pfnRTThreadCreate(NULL, supR3HardenedWinParentWatcherThread, hParent, _64K /* stack */,
2460 RTTHREADTYPE_DEFAULT, 0 /*fFlags*/, "ParentWatcher");
2461 if (RT_FAILURE(rc))
2462 supR3HardenedFatal("supR3HardenedWinCreateParentWatcherThread: RTThreadCreate failed: %Rrc\n", rc);
2463}
2464
2465
2466/**
2467 * Checks if the calling thread is the only one in the process.
2468 *
2469 * @returns true if we're positive we're alone, false if not.
2470 */
2471static bool supR3HardenedWinAmIAlone(void)
2472{
2473 ULONG fAmIAlone = 0;
2474 ULONG cbIgn = 0;
2475 NTSTATUS rcNt = NtQueryInformationThread(NtCurrentThread(), ThreadAmILastThread, &fAmIAlone, sizeof(fAmIAlone), &cbIgn);
2476 Assert(NT_SUCCESS(rcNt));
2477 return NT_SUCCESS(rcNt) && fAmIAlone != 0;
2478}
2479
2480
2481/**
2482 * Simplify NtProtectVirtualMemory interface.
2483 *
2484 * Modifies protection for the current process. Caller must know the current
2485 * protection as it's not returned.
2486 *
2487 * @returns NT status code.
2488 * @param pvMem The memory to change protection for.
2489 * @param cbMem The amount of memory to change.
2490 * @param fNewProt The new protection.
2491 */
2492static NTSTATUS supR3HardenedWinProtectMemory(PVOID pvMem, SIZE_T cbMem, ULONG fNewProt)
2493{
2494 ULONG fOldProt = 0;
2495 return NtProtectVirtualMemory(NtCurrentProcess(), &pvMem, &cbMem, fNewProt, &fOldProt);
2496}
2497
2498
2499/**
2500 * Installs or reinstalls the NTDLL patches.
2501 */
2502static void supR3HardenedWinReInstallHooks(bool fFirstCall)
2503{
2504 struct
2505 {
2506 size_t cbPatch;
2507 uint8_t const *pabPatch;
2508 uint8_t **ppbApi;
2509 const char *pszName;
2510 } const s_aPatches[] =
2511 {
2512 { sizeof(g_abNtCreateSectionPatch), g_abNtCreateSectionPatch, &g_pbNtCreateSection, "NtCreateSection" },
2513 { sizeof(g_abLdrLoadDllPatch), g_abLdrLoadDllPatch, &g_pbLdrLoadDll, "LdrLoadDll" },
2514 };
2515
2516 ULONG fAmIAlone = ~(ULONG)0;
2517
2518 for (uint32_t i = 0; i < RT_ELEMENTS(s_aPatches); i++)
2519 {
2520 uint8_t *pbApi = *s_aPatches[i].ppbApi;
2521 if (memcmp(pbApi, s_aPatches[i].pabPatch, s_aPatches[i].cbPatch) != 0)
2522 {
2523 /*
2524 * Log the incident if it's not the initial call.
2525 */
2526 static uint32_t volatile s_cTimes = 0;
2527 if (!fFirstCall && s_cTimes < 128)
2528 {
2529 s_cTimes++;
2530 SUP_DPRINTF(("supR3HardenedWinReInstallHooks: Reinstalling %s (%p: %.*Rhxs).\n",
2531 s_aPatches[i].pszName, pbApi, s_aPatches[i].cbPatch, pbApi));
2532 }
2533
2534 Assert(s_aPatches[i].cbPatch >= 4);
2535
2536 SUPR3HARDENED_ASSERT_NT_SUCCESS(supR3HardenedWinProtectMemory(pbApi, s_aPatches[i].cbPatch, PAGE_EXECUTE_READWRITE));
2537
2538 /*
2539 * If we're alone, just memcpy the patch in.
2540 */
2541
2542 if (fAmIAlone == ~(ULONG)0)
2543 fAmIAlone = supR3HardenedWinAmIAlone();
2544 if (fAmIAlone)
2545 memcpy(pbApi, s_aPatches[i].pabPatch, s_aPatches[i].cbPatch);
2546 else
2547 {
2548 /*
2549 * Not alone. Start by injecting a JMP $-2, then waste some
2550 * CPU cycles to get the other threads a good chance of getting
2551 * out of the code before we replace it.
2552 */
2553 RTUINT32U uJmpDollarMinus;
2554 uJmpDollarMinus.au8[0] = 0xeb;
2555 uJmpDollarMinus.au8[1] = 0xfe;
2556 uJmpDollarMinus.au8[2] = pbApi[2];
2557 uJmpDollarMinus.au8[3] = pbApi[3];
2558 ASMAtomicXchgU32((uint32_t volatile *)pbApi, uJmpDollarMinus.u);
2559
2560 NtYieldExecution();
2561 NtYieldExecution();
2562
2563 /* Copy in the tail bytes of the patch, then xchg the jmp $-2. */
2564 if (s_aPatches[i].cbPatch > 4)
2565 memcpy(&pbApi[4], &s_aPatches[i].pabPatch[4], s_aPatches[i].cbPatch - 4);
2566 ASMAtomicXchgU32((uint32_t volatile *)pbApi, *(uint32_t *)s_aPatches[i].pabPatch);
2567 }
2568
2569 SUPR3HARDENED_ASSERT_NT_SUCCESS(supR3HardenedWinProtectMemory(pbApi, s_aPatches[i].cbPatch, PAGE_EXECUTE_READ));
2570 }
2571 }
2572}
2573
2574
2575/**
2576 * Install hooks for intercepting calls dealing with mapping shared libraries
2577 * into the process.
2578 *
2579 * This allows us to prevent undesirable shared libraries from being loaded.
2580 *
2581 * @remarks We assume we're alone in this process, so no seralizing trickery is
2582 * necessary when installing the patch.
2583 *
2584 * @remarks We would normally just copy the prologue sequence somewhere and add
2585 * a jump back at the end of it. But because we wish to avoid
2586 * allocating executable memory, we need to have preprepared assembly
2587 * "copies". This makes the non-system call patching a little tedious
2588 * and inflexible.
2589 */
2590static void supR3HardenedWinInstallHooks(void)
2591{
2592 NTSTATUS rcNt;
2593
2594 /*
2595 * Disable hard error popups so we can quietly refuse images to be loaded.
2596 */
2597 ULONG fHardErr = 0;
2598 rcNt = NtQueryInformationProcess(NtCurrentProcess(), ProcessDefaultHardErrorMode, &fHardErr, sizeof(fHardErr), NULL);
2599 if (!NT_SUCCESS(rcNt))
2600 supR3HardenedFatalMsg("supR3HardenedWinInstallHooks", kSupInitOp_Misc, VERR_GENERAL_FAILURE,
2601 "NtQueryInformationProcess/ProcessDefaultHardErrorMode failed: %#x\n", rcNt);
2602 if (fHardErr & PROCESS_HARDERR_CRITICAL_ERROR)
2603 {
2604 fHardErr &= ~PROCESS_HARDERR_CRITICAL_ERROR;
2605 rcNt = NtSetInformationProcess(NtCurrentProcess(), ProcessDefaultHardErrorMode, &fHardErr, sizeof(fHardErr));
2606 if (!NT_SUCCESS(rcNt))
2607 supR3HardenedFatalMsg("supR3HardenedWinInstallHooks", kSupInitOp_Misc, VERR_GENERAL_FAILURE,
2608 "NtSetInformationProcess/ProcessDefaultHardErrorMode failed: %#x\n", rcNt);
2609 }
2610
2611 /*
2612 * Locate the routines first so we can allocate memory that's near enough.
2613 */
2614 PFNRT pfnNtCreateSection = supR3HardenedWinGetRealDllSymbol("ntdll.dll", "NtCreateSection");
2615 SUPR3HARDENED_ASSERT(pfnNtCreateSection != NULL);
2616 //SUPR3HARDENED_ASSERT(pfnNtCreateSection == (FARPROC)NtCreateSection);
2617
2618 PFNRT pfnLdrLoadDll = supR3HardenedWinGetRealDllSymbol("ntdll.dll", "LdrLoadDll");
2619 SUPR3HARDENED_ASSERT(pfnLdrLoadDll != NULL);
2620 //SUPR3HARDENED_ASSERT(pfnLdrLoadDll == (FARPROC)LdrLoadDll);
2621
2622 /*
2623 * Exec page setup & management.
2624 */
2625 uint32_t offExecPage = 0;
2626 memset(g_abSupHardReadWriteExecPage, 0xcc, PAGE_SIZE);
2627
2628 /*
2629 * Hook #1 - NtCreateSection.
2630 * Purpose: Validate everything that can be mapped into the process before
2631 * it's mapped and we still have a file handle to work with.
2632 */
2633 uint8_t * const pbNtCreateSection = (uint8_t *)(uintptr_t)pfnNtCreateSection;
2634 g_pbNtCreateSection = pbNtCreateSection;
2635 memcpy(g_abNtCreateSectionPatch, pbNtCreateSection, sizeof(g_abNtCreateSectionPatch));
2636
2637 g_pfnNtCreateSectionReal = NtCreateSection; /* our direct syscall */
2638
2639#ifdef RT_ARCH_AMD64
2640 /*
2641 * Patch 64-bit hosts.
2642 */
2643 /* Pattern #1: XP64/W2K3-64 thru Windows 8.1
2644 0:000> u ntdll!NtCreateSection
2645 ntdll!NtCreateSection:
2646 00000000`779f1750 4c8bd1 mov r10,rcx
2647 00000000`779f1753 b847000000 mov eax,47h
2648 00000000`779f1758 0f05 syscall
2649 00000000`779f175a c3 ret
2650 00000000`779f175b 0f1f440000 nop dword ptr [rax+rax]
2651 The variant is the value loaded into eax: W2K3=??, Vista=47h?, W7=47h, W80=48h, W81=49h */
2652
2653 /* Assemble the patch. */
2654 g_abNtCreateSectionPatch[0] = 0x48; /* mov rax, qword */
2655 g_abNtCreateSectionPatch[1] = 0xb8;
2656 *(uint64_t *)&g_abNtCreateSectionPatch[2] = (uint64_t)supR3HardenedMonitor_NtCreateSection;
2657 g_abNtCreateSectionPatch[10] = 0xff; /* jmp rax */
2658 g_abNtCreateSectionPatch[11] = 0xe0;
2659
2660#else
2661 /*
2662 * Patch 32-bit hosts.
2663 */
2664 /* Pattern #1: XP thru Windows 7
2665 kd> u ntdll!NtCreateSection
2666 ntdll!NtCreateSection:
2667 7c90d160 b832000000 mov eax,32h
2668 7c90d165 ba0003fe7f mov edx,offset SharedUserData!SystemCallStub (7ffe0300)
2669 7c90d16a ff12 call dword ptr [edx]
2670 7c90d16c c21c00 ret 1Ch
2671 7c90d16f 90 nop
2672 The variable bit is the value loaded into eax: XP=32h, W2K3=34h, Vista=4bh, W7=54h
2673
2674 Pattern #2: Windows 8.1
2675 0:000:x86> u ntdll_6a0f0000!NtCreateSection
2676 ntdll_6a0f0000!NtCreateSection:
2677 6a15eabc b854010000 mov eax,154h
2678 6a15eac1 e803000000 call ntdll_6a0f0000!NtCreateSection+0xd (6a15eac9)
2679 6a15eac6 c21c00 ret 1Ch
2680 6a15eac9 8bd4 mov edx,esp
2681 6a15eacb 0f34 sysenter
2682 6a15eacd c3 ret
2683 The variable bit is the value loaded into eax: W81=154h */
2684
2685 /* Assemble the patch. */
2686 g_abNtCreateSectionPatch[0] = 0xe9; /* jmp rel32 */
2687 *(uint32_t *)&g_abNtCreateSectionPatch[1] = (uintptr_t)supR3HardenedMonitor_NtCreateSection
2688 - (uintptr_t)&pbNtCreateSection[1+4];
2689
2690#endif
2691
2692 /*
2693 * Hook #2 - LdrLoadDll
2694 * Purpose: (a) Enforce LdrLoadDll search path constraints, and (b) pre-validate
2695 * DLLs so we can avoid calling WinVerifyTrust from the first hook,
2696 * and thus avoiding messing up the loader data on some installations.
2697 *
2698 * This differs from the above function in that is no a system call and
2699 * we're at the mercy of the compiler.
2700 */
2701 uint8_t * const pbLdrLoadDll = (uint8_t *)(uintptr_t)pfnLdrLoadDll;
2702 g_pbLdrLoadDll = pbLdrLoadDll;
2703 memcpy(g_abLdrLoadDllPatch, pbLdrLoadDll, sizeof(g_abLdrLoadDllPatch));
2704
2705 DISSTATE Dis;
2706 uint32_t cbInstr;
2707 uint32_t offJmpBack = 0;
2708
2709#ifdef RT_ARCH_AMD64
2710 /*
2711 * Patch 64-bit hosts.
2712 */
2713 /* Just use the disassembler to skip 12 bytes or more. */
2714 while (offJmpBack < 12)
2715 {
2716 cbInstr = 1;
2717 int rc = DISInstr(pbLdrLoadDll + offJmpBack, DISCPUMODE_64BIT, &Dis, &cbInstr);
2718 if ( RT_FAILURE(rc)
2719 || (Dis.pCurInstr->fOpType & (DISOPTYPE_CONTROLFLOW))
2720 || (Dis.ModRM.Bits.Mod == 0 && Dis.ModRM.Bits.Rm == 5 /* wrt RIP */) )
2721 supR3HardenedWinHookFailed("LdrLoadDll", pbLdrLoadDll);
2722 offJmpBack += cbInstr;
2723 }
2724
2725 /* Assemble the code for resuming the call.*/
2726 *(PFNRT *)&g_pfnLdrLoadDllReal = (PFNRT)(uintptr_t)&g_abSupHardReadWriteExecPage[offExecPage];
2727
2728 memcpy(&g_abSupHardReadWriteExecPage[offExecPage], pbLdrLoadDll, offJmpBack);
2729 offExecPage += offJmpBack;
2730
2731 g_abSupHardReadWriteExecPage[offExecPage++] = 0xff; /* jmp qword [$+8 wrt RIP] */
2732 g_abSupHardReadWriteExecPage[offExecPage++] = 0x25;
2733 *(uint32_t *)&g_abSupHardReadWriteExecPage[offExecPage] = RT_ALIGN_32(offExecPage + 4, 8) - (offExecPage + 4);
2734 offExecPage = RT_ALIGN_32(offExecPage + 4, 8);
2735 *(uint64_t *)&g_abSupHardReadWriteExecPage[offExecPage] = (uintptr_t)&pbLdrLoadDll[offJmpBack];
2736 offExecPage = RT_ALIGN_32(offExecPage + 8, 16);
2737
2738 /* Assemble the LdrLoadDll patch. */
2739 Assert(offJmpBack >= 12);
2740 g_abLdrLoadDllPatch[0] = 0x48; /* mov rax, qword */
2741 g_abLdrLoadDllPatch[1] = 0xb8;
2742 *(uint64_t *)&g_abLdrLoadDllPatch[2] = (uint64_t)supR3HardenedMonitor_LdrLoadDll;
2743 g_abLdrLoadDllPatch[10] = 0xff; /* jmp rax */
2744 g_abLdrLoadDllPatch[11] = 0xe0;
2745
2746#else
2747 /*
2748 * Patch 32-bit hosts.
2749 */
2750 /* Just use the disassembler to skip 5 bytes or more. */
2751 while (offJmpBack < 5)
2752 {
2753 cbInstr = 1;
2754 int rc = DISInstr(pbLdrLoadDll + offJmpBack, DISCPUMODE_32BIT, &Dis, &cbInstr);
2755 if ( RT_FAILURE(rc)
2756 || (Dis.pCurInstr->fOpType & (DISOPTYPE_CONTROLFLOW)) )
2757 supR3HardenedWinHookFailed("LdrLoadDll", pbLdrLoadDll);
2758 offJmpBack += cbInstr;
2759 }
2760
2761 /* Assemble the code for resuming the call.*/
2762 *(PFNRT *)&g_pfnLdrLoadDllReal = (PFNRT)(uintptr_t)&g_abSupHardReadWriteExecPage[offExecPage];
2763
2764 memcpy(&g_abSupHardReadWriteExecPage[offExecPage], pbLdrLoadDll, offJmpBack);
2765 offExecPage += offJmpBack;
2766
2767 g_abSupHardReadWriteExecPage[offExecPage++] = 0xe9; /* jmp rel32 */
2768 *(uint32_t *)&g_abSupHardReadWriteExecPage[offExecPage] = (uintptr_t)&pbLdrLoadDll[offJmpBack]
2769 - (uintptr_t)&g_abSupHardReadWriteExecPage[offExecPage + 4];
2770 offExecPage = RT_ALIGN_32(offExecPage + 4, 16);
2771
2772 /* Assemble the LdrLoadDll patch. */
2773 memcpy(g_abLdrLoadDllPatch, pbLdrLoadDll, sizeof(g_abLdrLoadDllPatch));
2774 Assert(offJmpBack >= 5);
2775 g_abLdrLoadDllPatch[0] = 0xe9;
2776 *(uint32_t *)&g_abLdrLoadDllPatch[1] = (uintptr_t)supR3HardenedMonitor_LdrLoadDll - (uintptr_t)&pbLdrLoadDll[1+4];
2777#endif
2778
2779 /*
2780 * Seal the rwx page.
2781 */
2782 SUPR3HARDENED_ASSERT_NT_SUCCESS(supR3HardenedWinProtectMemory(g_abSupHardReadWriteExecPage, PAGE_SIZE, PAGE_EXECUTE_READ));
2783
2784 /*
2785 * Install the patches.
2786 */
2787 supR3HardenedWinReInstallHooks(true /*fFirstCall*/);
2788}
2789
2790
2791
2792
2793
2794
2795/*
2796 *
2797 * T h r e a d c r e a t i o n c o n t r o l
2798 * T h r e a d c r e a t i o n c o n t r o l
2799 * T h r e a d c r e a t i o n c o n t r o l
2800 *
2801 */
2802
2803
2804/**
2805 * Common code used for child and parent to make new threads exit immediately.
2806 *
2807 * This patches the LdrInitializeThunk code to call NtTerminateThread with
2808 * STATUS_SUCCESS instead of doing the NTDLL initialization.
2809 *
2810 * @returns VBox status code.
2811 * @param hProcess The process to do this to.
2812 * @param pvLdrInitThunk The address of the LdrInitializeThunk code to
2813 * override.
2814 * @param pvNtTerminateThread The address of the NtTerminateThread function in
2815 * the NTDLL instance we're patching. (Must be +/-
2816 * 2GB from the thunk code.)
2817 * @param pabBackup Where to back up the original instruction bytes
2818 * at pvLdrInitThunk.
2819 * @param cbBackup The size of the backup area. Must be 16 bytes.
2820 * @param pErrInfo Where to return extended error information.
2821 * Optional.
2822 */
2823static int supR3HardNtDisableThreadCreationEx(HANDLE hProcess, void *pvLdrInitThunk, void *pvNtTerminateThread,
2824 uint8_t *pabBackup, size_t cbBackup, PRTERRINFO pErrInfo)
2825{
2826 SUP_DPRINTF(("supR3HardNtDisableThreadCreation: pvLdrInitThunk=%p pvNtTerminateThread=%p\n", pvLdrInitThunk, pvNtTerminateThread));
2827 SUPR3HARDENED_ASSERT(cbBackup == 16);
2828 SUPR3HARDENED_ASSERT(RT_ABS((intptr_t)pvLdrInitThunk - (intptr_t)pvNtTerminateThread) < 16*_1M);
2829
2830 /*
2831 * Back up the thunk code.
2832 */
2833 SIZE_T cbIgnored;
2834 NTSTATUS rcNt = NtReadVirtualMemory(hProcess, pvLdrInitThunk, pabBackup, cbBackup, &cbIgnored);
2835 if (!NT_SUCCESS(rcNt))
2836 return RTErrInfoSetF(pErrInfo, VERR_GENERAL_FAILURE,
2837 "supR3HardNtDisableThreadCreation: NtReadVirtualMemory/LdrInitializeThunk failed: %#x", rcNt);
2838
2839 /*
2840 * Cook up replacement code that calls NtTerminateThread.
2841 */
2842 uint8_t abReplacement[16];
2843 memcpy(abReplacement, pabBackup, sizeof(abReplacement));
2844
2845#ifdef RT_ARCH_AMD64
2846 abReplacement[0] = 0x31; /* xor ecx, ecx */
2847 abReplacement[1] = 0xc9;
2848 abReplacement[2] = 0x31; /* xor edx, edx */
2849 abReplacement[3] = 0xd2;
2850 abReplacement[4] = 0xe8; /* call near NtTerminateThread */
2851 *(int32_t *)&abReplacement[5] = (int32_t)((uintptr_t)pvNtTerminateThread - ((uintptr_t)pvLdrInitThunk + 9));
2852 abReplacement[9] = 0xcc; /* int3 */
2853#elif defined(RT_ARCH_X86)
2854 abReplacement[0] = 0x6a; /* push 0 */
2855 abReplacement[1] = 0x00;
2856 abReplacement[2] = 0x6a; /* push 0 */
2857 abReplacement[3] = 0x00;
2858 abReplacement[4] = 0xe8; /* call near NtTerminateThread */
2859 *(int32_t *)&abReplacement[5] = (int32_t)((uintptr_t)pvNtTerminateThread - ((uintptr_t)pvLdrInitThunk + 9));
2860 abReplacement[9] = 0xcc; /* int3 */
2861#else
2862# error "Unsupported arch."
2863#endif
2864
2865 /*
2866 * Install the replacment code.
2867 */
2868 PVOID pvProt = pvLdrInitThunk;
2869 SIZE_T cbProt = cbBackup;
2870 ULONG fOldProt = 0;
2871 rcNt = NtProtectVirtualMemory(hProcess, &pvProt, &cbProt, PAGE_EXECUTE_READWRITE, &fOldProt);
2872 if (!NT_SUCCESS(rcNt))
2873 return RTErrInfoSetF(pErrInfo, VERR_GENERAL_FAILURE,
2874 "supR3HardNtDisableThreadCreationEx: NtProtectVirtualMemory/LdrInitializeThunk failed: %#x", rcNt);
2875
2876 rcNt = NtWriteVirtualMemory(hProcess, pvLdrInitThunk, abReplacement, sizeof(abReplacement), &cbIgnored);
2877 if (!NT_SUCCESS(rcNt))
2878 return RTErrInfoSetF(pErrInfo, VERR_GENERAL_FAILURE,
2879 "supR3HardNtDisableThreadCreationEx: NtWriteVirtualMemory/LdrInitializeThunk failed: %#x", rcNt);
2880
2881 pvProt = pvLdrInitThunk;
2882 cbProt = cbBackup;
2883 rcNt = NtProtectVirtualMemory(hProcess, &pvProt, &cbProt, fOldProt, &fOldProt);
2884 if (!NT_SUCCESS(rcNt))
2885 return RTErrInfoSetF(pErrInfo, VERR_GENERAL_FAILURE,
2886 "supR3HardNtDisableThreadCreationEx: NtProtectVirtualMemory/LdrInitializeThunk/2 failed: %#x", rcNt);
2887
2888 return VINF_SUCCESS;
2889}
2890
2891
2892/**
2893 * Undo the effects of supR3HardNtDisableThreadCreationEx.
2894 *
2895 * @returns VBox status code.
2896 * @param hProcess The process to do this to.
2897 * @param pvLdrInitThunk The address of the LdrInitializeThunk code to
2898 * override.
2899 * @param pabBackup Where to back up the original instruction bytes
2900 * at pvLdrInitThunk.
2901 * @param cbBackup The size of the backup area. Must be 16 bytes.
2902 * @param pErrInfo Where to return extended error information.
2903 * Optional.
2904 */
2905static int supR3HardNtEnableThreadCreationEx(HANDLE hProcess, void *pvLdrInitThunk, uint8_t const *pabBackup, size_t cbBackup,
2906 PRTERRINFO pErrInfo)
2907{
2908 SUP_DPRINTF(("supR3HardNtEnableThreadCreation:\n"));
2909 SUPR3HARDENED_ASSERT(cbBackup == 16);
2910
2911 PVOID pvProt = pvLdrInitThunk;
2912 SIZE_T cbProt = cbBackup;
2913 ULONG fOldProt = 0;
2914 NTSTATUS rcNt = NtProtectVirtualMemory(hProcess, &pvProt, &cbProt, PAGE_EXECUTE_READWRITE, &fOldProt);
2915 if (!NT_SUCCESS(rcNt))
2916 return RTErrInfoSetF(pErrInfo, VERR_GENERAL_FAILURE,
2917 "supR3HardNtDisableThreadCreationEx: NtProtectVirtualMemory/LdrInitializeThunk failed: %#x", rcNt);
2918
2919 SIZE_T cbIgnored;
2920 rcNt = NtWriteVirtualMemory(hProcess, pvLdrInitThunk, pabBackup, cbBackup, &cbIgnored);
2921 if (!NT_SUCCESS(rcNt))
2922 return RTErrInfoSetF(pErrInfo, VERR_GENERAL_FAILURE,
2923 "supR3HardNtEnableThreadCreation: NtWriteVirtualMemory/LdrInitializeThunk[restore] failed: %#x",
2924 rcNt);
2925
2926 pvProt = pvLdrInitThunk;
2927 cbProt = cbBackup;
2928 rcNt = NtProtectVirtualMemory(hProcess, &pvProt, &cbProt, fOldProt, &fOldProt);
2929 if (!NT_SUCCESS(rcNt))
2930 return RTErrInfoSetF(pErrInfo, VERR_GENERAL_FAILURE,
2931 "supR3HardNtEnableThreadCreation: NtProtectVirtualMemory/LdrInitializeThunk[restore] failed: %#x",
2932 rcNt);
2933
2934 return VINF_SUCCESS;
2935}
2936
2937
2938/**
2939 * Disable thread creation for the current process.
2940 *
2941 * @remarks Doesn't really disables it, just makes the threads exit immediately
2942 * without executing any real code.
2943 */
2944static void supR3HardenedWinDisableThreadCreation(void)
2945{
2946 /* Cannot use the imported NtTerminateThread as it's pointing to our own
2947 syscall assembly code. */
2948 static PFNRT s_pfnNtTerminateThread = NULL;
2949 if (s_pfnNtTerminateThread == NULL)
2950 s_pfnNtTerminateThread = supR3HardenedWinGetRealDllSymbol("ntdll.dll", "NtTerminateThread");
2951 SUPR3HARDENED_ASSERT(s_pfnNtTerminateThread);
2952
2953 int rc = supR3HardNtDisableThreadCreationEx(NtCurrentProcess(),
2954 (void *)(uintptr_t)&LdrInitializeThunk,
2955 (void *)(uintptr_t)s_pfnNtTerminateThread,
2956 g_abLdrInitThunkSelfBackup, sizeof(g_abLdrInitThunkSelfBackup),
2957 NULL /* pErrInfo*/);
2958 g_fSupInitThunkSelfPatched = RT_SUCCESS(rc);
2959}
2960
2961
2962/**
2963 * Undoes the effects of supR3HardenedWinDisableThreadCreation.
2964 */
2965DECLHIDDEN(void) supR3HardenedWinEnableThreadCreation(void)
2966{
2967 if (g_fSupInitThunkSelfPatched)
2968 {
2969 int rc = supR3HardNtEnableThreadCreationEx(NtCurrentProcess(),
2970 (void *)(uintptr_t)&LdrInitializeThunk,
2971 g_abLdrInitThunkSelfBackup, sizeof(g_abLdrInitThunkSelfBackup),
2972 RTErrInfoInitStatic(&g_ErrInfoStatic));
2973 if (RT_FAILURE(rc))
2974 supR3HardenedError(rc, true /*fFatal*/, "%s", g_ErrInfoStatic.szMsg);
2975 g_fSupInitThunkSelfPatched = false;
2976 }
2977}
2978
2979
2980
2981
2982/*
2983 *
2984 * R e s p a w n
2985 * R e s p a w n
2986 * R e s p a w n
2987 *
2988 */
2989
2990
2991/**
2992 * Gets the SID of the user associated with the process.
2993 *
2994 * @returns @c true if we've got a login SID, @c false if not.
2995 * @param pSidUser Where to return the user SID.
2996 * @param cbSidUser The size of the user SID buffer.
2997 * @param pSidLogin Where to return the login SID.
2998 * @param cbSidLogin The size of the login SID buffer.
2999 */
3000static bool supR3HardNtChildGetUserAndLogSids(PSID pSidUser, ULONG cbSidUser, PSID pSidLogin, ULONG cbSidLogin)
3001{
3002 HANDLE hToken;
3003 SUPR3HARDENED_ASSERT_NT_SUCCESS(NtOpenProcessToken(NtCurrentProcess(), TOKEN_QUERY, &hToken));
3004 union
3005 {
3006 TOKEN_USER UserInfo;
3007 TOKEN_GROUPS Groups;
3008 uint8_t abPadding[4096];
3009 } uBuf;
3010 ULONG cbRet = 0;
3011 SUPR3HARDENED_ASSERT_NT_SUCCESS(NtQueryInformationToken(hToken, TokenUser, &uBuf, sizeof(uBuf), &cbRet));
3012 SUPR3HARDENED_ASSERT_NT_SUCCESS(RtlCopySid(cbSidUser, pSidUser, uBuf.UserInfo.User.Sid));
3013
3014 bool fLoginSid = false;
3015 NTSTATUS rcNt = NtQueryInformationToken(hToken, TokenLogonSid, &uBuf, sizeof(uBuf), &cbRet);
3016 if (NT_SUCCESS(rcNt))
3017 {
3018 for (DWORD i = 0; i < uBuf.Groups.GroupCount; i++)
3019 if ((uBuf.Groups.Groups[i].Attributes & SE_GROUP_LOGON_ID) == SE_GROUP_LOGON_ID)
3020 {
3021 SUPR3HARDENED_ASSERT_NT_SUCCESS(RtlCopySid(cbSidLogin, pSidLogin, uBuf.Groups.Groups[i].Sid));
3022 fLoginSid = true;
3023 break;
3024 }
3025 }
3026
3027 SUPR3HARDENED_ASSERT_NT_SUCCESS(NtClose(hToken));
3028
3029 return fLoginSid;
3030}
3031
3032
3033/**
3034 * Build security attributes for the process or the primary thread (@a fProcess)
3035 *
3036 * Process DACLs can be bypassed using the SeDebugPrivilege (generally available
3037 * to admins, i.e. normal windows users), or by taking ownership and/or
3038 * modifying the DACL. However, it restricts
3039 *
3040 * @param pSecAttrs Where to return the security attributes.
3041 * @param pCleanup Cleanup record.
3042 * @param fProcess Set if it's for the process, clear if it's for
3043 * the primary thread.
3044 */
3045static void supR3HardNtChildInitSecAttrs(PSECURITY_ATTRIBUTES pSecAttrs, PMYSECURITYCLEANUP pCleanup, bool fProcess)
3046{
3047 /*
3048 * Safe return values.
3049 */
3050 suplibHardenedMemSet(pCleanup, 0, sizeof(*pCleanup));
3051
3052 pSecAttrs->nLength = sizeof(*pSecAttrs);
3053 pSecAttrs->bInheritHandle = FALSE;
3054 pSecAttrs->lpSecurityDescriptor = NULL;
3055
3056/** @todo This isn't at all complete, just sketches... */
3057
3058 /*
3059 * Create an ACL detailing the access of the above groups.
3060 */
3061 SUPR3HARDENED_ASSERT_NT_SUCCESS(RtlCreateAcl(&pCleanup->Acl.AclHdr, sizeof(pCleanup->Acl), ACL_REVISION));
3062
3063 ULONG fDeny = DELETE | WRITE_DAC | WRITE_OWNER;
3064 ULONG fAllow = SYNCHRONIZE | READ_CONTROL;
3065 ULONG fAllowLogin = SYNCHRONIZE | READ_CONTROL;
3066 if (fProcess)
3067 {
3068 fDeny |= PROCESS_CREATE_THREAD | PROCESS_SET_SESSIONID | PROCESS_VM_OPERATION | PROCESS_VM_WRITE
3069 | PROCESS_CREATE_PROCESS | PROCESS_DUP_HANDLE | PROCESS_SET_QUOTA
3070 | PROCESS_SET_INFORMATION | PROCESS_SUSPEND_RESUME;
3071 fAllow |= PROCESS_TERMINATE | PROCESS_VM_READ | PROCESS_QUERY_INFORMATION;
3072 fAllowLogin |= PROCESS_TERMINATE | PROCESS_VM_READ | PROCESS_QUERY_INFORMATION;
3073 if (g_uNtVerCombined >= SUP_MAKE_NT_VER_SIMPLE(6, 0)) /* Introduced in Vista. */
3074 {
3075 fAllow |= PROCESS_QUERY_LIMITED_INFORMATION;
3076 fAllowLogin |= PROCESS_QUERY_LIMITED_INFORMATION;
3077 }
3078 if (g_uNtVerCombined >= SUP_MAKE_NT_VER_SIMPLE(6, 3)) /* Introduced in Windows 8.1. */
3079 fAllow |= PROCESS_SET_LIMITED_INFORMATION;
3080 }
3081 else
3082 {
3083 fDeny |= THREAD_SUSPEND_RESUME | THREAD_SET_CONTEXT | THREAD_SET_INFORMATION | THREAD_SET_THREAD_TOKEN
3084 | THREAD_IMPERSONATE | THREAD_DIRECT_IMPERSONATION;
3085 fAllow |= THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION;
3086 fAllowLogin |= THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION;
3087 if (g_uNtVerCombined >= SUP_MAKE_NT_VER_SIMPLE(6, 0)) /* Introduced in Vista. */
3088 {
3089 fAllow |= THREAD_QUERY_LIMITED_INFORMATION | THREAD_SET_LIMITED_INFORMATION;
3090 fAllowLogin |= THREAD_QUERY_LIMITED_INFORMATION;
3091 }
3092
3093 }
3094 fDeny |= ~fAllow & (SPECIFIC_RIGHTS_ALL | STANDARD_RIGHTS_ALL);
3095
3096 /* Deny everyone access to bad bits. */
3097#if 1
3098 SID_IDENTIFIER_AUTHORITY SIDAuthWorld = SECURITY_WORLD_SID_AUTHORITY;
3099 SUPR3HARDENED_ASSERT_NT_SUCCESS(RtlInitializeSid(&pCleanup->Everyone.Sid, &SIDAuthWorld, 1));
3100 *RtlSubAuthoritySid(&pCleanup->Everyone.Sid, 0) = SECURITY_WORLD_RID;
3101 SUPR3HARDENED_ASSERT_NT_SUCCESS(RtlAddAccessDeniedAce(&pCleanup->Acl.AclHdr, ACL_REVISION,
3102 fDeny, &pCleanup->Everyone.Sid));
3103#endif
3104
3105#if 0
3106 /* Grant some access to the owner - doesn't work. */
3107 SID_IDENTIFIER_AUTHORITY SIDAuthCreator = SECURITY_CREATOR_SID_AUTHORITY;
3108 SUPR3HARDENED_ASSERT_NT_SUCCESS(RtlInitializeSid(&pCleanup->Owner.Sid, &SIDAuthCreator, 1));
3109 *RtlSubAuthoritySid(&pCleanup->Owner.Sid, 0) = SECURITY_CREATOR_OWNER_RID;
3110
3111 SUPR3HARDENED_ASSERT_NT_SUCCESS(RtlAddAccessDeniedAce(&pCleanup->Acl.AclHdr, ACL_REVISION,
3112 fDeny, &pCleanup->Owner.Sid));
3113 SUPR3HARDENED_ASSERT_NT_SUCCESS(RtlAddAccessAllowedAce(&pCleanup->Acl.AclHdr, ACL_REVISION,
3114 fAllow, &pCleanup->Owner.Sid));
3115#endif
3116
3117#if 1
3118 bool fHasLoginSid = supR3HardNtChildGetUserAndLogSids(&pCleanup->User.Sid, sizeof(pCleanup->User),
3119 &pCleanup->Login.Sid, sizeof(pCleanup->Login));
3120
3121# if 1
3122 /* Grant minimal access to the user. */
3123 SUPR3HARDENED_ASSERT_NT_SUCCESS(RtlAddAccessDeniedAce(&pCleanup->Acl.AclHdr, ACL_REVISION,
3124 fDeny, &pCleanup->User.Sid));
3125 SUPR3HARDENED_ASSERT_NT_SUCCESS(RtlAddAccessAllowedAce(&pCleanup->Acl.AclHdr, ACL_REVISION,
3126 fAllow, &pCleanup->User.Sid));
3127# endif
3128
3129# if 1
3130 /* Grant very limited access to the login sid. */
3131 if (fHasLoginSid)
3132 {
3133 SUPR3HARDENED_ASSERT_NT_SUCCESS(RtlAddAccessAllowedAce(&pCleanup->Acl.AclHdr, ACL_REVISION,
3134 fAllowLogin, &pCleanup->Login.Sid));
3135 }
3136# endif
3137
3138#endif
3139
3140 /*
3141 * Create a security descriptor with the above ACL.
3142 */
3143 PSECURITY_DESCRIPTOR pSecDesc = (PSECURITY_DESCRIPTOR)RTMemAllocZ(SECURITY_DESCRIPTOR_MIN_LENGTH);
3144 pCleanup->pSecDesc = pSecDesc;
3145
3146 SUPR3HARDENED_ASSERT_NT_SUCCESS(RtlCreateSecurityDescriptor(pSecDesc, SECURITY_DESCRIPTOR_REVISION));
3147 SUPR3HARDENED_ASSERT_NT_SUCCESS(RtlSetDaclSecurityDescriptor(pSecDesc, TRUE /*fDaclPresent*/, &pCleanup->Acl.AclHdr,
3148 FALSE /*fDaclDefaulted*/));
3149 pSecAttrs->lpSecurityDescriptor = pSecDesc;
3150}
3151
3152
3153/**
3154 * Predicate function which tests whether @a ch is a argument separator
3155 * character.
3156 *
3157 * @returns True/false.
3158 * @param ch The character to examine.
3159 */
3160DECLINLINE(bool) suplibCommandLineIsArgSeparator(int ch)
3161{
3162 return ch == ' '
3163 || ch == '\t'
3164 || ch == '\n'
3165 || ch == '\r';
3166}
3167
3168
3169/**
3170 * Construct the new command line.
3171 *
3172 * Since argc/argv are both derived from GetCommandLineW (see
3173 * suplibHardenedWindowsMain), we skip the argument by argument UTF-8 -> UTF-16
3174 * conversion and quoting by going to the original source.
3175 *
3176 * The executable name, though, is replaced in case it's not a fullly
3177 * qualified path.
3178 *
3179 * The re-spawn indicator is added immediately after the executable name
3180 * so that we don't get tripped up missing close quote chars in the last
3181 * argument.
3182 *
3183 * @returns Pointer to a command line string (heap).
3184 * @param pString Unicode string structure to initialize to the
3185 * command line. Optional.
3186 * @param iWhich Which respawn we're to check for, 1 being the first
3187 * one, and 2 the second and final.
3188 */
3189static PRTUTF16 supR3HardNtChildConstructCmdLine(PUNICODE_STRING pString, int iWhich)
3190{
3191 SUPR3HARDENED_ASSERT(iWhich == 1 || iWhich == 2);
3192
3193 /*
3194 * Get the command line and skip the executable name.
3195 */
3196 PUNICODE_STRING pCmdLineStr = &NtCurrentPeb()->ProcessParameters->CommandLine;
3197 PCRTUTF16 pawcArgs = pCmdLineStr->Buffer;
3198 uint32_t cwcArgs = pCmdLineStr->Length / sizeof(WCHAR);
3199
3200 /* Skip leading space (shouldn't be any, but whatever). */
3201 while (cwcArgs > 0 && suplibCommandLineIsArgSeparator(*pawcArgs) )
3202 cwcArgs--, pawcArgs++;
3203 SUPR3HARDENED_ASSERT(cwcArgs > 0 && *pawcArgs != '\0');
3204
3205 /* Walk to the end of it. */
3206 int fQuoted = false;
3207 do
3208 {
3209 if (*pawcArgs == '"')
3210 {
3211 fQuoted = !fQuoted;
3212 cwcArgs--; pawcArgs++;
3213 }
3214 else if (*pawcArgs != '\\' || (pawcArgs[1] != '\\' && pawcArgs[1] != '"'))
3215 cwcArgs--, pawcArgs++;
3216 else
3217 {
3218 unsigned cSlashes = 0;
3219 do
3220 {
3221 cSlashes++;
3222 cwcArgs--;
3223 pawcArgs++;
3224 }
3225 while (cwcArgs > 0 && *pawcArgs == '\\');
3226 if (cwcArgs > 0 && *pawcArgs == '"' && (cSlashes & 1))
3227 cwcArgs--, pawcArgs++; /* odd number of slashes == escaped quote */
3228 }
3229 } while (cwcArgs > 0 && (fQuoted || !suplibCommandLineIsArgSeparator(*pawcArgs)));
3230
3231 /* Skip trailing spaces. */
3232 while (cwcArgs > 0 && suplibCommandLineIsArgSeparator(*pawcArgs))
3233 cwcArgs--, pawcArgs++;
3234
3235 /*
3236 * Allocate a new buffer.
3237 */
3238 AssertCompile(sizeof(SUPR3_RESPAWN_1_ARG0) == sizeof(SUPR3_RESPAWN_2_ARG0));
3239 size_t cwcCmdLine = (sizeof(SUPR3_RESPAWN_1_ARG0) - 1) / sizeof(SUPR3_RESPAWN_1_ARG0[0]) /* Respawn exe name. */
3240 + !!cwcArgs + cwcArgs; /* if arguments present, add space + arguments. */
3241 if (cwcCmdLine * sizeof(WCHAR) >= 0xfff0)
3242 supR3HardenedFatalMsg("supR3HardNtChildConstructCmdLine", kSupInitOp_Misc, VERR_OUT_OF_RANGE,
3243 "Command line is too long (%u chars)!", cwcCmdLine);
3244
3245 PRTUTF16 pwszCmdLine = (PRTUTF16)RTMemAlloc((cwcCmdLine + 1) * sizeof(RTUTF16));
3246 SUPR3HARDENED_ASSERT(pwszCmdLine != NULL);
3247
3248 /*
3249 * Construct the new command line.
3250 */
3251 PRTUTF16 pwszDst = pwszCmdLine;
3252 for (const char *pszSrc = iWhich == 1 ? SUPR3_RESPAWN_1_ARG0 : SUPR3_RESPAWN_2_ARG0; *pszSrc; pszSrc++)
3253 *pwszDst++ = *pszSrc;
3254
3255 if (cwcArgs)
3256 {
3257 *pwszDst++ = ' ';
3258 suplibHardenedMemCopy(pwszDst, pawcArgs, cwcArgs * sizeof(RTUTF16));
3259 pwszDst += cwcArgs;
3260 }
3261
3262 *pwszDst = '\0';
3263 SUPR3HARDENED_ASSERT((uintptr_t)(pwszDst - pwszCmdLine) == cwcCmdLine);
3264
3265 if (pString)
3266 {
3267 pString->Buffer = pwszCmdLine;
3268 pString->Length = (USHORT)(cwcCmdLine * sizeof(WCHAR));
3269 pString->MaximumLength = pString->Length + sizeof(WCHAR);
3270 }
3271 return pwszCmdLine;
3272}
3273
3274
3275/**
3276 * Terminates the child process.
3277 *
3278 * @param hProcess The process handle.
3279 * @param pszWhere Who's having child rasing troubles.
3280 * @param rc The status code to report.
3281 * @param pszFormat The message format string.
3282 * @param ... Message format arguments.
3283 */
3284static void supR3HardenedWinKillChild(HANDLE hProcess, const char *pszWhere, int rc, const char *pszFormat, ...)
3285{
3286 /*
3287 * Terminate the process ASAP and display error.
3288 */
3289 NtTerminateProcess(hProcess, RTEXITCODE_FAILURE);
3290
3291 va_list va;
3292 va_start(va, pszFormat);
3293 supR3HardenedErrorV(rc, false /*fFatal*/, pszFormat, va);
3294 va_end(va);
3295
3296 /*
3297 * Wait for the process to really go away.
3298 */
3299 PROCESS_BASIC_INFORMATION BasicInfo;
3300 NTSTATUS rcNtExit = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &BasicInfo, sizeof(BasicInfo), NULL);
3301 bool fExitOk = NT_SUCCESS(rcNtExit) && BasicInfo.ExitStatus != STATUS_PENDING;
3302 if (!fExitOk)
3303 {
3304 NTSTATUS rcNtWait;
3305 uint64_t uMsTsStart = supR3HardenedWinGetMilliTS();
3306 do
3307 {
3308 NtTerminateProcess(hProcess, DBG_TERMINATE_PROCESS);
3309
3310 LARGE_INTEGER Timeout;
3311 Timeout.QuadPart = -20000000; /* 2 second */
3312 rcNtWait = NtWaitForSingleObject(hProcess, TRUE /*Alertable*/, &Timeout);
3313
3314 rcNtExit = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &BasicInfo, sizeof(BasicInfo), NULL);
3315 fExitOk = NT_SUCCESS(rcNtExit) && BasicInfo.ExitStatus != STATUS_PENDING;
3316 } while ( !fExitOk
3317 && ( rcNtWait == STATUS_TIMEOUT
3318 || rcNtWait == STATUS_USER_APC
3319 || rcNtWait == STATUS_ALERTED)
3320 && supR3HardenedWinGetMilliTS() - uMsTsStart < 60 * 1000);
3321 if (fExitOk)
3322 supR3HardenedError(rc, false /*fFatal*/,
3323 "NtDuplicateObject failed and we failed to kill child: rc=%u (%#x) rcNtWait=%#x hProcess=%p\n",
3324 rc, rc, rcNtWait, hProcess);
3325 }
3326
3327 /*
3328 * Final error message.
3329 */
3330 va_start(va, pszFormat);
3331 supR3HardenedFatalMsgV(pszWhere, kSupInitOp_Misc, rc, pszFormat, va);
3332 /* not reached */
3333}
3334
3335
3336/**
3337 * Checks the child process when hEvtParent is signalled.
3338 *
3339 * This will read the request data from the child and check it against expected
3340 * request. If an error is signalled, we'll raise it and make sure the child
3341 * terminates before terminating the calling process.
3342 *
3343 * @param pThis The child process data structure.
3344 * @param enmExpectedRequest The expected child request.
3345 * @param pszWhat What we're waiting for.
3346 */
3347static void supR3HardNtChildProcessRequest(PSUPR3HARDNTCHILD pThis, SUPR3WINCHILDREQ enmExpectedRequest, const char *pszWhat)
3348{
3349 /*
3350 * Read the process parameters from the child.
3351 */
3352 uintptr_t uChildAddr = (uintptr_t)pThis->Peb.ImageBaseAddress
3353 + ((uintptr_t)&g_ProcParams - (uintptr_t)NtCurrentPeb()->ImageBaseAddress);
3354 SIZE_T cbIgnored = 0;
3355 RT_ZERO(pThis->ProcParams);
3356 NTSTATUS rcNt = NtReadVirtualMemory(pThis->hProcess, (PVOID)uChildAddr,
3357 &pThis->ProcParams, sizeof(pThis->ProcParams), &cbIgnored);
3358 if (!NT_SUCCESS(rcNt))
3359 supR3HardenedWinKillChild(pThis, "supR3HardNtChildProcessRequest", rcNt,
3360 "NtReadVirtualMemory(,%p,) failed reading child process status: %#x\n", uChildAddr, rcNt);
3361
3362 /*
3363 * Is it the expected request?
3364 */
3365 if (pThis->ProcParams.enmRequest == enmExpectedRequest)
3366 return;
3367
3368 /*
3369 * No, not the expected request. If it's an error request, tell the child
3370 * to terminate itself, otherwise we'll have to terminate it.
3371 */
3372 pThis->ProcParams.szErrorMsg[sizeof(pThis->ProcParams.szErrorMsg) - 1] = '\0';
3373 pThis->ProcParams.szWhere[sizeof(pThis->ProcParams.szWhere) - 1] = '\0';
3374 SUP_DPRINTF(("supR3HardenedWinCheckChild: enmRequest=%d rc=%d enmWhat=%d %s: %s\n",
3375 pThis->ProcParams.enmRequest, pThis->ProcParams.rc, pThis->ProcParams.enmWhat,
3376 pThis->ProcParams.szWhere, pThis->ProcParams.szErrorMsg));
3377
3378 if (pThis->ProcParams.enmRequest != kSupR3WinChildReq_Error)
3379 supR3HardenedWinKillChild(pThis, "supR3HardenedWinCheckChild", VERR_INVALID_PARAMETER,
3380 "Unexpected child request #%d. Was expecting #%d (%s).\n",
3381 pThis->ProcParams.enmRequest, enmExpectedRequest, pszWhat);
3382
3383 rcNt = NtSetEvent(pThis->hEvtChild, NULL);
3384 if (!NT_SUCCESS(rcNt))
3385 supR3HardenedWinKillChild(pThis, "supR3HardNtChildProcessRequest", rcNt, "NtSetEvent failed: %#x\n", rcNt);
3386
3387 /* Wait for it to terminate. */
3388 LARGE_INTEGER Timeout;
3389 Timeout.QuadPart = -50000000; /* 5 seconds */
3390 rcNt = NtWaitForSingleObject(pThis->hProcess, FALSE /*Alertable*/, &Timeout);
3391 if (rcNt != STATUS_WAIT_0)
3392 {
3393 SUP_DPRINTF(("supR3HardNtChildProcessRequest: Child is taking too long to quit (rcWait=%#x), killing it...\n", rcNt));
3394 NtTerminateProcess(pThis->hProcess, DBG_TERMINATE_PROCESS);
3395 }
3396
3397 /*
3398 * Report the error in the same way as it occured in the guest.
3399 */
3400 if (pThis->ProcParams.enmWhat == kSupInitOp_Invalid)
3401 supR3HardenedFatalMsg("supR3HardenedWinCheckChild", kSupInitOp_Misc, pThis->ProcParams.rc,
3402 "%s", pThis->ProcParams.szErrorMsg);
3403 else
3404 supR3HardenedFatalMsg(pThis->ProcParams.szWhere, pThis->ProcParams.enmWhat, pThis->ProcParams.rc,
3405 "%s", pThis->ProcParams.szErrorMsg);
3406}
3407
3408
3409/**
3410 * Waits for the child to make a certain request or terminate.
3411 *
3412 * The stub process will also wait on it's parent to terminate.
3413 * This call will only return if the child made the expected request.
3414 *
3415 * @param pThis The child process data structure.
3416 * @param enmExpectedRequest The child request to wait for.
3417 * @param cMsTimeout The number of milliseconds to wait (at least).
3418 * @param pszWhat What we're waiting for.
3419 */
3420static void supR3HardNtChildWaitFor(PSUPR3HARDNTCHILD pThis, SUPR3WINCHILDREQ enmExpectedRequest, RTMSINTERVAL cMsTimeout,
3421 const char *pszWhat)
3422{
3423 /*
3424 * The wait loop.
3425 * Will return when the expected request arrives.
3426 * Will break out when one of the processes terminates.
3427 */
3428 NTSTATUS rcNtWait;
3429 LARGE_INTEGER Timeout;
3430 uint64_t uMsTsStart = supR3HardenedWinGetMilliTS();
3431 uint64_t cMsElapsed = 0;
3432 for (;;)
3433 {
3434 /*
3435 * Assemble handles to wait for.
3436 */
3437 ULONG cHandles = 1;
3438 HANDLE ahHandles[3];
3439 ahHandles[0] = pThis->hProcess;
3440 if (pThis->hEvtParent)
3441 ahHandles[cHandles++] = pThis->hEvtParent;
3442 if (pThis->hParent)
3443 ahHandles[cHandles++] = pThis->hParent;
3444
3445 /*
3446 * Do the waiting according to the callers wishes.
3447 */
3448 if ( enmExpectedRequest == kSupR3WinChildReq_End
3449 || cMsTimeout == RT_INDEFINITE_WAIT)
3450 rcNtWait = NtWaitForMultipleObjects(cHandles, &ahHandles[0], WaitAnyObject, TRUE /*Alertable*/, NULL /*Timeout*/);
3451 else
3452 {
3453 Timeout.QuadPart = -(int64_t)(cMsTimeout - cMsElapsed) * 10000;
3454 rcNtWait = NtWaitForMultipleObjects(cHandles, &ahHandles[0], WaitAnyObject, TRUE /*Alertable*/, &Timeout);
3455 }
3456
3457 /*
3458 * Process child request.
3459 */
3460 if (rcNtWait == STATUS_WAIT_0 + 1 && pThis->hEvtParent != NULL)
3461 {
3462 supR3HardNtChildProcessRequest(pThis, enmExpectedRequest, pszWhat);
3463 SUP_DPRINTF(("supR3HardNtChildWaitFor: Found expected request %d (%s) after %llu ms.\n",
3464 enmExpectedRequest, pszWhat, supR3HardenedWinGetMilliTS() - uMsTsStart));
3465 return; /* Expected request received. */
3466 }
3467
3468 /*
3469 * Process termination?
3470 */
3471 if ( (ULONG)rcNtWait - (ULONG)STATUS_WAIT_0 < cHandles
3472 || (ULONG)rcNtWait - (ULONG)STATUS_ABANDONED_WAIT_0 < cHandles)
3473 break;
3474
3475 /*
3476 * Check sanity.
3477 */
3478 if ( rcNtWait != STATUS_TIMEOUT
3479 && rcNtWait != STATUS_USER_APC
3480 && rcNtWait != STATUS_ALERTED)
3481 supR3HardenedWinKillChild(pThis, "supR3HardNtChildWaitFor", rcNtWait,
3482 "NtWaitForMultipleObjects returned %#x waiting for #%d (%s)\n",
3483 rcNtWait, enmExpectedRequest, pszWhat);
3484
3485 /*
3486 * Calc elapsed time for the next timeout calculation, checking to see
3487 * if we've timed out already.
3488 */
3489 cMsElapsed = supR3HardenedWinGetMilliTS() - uMsTsStart;
3490 if ( cMsElapsed > cMsTimeout
3491 && cMsTimeout != RT_INDEFINITE_WAIT
3492 && enmExpectedRequest != kSupR3WinChildReq_End)
3493 {
3494 if (rcNtWait == STATUS_USER_APC || rcNtWait == STATUS_ALERTED)
3495 cMsElapsed = cMsTimeout - 1; /* try again */
3496 else
3497 {
3498 /* We timed out. */
3499 supR3HardenedWinKillChild(pThis, "supR3HardNtChildWaitFor", rcNtWait,
3500 "Timed out after %llu ms waiting for child request #%d (%s).\n",
3501 cMsElapsed, enmExpectedRequest, pszWhat);
3502 }
3503 }
3504 }
3505
3506 /*
3507 * Proxy the termination code of the child, if it exited already.
3508 */
3509 PROCESS_BASIC_INFORMATION BasicInfo;
3510 NTSTATUS rcNt1 = NtQueryInformationProcess(pThis->hProcess, ProcessBasicInformation, &BasicInfo, sizeof(BasicInfo), NULL);
3511 NTSTATUS rcNt2 = STATUS_PENDING;
3512 NTSTATUS rcNt3 = STATUS_PENDING;
3513 if ( !NT_SUCCESS(rcNt1)
3514 || BasicInfo.ExitStatus == STATUS_PENDING)
3515 {
3516 rcNt2 = NtTerminateProcess(pThis->hProcess, RTEXITCODE_FAILURE);
3517 Timeout.QuadPart = NT_SUCCESS(rcNt2) ? -20000000 /* 2 sec */ : -1280000 /* 128 ms */;
3518 rcNt3 = NtWaitForSingleObject(pThis->hProcess, FALSE /*Alertable*/, NULL /*Timeout*/);
3519 BasicInfo.ExitStatus = RTEXITCODE_FAILURE;
3520 }
3521
3522 SUP_DPRINTF(("supR3HardNtChildWaitFor[%d]: Quitting: ExitCode=%#x (rcNtWait=%#x, rcNt1=%#x, rcNt2=%#x, rcNt3=%#x, %llu ms, %s);\n",
3523 pThis->iWhich, BasicInfo.ExitStatus, rcNtWait, rcNt1, rcNt2, rcNt3,
3524 supR3HardenedWinGetMilliTS() - uMsTsStart, pszWhat));
3525 suplibHardenedExit((RTEXITCODE)BasicInfo.ExitStatus);
3526}
3527
3528
3529/**
3530 * Closes full access child thread and process handles, making a harmless
3531 * duplicate of the process handle first.
3532 *
3533 * The hProcess member of the child process data structure will be change to the
3534 * harmless handle, while the hThread will be set to NULL.
3535 *
3536 * @param pThis The child process data structure.
3537 */
3538static void supR3HardNtChildCloseFullAccessHandles(PSUPR3HARDNTCHILD pThis)
3539{
3540 /*
3541 * The thread handle.
3542 */
3543 NTSTATUS rcNt = NtClose(pThis->hThread);
3544 if (!NT_SUCCESS(rcNt))
3545 supR3HardenedWinKillChild(pThis, "supR3HardenedWinReSpawn", rcNt, "NtClose(hThread) failed: %#x", rcNt);
3546 pThis->hThread = NULL;
3547
3548 /*
3549 * Duplicate the process handle into a harmless one.
3550 */
3551 HANDLE hProcWait;
3552 ULONG fRights = SYNCHRONIZE | PROCESS_TERMINATE | PROCESS_VM_READ;
3553 if (g_uNtVerCombined >= SUP_MAKE_NT_VER_SIMPLE(6, 0)) /* Introduced in Vista. */
3554 fRights |= PROCESS_QUERY_LIMITED_INFORMATION;
3555 else
3556 fRights |= PROCESS_QUERY_INFORMATION;
3557 rcNt = NtDuplicateObject(NtCurrentProcess(), pThis->hProcess,
3558 NtCurrentProcess(), &hProcWait,
3559 fRights, 0 /*HandleAttributes*/, 0);
3560 if (rcNt == STATUS_ACCESS_DENIED)
3561 {
3562 supR3HardenedError(rcNt, false /*fFatal*/,
3563 "supR3HardenedWinDoReSpawn: NtDuplicateObject(,,,,%#x,,) -> %#x, retrying with only %#x...\n",
3564 fRights, rcNt, SYNCHRONIZE);
3565 rcNt = NtDuplicateObject(NtCurrentProcess(), pThis->hProcess,
3566 NtCurrentProcess(), &hProcWait,
3567 SYNCHRONIZE, 0 /*HandleAttributes*/, 0);
3568 }
3569 if (!NT_SUCCESS(rcNt))
3570 supR3HardenedWinKillChild(pThis, "supR3HardenedWinReSpawn", rcNt,
3571 "NtDuplicateObject failed on child process handle: %#x\n", rcNt);
3572 /*
3573 * Close the process handle and replace it with the harmless one.
3574 */
3575 rcNt = NtClose(pThis->hProcess);
3576 pThis->hProcess = hProcWait;
3577 if (!NT_SUCCESS(rcNt))
3578 supR3HardenedWinKillChild(pThis, "supR3HardenedWinReSpawn", VERR_INVALID_NAME,
3579 "NtClose failed on child process handle: %#x\n", rcNt);
3580}
3581
3582
3583/**
3584 * This restores the child PEB and tweaks a couple of fields before we do the
3585 * child purification and let the process run normally.
3586 *
3587 * @param pThis The child process data structure.
3588 */
3589static void supR3HardNtChildSanitizePeb(PSUPR3HARDNTCHILD pThis)
3590{
3591 /*
3592 * Make a copy of the pre-execution PEB.
3593 */
3594 PEB Peb = pThis->Peb;
3595
3596#if 0
3597 /*
3598 * There should not be any activation context, so if there is, we scratch the memory associated with it.
3599 */
3600 int rc = 0;
3601 if (RT_SUCCESS(rc) && Peb.pShimData && !((uintptr_t)Peb.pShimData & PAGE_OFFSET_MASK))
3602 rc = supR3HardenedWinScratchChildMemory(hProcess, Peb.pShimData, PAGE_SIZE, "pShimData", pErrInfo);
3603 if (RT_SUCCESS(rc) && Peb.ActivationContextData && !((uintptr_t)Peb.ActivationContextData & PAGE_OFFSET_MASK))
3604 rc = supR3HardenedWinScratchChildMemory(hProcess, Peb.ActivationContextData, PAGE_SIZE, "ActivationContextData", pErrInfo);
3605 if (RT_SUCCESS(rc) && Peb.ProcessAssemblyStorageMap && !((uintptr_t)Peb.ProcessAssemblyStorageMap & PAGE_OFFSET_MASK))
3606 rc = supR3HardenedWinScratchChildMemory(hProcess, Peb.ProcessAssemblyStorageMap, PAGE_SIZE, "ProcessAssemblyStorageMap", pErrInfo);
3607 if (RT_SUCCESS(rc) && Peb.SystemDefaultActivationContextData && !((uintptr_t)Peb.SystemDefaultActivationContextData & PAGE_OFFSET_MASK))
3608 rc = supR3HardenedWinScratchChildMemory(hProcess, Peb.ProcessAssemblyStorageMap, PAGE_SIZE, "SystemDefaultActivationContextData", pErrInfo);
3609 if (RT_SUCCESS(rc) && Peb.SystemAssemblyStorageMap && !((uintptr_t)Peb.SystemAssemblyStorageMap & PAGE_OFFSET_MASK))
3610 rc = supR3HardenedWinScratchChildMemory(hProcess, Peb.SystemAssemblyStorageMap, PAGE_SIZE, "SystemAssemblyStorageMap", pErrInfo);
3611 if (RT_FAILURE(rc))
3612 return rc;
3613#endif
3614
3615 /*
3616 * Clear compatibility and activation related fields.
3617 */
3618 Peb.AppCompatFlags.QuadPart = 0;
3619 Peb.AppCompatFlagsUser.QuadPart = 0;
3620 Peb.pShimData = NULL;
3621 Peb.AppCompatInfo = NULL;
3622#if 0
3623 Peb.ActivationContextData = NULL;
3624 Peb.ProcessAssemblyStorageMap = NULL;
3625 Peb.SystemDefaultActivationContextData = NULL;
3626 Peb.SystemAssemblyStorageMap = NULL;
3627 /*Peb.Diff0.W6.IsProtectedProcess = 1;*/
3628#endif
3629
3630 /*
3631 * Write back the PEB.
3632 */
3633 SIZE_T cbActualMem = pThis->cbPeb;
3634 NTSTATUS rcNt = NtWriteVirtualMemory(pThis->hProcess, pThis->BasicInfo.PebBaseAddress, &Peb, pThis->cbPeb, &cbActualMem);
3635 if (!NT_SUCCESS(rcNt))
3636 supR3HardenedWinKillChild(pThis, "supR3HardNtChildSanitizePeb", rcNt,
3637 "NtWriteVirtualMemory/Peb failed: %#x", rcNt);
3638
3639}
3640
3641
3642/**
3643 * Purifies the child process after very early init has been performed.
3644 *
3645 * @param pThis The child process data structure.
3646 */
3647static void supR3HardNtChildPurify(PSUPR3HARDNTCHILD pThis)
3648{
3649 /*
3650 * We loop until we no longer make any fixes. This is similar to what
3651 * we do (or used to do, really) in the fAvastKludge case of
3652 * supR3HardenedWinInit. We might be up against asynchronous changes,
3653 * which we fudge by waiting a short while before earch purification. This
3654 * is arguably a fragile technique, but it's currently the best we've got.
3655 * Fortunately, most AVs seems to either favor immediate action on initial
3656 * load events or (much better for us) later events like kernel32.
3657 */
3658 uint64_t uMsTsOuterStart = supR3HardenedWinGetMilliTS();
3659 uint32_t cMsFudge = g_fSupAdversaries ? 512 : 256;
3660 uint32_t cTotalFixes = 0;
3661 uint32_t cFixes = 0; /* (MSC wrongly thinks this maybe used uninitialized) */
3662 for (uint32_t iLoop = 0; iLoop < 16; iLoop++)
3663 {
3664 /*
3665 * Delay.
3666 */
3667 uint32_t cSleeps = 0;
3668 uint64_t uMsTsStart = supR3HardenedWinGetMilliTS();
3669 do
3670 {
3671 NtYieldExecution();
3672 LARGE_INTEGER Time;
3673 Time.QuadPart = -8000000 / 100; /* 8ms in 100ns units, relative time. */
3674 NtDelayExecution(FALSE, &Time);
3675 cSleeps++;
3676 } while ( supR3HardenedWinGetMilliTS() - uMsTsStart <= cMsFudge
3677 || cSleeps < 8);
3678 SUP_DPRINTF(("supR3HardNtChildPurify: Startup delay kludge #1/%u: %u ms, %u sleeps\n",
3679 iLoop, supR3HardenedWinGetMilliTS() - uMsTsStart, cSleeps));
3680
3681 /*
3682 * Purify.
3683 */
3684 cFixes = 0;
3685 int rc = supHardenedWinVerifyProcess(pThis->hProcess, pThis->hThread, SUPHARDNTVPKIND_CHILD_PURIFICATION,
3686 g_fSupAdversaries & ( SUPHARDNT_ADVERSARY_TRENDMICRO_SAKFILE
3687 | SUPHARDNT_ADVERSARY_DIGITAL_GUARDIAN_OLD)
3688 ? SUPHARDNTVP_F_EXEC_ALLOC_REPLACE_WITH_RW : 0,
3689 &cFixes, RTErrInfoInitStatic(&g_ErrInfoStatic));
3690 if (RT_FAILURE(rc))
3691 supR3HardenedWinKillChild(pThis, "supR3HardNtChildPurify", rc,
3692 "supHardenedWinVerifyProcess failed with %Rrc: %s", rc, g_ErrInfoStatic.szMsg);
3693 if (cFixes == 0)
3694 {
3695 SUP_DPRINTF(("supR3HardNtChildPurify: Done after %llu ms and %u fixes (loop #%u).\n",
3696 supR3HardenedWinGetMilliTS() - uMsTsOuterStart, cTotalFixes, iLoop));
3697 return; /* We're probably good. */
3698 }
3699 cTotalFixes += cFixes;
3700
3701 if (!g_fSupAdversaries)
3702 g_fSupAdversaries |= SUPHARDNT_ADVERSARY_UNKNOWN;
3703 cMsFudge = 512;
3704
3705 /*
3706 * Log the KiOpPrefetchPatchCount value if available, hoping it might
3707 * sched some light on spider38's case.
3708 */
3709 ULONG cPatchCount = 0;
3710 NTSTATUS rcNt = NtQuerySystemInformation(SystemInformation_KiOpPrefetchPatchCount,
3711 &cPatchCount, sizeof(cPatchCount), NULL);
3712 if (NT_SUCCESS(rcNt))
3713 SUP_DPRINTF(("supR3HardNtChildPurify: cFixes=%u g_fSupAdversaries=%#x cPatchCount=%#u\n",
3714 cFixes, g_fSupAdversaries, cPatchCount));
3715 else
3716 SUP_DPRINTF(("supR3HardNtChildPurify: cFixes=%u g_fSupAdversaries=%#x\n", cFixes, g_fSupAdversaries));
3717 }
3718
3719 /*
3720 * We've given up fixing the child process. Probably fighting someone
3721 * that monitors their patches or/and our activities.
3722 */
3723 supR3HardenedWinKillChild(pThis, "supR3HardNtChildPurify", VERR_TRY_AGAIN,
3724 "Unable to purify child process! After 16 tries over %llu ms, we still %u fix(es) in the last pass.",
3725 supR3HardenedWinGetMilliTS() - uMsTsOuterStart, cFixes);
3726}
3727
3728
3729
3730/**
3731 * Sets up the early process init.
3732 *
3733 * @param pThis The child process data structure.
3734 */
3735static void supR3HardNtChildSetUpChildInit(PSUPR3HARDNTCHILD pThis)
3736{
3737 uintptr_t const uChildExeAddr = (uintptr_t)pThis->Peb.ImageBaseAddress;
3738
3739 /*
3740 * Plant the process parameters. This ASSUMES the handle inheritance is
3741 * performed when creating the child process.
3742 */
3743 RT_ZERO(pThis->ProcParams);
3744 pThis->ProcParams.hEvtChild = pThis->hEvtChild;
3745 pThis->ProcParams.hEvtParent = pThis->hEvtParent;
3746 pThis->ProcParams.uNtDllAddr = pThis->uNtDllAddr;
3747 pThis->ProcParams.enmRequest = kSupR3WinChildReq_Error;
3748 pThis->ProcParams.rc = VINF_SUCCESS;
3749
3750 uintptr_t uChildAddr = uChildExeAddr + ((uintptr_t)&g_ProcParams - (uintptr_t)NtCurrentPeb()->ImageBaseAddress);
3751 SIZE_T cbIgnored;
3752 NTSTATUS rcNt = NtWriteVirtualMemory(pThis->hProcess, (PVOID)uChildAddr, &pThis->ProcParams,
3753 sizeof(pThis->ProcParams), &cbIgnored);
3754 if (!NT_SUCCESS(rcNt))
3755 supR3HardenedWinKillChild(pThis, "supR3HardenedWinSetupChildInit", rcNt,
3756 "NtWriteVirtualMemory(,%p,) failed writing child process parameters: %#x\n", uChildAddr, rcNt);
3757
3758 /*
3759 * Locate the LdrInitializeThunk address in the child as well as pristine
3760 * code bits for it.
3761 */
3762 PSUPHNTLDRCACHEENTRY pLdrEntry;
3763 int rc = supHardNtLdrCacheOpen("ntdll.dll", &pLdrEntry, NULL /*pErrInfo*/);
3764 if (RT_FAILURE(rc))
3765 supR3HardenedWinKillChild(pThis, "supR3HardenedWinSetupChildInit", rc,
3766 "supHardNtLdrCacheOpen failed on NTDLL: %Rrc\n", rc);
3767
3768 uint8_t *pbChildNtDllBits;
3769 rc = supHardNtLdrCacheEntryGetBits(pLdrEntry, &pbChildNtDllBits, pThis->uNtDllAddr, NULL, NULL, NULL /*pErrInfo*/);
3770 if (RT_FAILURE(rc))
3771 supR3HardenedWinKillChild(pThis, "supR3HardenedWinSetupChildInit", rc,
3772 "supHardNtLdrCacheEntryGetBits failed on NTDLL: %Rrc\n", rc);
3773
3774 RTLDRADDR uLdrInitThunk;
3775 rc = RTLdrGetSymbolEx(pLdrEntry->hLdrMod, pbChildNtDllBits, pThis->uNtDllAddr, UINT32_MAX,
3776 "LdrInitializeThunk", &uLdrInitThunk);
3777 if (RT_FAILURE(rc))
3778 supR3HardenedWinKillChild(pThis, "supR3HardenedWinSetupChildInit", rc,
3779 "Error locating LdrInitializeThunk in NTDLL: %Rrc", rc);
3780 PVOID pvLdrInitThunk = (PVOID)(uintptr_t)uLdrInitThunk;
3781 SUP_DPRINTF(("supR3HardenedWinSetupChildInit: uLdrInitThunk=%p\n", (uintptr_t)uLdrInitThunk));
3782
3783 /*
3784 * Calculate the address of our code in the child process.
3785 */
3786 uintptr_t uEarlyProcInitEP = uChildExeAddr + ( (uintptr_t)&supR3HardenedEarlyProcessInitThunk
3787 - (uintptr_t)NtCurrentPeb()->ImageBaseAddress);
3788
3789 /*
3790 * Compose the LdrInitializeThunk replacement bytes.
3791 * Note! The amount of code we replace here must be less or equal to what
3792 * the process verification code ignores.
3793 */
3794 uint8_t abNew[16];
3795 memcpy(abNew, pbChildNtDllBits + ((uintptr_t)uLdrInitThunk - pThis->uNtDllAddr), sizeof(abNew));
3796#ifdef RT_ARCH_AMD64
3797 abNew[0] = 0xff;
3798 abNew[1] = 0x25;
3799 *(uint32_t *)&abNew[2] = 0;
3800 *(uint64_t *)&abNew[6] = uEarlyProcInitEP;
3801#elif defined(RT_ARCH_X86)
3802 abNew[0] = 0xe9;
3803 *(uint32_t *)&abNew[1] = uEarlyProcInitEP - ((uint32_t)uLdrInitThunk + 5);
3804#else
3805# error "Unsupported arch."
3806#endif
3807
3808 /*
3809 * Install the LdrInitializeThunk replacement code in the child process.
3810 */
3811 PVOID pvProt = pvLdrInitThunk;
3812 SIZE_T cbProt = sizeof(abNew);
3813 ULONG fOldProt;
3814 rcNt = NtProtectVirtualMemory(pThis->hProcess, &pvProt, &cbProt, PAGE_EXECUTE_READWRITE, &fOldProt);
3815 if (!NT_SUCCESS(rcNt))
3816 supR3HardenedWinKillChild(pThis, "supR3HardenedWinSetupChildInit", rcNt,
3817 "NtProtectVirtualMemory/LdrInitializeThunk failed: %#x", rcNt);
3818
3819 rcNt = NtWriteVirtualMemory(pThis->hProcess, pvLdrInitThunk, abNew, sizeof(abNew), &cbIgnored);
3820 if (!NT_SUCCESS(rcNt))
3821 supR3HardenedWinKillChild(pThis, "supR3HardenedWinSetupChildInit", rcNt,
3822 "NtWriteVirtualMemory/LdrInitializeThunk failed: %#x", rcNt);
3823
3824 pvProt = pvLdrInitThunk;
3825 cbProt = sizeof(abNew);
3826 rcNt = NtProtectVirtualMemory(pThis->hProcess, &pvProt, &cbProt, fOldProt, &fOldProt);
3827 if (!NT_SUCCESS(rcNt))
3828 supR3HardenedWinKillChild(pThis, "supR3HardenedWinSetupChildInit", rcNt,
3829 "NtProtectVirtualMemory/LdrInitializeThunk[restore] failed: %#x", rcNt);
3830
3831 /* Caller starts child execution. */
3832 SUP_DPRINTF(("supR3HardenedWinSetupChildInit: Start child.\n"));
3833}
3834
3835
3836
3837/**
3838 * This messes with the child PEB before we trigger the initial image events.
3839 *
3840 * @param pThis The child process data structure.
3841 */
3842static void supR3HardNtChildScrewUpPebForInitialImageEvents(PSUPR3HARDNTCHILD pThis)
3843{
3844 /*
3845 * Not sure if any of the cracker software uses the PEB at this point, but
3846 * just in case they do make some of the PEB fields a little less useful.
3847 */
3848 PEB Peb = pThis->Peb;
3849
3850 /* Make ImageBaseAddress useless. */
3851 Peb.ImageBaseAddress = (PVOID)((uintptr_t)Peb.ImageBaseAddress ^ UINT32_C(0x5f139000));
3852#ifdef RT_ARCH_AMD64
3853 Peb.ImageBaseAddress = (PVOID)((uintptr_t)Peb.ImageBaseAddress | UINT64_C(0x0313000000000000));
3854#endif
3855
3856 /*
3857 * Write the PEB.
3858 */
3859 SIZE_T cbActualMem = pThis->cbPeb;
3860 NTSTATUS rcNt = NtWriteVirtualMemory(pThis->hProcess, pThis->BasicInfo.PebBaseAddress, &Peb, pThis->cbPeb, &cbActualMem);
3861 if (!NT_SUCCESS(rcNt))
3862 supR3HardenedWinKillChild(pThis, "supR3HardNtChildScrewUpPebForInitialImageEvents", rcNt,
3863 "NtWriteVirtualMemory/Peb failed: %#x", rcNt);
3864}
3865
3866
3867/**
3868 * Check if the zero terminated NT unicode string is the path to the given
3869 * system32 DLL.
3870 *
3871 * @returns true if it is, false if not.
3872 * @param pUniStr The zero terminated NT unicode string path.
3873 * @param pszName The name of the system32 DLL.
3874 */
3875static bool supR3HardNtIsNamedSystem32Dll(PUNICODE_STRING pUniStr, const char *pszName)
3876{
3877 if (pUniStr->Length > g_System32NtPath.UniStr.Length)
3878 {
3879 if (memcmp(pUniStr->Buffer, g_System32NtPath.UniStr.Buffer, g_System32NtPath.UniStr.Length) == 0)
3880 {
3881 if (pUniStr->Buffer[g_System32NtPath.UniStr.Length / sizeof(WCHAR)] == '\\')
3882 {
3883 if (RTUtf16ICmpAscii(&pUniStr->Buffer[g_System32NtPath.UniStr.Length / sizeof(WCHAR) + 1], pszName) == 0)
3884 return true;
3885 }
3886 }
3887 }
3888
3889 return false;
3890}
3891
3892
3893/**
3894 * Worker for supR3HardNtChildGatherData that locates NTDLL in the child
3895 * process.
3896 *
3897 * @param pThis The child process data structure.
3898 */
3899static void supR3HardNtChildFindNtdll(PSUPR3HARDNTCHILD pThis)
3900{
3901 /*
3902 * Find NTDLL in this process first and take that as a starting point.
3903 */
3904 pThis->uNtDllParentAddr = (uintptr_t)GetModuleHandleW(L"ntdll.dll");
3905 SUPR3HARDENED_ASSERT(pThis->uNtDllParentAddr != 0 && !(pThis->uNtDllParentAddr & PAGE_OFFSET_MASK));
3906 pThis->uNtDllAddr = pThis->uNtDllParentAddr;
3907
3908 /*
3909 * Scan the virtual memory of the child.
3910 */
3911 uintptr_t cbAdvance = 0;
3912 uintptr_t uPtrWhere = 0;
3913 for (uint32_t i = 0; i < 1024; i++)
3914 {
3915 /* Query information. */
3916 SIZE_T cbActual = 0;
3917 MEMORY_BASIC_INFORMATION MemInfo = { 0, 0, 0, 0, 0, 0, 0 };
3918 NTSTATUS rcNt = NtQueryVirtualMemory(pThis->hProcess,
3919 (void const *)uPtrWhere,
3920 MemoryBasicInformation,
3921 &MemInfo,
3922 sizeof(MemInfo),
3923 &cbActual);
3924 if (!NT_SUCCESS(rcNt))
3925 break;
3926
3927 if ( MemInfo.Type == SEC_IMAGE
3928 || MemInfo.Type == SEC_PROTECTED_IMAGE
3929 || MemInfo.Type == (SEC_IMAGE | SEC_PROTECTED_IMAGE))
3930 {
3931 if (MemInfo.BaseAddress == MemInfo.AllocationBase)
3932 {
3933 /* Get the image name. */
3934 union
3935 {
3936 UNICODE_STRING UniStr;
3937 uint8_t abPadding[4096];
3938 } uBuf;
3939 NTSTATUS rcNt = NtQueryVirtualMemory(pThis->hProcess,
3940 MemInfo.BaseAddress,
3941 MemorySectionName,
3942 &uBuf,
3943 sizeof(uBuf) - sizeof(WCHAR),
3944 &cbActual);
3945 if (NT_SUCCESS(rcNt))
3946 {
3947 uBuf.UniStr.Buffer[uBuf.UniStr.Length / sizeof(WCHAR)] = '\0';
3948 if (supR3HardNtIsNamedSystem32Dll(&uBuf.UniStr, "ntdll.dll"))
3949 {
3950 pThis->uNtDllAddr = (uintptr_t)MemInfo.AllocationBase;
3951 SUP_DPRINTF(("supR3HardNtPuChFindNtdll: uNtDllParentAddr=%p uNtDllChildAddr=%p\n",
3952 pThis->uNtDllParentAddr, pThis->uNtDllAddr));
3953 return;
3954 }
3955 }
3956 }
3957 }
3958
3959 /*
3960 * Advance.
3961 */
3962 cbAdvance = MemInfo.RegionSize;
3963 if (uPtrWhere + cbAdvance <= uPtrWhere)
3964 break;
3965 uPtrWhere += MemInfo.RegionSize;
3966 }
3967
3968 supR3HardenedWinKillChild(pThis, "supR3HardNtChildFindNtdll", VERR_MODULE_NOT_FOUND, "ntdll.dll not found in child process.");
3969}
3970
3971
3972/**
3973 * Gather child data.
3974 *
3975 * @param pThis The child process data structure.
3976 */
3977static void supR3HardNtChildGatherData(PSUPR3HARDNTCHILD pThis)
3978{
3979 /*
3980 * Basic info.
3981 */
3982 ULONG cbActual = 0;
3983 NTSTATUS rcNt = NtQueryInformationProcess(pThis->hProcess, ProcessBasicInformation,
3984 &pThis->BasicInfo, sizeof(pThis->BasicInfo), &cbActual);
3985 if (!NT_SUCCESS(rcNt))
3986 supR3HardenedWinKillChild(pThis, "supR3HardNtChildGatherData", rcNt,
3987 "NtQueryInformationProcess/ProcessBasicInformation failed: %#x", rcNt);
3988
3989 /*
3990 * If this is the middle (stub) process, we wish to wait for both child
3991 * and parent. So open the parent process. Not fatal if we cannnot.
3992 */
3993 if (pThis->iWhich > 1)
3994 {
3995 PROCESS_BASIC_INFORMATION SelfInfo;
3996 rcNt = NtQueryInformationProcess(NtCurrentProcess(), ProcessBasicInformation, &SelfInfo, sizeof(SelfInfo), &cbActual);
3997 if (NT_SUCCESS(rcNt))
3998 {
3999 OBJECT_ATTRIBUTES ObjAttr;
4000 InitializeObjectAttributes(&ObjAttr, NULL, 0, NULL /*hRootDir*/, NULL /*pSecDesc*/);
4001
4002 CLIENT_ID ClientId;
4003 ClientId.UniqueProcess = (HANDLE)SelfInfo.InheritedFromUniqueProcessId;
4004 ClientId.UniqueThread = NULL;
4005
4006 rcNt = NtOpenProcess(&pThis->hParent, SYNCHRONIZE | PROCESS_QUERY_INFORMATION, &ObjAttr, &ClientId);
4007#ifdef DEBUG
4008 SUPR3HARDENED_ASSERT_NT_SUCCESS(rcNt);
4009#endif
4010 if (!NT_SUCCESS(rcNt))
4011 {
4012 pThis->hParent = NULL;
4013 SUP_DPRINTF(("supR3HardNtChildGatherData: Failed to open parent process (%#p): %#x\n", ClientId.UniqueProcess, rcNt));
4014 }
4015 }
4016
4017 }
4018
4019 /*
4020 * Process environment block.
4021 */
4022 if (g_uNtVerCombined < SUP_NT_VER_W2K3)
4023 pThis->cbPeb = PEB_SIZE_W51;
4024 else if (g_uNtVerCombined < SUP_NT_VER_VISTA)
4025 pThis->cbPeb = PEB_SIZE_W52;
4026 else if (g_uNtVerCombined < SUP_NT_VER_W70)
4027 pThis->cbPeb = PEB_SIZE_W6;
4028 else if (g_uNtVerCombined < SUP_NT_VER_W80)
4029 pThis->cbPeb = PEB_SIZE_W7;
4030 else if (g_uNtVerCombined < SUP_NT_VER_W81)
4031 pThis->cbPeb = PEB_SIZE_W80;
4032 else
4033 pThis->cbPeb = PEB_SIZE_W81;
4034
4035 SUP_DPRINTF(("supR3HardNtChildGatherData: PebBaseAddress=%p cbPeb=%#x\n",
4036 pThis->BasicInfo.PebBaseAddress, pThis->cbPeb));
4037
4038 SIZE_T cbActualMem;
4039 RT_ZERO(pThis->Peb);
4040 rcNt = NtReadVirtualMemory(pThis->hProcess, pThis->BasicInfo.PebBaseAddress, &pThis->Peb, sizeof(pThis->Peb), &cbActualMem);
4041 if (!NT_SUCCESS(rcNt))
4042 supR3HardenedWinKillChild(pThis, "supR3HardNtChildGatherData", rcNt,
4043 "NtReadVirtualMemory/Peb failed: %#x", rcNt);
4044
4045 /*
4046 * Locate NtDll.
4047 */
4048 supR3HardNtChildFindNtdll(pThis);
4049}
4050
4051
4052/**
4053 * Does the actually respawning.
4054 *
4055 * @returns Never, will call exit or raise fatal error.
4056 * @param iWhich Which respawn we're to check for, 1 being the
4057 * first one, and 2 the second and final.
4058 */
4059static DECL_NO_RETURN(void) supR3HardenedWinDoReSpawn(int iWhich)
4060{
4061 NTSTATUS rcNt;
4062 PPEB pPeb = NtCurrentPeb();
4063 PRTL_USER_PROCESS_PARAMETERS pParentProcParams = pPeb->ProcessParameters;
4064
4065 SUPR3HARDENED_ASSERT(g_cSuplibHardenedWindowsMainCalls == 1);
4066
4067 /*
4068 * Init the child process data structure, creating the child communication
4069 * event sempahores.
4070 */
4071 SUPR3HARDNTCHILD This;
4072 RT_ZERO(This);
4073 This.iWhich = iWhich;
4074
4075 OBJECT_ATTRIBUTES ObjAttrs;
4076 This.hEvtChild = NULL;
4077 InitializeObjectAttributes(&ObjAttrs, NULL /*pName*/, OBJ_INHERIT, NULL /*hRootDir*/, NULL /*pSecDesc*/);
4078 SUPR3HARDENED_ASSERT_NT_SUCCESS(NtCreateEvent(&This.hEvtChild, EVENT_ALL_ACCESS, &ObjAttrs, SynchronizationEvent, FALSE));
4079
4080 This.hEvtParent = NULL;
4081 InitializeObjectAttributes(&ObjAttrs, NULL /*pName*/, OBJ_INHERIT, NULL /*hRootDir*/, NULL /*pSecDesc*/);
4082 SUPR3HARDENED_ASSERT_NT_SUCCESS(NtCreateEvent(&This.hEvtParent, EVENT_ALL_ACCESS, &ObjAttrs, SynchronizationEvent, FALSE));
4083
4084 /*
4085 * Set up security descriptors.
4086 */
4087 SECURITY_ATTRIBUTES ProcessSecAttrs;
4088 MYSECURITYCLEANUP ProcessSecAttrsCleanup;
4089 supR3HardNtChildInitSecAttrs(&ProcessSecAttrs, &ProcessSecAttrsCleanup, true /*fProcess*/);
4090
4091 SECURITY_ATTRIBUTES ThreadSecAttrs;
4092 MYSECURITYCLEANUP ThreadSecAttrsCleanup;
4093 supR3HardNtChildInitSecAttrs(&ThreadSecAttrs, &ThreadSecAttrsCleanup, false /*fProcess*/);
4094
4095#if 1
4096 /*
4097 * Configure the startup info and creation flags.
4098 */
4099 DWORD dwCreationFlags = CREATE_SUSPENDED;
4100
4101 STARTUPINFOEXW SiEx;
4102 suplibHardenedMemSet(&SiEx, 0, sizeof(SiEx));
4103 if (1)
4104 SiEx.StartupInfo.cb = sizeof(SiEx.StartupInfo);
4105 else
4106 {
4107 SiEx.StartupInfo.cb = sizeof(SiEx);
4108 dwCreationFlags |= EXTENDED_STARTUPINFO_PRESENT;
4109 /** @todo experiment with protected process stuff later on. */
4110 }
4111
4112 SiEx.StartupInfo.dwFlags |= pParentProcParams->WindowFlags & STARTF_USESHOWWINDOW;
4113 SiEx.StartupInfo.wShowWindow = (WORD)pParentProcParams->ShowWindowFlags;
4114
4115 SiEx.StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
4116 SiEx.StartupInfo.hStdInput = pParentProcParams->StandardInput;
4117 SiEx.StartupInfo.hStdOutput = pParentProcParams->StandardOutput;
4118 SiEx.StartupInfo.hStdError = pParentProcParams->StandardError;
4119
4120 /*
4121 * Construct the command line and launch the process.
4122 */
4123 PRTUTF16 pwszCmdLine = supR3HardNtChildConstructCmdLine(NULL, iWhich);
4124
4125 supR3HardenedWinEnableThreadCreation();
4126 PROCESS_INFORMATION ProcessInfoW32;
4127 if (!CreateProcessW(g_wszSupLibHardenedExePath,
4128 pwszCmdLine,
4129 &ProcessSecAttrs,
4130 &ThreadSecAttrs,
4131 TRUE /*fInheritHandles*/,
4132 dwCreationFlags,
4133 NULL /*pwszzEnvironment*/,
4134 NULL /*pwszCurDir*/,
4135 &SiEx.StartupInfo,
4136 &ProcessInfoW32))
4137 supR3HardenedFatalMsg("supR3HardenedWinReSpawn", kSupInitOp_Misc, VERR_INVALID_NAME,
4138 "Error relaunching VirtualBox VM process: %u\n"
4139 "Command line: '%ls'",
4140 RtlGetLastWin32Error(), pwszCmdLine);
4141 supR3HardenedWinDisableThreadCreation();
4142
4143 SUP_DPRINTF(("supR3HardenedWinDoReSpawn(%d): New child %x.%x [kernel32].\n",
4144 iWhich, ProcessInfoW32.dwProcessId, ProcessInfoW32.dwThreadId));
4145 This.hProcess = ProcessInfoW32.hProcess;
4146 This.hThread = ProcessInfoW32.hThread;
4147
4148#else
4149
4150 /*
4151 * Construct the process parameters.
4152 */
4153 UNICODE_STRING W32ImageName;
4154 W32ImageName.Buffer = g_wszSupLibHardenedExePath; /* Yes the windows name for the process parameters. */
4155 W32ImageName.Length = (USHORT)RTUtf16Len(g_wszSupLibHardenedExePath) * sizeof(WCHAR);
4156 W32ImageName.MaximumLength = W32ImageName.Length + sizeof(WCHAR);
4157
4158 UNICODE_STRING CmdLine;
4159 supR3HardNtChildConstructCmdLine(&CmdLine, iWhich);
4160
4161 PRTL_USER_PROCESS_PARAMETERS pProcParams = NULL;
4162 SUPR3HARDENED_ASSERT_NT_SUCCESS(RtlCreateProcessParameters(&pProcParams,
4163 &W32ImageName,
4164 NULL /* DllPath - inherit from this process */,
4165 NULL /* CurrentDirectory - inherit from this process */,
4166 &CmdLine,
4167 NULL /* Environment - inherit from this process */,
4168 NULL /* WindowsTitle - none */,
4169 NULL /* DesktopTitle - none. */,
4170 NULL /* ShellInfo - none. */,
4171 NULL /* RuntimeInfo - none (byte array for MSVCRT file info) */)
4172 );
4173
4174 /** @todo this doesn't work. :-( */
4175 pProcParams->ConsoleHandle = pParentProcParams->ConsoleHandle;
4176 pProcParams->ConsoleFlags = pParentProcParams->ConsoleFlags;
4177 pProcParams->StandardInput = pParentProcParams->StandardInput;
4178 pProcParams->StandardOutput = pParentProcParams->StandardOutput;
4179 pProcParams->StandardError = pParentProcParams->StandardError;
4180
4181 RTL_USER_PROCESS_INFORMATION ProcessInfoNt = { sizeof(ProcessInfoNt) };
4182 rcNt = RtlCreateUserProcess(&g_SupLibHardenedExeNtPath.UniStr,
4183 OBJ_INHERIT | OBJ_CASE_INSENSITIVE /*Attributes*/,
4184 pProcParams,
4185 NULL, //&ProcessSecAttrs,
4186 NULL, //&ThreadSecAttrs,
4187 NtCurrentProcess() /* ParentProcess */,
4188 FALSE /*fInheritHandles*/,
4189 NULL /* DebugPort */,
4190 NULL /* ExceptionPort */,
4191 &ProcessInfoNt);
4192 if (!NT_SUCCESS(rcNt))
4193 supR3HardenedFatalMsg("supR3HardenedWinReSpawn", kSupInitOp_Misc, VERR_INVALID_NAME,
4194 "Error relaunching VirtualBox VM process: %#x\n"
4195 "Command line: '%ls'",
4196 rcNt, CmdLine.Buffer);
4197
4198 SUP_DPRINTF(("supR3HardenedWinDoReSpawn(%d): New child %x.%x [ntdll].\n",
4199 iWhich, ProcessInfo.ClientId.UniqueProcess, ProcessInfo.ClientId.UniqueThread));
4200 RtlDestroyProcessParameters(pProcParams);
4201
4202 This.hProcess = ProcessInfoNt.ProcessHandle;
4203 This.hThread = ProcessInfoNt.ThreadHandle;
4204#endif
4205
4206#ifndef VBOX_WITHOUT_DEBUGGER_CHECKS
4207 /*
4208 * Apply anti debugger notification trick to the thread. (Also done in
4209 * supR3HardenedWinInit.) This may fail with STATUS_ACCESS_DENIED and
4210 * maybe other errors. (Unfortunately, recent (SEP 12.1) of symantec's
4211 * sysplant.sys driver will cause process deadlocks and a shutdown/reboot
4212 * denial of service problem if we hide the initial thread, so we postpone
4213 * this action if we've detected SEP.)
4214 */
4215 if (!(g_fSupAdversaries & (SUPHARDNT_ADVERSARY_SYMANTEC_SYSPLANT | SUPHARDNT_ADVERSARY_SYMANTEC_N360)))
4216 {
4217 rcNt = NtSetInformationThread(This.hThread, ThreadHideFromDebugger, NULL, 0);
4218 if (!NT_SUCCESS(rcNt))
4219 SUP_DPRINTF(("supR3HardenedWinReSpawn: NtSetInformationThread/ThreadHideFromDebugger failed: %#x (harmless)\n", rcNt));
4220 }
4221#endif
4222
4223 /*
4224 * Perform very early child initialization.
4225 */
4226 supR3HardNtChildGatherData(&This);
4227 supR3HardNtChildScrewUpPebForInitialImageEvents(&This);
4228 supR3HardNtChildSetUpChildInit(&This);
4229
4230 ULONG cSuspendCount = 0;
4231 rcNt = NtResumeThread(This.hThread, &cSuspendCount);
4232 if (!NT_SUCCESS(rcNt))
4233 supR3HardenedWinKillChild(&This, "supR3HardenedWinDoReSpawn", rcNt, "NtResumeThread failed: %#x", rcNt);
4234
4235 /*
4236 * Santizie the pre-NTDLL child when it's ready.
4237 *
4238 * AV software and other things injecting themselves into the embryonic
4239 * and budding process to intercept API calls and what not. Unfortunately
4240 * this is also the behavior of viruses, malware and other unfriendly
4241 * software, so we won't stand for it. AV software can scan our image
4242 * as they are loaded via kernel hooks, that's sufficient. No need for
4243 * patching half of NTDLL or messing with the import table of the
4244 * process executable.
4245 */
4246 supR3HardNtChildWaitFor(&This, kSupR3WinChildReq_PurifyChildAndCloseHandles, 2000 /*ms*/, "PurifyChildAndCloseHandles");
4247 supR3HardNtChildPurify(&This);
4248 supR3HardNtChildSanitizePeb(&This);
4249
4250 /*
4251 * Close the unrestricted access handles. Since we need to wait on the
4252 * child process, we'll reopen the process with limited access before doing
4253 * away with the process handle returned by CreateProcess.
4254 */
4255 supR3HardNtChildCloseFullAccessHandles(&This);
4256
4257 /*
4258 * Signal the child that we've closed the unrestricted handles and it can
4259 * safely try open the driver.
4260 */
4261 rcNt = NtSetEvent(This.hEvtChild, NULL);
4262 if (!NT_SUCCESS(rcNt))
4263 supR3HardenedWinKillChild(&This, "supR3HardenedWinReSpawn", VERR_INVALID_NAME,
4264 "NtSetEvent failed on child process handle: %#x\n", rcNt);
4265
4266 /*
4267 * Ditch the loader cache so we don't sit on too much memory while waiting.
4268 */
4269 supR3HardenedWinFlushLoaderCache();
4270 supR3HardenedWinCompactHeaps();
4271
4272 /*
4273 * Enable thread creation at this point so Ctrl-C and Ctrl-Break can be processed.
4274 */
4275 supR3HardenedWinEnableThreadCreation();
4276
4277 /*
4278 * Wait for the child to get to suplibHardenedWindowsMain so we can close the handles.
4279 */
4280 supR3HardNtChildWaitFor(&This, kSupR3WinChildReq_CloseEvents, 60000 /*ms*/, "CloseEvents");
4281
4282 NtClose(This.hEvtChild);
4283 NtClose(This.hEvtParent);
4284 This.hEvtChild = NULL;
4285 This.hEvtParent = NULL;
4286
4287 /*
4288 * Wait for the process to terminate.
4289 */
4290 supR3HardNtChildWaitFor(&This, kSupR3WinChildReq_End, RT_INDEFINITE_WAIT, "the end");
4291 supR3HardenedFatal("supR3HardenedWinDoReSpawn: supR3HardNtChildWaitFor unexpectedly returned!\n");
4292 /* not reached*/
4293}
4294
4295
4296/**
4297 * Logs the content of the given object directory.
4298 *
4299 * @returns true if it exists, false if not.
4300 * @param pszDir The path of the directory to log (ASCII).
4301 */
4302static void supR3HardenedWinLogObjDir(const char *pszDir)
4303{
4304 /*
4305 * Open the driver object directory.
4306 */
4307 RTUTF16 wszDir[128];
4308 int rc = RTUtf16CopyAscii(wszDir, RT_ELEMENTS(wszDir), pszDir);
4309 if (RT_FAILURE(rc))
4310 {
4311 SUP_DPRINTF(("supR3HardenedWinLogObjDir: RTUtf16CopyAscii -> %Rrc on '%s'\n", rc, pszDir));
4312 return;
4313 }
4314
4315 UNICODE_STRING NtDirName;
4316 NtDirName.Buffer = (WCHAR *)wszDir;
4317 NtDirName.Length = (USHORT)(RTUtf16Len(wszDir) * sizeof(WCHAR));
4318 NtDirName.MaximumLength = NtDirName.Length + sizeof(WCHAR);
4319
4320 OBJECT_ATTRIBUTES ObjAttr;
4321 InitializeObjectAttributes(&ObjAttr, &NtDirName, OBJ_CASE_INSENSITIVE, NULL /*hRootDir*/, NULL /*pSecDesc*/);
4322
4323 HANDLE hDir;
4324 NTSTATUS rcNt = NtOpenDirectoryObject(&hDir, DIRECTORY_QUERY | FILE_LIST_DIRECTORY, &ObjAttr);
4325 SUP_DPRINTF(("supR3HardenedWinLogObjDir: %ls => %#x\n", wszDir, rcNt));
4326 if (!NT_SUCCESS(rcNt))
4327 return;
4328
4329 /*
4330 * Enumerate it, looking for the driver.
4331 */
4332 ULONG uObjDirCtx = 0;
4333 for (;;)
4334 {
4335 uint32_t abBuffer[_64K + _1K];
4336 ULONG cbActual;
4337 rcNt = NtQueryDirectoryObject(hDir,
4338 abBuffer,
4339 sizeof(abBuffer) - 4, /* minus four for string terminator space. */
4340 FALSE /*ReturnSingleEntry */,
4341 FALSE /*RestartScan*/,
4342 &uObjDirCtx,
4343 &cbActual);
4344 if (!NT_SUCCESS(rcNt) || cbActual < sizeof(OBJECT_DIRECTORY_INFORMATION))
4345 {
4346 SUP_DPRINTF(("supR3HardenedWinLogObjDir: NtQueryDirectoryObject => rcNt=%#x cbActual=%#x\n", rcNt, cbActual));
4347 break;
4348 }
4349
4350 POBJECT_DIRECTORY_INFORMATION pObjDir = (POBJECT_DIRECTORY_INFORMATION)abBuffer;
4351 while (pObjDir->Name.Length != 0)
4352 {
4353 SUP_DPRINTF((" %.*ls %.*ls\n",
4354 pObjDir->TypeName.Length / sizeof(WCHAR), pObjDir->TypeName.Buffer,
4355 pObjDir->Name.Length / sizeof(WCHAR), pObjDir->Name.Buffer));
4356
4357 /* Next directory entry. */
4358 pObjDir++;
4359 }
4360 }
4361
4362 /*
4363 * Clean up and return.
4364 */
4365 NtClose(hDir);
4366}
4367
4368
4369/**
4370 * Tries to open VBoxDrvErrorInfo and read extra error info from it.
4371 *
4372 * @returns pszErrorInfo.
4373 * @param pszErrorInfo The destination buffer. Will always be
4374 * terminated.
4375 * @param cbErrorInfo The size of the destination buffer.
4376 * @param pszPrefix What to prefix the error info with, if we got
4377 * anything.
4378 */
4379DECLHIDDEN(char *) supR3HardenedWinReadErrorInfoDevice(char *pszErrorInfo, size_t cbErrorInfo, const char *pszPrefix)
4380{
4381 RT_BZERO(pszErrorInfo, cbErrorInfo);
4382
4383 /*
4384 * Try open the device.
4385 */
4386 HANDLE hFile = RTNT_INVALID_HANDLE_VALUE;
4387 IO_STATUS_BLOCK Ios = RTNT_IO_STATUS_BLOCK_INITIALIZER;
4388 UNICODE_STRING NtName = RTNT_CONSTANT_UNISTR(SUPDRV_NT_DEVICE_NAME_ERROR_INFO);
4389 OBJECT_ATTRIBUTES ObjAttr;
4390 InitializeObjectAttributes(&ObjAttr, &NtName, OBJ_CASE_INSENSITIVE, NULL /*hRootDir*/, NULL /*pSecDesc*/);
4391 NTSTATUS rcNt = NtCreateFile(&hFile,
4392 GENERIC_READ, /* No SYNCHRONIZE. */
4393 &ObjAttr,
4394 &Ios,
4395 NULL /* Allocation Size*/,
4396 FILE_ATTRIBUTE_NORMAL,
4397 FILE_SHARE_READ | FILE_SHARE_WRITE,
4398 FILE_OPEN,
4399 FILE_NON_DIRECTORY_FILE, /* No FILE_SYNCHRONOUS_IO_NONALERT. */
4400 NULL /*EaBuffer*/,
4401 0 /*EaLength*/);
4402 if (NT_SUCCESS(rcNt))
4403 rcNt = Ios.Status;
4404 if (NT_SUCCESS(rcNt))
4405 {
4406 /*
4407 * Try read error info.
4408 */
4409 size_t cchPrefix = strlen(pszPrefix);
4410 if (cchPrefix + 3 < cbErrorInfo)
4411 {
4412 LARGE_INTEGER offRead;
4413 offRead.QuadPart = 0;
4414 rcNt = NtReadFile(hFile, NULL /*hEvent*/, NULL /*ApcRoutine*/, NULL /*ApcContext*/, &Ios,
4415 &pszErrorInfo[cchPrefix], (ULONG)(cbErrorInfo - cchPrefix - 1), &offRead, NULL);
4416 if (NT_SUCCESS(rcNt) && NT_SUCCESS(Ios.Status) && Ios.Information > 0)
4417 {
4418 memcpy(pszErrorInfo, pszPrefix, cchPrefix);
4419 pszErrorInfo[RT_MIN(cbErrorInfo - 1, cchPrefix + Ios.Information)] = '\0';
4420 SUP_DPRINTF(("supR3HardenedWinReadErrorInfoDevice: '%s'", &pszErrorInfo[cchPrefix]));
4421 }
4422 else
4423 {
4424 *pszErrorInfo = '\0';
4425 if (rcNt != STATUS_END_OF_FILE || Ios.Status != STATUS_END_OF_FILE)
4426 SUP_DPRINTF(("supR3HardenedWinReadErrorInfoDevice: NtReadFile -> %#x / %#x / %p\n",
4427 rcNt, Ios.Status, Ios.Information));
4428 }
4429 }
4430 else
4431 RTStrCopy(pszErrorInfo, cbErrorInfo, "error info buffer too small");
4432 NtClose(hFile);
4433 }
4434 else
4435 SUP_DPRINTF(("supR3HardenedWinReadErrorInfoDevice: NtCreateFile -> %#x\n", rcNt));
4436
4437 return pszErrorInfo;
4438}
4439
4440
4441
4442/**
4443 * Checks if the driver exists.
4444 *
4445 * This checks whether the driver is present in the /Driver object directory.
4446 * Drivers being initialized or terminated will have an object there
4447 * before/after their devices nodes are created/deleted.
4448 *
4449 * @returns true if it exists, false if not.
4450 * @param pszDriver The driver name.
4451 */
4452static bool supR3HardenedWinDriverExists(const char *pszDriver)
4453{
4454 /*
4455 * Open the driver object directory.
4456 */
4457 UNICODE_STRING NtDirName = RTNT_CONSTANT_UNISTR(L"\\Driver");
4458
4459 OBJECT_ATTRIBUTES ObjAttr;
4460 InitializeObjectAttributes(&ObjAttr, &NtDirName, OBJ_CASE_INSENSITIVE, NULL /*hRootDir*/, NULL /*pSecDesc*/);
4461
4462 HANDLE hDir;
4463 NTSTATUS rcNt = NtOpenDirectoryObject(&hDir, DIRECTORY_QUERY | FILE_LIST_DIRECTORY, &ObjAttr);
4464#ifdef VBOX_STRICT
4465 SUPR3HARDENED_ASSERT_NT_SUCCESS(rcNt);
4466#endif
4467 if (!NT_SUCCESS(rcNt))
4468 return true;
4469
4470 /*
4471 * Enumerate it, looking for the driver.
4472 */
4473 bool fFound = true;
4474 ULONG uObjDirCtx = 0;
4475 do
4476 {
4477 uint32_t abBuffer[_64K + _1K];
4478 ULONG cbActual;
4479 rcNt = NtQueryDirectoryObject(hDir,
4480 abBuffer,
4481 sizeof(abBuffer) - 4, /* minus four for string terminator space. */
4482 FALSE /*ReturnSingleEntry */,
4483 FALSE /*RestartScan*/,
4484 &uObjDirCtx,
4485 &cbActual);
4486 if (!NT_SUCCESS(rcNt) || cbActual < sizeof(OBJECT_DIRECTORY_INFORMATION))
4487 break;
4488
4489 POBJECT_DIRECTORY_INFORMATION pObjDir = (POBJECT_DIRECTORY_INFORMATION)abBuffer;
4490 while (pObjDir->Name.Length != 0)
4491 {
4492 WCHAR wcSaved = pObjDir->Name.Buffer[pObjDir->Name.Length / sizeof(WCHAR)];
4493 pObjDir->Name.Buffer[pObjDir->Name.Length / sizeof(WCHAR)] = '\0';
4494 if ( pObjDir->Name.Length > 1
4495 && RTUtf16ICmpAscii(pObjDir->Name.Buffer, pszDriver) == 0)
4496 {
4497 fFound = true;
4498 break;
4499 }
4500 pObjDir->Name.Buffer[pObjDir->Name.Length / sizeof(WCHAR)] = wcSaved;
4501
4502 /* Next directory entry. */
4503 pObjDir++;
4504 }
4505 } while (!fFound);
4506
4507 /*
4508 * Clean up and return.
4509 */
4510 NtClose(hDir);
4511
4512 return fFound;
4513}
4514
4515
4516/**
4517 * Open the stub device before the 2nd respawn.
4518 */
4519static void supR3HardenedWinOpenStubDevice(void)
4520{
4521 if (g_fSupStubOpened)
4522 return;
4523
4524 /*
4525 * Retry if we think driver might still be initializing (STATUS_NO_SUCH_DEVICE + \Drivers\VBoxDrv).
4526 */
4527 static const WCHAR s_wszName[] = SUPDRV_NT_DEVICE_NAME_STUB;
4528 uint64_t const uMsTsStart = supR3HardenedWinGetMilliTS();
4529 NTSTATUS rcNt;
4530 uint32_t iTry;
4531
4532 for (iTry = 0;; iTry++)
4533 {
4534 HANDLE hFile = RTNT_INVALID_HANDLE_VALUE;
4535 IO_STATUS_BLOCK Ios = RTNT_IO_STATUS_BLOCK_INITIALIZER;
4536
4537 UNICODE_STRING NtName;
4538 NtName.Buffer = (PWSTR)s_wszName;
4539 NtName.Length = sizeof(s_wszName) - sizeof(WCHAR);
4540 NtName.MaximumLength = sizeof(s_wszName);
4541
4542 OBJECT_ATTRIBUTES ObjAttr;
4543 InitializeObjectAttributes(&ObjAttr, &NtName, OBJ_CASE_INSENSITIVE, NULL /*hRootDir*/, NULL /*pSecDesc*/);
4544
4545 rcNt = NtCreateFile(&hFile,
4546 GENERIC_READ | GENERIC_WRITE, /* No SYNCHRONIZE. */
4547 &ObjAttr,
4548 &Ios,
4549 NULL /* Allocation Size*/,
4550 FILE_ATTRIBUTE_NORMAL,
4551 FILE_SHARE_READ | FILE_SHARE_WRITE,
4552 FILE_OPEN,
4553 FILE_NON_DIRECTORY_FILE, /* No FILE_SYNCHRONOUS_IO_NONALERT. */
4554 NULL /*EaBuffer*/,
4555 0 /*EaLength*/);
4556 if (NT_SUCCESS(rcNt))
4557 rcNt = Ios.Status;
4558
4559 /* The STATUS_NO_SUCH_DEVICE might be returned if the device is not
4560 completely initialized. Delay a little bit and try again. */
4561 if (rcNt != STATUS_NO_SUCH_DEVICE)
4562 break;
4563 if (iTry > 0 && supR3HardenedWinGetMilliTS() - uMsTsStart > 5000) /* 5 sec, at least two tries */
4564 break;
4565 if (!supR3HardenedWinDriverExists("VBoxDrv"))
4566 {
4567 /** @todo Consider starting the VBoxdrv.sys service. Requires 2nd process
4568 * though, rather complicated actually as CreateProcess causes all
4569 * kind of things to happen to this process which would make it hard to
4570 * pass the process verification tests... :-/ */
4571 break;
4572 }
4573
4574 LARGE_INTEGER Time;
4575 if (iTry < 8)
4576 Time.QuadPart = -1000000 / 100; /* 1ms in 100ns units, relative time. */
4577 else
4578 Time.QuadPart = -32000000 / 100; /* 32ms in 100ns units, relative time. */
4579 NtDelayExecution(TRUE, &Time);
4580 }
4581
4582 if (NT_SUCCESS(rcNt))
4583 g_fSupStubOpened = true;
4584 else
4585 {
4586 /*
4587 * Report trouble (fatal). For some errors codes we try gather some
4588 * extra information that goes into VBoxStartup.log so that we stand a
4589 * better chance resolving the issue.
4590 */
4591 char szErrorInfo[16384];
4592 int rc = VERR_OPEN_FAILED;
4593 if (SUP_NT_STATUS_IS_VBOX(rcNt)) /* See VBoxDrvNtErr2NtStatus. */
4594 {
4595 rc = SUP_NT_STATUS_TO_VBOX(rcNt);
4596
4597 /*
4598 * \Windows\ApiPort open trouble. So far only
4599 * STATUS_OBJECT_TYPE_MISMATCH has been observed.
4600 */
4601 if (rc == VERR_SUPDRV_APIPORT_OPEN_ERROR)
4602 {
4603 SUP_DPRINTF(("Error opening VBoxDrvStub: VERR_SUPDRV_APIPORT_OPEN_ERROR\n"));
4604
4605 uint32_t uSessionId = NtCurrentPeb()->SessionId;
4606 SUP_DPRINTF((" SessionID=%#x\n", uSessionId));
4607 char szDir[64];
4608 if (uSessionId == 0)
4609 RTStrCopy(szDir, sizeof(szDir), "\\Windows");
4610 else
4611 {
4612 RTStrPrintf(szDir, sizeof(szDir), "\\Sessions\\%u\\Windows", uSessionId);
4613 supR3HardenedWinLogObjDir(szDir);
4614 }
4615 supR3HardenedWinLogObjDir("\\Windows");
4616 supR3HardenedWinLogObjDir("\\Sessions");
4617
4618 supR3HardenedFatalMsg("supR3HardenedWinReSpawn", kSupInitOp_Misc, rc,
4619 "NtCreateFile(%ls) failed: VERR_SUPDRV_APIPORT_OPEN_ERROR\n"
4620 "\n"
4621 "Error getting %s\\ApiPort in the driver from vboxdrv.\n"
4622 "\n"
4623 "Could be due to security software is redirecting access to it, so please include full "
4624 "details of such software in a bug report. VBoxStartup.log may contain details important "
4625 "to resolving the issue.%s"
4626 , s_wszName, szDir,
4627 supR3HardenedWinReadErrorInfoDevice(szErrorInfo, sizeof(szErrorInfo),
4628 "\n\nVBoxDrvStub error: "));
4629 }
4630
4631 /*
4632 * Generic VBox failure message.
4633 */
4634 supR3HardenedFatalMsg("supR3HardenedWinReSpawn", kSupInitOp_Driver, rc,
4635 "NtCreateFile(%ls) failed: %Rrc (rcNt=%#x)%s", s_wszName, rc, rcNt,
4636 supR3HardenedWinReadErrorInfoDevice(szErrorInfo, sizeof(szErrorInfo),
4637 "\nVBoxDrvStub error: "));
4638 }
4639 else
4640 {
4641 const char *pszDefine;
4642 switch (rcNt)
4643 {
4644 case STATUS_NO_SUCH_DEVICE: pszDefine = " STATUS_NO_SUCH_DEVICE"; break;
4645 case STATUS_OBJECT_NAME_NOT_FOUND: pszDefine = " STATUS_OBJECT_NAME_NOT_FOUND"; break;
4646 case STATUS_ACCESS_DENIED: pszDefine = " STATUS_ACCESS_DENIED"; break;
4647 case STATUS_TRUST_FAILURE: pszDefine = " STATUS_TRUST_FAILURE"; break;
4648 default: pszDefine = ""; break;
4649 }
4650
4651 /*
4652 * Problems opening the device is generally due to driver load/
4653 * unload issues. Check whether the driver is loaded and make
4654 * suggestions accordingly.
4655 */
4656/** @todo don't fail during early init, wait till later and try load the driver if missing or at least query the service manager for additional information. */
4657 if ( rcNt == STATUS_NO_SUCH_DEVICE
4658 || rcNt == STATUS_OBJECT_NAME_NOT_FOUND)
4659 {
4660 SUP_DPRINTF(("Error opening VBoxDrvStub: %s\n", pszDefine));
4661 if (supR3HardenedWinDriverExists("VBoxDrv"))
4662 supR3HardenedFatalMsg("supR3HardenedWinReSpawn", kSupInitOp_Driver, VERR_OPEN_FAILED,
4663 "NtCreateFile(%ls) failed: %#x%s (%u retries)\n"
4664 "\n"
4665 "Driver is probably stuck stopping/starting. Try 'sc.exe query vboxdrv' to get more "
4666 "information about its state. Rebooting may actually help.%s"
4667 , s_wszName, rcNt, pszDefine, iTry,
4668 supR3HardenedWinReadErrorInfoDevice(szErrorInfo, sizeof(szErrorInfo),
4669 "\nVBoxDrvStub error: "));
4670 else
4671 supR3HardenedFatalMsg("supR3HardenedWinReSpawn", kSupInitOp_Driver, VERR_OPEN_FAILED,
4672 "NtCreateFile(%ls) failed: %#x%s (%u retries)\n"
4673 "\n"
4674 "Driver is does not appear to be loaded. Try 'sc.exe start vboxdrv', reinstall "
4675 "VirtualBox or reboot.%s"
4676 , s_wszName, rcNt, pszDefine, iTry,
4677 supR3HardenedWinReadErrorInfoDevice(szErrorInfo, sizeof(szErrorInfo),
4678 "\nVBoxDrvStub error: "));
4679 }
4680
4681 /* Generic NT failure message. */
4682 supR3HardenedFatalMsg("supR3HardenedWinReSpawn", kSupInitOp_Driver, VERR_OPEN_FAILED,
4683 "NtCreateFile(%ls) failed: %#x%s (%u retries)%s",
4684 s_wszName, rcNt, pszDefine, iTry,
4685 supR3HardenedWinReadErrorInfoDevice(szErrorInfo, sizeof(szErrorInfo),
4686 "\nVBoxDrvStub error: "));
4687 }
4688 }
4689}
4690
4691
4692/**
4693 * Called by the main code if supR3HardenedWinIsReSpawnNeeded returns @c true.
4694 *
4695 * @returns Program exit code.
4696 */
4697DECLHIDDEN(int) supR3HardenedWinReSpawn(int iWhich)
4698{
4699 /*
4700 * Before the 2nd respawn we set up a child protection deal with the
4701 * support driver via /Devices/VBoxDrvStub. (We tried to do this
4702 * during the early init, but in case we had trouble accessing vboxdrv we
4703 * retry it here where we have kernel32.dll and others to pull in for
4704 * better diagnostics.)
4705 */
4706 if (iWhich == 2)
4707 supR3HardenedWinOpenStubDevice();
4708
4709 /*
4710 * Make sure we're alone in the stub process before creating the VM process
4711 * and that there aren't any debuggers attached.
4712 */
4713 if (iWhich == 2)
4714 {
4715 int rc = supHardNtVpDebugger(NtCurrentProcess(), RTErrInfoInitStatic(&g_ErrInfoStatic));
4716 if (RT_SUCCESS(rc))
4717 rc = supHardNtVpThread(NtCurrentProcess(), NtCurrentThread(), RTErrInfoInitStatic(&g_ErrInfoStatic));
4718 if (RT_FAILURE(rc))
4719 supR3HardenedFatalMsg("supR3HardenedWinReSpawn", kSupInitOp_Integrity, rc, "%s", g_ErrInfoStatic.szMsg);
4720 }
4721
4722
4723 /*
4724 * Respawn the process with kernel protection for the new process.
4725 */
4726 supR3HardenedWinDoReSpawn(iWhich);
4727 /* not reached! */
4728}
4729
4730
4731/**
4732 * Checks if re-spawning is required, replacing the respawn argument if not.
4733 *
4734 * @returns true if required, false if not. In the latter case, the first
4735 * argument in the vector is replaced.
4736 * @param iWhich Which respawn we're to check for, 1 being the
4737 * first one, and 2 the second and final.
4738 * @param cArgs The number of arguments.
4739 * @param papszArgs Pointer to the argument vector.
4740 */
4741DECLHIDDEN(bool) supR3HardenedWinIsReSpawnNeeded(int iWhich, int cArgs, char **papszArgs)
4742{
4743 SUPR3HARDENED_ASSERT(g_cSuplibHardenedWindowsMainCalls == 1);
4744 SUPR3HARDENED_ASSERT(iWhich == 1 || iWhich == 2);
4745
4746 if (cArgs < 1)
4747 return true;
4748
4749 if (suplibHardenedStrCmp(papszArgs[0], SUPR3_RESPAWN_1_ARG0) == 0)
4750 {
4751 if (iWhich > 1)
4752 return true;
4753 }
4754 else if (suplibHardenedStrCmp(papszArgs[0], SUPR3_RESPAWN_2_ARG0) == 0)
4755 {
4756 if (iWhich < 2)
4757 return false;
4758 }
4759 else
4760 return true;
4761
4762 /* Replace the argument. */
4763 papszArgs[0] = g_szSupLibHardenedExePath;
4764 return false;
4765}
4766
4767
4768/**
4769 * Initializes the windows verficiation bits and other things we're better off
4770 * doing after main() has passed on it's data.
4771 *
4772 * @param fFlags The main flags.
4773 * @param fAvastKludge Whether to apply the avast kludge.
4774 */
4775DECLHIDDEN(void) supR3HardenedWinInit(uint32_t fFlags, bool fAvastKludge)
4776{
4777 NTSTATUS rcNt;
4778
4779#ifndef VBOX_WITHOUT_DEBUGGER_CHECKS
4780 /*
4781 * Install a anti debugging hack before we continue. This prevents most
4782 * notifications from ending up in the debugger. (Also applied to the
4783 * child process when respawning.)
4784 */
4785 rcNt = NtSetInformationThread(NtCurrentThread(), ThreadHideFromDebugger, NULL, 0);
4786 if (!NT_SUCCESS(rcNt))
4787 supR3HardenedFatalMsg("supR3HardenedWinInit", kSupInitOp_Misc, VERR_GENERAL_FAILURE,
4788 "NtSetInformationThread/ThreadHideFromDebugger failed: %#x\n", rcNt);
4789#endif
4790
4791 /*
4792 * Init the verifier.
4793 */
4794 RTErrInfoInitStatic(&g_ErrInfoStatic);
4795 int rc = supHardenedWinInitImageVerifier(&g_ErrInfoStatic.Core);
4796 if (RT_FAILURE(rc))
4797 supR3HardenedFatalMsg("supR3HardenedWinInit", kSupInitOp_Misc, rc,
4798 "supHardenedWinInitImageVerifier failed: %s", g_ErrInfoStatic.szMsg);
4799
4800 /*
4801 * Get the windows system directory from the KnownDlls dir.
4802 */
4803 HANDLE hSymlink = INVALID_HANDLE_VALUE;
4804 UNICODE_STRING UniStr = RTNT_CONSTANT_UNISTR(L"\\KnownDlls\\KnownDllPath");
4805 OBJECT_ATTRIBUTES ObjAttrs;
4806 InitializeObjectAttributes(&ObjAttrs, &UniStr, OBJ_CASE_INSENSITIVE, NULL /*hRootDir*/, NULL /*pSecDesc*/);
4807 rcNt = NtOpenSymbolicLinkObject(&hSymlink, SYMBOLIC_LINK_QUERY, &ObjAttrs);
4808 if (!NT_SUCCESS(rcNt))
4809 supR3HardenedFatalMsg("supR3HardenedWinInit", kSupInitOp_Misc, rcNt, "Error opening '%ls': %#x", UniStr.Buffer, rcNt);
4810
4811 g_System32WinPath.UniStr.Buffer = g_System32WinPath.awcBuffer;
4812 g_System32WinPath.UniStr.Length = 0;
4813 g_System32WinPath.UniStr.MaximumLength = sizeof(g_System32WinPath.awcBuffer) - sizeof(RTUTF16);
4814 rcNt = NtQuerySymbolicLinkObject(hSymlink, &g_System32WinPath.UniStr, NULL);
4815 if (!NT_SUCCESS(rcNt))
4816 supR3HardenedFatalMsg("supR3HardenedWinInit", kSupInitOp_Misc, rcNt, "Error querying '%ls': %#x", UniStr.Buffer, rcNt);
4817 g_System32WinPath.UniStr.Buffer[g_System32WinPath.UniStr.Length / sizeof(RTUTF16)] = '\0';
4818
4819 SUP_DPRINTF(("KnownDllPath: %ls\n", g_System32WinPath.UniStr.Buffer));
4820 NtClose(hSymlink);
4821
4822 if (!(fFlags & SUPSECMAIN_FLAGS_DONT_OPEN_DEV))
4823 {
4824 if (fAvastKludge)
4825 {
4826 /*
4827 * Do a self purification to cure avast's weird NtOpenFile write-thru
4828 * change in GetBinaryTypeW change in kernel32. Unfortunately, avast
4829 * uses a system thread to perform the process modifications, which
4830 * means it's hard to make sure it had the chance to make them...
4831 *
4832 * We have to resort to kludge doing yield and sleep fudging for a
4833 * number of milliseconds and schedulings before we can hope that avast
4834 * and similar products have done what they need to do. If we do any
4835 * fixes, we wait for a while again and redo it until we're clean.
4836 *
4837 * This is unfortunately kind of fragile.
4838 */
4839 uint32_t cMsFudge = g_fSupAdversaries ? 512 : 128;
4840 uint32_t cFixes;
4841 for (uint32_t iLoop = 0; iLoop < 16; iLoop++)
4842 {
4843 uint32_t cSleeps = 0;
4844 uint64_t uMsTsStart = supR3HardenedWinGetMilliTS();
4845 do
4846 {
4847 NtYieldExecution();
4848 LARGE_INTEGER Time;
4849 Time.QuadPart = -8000000 / 100; /* 8ms in 100ns units, relative time. */
4850 NtDelayExecution(FALSE, &Time);
4851 cSleeps++;
4852 } while ( supR3HardenedWinGetMilliTS() - uMsTsStart <= cMsFudge
4853 || cSleeps < 8);
4854 SUP_DPRINTF(("supR3HardenedWinInit: Startup delay kludge #2/%u: %u ms, %u sleeps\n",
4855 iLoop, supR3HardenedWinGetMilliTS() - uMsTsStart, cSleeps));
4856
4857 cFixes = 0;
4858 rc = supHardenedWinVerifyProcess(NtCurrentProcess(), NtCurrentThread(), SUPHARDNTVPKIND_SELF_PURIFICATION,
4859 0 /*fFlags*/, &cFixes, NULL /*pErrInfo*/);
4860 if (RT_FAILURE(rc) || cFixes == 0)
4861 break;
4862
4863 if (!g_fSupAdversaries)
4864 g_fSupAdversaries |= SUPHARDNT_ADVERSARY_UNKNOWN;
4865 cMsFudge = 512;
4866
4867 /* Log the KiOpPrefetchPatchCount value if available, hoping it might sched some light on spider38's case. */
4868 ULONG cPatchCount = 0;
4869 rcNt = NtQuerySystemInformation(SystemInformation_KiOpPrefetchPatchCount,
4870 &cPatchCount, sizeof(cPatchCount), NULL);
4871 if (NT_SUCCESS(rcNt))
4872 SUP_DPRINTF(("supR3HardenedWinInit: cFixes=%u g_fSupAdversaries=%#x cPatchCount=%#u\n",
4873 cFixes, g_fSupAdversaries, cPatchCount));
4874 else
4875 SUP_DPRINTF(("supR3HardenedWinInit: cFixes=%u g_fSupAdversaries=%#x\n", cFixes, g_fSupAdversaries));
4876 }
4877 }
4878
4879 /*
4880 * Install the hooks.
4881 */
4882 supR3HardenedWinInstallHooks();
4883 }
4884
4885#ifndef VBOX_WITH_VISTA_NO_SP
4886 /*
4887 * Complain about Vista w/o service pack if we're launching a VM.
4888 */
4889 if ( !(fFlags & SUPSECMAIN_FLAGS_DONT_OPEN_DEV)
4890 && g_uNtVerCombined >= SUP_NT_VER_VISTA
4891 && g_uNtVerCombined < SUP_MAKE_NT_VER_COMBINED(6, 0, 6001, 0, 0))
4892 supR3HardenedFatalMsg("supR3HardenedWinInit", kSupInitOp_Misc, VERR_NOT_SUPPORTED,
4893 "Window Vista without any service pack installed is not supported. Please install the latest service pack.");
4894#endif
4895}
4896
4897
4898/**
4899 * Modifies the DLL search path for testcases.
4900 *
4901 * This makes sure the application binary path is in the search path. When
4902 * starting a testcase executable in the testcase/ subdirectory this isn't the
4903 * case by default. So, unless we do something about it we won't be able to
4904 * import VBox DLLs.
4905 *
4906 * @param fFlags The main flags (giving the location).
4907 * @param pszAppBinPath The path to the application binary directory
4908 * (windows style).
4909 */
4910DECLHIDDEN(void) supR3HardenedWinModifyDllSearchPath(uint32_t fFlags, const char *pszAppBinPath)
4911{
4912 /*
4913 * For the testcases to work, we must add the app bin directory to the
4914 * DLL search list before the testcase dll is loaded or it won't be
4915 * able to find the VBox DLLs. This is done _after_ VBoxRT.dll is
4916 * initialized and sets its defaults.
4917 */
4918 switch (fFlags & SUPSECMAIN_FLAGS_LOC_MASK)
4919 {
4920 case SUPSECMAIN_FLAGS_LOC_TESTCASE:
4921 break;
4922 default:
4923 return;
4924 }
4925
4926 /*
4927 * Dynamically resolve the two APIs we need (the latter uses forwarders on w7).
4928 */
4929 HMODULE hModKernel32 = GetModuleHandleW(L"kernel32.dll");
4930
4931 typedef BOOL (WINAPI *PFNSETDLLDIRECTORY)(LPCWSTR);
4932 PFNSETDLLDIRECTORY pfnSetDllDir;
4933 pfnSetDllDir = (PFNSETDLLDIRECTORY)GetProcAddress(hModKernel32, "SetDllDirectoryW");
4934
4935 typedef BOOL (WINAPI *PFNSETDEFAULTDLLDIRECTORIES)(DWORD);
4936 PFNSETDEFAULTDLLDIRECTORIES pfnSetDefDllDirs;
4937 pfnSetDefDllDirs = (PFNSETDEFAULTDLLDIRECTORIES)GetProcAddress(hModKernel32, "SetDefaultDllDirectories");
4938
4939 if (pfnSetDllDir != NULL)
4940 {
4941 /*
4942 * Convert the path to UTF-16 and try set it.
4943 */
4944 PRTUTF16 pwszAppBinPath = NULL;
4945 int rc = RTStrToUtf16(pszAppBinPath, &pwszAppBinPath);
4946 if (RT_SUCCESS(rc))
4947 {
4948 if (pfnSetDllDir(pwszAppBinPath))
4949 {
4950 SUP_DPRINTF(("supR3HardenedWinModifyDllSearchPath: Set dll dir to '%ls'\n", pwszAppBinPath));
4951 g_fSupLibHardenedDllSearchUserDirs = true;
4952
4953 /*
4954 * We set it alright, on W7 and later we also must modify the
4955 * default DLL search order. See @bugref{6861} for details on
4956 * why we don't do this on Vista (also see init-win.cpp in IPRT).
4957 */
4958 if ( pfnSetDefDllDirs
4959 && g_uNtVerCombined >= SUP_NT_VER_W70)
4960 {
4961 if (pfnSetDefDllDirs( LOAD_LIBRARY_SEARCH_APPLICATION_DIR
4962 | LOAD_LIBRARY_SEARCH_SYSTEM32
4963 | LOAD_LIBRARY_SEARCH_USER_DIRS))
4964 SUP_DPRINTF(("supR3HardenedWinModifyDllSearchPath: Successfully modified search dirs.\n"));
4965 else
4966 supR3HardenedFatal("supR3HardenedWinModifyDllSearchPath: SetDllDirectoryW(%ls) failed: %d\n",
4967 pwszAppBinPath, RtlGetLastWin32Error());
4968 }
4969 }
4970 else
4971 supR3HardenedFatal("supR3HardenedWinModifyDllSearchPath: SetDllDirectoryW(%ls) failed: %d\n",
4972 pwszAppBinPath, RtlGetLastWin32Error());
4973 RTUtf16Free(pwszAppBinPath);
4974 }
4975 else
4976 supR3HardenedFatal("supR3HardenedWinModifyDllSearchPath: RTStrToUtf16(%s) failed: %d\n", pszAppBinPath, rc);
4977 }
4978}
4979
4980
4981/**
4982 * Initializes the application binary directory path.
4983 *
4984 * This is called once or twice.
4985 *
4986 * @param fFlags The main flags (giving the location).
4987 */
4988DECLHIDDEN(void) supR3HardenedWinInitAppBin(uint32_t fFlags)
4989{
4990 USHORT cwc = (USHORT)g_offSupLibHardenedExeNtName - 1;
4991 g_SupLibHardenedAppBinNtPath.UniStr.Buffer = g_SupLibHardenedAppBinNtPath.awcBuffer;
4992 memcpy(g_SupLibHardenedAppBinNtPath.UniStr.Buffer, g_SupLibHardenedExeNtPath.UniStr.Buffer, cwc * sizeof(WCHAR));
4993
4994 switch (fFlags & SUPSECMAIN_FLAGS_LOC_MASK)
4995 {
4996 case SUPSECMAIN_FLAGS_LOC_APP_BIN:
4997 break;
4998 case SUPSECMAIN_FLAGS_LOC_TESTCASE:
4999 {
5000 /* Drop one directory level. */
5001 USHORT off = cwc;
5002 WCHAR wc;
5003 while ( off > 1
5004 && (wc = g_SupLibHardenedAppBinNtPath.UniStr.Buffer[off - 1]) != '\0')
5005 if (wc != '\\' && wc != '/')
5006 off--;
5007 else
5008 {
5009 if (g_SupLibHardenedAppBinNtPath.UniStr.Buffer[off - 2] == ':')
5010 cwc = off;
5011 else
5012 cwc = off - 1;
5013 break;
5014 }
5015 break;
5016 }
5017 default:
5018 supR3HardenedFatal("supR3HardenedWinInitAppBin: Unknown program binary location: %#x\n", fFlags);
5019 }
5020
5021 g_SupLibHardenedAppBinNtPath.UniStr.Buffer[cwc] = '\0';
5022 g_SupLibHardenedAppBinNtPath.UniStr.Length = cwc * sizeof(WCHAR);
5023 g_SupLibHardenedAppBinNtPath.UniStr.MaximumLength = sizeof(g_SupLibHardenedAppBinNtPath.awcBuffer);
5024 SUP_DPRINTF(("supR3HardenedWinInitAppBin(%#x): '%ls'\n", fFlags, g_SupLibHardenedAppBinNtPath.UniStr.Buffer));
5025}
5026
5027
5028/**
5029 * Converts the Windows command line string (UTF-16) to an array of UTF-8
5030 * arguments suitable for passing to main().
5031 *
5032 * @returns Pointer to the argument array.
5033 * @param pawcCmdLine The UTF-16 windows command line to parse.
5034 * @param cwcCmdLine The length of the command line.
5035 * @param pcArgs Where to return the number of arguments.
5036 */
5037static char **suplibCommandLineToArgvWStub(PCRTUTF16 pawcCmdLine, size_t cwcCmdLine, int *pcArgs)
5038{
5039 /*
5040 * Convert the command line string to UTF-8.
5041 */
5042 char *pszCmdLine = NULL;
5043 SUPR3HARDENED_ASSERT(RT_SUCCESS(RTUtf16ToUtf8Ex(pawcCmdLine, cwcCmdLine, &pszCmdLine, 0, NULL)));
5044
5045 /*
5046 * Parse the command line, carving argument strings out of it.
5047 */
5048 int cArgs = 0;
5049 int cArgsAllocated = 4;
5050 char **papszArgs = (char **)RTMemAllocZ(sizeof(char *) * cArgsAllocated);
5051 char *pszSrc = pszCmdLine;
5052 for (;;)
5053 {
5054 /* skip leading blanks. */
5055 char ch = *pszSrc;
5056 while (suplibCommandLineIsArgSeparator(ch))
5057 ch = *++pszSrc;
5058 if (!ch)
5059 break;
5060
5061 /* Add argument to the vector. */
5062 if (cArgs + 2 >= cArgsAllocated)
5063 {
5064 cArgsAllocated *= 2;
5065 papszArgs = (char **)RTMemRealloc(papszArgs, sizeof(char *) * cArgsAllocated);
5066 }
5067 papszArgs[cArgs++] = pszSrc;
5068 papszArgs[cArgs] = NULL;
5069
5070 /* Unquote and unescape the string. */
5071 char *pszDst = pszSrc++;
5072 bool fQuoted = false;
5073 do
5074 {
5075 if (ch == '"')
5076 fQuoted = !fQuoted;
5077 else if (ch != '\\' || (*pszSrc != '\\' && *pszSrc != '"'))
5078 *pszDst++ = ch;
5079 else
5080 {
5081 unsigned cSlashes = 0;
5082 while ((ch = *pszSrc++) == '\\')
5083 cSlashes++;
5084 if (ch == '"')
5085 {
5086 while (cSlashes >= 2)
5087 {
5088 cSlashes -= 2;
5089 *pszDst++ = '\\';
5090 }
5091 if (cSlashes)
5092 *pszDst++ = '"';
5093 else
5094 fQuoted = !fQuoted;
5095 }
5096 else
5097 {
5098 pszSrc--;
5099 while (cSlashes-- > 0)
5100 *pszDst++ = '\\';
5101 }
5102 }
5103
5104 ch = *pszSrc++;
5105 } while (ch != '\0' && (fQuoted || !suplibCommandLineIsArgSeparator(ch)));
5106
5107 /* Terminate the argument. */
5108 *pszDst = '\0';
5109 if (!ch)
5110 break;
5111 }
5112
5113 *pcArgs = cArgs;
5114 return papszArgs;
5115}
5116
5117
5118/**
5119 * Worker for supR3HardenedFindVersionRsrcOffset.
5120 *
5121 * @returns RVA the version resource data, UINT32_MAX if not found.
5122 * @param pRootDir The root resource directory. Expects data to
5123 * follow.
5124 * @param cbBuf The amount of data at pRootDir.
5125 * @param offData The offset to the data entry.
5126 * @param pcbData Where to return the size of the data.
5127 */
5128static uint32_t supR3HardenedGetRvaFromRsrcDataEntry(PIMAGE_RESOURCE_DIRECTORY pRootDir, uint32_t cbBuf, uint32_t offData,
5129 uint32_t *pcbData)
5130{
5131 if ( offData <= cbBuf
5132 && offData + sizeof(IMAGE_RESOURCE_DATA_ENTRY) <= cbBuf)
5133 {
5134 PIMAGE_RESOURCE_DATA_ENTRY pRsrcData = (PIMAGE_RESOURCE_DATA_ENTRY)((uintptr_t)pRootDir + offData);
5135 SUP_DPRINTF((" [Raw version resource data: %#x LB %#x, codepage %#x (reserved %#x)]\n",
5136 pRsrcData->OffsetToData, pRsrcData->Size, pRsrcData->CodePage, pRsrcData->Reserved));
5137 if (pRsrcData->Size > 0)
5138 {
5139 *pcbData = pRsrcData->Size;
5140 return pRsrcData->OffsetToData;
5141 }
5142 }
5143 else
5144 SUP_DPRINTF((" Version resource data (%#x) is outside the buffer (%#x)! :-(\n", offData, cbBuf));
5145
5146 *pcbData = 0;
5147 return UINT32_MAX;
5148}
5149
5150
5151/** @def SUP_RSRC_DPRINTF
5152 * Dedicated debug printf for resource directory parsing.
5153 * @sa SUP_DPRINTF
5154 */
5155#if 0 /* more details */
5156# define SUP_RSRC_DPRINTF(a) SUP_DPRINTF(a)
5157#else
5158# define SUP_RSRC_DPRINTF(a) do { } while (0)
5159#endif
5160
5161/**
5162 * Scans the resource directory for a version resource.
5163 *
5164 * @returns RVA of the version resource data, UINT32_MAX if not found.
5165 * @param pRootDir The root resource directory. Expects data to
5166 * follow.
5167 * @param cbBuf The amount of data at pRootDir.
5168 * @param pcbData Where to return the size of the version data.
5169 */
5170static uint32_t supR3HardenedFindVersionRsrcRva(PIMAGE_RESOURCE_DIRECTORY pRootDir, uint32_t cbBuf, uint32_t *pcbData)
5171{
5172 SUP_RSRC_DPRINTF((" ResDir: Char=%#x Time=%#x Ver=%d%d #NamedEntries=%#x #IdEntries=%#x\n",
5173 pRootDir->Characteristics,
5174 pRootDir->TimeDateStamp,
5175 pRootDir->MajorVersion,
5176 pRootDir->MinorVersion,
5177 pRootDir->NumberOfNamedEntries,
5178 pRootDir->NumberOfIdEntries));
5179
5180 PIMAGE_RESOURCE_DIRECTORY_ENTRY paEntries = (PIMAGE_RESOURCE_DIRECTORY_ENTRY)(pRootDir + 1);
5181 unsigned cMaxEntries = (cbBuf - sizeof(IMAGE_RESOURCE_DIRECTORY)) / sizeof(IMAGE_RESOURCE_DIRECTORY_ENTRY);
5182 unsigned cEntries = pRootDir->NumberOfNamedEntries + pRootDir->NumberOfIdEntries;
5183 if (cEntries > cMaxEntries)
5184 cEntries = cMaxEntries;
5185 for (unsigned i = 0; i < cEntries; i++)
5186 {
5187 if (!paEntries[i].NameIsString)
5188 {
5189 if (!paEntries[i].DataIsDirectory)
5190 SUP_RSRC_DPRINTF((" #%u: ID: #%#06x Data: %#010x\n",
5191 i, paEntries[i].Id, paEntries[i].OffsetToData));
5192 else
5193 SUP_RSRC_DPRINTF((" #%u: ID: #%#06x Dir: %#010x\n",
5194 i, paEntries[i].Id, paEntries[i].OffsetToDirectory));
5195 }
5196 else
5197 {
5198 if (!paEntries[i].DataIsDirectory)
5199 SUP_RSRC_DPRINTF((" #%u: Name: #%#06x Data: %#010x\n",
5200 i, paEntries[i].NameOffset, paEntries[i].OffsetToData));
5201 else
5202 SUP_RSRC_DPRINTF((" #%u: Name: #%#06x Dir: %#010x\n",
5203 i, paEntries[i].NameOffset, paEntries[i].OffsetToDirectory));
5204 }
5205
5206 /*
5207 * Look for the version resource type. Skip to the next entry if not found.
5208 */
5209 if (paEntries[i].NameIsString)
5210 continue;
5211 if (paEntries[i].Id != 0x10 /*RT_VERSION*/)
5212 continue;
5213 if (!paEntries[i].DataIsDirectory)
5214 {
5215 SUP_DPRINTF((" #%u: ID: #%#06x Data: %#010x - WEIRD!\n", i, paEntries[i].Id, paEntries[i].OffsetToData));
5216 continue;
5217 }
5218 SUP_RSRC_DPRINTF((" Version resource dir entry #%u: dir offset: %#x (cbBuf=%#x)\n",
5219 i, paEntries[i].OffsetToDirectory, cbBuf));
5220
5221 /*
5222 * Locate the sub-resource directory for it.
5223 */
5224 if (paEntries[i].OffsetToDirectory >= cbBuf)
5225 {
5226 SUP_DPRINTF((" Version resource dir is outside the buffer! :-(\n"));
5227 continue;
5228 }
5229 uint32_t cbMax = cbBuf - paEntries[i].OffsetToDirectory;
5230 if (cbMax < sizeof(IMAGE_RESOURCE_DIRECTORY) + sizeof(IMAGE_RESOURCE_DIRECTORY_ENTRY))
5231 {
5232 SUP_DPRINTF((" Version resource dir entry #0 is outside the buffer! :-(\n"));
5233 continue;
5234 }
5235 PIMAGE_RESOURCE_DIRECTORY pVerDir = (PIMAGE_RESOURCE_DIRECTORY)((uintptr_t)pRootDir + paEntries[i].OffsetToDirectory);
5236 SUP_RSRC_DPRINTF((" VerDir: Char=%#x Time=%#x Ver=%d%d #NamedEntries=%#x #IdEntries=%#x\n",
5237 pVerDir->Characteristics,
5238 pVerDir->TimeDateStamp,
5239 pVerDir->MajorVersion,
5240 pVerDir->MinorVersion,
5241 pVerDir->NumberOfNamedEntries,
5242 pVerDir->NumberOfIdEntries));
5243 PIMAGE_RESOURCE_DIRECTORY_ENTRY paVerEntries = (PIMAGE_RESOURCE_DIRECTORY_ENTRY)(pVerDir + 1);
5244 unsigned cMaxVerEntries = (cbMax - sizeof(IMAGE_RESOURCE_DIRECTORY)) / sizeof(IMAGE_RESOURCE_DIRECTORY_ENTRY);
5245 unsigned cVerEntries = pVerDir->NumberOfNamedEntries + pVerDir->NumberOfIdEntries;
5246 if (cVerEntries > cMaxVerEntries)
5247 cVerEntries = cMaxVerEntries;
5248 for (unsigned iVer = 0; iVer < cVerEntries; iVer++)
5249 {
5250 if (!paVerEntries[iVer].NameIsString)
5251 {
5252 if (!paVerEntries[iVer].DataIsDirectory)
5253 SUP_RSRC_DPRINTF((" #%u: ID: #%#06x Data: %#010x\n",
5254 iVer, paVerEntries[iVer].Id, paVerEntries[iVer].OffsetToData));
5255 else
5256 SUP_RSRC_DPRINTF((" #%u: ID: #%#06x Dir: %#010x\n",
5257 iVer, paVerEntries[iVer].Id, paVerEntries[iVer].OffsetToDirectory));
5258 }
5259 else
5260 {
5261 if (!paVerEntries[iVer].DataIsDirectory)
5262 SUP_RSRC_DPRINTF((" #%u: Name: #%#06x Data: %#010x\n",
5263 iVer, paVerEntries[iVer].NameOffset, paVerEntries[iVer].OffsetToData));
5264 else
5265 SUP_RSRC_DPRINTF((" #%u: Name: #%#06x Dir: %#010x\n",
5266 iVer, paVerEntries[iVer].NameOffset, paVerEntries[iVer].OffsetToDirectory));
5267 }
5268 if (!paVerEntries[iVer].DataIsDirectory)
5269 {
5270 SUP_DPRINTF((" [Version info resource found at %#x! (ID/Name: #%#x)]\n",
5271 paVerEntries[iVer].OffsetToData, paVerEntries[iVer].Name));
5272 return supR3HardenedGetRvaFromRsrcDataEntry(pRootDir, cbBuf, paVerEntries[iVer].OffsetToData, pcbData);
5273 }
5274
5275 /*
5276 * Check out the next directory level.
5277 */
5278 if (paVerEntries[iVer].OffsetToDirectory >= cbBuf)
5279 {
5280 SUP_DPRINTF((" Version resource subdir is outside the buffer! :-(\n"));
5281 continue;
5282 }
5283 cbMax = cbBuf - paVerEntries[iVer].OffsetToDirectory;
5284 if (cbMax < sizeof(IMAGE_RESOURCE_DIRECTORY) + sizeof(IMAGE_RESOURCE_DIRECTORY_ENTRY))
5285 {
5286 SUP_DPRINTF((" Version resource subdir entry #0 is outside the buffer! :-(\n"));
5287 continue;
5288 }
5289 PIMAGE_RESOURCE_DIRECTORY pVerSubDir = (PIMAGE_RESOURCE_DIRECTORY)((uintptr_t)pRootDir + paVerEntries[iVer].OffsetToDirectory);
5290 SUP_RSRC_DPRINTF((" VerSubDir#%u: Char=%#x Time=%#x Ver=%d%d #NamedEntries=%#x #IdEntries=%#x\n",
5291 iVer,
5292 pVerSubDir->Characteristics,
5293 pVerSubDir->TimeDateStamp,
5294 pVerSubDir->MajorVersion,
5295 pVerSubDir->MinorVersion,
5296 pVerSubDir->NumberOfNamedEntries,
5297 pVerSubDir->NumberOfIdEntries));
5298 PIMAGE_RESOURCE_DIRECTORY_ENTRY paVerSubEntries = (PIMAGE_RESOURCE_DIRECTORY_ENTRY)(pVerSubDir + 1);
5299 unsigned cMaxVerSubEntries = (cbMax - sizeof(IMAGE_RESOURCE_DIRECTORY)) / sizeof(IMAGE_RESOURCE_DIRECTORY_ENTRY);
5300 unsigned cVerSubEntries = pVerSubDir->NumberOfNamedEntries + pVerSubDir->NumberOfIdEntries;
5301 if (cVerSubEntries > cMaxVerSubEntries)
5302 cVerSubEntries = cMaxVerSubEntries;
5303 for (unsigned iVerSub = 0; iVerSub < cVerSubEntries; iVerSub++)
5304 {
5305 if (!paVerSubEntries[iVerSub].NameIsString)
5306 {
5307 if (!paVerSubEntries[iVerSub].DataIsDirectory)
5308 SUP_RSRC_DPRINTF((" #%u: ID: #%#06x Data: %#010x\n",
5309 iVerSub, paVerSubEntries[iVerSub].Id, paVerSubEntries[iVerSub].OffsetToData));
5310 else
5311 SUP_RSRC_DPRINTF((" #%u: ID: #%#06x Dir: %#010x\n",
5312 iVerSub, paVerSubEntries[iVerSub].Id, paVerSubEntries[iVerSub].OffsetToDirectory));
5313 }
5314 else
5315 {
5316 if (!paVerSubEntries[iVerSub].DataIsDirectory)
5317 SUP_RSRC_DPRINTF((" #%u: Name: #%#06x Data: %#010x\n",
5318 iVerSub, paVerSubEntries[iVerSub].NameOffset, paVerSubEntries[iVerSub].OffsetToData));
5319 else
5320 SUP_RSRC_DPRINTF((" #%u: Name: #%#06x Dir: %#010x\n",
5321 iVerSub, paVerSubEntries[iVerSub].NameOffset, paVerSubEntries[iVerSub].OffsetToDirectory));
5322 }
5323 if (!paVerSubEntries[iVerSub].DataIsDirectory)
5324 {
5325 SUP_DPRINTF((" [Version info resource found at %#x! (ID/Name: %#x; SubID/SubName: %#x)]\n",
5326 paVerSubEntries[iVerSub].OffsetToData, paVerEntries[iVer].Name, paVerSubEntries[iVerSub].Name));
5327 return supR3HardenedGetRvaFromRsrcDataEntry(pRootDir, cbBuf, paVerSubEntries[iVerSub].OffsetToData, pcbData);
5328 }
5329 }
5330 }
5331 }
5332
5333 *pcbData = 0;
5334 return UINT32_MAX;
5335}
5336
5337
5338/**
5339 * Logs information about a file from a protection product or from Windows,
5340 * optionally returning the file version.
5341 *
5342 * The purpose here is to better see which version of the product is installed
5343 * and not needing to depend on the user supplying the correct information.
5344 *
5345 * @param pwszFile The NT path to the file.
5346 * @param pwszFileVersion Where to return the file version, if found. NULL if
5347 * not interested.
5348 * @param cwcFileVersion The size of the file version buffer (UTF-16 units).
5349 */
5350static void supR3HardenedLogFileInfo(PCRTUTF16 pwszFile, PRTUTF16 pwszFileVersion, size_t cwcFileVersion)
5351{
5352 /*
5353 * Make sure the file version is always set when we return.
5354 */
5355 if (pwszFileVersion && cwcFileVersion)
5356 *pwszFileVersion = '\0';
5357
5358 /*
5359 * Open the file.
5360 */
5361 HANDLE hFile = RTNT_INVALID_HANDLE_VALUE;
5362 IO_STATUS_BLOCK Ios = RTNT_IO_STATUS_BLOCK_INITIALIZER;
5363 UNICODE_STRING UniStrName;
5364 UniStrName.Buffer = (WCHAR *)pwszFile;
5365 UniStrName.Length = (USHORT)(RTUtf16Len(pwszFile) * sizeof(WCHAR));
5366 UniStrName.MaximumLength = UniStrName.Length + sizeof(WCHAR);
5367 OBJECT_ATTRIBUTES ObjAttr;
5368 InitializeObjectAttributes(&ObjAttr, &UniStrName, OBJ_CASE_INSENSITIVE, NULL /*hRootDir*/, NULL /*pSecDesc*/);
5369 NTSTATUS rcNt = NtCreateFile(&hFile,
5370 GENERIC_READ | SYNCHRONIZE,
5371 &ObjAttr,
5372 &Ios,
5373 NULL /* Allocation Size*/,
5374 FILE_ATTRIBUTE_NORMAL,
5375 FILE_SHARE_READ,
5376 FILE_OPEN,
5377 FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT,
5378 NULL /*EaBuffer*/,
5379 0 /*EaLength*/);
5380 if (NT_SUCCESS(rcNt))
5381 rcNt = Ios.Status;
5382 if (NT_SUCCESS(rcNt))
5383 {
5384 SUP_DPRINTF(("%ls:\n", pwszFile));
5385 union
5386 {
5387 uint64_t u64AlignmentInsurance;
5388 FILE_BASIC_INFORMATION BasicInfo;
5389 FILE_STANDARD_INFORMATION StdInfo;
5390 uint8_t abBuf[32768];
5391 RTUTF16 awcBuf[16384];
5392 IMAGE_DOS_HEADER MzHdr;
5393 IMAGE_RESOURCE_DIRECTORY ResDir;
5394 } u;
5395 RTTIMESPEC TimeSpec;
5396 char szTmp[64];
5397
5398 /*
5399 * Print basic file information available via NtQueryInformationFile.
5400 */
5401 IO_STATUS_BLOCK Ios = RTNT_IO_STATUS_BLOCK_INITIALIZER;
5402 rcNt = NtQueryInformationFile(hFile, &Ios, &u.BasicInfo, sizeof(u.BasicInfo), FileBasicInformation);
5403 if (NT_SUCCESS(rcNt) && NT_SUCCESS(Ios.Status))
5404 {
5405 SUP_DPRINTF((" CreationTime: %s\n", RTTimeSpecToString(RTTimeSpecSetNtTime(&TimeSpec, u.BasicInfo.CreationTime.QuadPart), szTmp, sizeof(szTmp))));
5406 /*SUP_DPRINTF((" LastAccessTime: %s\n", RTTimeSpecToString(RTTimeSpecSetNtTime(&TimeSpec, u.BasicInfo.LastAccessTime.QuadPart), szTmp, sizeof(szTmp))));*/
5407 SUP_DPRINTF((" LastWriteTime: %s\n", RTTimeSpecToString(RTTimeSpecSetNtTime(&TimeSpec, u.BasicInfo.LastWriteTime.QuadPart), szTmp, sizeof(szTmp))));
5408 SUP_DPRINTF((" ChangeTime: %s\n", RTTimeSpecToString(RTTimeSpecSetNtTime(&TimeSpec, u.BasicInfo.ChangeTime.QuadPart), szTmp, sizeof(szTmp))));
5409 SUP_DPRINTF((" FileAttributes: %#x\n", u.BasicInfo.FileAttributes));
5410 }
5411 else
5412 SUP_DPRINTF((" FileBasicInformation -> %#x %#x\n", rcNt, Ios.Status));
5413
5414 rcNt = NtQueryInformationFile(hFile, &Ios, &u.StdInfo, sizeof(u.StdInfo), FileStandardInformation);
5415 if (NT_SUCCESS(rcNt) && NT_SUCCESS(Ios.Status))
5416 SUP_DPRINTF((" Size: %#llx\n", u.StdInfo.EndOfFile.QuadPart));
5417 else
5418 SUP_DPRINTF((" FileStandardInformation -> %#x %#x\n", rcNt, Ios.Status));
5419
5420 /*
5421 * Read the image header and extract the timestamp and other useful info.
5422 */
5423 RT_ZERO(u);
5424 LARGE_INTEGER offRead;
5425 offRead.QuadPart = 0;
5426 rcNt = NtReadFile(hFile, NULL /*hEvent*/, NULL /*ApcRoutine*/, NULL /*ApcContext*/, &Ios,
5427 &u, (ULONG)sizeof(u), &offRead, NULL);
5428 if (NT_SUCCESS(rcNt) && NT_SUCCESS(Ios.Status))
5429 {
5430 uint32_t offNtHdrs = 0;
5431 if (u.MzHdr.e_magic == IMAGE_DOS_SIGNATURE)
5432 offNtHdrs = u.MzHdr.e_lfanew;
5433 if (offNtHdrs < sizeof(u) - sizeof(IMAGE_NT_HEADERS))
5434 {
5435 PIMAGE_NT_HEADERS64 pNtHdrs64 = (PIMAGE_NT_HEADERS64)&u.abBuf[offNtHdrs];
5436 PIMAGE_NT_HEADERS32 pNtHdrs32 = (PIMAGE_NT_HEADERS32)&u.abBuf[offNtHdrs];
5437 if (pNtHdrs64->Signature == IMAGE_NT_SIGNATURE)
5438 {
5439 SUP_DPRINTF((" NT Headers: %#x\n", offNtHdrs));
5440 SUP_DPRINTF((" Timestamp: %#x\n", pNtHdrs64->FileHeader.TimeDateStamp));
5441 SUP_DPRINTF((" Machine: %#x%s\n", pNtHdrs64->FileHeader.Machine,
5442 pNtHdrs64->FileHeader.Machine == IMAGE_FILE_MACHINE_I386 ? " - i386"
5443 : pNtHdrs64->FileHeader.Machine == IMAGE_FILE_MACHINE_AMD64 ? " - amd64" : ""));
5444 SUP_DPRINTF((" Timestamp: %#x\n", pNtHdrs64->FileHeader.TimeDateStamp));
5445 SUP_DPRINTF((" Image Version: %u.%u\n",
5446 pNtHdrs64->OptionalHeader.MajorImageVersion, pNtHdrs64->OptionalHeader.MinorImageVersion));
5447 SUP_DPRINTF((" SizeOfImage: %#x (%u)\n", pNtHdrs64->OptionalHeader.SizeOfImage, pNtHdrs64->OptionalHeader.SizeOfImage));
5448
5449 /*
5450 * Very crude way to extract info from the file version resource.
5451 */
5452 PIMAGE_SECTION_HEADER paSectHdrs = (PIMAGE_SECTION_HEADER)( (uintptr_t)&pNtHdrs64->OptionalHeader
5453 + pNtHdrs64->FileHeader.SizeOfOptionalHeader);
5454 IMAGE_DATA_DIRECTORY RsrcDir = { 0, 0 };
5455 if ( pNtHdrs64->FileHeader.SizeOfOptionalHeader == sizeof(IMAGE_OPTIONAL_HEADER64)
5456 && pNtHdrs64->OptionalHeader.NumberOfRvaAndSizes > IMAGE_DIRECTORY_ENTRY_RESOURCE)
5457 RsrcDir = pNtHdrs64->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE];
5458 else if ( pNtHdrs64->FileHeader.SizeOfOptionalHeader == sizeof(IMAGE_OPTIONAL_HEADER32)
5459 && pNtHdrs32->OptionalHeader.NumberOfRvaAndSizes > IMAGE_DIRECTORY_ENTRY_RESOURCE)
5460 RsrcDir = pNtHdrs32->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE];
5461 SUP_DPRINTF((" Resource Dir: %#x LB %#x\n", RsrcDir.VirtualAddress, RsrcDir.Size));
5462 if ( RsrcDir.VirtualAddress > offNtHdrs
5463 && RsrcDir.Size > 0
5464 && (uintptr_t)&u + sizeof(u) - (uintptr_t)paSectHdrs
5465 >= pNtHdrs64->FileHeader.NumberOfSections * sizeof(IMAGE_SECTION_HEADER) )
5466 {
5467 uint32_t uRvaRsrcSect = 0;
5468 uint32_t cbRsrcSect = 0;
5469 uint32_t offRsrcSect = 0;
5470 offRead.QuadPart = 0;
5471 for (uint32_t i = 0; i < pNtHdrs64->FileHeader.NumberOfSections; i++)
5472 {
5473 uRvaRsrcSect = paSectHdrs[i].VirtualAddress;
5474 cbRsrcSect = paSectHdrs[i].Misc.VirtualSize;
5475 offRsrcSect = paSectHdrs[i].PointerToRawData;
5476 if ( RsrcDir.VirtualAddress - uRvaRsrcSect < cbRsrcSect
5477 && offRsrcSect > offNtHdrs)
5478 {
5479 offRead.QuadPart = offRsrcSect + (RsrcDir.VirtualAddress - uRvaRsrcSect);
5480 break;
5481 }
5482 }
5483 if (offRead.QuadPart > 0)
5484 {
5485 RT_ZERO(u);
5486 rcNt = NtReadFile(hFile, NULL /*hEvent*/, NULL /*ApcRoutine*/, NULL /*ApcContext*/, &Ios,
5487 &u, (ULONG)sizeof(u), &offRead, NULL);
5488 PCRTUTF16 pwcVersionData = &u.awcBuf[0];
5489 size_t cbVersionData = sizeof(u);
5490
5491 if (NT_SUCCESS(rcNt) && NT_SUCCESS(Ios.Status))
5492 {
5493 /* Make it less crude by try find the version resource data. */
5494 uint32_t cbVersion;
5495 uint32_t uRvaVersion = supR3HardenedFindVersionRsrcRva(&u.ResDir, sizeof(u), &cbVersion);
5496 NOREF(uRvaVersion);
5497 if ( uRvaVersion != UINT32_MAX
5498 && cbVersion < cbRsrcSect
5499 && uRvaVersion - uRvaRsrcSect <= cbRsrcSect - cbVersion)
5500 {
5501 uint32_t const offVersion = uRvaVersion - uRvaRsrcSect;
5502 if ( offVersion < sizeof(u)
5503 && offVersion + cbVersion <= sizeof(u))
5504 {
5505 pwcVersionData = (PCRTUTF16)&u.abBuf[offVersion];
5506 cbVersionData = cbVersion;
5507 }
5508 else
5509 {
5510 offRead.QuadPart = offVersion + offRsrcSect;
5511 RT_ZERO(u);
5512 rcNt = NtReadFile(hFile, NULL /*hEvent*/, NULL /*ApcRoutine*/, NULL /*ApcContext*/, &Ios,
5513 &u, (ULONG)sizeof(u), &offRead, NULL);
5514 pwcVersionData = &u.awcBuf[0];
5515 cbVersionData = RT_MIN(cbVersion, sizeof(u));
5516 }
5517 }
5518 }
5519
5520 if (NT_SUCCESS(rcNt) && NT_SUCCESS(Ios.Status))
5521 {
5522 static const struct { PCRTUTF16 pwsz; size_t cb; bool fRet; } s_abFields[] =
5523 {
5524#define MY_WIDE_STR_TUPLE(a_sz, a_fRet) { L ## a_sz, sizeof(L ## a_sz) - sizeof(RTUTF16), a_fRet }
5525 MY_WIDE_STR_TUPLE("ProductName", false),
5526 MY_WIDE_STR_TUPLE("ProductVersion", false),
5527 MY_WIDE_STR_TUPLE("FileVersion", true),
5528 MY_WIDE_STR_TUPLE("SpecialBuild", false),
5529 MY_WIDE_STR_TUPLE("PrivateBuild", false),
5530 MY_WIDE_STR_TUPLE("FileDescription", false),
5531#undef MY_WIDE_STR_TUPLE
5532 };
5533 for (uint32_t i = 0; i < RT_ELEMENTS(s_abFields); i++)
5534 {
5535 if (cbVersionData <= s_abFields[i].cb + 10)
5536 continue;
5537 size_t cwcLeft = (cbVersionData - s_abFields[i].cb - 10) / sizeof(RTUTF16);
5538 PCRTUTF16 pwc = pwcVersionData;
5539 RTUTF16 const wcFirst = *s_abFields[i].pwsz;
5540 while (cwcLeft-- > 0)
5541 {
5542 if ( pwc[0] == 1 /* wType == text */
5543 && pwc[1] == wcFirst)
5544 {
5545 if (memcmp(pwc + 1, s_abFields[i].pwsz, s_abFields[i].cb + sizeof(RTUTF16)) == 0)
5546 {
5547 size_t cwcField = s_abFields[i].cb / sizeof(RTUTF16);
5548 pwc += cwcField + 2;
5549 cwcLeft -= cwcField + 2;
5550 for (uint32_t iPadding = 0; iPadding < 3; iPadding++, pwc++, cwcLeft--)
5551 if (*pwc)
5552 break;
5553 int rc = RTUtf16ValidateEncodingEx(pwc, cwcLeft,
5554 RTSTR_VALIDATE_ENCODING_ZERO_TERMINATED);
5555 if (RT_SUCCESS(rc))
5556 {
5557 SUP_DPRINTF((" %ls:%*s %ls",
5558 s_abFields[i].pwsz, cwcField < 15 ? 15 - cwcField : 0, "", pwc));
5559 if ( s_abFields[i].fRet
5560 && pwszFileVersion
5561 && cwcFileVersion > 1)
5562 RTUtf16Copy(pwszFileVersion, cwcFileVersion, pwc);
5563 }
5564 else
5565 SUP_DPRINTF((" %ls:%*s rc=%Rrc",
5566 s_abFields[i].pwsz, cwcField < 15 ? 15 - cwcField : 0, "", rc));
5567
5568 break;
5569 }
5570 }
5571 pwc++;
5572 }
5573 }
5574 }
5575 else
5576 SUP_DPRINTF((" NtReadFile @%#llx -> %#x %#x\n", offRead.QuadPart, rcNt, Ios.Status));
5577 }
5578 else
5579 SUP_DPRINTF((" Resource section not found.\n"));
5580 }
5581 }
5582 else
5583 SUP_DPRINTF((" Nt Headers @%#x: Invalid signature\n", offNtHdrs));
5584 }
5585 else
5586 SUP_DPRINTF((" Nt Headers @%#x: out side buffer\n", offNtHdrs));
5587 }
5588 else
5589 SUP_DPRINTF((" NtReadFile @0 -> %#x %#x\n", rcNt, Ios.Status));
5590 NtClose(hFile);
5591 }
5592}
5593
5594
5595/**
5596 * Scans the Driver directory for drivers which may invade our processes.
5597 *
5598 * @returns Mask of SUPHARDNT_ADVERSARY_XXX flags.
5599 *
5600 * @remarks The enumeration of \\Driver normally requires administrator
5601 * privileges. So, the detection we're doing here isn't always gonna
5602 * work just based on that.
5603 *
5604 * @todo Find drivers in \\FileSystems as well, then we could detect VrNsdDrv
5605 * from ViRobot APT Shield 2.0.
5606 */
5607static uint32_t supR3HardenedWinFindAdversaries(void)
5608{
5609 static const struct
5610 {
5611 uint32_t fAdversary;
5612 const char *pszDriver;
5613 } s_aDrivers[] =
5614 {
5615 { SUPHARDNT_ADVERSARY_SYMANTEC_SYSPLANT, "SysPlant" },
5616
5617 { SUPHARDNT_ADVERSARY_SYMANTEC_N360, "SRTSPX" },
5618 { SUPHARDNT_ADVERSARY_SYMANTEC_N360, "SymDS" },
5619 { SUPHARDNT_ADVERSARY_SYMANTEC_N360, "SymEvent" },
5620 { SUPHARDNT_ADVERSARY_SYMANTEC_N360, "SymIRON" },
5621 { SUPHARDNT_ADVERSARY_SYMANTEC_N360, "SymNetS" },
5622
5623 { SUPHARDNT_ADVERSARY_AVAST, "aswHwid" },
5624 { SUPHARDNT_ADVERSARY_AVAST, "aswMonFlt" },
5625 { SUPHARDNT_ADVERSARY_AVAST, "aswRdr2" },
5626 { SUPHARDNT_ADVERSARY_AVAST, "aswRvrt" },
5627 { SUPHARDNT_ADVERSARY_AVAST, "aswSnx" },
5628 { SUPHARDNT_ADVERSARY_AVAST, "aswsp" },
5629 { SUPHARDNT_ADVERSARY_AVAST, "aswStm" },
5630 { SUPHARDNT_ADVERSARY_AVAST, "aswVmm" },
5631
5632 { SUPHARDNT_ADVERSARY_TRENDMICRO, "tmcomm" },
5633 { SUPHARDNT_ADVERSARY_TRENDMICRO, "tmactmon" },
5634 { SUPHARDNT_ADVERSARY_TRENDMICRO, "tmevtmgr" },
5635 { SUPHARDNT_ADVERSARY_TRENDMICRO, "tmtdi" },
5636 { SUPHARDNT_ADVERSARY_TRENDMICRO, "tmebc64" }, /* Titanium internet security, not officescan. */
5637 { SUPHARDNT_ADVERSARY_TRENDMICRO, "tmeevw" }, /* Titanium internet security, not officescan. */
5638 { SUPHARDNT_ADVERSARY_TRENDMICRO, "tmciesc" }, /* Titanium internet security, not officescan. */
5639
5640 { SUPHARDNT_ADVERSARY_MCAFEE, "cfwids" },
5641 { SUPHARDNT_ADVERSARY_MCAFEE, "McPvDrv" },
5642 { SUPHARDNT_ADVERSARY_MCAFEE, "mfeapfk" },
5643 { SUPHARDNT_ADVERSARY_MCAFEE, "mfeavfk" },
5644 { SUPHARDNT_ADVERSARY_MCAFEE, "mfefirek" },
5645 { SUPHARDNT_ADVERSARY_MCAFEE, "mfehidk" },
5646 { SUPHARDNT_ADVERSARY_MCAFEE, "mfencbdc" },
5647 { SUPHARDNT_ADVERSARY_MCAFEE, "mfewfpk" },
5648
5649 { SUPHARDNT_ADVERSARY_KASPERSKY, "kl1" },
5650 { SUPHARDNT_ADVERSARY_KASPERSKY, "klflt" },
5651 { SUPHARDNT_ADVERSARY_KASPERSKY, "klif" },
5652 { SUPHARDNT_ADVERSARY_KASPERSKY, "KLIM6" },
5653 { SUPHARDNT_ADVERSARY_KASPERSKY, "klkbdflt" },
5654 { SUPHARDNT_ADVERSARY_KASPERSKY, "klmouflt" },
5655 { SUPHARDNT_ADVERSARY_KASPERSKY, "kltdi" },
5656 { SUPHARDNT_ADVERSARY_KASPERSKY, "kneps" },
5657
5658 { SUPHARDNT_ADVERSARY_MBAM, "MBAMWebAccessControl" },
5659 { SUPHARDNT_ADVERSARY_MBAM, "mbam" },
5660 { SUPHARDNT_ADVERSARY_MBAM, "mbamchameleon" },
5661 { SUPHARDNT_ADVERSARY_MBAM, "mwav" },
5662 { SUPHARDNT_ADVERSARY_MBAM, "mbamswissarmy" },
5663
5664 { SUPHARDNT_ADVERSARY_AVG, "avgfwfd" },
5665 { SUPHARDNT_ADVERSARY_AVG, "avgtdia" },
5666
5667 { SUPHARDNT_ADVERSARY_PANDA, "PSINAflt" },
5668 { SUPHARDNT_ADVERSARY_PANDA, "PSINFile" },
5669 { SUPHARDNT_ADVERSARY_PANDA, "PSINKNC" },
5670 { SUPHARDNT_ADVERSARY_PANDA, "PSINProc" },
5671 { SUPHARDNT_ADVERSARY_PANDA, "PSINProt" },
5672 { SUPHARDNT_ADVERSARY_PANDA, "PSINReg" },
5673 { SUPHARDNT_ADVERSARY_PANDA, "PSKMAD" },
5674 { SUPHARDNT_ADVERSARY_PANDA, "NNSAlpc" },
5675 { SUPHARDNT_ADVERSARY_PANDA, "NNSHttp" },
5676 { SUPHARDNT_ADVERSARY_PANDA, "NNShttps" },
5677 { SUPHARDNT_ADVERSARY_PANDA, "NNSIds" },
5678 { SUPHARDNT_ADVERSARY_PANDA, "NNSNAHSL" },
5679 { SUPHARDNT_ADVERSARY_PANDA, "NNSpicc" },
5680 { SUPHARDNT_ADVERSARY_PANDA, "NNSPihsw" },
5681 { SUPHARDNT_ADVERSARY_PANDA, "NNSPop3" },
5682 { SUPHARDNT_ADVERSARY_PANDA, "NNSProt" },
5683 { SUPHARDNT_ADVERSARY_PANDA, "NNSPrv" },
5684 { SUPHARDNT_ADVERSARY_PANDA, "NNSSmtp" },
5685 { SUPHARDNT_ADVERSARY_PANDA, "NNSStrm" },
5686 { SUPHARDNT_ADVERSARY_PANDA, "NNStlsc" },
5687
5688 { SUPHARDNT_ADVERSARY_MSE, "NisDrv" },
5689
5690 /*{ SUPHARDNT_ADVERSARY_COMODO, "cmdguard" }, file system */
5691 { SUPHARDNT_ADVERSARY_COMODO, "inspect" },
5692 { SUPHARDNT_ADVERSARY_COMODO, "cmdHlp" },
5693
5694 { SUPHARDNT_ADVERSARY_DIGITAL_GUARDIAN_OLD, "dgmaster" },
5695
5696 { SUPHARDNT_ADVERSARY_CYLANCE, "cyprotectdrv" }, /* Not verified. */
5697
5698 { SUPHARDNT_ADVERSARY_BEYONDTRUST, "privman" }, /* Not verified. */
5699
5700 { SUPHARDNT_ADVERSARY_AVECTO, "PGDriver" },
5701 };
5702
5703 static const struct
5704 {
5705 uint32_t fAdversary;
5706 PCRTUTF16 pwszFile;
5707 } s_aFiles[] =
5708 {
5709 { SUPHARDNT_ADVERSARY_SYMANTEC_SYSPLANT, L"\\SystemRoot\\System32\\drivers\\SysPlant.sys" },
5710 { SUPHARDNT_ADVERSARY_SYMANTEC_SYSPLANT, L"\\SystemRoot\\System32\\sysfer.dll" },
5711 { SUPHARDNT_ADVERSARY_SYMANTEC_SYSPLANT, L"\\SystemRoot\\System32\\sysferThunk.dll" },
5712
5713 { SUPHARDNT_ADVERSARY_SYMANTEC_N360, L"\\SystemRoot\\System32\\drivers\\N360x64\\1505000.013\\ccsetx64.sys" },
5714 { SUPHARDNT_ADVERSARY_SYMANTEC_N360, L"\\SystemRoot\\System32\\drivers\\N360x64\\1505000.013\\ironx64.sys" },
5715 { SUPHARDNT_ADVERSARY_SYMANTEC_N360, L"\\SystemRoot\\System32\\drivers\\N360x64\\1505000.013\\srtsp64.sys" },
5716 { SUPHARDNT_ADVERSARY_SYMANTEC_N360, L"\\SystemRoot\\System32\\drivers\\N360x64\\1505000.013\\srtspx64.sys" },
5717 { SUPHARDNT_ADVERSARY_SYMANTEC_N360, L"\\SystemRoot\\System32\\drivers\\N360x64\\1505000.013\\symds64.sys" },
5718 { SUPHARDNT_ADVERSARY_SYMANTEC_N360, L"\\SystemRoot\\System32\\drivers\\N360x64\\1505000.013\\symefa64.sys" },
5719 { SUPHARDNT_ADVERSARY_SYMANTEC_N360, L"\\SystemRoot\\System32\\drivers\\N360x64\\1505000.013\\symelam.sys" },
5720 { SUPHARDNT_ADVERSARY_SYMANTEC_N360, L"\\SystemRoot\\System32\\drivers\\N360x64\\1505000.013\\symnets.sys" },
5721 { SUPHARDNT_ADVERSARY_SYMANTEC_N360, L"\\SystemRoot\\System32\\drivers\\symevent64x86.sys" },
5722
5723 { SUPHARDNT_ADVERSARY_AVAST, L"\\SystemRoot\\System32\\drivers\\aswHwid.sys" },
5724 { SUPHARDNT_ADVERSARY_AVAST, L"\\SystemRoot\\System32\\drivers\\aswMonFlt.sys" },
5725 { SUPHARDNT_ADVERSARY_AVAST, L"\\SystemRoot\\System32\\drivers\\aswRdr2.sys" },
5726 { SUPHARDNT_ADVERSARY_AVAST, L"\\SystemRoot\\System32\\drivers\\aswRvrt.sys" },
5727 { SUPHARDNT_ADVERSARY_AVAST, L"\\SystemRoot\\System32\\drivers\\aswSnx.sys" },
5728 { SUPHARDNT_ADVERSARY_AVAST, L"\\SystemRoot\\System32\\drivers\\aswsp.sys" },
5729 { SUPHARDNT_ADVERSARY_AVAST, L"\\SystemRoot\\System32\\drivers\\aswStm.sys" },
5730 { SUPHARDNT_ADVERSARY_AVAST, L"\\SystemRoot\\System32\\drivers\\aswVmm.sys" },
5731
5732 { SUPHARDNT_ADVERSARY_TRENDMICRO, L"\\SystemRoot\\System32\\drivers\\tmcomm.sys" },
5733 { SUPHARDNT_ADVERSARY_TRENDMICRO, L"\\SystemRoot\\System32\\drivers\\tmactmon.sys" },
5734 { SUPHARDNT_ADVERSARY_TRENDMICRO, L"\\SystemRoot\\System32\\drivers\\tmevtmgr.sys" },
5735 { SUPHARDNT_ADVERSARY_TRENDMICRO, L"\\SystemRoot\\System32\\drivers\\tmtdi.sys" },
5736 { SUPHARDNT_ADVERSARY_TRENDMICRO, L"\\SystemRoot\\System32\\drivers\\tmebc64.sys" },
5737 { SUPHARDNT_ADVERSARY_TRENDMICRO, L"\\SystemRoot\\System32\\drivers\\tmeevw.sys" },
5738 { SUPHARDNT_ADVERSARY_TRENDMICRO, L"\\SystemRoot\\System32\\drivers\\tmciesc.sys" },
5739 { SUPHARDNT_ADVERSARY_TRENDMICRO_SAKFILE, L"\\SystemRoot\\System32\\drivers\\sakfile.sys" }, /* Data Loss Prevention, not officescan. */
5740 { SUPHARDNT_ADVERSARY_TRENDMICRO, L"\\SystemRoot\\System32\\drivers\\sakcd.sys" }, /* Data Loss Prevention, not officescan. */
5741
5742
5743 { SUPHARDNT_ADVERSARY_MCAFEE, L"\\SystemRoot\\System32\\drivers\\cfwids.sys" },
5744 { SUPHARDNT_ADVERSARY_MCAFEE, L"\\SystemRoot\\System32\\drivers\\McPvDrv.sys" },
5745 { SUPHARDNT_ADVERSARY_MCAFEE, L"\\SystemRoot\\System32\\drivers\\mfeapfk.sys" },
5746 { SUPHARDNT_ADVERSARY_MCAFEE, L"\\SystemRoot\\System32\\drivers\\mfeavfk.sys" },
5747 { SUPHARDNT_ADVERSARY_MCAFEE, L"\\SystemRoot\\System32\\drivers\\mfefirek.sys" },
5748 { SUPHARDNT_ADVERSARY_MCAFEE, L"\\SystemRoot\\System32\\drivers\\mfehidk.sys" },
5749 { SUPHARDNT_ADVERSARY_MCAFEE, L"\\SystemRoot\\System32\\drivers\\mfencbdc.sys" },
5750 { SUPHARDNT_ADVERSARY_MCAFEE, L"\\SystemRoot\\System32\\drivers\\mfewfpk.sys" },
5751
5752 { SUPHARDNT_ADVERSARY_KASPERSKY, L"\\SystemRoot\\System32\\drivers\\kl1.sys" },
5753 { SUPHARDNT_ADVERSARY_KASPERSKY, L"\\SystemRoot\\System32\\drivers\\klflt.sys" },
5754 { SUPHARDNT_ADVERSARY_KASPERSKY, L"\\SystemRoot\\System32\\drivers\\klif.sys" },
5755 { SUPHARDNT_ADVERSARY_KASPERSKY, L"\\SystemRoot\\System32\\drivers\\klim6.sys" },
5756 { SUPHARDNT_ADVERSARY_KASPERSKY, L"\\SystemRoot\\System32\\drivers\\klkbdflt.sys" },
5757 { SUPHARDNT_ADVERSARY_KASPERSKY, L"\\SystemRoot\\System32\\drivers\\klmouflt.sys" },
5758 { SUPHARDNT_ADVERSARY_KASPERSKY, L"\\SystemRoot\\System32\\drivers\\kltdi.sys" },
5759 { SUPHARDNT_ADVERSARY_KASPERSKY, L"\\SystemRoot\\System32\\drivers\\kneps.sys" },
5760 { SUPHARDNT_ADVERSARY_KASPERSKY, L"\\SystemRoot\\System32\\klfphc.dll" },
5761
5762 { SUPHARDNT_ADVERSARY_MBAM, L"\\SystemRoot\\System32\\drivers\\MBAMSwissArmy.sys" },
5763 { SUPHARDNT_ADVERSARY_MBAM, L"\\SystemRoot\\System32\\drivers\\mwac.sys" },
5764 { SUPHARDNT_ADVERSARY_MBAM, L"\\SystemRoot\\System32\\drivers\\mbamchameleon.sys" },
5765 { SUPHARDNT_ADVERSARY_MBAM, L"\\SystemRoot\\System32\\drivers\\mbam.sys" },
5766
5767 { SUPHARDNT_ADVERSARY_AVG, L"\\SystemRoot\\System32\\drivers\\avgrkx64.sys" },
5768 { SUPHARDNT_ADVERSARY_AVG, L"\\SystemRoot\\System32\\drivers\\avgmfx64.sys" },
5769 { SUPHARDNT_ADVERSARY_AVG, L"\\SystemRoot\\System32\\drivers\\avgidsdrivera.sys" },
5770 { SUPHARDNT_ADVERSARY_AVG, L"\\SystemRoot\\System32\\drivers\\avgidsha.sys" },
5771 { SUPHARDNT_ADVERSARY_AVG, L"\\SystemRoot\\System32\\drivers\\avgtdia.sys" },
5772 { SUPHARDNT_ADVERSARY_AVG, L"\\SystemRoot\\System32\\drivers\\avgloga.sys" },
5773 { SUPHARDNT_ADVERSARY_AVG, L"\\SystemRoot\\System32\\drivers\\avgldx64.sys" },
5774 { SUPHARDNT_ADVERSARY_AVG, L"\\SystemRoot\\System32\\drivers\\avgdiska.sys" },
5775
5776 { SUPHARDNT_ADVERSARY_PANDA, L"\\SystemRoot\\System32\\drivers\\PSINAflt.sys" },
5777 { SUPHARDNT_ADVERSARY_PANDA, L"\\SystemRoot\\System32\\drivers\\PSINFile.sys" },
5778 { SUPHARDNT_ADVERSARY_PANDA, L"\\SystemRoot\\System32\\drivers\\PSINKNC.sys" },
5779 { SUPHARDNT_ADVERSARY_PANDA, L"\\SystemRoot\\System32\\drivers\\PSINProc.sys" },
5780 { SUPHARDNT_ADVERSARY_PANDA, L"\\SystemRoot\\System32\\drivers\\PSINProt.sys" },
5781 { SUPHARDNT_ADVERSARY_PANDA, L"\\SystemRoot\\System32\\drivers\\PSINReg.sys" },
5782 { SUPHARDNT_ADVERSARY_PANDA, L"\\SystemRoot\\System32\\drivers\\PSKMAD.sys" },
5783 { SUPHARDNT_ADVERSARY_PANDA, L"\\SystemRoot\\System32\\drivers\\NNSAlpc.sys" },
5784 { SUPHARDNT_ADVERSARY_PANDA, L"\\SystemRoot\\System32\\drivers\\NNSHttp.sys" },
5785 { SUPHARDNT_ADVERSARY_PANDA, L"\\SystemRoot\\System32\\drivers\\NNShttps.sys" },
5786 { SUPHARDNT_ADVERSARY_PANDA, L"\\SystemRoot\\System32\\drivers\\NNSIds.sys" },
5787 { SUPHARDNT_ADVERSARY_PANDA, L"\\SystemRoot\\System32\\drivers\\NNSNAHSL.sys" },
5788 { SUPHARDNT_ADVERSARY_PANDA, L"\\SystemRoot\\System32\\drivers\\NNSpicc.sys" },
5789 { SUPHARDNT_ADVERSARY_PANDA, L"\\SystemRoot\\System32\\drivers\\NNSPihsw.sys" },
5790 { SUPHARDNT_ADVERSARY_PANDA, L"\\SystemRoot\\System32\\drivers\\NNSPop3.sys" },
5791 { SUPHARDNT_ADVERSARY_PANDA, L"\\SystemRoot\\System32\\drivers\\NNSProt.sys" },
5792 { SUPHARDNT_ADVERSARY_PANDA, L"\\SystemRoot\\System32\\drivers\\NNSPrv.sys" },
5793 { SUPHARDNT_ADVERSARY_PANDA, L"\\SystemRoot\\System32\\drivers\\NNSSmtp.sys" },
5794 { SUPHARDNT_ADVERSARY_PANDA, L"\\SystemRoot\\System32\\drivers\\NNSStrm.sys" },
5795 { SUPHARDNT_ADVERSARY_PANDA, L"\\SystemRoot\\System32\\drivers\\NNStlsc.sys" },
5796
5797 { SUPHARDNT_ADVERSARY_MSE, L"\\SystemRoot\\System32\\drivers\\MpFilter.sys" },
5798 { SUPHARDNT_ADVERSARY_MSE, L"\\SystemRoot\\System32\\drivers\\NisDrvWFP.sys" },
5799
5800 { SUPHARDNT_ADVERSARY_COMODO, L"\\SystemRoot\\System32\\drivers\\cmdguard.sys" },
5801 { SUPHARDNT_ADVERSARY_COMODO, L"\\SystemRoot\\System32\\drivers\\cmderd.sys" },
5802 { SUPHARDNT_ADVERSARY_COMODO, L"\\SystemRoot\\System32\\drivers\\inspect.sys" },
5803 { SUPHARDNT_ADVERSARY_COMODO, L"\\SystemRoot\\System32\\drivers\\cmdhlp.sys" },
5804 { SUPHARDNT_ADVERSARY_COMODO, L"\\SystemRoot\\System32\\drivers\\cfrmd.sys" },
5805 { SUPHARDNT_ADVERSARY_COMODO, L"\\SystemRoot\\System32\\drivers\\hmd.sys" },
5806 { SUPHARDNT_ADVERSARY_COMODO, L"\\SystemRoot\\System32\\guard64.dll" },
5807 { SUPHARDNT_ADVERSARY_COMODO, L"\\SystemRoot\\System32\\cmdvrt64.dll" },
5808 { SUPHARDNT_ADVERSARY_COMODO, L"\\SystemRoot\\System32\\cmdkbd64.dll" },
5809 { SUPHARDNT_ADVERSARY_COMODO, L"\\SystemRoot\\System32\\cmdcsr.dll" },
5810
5811 { SUPHARDNT_ADVERSARY_ZONE_ALARM, L"\\SystemRoot\\System32\\drivers\\vsdatant.sys" },
5812 { SUPHARDNT_ADVERSARY_ZONE_ALARM, L"\\SystemRoot\\System32\\AntiTheftCredentialProvider.dll" },
5813
5814 { SUPHARDNT_ADVERSARY_DIGITAL_GUARDIAN_OLD, L"\\SystemRoot\\System32\\drivers\\dgmaster.sys" },
5815
5816 { SUPHARDNT_ADVERSARY_CYLANCE, L"\\SystemRoot\\System32\\drivers\\cyprotectdrv32.sys" },
5817 { SUPHARDNT_ADVERSARY_CYLANCE, L"\\SystemRoot\\System32\\drivers\\cyprotectdrv64.sys" },
5818
5819 { SUPHARDNT_ADVERSARY_BEYONDTRUST, L"\\SystemRoot\\System32\\drivers\\privman.sys" },
5820 { SUPHARDNT_ADVERSARY_BEYONDTRUST, L"\\SystemRoot\\System32\\privman64.dll" },
5821 { SUPHARDNT_ADVERSARY_BEYONDTRUST, L"\\SystemRoot\\System32\\privman32.dll" },
5822
5823 { SUPHARDNT_ADVERSARY_AVECTO, L"\\SystemRoot\\System32\\drivers\\PGDriver.sys" },
5824 };
5825
5826 uint32_t fFound = 0;
5827
5828 /*
5829 * Open the driver object directory.
5830 */
5831 UNICODE_STRING NtDirName = RTNT_CONSTANT_UNISTR(L"\\Driver");
5832
5833 OBJECT_ATTRIBUTES ObjAttr;
5834 InitializeObjectAttributes(&ObjAttr, &NtDirName, OBJ_CASE_INSENSITIVE, NULL /*hRootDir*/, NULL /*pSecDesc*/);
5835
5836 HANDLE hDir;
5837 NTSTATUS rcNt = NtOpenDirectoryObject(&hDir, DIRECTORY_QUERY | FILE_LIST_DIRECTORY, &ObjAttr);
5838#ifdef VBOX_STRICT
5839 if (rcNt != STATUS_ACCESS_DENIED) /* non-admin */
5840 SUPR3HARDENED_ASSERT_NT_SUCCESS(rcNt);
5841#endif
5842 if (NT_SUCCESS(rcNt))
5843 {
5844 /*
5845 * Enumerate it, looking for the driver.
5846 */
5847 ULONG uObjDirCtx = 0;
5848 for (;;)
5849 {
5850 uint32_t abBuffer[_64K + _1K];
5851 ULONG cbActual;
5852 rcNt = NtQueryDirectoryObject(hDir,
5853 abBuffer,
5854 sizeof(abBuffer) - 4, /* minus four for string terminator space. */
5855 FALSE /*ReturnSingleEntry */,
5856 FALSE /*RestartScan*/,
5857 &uObjDirCtx,
5858 &cbActual);
5859 if (!NT_SUCCESS(rcNt) || cbActual < sizeof(OBJECT_DIRECTORY_INFORMATION))
5860 break;
5861
5862 POBJECT_DIRECTORY_INFORMATION pObjDir = (POBJECT_DIRECTORY_INFORMATION)abBuffer;
5863 while (pObjDir->Name.Length != 0)
5864 {
5865 WCHAR wcSaved = pObjDir->Name.Buffer[pObjDir->Name.Length / sizeof(WCHAR)];
5866 pObjDir->Name.Buffer[pObjDir->Name.Length / sizeof(WCHAR)] = '\0';
5867
5868 for (uint32_t i = 0; i < RT_ELEMENTS(s_aDrivers); i++)
5869 if (RTUtf16ICmpAscii(pObjDir->Name.Buffer, s_aDrivers[i].pszDriver) == 0)
5870 {
5871 fFound |= s_aDrivers[i].fAdversary;
5872 SUP_DPRINTF(("Found driver %s (%#x)\n", s_aDrivers[i].pszDriver, s_aDrivers[i].fAdversary));
5873 break;
5874 }
5875
5876 pObjDir->Name.Buffer[pObjDir->Name.Length / sizeof(WCHAR)] = wcSaved;
5877
5878 /* Next directory entry. */
5879 pObjDir++;
5880 }
5881 }
5882
5883 NtClose(hDir);
5884 }
5885 else
5886 SUP_DPRINTF(("NtOpenDirectoryObject failed on \\Driver: %#x\n", rcNt));
5887
5888 /*
5889 * Look for files.
5890 */
5891 for (uint32_t i = 0; i < RT_ELEMENTS(s_aFiles); i++)
5892 {
5893 HANDLE hFile = RTNT_INVALID_HANDLE_VALUE;
5894 IO_STATUS_BLOCK Ios = RTNT_IO_STATUS_BLOCK_INITIALIZER;
5895 UNICODE_STRING UniStrName;
5896 UniStrName.Buffer = (WCHAR *)s_aFiles[i].pwszFile;
5897 UniStrName.Length = (USHORT)(RTUtf16Len(s_aFiles[i].pwszFile) * sizeof(WCHAR));
5898 UniStrName.MaximumLength = UniStrName.Length + sizeof(WCHAR);
5899 InitializeObjectAttributes(&ObjAttr, &UniStrName, OBJ_CASE_INSENSITIVE, NULL /*hRootDir*/, NULL /*pSecDesc*/);
5900 rcNt = NtCreateFile(&hFile, GENERIC_READ | SYNCHRONIZE, &ObjAttr, &Ios, NULL /* Allocation Size*/,
5901 FILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ, FILE_OPEN,
5902 FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT, NULL /*EaBuffer*/, 0 /*EaLength*/);
5903 if (NT_SUCCESS(rcNt) && NT_SUCCESS(Ios.Status))
5904 {
5905 fFound |= s_aFiles[i].fAdversary;
5906 NtClose(hFile);
5907 }
5908 }
5909
5910 /*
5911 * Log details and upgrade select adversaries.
5912 */
5913 SUP_DPRINTF(("supR3HardenedWinFindAdversaries: %#x\n", fFound));
5914 for (uint32_t i = 0; i < RT_ELEMENTS(s_aFiles); i++)
5915 if (s_aFiles[i].fAdversary & fFound)
5916 {
5917 if (!(s_aFiles[i].fAdversary & SUPHARDNT_ADVERSARY_DIGITAL_GUARDIAN_OLD))
5918 supR3HardenedLogFileInfo(s_aFiles[i].pwszFile, NULL, 0);
5919 else
5920 {
5921 /*
5922 * See if it's a newer version of the driver which doesn't BSODs when we free
5923 * its memory. To use RTStrVersionCompare we do a rough UTF-16 -> ASCII conversion.
5924 */
5925 union
5926 {
5927 char szFileVersion[64];
5928 RTUTF16 wszFileVersion[32];
5929 } uBuf;
5930 supR3HardenedLogFileInfo(s_aFiles[i].pwszFile, uBuf.wszFileVersion, RT_ELEMENTS(uBuf.wszFileVersion));
5931 if (uBuf.wszFileVersion[0])
5932 {
5933 for (uint32_t off = 0; off < RT_ELEMENTS(uBuf.wszFileVersion); off++)
5934 {
5935 RTUTF16 wch = uBuf.wszFileVersion[off];
5936 uBuf.szFileVersion[off] = (char)wch;
5937 if (!wch)
5938 break;
5939 }
5940 uBuf.szFileVersion[RT_ELEMENTS(uBuf.wszFileVersion)] = '\0';
5941#define VER_IN_RANGE(a_pszFirst, a_pszLast) \
5942 (RTStrVersionCompare(uBuf.szFileVersion, a_pszFirst) >= 0 && RTStrVersionCompare(uBuf.szFileVersion, a_pszLast) <= 0)
5943 if ( VER_IN_RANGE("7.3.2.0000", "999999999.9.9.9999")
5944 || VER_IN_RANGE("7.3.1.1000", "7.3.1.3000")
5945 || VER_IN_RANGE("7.3.0.3000", "7.3.0.999999999")
5946 || VER_IN_RANGE("7.2.1.3000", "7.2.999999999.999999999") )
5947 {
5948 uint32_t const fOldFound = fFound;
5949 fFound = (fOldFound & ~SUPHARDNT_ADVERSARY_DIGITAL_GUARDIAN_OLD)
5950 | SUPHARDNT_ADVERSARY_DIGITAL_GUARDIAN_NEW;
5951 SUP_DPRINTF(("supR3HardenedWinFindAdversaries: Found newer version: %#x -> %#x\n", fOldFound, fFound));
5952 }
5953 }
5954 }
5955 }
5956
5957 return fFound;
5958}
5959
5960
5961extern "C" int main(int argc, char **argv, char **envp);
5962
5963/**
5964 * The executable entry point.
5965 *
5966 * This is normally taken care of by the C runtime library, but we don't want to
5967 * get involved with anything as complicated like the CRT in this setup. So, we
5968 * it everything ourselves, including parameter parsing.
5969 */
5970extern "C" void __stdcall suplibHardenedWindowsMain(void)
5971{
5972 RTEXITCODE rcExit = RTEXITCODE_FAILURE;
5973
5974 g_cSuplibHardenedWindowsMainCalls++;
5975 g_enmSupR3HardenedMainState = SUPR3HARDENEDMAINSTATE_WIN_EP_CALLED;
5976
5977 /*
5978 * Initialize the NTDLL API wrappers. This aims at bypassing patched NTDLL
5979 * in all the processes leading up the VM process.
5980 */
5981 supR3HardenedWinInitImports();
5982 g_enmSupR3HardenedMainState = SUPR3HARDENEDMAINSTATE_WIN_IMPORTS_RESOLVED;
5983
5984 /*
5985 * Notify the parent process that we're probably capable of reporting our
5986 * own errors.
5987 */
5988 if (g_ProcParams.hEvtParent || g_ProcParams.hEvtChild)
5989 {
5990 SUPR3HARDENED_ASSERT(g_fSupEarlyProcessInit);
5991
5992 g_ProcParams.enmRequest = kSupR3WinChildReq_CloseEvents;
5993 NtSetEvent(g_ProcParams.hEvtParent, NULL);
5994
5995 NtClose(g_ProcParams.hEvtParent);
5996 NtClose(g_ProcParams.hEvtChild);
5997 g_ProcParams.hEvtParent = NULL;
5998 g_ProcParams.hEvtChild = NULL;
5999 }
6000 else
6001 SUPR3HARDENED_ASSERT(!g_fSupEarlyProcessInit);
6002
6003 /*
6004 * After having resolved imports we patch the LdrInitializeThunk code so
6005 * that it's more difficult to invade our privacy by CreateRemoteThread.
6006 * We'll re-enable this after opening the driver or temporarily while respawning.
6007 */
6008 supR3HardenedWinDisableThreadCreation();
6009
6010 /*
6011 * Init g_uNtVerCombined. (The code is shared with SUPR3.lib and lives in
6012 * SUPHardenedVerfiyImage-win.cpp.)
6013 */
6014 supR3HardenedWinInitVersion(false /*fEarly*/);
6015 g_enmSupR3HardenedMainState = SUPR3HARDENEDMAINSTATE_WIN_VERSION_INITIALIZED;
6016
6017 /*
6018 * Convert the arguments to UTF-8 and open the log file if specified.
6019 * This must be done as early as possible since the code below may fail.
6020 */
6021 PUNICODE_STRING pCmdLineStr = &NtCurrentPeb()->ProcessParameters->CommandLine;
6022 int cArgs;
6023 char **papszArgs = suplibCommandLineToArgvWStub(pCmdLineStr->Buffer, pCmdLineStr->Length / sizeof(WCHAR), &cArgs);
6024
6025 supR3HardenedOpenLog(&cArgs, papszArgs);
6026
6027 /*
6028 * Log information about important system files.
6029 */
6030 supR3HardenedLogFileInfo(L"\\SystemRoot\\System32\\ntdll.dll", NULL /*pwszFileVersion*/, 0 /*cwcFileVersion*/);
6031 supR3HardenedLogFileInfo(L"\\SystemRoot\\System32\\kernel32.dll", NULL /*pwszFileVersion*/, 0 /*cwcFileVersion*/);
6032 supR3HardenedLogFileInfo(L"\\SystemRoot\\System32\\KernelBase.dll", NULL /*pwszFileVersion*/, 0 /*cwcFileVersion*/);
6033 supR3HardenedLogFileInfo(L"\\SystemRoot\\System32\\apisetschema.dll", NULL /*pwszFileVersion*/, 0 /*cwcFileVersion*/);
6034
6035 /*
6036 * Scan the system for adversaries, logging information about them.
6037 */
6038 g_fSupAdversaries = supR3HardenedWinFindAdversaries();
6039
6040 /*
6041 * Get the executable name, make sure it's the long version.
6042 */
6043 DWORD cwcExecName = GetModuleFileNameW(GetModuleHandleW(NULL), g_wszSupLibHardenedExePath,
6044 RT_ELEMENTS(g_wszSupLibHardenedExePath));
6045 if (cwcExecName >= RT_ELEMENTS(g_wszSupLibHardenedExePath))
6046 supR3HardenedFatalMsg("suplibHardenedWindowsMain", kSupInitOp_Integrity, VERR_BUFFER_OVERFLOW,
6047 "The executable path is too long.");
6048
6049 RTUTF16 wszLong[RT_ELEMENTS(g_wszSupLibHardenedExePath)];
6050 DWORD cwcLong = GetLongPathNameW(g_wszSupLibHardenedExePath, wszLong, RT_ELEMENTS(wszLong));
6051 if (cwcLong > 0)
6052 {
6053 memcpy(g_wszSupLibHardenedExePath, wszLong, (cwcLong + 1) * sizeof(RTUTF16));
6054 cwcExecName = cwcLong;
6055 }
6056
6057 /* The NT version of it. */
6058 HANDLE hFile = CreateFileW(g_wszSupLibHardenedExePath, GENERIC_READ, FILE_SHARE_READ, NULL /*pSecurityAttributes*/,
6059 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL /*hTemplateFile*/);
6060 if (hFile == NULL || hFile == INVALID_HANDLE_VALUE)
6061 supR3HardenedFatalMsg("suplibHardenedWindowsMain", kSupInitOp_Integrity, RTErrConvertFromWin32(RtlGetLastWin32Error()),
6062 "Error opening the executable: %u (%ls).", RtlGetLastWin32Error());
6063 RT_ZERO(g_SupLibHardenedExeNtPath);
6064 ULONG cbIgn;
6065 NTSTATUS rcNt = NtQueryObject(hFile, ObjectNameInformation, &g_SupLibHardenedExeNtPath,
6066 sizeof(g_SupLibHardenedExeNtPath) - sizeof(WCHAR), &cbIgn);
6067 if (!NT_SUCCESS(rcNt))
6068 supR3HardenedFatalMsg("suplibHardenedWindowsMain", kSupInitOp_Integrity, RTErrConvertFromNtStatus(rcNt),
6069 "NtQueryObject -> %#x (on %ls)\n", rcNt, g_wszSupLibHardenedExePath);
6070 NtClose(hFile);
6071
6072 /* The NT executable name offset / dir path length. */
6073 g_offSupLibHardenedExeNtName = g_SupLibHardenedExeNtPath.UniStr.Length / sizeof(WCHAR);
6074 while ( g_offSupLibHardenedExeNtName > 1
6075 && g_SupLibHardenedExeNtPath.UniStr.Buffer[g_offSupLibHardenedExeNtName - 1] != '\\' )
6076 g_offSupLibHardenedExeNtName--;
6077
6078 /*
6079 * Preliminary app binary path init. May change when SUPR3HardenedMain is
6080 * called (via main below).
6081 */
6082 supR3HardenedWinInitAppBin(SUPSECMAIN_FLAGS_LOC_APP_BIN);
6083
6084 /*
6085 * If we've done early init already, register the DLL load notification
6086 * callback and reinstall the NtDll patches.
6087 */
6088 if (g_fSupEarlyProcessInit)
6089 {
6090 supR3HardenedWinRegisterDllNotificationCallback();
6091 supR3HardenedWinReInstallHooks(false /*fFirstCall */);
6092 }
6093
6094 /*
6095 * Call the C/C++ main function.
6096 */
6097 SUP_DPRINTF(("Calling main()\n"));
6098 rcExit = (RTEXITCODE)main(cArgs, papszArgs, NULL);
6099
6100 /*
6101 * Exit the process (never return).
6102 */
6103 SUP_DPRINTF(("Terminating the normal way: rcExit=%d\n", rcExit));
6104 suplibHardenedExit(rcExit);
6105}
6106
6107
6108/**
6109 * Reports an error to the parent process via the process parameter structure.
6110 *
6111 * @param pszWhere Where this error occured, if fatal message. NULL
6112 * if not message.
6113 * @param enmWhat Which init operation went wrong if fatal
6114 * message. kSupInitOp_Invalid if not message.
6115 * @param rc The status code to report.
6116 * @param pszFormat The format string.
6117 * @param va The format arguments.
6118 */
6119DECLHIDDEN(void) supR3HardenedWinReportErrorToParent(const char *pszWhere, SUPINITOP enmWhat, int rc,
6120 const char *pszFormat, va_list va)
6121{
6122 if (pszWhere)
6123 RTStrCopy(g_ProcParams.szWhere, sizeof(g_ProcParams.szWhere), pszWhere);
6124 else
6125 g_ProcParams.szWhere[0] = '\0';
6126 RTStrPrintfV(g_ProcParams.szErrorMsg, sizeof(g_ProcParams.szErrorMsg), pszFormat, va);
6127 g_ProcParams.enmWhat = enmWhat;
6128 g_ProcParams.rc = RT_SUCCESS(rc) ? VERR_INTERNAL_ERROR_2 : rc;
6129 g_ProcParams.enmRequest = kSupR3WinChildReq_Error;
6130
6131 NtClearEvent(g_ProcParams.hEvtChild);
6132 NTSTATUS rcNt = NtSetEvent(g_ProcParams.hEvtParent, NULL);
6133 if (NT_SUCCESS(rcNt))
6134 {
6135 LARGE_INTEGER Timeout;
6136 Timeout.QuadPart = -300000000; /* 30 second */
6137 /*NTSTATUS rcNt =*/ NtWaitForSingleObject(g_ProcParams.hEvtChild, FALSE /*Alertable*/, &Timeout);
6138 }
6139}
6140
6141
6142/**
6143 * Routine called by the supR3HardenedEarlyProcessInitThunk assembly routine
6144 * when LdrInitializeThunk is executed during process initialization.
6145 *
6146 * This initializes the Stub and VM processes, hooking NTDLL APIs and opening
6147 * the device driver before any other DLLs gets loaded into the process. This
6148 * greately reduces and controls the trusted code base of the process compared
6149 * to opening the driver from SUPR3HardenedMain. It also avoids issues with so
6150 * call protection software that is in the habit of patching half of the ntdll
6151 * and kernel32 APIs in the process, making it almost indistinguishable from
6152 * software that is up to no good. Once we've opened vboxdrv, the process
6153 * should be locked down so thighly that only kernel software and csrss can mess
6154 * with the process.
6155 */
6156DECLASM(uintptr_t) supR3HardenedEarlyProcessInit(void)
6157{
6158 /*
6159 * When the first thread gets here we wait for the parent to continue with
6160 * the process purifications. The primary thread must execute for image
6161 * load notifications to trigger, at least in more recent windows versions.
6162 * The old trick of starting a different thread that terminates immediately
6163 * thus doesn't work.
6164 *
6165 * We are not allowed to modify any data at this point because it will be
6166 * reset by the child process purification the parent does when we stop. To
6167 * sabotage thread creation during purification, and to avoid unnecessary
6168 * work for the parent, we reset g_ProcParams before signalling the parent
6169 * here.
6170 */
6171 if (g_enmSupR3HardenedMainState != SUPR3HARDENEDMAINSTATE_NOT_YET_CALLED)
6172 {
6173 NtTerminateThread(0, 0);
6174 return 0x22; /* crash */
6175 }
6176
6177 /* Retrieve the data we need. */
6178 uintptr_t uNtDllAddr = ASMAtomicXchgPtrT(&g_ProcParams.uNtDllAddr, 0, uintptr_t);
6179 if (!RT_VALID_PTR(uNtDllAddr))
6180 {
6181 NtTerminateThread(0, 0);
6182 return 0x23; /* crash */
6183 }
6184
6185 HANDLE hEvtChild = g_ProcParams.hEvtChild;
6186 HANDLE hEvtParent = g_ProcParams.hEvtParent;
6187 if ( hEvtChild == NULL
6188 || hEvtChild == RTNT_INVALID_HANDLE_VALUE
6189 || hEvtParent == NULL
6190 || hEvtParent == RTNT_INVALID_HANDLE_VALUE)
6191 {
6192 NtTerminateThread(0, 0);
6193 return 0x24; /* crash */
6194 }
6195
6196 /* Resolve the APIs we need. */
6197 PFNNTWAITFORSINGLEOBJECT pfnNtWaitForSingleObject;
6198 PFNNTSETEVENT pfnNtSetEvent;
6199 supR3HardenedWinGetVeryEarlyImports(uNtDllAddr, &pfnNtWaitForSingleObject, &pfnNtSetEvent);
6200
6201 /* Signal the parent that we're ready for purification. */
6202 RT_ZERO(g_ProcParams);
6203 g_ProcParams.enmRequest = kSupR3WinChildReq_PurifyChildAndCloseHandles;
6204 NTSTATUS rcNt = pfnNtSetEvent(hEvtParent, NULL);
6205 if (rcNt != STATUS_SUCCESS)
6206 return 0x33; /* crash */
6207
6208 /* Wait up to 2 mins for the parent to exorcise evil. */
6209 LARGE_INTEGER Timeout;
6210 Timeout.QuadPart = -1200000000; /* 120 second */
6211 rcNt = pfnNtWaitForSingleObject(hEvtChild, FALSE /*Alertable*/, &Timeout);
6212 if (rcNt != STATUS_SUCCESS)
6213 return 0x34; /* crash */
6214
6215 /*
6216 * We're good to go, work global state and restore process parameters.
6217 * Note that we will not restore uNtDllAddr since that is our first defence
6218 * against unwanted threads (see above).
6219 */
6220 g_enmSupR3HardenedMainState = SUPR3HARDENEDMAINSTATE_WIN_EARLY_INIT_CALLED;
6221 g_fSupEarlyProcessInit = true;
6222
6223 g_ProcParams.hEvtChild = hEvtChild;
6224 g_ProcParams.hEvtParent = hEvtParent;
6225 g_ProcParams.enmRequest = kSupR3WinChildReq_Error;
6226 g_ProcParams.rc = VINF_SUCCESS;
6227
6228 /*
6229 * Initialize the NTDLL imports that we consider usable before the
6230 * process has been initialized.
6231 */
6232 supR3HardenedWinInitImportsEarly(uNtDllAddr);
6233 g_enmSupR3HardenedMainState = SUPR3HARDENEDMAINSTATE_WIN_EARLY_IMPORTS_RESOLVED;
6234
6235 /*
6236 * Init g_uNtVerCombined as well as we can at this point.
6237 */
6238 supR3HardenedWinInitVersion(true /*fEarly*/);
6239
6240 /*
6241 * Convert the arguments to UTF-8 so we can open the log file if specified.
6242 * We may have to normalize the pointer on older windows version (not w7/64 +).
6243 * Note! This leaks memory at present.
6244 */
6245 PRTL_USER_PROCESS_PARAMETERS pUserProcParams = NtCurrentPeb()->ProcessParameters;
6246 UNICODE_STRING CmdLineStr = pUserProcParams->CommandLine;
6247 if ( CmdLineStr.Buffer != NULL
6248 && !(pUserProcParams->Flags & RTL_USER_PROCESS_PARAMS_FLAG_NORMALIZED) )
6249 CmdLineStr.Buffer = (WCHAR *)((uintptr_t)CmdLineStr.Buffer + (uintptr_t)pUserProcParams);
6250 int cArgs;
6251 char **papszArgs = suplibCommandLineToArgvWStub(CmdLineStr.Buffer, CmdLineStr.Length / sizeof(WCHAR), &cArgs);
6252 supR3HardenedOpenLog(&cArgs, papszArgs);
6253 SUP_DPRINTF(("supR3HardenedVmProcessInit: uNtDllAddr=%p g_uNtVerCombined=%#x\n", uNtDllAddr, g_uNtVerCombined));
6254
6255 /*
6256 * Set up the direct system calls so we can more easily hook NtCreateSection.
6257 */
6258 RTERRINFOSTATIC ErrInfo;
6259 supR3HardenedWinInitSyscalls(true /*fReportErrors*/, RTErrInfoInitStatic(&ErrInfo));
6260
6261 /*
6262 * Determine the executable path and name. Will NOT determine the windows style
6263 * executable path here as we don't need it.
6264 */
6265 SIZE_T cbActual = 0;
6266 rcNt = NtQueryVirtualMemory(NtCurrentProcess(), &g_ProcParams, MemorySectionName, &g_SupLibHardenedExeNtPath,
6267 sizeof(g_SupLibHardenedExeNtPath) - sizeof(WCHAR), &cbActual);
6268 if ( !NT_SUCCESS(rcNt)
6269 || g_SupLibHardenedExeNtPath.UniStr.Length == 0
6270 || g_SupLibHardenedExeNtPath.UniStr.Length & 1)
6271 supR3HardenedFatal("NtQueryVirtualMemory/MemorySectionName failed in supR3HardenedVmProcessInit: %#x\n", rcNt);
6272
6273 /* The NT executable name offset / dir path length. */
6274 g_offSupLibHardenedExeNtName = g_SupLibHardenedExeNtPath.UniStr.Length / sizeof(WCHAR);
6275 while ( g_offSupLibHardenedExeNtName > 1
6276 && g_SupLibHardenedExeNtPath.UniStr.Buffer[g_offSupLibHardenedExeNtName - 1] != '\\' )
6277 g_offSupLibHardenedExeNtName--;
6278
6279 /*
6280 * Preliminary app binary path init. May change when SUPR3HardenedMain is called.
6281 */
6282 supR3HardenedWinInitAppBin(SUPSECMAIN_FLAGS_LOC_APP_BIN);
6283
6284 /*
6285 * Initialize the image verification stuff (hooks LdrLoadDll and NtCreateSection).
6286 */
6287 supR3HardenedWinInit(0, false /*fAvastKludge*/);
6288
6289 /*
6290 * Open the driver.
6291 */
6292 if (cArgs >= 1 && suplibHardenedStrCmp(papszArgs[0], SUPR3_RESPAWN_1_ARG0) == 0)
6293 {
6294 SUP_DPRINTF(("supR3HardenedVmProcessInit: Opening vboxdrv stub...\n"));
6295 supR3HardenedWinOpenStubDevice();
6296 g_enmSupR3HardenedMainState = SUPR3HARDENEDMAINSTATE_WIN_EARLY_STUB_DEVICE_OPENED;
6297 }
6298 else if (cArgs >= 1 && suplibHardenedStrCmp(papszArgs[0], SUPR3_RESPAWN_2_ARG0) == 0)
6299 {
6300 SUP_DPRINTF(("supR3HardenedVmProcessInit: Opening vboxdrv...\n"));
6301 supR3HardenedMainOpenDevice();
6302 g_enmSupR3HardenedMainState = SUPR3HARDENEDMAINSTATE_WIN_EARLY_REAL_DEVICE_OPENED;
6303 }
6304 else
6305 supR3HardenedFatal("Unexpected first argument '%s'!\n", papszArgs[0]);
6306
6307 /*
6308 * Reinstall the NtDll patches since there is a slight possibility that
6309 * someone undid them while we where busy opening the device.
6310 */
6311 supR3HardenedWinReInstallHooks(false /*fFirstCall */);
6312
6313 /*
6314 * Restore the LdrInitializeThunk code so we can initialize the process
6315 * normally when we return.
6316 */
6317 SUP_DPRINTF(("supR3HardenedVmProcessInit: Restoring LdrInitializeThunk...\n"));
6318 PSUPHNTLDRCACHEENTRY pLdrEntry;
6319 int rc = supHardNtLdrCacheOpen("ntdll.dll", &pLdrEntry, RTErrInfoInitStatic(&ErrInfo));
6320 if (RT_FAILURE(rc))
6321 supR3HardenedFatal("supR3HardenedVmProcessInit: supHardNtLdrCacheOpen failed on NTDLL: %Rrc %s\n",
6322 rc, ErrInfo.Core.pszMsg);
6323
6324 uint8_t *pbBits;
6325 rc = supHardNtLdrCacheEntryGetBits(pLdrEntry, &pbBits, uNtDllAddr, NULL, NULL, RTErrInfoInitStatic(&ErrInfo));
6326 if (RT_FAILURE(rc))
6327 supR3HardenedFatal("supR3HardenedVmProcessInit: supHardNtLdrCacheEntryGetBits failed on NTDLL: %Rrc %s\n",
6328 rc, ErrInfo.Core.pszMsg);
6329
6330 RTLDRADDR uValue;
6331 rc = RTLdrGetSymbolEx(pLdrEntry->hLdrMod, pbBits, uNtDllAddr, UINT32_MAX, "LdrInitializeThunk", &uValue);
6332 if (RT_FAILURE(rc))
6333 supR3HardenedFatal("supR3HardenedVmProcessInit: Failed to find LdrInitializeThunk (%Rrc).\n", rc);
6334
6335 PVOID pvLdrInitThunk = (PVOID)(uintptr_t)uValue;
6336 SUPR3HARDENED_ASSERT_NT_SUCCESS(supR3HardenedWinProtectMemory(pvLdrInitThunk, 16, PAGE_EXECUTE_READWRITE));
6337 memcpy(pvLdrInitThunk, pbBits + ((uintptr_t)uValue - uNtDllAddr), 16);
6338 SUPR3HARDENED_ASSERT_NT_SUCCESS(supR3HardenedWinProtectMemory(pvLdrInitThunk, 16, PAGE_EXECUTE_READ));
6339
6340 SUP_DPRINTF(("supR3HardenedVmProcessInit: Returning to LdrInitializeThunk...\n"));
6341 return (uintptr_t)pvLdrInitThunk;
6342}
6343
Note: See TracBrowser for help on using the repository browser.

© 2023 Oracle
ContactPrivacy policyTerms of Use