VirtualBox

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

Last change on this file since 66484 was 66484, checked in by vboxsync, 8 years ago

SUPHardNt: Improved file version dumping. Version hack for dgmaster.sys.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 266.1 KB
Line 
1/* $Id: SUPR3HardenedMain-win.cpp 66484 2017-04-08 17:20:26Z 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 if ( hFile != NULL
1571 && hFile != INVALID_HANDLE_VALUE)
1572 {
1573 bool const fImage = RT_BOOL(fAttribs & (SEC_IMAGE | SEC_PROTECTED_IMAGE));
1574 bool const fExecMap = RT_BOOL(fAccess & SECTION_MAP_EXECUTE);
1575 bool const fExecProt = RT_BOOL(fProtect & (PAGE_EXECUTE | PAGE_EXECUTE_READ | PAGE_EXECUTE_WRITECOPY
1576 | PAGE_EXECUTE_READWRITE));
1577 if (fImage || fExecMap || fExecProt)
1578 {
1579 DWORD dwSavedLastError = RtlGetLastWin32Error();
1580
1581 bool fCallRealApi;
1582 //SUP_DPRINTF(("supR3HardenedMonitor_NtCreateSection: 1\n"));
1583 NTSTATUS rcNt = supR3HardenedScreenImage(hFile, fImage, true /*fIgnoreArch*/, &fAccess, &fProtect, &fCallRealApi,
1584 "NtCreateSection", true /*fAvoidWinVerifyTrust*/, NULL /*pfQuiet*/);
1585 //SUP_DPRINTF(("supR3HardenedMonitor_NtCreateSection: 2 rcNt=%#x fCallRealApi=%#x\n", rcNt, fCallRealApi));
1586
1587 RtlRestoreLastWin32Error(dwSavedLastError);
1588
1589 if (!NT_SUCCESS(rcNt))
1590 return rcNt;
1591 Assert(fCallRealApi);
1592 if (!fCallRealApi)
1593 return STATUS_TRUST_FAILURE;
1594
1595 }
1596 }
1597
1598 /*
1599 * Call checked out OK, call the original.
1600 */
1601 return g_pfnNtCreateSectionReal(phSection, fAccess, pObjAttribs, pcbSection, fProtect, fAttribs, hFile);
1602}
1603
1604
1605/**
1606 * Helper for supR3HardenedMonitor_LdrLoadDll.
1607 *
1608 * @returns NT status code.
1609 * @param pwszPath The path destination buffer.
1610 * @param cwcPath The size of the path buffer.
1611 * @param pUniStrResult The result string.
1612 * @param pOrgName The orignal name (for errors).
1613 * @param pcwc Where to return the actual length.
1614 */
1615static NTSTATUS supR3HardenedCopyRedirectionResult(WCHAR *pwszPath, size_t cwcPath, PUNICODE_STRING pUniStrResult,
1616 PUNICODE_STRING pOrgName, UINT *pcwc)
1617{
1618 UINT cwc;
1619 *pcwc = cwc = pUniStrResult->Length / sizeof(WCHAR);
1620 if (pUniStrResult->Buffer == pwszPath)
1621 pwszPath[cwc] = '\0';
1622 else
1623 {
1624 if (cwc > cwcPath - 1)
1625 {
1626 supR3HardenedError(VINF_SUCCESS, false,
1627 "supR3HardenedMonitor_LdrLoadDll: Name too long: %.*ls -> %.*ls (RtlDosApplyFileIoslationRedirection_Ustr)\n",
1628 pOrgName->Length / sizeof(WCHAR), pOrgName->Buffer,
1629 pUniStrResult->Length / sizeof(WCHAR), pUniStrResult->Buffer);
1630 return STATUS_NAME_TOO_LONG;
1631 }
1632 memcpy(&pwszPath[0], pUniStrResult->Buffer, pUniStrResult->Length);
1633 pwszPath[cwc] = '\0';
1634 }
1635 return STATUS_SUCCESS;
1636}
1637
1638
1639/**
1640 * Hooks that intercepts LdrLoadDll calls.
1641 *
1642 * Two purposes:
1643 * -# Enforce our own search path restrictions.
1644 * -# Prevalidate DLLs about to be loaded so we don't upset the loader data
1645 * by doing it from within the NtCreateSection hook (WinVerifyTrust
1646 * seems to be doing harm there on W7/32).
1647 *
1648 * @returns
1649 * @param pwszSearchPath The search path to use.
1650 * @param pfFlags Flags on input. DLL characteristics or something
1651 * on return?
1652 * @param pName The name of the module.
1653 * @param phMod Where the handle of the loaded DLL is to be
1654 * returned to the caller.
1655 */
1656static NTSTATUS NTAPI
1657supR3HardenedMonitor_LdrLoadDll(PWSTR pwszSearchPath, PULONG pfFlags, PUNICODE_STRING pName, PHANDLE phMod)
1658{
1659 DWORD dwSavedLastError = RtlGetLastWin32Error();
1660 PUNICODE_STRING const pOrgName = pName;
1661 NTSTATUS rcNt;
1662
1663 /*
1664 * Make sure the DLL notification callback is registered. If we could, we
1665 * would've done this during early process init, but due to lack of heap
1666 * and uninitialized loader lock, it's not possible that early on.
1667 *
1668 * The callback protects our NtDll hooks from getting unhooked by
1669 * "friendly" fire from the AV crowd.
1670 */
1671 supR3HardenedWinRegisterDllNotificationCallback();
1672
1673 /*
1674 * Process WinVerifyTrust todo before and after.
1675 */
1676 supR3HardenedWinVerifyCacheProcessWvtTodos();
1677
1678 /*
1679 * Reject things we don't want to deal with.
1680 */
1681 if (!pName || pName->Length == 0)
1682 {
1683 supR3HardenedError(VINF_SUCCESS, false, "supR3HardenedMonitor_LdrLoadDll: name is NULL or have a zero length.\n");
1684 SUP_DPRINTF(("supR3HardenedMonitor_LdrLoadDll: returns rcNt=%#x (pName=%p)\n", STATUS_INVALID_PARAMETER, pName));
1685 RtlRestoreLastWin32Error(dwSavedLastError);
1686 return STATUS_INVALID_PARAMETER;
1687 }
1688 /*SUP_DPRINTF(("supR3HardenedMonitor_LdrLoadDll: pName=%.*ls *pfFlags=%#x pwszSearchPath=%p:%ls\n",
1689 (unsigned)pName->Length / sizeof(WCHAR), pName->Buffer, pfFlags ? *pfFlags : UINT32_MAX, pwszSearchPath,
1690 !((uintptr_t)pwszSearchPath & 1) && (uintptr_t)pwszSearchPath >= 0x2000U ? pwszSearchPath : L"<flags>"));*/
1691
1692 /*
1693 * Reject long paths that's close to the 260 limit without looking.
1694 */
1695 if (pName->Length > 256 * sizeof(WCHAR))
1696 {
1697 supR3HardenedError(VINF_SUCCESS, false, "supR3HardenedMonitor_LdrLoadDll: too long name: %#x bytes\n", pName->Length);
1698 SUP_DPRINTF(("supR3HardenedMonitor_LdrLoadDll: returns rcNt=%#x\n", STATUS_NAME_TOO_LONG));
1699 RtlRestoreLastWin32Error(dwSavedLastError);
1700 return STATUS_NAME_TOO_LONG;
1701 }
1702
1703 /*
1704 * Reject PGHook.dll as it creates a thread from its DllMain that breaks
1705 * our preconditions respawning the 2nd process, resulting in
1706 * VERR_SUP_VP_THREAD_NOT_ALONE. The DLL is being loaded by a user APC
1707 * scheduled during kernel32.dll load notification from a kernel driver,
1708 * so failing the load attempt should not upset anyone.
1709 */
1710 if (g_enmSupR3HardenedMainState == SUPR3HARDENEDMAINSTATE_WIN_EARLY_STUB_DEVICE_OPENED)
1711 {
1712 static const struct { const char *psz; size_t cch; } s_aUnwantedEarlyDlls[] =
1713 {
1714 { RT_STR_TUPLE("PGHook.dll") },
1715 };
1716
1717 for (unsigned i = 0; i < RT_ELEMENTS(s_aUnwantedEarlyDlls); i++)
1718 {
1719 if (pName->Length < s_aUnwantedEarlyDlls[i].cch * 2)
1720 continue;
1721 PCRTUTF16 pwszTmp = &pName->Buffer[pName->Length / sizeof(RTUTF16) - s_aUnwantedEarlyDlls[i].cch];
1722 if ( pName->Length != s_aUnwantedEarlyDlls[i].cch * 2
1723 && pwszTmp[-1] != '\\'
1724 && pwszTmp[-1] != '/')
1725 continue;
1726 if (RTUtf16ICmpAscii(pwszTmp, s_aUnwantedEarlyDlls[i].psz) != 0)
1727 continue;
1728 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",
1729 pName->Length / sizeof(RTUTF16), pName->Buffer));
1730 return STATUS_TOO_MANY_THREADS;
1731 }
1732 }
1733
1734 /*
1735 * Absolute path?
1736 */
1737 NTSTATUS rcNtResolve = STATUS_SUCCESS;
1738 bool fSkipValidation = false;
1739 bool fCheckIfLoaded = false;
1740 WCHAR wszPath[260];
1741 static UNICODE_STRING const s_DefaultSuffix = RTNT_CONSTANT_UNISTR(L".dll");
1742 UNICODE_STRING UniStrStatic = { 0, (USHORT)sizeof(wszPath) - sizeof(WCHAR), wszPath };
1743 UNICODE_STRING UniStrDynamic = { 0, 0, NULL };
1744 PUNICODE_STRING pUniStrResult = NULL;
1745 UNICODE_STRING ResolvedName;
1746
1747 if ( ( pName->Length >= 4 * sizeof(WCHAR)
1748 && RT_C_IS_ALPHA(pName->Buffer[0])
1749 && pName->Buffer[1] == ':'
1750 && RTPATH_IS_SLASH(pName->Buffer[2]) )
1751 || ( pName->Length >= 1 * sizeof(WCHAR)
1752 && RTPATH_IS_SLASH(pName->Buffer[1]) )
1753 )
1754 {
1755 rcNtResolve = RtlDosApplyFileIsolationRedirection_Ustr(1 /*fFlags*/,
1756 pName,
1757 (PUNICODE_STRING)&s_DefaultSuffix,
1758 &UniStrStatic,
1759 &UniStrDynamic,
1760 &pUniStrResult,
1761 NULL /*pNewFlags*/,
1762 NULL /*pcbFilename*/,
1763 NULL /*pcbNeeded*/);
1764 if (NT_SUCCESS(rcNtResolve))
1765 {
1766 UINT cwc;
1767 rcNt = supR3HardenedCopyRedirectionResult(wszPath, RT_ELEMENTS(wszPath), pUniStrResult, pName, &cwc);
1768 RtlFreeUnicodeString(&UniStrDynamic);
1769 if (!NT_SUCCESS(rcNt))
1770 {
1771 SUP_DPRINTF(("supR3HardenedMonitor_LdrLoadDll: returns rcNt=%#x\n", rcNt));
1772 RtlRestoreLastWin32Error(dwSavedLastError);
1773 return rcNt;
1774 }
1775
1776 ResolvedName.Buffer = wszPath;
1777 ResolvedName.Length = (USHORT)(cwc * sizeof(WCHAR));
1778 ResolvedName.MaximumLength = ResolvedName.Length + sizeof(WCHAR);
1779
1780 SUP_DPRINTF(("supR3HardenedMonitor_LdrLoadDll: '%.*ls' -> '%.*ls' [redir]\n",
1781 (unsigned)pName->Length / sizeof(WCHAR), pName->Buffer,
1782 ResolvedName.Length / sizeof(WCHAR), ResolvedName.Buffer, rcNt));
1783 pName = &ResolvedName;
1784 }
1785 else
1786 {
1787 memcpy(wszPath, pName->Buffer, pName->Length);
1788 wszPath[pName->Length / sizeof(WCHAR)] = '\0';
1789 }
1790 }
1791 /*
1792 * Not an absolute path. Check if it's one of those special API set DLLs
1793 * or something we're known to use but should be taken from WinSxS.
1794 */
1795 else if ( supHardViUtf16PathStartsWithEx(pName->Buffer, pName->Length / sizeof(WCHAR),
1796 L"api-ms-win-", 11, false /*fCheckSlash*/)
1797 || supHardViUtf16PathStartsWithEx(pName->Buffer, pName->Length / sizeof(WCHAR),
1798 L"ext-ms-win-", 11, false /*fCheckSlash*/)
1799 )
1800 {
1801 memcpy(wszPath, pName->Buffer, pName->Length);
1802 wszPath[pName->Length / sizeof(WCHAR)] = '\0';
1803 fSkipValidation = true;
1804 }
1805 /*
1806 * Not an absolute path or special API set. There are two alternatives
1807 * now, either there is no path at all or there is a relative path. We
1808 * will resolve it to an absolute path in either case, failing the call
1809 * if we can't.
1810 */
1811 else
1812 {
1813 PCWCHAR pawcName = pName->Buffer;
1814 uint32_t cwcName = pName->Length / sizeof(WCHAR);
1815 uint32_t offLastSlash = UINT32_MAX;
1816 uint32_t offLastDot = UINT32_MAX;
1817 for (uint32_t i = 0; i < cwcName; i++)
1818 switch (pawcName[i])
1819 {
1820 case '\\':
1821 case '/':
1822 offLastSlash = i;
1823 offLastDot = UINT32_MAX;
1824 break;
1825 case '.':
1826 offLastDot = i;
1827 break;
1828 }
1829
1830 bool const fNeedDllSuffix = offLastDot == UINT32_MAX && offLastSlash == UINT32_MAX;
1831
1832 if (offLastDot != UINT32_MAX && offLastDot == cwcName - 1)
1833 cwcName--;
1834
1835 /*
1836 * Reject relative paths for now as they might be breakout attempts.
1837 */
1838 if (offLastSlash != UINT32_MAX)
1839 {
1840 supR3HardenedError(VINF_SUCCESS, false,
1841 "supR3HardenedMonitor_LdrLoadDll: relative name not permitted: %.*ls\n",
1842 cwcName, pawcName);
1843 SUP_DPRINTF(("supR3HardenedMonitor_LdrLoadDll: returns rcNt=%#x\n", STATUS_OBJECT_NAME_INVALID));
1844 RtlRestoreLastWin32Error(dwSavedLastError);
1845 return STATUS_OBJECT_NAME_INVALID;
1846 }
1847
1848 /*
1849 * Perform dll redirection to WinSxS such. We using an undocumented
1850 * API here, which as always is a bit risky... ASSUMES that the API
1851 * returns a full DOS path.
1852 */
1853 UINT cwc;
1854 rcNtResolve = RtlDosApplyFileIsolationRedirection_Ustr(1 /*fFlags*/,
1855 pName,
1856 (PUNICODE_STRING)&s_DefaultSuffix,
1857 &UniStrStatic,
1858 &UniStrDynamic,
1859 &pUniStrResult,
1860 NULL /*pNewFlags*/,
1861 NULL /*pcbFilename*/,
1862 NULL /*pcbNeeded*/);
1863 if (NT_SUCCESS(rcNtResolve))
1864 {
1865 rcNt = supR3HardenedCopyRedirectionResult(wszPath, RT_ELEMENTS(wszPath), pUniStrResult, pName, &cwc);
1866 RtlFreeUnicodeString(&UniStrDynamic);
1867 if (!NT_SUCCESS(rcNt))
1868 {
1869 SUP_DPRINTF(("supR3HardenedMonitor_LdrLoadDll: returns rcNt=%#x\n", rcNt));
1870 RtlRestoreLastWin32Error(dwSavedLastError);
1871 return rcNt;
1872 }
1873 }
1874 else
1875 {
1876 /*
1877 * Search for the DLL. Only System32 is allowed as the target of
1878 * a search on the API level, all VBox calls will have full paths.
1879 * If the DLL is not in System32, we will resort to check if it's
1880 * refering to an already loaded DLL (fCheckIfLoaded).
1881 */
1882 AssertCompile(sizeof(g_System32WinPath.awcBuffer) <= sizeof(wszPath));
1883 cwc = g_System32WinPath.UniStr.Length / sizeof(RTUTF16); Assert(cwc > 2);
1884 if (cwc + 1 + cwcName + fNeedDllSuffix * 4 >= RT_ELEMENTS(wszPath))
1885 {
1886 supR3HardenedError(VINF_SUCCESS, false,
1887 "supR3HardenedMonitor_LdrLoadDll: Name too long (system32): %.*ls\n", cwcName, pawcName);
1888 SUP_DPRINTF(("supR3HardenedMonitor_LdrLoadDll: returns rcNt=%#x\n", STATUS_NAME_TOO_LONG));
1889 RtlRestoreLastWin32Error(dwSavedLastError);
1890 return STATUS_NAME_TOO_LONG;
1891 }
1892 memcpy(wszPath, g_System32WinPath.UniStr.Buffer, cwc * sizeof(RTUTF16));
1893 wszPath[cwc++] = '\\';
1894 memcpy(&wszPath[cwc], pawcName, cwcName * sizeof(WCHAR));
1895 cwc += cwcName;
1896 if (!fNeedDllSuffix)
1897 wszPath[cwc] = '\0';
1898 else
1899 {
1900 memcpy(&wszPath[cwc], L".dll", 5 * sizeof(WCHAR));
1901 cwc += 4;
1902 }
1903 fCheckIfLoaded = true;
1904 }
1905
1906 ResolvedName.Buffer = wszPath;
1907 ResolvedName.Length = (USHORT)(cwc * sizeof(WCHAR));
1908 ResolvedName.MaximumLength = ResolvedName.Length + sizeof(WCHAR);
1909 pName = &ResolvedName;
1910 }
1911
1912 bool fQuiet = false;
1913 if (!fSkipValidation)
1914 {
1915 /*
1916 * Try open the file. If this fails, never mind, just pass it on to
1917 * the real API as we've replaced any searchable name with a full name
1918 * and the real API can come up with a fitting status code for it.
1919 */
1920 HANDLE hRootDir;
1921 UNICODE_STRING NtPathUniStr;
1922 int rc = RTNtPathFromWinUtf16Ex(&NtPathUniStr, &hRootDir, wszPath, RTSTR_MAX);
1923 if (RT_FAILURE(rc))
1924 {
1925 supR3HardenedError(rc, false,
1926 "supR3HardenedMonitor_LdrLoadDll: RTNtPathFromWinUtf16Ex failed on '%ls': %Rrc\n", wszPath, rc);
1927 SUP_DPRINTF(("supR3HardenedMonitor_LdrLoadDll: returns rcNt=%#x\n", STATUS_OBJECT_NAME_INVALID));
1928 RtlRestoreLastWin32Error(dwSavedLastError);
1929 return STATUS_OBJECT_NAME_INVALID;
1930 }
1931
1932 HANDLE hFile = RTNT_INVALID_HANDLE_VALUE;
1933 IO_STATUS_BLOCK Ios = RTNT_IO_STATUS_BLOCK_INITIALIZER;
1934 OBJECT_ATTRIBUTES ObjAttr;
1935 InitializeObjectAttributes(&ObjAttr, &NtPathUniStr, OBJ_CASE_INSENSITIVE, hRootDir, NULL /*pSecDesc*/);
1936
1937 rcNt = NtCreateFile(&hFile,
1938 FILE_READ_DATA | READ_CONTROL | SYNCHRONIZE,
1939 &ObjAttr,
1940 &Ios,
1941 NULL /* Allocation Size*/,
1942 FILE_ATTRIBUTE_NORMAL,
1943 FILE_SHARE_READ,
1944 FILE_OPEN,
1945 FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT,
1946 NULL /*EaBuffer*/,
1947 0 /*EaLength*/);
1948 if (NT_SUCCESS(rcNt))
1949 rcNt = Ios.Status;
1950 if (NT_SUCCESS(rcNt))
1951 {
1952 ULONG fAccess = 0;
1953 ULONG fProtect = 0;
1954 bool fCallRealApi = false;
1955 rcNt = supR3HardenedScreenImage(hFile, true /*fImage*/, RT_VALID_PTR(pfFlags) && (*pfFlags & 0x2) /*fIgnoreArch*/,
1956 &fAccess, &fProtect, &fCallRealApi,
1957 "LdrLoadDll", false /*fAvoidWinVerifyTrust*/, &fQuiet);
1958 NtClose(hFile);
1959 if (!NT_SUCCESS(rcNt))
1960 {
1961 if (!fQuiet)
1962 {
1963 if (pOrgName != pName)
1964 supR3HardenedError(VINF_SUCCESS, false, "supR3HardenedMonitor_LdrLoadDll: rejecting '%ls': rcNt=%#x\n",
1965 wszPath, rcNt);
1966 else
1967 supR3HardenedError(VINF_SUCCESS, false, "supR3HardenedMonitor_LdrLoadDll: rejecting '%ls' (%.*ls): rcNt=%#x\n",
1968 wszPath, pOrgName->Length / sizeof(WCHAR), pOrgName->Buffer, rcNt);
1969 SUP_DPRINTF(("supR3HardenedMonitor_LdrLoadDll: returns rcNt=%#x '%ls'\n", rcNt, wszPath));
1970 }
1971 RtlRestoreLastWin32Error(dwSavedLastError);
1972 return rcNt;
1973 }
1974
1975 supR3HardenedWinVerifyCacheProcessImportTodos();
1976 }
1977 else
1978 {
1979 DWORD dwErr = RtlGetLastWin32Error();
1980
1981 /*
1982 * Deal with special case where the caller (first case was MS LifeCam)
1983 * is using LoadLibrary instead of GetModuleHandle to find a loaded DLL.
1984 */
1985 NTSTATUS rcNtGetDll = STATUS_SUCCESS;
1986 if ( fCheckIfLoaded
1987 && ( rcNt == STATUS_OBJECT_NAME_NOT_FOUND
1988 || rcNt == STATUS_OBJECT_PATH_NOT_FOUND))
1989 {
1990 rcNtGetDll = LdrGetDllHandle(NULL /*DllPath*/, NULL /*pfFlags*/, pOrgName, phMod);
1991 if (NT_SUCCESS(rcNtGetDll))
1992 {
1993 RtlRestoreLastWin32Error(dwSavedLastError);
1994 return rcNtGetDll;
1995 }
1996 }
1997
1998 SUP_DPRINTF(("supR3HardenedMonitor_LdrLoadDll: error opening '%ls': %u (NtPath=%.*ls; Input=%.*ls; rcNtGetDll=%#x\n",
1999 wszPath, dwErr, NtPathUniStr.Length / sizeof(RTUTF16), NtPathUniStr.Buffer,
2000 pOrgName->Length / sizeof(WCHAR), pOrgName->Buffer, rcNtGetDll));
2001 }
2002 RTNtPathFree(&NtPathUniStr, &hRootDir);
2003 }
2004
2005 /*
2006 * Screened successfully enough. Call the real thing.
2007 */
2008 if (!fQuiet)
2009 {
2010 if (pOrgName != pName)
2011 SUP_DPRINTF(("supR3HardenedMonitor_LdrLoadDll: pName=%.*ls (Input=%.*ls, rcNtResolve=%#x) *pfFlags=%#x pwszSearchPath=%p:%ls [calling]\n",
2012 (unsigned)pName->Length / sizeof(WCHAR), pName->Buffer,
2013 (unsigned)pOrgName->Length / sizeof(WCHAR), pOrgName->Buffer, rcNtResolve,
2014 pfFlags ? *pfFlags : UINT32_MAX, pwszSearchPath,
2015 !((uintptr_t)pwszSearchPath & 1) && (uintptr_t)pwszSearchPath >= 0x2000U ? pwszSearchPath : L"<flags>"));
2016 else
2017 SUP_DPRINTF(("supR3HardenedMonitor_LdrLoadDll: pName=%.*ls (rcNtResolve=%#x) *pfFlags=%#x pwszSearchPath=%p:%ls [calling]\n",
2018 (unsigned)pName->Length / sizeof(WCHAR), pName->Buffer, rcNtResolve,
2019 pfFlags ? *pfFlags : UINT32_MAX, pwszSearchPath,
2020 !((uintptr_t)pwszSearchPath & 1) && (uintptr_t)pwszSearchPath >= 0x2000U ? pwszSearchPath : L"<flags>"));
2021 }
2022
2023 RtlRestoreLastWin32Error(dwSavedLastError);
2024 rcNt = g_pfnLdrLoadDllReal(pwszSearchPath, pfFlags, pName, phMod);
2025
2026 /*
2027 * Log the result and process pending WinVerifyTrust work if we can.
2028 */
2029 dwSavedLastError = RtlGetLastWin32Error();
2030
2031 if (NT_SUCCESS(rcNt) && phMod)
2032 SUP_DPRINTF(("supR3HardenedMonitor_LdrLoadDll: returns rcNt=%#x hMod=%p '%ls'\n", rcNt, *phMod, wszPath));
2033 else if (!NT_SUCCESS(rcNt) || !fQuiet)
2034 SUP_DPRINTF(("supR3HardenedMonitor_LdrLoadDll: returns rcNt=%#x '%ls'\n", rcNt, wszPath));
2035
2036 supR3HardenedWinVerifyCacheProcessWvtTodos();
2037
2038 RtlRestoreLastWin32Error(dwSavedLastError);
2039
2040 return rcNt;
2041}
2042
2043
2044/**
2045 * DLL load and unload notification callback.
2046 *
2047 * This is a safety against our LdrLoadDll hook being replaced by protection
2048 * software. Though, we prefer the LdrLoadDll hook to this one as it allows us
2049 * to call WinVerifyTrust more freely.
2050 *
2051 * @param ulReason The reason we're called, see
2052 * LDR_DLL_NOTIFICATION_REASON_XXX.
2053 * @param pData Reason specific data. (Format is currently the same for
2054 * both load and unload.)
2055 * @param pvUser User parameter (ignored).
2056 *
2057 * @remarks Vista and later.
2058 * @remarks The loader lock is held when we're called, at least on Windows 7.
2059 */
2060static VOID CALLBACK supR3HardenedDllNotificationCallback(ULONG ulReason, PCLDR_DLL_NOTIFICATION_DATA pData, PVOID pvUser)
2061{
2062 NOREF(pvUser);
2063
2064 /*
2065 * Screen the image on load. We will normally get a verification cache
2066 * hit here because of the LdrLoadDll and NtCreateSection hooks, so it
2067 * should be relatively cheap to recheck. In case our NtDll patches
2068 * got re
2069 *
2070 * This ASSUMES that we get informed after the fact as indicated by the
2071 * available documentation.
2072 */
2073 if (ulReason == LDR_DLL_NOTIFICATION_REASON_LOADED)
2074 {
2075 SUP_DPRINTF(("supR3HardenedDllNotificationCallback: load %p LB %#010x %.*ls [fFlags=%#x]\n",
2076 pData->Loaded.DllBase, pData->Loaded.SizeOfImage,
2077 pData->Loaded.FullDllName->Length / sizeof(WCHAR), pData->Loaded.FullDllName->Buffer,
2078 pData->Loaded.Flags));
2079
2080 /* Convert the windows path to an NT path and open it. */
2081 HANDLE hRootDir;
2082 UNICODE_STRING NtPathUniStr;
2083 int rc = RTNtPathFromWinUtf16Ex(&NtPathUniStr, &hRootDir, pData->Loaded.FullDllName->Buffer,
2084 pData->Loaded.FullDllName->Length / sizeof(WCHAR));
2085 if (RT_FAILURE(rc))
2086 {
2087 supR3HardenedFatal("supR3HardenedDllNotificationCallback: RTNtPathFromWinUtf16Ex failed on '%.*ls': %Rrc\n",
2088 pData->Loaded.FullDllName->Length / sizeof(WCHAR), pData->Loaded.FullDllName->Buffer, rc);
2089 return;
2090 }
2091
2092 HANDLE hFile = RTNT_INVALID_HANDLE_VALUE;
2093 IO_STATUS_BLOCK Ios = RTNT_IO_STATUS_BLOCK_INITIALIZER;
2094 OBJECT_ATTRIBUTES ObjAttr;
2095 InitializeObjectAttributes(&ObjAttr, &NtPathUniStr, OBJ_CASE_INSENSITIVE, hRootDir, NULL /*pSecDesc*/);
2096
2097 NTSTATUS rcNt = NtCreateFile(&hFile,
2098 FILE_READ_DATA | READ_CONTROL | SYNCHRONIZE,
2099 &ObjAttr,
2100 &Ios,
2101 NULL /* Allocation Size*/,
2102 FILE_ATTRIBUTE_NORMAL,
2103 FILE_SHARE_READ,
2104 FILE_OPEN,
2105 FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT,
2106 NULL /*EaBuffer*/,
2107 0 /*EaLength*/);
2108 if (NT_SUCCESS(rcNt))
2109 rcNt = Ios.Status;
2110 if (!NT_SUCCESS(rcNt))
2111 {
2112 supR3HardenedFatal("supR3HardenedDllNotificationCallback: NtCreateFile failed on '%.*ls' / '%.*ls': %#x\n",
2113 pData->Loaded.FullDllName->Length / sizeof(WCHAR), pData->Loaded.FullDllName->Buffer,
2114 NtPathUniStr.Length / sizeof(WCHAR), NtPathUniStr.Buffer, rcNt);
2115 /* not reached */
2116 }
2117
2118 /* Do the screening. */
2119 ULONG fAccess = 0;
2120 ULONG fProtect = 0;
2121 bool fCallRealApi = false;
2122 bool fQuietFailure = false;
2123 rcNt = supR3HardenedScreenImage(hFile, true /*fImage*/, true /*fIgnoreArch*/, &fAccess, &fProtect, &fCallRealApi,
2124 "LdrLoadDll", true /*fAvoidWinVerifyTrust*/, &fQuietFailure);
2125 NtClose(hFile);
2126 if (!NT_SUCCESS(rcNt))
2127 {
2128 supR3HardenedFatal("supR3HardenedDllNotificationCallback: supR3HardenedScreenImage failed on '%.*ls' / '%.*ls': %#x\n",
2129 pData->Loaded.FullDllName->Length / sizeof(WCHAR), pData->Loaded.FullDllName->Buffer,
2130 NtPathUniStr.Length / sizeof(WCHAR), NtPathUniStr.Buffer, rcNt);
2131 /* not reached */
2132 }
2133 RTNtPathFree(&NtPathUniStr, &hRootDir);
2134 }
2135 /*
2136 * Log the unload call.
2137 */
2138 else if (ulReason == LDR_DLL_NOTIFICATION_REASON_UNLOADED)
2139 {
2140 SUP_DPRINTF(("supR3HardenedDllNotificationCallback: Unload %p LB %#010x %.*ls [flags=%#x]\n",
2141 pData->Unloaded.DllBase, pData->Unloaded.SizeOfImage,
2142 pData->Unloaded.FullDllName->Length / sizeof(WCHAR), pData->Unloaded.FullDllName->Buffer,
2143 pData->Unloaded.Flags));
2144 }
2145 /*
2146 * Just log things we don't know and then return without caching anything.
2147 */
2148 else
2149 {
2150 static uint32_t s_cLogEntries = 0;
2151 if (s_cLogEntries++ < 32)
2152 SUP_DPRINTF(("supR3HardenedDllNotificationCallback: ulReason=%u pData=%p\n", ulReason, pData));
2153 return;
2154 }
2155
2156 /*
2157 * Use this opportunity to make sure our NtDll patches are still in place,
2158 * since they may be replaced by indecent protection software solutions.
2159 */
2160 supR3HardenedWinReInstallHooks(false /*fFirstCall */);
2161}
2162
2163
2164/**
2165 * Registers the DLL notification callback if it hasn't already been registered.
2166 */
2167static void supR3HardenedWinRegisterDllNotificationCallback(void)
2168{
2169 /*
2170 * The notification API was added in Vista, so it's an optional (weak) import.
2171 */
2172 if ( LdrRegisterDllNotification != NULL
2173 && g_cDllNotificationRegistered <= 0
2174 && g_cDllNotificationRegistered > -32)
2175 {
2176 NTSTATUS rcNt = LdrRegisterDllNotification(0, supR3HardenedDllNotificationCallback, NULL, &g_pvDllNotificationCookie);
2177 if (NT_SUCCESS(rcNt))
2178 {
2179 SUP_DPRINTF(("Registered Dll notification callback with NTDLL.\n"));
2180 g_cDllNotificationRegistered = 1;
2181 }
2182 else
2183 {
2184 supR3HardenedError(rcNt, false /*fFatal*/, "LdrRegisterDllNotification failed: %#x\n", rcNt);
2185 g_cDllNotificationRegistered--;
2186 }
2187 }
2188}
2189
2190
2191static void supR3HardenedWinHookFailed(const char *pszWhich, uint8_t const *pbPrologue)
2192{
2193 supR3HardenedFatalMsg("supR3HardenedWinInstallHooks", kSupInitOp_Misc, VERR_NO_MEMORY,
2194 "Failed to install %s monitor: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x\n "
2195#ifdef RT_ARCH_X86
2196 "(It is also possible you are running 32-bit VirtualBox under 64-bit windows.)\n"
2197#endif
2198 ,
2199 pszWhich,
2200 pbPrologue[0], pbPrologue[1], pbPrologue[2], pbPrologue[3],
2201 pbPrologue[4], pbPrologue[5], pbPrologue[6], pbPrologue[7],
2202 pbPrologue[8], pbPrologue[9], pbPrologue[10], pbPrologue[11],
2203 pbPrologue[12], pbPrologue[13], pbPrologue[14], pbPrologue[15]);
2204}
2205
2206
2207/**
2208 * IPRT thread that waits for the parent process to terminate and reacts by
2209 * exiting the current process.
2210 *
2211 * @returns VINF_SUCCESS
2212 * @param hSelf The current thread. Ignored.
2213 * @param pvUser The handle of the parent process.
2214 */
2215static DECLCALLBACK(int) supR3HardenedWinParentWatcherThread(RTTHREAD hSelf, void *pvUser)
2216{
2217 HANDLE hProcWait = (HANDLE)pvUser;
2218 NOREF(hSelf);
2219
2220 /*
2221 * Wait for the parent to terminate.
2222 */
2223 NTSTATUS rcNt;
2224 for (;;)
2225 {
2226 rcNt = NtWaitForSingleObject(hProcWait, TRUE /*Alertable*/, NULL /*pTimeout*/);
2227 if ( rcNt == STATUS_WAIT_0
2228 || rcNt == STATUS_ABANDONED_WAIT_0)
2229 break;
2230 if ( rcNt != STATUS_TIMEOUT
2231 && rcNt != STATUS_USER_APC
2232 && rcNt != STATUS_ALERTED)
2233 supR3HardenedFatal("NtWaitForSingleObject returned %#x\n", rcNt);
2234 }
2235
2236 /*
2237 * Proxy the termination code of the child, if it exited already.
2238 */
2239 PROCESS_BASIC_INFORMATION BasicInfo;
2240 NTSTATUS rcNt2 = NtQueryInformationProcess(hProcWait, ProcessBasicInformation, &BasicInfo, sizeof(BasicInfo), NULL);
2241 if ( !NT_SUCCESS(rcNt2)
2242 || BasicInfo.ExitStatus == STATUS_PENDING)
2243 BasicInfo.ExitStatus = RTEXITCODE_FAILURE;
2244
2245 NtClose(hProcWait);
2246 SUP_DPRINTF(("supR3HardenedWinParentWatcherThread: Quitting: ExitCode=%#x rcNt=%#x\n", BasicInfo.ExitStatus, rcNt));
2247 suplibHardenedExit((RTEXITCODE)BasicInfo.ExitStatus);
2248 /* not reached */
2249}
2250
2251
2252/**
2253 * Creates the parent watcher thread that will make sure this process exits when
2254 * the parent does.
2255 *
2256 * This is a necessary evil to make VBoxNetDhcp and VBoxNetNat termination from
2257 * Main work without too much new magic. It also makes Ctrl-C or similar work
2258 * in on the hardened processes in the windows console.
2259 *
2260 * @param hVBoxRT The VBoxRT.dll handle. We use RTThreadCreate to
2261 * spawn the thread to avoid duplicating thread
2262 * creation and thread naming code from IPRT.
2263 */
2264DECLHIDDEN(void) supR3HardenedWinCreateParentWatcherThread(HMODULE hVBoxRT)
2265{
2266 /*
2267 * Resolve runtime methods that we need.
2268 */
2269 PFNRTTHREADCREATE pfnRTThreadCreate = (PFNRTTHREADCREATE)GetProcAddress(hVBoxRT, "RTThreadCreate");
2270 SUPR3HARDENED_ASSERT(pfnRTThreadCreate != NULL);
2271
2272 /*
2273 * Find the parent process ID.
2274 */
2275 PROCESS_BASIC_INFORMATION BasicInfo;
2276 NTSTATUS rcNt = NtQueryInformationProcess(NtCurrentProcess(), ProcessBasicInformation, &BasicInfo, sizeof(BasicInfo), NULL);
2277 if (!NT_SUCCESS(rcNt))
2278 supR3HardenedFatal("supR3HardenedWinCreateParentWatcherThread: NtQueryInformationProcess failed: %#x\n", rcNt);
2279
2280 /*
2281 * Open the parent process for waiting and exitcode query.
2282 */
2283 OBJECT_ATTRIBUTES ObjAttr;
2284 InitializeObjectAttributes(&ObjAttr, NULL, 0, NULL /*hRootDir*/, NULL /*pSecDesc*/);
2285
2286 CLIENT_ID ClientId;
2287 ClientId.UniqueProcess = (HANDLE)BasicInfo.InheritedFromUniqueProcessId;
2288 ClientId.UniqueThread = NULL;
2289
2290 HANDLE hParent;
2291 rcNt = NtOpenProcess(&hParent, SYNCHRONIZE | PROCESS_QUERY_INFORMATION, &ObjAttr, &ClientId);
2292 if (!NT_SUCCESS(rcNt))
2293 supR3HardenedFatalMsg("supR3HardenedWinCreateParentWatcherThread", kSupInitOp_Misc, VERR_GENERAL_FAILURE,
2294 "NtOpenProcess(%p.0) failed: %#x\n", ClientId.UniqueProcess, rcNt);
2295
2296 /*
2297 * Create the thread that should do the waiting.
2298 */
2299 int rc = pfnRTThreadCreate(NULL, supR3HardenedWinParentWatcherThread, hParent, _64K /* stack */,
2300 RTTHREADTYPE_DEFAULT, 0 /*fFlags*/, "ParentWatcher");
2301 if (RT_FAILURE(rc))
2302 supR3HardenedFatal("supR3HardenedWinCreateParentWatcherThread: RTThreadCreate failed: %Rrc\n", rc);
2303}
2304
2305
2306/**
2307 * Checks if the calling thread is the only one in the process.
2308 *
2309 * @returns true if we're positive we're alone, false if not.
2310 */
2311static bool supR3HardenedWinAmIAlone(void)
2312{
2313 ULONG fAmIAlone = 0;
2314 ULONG cbIgn = 0;
2315 NTSTATUS rcNt = NtQueryInformationThread(NtCurrentThread(), ThreadAmILastThread, &fAmIAlone, sizeof(fAmIAlone), &cbIgn);
2316 Assert(NT_SUCCESS(rcNt));
2317 return NT_SUCCESS(rcNt) && fAmIAlone != 0;
2318}
2319
2320
2321/**
2322 * Simplify NtProtectVirtualMemory interface.
2323 *
2324 * Modifies protection for the current process. Caller must know the current
2325 * protection as it's not returned.
2326 *
2327 * @returns NT status code.
2328 * @param pvMem The memory to change protection for.
2329 * @param cbMem The amount of memory to change.
2330 * @param fNewProt The new protection.
2331 */
2332static NTSTATUS supR3HardenedWinProtectMemory(PVOID pvMem, SIZE_T cbMem, ULONG fNewProt)
2333{
2334 ULONG fOldProt = 0;
2335 return NtProtectVirtualMemory(NtCurrentProcess(), &pvMem, &cbMem, fNewProt, &fOldProt);
2336}
2337
2338
2339/**
2340 * Installs or reinstalls the NTDLL patches.
2341 */
2342static void supR3HardenedWinReInstallHooks(bool fFirstCall)
2343{
2344 struct
2345 {
2346 size_t cbPatch;
2347 uint8_t const *pabPatch;
2348 uint8_t **ppbApi;
2349 const char *pszName;
2350 } const s_aPatches[] =
2351 {
2352 { sizeof(g_abNtCreateSectionPatch), g_abNtCreateSectionPatch, &g_pbNtCreateSection, "NtCreateSection" },
2353 { sizeof(g_abLdrLoadDllPatch), g_abLdrLoadDllPatch, &g_pbLdrLoadDll, "LdrLoadDll" },
2354 };
2355
2356 ULONG fAmIAlone = ~(ULONG)0;
2357
2358 for (uint32_t i = 0; i < RT_ELEMENTS(s_aPatches); i++)
2359 {
2360 uint8_t *pbApi = *s_aPatches[i].ppbApi;
2361 if (memcmp(pbApi, s_aPatches[i].pabPatch, s_aPatches[i].cbPatch) != 0)
2362 {
2363 /*
2364 * Log the incident if it's not the initial call.
2365 */
2366 static uint32_t volatile s_cTimes = 0;
2367 if (!fFirstCall && s_cTimes < 128)
2368 {
2369 s_cTimes++;
2370 SUP_DPRINTF(("supR3HardenedWinReInstallHooks: Reinstalling %s (%p: %.*Rhxs).\n",
2371 s_aPatches[i].pszName, pbApi, s_aPatches[i].cbPatch, pbApi));
2372 }
2373
2374 Assert(s_aPatches[i].cbPatch >= 4);
2375
2376 SUPR3HARDENED_ASSERT_NT_SUCCESS(supR3HardenedWinProtectMemory(pbApi, s_aPatches[i].cbPatch, PAGE_EXECUTE_READWRITE));
2377
2378 /*
2379 * If we're alone, just memcpy the patch in.
2380 */
2381
2382 if (fAmIAlone == ~(ULONG)0)
2383 fAmIAlone = supR3HardenedWinAmIAlone();
2384 if (fAmIAlone)
2385 memcpy(pbApi, s_aPatches[i].pabPatch, s_aPatches[i].cbPatch);
2386 else
2387 {
2388 /*
2389 * Not alone. Start by injecting a JMP $-2, then waste some
2390 * CPU cycles to get the other threads a good chance of getting
2391 * out of the code before we replace it.
2392 */
2393 RTUINT32U uJmpDollarMinus;
2394 uJmpDollarMinus.au8[0] = 0xeb;
2395 uJmpDollarMinus.au8[1] = 0xfe;
2396 uJmpDollarMinus.au8[2] = pbApi[2];
2397 uJmpDollarMinus.au8[3] = pbApi[3];
2398 ASMAtomicXchgU32((uint32_t volatile *)pbApi, uJmpDollarMinus.u);
2399
2400 NtYieldExecution();
2401 NtYieldExecution();
2402
2403 /* Copy in the tail bytes of the patch, then xchg the jmp $-2. */
2404 if (s_aPatches[i].cbPatch > 4)
2405 memcpy(&pbApi[4], &s_aPatches[i].pabPatch[4], s_aPatches[i].cbPatch - 4);
2406 ASMAtomicXchgU32((uint32_t volatile *)pbApi, *(uint32_t *)s_aPatches[i].pabPatch);
2407 }
2408
2409 SUPR3HARDENED_ASSERT_NT_SUCCESS(supR3HardenedWinProtectMemory(pbApi, s_aPatches[i].cbPatch, PAGE_EXECUTE_READ));
2410 }
2411 }
2412}
2413
2414
2415/**
2416 * Install hooks for intercepting calls dealing with mapping shared libraries
2417 * into the process.
2418 *
2419 * This allows us to prevent undesirable shared libraries from being loaded.
2420 *
2421 * @remarks We assume we're alone in this process, so no seralizing trickery is
2422 * necessary when installing the patch.
2423 *
2424 * @remarks We would normally just copy the prologue sequence somewhere and add
2425 * a jump back at the end of it. But because we wish to avoid
2426 * allocating executable memory, we need to have preprepared assembly
2427 * "copies". This makes the non-system call patching a little tedious
2428 * and inflexible.
2429 */
2430static void supR3HardenedWinInstallHooks(void)
2431{
2432 NTSTATUS rcNt;
2433
2434 /*
2435 * Disable hard error popups so we can quietly refuse images to be loaded.
2436 */
2437 ULONG fHardErr = 0;
2438 rcNt = NtQueryInformationProcess(NtCurrentProcess(), ProcessDefaultHardErrorMode, &fHardErr, sizeof(fHardErr), NULL);
2439 if (!NT_SUCCESS(rcNt))
2440 supR3HardenedFatalMsg("supR3HardenedWinInstallHooks", kSupInitOp_Misc, VERR_GENERAL_FAILURE,
2441 "NtQueryInformationProcess/ProcessDefaultHardErrorMode failed: %#x\n", rcNt);
2442 if (fHardErr & PROCESS_HARDERR_CRITICAL_ERROR)
2443 {
2444 fHardErr &= ~PROCESS_HARDERR_CRITICAL_ERROR;
2445 rcNt = NtSetInformationProcess(NtCurrentProcess(), ProcessDefaultHardErrorMode, &fHardErr, sizeof(fHardErr));
2446 if (!NT_SUCCESS(rcNt))
2447 supR3HardenedFatalMsg("supR3HardenedWinInstallHooks", kSupInitOp_Misc, VERR_GENERAL_FAILURE,
2448 "NtSetInformationProcess/ProcessDefaultHardErrorMode failed: %#x\n", rcNt);
2449 }
2450
2451 /*
2452 * Locate the routines first so we can allocate memory that's near enough.
2453 */
2454 PFNRT pfnNtCreateSection = supR3HardenedWinGetRealDllSymbol("ntdll.dll", "NtCreateSection");
2455 SUPR3HARDENED_ASSERT(pfnNtCreateSection != NULL);
2456 //SUPR3HARDENED_ASSERT(pfnNtCreateSection == (FARPROC)NtCreateSection);
2457
2458 PFNRT pfnLdrLoadDll = supR3HardenedWinGetRealDllSymbol("ntdll.dll", "LdrLoadDll");
2459 SUPR3HARDENED_ASSERT(pfnLdrLoadDll != NULL);
2460 //SUPR3HARDENED_ASSERT(pfnLdrLoadDll == (FARPROC)LdrLoadDll);
2461
2462 /*
2463 * Exec page setup & management.
2464 */
2465 uint32_t offExecPage = 0;
2466 memset(g_abSupHardReadWriteExecPage, 0xcc, PAGE_SIZE);
2467
2468 /*
2469 * Hook #1 - NtCreateSection.
2470 * Purpose: Validate everything that can be mapped into the process before
2471 * it's mapped and we still have a file handle to work with.
2472 */
2473 uint8_t * const pbNtCreateSection = (uint8_t *)(uintptr_t)pfnNtCreateSection;
2474 g_pbNtCreateSection = pbNtCreateSection;
2475 memcpy(g_abNtCreateSectionPatch, pbNtCreateSection, sizeof(g_abNtCreateSectionPatch));
2476
2477 g_pfnNtCreateSectionReal = NtCreateSection; /* our direct syscall */
2478
2479#ifdef RT_ARCH_AMD64
2480 /*
2481 * Patch 64-bit hosts.
2482 */
2483 /* Pattern #1: XP64/W2K3-64 thru Windows 8.1
2484 0:000> u ntdll!NtCreateSection
2485 ntdll!NtCreateSection:
2486 00000000`779f1750 4c8bd1 mov r10,rcx
2487 00000000`779f1753 b847000000 mov eax,47h
2488 00000000`779f1758 0f05 syscall
2489 00000000`779f175a c3 ret
2490 00000000`779f175b 0f1f440000 nop dword ptr [rax+rax]
2491 The variant is the value loaded into eax: W2K3=??, Vista=47h?, W7=47h, W80=48h, W81=49h */
2492
2493 /* Assemble the patch. */
2494 g_abNtCreateSectionPatch[0] = 0x48; /* mov rax, qword */
2495 g_abNtCreateSectionPatch[1] = 0xb8;
2496 *(uint64_t *)&g_abNtCreateSectionPatch[2] = (uint64_t)supR3HardenedMonitor_NtCreateSection;
2497 g_abNtCreateSectionPatch[10] = 0xff; /* jmp rax */
2498 g_abNtCreateSectionPatch[11] = 0xe0;
2499
2500#else
2501 /*
2502 * Patch 32-bit hosts.
2503 */
2504 /* Pattern #1: XP thru Windows 7
2505 kd> u ntdll!NtCreateSection
2506 ntdll!NtCreateSection:
2507 7c90d160 b832000000 mov eax,32h
2508 7c90d165 ba0003fe7f mov edx,offset SharedUserData!SystemCallStub (7ffe0300)
2509 7c90d16a ff12 call dword ptr [edx]
2510 7c90d16c c21c00 ret 1Ch
2511 7c90d16f 90 nop
2512 The variable bit is the value loaded into eax: XP=32h, W2K3=34h, Vista=4bh, W7=54h
2513
2514 Pattern #2: Windows 8.1
2515 0:000:x86> u ntdll_6a0f0000!NtCreateSection
2516 ntdll_6a0f0000!NtCreateSection:
2517 6a15eabc b854010000 mov eax,154h
2518 6a15eac1 e803000000 call ntdll_6a0f0000!NtCreateSection+0xd (6a15eac9)
2519 6a15eac6 c21c00 ret 1Ch
2520 6a15eac9 8bd4 mov edx,esp
2521 6a15eacb 0f34 sysenter
2522 6a15eacd c3 ret
2523 The variable bit is the value loaded into eax: W81=154h */
2524
2525 /* Assemble the patch. */
2526 g_abNtCreateSectionPatch[0] = 0xe9; /* jmp rel32 */
2527 *(uint32_t *)&g_abNtCreateSectionPatch[1] = (uintptr_t)supR3HardenedMonitor_NtCreateSection
2528 - (uintptr_t)&pbNtCreateSection[1+4];
2529
2530#endif
2531
2532 /*
2533 * Hook #2 - LdrLoadDll
2534 * Purpose: (a) Enforce LdrLoadDll search path constraints, and (b) pre-validate
2535 * DLLs so we can avoid calling WinVerifyTrust from the first hook,
2536 * and thus avoiding messing up the loader data on some installations.
2537 *
2538 * This differs from the above function in that is no a system call and
2539 * we're at the mercy of the compiler.
2540 */
2541 uint8_t * const pbLdrLoadDll = (uint8_t *)(uintptr_t)pfnLdrLoadDll;
2542 g_pbLdrLoadDll = pbLdrLoadDll;
2543 memcpy(g_abLdrLoadDllPatch, pbLdrLoadDll, sizeof(g_abLdrLoadDllPatch));
2544
2545 DISSTATE Dis;
2546 uint32_t cbInstr;
2547 uint32_t offJmpBack = 0;
2548
2549#ifdef RT_ARCH_AMD64
2550 /*
2551 * Patch 64-bit hosts.
2552 */
2553 /* Just use the disassembler to skip 12 bytes or more. */
2554 while (offJmpBack < 12)
2555 {
2556 cbInstr = 1;
2557 int rc = DISInstr(pbLdrLoadDll + offJmpBack, DISCPUMODE_64BIT, &Dis, &cbInstr);
2558 if ( RT_FAILURE(rc)
2559 || (Dis.pCurInstr->fOpType & (DISOPTYPE_CONTROLFLOW))
2560 || (Dis.ModRM.Bits.Mod == 0 && Dis.ModRM.Bits.Rm == 5 /* wrt RIP */) )
2561 supR3HardenedWinHookFailed("LdrLoadDll", pbLdrLoadDll);
2562 offJmpBack += cbInstr;
2563 }
2564
2565 /* Assemble the code for resuming the call.*/
2566 *(PFNRT *)&g_pfnLdrLoadDllReal = (PFNRT)(uintptr_t)&g_abSupHardReadWriteExecPage[offExecPage];
2567
2568 memcpy(&g_abSupHardReadWriteExecPage[offExecPage], pbLdrLoadDll, offJmpBack);
2569 offExecPage += offJmpBack;
2570
2571 g_abSupHardReadWriteExecPage[offExecPage++] = 0xff; /* jmp qword [$+8 wrt RIP] */
2572 g_abSupHardReadWriteExecPage[offExecPage++] = 0x25;
2573 *(uint32_t *)&g_abSupHardReadWriteExecPage[offExecPage] = RT_ALIGN_32(offExecPage + 4, 8) - (offExecPage + 4);
2574 offExecPage = RT_ALIGN_32(offExecPage + 4, 8);
2575 *(uint64_t *)&g_abSupHardReadWriteExecPage[offExecPage] = (uintptr_t)&pbLdrLoadDll[offJmpBack];
2576 offExecPage = RT_ALIGN_32(offExecPage + 8, 16);
2577
2578 /* Assemble the LdrLoadDll patch. */
2579 Assert(offJmpBack >= 12);
2580 g_abLdrLoadDllPatch[0] = 0x48; /* mov rax, qword */
2581 g_abLdrLoadDllPatch[1] = 0xb8;
2582 *(uint64_t *)&g_abLdrLoadDllPatch[2] = (uint64_t)supR3HardenedMonitor_LdrLoadDll;
2583 g_abLdrLoadDllPatch[10] = 0xff; /* jmp rax */
2584 g_abLdrLoadDllPatch[11] = 0xe0;
2585
2586#else
2587 /*
2588 * Patch 32-bit hosts.
2589 */
2590 /* Just use the disassembler to skip 5 bytes or more. */
2591 while (offJmpBack < 5)
2592 {
2593 cbInstr = 1;
2594 int rc = DISInstr(pbLdrLoadDll + offJmpBack, DISCPUMODE_32BIT, &Dis, &cbInstr);
2595 if ( RT_FAILURE(rc)
2596 || (Dis.pCurInstr->fOpType & (DISOPTYPE_CONTROLFLOW)) )
2597 supR3HardenedWinHookFailed("LdrLoadDll", pbLdrLoadDll);
2598 offJmpBack += cbInstr;
2599 }
2600
2601 /* Assemble the code for resuming the call.*/
2602 *(PFNRT *)&g_pfnLdrLoadDllReal = (PFNRT)(uintptr_t)&g_abSupHardReadWriteExecPage[offExecPage];
2603
2604 memcpy(&g_abSupHardReadWriteExecPage[offExecPage], pbLdrLoadDll, offJmpBack);
2605 offExecPage += offJmpBack;
2606
2607 g_abSupHardReadWriteExecPage[offExecPage++] = 0xe9; /* jmp rel32 */
2608 *(uint32_t *)&g_abSupHardReadWriteExecPage[offExecPage] = (uintptr_t)&pbLdrLoadDll[offJmpBack]
2609 - (uintptr_t)&g_abSupHardReadWriteExecPage[offExecPage + 4];
2610 offExecPage = RT_ALIGN_32(offExecPage + 4, 16);
2611
2612 /* Assemble the LdrLoadDll patch. */
2613 memcpy(g_abLdrLoadDllPatch, pbLdrLoadDll, sizeof(g_abLdrLoadDllPatch));
2614 Assert(offJmpBack >= 5);
2615 g_abLdrLoadDllPatch[0] = 0xe9;
2616 *(uint32_t *)&g_abLdrLoadDllPatch[1] = (uintptr_t)supR3HardenedMonitor_LdrLoadDll - (uintptr_t)&pbLdrLoadDll[1+4];
2617#endif
2618
2619 /*
2620 * Seal the rwx page.
2621 */
2622 SUPR3HARDENED_ASSERT_NT_SUCCESS(supR3HardenedWinProtectMemory(g_abSupHardReadWriteExecPage, PAGE_SIZE, PAGE_EXECUTE_READ));
2623
2624 /*
2625 * Install the patches.
2626 */
2627 supR3HardenedWinReInstallHooks(true /*fFirstCall*/);
2628}
2629
2630
2631
2632
2633
2634
2635/*
2636 *
2637 * T h r e a d c r e a t i o n c o n t r o l
2638 * T h r e a d c r e a t i o n c o n t r o l
2639 * T h r e a d c r e a t i o n c o n t r o l
2640 *
2641 */
2642
2643
2644/**
2645 * Common code used for child and parent to make new threads exit immediately.
2646 *
2647 * This patches the LdrInitializeThunk code to call NtTerminateThread with
2648 * STATUS_SUCCESS instead of doing the NTDLL initialization.
2649 *
2650 * @returns VBox status code.
2651 * @param hProcess The process to do this to.
2652 * @param pvLdrInitThunk The address of the LdrInitializeThunk code to
2653 * override.
2654 * @param pvNtTerminateThread The address of the NtTerminateThread function in
2655 * the NTDLL instance we're patching. (Must be +/-
2656 * 2GB from the thunk code.)
2657 * @param pabBackup Where to back up the original instruction bytes
2658 * at pvLdrInitThunk.
2659 * @param cbBackup The size of the backup area. Must be 16 bytes.
2660 * @param pErrInfo Where to return extended error information.
2661 * Optional.
2662 */
2663static int supR3HardNtDisableThreadCreationEx(HANDLE hProcess, void *pvLdrInitThunk, void *pvNtTerminateThread,
2664 uint8_t *pabBackup, size_t cbBackup, PRTERRINFO pErrInfo)
2665{
2666 SUP_DPRINTF(("supR3HardNtDisableThreadCreation: pvLdrInitThunk=%p pvNtTerminateThread=%p\n", pvLdrInitThunk, pvNtTerminateThread));
2667 SUPR3HARDENED_ASSERT(cbBackup == 16);
2668 SUPR3HARDENED_ASSERT(RT_ABS((intptr_t)pvLdrInitThunk - (intptr_t)pvNtTerminateThread) < 16*_1M);
2669
2670 /*
2671 * Back up the thunk code.
2672 */
2673 SIZE_T cbIgnored;
2674 NTSTATUS rcNt = NtReadVirtualMemory(hProcess, pvLdrInitThunk, pabBackup, cbBackup, &cbIgnored);
2675 if (!NT_SUCCESS(rcNt))
2676 return RTErrInfoSetF(pErrInfo, VERR_GENERAL_FAILURE,
2677 "supR3HardNtDisableThreadCreation: NtReadVirtualMemory/LdrInitializeThunk failed: %#x", rcNt);
2678
2679 /*
2680 * Cook up replacement code that calls NtTerminateThread.
2681 */
2682 uint8_t abReplacement[16];
2683 memcpy(abReplacement, pabBackup, sizeof(abReplacement));
2684
2685#ifdef RT_ARCH_AMD64
2686 abReplacement[0] = 0x31; /* xor ecx, ecx */
2687 abReplacement[1] = 0xc9;
2688 abReplacement[2] = 0x31; /* xor edx, edx */
2689 abReplacement[3] = 0xd2;
2690 abReplacement[4] = 0xe8; /* call near NtTerminateThread */
2691 *(int32_t *)&abReplacement[5] = (int32_t)((uintptr_t)pvNtTerminateThread - ((uintptr_t)pvLdrInitThunk + 9));
2692 abReplacement[9] = 0xcc; /* int3 */
2693#elif defined(RT_ARCH_X86)
2694 abReplacement[0] = 0x6a; /* push 0 */
2695 abReplacement[1] = 0x00;
2696 abReplacement[2] = 0x6a; /* push 0 */
2697 abReplacement[3] = 0x00;
2698 abReplacement[4] = 0xe8; /* call near NtTerminateThread */
2699 *(int32_t *)&abReplacement[5] = (int32_t)((uintptr_t)pvNtTerminateThread - ((uintptr_t)pvLdrInitThunk + 9));
2700 abReplacement[9] = 0xcc; /* int3 */
2701#else
2702# error "Unsupported arch."
2703#endif
2704
2705 /*
2706 * Install the replacment code.
2707 */
2708 PVOID pvProt = pvLdrInitThunk;
2709 SIZE_T cbProt = cbBackup;
2710 ULONG fOldProt = 0;
2711 rcNt = NtProtectVirtualMemory(hProcess, &pvProt, &cbProt, PAGE_EXECUTE_READWRITE, &fOldProt);
2712 if (!NT_SUCCESS(rcNt))
2713 return RTErrInfoSetF(pErrInfo, VERR_GENERAL_FAILURE,
2714 "supR3HardNtDisableThreadCreationEx: NtProtectVirtualMemory/LdrInitializeThunk failed: %#x", rcNt);
2715
2716 rcNt = NtWriteVirtualMemory(hProcess, pvLdrInitThunk, abReplacement, sizeof(abReplacement), &cbIgnored);
2717 if (!NT_SUCCESS(rcNt))
2718 return RTErrInfoSetF(pErrInfo, VERR_GENERAL_FAILURE,
2719 "supR3HardNtDisableThreadCreationEx: NtWriteVirtualMemory/LdrInitializeThunk failed: %#x", rcNt);
2720
2721 pvProt = pvLdrInitThunk;
2722 cbProt = cbBackup;
2723 rcNt = NtProtectVirtualMemory(hProcess, &pvProt, &cbProt, fOldProt, &fOldProt);
2724 if (!NT_SUCCESS(rcNt))
2725 return RTErrInfoSetF(pErrInfo, VERR_GENERAL_FAILURE,
2726 "supR3HardNtDisableThreadCreationEx: NtProtectVirtualMemory/LdrInitializeThunk/2 failed: %#x", rcNt);
2727
2728 return VINF_SUCCESS;
2729}
2730
2731
2732/**
2733 * Undo the effects of supR3HardNtDisableThreadCreationEx.
2734 *
2735 * @returns VBox status code.
2736 * @param hProcess The process to do this to.
2737 * @param pvLdrInitThunk The address of the LdrInitializeThunk code to
2738 * override.
2739 * @param pabBackup Where to back up the original instruction bytes
2740 * at pvLdrInitThunk.
2741 * @param cbBackup The size of the backup area. Must be 16 bytes.
2742 * @param pErrInfo Where to return extended error information.
2743 * Optional.
2744 */
2745static int supR3HardNtEnableThreadCreationEx(HANDLE hProcess, void *pvLdrInitThunk, uint8_t const *pabBackup, size_t cbBackup,
2746 PRTERRINFO pErrInfo)
2747{
2748 SUP_DPRINTF(("supR3HardNtEnableThreadCreation:\n"));
2749 SUPR3HARDENED_ASSERT(cbBackup == 16);
2750
2751 PVOID pvProt = pvLdrInitThunk;
2752 SIZE_T cbProt = cbBackup;
2753 ULONG fOldProt = 0;
2754 NTSTATUS rcNt = NtProtectVirtualMemory(hProcess, &pvProt, &cbProt, PAGE_EXECUTE_READWRITE, &fOldProt);
2755 if (!NT_SUCCESS(rcNt))
2756 return RTErrInfoSetF(pErrInfo, VERR_GENERAL_FAILURE,
2757 "supR3HardNtDisableThreadCreationEx: NtProtectVirtualMemory/LdrInitializeThunk failed: %#x", rcNt);
2758
2759 SIZE_T cbIgnored;
2760 rcNt = NtWriteVirtualMemory(hProcess, pvLdrInitThunk, pabBackup, cbBackup, &cbIgnored);
2761 if (!NT_SUCCESS(rcNt))
2762 return RTErrInfoSetF(pErrInfo, VERR_GENERAL_FAILURE,
2763 "supR3HardNtEnableThreadCreation: NtWriteVirtualMemory/LdrInitializeThunk[restore] failed: %#x",
2764 rcNt);
2765
2766 pvProt = pvLdrInitThunk;
2767 cbProt = cbBackup;
2768 rcNt = NtProtectVirtualMemory(hProcess, &pvProt, &cbProt, fOldProt, &fOldProt);
2769 if (!NT_SUCCESS(rcNt))
2770 return RTErrInfoSetF(pErrInfo, VERR_GENERAL_FAILURE,
2771 "supR3HardNtEnableThreadCreation: NtProtectVirtualMemory/LdrInitializeThunk[restore] failed: %#x",
2772 rcNt);
2773
2774 return VINF_SUCCESS;
2775}
2776
2777
2778/**
2779 * Disable thread creation for the current process.
2780 *
2781 * @remarks Doesn't really disables it, just makes the threads exit immediately
2782 * without executing any real code.
2783 */
2784static void supR3HardenedWinDisableThreadCreation(void)
2785{
2786 /* Cannot use the imported NtTerminateThread as it's pointing to our own
2787 syscall assembly code. */
2788 static PFNRT s_pfnNtTerminateThread = NULL;
2789 if (s_pfnNtTerminateThread == NULL)
2790 s_pfnNtTerminateThread = supR3HardenedWinGetRealDllSymbol("ntdll.dll", "NtTerminateThread");
2791 SUPR3HARDENED_ASSERT(s_pfnNtTerminateThread);
2792
2793 int rc = supR3HardNtDisableThreadCreationEx(NtCurrentProcess(),
2794 (void *)(uintptr_t)&LdrInitializeThunk,
2795 (void *)(uintptr_t)s_pfnNtTerminateThread,
2796 g_abLdrInitThunkSelfBackup, sizeof(g_abLdrInitThunkSelfBackup),
2797 NULL /* pErrInfo*/);
2798 g_fSupInitThunkSelfPatched = RT_SUCCESS(rc);
2799}
2800
2801
2802/**
2803 * Undoes the effects of supR3HardenedWinDisableThreadCreation.
2804 */
2805DECLHIDDEN(void) supR3HardenedWinEnableThreadCreation(void)
2806{
2807 if (g_fSupInitThunkSelfPatched)
2808 {
2809 int rc = supR3HardNtEnableThreadCreationEx(NtCurrentProcess(),
2810 (void *)(uintptr_t)&LdrInitializeThunk,
2811 g_abLdrInitThunkSelfBackup, sizeof(g_abLdrInitThunkSelfBackup),
2812 RTErrInfoInitStatic(&g_ErrInfoStatic));
2813 if (RT_FAILURE(rc))
2814 supR3HardenedError(rc, true /*fFatal*/, "%s", g_ErrInfoStatic.szMsg);
2815 g_fSupInitThunkSelfPatched = false;
2816 }
2817}
2818
2819
2820
2821
2822/*
2823 *
2824 * R e s p a w n
2825 * R e s p a w n
2826 * R e s p a w n
2827 *
2828 */
2829
2830
2831/**
2832 * Gets the SID of the user associated with the process.
2833 *
2834 * @returns @c true if we've got a login SID, @c false if not.
2835 * @param pSidUser Where to return the user SID.
2836 * @param cbSidUser The size of the user SID buffer.
2837 * @param pSidLogin Where to return the login SID.
2838 * @param cbSidLogin The size of the login SID buffer.
2839 */
2840static bool supR3HardNtChildGetUserAndLogSids(PSID pSidUser, ULONG cbSidUser, PSID pSidLogin, ULONG cbSidLogin)
2841{
2842 HANDLE hToken;
2843 SUPR3HARDENED_ASSERT_NT_SUCCESS(NtOpenProcessToken(NtCurrentProcess(), TOKEN_QUERY, &hToken));
2844 union
2845 {
2846 TOKEN_USER UserInfo;
2847 TOKEN_GROUPS Groups;
2848 uint8_t abPadding[4096];
2849 } uBuf;
2850 ULONG cbRet = 0;
2851 SUPR3HARDENED_ASSERT_NT_SUCCESS(NtQueryInformationToken(hToken, TokenUser, &uBuf, sizeof(uBuf), &cbRet));
2852 SUPR3HARDENED_ASSERT_NT_SUCCESS(RtlCopySid(cbSidUser, pSidUser, uBuf.UserInfo.User.Sid));
2853
2854 bool fLoginSid = false;
2855 NTSTATUS rcNt = NtQueryInformationToken(hToken, TokenLogonSid, &uBuf, sizeof(uBuf), &cbRet);
2856 if (NT_SUCCESS(rcNt))
2857 {
2858 for (DWORD i = 0; i < uBuf.Groups.GroupCount; i++)
2859 if ((uBuf.Groups.Groups[i].Attributes & SE_GROUP_LOGON_ID) == SE_GROUP_LOGON_ID)
2860 {
2861 SUPR3HARDENED_ASSERT_NT_SUCCESS(RtlCopySid(cbSidLogin, pSidLogin, uBuf.Groups.Groups[i].Sid));
2862 fLoginSid = true;
2863 break;
2864 }
2865 }
2866
2867 SUPR3HARDENED_ASSERT_NT_SUCCESS(NtClose(hToken));
2868
2869 return fLoginSid;
2870}
2871
2872
2873/**
2874 * Build security attributes for the process or the primary thread (@a fProcess)
2875 *
2876 * Process DACLs can be bypassed using the SeDebugPrivilege (generally available
2877 * to admins, i.e. normal windows users), or by taking ownership and/or
2878 * modifying the DACL. However, it restricts
2879 *
2880 * @param pSecAttrs Where to return the security attributes.
2881 * @param pCleanup Cleanup record.
2882 * @param fProcess Set if it's for the process, clear if it's for
2883 * the primary thread.
2884 */
2885static void supR3HardNtChildInitSecAttrs(PSECURITY_ATTRIBUTES pSecAttrs, PMYSECURITYCLEANUP pCleanup, bool fProcess)
2886{
2887 /*
2888 * Safe return values.
2889 */
2890 suplibHardenedMemSet(pCleanup, 0, sizeof(*pCleanup));
2891
2892 pSecAttrs->nLength = sizeof(*pSecAttrs);
2893 pSecAttrs->bInheritHandle = FALSE;
2894 pSecAttrs->lpSecurityDescriptor = NULL;
2895
2896/** @todo This isn't at all complete, just sketches... */
2897
2898 /*
2899 * Create an ACL detailing the access of the above groups.
2900 */
2901 SUPR3HARDENED_ASSERT_NT_SUCCESS(RtlCreateAcl(&pCleanup->Acl.AclHdr, sizeof(pCleanup->Acl), ACL_REVISION));
2902
2903 ULONG fDeny = DELETE | WRITE_DAC | WRITE_OWNER;
2904 ULONG fAllow = SYNCHRONIZE | READ_CONTROL;
2905 ULONG fAllowLogin = SYNCHRONIZE | READ_CONTROL;
2906 if (fProcess)
2907 {
2908 fDeny |= PROCESS_CREATE_THREAD | PROCESS_SET_SESSIONID | PROCESS_VM_OPERATION | PROCESS_VM_WRITE
2909 | PROCESS_CREATE_PROCESS | PROCESS_DUP_HANDLE | PROCESS_SET_QUOTA
2910 | PROCESS_SET_INFORMATION | PROCESS_SUSPEND_RESUME;
2911 fAllow |= PROCESS_TERMINATE | PROCESS_VM_READ | PROCESS_QUERY_INFORMATION;
2912 fAllowLogin |= PROCESS_TERMINATE | PROCESS_VM_READ | PROCESS_QUERY_INFORMATION;
2913 if (g_uNtVerCombined >= SUP_MAKE_NT_VER_SIMPLE(6, 0)) /* Introduced in Vista. */
2914 {
2915 fAllow |= PROCESS_QUERY_LIMITED_INFORMATION;
2916 fAllowLogin |= PROCESS_QUERY_LIMITED_INFORMATION;
2917 }
2918 if (g_uNtVerCombined >= SUP_MAKE_NT_VER_SIMPLE(6, 3)) /* Introduced in Windows 8.1. */
2919 fAllow |= PROCESS_SET_LIMITED_INFORMATION;
2920 }
2921 else
2922 {
2923 fDeny |= THREAD_SUSPEND_RESUME | THREAD_SET_CONTEXT | THREAD_SET_INFORMATION | THREAD_SET_THREAD_TOKEN
2924 | THREAD_IMPERSONATE | THREAD_DIRECT_IMPERSONATION;
2925 fAllow |= THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION;
2926 fAllowLogin |= THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION;
2927 if (g_uNtVerCombined >= SUP_MAKE_NT_VER_SIMPLE(6, 0)) /* Introduced in Vista. */
2928 {
2929 fAllow |= THREAD_QUERY_LIMITED_INFORMATION | THREAD_SET_LIMITED_INFORMATION;
2930 fAllowLogin |= THREAD_QUERY_LIMITED_INFORMATION;
2931 }
2932
2933 }
2934 fDeny |= ~fAllow & (SPECIFIC_RIGHTS_ALL | STANDARD_RIGHTS_ALL);
2935
2936 /* Deny everyone access to bad bits. */
2937#if 1
2938 SID_IDENTIFIER_AUTHORITY SIDAuthWorld = SECURITY_WORLD_SID_AUTHORITY;
2939 SUPR3HARDENED_ASSERT_NT_SUCCESS(RtlInitializeSid(&pCleanup->Everyone.Sid, &SIDAuthWorld, 1));
2940 *RtlSubAuthoritySid(&pCleanup->Everyone.Sid, 0) = SECURITY_WORLD_RID;
2941 SUPR3HARDENED_ASSERT_NT_SUCCESS(RtlAddAccessDeniedAce(&pCleanup->Acl.AclHdr, ACL_REVISION,
2942 fDeny, &pCleanup->Everyone.Sid));
2943#endif
2944
2945#if 0
2946 /* Grant some access to the owner - doesn't work. */
2947 SID_IDENTIFIER_AUTHORITY SIDAuthCreator = SECURITY_CREATOR_SID_AUTHORITY;
2948 SUPR3HARDENED_ASSERT_NT_SUCCESS(RtlInitializeSid(&pCleanup->Owner.Sid, &SIDAuthCreator, 1));
2949 *RtlSubAuthoritySid(&pCleanup->Owner.Sid, 0) = SECURITY_CREATOR_OWNER_RID;
2950
2951 SUPR3HARDENED_ASSERT_NT_SUCCESS(RtlAddAccessDeniedAce(&pCleanup->Acl.AclHdr, ACL_REVISION,
2952 fDeny, &pCleanup->Owner.Sid));
2953 SUPR3HARDENED_ASSERT_NT_SUCCESS(RtlAddAccessAllowedAce(&pCleanup->Acl.AclHdr, ACL_REVISION,
2954 fAllow, &pCleanup->Owner.Sid));
2955#endif
2956
2957#if 1
2958 bool fHasLoginSid = supR3HardNtChildGetUserAndLogSids(&pCleanup->User.Sid, sizeof(pCleanup->User),
2959 &pCleanup->Login.Sid, sizeof(pCleanup->Login));
2960
2961# if 1
2962 /* Grant minimal access to the user. */
2963 SUPR3HARDENED_ASSERT_NT_SUCCESS(RtlAddAccessDeniedAce(&pCleanup->Acl.AclHdr, ACL_REVISION,
2964 fDeny, &pCleanup->User.Sid));
2965 SUPR3HARDENED_ASSERT_NT_SUCCESS(RtlAddAccessAllowedAce(&pCleanup->Acl.AclHdr, ACL_REVISION,
2966 fAllow, &pCleanup->User.Sid));
2967# endif
2968
2969# if 1
2970 /* Grant very limited access to the login sid. */
2971 if (fHasLoginSid)
2972 {
2973 SUPR3HARDENED_ASSERT_NT_SUCCESS(RtlAddAccessAllowedAce(&pCleanup->Acl.AclHdr, ACL_REVISION,
2974 fAllowLogin, &pCleanup->Login.Sid));
2975 }
2976# endif
2977
2978#endif
2979
2980 /*
2981 * Create a security descriptor with the above ACL.
2982 */
2983 PSECURITY_DESCRIPTOR pSecDesc = (PSECURITY_DESCRIPTOR)RTMemAllocZ(SECURITY_DESCRIPTOR_MIN_LENGTH);
2984 pCleanup->pSecDesc = pSecDesc;
2985
2986 SUPR3HARDENED_ASSERT_NT_SUCCESS(RtlCreateSecurityDescriptor(pSecDesc, SECURITY_DESCRIPTOR_REVISION));
2987 SUPR3HARDENED_ASSERT_NT_SUCCESS(RtlSetDaclSecurityDescriptor(pSecDesc, TRUE /*fDaclPresent*/, &pCleanup->Acl.AclHdr,
2988 FALSE /*fDaclDefaulted*/));
2989 pSecAttrs->lpSecurityDescriptor = pSecDesc;
2990}
2991
2992
2993/**
2994 * Predicate function which tests whether @a ch is a argument separator
2995 * character.
2996 *
2997 * @returns True/false.
2998 * @param ch The character to examine.
2999 */
3000DECLINLINE(bool) suplibCommandLineIsArgSeparator(int ch)
3001{
3002 return ch == ' '
3003 || ch == '\t'
3004 || ch == '\n'
3005 || ch == '\r';
3006}
3007
3008
3009/**
3010 * Construct the new command line.
3011 *
3012 * Since argc/argv are both derived from GetCommandLineW (see
3013 * suplibHardenedWindowsMain), we skip the argument by argument UTF-8 -> UTF-16
3014 * conversion and quoting by going to the original source.
3015 *
3016 * The executable name, though, is replaced in case it's not a fullly
3017 * qualified path.
3018 *
3019 * The re-spawn indicator is added immediately after the executable name
3020 * so that we don't get tripped up missing close quote chars in the last
3021 * argument.
3022 *
3023 * @returns Pointer to a command line string (heap).
3024 * @param pString Unicode string structure to initialize to the
3025 * command line. Optional.
3026 * @param iWhich Which respawn we're to check for, 1 being the first
3027 * one, and 2 the second and final.
3028 */
3029static PRTUTF16 supR3HardNtChildConstructCmdLine(PUNICODE_STRING pString, int iWhich)
3030{
3031 SUPR3HARDENED_ASSERT(iWhich == 1 || iWhich == 2);
3032
3033 /*
3034 * Get the command line and skip the executable name.
3035 */
3036 PUNICODE_STRING pCmdLineStr = &NtCurrentPeb()->ProcessParameters->CommandLine;
3037 PCRTUTF16 pawcArgs = pCmdLineStr->Buffer;
3038 uint32_t cwcArgs = pCmdLineStr->Length / sizeof(WCHAR);
3039
3040 /* Skip leading space (shouldn't be any, but whatever). */
3041 while (cwcArgs > 0 && suplibCommandLineIsArgSeparator(*pawcArgs) )
3042 cwcArgs--, pawcArgs++;
3043 SUPR3HARDENED_ASSERT(cwcArgs > 0 && *pawcArgs != '\0');
3044
3045 /* Walk to the end of it. */
3046 int fQuoted = false;
3047 do
3048 {
3049 if (*pawcArgs == '"')
3050 {
3051 fQuoted = !fQuoted;
3052 cwcArgs--; pawcArgs++;
3053 }
3054 else if (*pawcArgs != '\\' || (pawcArgs[1] != '\\' && pawcArgs[1] != '"'))
3055 cwcArgs--, pawcArgs++;
3056 else
3057 {
3058 unsigned cSlashes = 0;
3059 do
3060 {
3061 cSlashes++;
3062 cwcArgs--;
3063 pawcArgs++;
3064 }
3065 while (cwcArgs > 0 && *pawcArgs == '\\');
3066 if (cwcArgs > 0 && *pawcArgs == '"' && (cSlashes & 1))
3067 cwcArgs--, pawcArgs++; /* odd number of slashes == escaped quote */
3068 }
3069 } while (cwcArgs > 0 && (fQuoted || !suplibCommandLineIsArgSeparator(*pawcArgs)));
3070
3071 /* Skip trailing spaces. */
3072 while (cwcArgs > 0 && suplibCommandLineIsArgSeparator(*pawcArgs))
3073 cwcArgs--, pawcArgs++;
3074
3075 /*
3076 * Allocate a new buffer.
3077 */
3078 AssertCompile(sizeof(SUPR3_RESPAWN_1_ARG0) == sizeof(SUPR3_RESPAWN_2_ARG0));
3079 size_t cwcCmdLine = (sizeof(SUPR3_RESPAWN_1_ARG0) - 1) / sizeof(SUPR3_RESPAWN_1_ARG0[0]) /* Respawn exe name. */
3080 + !!cwcArgs + cwcArgs; /* if arguments present, add space + arguments. */
3081 if (cwcCmdLine * sizeof(WCHAR) >= 0xfff0)
3082 supR3HardenedFatalMsg("supR3HardNtChildConstructCmdLine", kSupInitOp_Misc, VERR_OUT_OF_RANGE,
3083 "Command line is too long (%u chars)!", cwcCmdLine);
3084
3085 PRTUTF16 pwszCmdLine = (PRTUTF16)RTMemAlloc((cwcCmdLine + 1) * sizeof(RTUTF16));
3086 SUPR3HARDENED_ASSERT(pwszCmdLine != NULL);
3087
3088 /*
3089 * Construct the new command line.
3090 */
3091 PRTUTF16 pwszDst = pwszCmdLine;
3092 for (const char *pszSrc = iWhich == 1 ? SUPR3_RESPAWN_1_ARG0 : SUPR3_RESPAWN_2_ARG0; *pszSrc; pszSrc++)
3093 *pwszDst++ = *pszSrc;
3094
3095 if (cwcArgs)
3096 {
3097 *pwszDst++ = ' ';
3098 suplibHardenedMemCopy(pwszDst, pawcArgs, cwcArgs * sizeof(RTUTF16));
3099 pwszDst += cwcArgs;
3100 }
3101
3102 *pwszDst = '\0';
3103 SUPR3HARDENED_ASSERT((uintptr_t)(pwszDst - pwszCmdLine) == cwcCmdLine);
3104
3105 if (pString)
3106 {
3107 pString->Buffer = pwszCmdLine;
3108 pString->Length = (USHORT)(cwcCmdLine * sizeof(WCHAR));
3109 pString->MaximumLength = pString->Length + sizeof(WCHAR);
3110 }
3111 return pwszCmdLine;
3112}
3113
3114
3115/**
3116 * Terminates the child process.
3117 *
3118 * @param hProcess The process handle.
3119 * @param pszWhere Who's having child rasing troubles.
3120 * @param rc The status code to report.
3121 * @param pszFormat The message format string.
3122 * @param ... Message format arguments.
3123 */
3124static void supR3HardenedWinKillChild(HANDLE hProcess, const char *pszWhere, int rc, const char *pszFormat, ...)
3125{
3126 /*
3127 * Terminate the process ASAP and display error.
3128 */
3129 NtTerminateProcess(hProcess, RTEXITCODE_FAILURE);
3130
3131 va_list va;
3132 va_start(va, pszFormat);
3133 supR3HardenedErrorV(rc, false /*fFatal*/, pszFormat, va);
3134 va_end(va);
3135
3136 /*
3137 * Wait for the process to really go away.
3138 */
3139 PROCESS_BASIC_INFORMATION BasicInfo;
3140 NTSTATUS rcNtExit = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &BasicInfo, sizeof(BasicInfo), NULL);
3141 bool fExitOk = NT_SUCCESS(rcNtExit) && BasicInfo.ExitStatus != STATUS_PENDING;
3142 if (!fExitOk)
3143 {
3144 NTSTATUS rcNtWait;
3145 uint64_t uMsTsStart = supR3HardenedWinGetMilliTS();
3146 do
3147 {
3148 NtTerminateProcess(hProcess, DBG_TERMINATE_PROCESS);
3149
3150 LARGE_INTEGER Timeout;
3151 Timeout.QuadPart = -20000000; /* 2 second */
3152 rcNtWait = NtWaitForSingleObject(hProcess, TRUE /*Alertable*/, &Timeout);
3153
3154 rcNtExit = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &BasicInfo, sizeof(BasicInfo), NULL);
3155 fExitOk = NT_SUCCESS(rcNtExit) && BasicInfo.ExitStatus != STATUS_PENDING;
3156 } while ( !fExitOk
3157 && ( rcNtWait == STATUS_TIMEOUT
3158 || rcNtWait == STATUS_USER_APC
3159 || rcNtWait == STATUS_ALERTED)
3160 && supR3HardenedWinGetMilliTS() - uMsTsStart < 60 * 1000);
3161 if (fExitOk)
3162 supR3HardenedError(rc, false /*fFatal*/,
3163 "NtDuplicateObject failed and we failed to kill child: rc=%u (%#x) rcNtWait=%#x hProcess=%p\n",
3164 rc, rc, rcNtWait, hProcess);
3165 }
3166
3167 /*
3168 * Final error message.
3169 */
3170 va_start(va, pszFormat);
3171 supR3HardenedFatalMsgV(pszWhere, kSupInitOp_Misc, rc, pszFormat, va);
3172 /* not reached */
3173}
3174
3175
3176/**
3177 * Checks the child process when hEvtParent is signalled.
3178 *
3179 * This will read the request data from the child and check it against expected
3180 * request. If an error is signalled, we'll raise it and make sure the child
3181 * terminates before terminating the calling process.
3182 *
3183 * @param pThis The child process data structure.
3184 * @param enmExpectedRequest The expected child request.
3185 * @param pszWhat What we're waiting for.
3186 */
3187static void supR3HardNtChildProcessRequest(PSUPR3HARDNTCHILD pThis, SUPR3WINCHILDREQ enmExpectedRequest, const char *pszWhat)
3188{
3189 /*
3190 * Read the process parameters from the child.
3191 */
3192 uintptr_t uChildAddr = (uintptr_t)pThis->Peb.ImageBaseAddress
3193 + ((uintptr_t)&g_ProcParams - (uintptr_t)NtCurrentPeb()->ImageBaseAddress);
3194 SIZE_T cbIgnored = 0;
3195 RT_ZERO(pThis->ProcParams);
3196 NTSTATUS rcNt = NtReadVirtualMemory(pThis->hProcess, (PVOID)uChildAddr,
3197 &pThis->ProcParams, sizeof(pThis->ProcParams), &cbIgnored);
3198 if (!NT_SUCCESS(rcNt))
3199 supR3HardenedWinKillChild(pThis, "supR3HardNtChildProcessRequest", rcNt,
3200 "NtReadVirtualMemory(,%p,) failed reading child process status: %#x\n", uChildAddr, rcNt);
3201
3202 /*
3203 * Is it the expected request?
3204 */
3205 if (pThis->ProcParams.enmRequest == enmExpectedRequest)
3206 return;
3207
3208 /*
3209 * No, not the expected request. If it's an error request, tell the child
3210 * to terminate itself, otherwise we'll have to terminate it.
3211 */
3212 pThis->ProcParams.szErrorMsg[sizeof(pThis->ProcParams.szErrorMsg) - 1] = '\0';
3213 pThis->ProcParams.szWhere[sizeof(pThis->ProcParams.szWhere) - 1] = '\0';
3214 SUP_DPRINTF(("supR3HardenedWinCheckChild: enmRequest=%d rc=%d enmWhat=%d %s: %s\n",
3215 pThis->ProcParams.enmRequest, pThis->ProcParams.rc, pThis->ProcParams.enmWhat,
3216 pThis->ProcParams.szWhere, pThis->ProcParams.szErrorMsg));
3217
3218 if (pThis->ProcParams.enmRequest != kSupR3WinChildReq_Error)
3219 supR3HardenedWinKillChild(pThis, "supR3HardenedWinCheckChild", VERR_INVALID_PARAMETER,
3220 "Unexpected child request #%d. Was expecting #%d (%s).\n",
3221 pThis->ProcParams.enmRequest, enmExpectedRequest, pszWhat);
3222
3223 rcNt = NtSetEvent(pThis->hEvtChild, NULL);
3224 if (!NT_SUCCESS(rcNt))
3225 supR3HardenedWinKillChild(pThis, "supR3HardNtChildProcessRequest", rcNt, "NtSetEvent failed: %#x\n", rcNt);
3226
3227 /* Wait for it to terminate. */
3228 LARGE_INTEGER Timeout;
3229 Timeout.QuadPart = -50000000; /* 5 seconds */
3230 rcNt = NtWaitForSingleObject(pThis->hProcess, FALSE /*Alertable*/, &Timeout);
3231 if (rcNt != STATUS_WAIT_0)
3232 {
3233 SUP_DPRINTF(("supR3HardNtChildProcessRequest: Child is taking too long to quit (rcWait=%#x), killing it...\n", rcNt));
3234 NtTerminateProcess(pThis->hProcess, DBG_TERMINATE_PROCESS);
3235 }
3236
3237 /*
3238 * Report the error in the same way as it occured in the guest.
3239 */
3240 if (pThis->ProcParams.enmWhat == kSupInitOp_Invalid)
3241 supR3HardenedFatalMsg("supR3HardenedWinCheckChild", kSupInitOp_Misc, pThis->ProcParams.rc,
3242 "%s", pThis->ProcParams.szErrorMsg);
3243 else
3244 supR3HardenedFatalMsg(pThis->ProcParams.szWhere, pThis->ProcParams.enmWhat, pThis->ProcParams.rc,
3245 "%s", pThis->ProcParams.szErrorMsg);
3246}
3247
3248
3249/**
3250 * Waits for the child to make a certain request or terminate.
3251 *
3252 * The stub process will also wait on it's parent to terminate.
3253 * This call will only return if the child made the expected request.
3254 *
3255 * @param pThis The child process data structure.
3256 * @param enmExpectedRequest The child request to wait for.
3257 * @param cMsTimeout The number of milliseconds to wait (at least).
3258 * @param pszWhat What we're waiting for.
3259 */
3260static void supR3HardNtChildWaitFor(PSUPR3HARDNTCHILD pThis, SUPR3WINCHILDREQ enmExpectedRequest, RTMSINTERVAL cMsTimeout,
3261 const char *pszWhat)
3262{
3263 /*
3264 * The wait loop.
3265 * Will return when the expected request arrives.
3266 * Will break out when one of the processes terminates.
3267 */
3268 NTSTATUS rcNtWait;
3269 LARGE_INTEGER Timeout;
3270 uint64_t uMsTsStart = supR3HardenedWinGetMilliTS();
3271 uint64_t cMsElapsed = 0;
3272 for (;;)
3273 {
3274 /*
3275 * Assemble handles to wait for.
3276 */
3277 ULONG cHandles = 1;
3278 HANDLE ahHandles[3];
3279 ahHandles[0] = pThis->hProcess;
3280 if (pThis->hEvtParent)
3281 ahHandles[cHandles++] = pThis->hEvtParent;
3282 if (pThis->hParent)
3283 ahHandles[cHandles++] = pThis->hParent;
3284
3285 /*
3286 * Do the waiting according to the callers wishes.
3287 */
3288 if ( enmExpectedRequest == kSupR3WinChildReq_End
3289 || cMsTimeout == RT_INDEFINITE_WAIT)
3290 rcNtWait = NtWaitForMultipleObjects(cHandles, &ahHandles[0], WaitAnyObject, TRUE /*Alertable*/, NULL /*Timeout*/);
3291 else
3292 {
3293 Timeout.QuadPart = -(int64_t)(cMsTimeout - cMsElapsed) * 10000;
3294 rcNtWait = NtWaitForMultipleObjects(cHandles, &ahHandles[0], WaitAnyObject, TRUE /*Alertable*/, &Timeout);
3295 }
3296
3297 /*
3298 * Process child request.
3299 */
3300 if (rcNtWait == STATUS_WAIT_0 + 1 && pThis->hEvtParent != NULL)
3301 {
3302 supR3HardNtChildProcessRequest(pThis, enmExpectedRequest, pszWhat);
3303 SUP_DPRINTF(("supR3HardNtChildWaitFor: Found expected request %d (%s) after %llu ms.\n",
3304 enmExpectedRequest, pszWhat, supR3HardenedWinGetMilliTS() - uMsTsStart));
3305 return; /* Expected request received. */
3306 }
3307
3308 /*
3309 * Process termination?
3310 */
3311 if ( (ULONG)rcNtWait - (ULONG)STATUS_WAIT_0 < cHandles
3312 || (ULONG)rcNtWait - (ULONG)STATUS_ABANDONED_WAIT_0 < cHandles)
3313 break;
3314
3315 /*
3316 * Check sanity.
3317 */
3318 if ( rcNtWait != STATUS_TIMEOUT
3319 && rcNtWait != STATUS_USER_APC
3320 && rcNtWait != STATUS_ALERTED)
3321 supR3HardenedWinKillChild(pThis, "supR3HardNtChildWaitFor", rcNtWait,
3322 "NtWaitForMultipleObjects returned %#x waiting for #%d (%s)\n",
3323 rcNtWait, enmExpectedRequest, pszWhat);
3324
3325 /*
3326 * Calc elapsed time for the next timeout calculation, checking to see
3327 * if we've timed out already.
3328 */
3329 cMsElapsed = supR3HardenedWinGetMilliTS() - uMsTsStart;
3330 if ( cMsElapsed > cMsTimeout
3331 && cMsTimeout != RT_INDEFINITE_WAIT
3332 && enmExpectedRequest != kSupR3WinChildReq_End)
3333 {
3334 if (rcNtWait == STATUS_USER_APC || rcNtWait == STATUS_ALERTED)
3335 cMsElapsed = cMsTimeout - 1; /* try again */
3336 else
3337 {
3338 /* We timed out. */
3339 supR3HardenedWinKillChild(pThis, "supR3HardNtChildWaitFor", rcNtWait,
3340 "Timed out after %llu ms waiting for child request #%d (%s).\n",
3341 cMsElapsed, enmExpectedRequest, pszWhat);
3342 }
3343 }
3344 }
3345
3346 /*
3347 * Proxy the termination code of the child, if it exited already.
3348 */
3349 PROCESS_BASIC_INFORMATION BasicInfo;
3350 NTSTATUS rcNt1 = NtQueryInformationProcess(pThis->hProcess, ProcessBasicInformation, &BasicInfo, sizeof(BasicInfo), NULL);
3351 NTSTATUS rcNt2 = STATUS_PENDING;
3352 NTSTATUS rcNt3 = STATUS_PENDING;
3353 if ( !NT_SUCCESS(rcNt1)
3354 || BasicInfo.ExitStatus == STATUS_PENDING)
3355 {
3356 rcNt2 = NtTerminateProcess(pThis->hProcess, RTEXITCODE_FAILURE);
3357 Timeout.QuadPart = NT_SUCCESS(rcNt2) ? -20000000 /* 2 sec */ : -1280000 /* 128 ms */;
3358 rcNt3 = NtWaitForSingleObject(pThis->hProcess, FALSE /*Alertable*/, NULL /*Timeout*/);
3359 BasicInfo.ExitStatus = RTEXITCODE_FAILURE;
3360 }
3361
3362 SUP_DPRINTF(("supR3HardNtChildWaitFor[%d]: Quitting: ExitCode=%#x (rcNtWait=%#x, rcNt1=%#x, rcNt2=%#x, rcNt3=%#x, %llu ms, %s);\n",
3363 pThis->iWhich, BasicInfo.ExitStatus, rcNtWait, rcNt1, rcNt2, rcNt3,
3364 supR3HardenedWinGetMilliTS() - uMsTsStart, pszWhat));
3365 suplibHardenedExit((RTEXITCODE)BasicInfo.ExitStatus);
3366}
3367
3368
3369/**
3370 * Closes full access child thread and process handles, making a harmless
3371 * duplicate of the process handle first.
3372 *
3373 * The hProcess member of the child process data structure will be change to the
3374 * harmless handle, while the hThread will be set to NULL.
3375 *
3376 * @param pThis The child process data structure.
3377 */
3378static void supR3HardNtChildCloseFullAccessHandles(PSUPR3HARDNTCHILD pThis)
3379{
3380 /*
3381 * The thread handle.
3382 */
3383 NTSTATUS rcNt = NtClose(pThis->hThread);
3384 if (!NT_SUCCESS(rcNt))
3385 supR3HardenedWinKillChild(pThis, "supR3HardenedWinReSpawn", rcNt, "NtClose(hThread) failed: %#x", rcNt);
3386 pThis->hThread = NULL;
3387
3388 /*
3389 * Duplicate the process handle into a harmless one.
3390 */
3391 HANDLE hProcWait;
3392 ULONG fRights = SYNCHRONIZE | PROCESS_TERMINATE | PROCESS_VM_READ;
3393 if (g_uNtVerCombined >= SUP_MAKE_NT_VER_SIMPLE(6, 0)) /* Introduced in Vista. */
3394 fRights |= PROCESS_QUERY_LIMITED_INFORMATION;
3395 else
3396 fRights |= PROCESS_QUERY_INFORMATION;
3397 rcNt = NtDuplicateObject(NtCurrentProcess(), pThis->hProcess,
3398 NtCurrentProcess(), &hProcWait,
3399 fRights, 0 /*HandleAttributes*/, 0);
3400 if (rcNt == STATUS_ACCESS_DENIED)
3401 {
3402 supR3HardenedError(rcNt, false /*fFatal*/,
3403 "supR3HardenedWinDoReSpawn: NtDuplicateObject(,,,,%#x,,) -> %#x, retrying with only %#x...\n",
3404 fRights, rcNt, SYNCHRONIZE);
3405 rcNt = NtDuplicateObject(NtCurrentProcess(), pThis->hProcess,
3406 NtCurrentProcess(), &hProcWait,
3407 SYNCHRONIZE, 0 /*HandleAttributes*/, 0);
3408 }
3409 if (!NT_SUCCESS(rcNt))
3410 supR3HardenedWinKillChild(pThis, "supR3HardenedWinReSpawn", rcNt,
3411 "NtDuplicateObject failed on child process handle: %#x\n", rcNt);
3412 /*
3413 * Close the process handle and replace it with the harmless one.
3414 */
3415 rcNt = NtClose(pThis->hProcess);
3416 pThis->hProcess = hProcWait;
3417 if (!NT_SUCCESS(rcNt))
3418 supR3HardenedWinKillChild(pThis, "supR3HardenedWinReSpawn", VERR_INVALID_NAME,
3419 "NtClose failed on child process handle: %#x\n", rcNt);
3420}
3421
3422
3423/**
3424 * This restores the child PEB and tweaks a couple of fields before we do the
3425 * child purification and let the process run normally.
3426 *
3427 * @param pThis The child process data structure.
3428 */
3429static void supR3HardNtChildSanitizePeb(PSUPR3HARDNTCHILD pThis)
3430{
3431 /*
3432 * Make a copy of the pre-execution PEB.
3433 */
3434 PEB Peb = pThis->Peb;
3435
3436#if 0
3437 /*
3438 * There should not be any activation context, so if there is, we scratch the memory associated with it.
3439 */
3440 int rc = 0;
3441 if (RT_SUCCESS(rc) && Peb.pShimData && !((uintptr_t)Peb.pShimData & PAGE_OFFSET_MASK))
3442 rc = supR3HardenedWinScratchChildMemory(hProcess, Peb.pShimData, PAGE_SIZE, "pShimData", pErrInfo);
3443 if (RT_SUCCESS(rc) && Peb.ActivationContextData && !((uintptr_t)Peb.ActivationContextData & PAGE_OFFSET_MASK))
3444 rc = supR3HardenedWinScratchChildMemory(hProcess, Peb.ActivationContextData, PAGE_SIZE, "ActivationContextData", pErrInfo);
3445 if (RT_SUCCESS(rc) && Peb.ProcessAssemblyStorageMap && !((uintptr_t)Peb.ProcessAssemblyStorageMap & PAGE_OFFSET_MASK))
3446 rc = supR3HardenedWinScratchChildMemory(hProcess, Peb.ProcessAssemblyStorageMap, PAGE_SIZE, "ProcessAssemblyStorageMap", pErrInfo);
3447 if (RT_SUCCESS(rc) && Peb.SystemDefaultActivationContextData && !((uintptr_t)Peb.SystemDefaultActivationContextData & PAGE_OFFSET_MASK))
3448 rc = supR3HardenedWinScratchChildMemory(hProcess, Peb.ProcessAssemblyStorageMap, PAGE_SIZE, "SystemDefaultActivationContextData", pErrInfo);
3449 if (RT_SUCCESS(rc) && Peb.SystemAssemblyStorageMap && !((uintptr_t)Peb.SystemAssemblyStorageMap & PAGE_OFFSET_MASK))
3450 rc = supR3HardenedWinScratchChildMemory(hProcess, Peb.SystemAssemblyStorageMap, PAGE_SIZE, "SystemAssemblyStorageMap", pErrInfo);
3451 if (RT_FAILURE(rc))
3452 return rc;
3453#endif
3454
3455 /*
3456 * Clear compatibility and activation related fields.
3457 */
3458 Peb.AppCompatFlags.QuadPart = 0;
3459 Peb.AppCompatFlagsUser.QuadPart = 0;
3460 Peb.pShimData = NULL;
3461 Peb.AppCompatInfo = NULL;
3462#if 0
3463 Peb.ActivationContextData = NULL;
3464 Peb.ProcessAssemblyStorageMap = NULL;
3465 Peb.SystemDefaultActivationContextData = NULL;
3466 Peb.SystemAssemblyStorageMap = NULL;
3467 /*Peb.Diff0.W6.IsProtectedProcess = 1;*/
3468#endif
3469
3470 /*
3471 * Write back the PEB.
3472 */
3473 SIZE_T cbActualMem = pThis->cbPeb;
3474 NTSTATUS rcNt = NtWriteVirtualMemory(pThis->hProcess, pThis->BasicInfo.PebBaseAddress, &Peb, pThis->cbPeb, &cbActualMem);
3475 if (!NT_SUCCESS(rcNt))
3476 supR3HardenedWinKillChild(pThis, "supR3HardNtChildSanitizePeb", rcNt,
3477 "NtWriteVirtualMemory/Peb failed: %#x", rcNt);
3478
3479}
3480
3481
3482/**
3483 * Purifies the child process after very early init has been performed.
3484 *
3485 * @param pThis The child process data structure.
3486 */
3487static void supR3HardNtChildPurify(PSUPR3HARDNTCHILD pThis)
3488{
3489 /*
3490 * We loop until we no longer make any fixes. This is similar to what
3491 * we do (or used to do, really) in the fAvastKludge case of
3492 * supR3HardenedWinInit. We might be up against asynchronous changes,
3493 * which we fudge by waiting a short while before earch purification. This
3494 * is arguably a fragile technique, but it's currently the best we've got.
3495 * Fortunately, most AVs seems to either favor immediate action on initial
3496 * load events or (much better for us) later events like kernel32.
3497 */
3498 uint64_t uMsTsOuterStart = supR3HardenedWinGetMilliTS();
3499 uint32_t cMsFudge = g_fSupAdversaries ? 512 : 256;
3500 uint32_t cTotalFixes = 0;
3501 uint32_t cFixes = 0; /* (MSC wrongly thinks this maybe used uninitialized) */
3502 for (uint32_t iLoop = 0; iLoop < 16; iLoop++)
3503 {
3504 /*
3505 * Delay.
3506 */
3507 uint32_t cSleeps = 0;
3508 uint64_t uMsTsStart = supR3HardenedWinGetMilliTS();
3509 do
3510 {
3511 NtYieldExecution();
3512 LARGE_INTEGER Time;
3513 Time.QuadPart = -8000000 / 100; /* 8ms in 100ns units, relative time. */
3514 NtDelayExecution(FALSE, &Time);
3515 cSleeps++;
3516 } while ( supR3HardenedWinGetMilliTS() - uMsTsStart <= cMsFudge
3517 || cSleeps < 8);
3518 SUP_DPRINTF(("supR3HardNtChildPurify: Startup delay kludge #1/%u: %u ms, %u sleeps\n",
3519 iLoop, supR3HardenedWinGetMilliTS() - uMsTsStart, cSleeps));
3520
3521 /*
3522 * Purify.
3523 */
3524 cFixes = 0;
3525 int rc = supHardenedWinVerifyProcess(pThis->hProcess, pThis->hThread, SUPHARDNTVPKIND_CHILD_PURIFICATION,
3526 g_fSupAdversaries & ( SUPHARDNT_ADVERSARY_TRENDMICRO_SAKFILE
3527 | SUPHARDNT_ADVERSARY_DIGITAL_GUARDIAN_OLD)
3528 ? SUPHARDNTVP_F_EXEC_ALLOC_REPLACE_WITH_RW : 0,
3529 &cFixes, RTErrInfoInitStatic(&g_ErrInfoStatic));
3530 if (RT_FAILURE(rc))
3531 supR3HardenedWinKillChild(pThis, "supR3HardNtChildPurify", rc,
3532 "supHardenedWinVerifyProcess failed with %Rrc: %s", rc, g_ErrInfoStatic.szMsg);
3533 if (cFixes == 0)
3534 {
3535 SUP_DPRINTF(("supR3HardNtChildPurify: Done after %llu ms and %u fixes (loop #%u).\n",
3536 supR3HardenedWinGetMilliTS() - uMsTsOuterStart, cTotalFixes, iLoop));
3537 return; /* We're probably good. */
3538 }
3539 cTotalFixes += cFixes;
3540
3541 if (!g_fSupAdversaries)
3542 g_fSupAdversaries |= SUPHARDNT_ADVERSARY_UNKNOWN;
3543 cMsFudge = 512;
3544
3545 /*
3546 * Log the KiOpPrefetchPatchCount value if available, hoping it might
3547 * sched some light on spider38's case.
3548 */
3549 ULONG cPatchCount = 0;
3550 NTSTATUS rcNt = NtQuerySystemInformation(SystemInformation_KiOpPrefetchPatchCount,
3551 &cPatchCount, sizeof(cPatchCount), NULL);
3552 if (NT_SUCCESS(rcNt))
3553 SUP_DPRINTF(("supR3HardNtChildPurify: cFixes=%u g_fSupAdversaries=%#x cPatchCount=%#u\n",
3554 cFixes, g_fSupAdversaries, cPatchCount));
3555 else
3556 SUP_DPRINTF(("supR3HardNtChildPurify: cFixes=%u g_fSupAdversaries=%#x\n", cFixes, g_fSupAdversaries));
3557 }
3558
3559 /*
3560 * We've given up fixing the child process. Probably fighting someone
3561 * that monitors their patches or/and our activities.
3562 */
3563 supR3HardenedWinKillChild(pThis, "supR3HardNtChildPurify", VERR_TRY_AGAIN,
3564 "Unable to purify child process! After 16 tries over %llu ms, we still %u fix(es) in the last pass.",
3565 supR3HardenedWinGetMilliTS() - uMsTsOuterStart, cFixes);
3566}
3567
3568
3569
3570/**
3571 * Sets up the early process init.
3572 *
3573 * @param pThis The child process data structure.
3574 */
3575static void supR3HardNtChildSetUpChildInit(PSUPR3HARDNTCHILD pThis)
3576{
3577 uintptr_t const uChildExeAddr = (uintptr_t)pThis->Peb.ImageBaseAddress;
3578
3579 /*
3580 * Plant the process parameters. This ASSUMES the handle inheritance is
3581 * performed when creating the child process.
3582 */
3583 RT_ZERO(pThis->ProcParams);
3584 pThis->ProcParams.hEvtChild = pThis->hEvtChild;
3585 pThis->ProcParams.hEvtParent = pThis->hEvtParent;
3586 pThis->ProcParams.uNtDllAddr = pThis->uNtDllAddr;
3587 pThis->ProcParams.enmRequest = kSupR3WinChildReq_Error;
3588 pThis->ProcParams.rc = VINF_SUCCESS;
3589
3590 uintptr_t uChildAddr = uChildExeAddr + ((uintptr_t)&g_ProcParams - (uintptr_t)NtCurrentPeb()->ImageBaseAddress);
3591 SIZE_T cbIgnored;
3592 NTSTATUS rcNt = NtWriteVirtualMemory(pThis->hProcess, (PVOID)uChildAddr, &pThis->ProcParams,
3593 sizeof(pThis->ProcParams), &cbIgnored);
3594 if (!NT_SUCCESS(rcNt))
3595 supR3HardenedWinKillChild(pThis, "supR3HardenedWinSetupChildInit", rcNt,
3596 "NtWriteVirtualMemory(,%p,) failed writing child process parameters: %#x\n", uChildAddr, rcNt);
3597
3598 /*
3599 * Locate the LdrInitializeThunk address in the child as well as pristine
3600 * code bits for it.
3601 */
3602 PSUPHNTLDRCACHEENTRY pLdrEntry;
3603 int rc = supHardNtLdrCacheOpen("ntdll.dll", &pLdrEntry, NULL /*pErrInfo*/);
3604 if (RT_FAILURE(rc))
3605 supR3HardenedWinKillChild(pThis, "supR3HardenedWinSetupChildInit", rc,
3606 "supHardNtLdrCacheOpen failed on NTDLL: %Rrc\n", rc);
3607
3608 uint8_t *pbChildNtDllBits;
3609 rc = supHardNtLdrCacheEntryGetBits(pLdrEntry, &pbChildNtDllBits, pThis->uNtDllAddr, NULL, NULL, NULL /*pErrInfo*/);
3610 if (RT_FAILURE(rc))
3611 supR3HardenedWinKillChild(pThis, "supR3HardenedWinSetupChildInit", rc,
3612 "supHardNtLdrCacheEntryGetBits failed on NTDLL: %Rrc\n", rc);
3613
3614 RTLDRADDR uLdrInitThunk;
3615 rc = RTLdrGetSymbolEx(pLdrEntry->hLdrMod, pbChildNtDllBits, pThis->uNtDllAddr, UINT32_MAX,
3616 "LdrInitializeThunk", &uLdrInitThunk);
3617 if (RT_FAILURE(rc))
3618 supR3HardenedWinKillChild(pThis, "supR3HardenedWinSetupChildInit", rc,
3619 "Error locating LdrInitializeThunk in NTDLL: %Rrc", rc);
3620 PVOID pvLdrInitThunk = (PVOID)(uintptr_t)uLdrInitThunk;
3621 SUP_DPRINTF(("supR3HardenedWinSetupChildInit: uLdrInitThunk=%p\n", (uintptr_t)uLdrInitThunk));
3622
3623 /*
3624 * Calculate the address of our code in the child process.
3625 */
3626 uintptr_t uEarlyProcInitEP = uChildExeAddr + ( (uintptr_t)&supR3HardenedEarlyProcessInitThunk
3627 - (uintptr_t)NtCurrentPeb()->ImageBaseAddress);
3628
3629 /*
3630 * Compose the LdrInitializeThunk replacement bytes.
3631 * Note! The amount of code we replace here must be less or equal to what
3632 * the process verification code ignores.
3633 */
3634 uint8_t abNew[16];
3635 memcpy(abNew, pbChildNtDllBits + ((uintptr_t)uLdrInitThunk - pThis->uNtDllAddr), sizeof(abNew));
3636#ifdef RT_ARCH_AMD64
3637 abNew[0] = 0xff;
3638 abNew[1] = 0x25;
3639 *(uint32_t *)&abNew[2] = 0;
3640 *(uint64_t *)&abNew[6] = uEarlyProcInitEP;
3641#elif defined(RT_ARCH_X86)
3642 abNew[0] = 0xe9;
3643 *(uint32_t *)&abNew[1] = uEarlyProcInitEP - ((uint32_t)uLdrInitThunk + 5);
3644#else
3645# error "Unsupported arch."
3646#endif
3647
3648 /*
3649 * Install the LdrInitializeThunk replacement code in the child process.
3650 */
3651 PVOID pvProt = pvLdrInitThunk;
3652 SIZE_T cbProt = sizeof(abNew);
3653 ULONG fOldProt;
3654 rcNt = NtProtectVirtualMemory(pThis->hProcess, &pvProt, &cbProt, PAGE_EXECUTE_READWRITE, &fOldProt);
3655 if (!NT_SUCCESS(rcNt))
3656 supR3HardenedWinKillChild(pThis, "supR3HardenedWinSetupChildInit", rcNt,
3657 "NtProtectVirtualMemory/LdrInitializeThunk failed: %#x", rcNt);
3658
3659 rcNt = NtWriteVirtualMemory(pThis->hProcess, pvLdrInitThunk, abNew, sizeof(abNew), &cbIgnored);
3660 if (!NT_SUCCESS(rcNt))
3661 supR3HardenedWinKillChild(pThis, "supR3HardenedWinSetupChildInit", rcNt,
3662 "NtWriteVirtualMemory/LdrInitializeThunk failed: %#x", rcNt);
3663
3664 pvProt = pvLdrInitThunk;
3665 cbProt = sizeof(abNew);
3666 rcNt = NtProtectVirtualMemory(pThis->hProcess, &pvProt, &cbProt, fOldProt, &fOldProt);
3667 if (!NT_SUCCESS(rcNt))
3668 supR3HardenedWinKillChild(pThis, "supR3HardenedWinSetupChildInit", rcNt,
3669 "NtProtectVirtualMemory/LdrInitializeThunk[restore] failed: %#x", rcNt);
3670
3671 /* Caller starts child execution. */
3672 SUP_DPRINTF(("supR3HardenedWinSetupChildInit: Start child.\n"));
3673}
3674
3675
3676
3677/**
3678 * This messes with the child PEB before we trigger the initial image events.
3679 *
3680 * @param pThis The child process data structure.
3681 */
3682static void supR3HardNtChildScrewUpPebForInitialImageEvents(PSUPR3HARDNTCHILD pThis)
3683{
3684 /*
3685 * Not sure if any of the cracker software uses the PEB at this point, but
3686 * just in case they do make some of the PEB fields a little less useful.
3687 */
3688 PEB Peb = pThis->Peb;
3689
3690 /* Make ImageBaseAddress useless. */
3691 Peb.ImageBaseAddress = (PVOID)((uintptr_t)Peb.ImageBaseAddress ^ UINT32_C(0x5f139000));
3692#ifdef RT_ARCH_AMD64
3693 Peb.ImageBaseAddress = (PVOID)((uintptr_t)Peb.ImageBaseAddress | UINT64_C(0x0313000000000000));
3694#endif
3695
3696 /*
3697 * Write the PEB.
3698 */
3699 SIZE_T cbActualMem = pThis->cbPeb;
3700 NTSTATUS rcNt = NtWriteVirtualMemory(pThis->hProcess, pThis->BasicInfo.PebBaseAddress, &Peb, pThis->cbPeb, &cbActualMem);
3701 if (!NT_SUCCESS(rcNt))
3702 supR3HardenedWinKillChild(pThis, "supR3HardNtChildScrewUpPebForInitialImageEvents", rcNt,
3703 "NtWriteVirtualMemory/Peb failed: %#x", rcNt);
3704}
3705
3706
3707/**
3708 * Check if the zero terminated NT unicode string is the path to the given
3709 * system32 DLL.
3710 *
3711 * @returns true if it is, false if not.
3712 * @param pUniStr The zero terminated NT unicode string path.
3713 * @param pszName The name of the system32 DLL.
3714 */
3715static bool supR3HardNtIsNamedSystem32Dll(PUNICODE_STRING pUniStr, const char *pszName)
3716{
3717 if (pUniStr->Length > g_System32NtPath.UniStr.Length)
3718 {
3719 if (memcmp(pUniStr->Buffer, g_System32NtPath.UniStr.Buffer, g_System32NtPath.UniStr.Length) == 0)
3720 {
3721 if (pUniStr->Buffer[g_System32NtPath.UniStr.Length / sizeof(WCHAR)] == '\\')
3722 {
3723 if (RTUtf16ICmpAscii(&pUniStr->Buffer[g_System32NtPath.UniStr.Length / sizeof(WCHAR) + 1], pszName) == 0)
3724 return true;
3725 }
3726 }
3727 }
3728
3729 return false;
3730}
3731
3732
3733/**
3734 * Worker for supR3HardNtChildGatherData that locates NTDLL in the child
3735 * process.
3736 *
3737 * @param pThis The child process data structure.
3738 */
3739static void supR3HardNtChildFindNtdll(PSUPR3HARDNTCHILD pThis)
3740{
3741 /*
3742 * Find NTDLL in this process first and take that as a starting point.
3743 */
3744 pThis->uNtDllParentAddr = (uintptr_t)GetModuleHandleW(L"ntdll.dll");
3745 SUPR3HARDENED_ASSERT(pThis->uNtDllParentAddr != 0 && !(pThis->uNtDllParentAddr & PAGE_OFFSET_MASK));
3746 pThis->uNtDllAddr = pThis->uNtDllParentAddr;
3747
3748 /*
3749 * Scan the virtual memory of the child.
3750 */
3751 uintptr_t cbAdvance = 0;
3752 uintptr_t uPtrWhere = 0;
3753 for (uint32_t i = 0; i < 1024; i++)
3754 {
3755 /* Query information. */
3756 SIZE_T cbActual = 0;
3757 MEMORY_BASIC_INFORMATION MemInfo = { 0, 0, 0, 0, 0, 0, 0 };
3758 NTSTATUS rcNt = NtQueryVirtualMemory(pThis->hProcess,
3759 (void const *)uPtrWhere,
3760 MemoryBasicInformation,
3761 &MemInfo,
3762 sizeof(MemInfo),
3763 &cbActual);
3764 if (!NT_SUCCESS(rcNt))
3765 break;
3766
3767 if ( MemInfo.Type == SEC_IMAGE
3768 || MemInfo.Type == SEC_PROTECTED_IMAGE
3769 || MemInfo.Type == (SEC_IMAGE | SEC_PROTECTED_IMAGE))
3770 {
3771 if (MemInfo.BaseAddress == MemInfo.AllocationBase)
3772 {
3773 /* Get the image name. */
3774 union
3775 {
3776 UNICODE_STRING UniStr;
3777 uint8_t abPadding[4096];
3778 } uBuf;
3779 NTSTATUS rcNt = NtQueryVirtualMemory(pThis->hProcess,
3780 MemInfo.BaseAddress,
3781 MemorySectionName,
3782 &uBuf,
3783 sizeof(uBuf) - sizeof(WCHAR),
3784 &cbActual);
3785 if (NT_SUCCESS(rcNt))
3786 {
3787 uBuf.UniStr.Buffer[uBuf.UniStr.Length / sizeof(WCHAR)] = '\0';
3788 if (supR3HardNtIsNamedSystem32Dll(&uBuf.UniStr, "ntdll.dll"))
3789 {
3790 pThis->uNtDllAddr = (uintptr_t)MemInfo.AllocationBase;
3791 SUP_DPRINTF(("supR3HardNtPuChFindNtdll: uNtDllParentAddr=%p uNtDllChildAddr=%p\n",
3792 pThis->uNtDllParentAddr, pThis->uNtDllAddr));
3793 return;
3794 }
3795 }
3796 }
3797 }
3798
3799 /*
3800 * Advance.
3801 */
3802 cbAdvance = MemInfo.RegionSize;
3803 if (uPtrWhere + cbAdvance <= uPtrWhere)
3804 break;
3805 uPtrWhere += MemInfo.RegionSize;
3806 }
3807
3808 supR3HardenedWinKillChild(pThis, "supR3HardNtChildFindNtdll", VERR_MODULE_NOT_FOUND, "ntdll.dll not found in child process.");
3809}
3810
3811
3812/**
3813 * Gather child data.
3814 *
3815 * @param pThis The child process data structure.
3816 */
3817static void supR3HardNtChildGatherData(PSUPR3HARDNTCHILD pThis)
3818{
3819 /*
3820 * Basic info.
3821 */
3822 ULONG cbActual = 0;
3823 NTSTATUS rcNt = NtQueryInformationProcess(pThis->hProcess, ProcessBasicInformation,
3824 &pThis->BasicInfo, sizeof(pThis->BasicInfo), &cbActual);
3825 if (!NT_SUCCESS(rcNt))
3826 supR3HardenedWinKillChild(pThis, "supR3HardNtChildGatherData", rcNt,
3827 "NtQueryInformationProcess/ProcessBasicInformation failed: %#x", rcNt);
3828
3829 /*
3830 * If this is the middle (stub) process, we wish to wait for both child
3831 * and parent. So open the parent process. Not fatal if we cannnot.
3832 */
3833 if (pThis->iWhich > 1)
3834 {
3835 PROCESS_BASIC_INFORMATION SelfInfo;
3836 rcNt = NtQueryInformationProcess(NtCurrentProcess(), ProcessBasicInformation, &SelfInfo, sizeof(SelfInfo), &cbActual);
3837 if (NT_SUCCESS(rcNt))
3838 {
3839 OBJECT_ATTRIBUTES ObjAttr;
3840 InitializeObjectAttributes(&ObjAttr, NULL, 0, NULL /*hRootDir*/, NULL /*pSecDesc*/);
3841
3842 CLIENT_ID ClientId;
3843 ClientId.UniqueProcess = (HANDLE)SelfInfo.InheritedFromUniqueProcessId;
3844 ClientId.UniqueThread = NULL;
3845
3846 rcNt = NtOpenProcess(&pThis->hParent, SYNCHRONIZE | PROCESS_QUERY_INFORMATION, &ObjAttr, &ClientId);
3847#ifdef DEBUG
3848 SUPR3HARDENED_ASSERT_NT_SUCCESS(rcNt);
3849#endif
3850 if (!NT_SUCCESS(rcNt))
3851 {
3852 pThis->hParent = NULL;
3853 SUP_DPRINTF(("supR3HardNtChildGatherData: Failed to open parent process (%#p): %#x\n", ClientId.UniqueProcess, rcNt));
3854 }
3855 }
3856
3857 }
3858
3859 /*
3860 * Process environment block.
3861 */
3862 if (g_uNtVerCombined < SUP_NT_VER_W2K3)
3863 pThis->cbPeb = PEB_SIZE_W51;
3864 else if (g_uNtVerCombined < SUP_NT_VER_VISTA)
3865 pThis->cbPeb = PEB_SIZE_W52;
3866 else if (g_uNtVerCombined < SUP_NT_VER_W70)
3867 pThis->cbPeb = PEB_SIZE_W6;
3868 else if (g_uNtVerCombined < SUP_NT_VER_W80)
3869 pThis->cbPeb = PEB_SIZE_W7;
3870 else if (g_uNtVerCombined < SUP_NT_VER_W81)
3871 pThis->cbPeb = PEB_SIZE_W80;
3872 else
3873 pThis->cbPeb = PEB_SIZE_W81;
3874
3875 SUP_DPRINTF(("supR3HardNtChildGatherData: PebBaseAddress=%p cbPeb=%#x\n",
3876 pThis->BasicInfo.PebBaseAddress, pThis->cbPeb));
3877
3878 SIZE_T cbActualMem;
3879 RT_ZERO(pThis->Peb);
3880 rcNt = NtReadVirtualMemory(pThis->hProcess, pThis->BasicInfo.PebBaseAddress, &pThis->Peb, sizeof(pThis->Peb), &cbActualMem);
3881 if (!NT_SUCCESS(rcNt))
3882 supR3HardenedWinKillChild(pThis, "supR3HardNtChildGatherData", rcNt,
3883 "NtReadVirtualMemory/Peb failed: %#x", rcNt);
3884
3885 /*
3886 * Locate NtDll.
3887 */
3888 supR3HardNtChildFindNtdll(pThis);
3889}
3890
3891
3892/**
3893 * Does the actually respawning.
3894 *
3895 * @returns Never, will call exit or raise fatal error.
3896 * @param iWhich Which respawn we're to check for, 1 being the
3897 * first one, and 2 the second and final.
3898 */
3899static DECL_NO_RETURN(void) supR3HardenedWinDoReSpawn(int iWhich)
3900{
3901 NTSTATUS rcNt;
3902 PPEB pPeb = NtCurrentPeb();
3903 PRTL_USER_PROCESS_PARAMETERS pParentProcParams = pPeb->ProcessParameters;
3904
3905 SUPR3HARDENED_ASSERT(g_cSuplibHardenedWindowsMainCalls == 1);
3906
3907 /*
3908 * Init the child process data structure, creating the child communication
3909 * event sempahores.
3910 */
3911 SUPR3HARDNTCHILD This;
3912 RT_ZERO(This);
3913 This.iWhich = iWhich;
3914
3915 OBJECT_ATTRIBUTES ObjAttrs;
3916 This.hEvtChild = NULL;
3917 InitializeObjectAttributes(&ObjAttrs, NULL /*pName*/, OBJ_INHERIT, NULL /*hRootDir*/, NULL /*pSecDesc*/);
3918 SUPR3HARDENED_ASSERT_NT_SUCCESS(NtCreateEvent(&This.hEvtChild, EVENT_ALL_ACCESS, &ObjAttrs, SynchronizationEvent, FALSE));
3919
3920 This.hEvtParent = NULL;
3921 InitializeObjectAttributes(&ObjAttrs, NULL /*pName*/, OBJ_INHERIT, NULL /*hRootDir*/, NULL /*pSecDesc*/);
3922 SUPR3HARDENED_ASSERT_NT_SUCCESS(NtCreateEvent(&This.hEvtParent, EVENT_ALL_ACCESS, &ObjAttrs, SynchronizationEvent, FALSE));
3923
3924 /*
3925 * Set up security descriptors.
3926 */
3927 SECURITY_ATTRIBUTES ProcessSecAttrs;
3928 MYSECURITYCLEANUP ProcessSecAttrsCleanup;
3929 supR3HardNtChildInitSecAttrs(&ProcessSecAttrs, &ProcessSecAttrsCleanup, true /*fProcess*/);
3930
3931 SECURITY_ATTRIBUTES ThreadSecAttrs;
3932 MYSECURITYCLEANUP ThreadSecAttrsCleanup;
3933 supR3HardNtChildInitSecAttrs(&ThreadSecAttrs, &ThreadSecAttrsCleanup, false /*fProcess*/);
3934
3935#if 1
3936 /*
3937 * Configure the startup info and creation flags.
3938 */
3939 DWORD dwCreationFlags = CREATE_SUSPENDED;
3940
3941 STARTUPINFOEXW SiEx;
3942 suplibHardenedMemSet(&SiEx, 0, sizeof(SiEx));
3943 if (1)
3944 SiEx.StartupInfo.cb = sizeof(SiEx.StartupInfo);
3945 else
3946 {
3947 SiEx.StartupInfo.cb = sizeof(SiEx);
3948 dwCreationFlags |= EXTENDED_STARTUPINFO_PRESENT;
3949 /** @todo experiment with protected process stuff later on. */
3950 }
3951
3952 SiEx.StartupInfo.dwFlags |= pParentProcParams->WindowFlags & STARTF_USESHOWWINDOW;
3953 SiEx.StartupInfo.wShowWindow = (WORD)pParentProcParams->ShowWindowFlags;
3954
3955 SiEx.StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
3956 SiEx.StartupInfo.hStdInput = pParentProcParams->StandardInput;
3957 SiEx.StartupInfo.hStdOutput = pParentProcParams->StandardOutput;
3958 SiEx.StartupInfo.hStdError = pParentProcParams->StandardError;
3959
3960 /*
3961 * Construct the command line and launch the process.
3962 */
3963 PRTUTF16 pwszCmdLine = supR3HardNtChildConstructCmdLine(NULL, iWhich);
3964
3965 supR3HardenedWinEnableThreadCreation();
3966 PROCESS_INFORMATION ProcessInfoW32;
3967 if (!CreateProcessW(g_wszSupLibHardenedExePath,
3968 pwszCmdLine,
3969 &ProcessSecAttrs,
3970 &ThreadSecAttrs,
3971 TRUE /*fInheritHandles*/,
3972 dwCreationFlags,
3973 NULL /*pwszzEnvironment*/,
3974 NULL /*pwszCurDir*/,
3975 &SiEx.StartupInfo,
3976 &ProcessInfoW32))
3977 supR3HardenedFatalMsg("supR3HardenedWinReSpawn", kSupInitOp_Misc, VERR_INVALID_NAME,
3978 "Error relaunching VirtualBox VM process: %u\n"
3979 "Command line: '%ls'",
3980 RtlGetLastWin32Error(), pwszCmdLine);
3981 supR3HardenedWinDisableThreadCreation();
3982
3983 SUP_DPRINTF(("supR3HardenedWinDoReSpawn(%d): New child %x.%x [kernel32].\n",
3984 iWhich, ProcessInfoW32.dwProcessId, ProcessInfoW32.dwThreadId));
3985 This.hProcess = ProcessInfoW32.hProcess;
3986 This.hThread = ProcessInfoW32.hThread;
3987
3988#else
3989
3990 /*
3991 * Construct the process parameters.
3992 */
3993 UNICODE_STRING W32ImageName;
3994 W32ImageName.Buffer = g_wszSupLibHardenedExePath; /* Yes the windows name for the process parameters. */
3995 W32ImageName.Length = (USHORT)RTUtf16Len(g_wszSupLibHardenedExePath) * sizeof(WCHAR);
3996 W32ImageName.MaximumLength = W32ImageName.Length + sizeof(WCHAR);
3997
3998 UNICODE_STRING CmdLine;
3999 supR3HardNtChildConstructCmdLine(&CmdLine, iWhich);
4000
4001 PRTL_USER_PROCESS_PARAMETERS pProcParams = NULL;
4002 SUPR3HARDENED_ASSERT_NT_SUCCESS(RtlCreateProcessParameters(&pProcParams,
4003 &W32ImageName,
4004 NULL /* DllPath - inherit from this process */,
4005 NULL /* CurrentDirectory - inherit from this process */,
4006 &CmdLine,
4007 NULL /* Environment - inherit from this process */,
4008 NULL /* WindowsTitle - none */,
4009 NULL /* DesktopTitle - none. */,
4010 NULL /* ShellInfo - none. */,
4011 NULL /* RuntimeInfo - none (byte array for MSVCRT file info) */)
4012 );
4013
4014 /** @todo this doesn't work. :-( */
4015 pProcParams->ConsoleHandle = pParentProcParams->ConsoleHandle;
4016 pProcParams->ConsoleFlags = pParentProcParams->ConsoleFlags;
4017 pProcParams->StandardInput = pParentProcParams->StandardInput;
4018 pProcParams->StandardOutput = pParentProcParams->StandardOutput;
4019 pProcParams->StandardError = pParentProcParams->StandardError;
4020
4021 RTL_USER_PROCESS_INFORMATION ProcessInfoNt = { sizeof(ProcessInfoNt) };
4022 rcNt = RtlCreateUserProcess(&g_SupLibHardenedExeNtPath.UniStr,
4023 OBJ_INHERIT | OBJ_CASE_INSENSITIVE /*Attributes*/,
4024 pProcParams,
4025 NULL, //&ProcessSecAttrs,
4026 NULL, //&ThreadSecAttrs,
4027 NtCurrentProcess() /* ParentProcess */,
4028 FALSE /*fInheritHandles*/,
4029 NULL /* DebugPort */,
4030 NULL /* ExceptionPort */,
4031 &ProcessInfoNt);
4032 if (!NT_SUCCESS(rcNt))
4033 supR3HardenedFatalMsg("supR3HardenedWinReSpawn", kSupInitOp_Misc, VERR_INVALID_NAME,
4034 "Error relaunching VirtualBox VM process: %#x\n"
4035 "Command line: '%ls'",
4036 rcNt, CmdLine.Buffer);
4037
4038 SUP_DPRINTF(("supR3HardenedWinDoReSpawn(%d): New child %x.%x [ntdll].\n",
4039 iWhich, ProcessInfo.ClientId.UniqueProcess, ProcessInfo.ClientId.UniqueThread));
4040 RtlDestroyProcessParameters(pProcParams);
4041
4042 This.hProcess = ProcessInfoNt.ProcessHandle;
4043 This.hThread = ProcessInfoNt.ThreadHandle;
4044#endif
4045
4046#ifndef VBOX_WITHOUT_DEBUGGER_CHECKS
4047 /*
4048 * Apply anti debugger notification trick to the thread. (Also done in
4049 * supR3HardenedWinInit.) This may fail with STATUS_ACCESS_DENIED and
4050 * maybe other errors. (Unfortunately, recent (SEP 12.1) of symantec's
4051 * sysplant.sys driver will cause process deadlocks and a shutdown/reboot
4052 * denial of service problem if we hide the initial thread, so we postpone
4053 * this action if we've detected SEP.)
4054 */
4055 if (!(g_fSupAdversaries & (SUPHARDNT_ADVERSARY_SYMANTEC_SYSPLANT | SUPHARDNT_ADVERSARY_SYMANTEC_N360)))
4056 {
4057 rcNt = NtSetInformationThread(This.hThread, ThreadHideFromDebugger, NULL, 0);
4058 if (!NT_SUCCESS(rcNt))
4059 SUP_DPRINTF(("supR3HardenedWinReSpawn: NtSetInformationThread/ThreadHideFromDebugger failed: %#x (harmless)\n", rcNt));
4060 }
4061#endif
4062
4063 /*
4064 * Perform very early child initialization.
4065 */
4066 supR3HardNtChildGatherData(&This);
4067 supR3HardNtChildScrewUpPebForInitialImageEvents(&This);
4068 supR3HardNtChildSetUpChildInit(&This);
4069
4070 ULONG cSuspendCount = 0;
4071 rcNt = NtResumeThread(This.hThread, &cSuspendCount);
4072 if (!NT_SUCCESS(rcNt))
4073 supR3HardenedWinKillChild(&This, "supR3HardenedWinDoReSpawn", rcNt, "NtResumeThread failed: %#x", rcNt);
4074
4075 /*
4076 * Santizie the pre-NTDLL child when it's ready.
4077 *
4078 * AV software and other things injecting themselves into the embryonic
4079 * and budding process to intercept API calls and what not. Unfortunately
4080 * this is also the behavior of viruses, malware and other unfriendly
4081 * software, so we won't stand for it. AV software can scan our image
4082 * as they are loaded via kernel hooks, that's sufficient. No need for
4083 * patching half of NTDLL or messing with the import table of the
4084 * process executable.
4085 */
4086 supR3HardNtChildWaitFor(&This, kSupR3WinChildReq_PurifyChildAndCloseHandles, 2000 /*ms*/, "PurifyChildAndCloseHandles");
4087 supR3HardNtChildPurify(&This);
4088 supR3HardNtChildSanitizePeb(&This);
4089
4090 /*
4091 * Close the unrestricted access handles. Since we need to wait on the
4092 * child process, we'll reopen the process with limited access before doing
4093 * away with the process handle returned by CreateProcess.
4094 */
4095 supR3HardNtChildCloseFullAccessHandles(&This);
4096
4097 /*
4098 * Signal the child that we've closed the unrestricted handles and it can
4099 * safely try open the driver.
4100 */
4101 rcNt = NtSetEvent(This.hEvtChild, NULL);
4102 if (!NT_SUCCESS(rcNt))
4103 supR3HardenedWinKillChild(&This, "supR3HardenedWinReSpawn", VERR_INVALID_NAME,
4104 "NtSetEvent failed on child process handle: %#x\n", rcNt);
4105
4106 /*
4107 * Ditch the loader cache so we don't sit on too much memory while waiting.
4108 */
4109 supR3HardenedWinFlushLoaderCache();
4110 supR3HardenedWinCompactHeaps();
4111
4112 /*
4113 * Enable thread creation at this point so Ctrl-C and Ctrl-Break can be processed.
4114 */
4115 supR3HardenedWinEnableThreadCreation();
4116
4117 /*
4118 * Wait for the child to get to suplibHardenedWindowsMain so we can close the handles.
4119 */
4120 supR3HardNtChildWaitFor(&This, kSupR3WinChildReq_CloseEvents, 60000 /*ms*/, "CloseEvents");
4121
4122 NtClose(This.hEvtChild);
4123 NtClose(This.hEvtParent);
4124 This.hEvtChild = NULL;
4125 This.hEvtParent = NULL;
4126
4127 /*
4128 * Wait for the process to terminate.
4129 */
4130 supR3HardNtChildWaitFor(&This, kSupR3WinChildReq_End, RT_INDEFINITE_WAIT, "the end");
4131 supR3HardenedFatal("supR3HardenedWinDoReSpawn: supR3HardNtChildWaitFor unexpectedly returned!\n");
4132 /* not reached*/
4133}
4134
4135
4136/**
4137 * Logs the content of the given object directory.
4138 *
4139 * @returns true if it exists, false if not.
4140 * @param pszDir The path of the directory to log (ASCII).
4141 */
4142static void supR3HardenedWinLogObjDir(const char *pszDir)
4143{
4144 /*
4145 * Open the driver object directory.
4146 */
4147 RTUTF16 wszDir[128];
4148 int rc = RTUtf16CopyAscii(wszDir, RT_ELEMENTS(wszDir), pszDir);
4149 if (RT_FAILURE(rc))
4150 {
4151 SUP_DPRINTF(("supR3HardenedWinLogObjDir: RTUtf16CopyAscii -> %Rrc on '%s'\n", rc, pszDir));
4152 return;
4153 }
4154
4155 UNICODE_STRING NtDirName;
4156 NtDirName.Buffer = (WCHAR *)wszDir;
4157 NtDirName.Length = (USHORT)(RTUtf16Len(wszDir) * sizeof(WCHAR));
4158 NtDirName.MaximumLength = NtDirName.Length + sizeof(WCHAR);
4159
4160 OBJECT_ATTRIBUTES ObjAttr;
4161 InitializeObjectAttributes(&ObjAttr, &NtDirName, OBJ_CASE_INSENSITIVE, NULL /*hRootDir*/, NULL /*pSecDesc*/);
4162
4163 HANDLE hDir;
4164 NTSTATUS rcNt = NtOpenDirectoryObject(&hDir, DIRECTORY_QUERY | FILE_LIST_DIRECTORY, &ObjAttr);
4165 SUP_DPRINTF(("supR3HardenedWinLogObjDir: %ls => %#x\n", wszDir, rcNt));
4166 if (!NT_SUCCESS(rcNt))
4167 return;
4168
4169 /*
4170 * Enumerate it, looking for the driver.
4171 */
4172 ULONG uObjDirCtx = 0;
4173 for (;;)
4174 {
4175 uint32_t abBuffer[_64K + _1K];
4176 ULONG cbActual;
4177 rcNt = NtQueryDirectoryObject(hDir,
4178 abBuffer,
4179 sizeof(abBuffer) - 4, /* minus four for string terminator space. */
4180 FALSE /*ReturnSingleEntry */,
4181 FALSE /*RestartScan*/,
4182 &uObjDirCtx,
4183 &cbActual);
4184 if (!NT_SUCCESS(rcNt) || cbActual < sizeof(OBJECT_DIRECTORY_INFORMATION))
4185 {
4186 SUP_DPRINTF(("supR3HardenedWinLogObjDir: NtQueryDirectoryObject => rcNt=%#x cbActual=%#x\n", rcNt, cbActual));
4187 break;
4188 }
4189
4190 POBJECT_DIRECTORY_INFORMATION pObjDir = (POBJECT_DIRECTORY_INFORMATION)abBuffer;
4191 while (pObjDir->Name.Length != 0)
4192 {
4193 SUP_DPRINTF((" %.*ls %.*ls\n",
4194 pObjDir->TypeName.Length / sizeof(WCHAR), pObjDir->TypeName.Buffer,
4195 pObjDir->Name.Length / sizeof(WCHAR), pObjDir->Name.Buffer));
4196
4197 /* Next directory entry. */
4198 pObjDir++;
4199 }
4200 }
4201
4202 /*
4203 * Clean up and return.
4204 */
4205 NtClose(hDir);
4206}
4207
4208
4209/**
4210 * Tries to open VBoxDrvErrorInfo and read extra error info from it.
4211 *
4212 * @returns pszErrorInfo.
4213 * @param pszErrorInfo The destination buffer. Will always be
4214 * terminated.
4215 * @param cbErrorInfo The size of the destination buffer.
4216 * @param pszPrefix What to prefix the error info with, if we got
4217 * anything.
4218 */
4219DECLHIDDEN(char *) supR3HardenedWinReadErrorInfoDevice(char *pszErrorInfo, size_t cbErrorInfo, const char *pszPrefix)
4220{
4221 RT_BZERO(pszErrorInfo, cbErrorInfo);
4222
4223 /*
4224 * Try open the device.
4225 */
4226 HANDLE hFile = RTNT_INVALID_HANDLE_VALUE;
4227 IO_STATUS_BLOCK Ios = RTNT_IO_STATUS_BLOCK_INITIALIZER;
4228 UNICODE_STRING NtName = RTNT_CONSTANT_UNISTR(SUPDRV_NT_DEVICE_NAME_ERROR_INFO);
4229 OBJECT_ATTRIBUTES ObjAttr;
4230 InitializeObjectAttributes(&ObjAttr, &NtName, OBJ_CASE_INSENSITIVE, NULL /*hRootDir*/, NULL /*pSecDesc*/);
4231 NTSTATUS rcNt = NtCreateFile(&hFile,
4232 GENERIC_READ, /* No SYNCHRONIZE. */
4233 &ObjAttr,
4234 &Ios,
4235 NULL /* Allocation Size*/,
4236 FILE_ATTRIBUTE_NORMAL,
4237 FILE_SHARE_READ | FILE_SHARE_WRITE,
4238 FILE_OPEN,
4239 FILE_NON_DIRECTORY_FILE, /* No FILE_SYNCHRONOUS_IO_NONALERT. */
4240 NULL /*EaBuffer*/,
4241 0 /*EaLength*/);
4242 if (NT_SUCCESS(rcNt))
4243 rcNt = Ios.Status;
4244 if (NT_SUCCESS(rcNt))
4245 {
4246 /*
4247 * Try read error info.
4248 */
4249 size_t cchPrefix = strlen(pszPrefix);
4250 if (cchPrefix + 3 < cbErrorInfo)
4251 {
4252 LARGE_INTEGER offRead;
4253 offRead.QuadPart = 0;
4254 rcNt = NtReadFile(hFile, NULL /*hEvent*/, NULL /*ApcRoutine*/, NULL /*ApcContext*/, &Ios,
4255 &pszErrorInfo[cchPrefix], (ULONG)(cbErrorInfo - cchPrefix - 1), &offRead, NULL);
4256 if (NT_SUCCESS(rcNt) && NT_SUCCESS(Ios.Status) && Ios.Information > 0)
4257 {
4258 memcpy(pszErrorInfo, pszPrefix, cchPrefix);
4259 pszErrorInfo[RT_MIN(cbErrorInfo - 1, cchPrefix + Ios.Information)] = '\0';
4260 SUP_DPRINTF(("supR3HardenedWinReadErrorInfoDevice: '%s'", &pszErrorInfo[cchPrefix]));
4261 }
4262 else
4263 {
4264 *pszErrorInfo = '\0';
4265 if (rcNt != STATUS_END_OF_FILE || Ios.Status != STATUS_END_OF_FILE)
4266 SUP_DPRINTF(("supR3HardenedWinReadErrorInfoDevice: NtReadFile -> %#x / %#x / %p\n",
4267 rcNt, Ios.Status, Ios.Information));
4268 }
4269 }
4270 else
4271 RTStrCopy(pszErrorInfo, cbErrorInfo, "error info buffer too small");
4272 NtClose(hFile);
4273 }
4274 else
4275 SUP_DPRINTF(("supR3HardenedWinReadErrorInfoDevice: NtCreateFile -> %#x\n", rcNt));
4276
4277 return pszErrorInfo;
4278}
4279
4280
4281
4282/**
4283 * Checks if the driver exists.
4284 *
4285 * This checks whether the driver is present in the /Driver object directory.
4286 * Drivers being initialized or terminated will have an object there
4287 * before/after their devices nodes are created/deleted.
4288 *
4289 * @returns true if it exists, false if not.
4290 * @param pszDriver The driver name.
4291 */
4292static bool supR3HardenedWinDriverExists(const char *pszDriver)
4293{
4294 /*
4295 * Open the driver object directory.
4296 */
4297 UNICODE_STRING NtDirName = RTNT_CONSTANT_UNISTR(L"\\Driver");
4298
4299 OBJECT_ATTRIBUTES ObjAttr;
4300 InitializeObjectAttributes(&ObjAttr, &NtDirName, OBJ_CASE_INSENSITIVE, NULL /*hRootDir*/, NULL /*pSecDesc*/);
4301
4302 HANDLE hDir;
4303 NTSTATUS rcNt = NtOpenDirectoryObject(&hDir, DIRECTORY_QUERY | FILE_LIST_DIRECTORY, &ObjAttr);
4304#ifdef VBOX_STRICT
4305 SUPR3HARDENED_ASSERT_NT_SUCCESS(rcNt);
4306#endif
4307 if (!NT_SUCCESS(rcNt))
4308 return true;
4309
4310 /*
4311 * Enumerate it, looking for the driver.
4312 */
4313 bool fFound = true;
4314 ULONG uObjDirCtx = 0;
4315 do
4316 {
4317 uint32_t abBuffer[_64K + _1K];
4318 ULONG cbActual;
4319 rcNt = NtQueryDirectoryObject(hDir,
4320 abBuffer,
4321 sizeof(abBuffer) - 4, /* minus four for string terminator space. */
4322 FALSE /*ReturnSingleEntry */,
4323 FALSE /*RestartScan*/,
4324 &uObjDirCtx,
4325 &cbActual);
4326 if (!NT_SUCCESS(rcNt) || cbActual < sizeof(OBJECT_DIRECTORY_INFORMATION))
4327 break;
4328
4329 POBJECT_DIRECTORY_INFORMATION pObjDir = (POBJECT_DIRECTORY_INFORMATION)abBuffer;
4330 while (pObjDir->Name.Length != 0)
4331 {
4332 WCHAR wcSaved = pObjDir->Name.Buffer[pObjDir->Name.Length / sizeof(WCHAR)];
4333 pObjDir->Name.Buffer[pObjDir->Name.Length / sizeof(WCHAR)] = '\0';
4334 if ( pObjDir->Name.Length > 1
4335 && RTUtf16ICmpAscii(pObjDir->Name.Buffer, pszDriver) == 0)
4336 {
4337 fFound = true;
4338 break;
4339 }
4340 pObjDir->Name.Buffer[pObjDir->Name.Length / sizeof(WCHAR)] = wcSaved;
4341
4342 /* Next directory entry. */
4343 pObjDir++;
4344 }
4345 } while (!fFound);
4346
4347 /*
4348 * Clean up and return.
4349 */
4350 NtClose(hDir);
4351
4352 return fFound;
4353}
4354
4355
4356/**
4357 * Open the stub device before the 2nd respawn.
4358 */
4359static void supR3HardenedWinOpenStubDevice(void)
4360{
4361 if (g_fSupStubOpened)
4362 return;
4363
4364 /*
4365 * Retry if we think driver might still be initializing (STATUS_NO_SUCH_DEVICE + \Drivers\VBoxDrv).
4366 */
4367 static const WCHAR s_wszName[] = SUPDRV_NT_DEVICE_NAME_STUB;
4368 uint64_t const uMsTsStart = supR3HardenedWinGetMilliTS();
4369 NTSTATUS rcNt;
4370 uint32_t iTry;
4371
4372 for (iTry = 0;; iTry++)
4373 {
4374 HANDLE hFile = RTNT_INVALID_HANDLE_VALUE;
4375 IO_STATUS_BLOCK Ios = RTNT_IO_STATUS_BLOCK_INITIALIZER;
4376
4377 UNICODE_STRING NtName;
4378 NtName.Buffer = (PWSTR)s_wszName;
4379 NtName.Length = sizeof(s_wszName) - sizeof(WCHAR);
4380 NtName.MaximumLength = sizeof(s_wszName);
4381
4382 OBJECT_ATTRIBUTES ObjAttr;
4383 InitializeObjectAttributes(&ObjAttr, &NtName, OBJ_CASE_INSENSITIVE, NULL /*hRootDir*/, NULL /*pSecDesc*/);
4384
4385 rcNt = NtCreateFile(&hFile,
4386 GENERIC_READ | GENERIC_WRITE, /* No SYNCHRONIZE. */
4387 &ObjAttr,
4388 &Ios,
4389 NULL /* Allocation Size*/,
4390 FILE_ATTRIBUTE_NORMAL,
4391 FILE_SHARE_READ | FILE_SHARE_WRITE,
4392 FILE_OPEN,
4393 FILE_NON_DIRECTORY_FILE, /* No FILE_SYNCHRONOUS_IO_NONALERT. */
4394 NULL /*EaBuffer*/,
4395 0 /*EaLength*/);
4396 if (NT_SUCCESS(rcNt))
4397 rcNt = Ios.Status;
4398
4399 /* The STATUS_NO_SUCH_DEVICE might be returned if the device is not
4400 completely initialized. Delay a little bit and try again. */
4401 if (rcNt != STATUS_NO_SUCH_DEVICE)
4402 break;
4403 if (iTry > 0 && supR3HardenedWinGetMilliTS() - uMsTsStart > 5000) /* 5 sec, at least two tries */
4404 break;
4405 if (!supR3HardenedWinDriverExists("VBoxDrv"))
4406 {
4407 /** @todo Consider starting the VBoxdrv.sys service. Requires 2nd process
4408 * though, rather complicated actually as CreateProcess causes all
4409 * kind of things to happen to this process which would make it hard to
4410 * pass the process verification tests... :-/ */
4411 break;
4412 }
4413
4414 LARGE_INTEGER Time;
4415 if (iTry < 8)
4416 Time.QuadPart = -1000000 / 100; /* 1ms in 100ns units, relative time. */
4417 else
4418 Time.QuadPart = -32000000 / 100; /* 32ms in 100ns units, relative time. */
4419 NtDelayExecution(TRUE, &Time);
4420 }
4421
4422 if (NT_SUCCESS(rcNt))
4423 g_fSupStubOpened = true;
4424 else
4425 {
4426 /*
4427 * Report trouble (fatal). For some errors codes we try gather some
4428 * extra information that goes into VBoxStartup.log so that we stand a
4429 * better chance resolving the issue.
4430 */
4431 char szErrorInfo[16384];
4432 int rc = VERR_OPEN_FAILED;
4433 if (SUP_NT_STATUS_IS_VBOX(rcNt)) /* See VBoxDrvNtErr2NtStatus. */
4434 {
4435 rc = SUP_NT_STATUS_TO_VBOX(rcNt);
4436
4437 /*
4438 * \Windows\ApiPort open trouble. So far only
4439 * STATUS_OBJECT_TYPE_MISMATCH has been observed.
4440 */
4441 if (rc == VERR_SUPDRV_APIPORT_OPEN_ERROR)
4442 {
4443 SUP_DPRINTF(("Error opening VBoxDrvStub: VERR_SUPDRV_APIPORT_OPEN_ERROR\n"));
4444
4445 uint32_t uSessionId = NtCurrentPeb()->SessionId;
4446 SUP_DPRINTF((" SessionID=%#x\n", uSessionId));
4447 char szDir[64];
4448 if (uSessionId == 0)
4449 RTStrCopy(szDir, sizeof(szDir), "\\Windows");
4450 else
4451 {
4452 RTStrPrintf(szDir, sizeof(szDir), "\\Sessions\\%u\\Windows", uSessionId);
4453 supR3HardenedWinLogObjDir(szDir);
4454 }
4455 supR3HardenedWinLogObjDir("\\Windows");
4456 supR3HardenedWinLogObjDir("\\Sessions");
4457
4458 supR3HardenedFatalMsg("supR3HardenedWinReSpawn", kSupInitOp_Misc, rc,
4459 "NtCreateFile(%ls) failed: VERR_SUPDRV_APIPORT_OPEN_ERROR\n"
4460 "\n"
4461 "Error getting %s\\ApiPort in the driver from vboxdrv.\n"
4462 "\n"
4463 "Could be due to security software is redirecting access to it, so please include full "
4464 "details of such software in a bug report. VBoxStartup.log may contain details important "
4465 "to resolving the issue.%s"
4466 , s_wszName, szDir,
4467 supR3HardenedWinReadErrorInfoDevice(szErrorInfo, sizeof(szErrorInfo),
4468 "\n\nVBoxDrvStub error: "));
4469 }
4470
4471 /*
4472 * Generic VBox failure message.
4473 */
4474 supR3HardenedFatalMsg("supR3HardenedWinReSpawn", kSupInitOp_Driver, rc,
4475 "NtCreateFile(%ls) failed: %Rrc (rcNt=%#x)%s", s_wszName, rc, rcNt,
4476 supR3HardenedWinReadErrorInfoDevice(szErrorInfo, sizeof(szErrorInfo),
4477 "\nVBoxDrvStub error: "));
4478 }
4479 else
4480 {
4481 const char *pszDefine;
4482 switch (rcNt)
4483 {
4484 case STATUS_NO_SUCH_DEVICE: pszDefine = " STATUS_NO_SUCH_DEVICE"; break;
4485 case STATUS_OBJECT_NAME_NOT_FOUND: pszDefine = " STATUS_OBJECT_NAME_NOT_FOUND"; break;
4486 case STATUS_ACCESS_DENIED: pszDefine = " STATUS_ACCESS_DENIED"; break;
4487 case STATUS_TRUST_FAILURE: pszDefine = " STATUS_TRUST_FAILURE"; break;
4488 default: pszDefine = ""; break;
4489 }
4490
4491 /*
4492 * Problems opening the device is generally due to driver load/
4493 * unload issues. Check whether the driver is loaded and make
4494 * suggestions accordingly.
4495 */
4496/** @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. */
4497 if ( rcNt == STATUS_NO_SUCH_DEVICE
4498 || rcNt == STATUS_OBJECT_NAME_NOT_FOUND)
4499 {
4500 SUP_DPRINTF(("Error opening VBoxDrvStub: %s\n", pszDefine));
4501 if (supR3HardenedWinDriverExists("VBoxDrv"))
4502 supR3HardenedFatalMsg("supR3HardenedWinReSpawn", kSupInitOp_Driver, VERR_OPEN_FAILED,
4503 "NtCreateFile(%ls) failed: %#x%s (%u retries)\n"
4504 "\n"
4505 "Driver is probably stuck stopping/starting. Try 'sc.exe query vboxdrv' to get more "
4506 "information about its state. Rebooting may actually help.%s"
4507 , s_wszName, rcNt, pszDefine, iTry,
4508 supR3HardenedWinReadErrorInfoDevice(szErrorInfo, sizeof(szErrorInfo),
4509 "\nVBoxDrvStub error: "));
4510 else
4511 supR3HardenedFatalMsg("supR3HardenedWinReSpawn", kSupInitOp_Driver, VERR_OPEN_FAILED,
4512 "NtCreateFile(%ls) failed: %#x%s (%u retries)\n"
4513 "\n"
4514 "Driver is does not appear to be loaded. Try 'sc.exe start vboxdrv', reinstall "
4515 "VirtualBox or reboot.%s"
4516 , s_wszName, rcNt, pszDefine, iTry,
4517 supR3HardenedWinReadErrorInfoDevice(szErrorInfo, sizeof(szErrorInfo),
4518 "\nVBoxDrvStub error: "));
4519 }
4520
4521 /* Generic NT failure message. */
4522 supR3HardenedFatalMsg("supR3HardenedWinReSpawn", kSupInitOp_Driver, VERR_OPEN_FAILED,
4523 "NtCreateFile(%ls) failed: %#x%s (%u retries)%s",
4524 s_wszName, rcNt, pszDefine, iTry,
4525 supR3HardenedWinReadErrorInfoDevice(szErrorInfo, sizeof(szErrorInfo),
4526 "\nVBoxDrvStub error: "));
4527 }
4528 }
4529}
4530
4531
4532/**
4533 * Called by the main code if supR3HardenedWinIsReSpawnNeeded returns @c true.
4534 *
4535 * @returns Program exit code.
4536 */
4537DECLHIDDEN(int) supR3HardenedWinReSpawn(int iWhich)
4538{
4539 /*
4540 * Before the 2nd respawn we set up a child protection deal with the
4541 * support driver via /Devices/VBoxDrvStub. (We tried to do this
4542 * during the early init, but in case we had trouble accessing vboxdrv we
4543 * retry it here where we have kernel32.dll and others to pull in for
4544 * better diagnostics.)
4545 */
4546 if (iWhich == 2)
4547 supR3HardenedWinOpenStubDevice();
4548
4549 /*
4550 * Make sure we're alone in the stub process before creating the VM process
4551 * and that there aren't any debuggers attached.
4552 */
4553 if (iWhich == 2)
4554 {
4555 int rc = supHardNtVpDebugger(NtCurrentProcess(), RTErrInfoInitStatic(&g_ErrInfoStatic));
4556 if (RT_SUCCESS(rc))
4557 rc = supHardNtVpThread(NtCurrentProcess(), NtCurrentThread(), RTErrInfoInitStatic(&g_ErrInfoStatic));
4558 if (RT_FAILURE(rc))
4559 supR3HardenedFatalMsg("supR3HardenedWinReSpawn", kSupInitOp_Integrity, rc, "%s", g_ErrInfoStatic.szMsg);
4560 }
4561
4562
4563 /*
4564 * Respawn the process with kernel protection for the new process.
4565 */
4566 supR3HardenedWinDoReSpawn(iWhich);
4567 /* not reached! */
4568}
4569
4570
4571/**
4572 * Checks if re-spawning is required, replacing the respawn argument if not.
4573 *
4574 * @returns true if required, false if not. In the latter case, the first
4575 * argument in the vector is replaced.
4576 * @param iWhich Which respawn we're to check for, 1 being the
4577 * first one, and 2 the second and final.
4578 * @param cArgs The number of arguments.
4579 * @param papszArgs Pointer to the argument vector.
4580 */
4581DECLHIDDEN(bool) supR3HardenedWinIsReSpawnNeeded(int iWhich, int cArgs, char **papszArgs)
4582{
4583 SUPR3HARDENED_ASSERT(g_cSuplibHardenedWindowsMainCalls == 1);
4584 SUPR3HARDENED_ASSERT(iWhich == 1 || iWhich == 2);
4585
4586 if (cArgs < 1)
4587 return true;
4588
4589 if (suplibHardenedStrCmp(papszArgs[0], SUPR3_RESPAWN_1_ARG0) == 0)
4590 {
4591 if (iWhich > 1)
4592 return true;
4593 }
4594 else if (suplibHardenedStrCmp(papszArgs[0], SUPR3_RESPAWN_2_ARG0) == 0)
4595 {
4596 if (iWhich < 2)
4597 return false;
4598 }
4599 else
4600 return true;
4601
4602 /* Replace the argument. */
4603 papszArgs[0] = g_szSupLibHardenedExePath;
4604 return false;
4605}
4606
4607
4608/**
4609 * Initializes the windows verficiation bits and other things we're better off
4610 * doing after main() has passed on it's data.
4611 *
4612 * @param fFlags The main flags.
4613 * @param fAvastKludge Whether to apply the avast kludge.
4614 */
4615DECLHIDDEN(void) supR3HardenedWinInit(uint32_t fFlags, bool fAvastKludge)
4616{
4617 NTSTATUS rcNt;
4618
4619#ifndef VBOX_WITHOUT_DEBUGGER_CHECKS
4620 /*
4621 * Install a anti debugging hack before we continue. This prevents most
4622 * notifications from ending up in the debugger. (Also applied to the
4623 * child process when respawning.)
4624 */
4625 rcNt = NtSetInformationThread(NtCurrentThread(), ThreadHideFromDebugger, NULL, 0);
4626 if (!NT_SUCCESS(rcNt))
4627 supR3HardenedFatalMsg("supR3HardenedWinInit", kSupInitOp_Misc, VERR_GENERAL_FAILURE,
4628 "NtSetInformationThread/ThreadHideFromDebugger failed: %#x\n", rcNt);
4629#endif
4630
4631 /*
4632 * Init the verifier.
4633 */
4634 RTErrInfoInitStatic(&g_ErrInfoStatic);
4635 int rc = supHardenedWinInitImageVerifier(&g_ErrInfoStatic.Core);
4636 if (RT_FAILURE(rc))
4637 supR3HardenedFatalMsg("supR3HardenedWinInit", kSupInitOp_Misc, rc,
4638 "supHardenedWinInitImageVerifier failed: %s", g_ErrInfoStatic.szMsg);
4639
4640 /*
4641 * Get the windows system directory from the KnownDlls dir.
4642 */
4643 HANDLE hSymlink = INVALID_HANDLE_VALUE;
4644 UNICODE_STRING UniStr = RTNT_CONSTANT_UNISTR(L"\\KnownDlls\\KnownDllPath");
4645 OBJECT_ATTRIBUTES ObjAttrs;
4646 InitializeObjectAttributes(&ObjAttrs, &UniStr, OBJ_CASE_INSENSITIVE, NULL /*hRootDir*/, NULL /*pSecDesc*/);
4647 rcNt = NtOpenSymbolicLinkObject(&hSymlink, SYMBOLIC_LINK_QUERY, &ObjAttrs);
4648 if (!NT_SUCCESS(rcNt))
4649 supR3HardenedFatalMsg("supR3HardenedWinInit", kSupInitOp_Misc, rcNt, "Error opening '%ls': %#x", UniStr.Buffer, rcNt);
4650
4651 g_System32WinPath.UniStr.Buffer = g_System32WinPath.awcBuffer;
4652 g_System32WinPath.UniStr.Length = 0;
4653 g_System32WinPath.UniStr.MaximumLength = sizeof(g_System32WinPath.awcBuffer) - sizeof(RTUTF16);
4654 rcNt = NtQuerySymbolicLinkObject(hSymlink, &g_System32WinPath.UniStr, NULL);
4655 if (!NT_SUCCESS(rcNt))
4656 supR3HardenedFatalMsg("supR3HardenedWinInit", kSupInitOp_Misc, rcNt, "Error querying '%ls': %#x", UniStr.Buffer, rcNt);
4657 g_System32WinPath.UniStr.Buffer[g_System32WinPath.UniStr.Length / sizeof(RTUTF16)] = '\0';
4658
4659 SUP_DPRINTF(("KnownDllPath: %ls\n", g_System32WinPath.UniStr.Buffer));
4660 NtClose(hSymlink);
4661
4662 if (!(fFlags & SUPSECMAIN_FLAGS_DONT_OPEN_DEV))
4663 {
4664 if (fAvastKludge)
4665 {
4666 /*
4667 * Do a self purification to cure avast's weird NtOpenFile write-thru
4668 * change in GetBinaryTypeW change in kernel32. Unfortunately, avast
4669 * uses a system thread to perform the process modifications, which
4670 * means it's hard to make sure it had the chance to make them...
4671 *
4672 * We have to resort to kludge doing yield and sleep fudging for a
4673 * number of milliseconds and schedulings before we can hope that avast
4674 * and similar products have done what they need to do. If we do any
4675 * fixes, we wait for a while again and redo it until we're clean.
4676 *
4677 * This is unfortunately kind of fragile.
4678 */
4679 uint32_t cMsFudge = g_fSupAdversaries ? 512 : 128;
4680 uint32_t cFixes;
4681 for (uint32_t iLoop = 0; iLoop < 16; iLoop++)
4682 {
4683 uint32_t cSleeps = 0;
4684 uint64_t uMsTsStart = supR3HardenedWinGetMilliTS();
4685 do
4686 {
4687 NtYieldExecution();
4688 LARGE_INTEGER Time;
4689 Time.QuadPart = -8000000 / 100; /* 8ms in 100ns units, relative time. */
4690 NtDelayExecution(FALSE, &Time);
4691 cSleeps++;
4692 } while ( supR3HardenedWinGetMilliTS() - uMsTsStart <= cMsFudge
4693 || cSleeps < 8);
4694 SUP_DPRINTF(("supR3HardenedWinInit: Startup delay kludge #2/%u: %u ms, %u sleeps\n",
4695 iLoop, supR3HardenedWinGetMilliTS() - uMsTsStart, cSleeps));
4696
4697 cFixes = 0;
4698 rc = supHardenedWinVerifyProcess(NtCurrentProcess(), NtCurrentThread(), SUPHARDNTVPKIND_SELF_PURIFICATION,
4699 0 /*fFlags*/, &cFixes, NULL /*pErrInfo*/);
4700 if (RT_FAILURE(rc) || cFixes == 0)
4701 break;
4702
4703 if (!g_fSupAdversaries)
4704 g_fSupAdversaries |= SUPHARDNT_ADVERSARY_UNKNOWN;
4705 cMsFudge = 512;
4706
4707 /* Log the KiOpPrefetchPatchCount value if available, hoping it might sched some light on spider38's case. */
4708 ULONG cPatchCount = 0;
4709 rcNt = NtQuerySystemInformation(SystemInformation_KiOpPrefetchPatchCount,
4710 &cPatchCount, sizeof(cPatchCount), NULL);
4711 if (NT_SUCCESS(rcNt))
4712 SUP_DPRINTF(("supR3HardenedWinInit: cFixes=%u g_fSupAdversaries=%#x cPatchCount=%#u\n",
4713 cFixes, g_fSupAdversaries, cPatchCount));
4714 else
4715 SUP_DPRINTF(("supR3HardenedWinInit: cFixes=%u g_fSupAdversaries=%#x\n", cFixes, g_fSupAdversaries));
4716 }
4717 }
4718
4719 /*
4720 * Install the hooks.
4721 */
4722 supR3HardenedWinInstallHooks();
4723 }
4724
4725#ifndef VBOX_WITH_VISTA_NO_SP
4726 /*
4727 * Complain about Vista w/o service pack if we're launching a VM.
4728 */
4729 if ( !(fFlags & SUPSECMAIN_FLAGS_DONT_OPEN_DEV)
4730 && g_uNtVerCombined >= SUP_NT_VER_VISTA
4731 && g_uNtVerCombined < SUP_MAKE_NT_VER_COMBINED(6, 0, 6001, 0, 0))
4732 supR3HardenedFatalMsg("supR3HardenedWinInit", kSupInitOp_Misc, VERR_NOT_SUPPORTED,
4733 "Window Vista without any service pack installed is not supported. Please install the latest service pack.");
4734#endif
4735}
4736
4737
4738/**
4739 * Modifies the DLL search path for testcases.
4740 *
4741 * This makes sure the application binary path is in the search path. When
4742 * starting a testcase executable in the testcase/ subdirectory this isn't the
4743 * case by default. So, unless we do something about it we won't be able to
4744 * import VBox DLLs.
4745 *
4746 * @param fFlags The main flags (giving the location).
4747 * @param pszAppBinPath The path to the application binary directory
4748 * (windows style).
4749 */
4750DECLHIDDEN(void) supR3HardenedWinModifyDllSearchPath(uint32_t fFlags, const char *pszAppBinPath)
4751{
4752 /*
4753 * For the testcases to work, we must add the app bin directory to the
4754 * DLL search list before the testcase dll is loaded or it won't be
4755 * able to find the VBox DLLs. This is done _after_ VBoxRT.dll is
4756 * initialized and sets its defaults.
4757 */
4758 switch (fFlags & SUPSECMAIN_FLAGS_LOC_MASK)
4759 {
4760 case SUPSECMAIN_FLAGS_LOC_TESTCASE:
4761 break;
4762 default:
4763 return;
4764 }
4765
4766 /*
4767 * Dynamically resolve the two APIs we need (the latter uses forwarders on w7).
4768 */
4769 HMODULE hModKernel32 = GetModuleHandleW(L"kernel32.dll");
4770
4771 typedef BOOL (WINAPI *PFNSETDLLDIRECTORY)(LPCWSTR);
4772 PFNSETDLLDIRECTORY pfnSetDllDir;
4773 pfnSetDllDir = (PFNSETDLLDIRECTORY)GetProcAddress(hModKernel32, "SetDllDirectoryW");
4774
4775 typedef BOOL (WINAPI *PFNSETDEFAULTDLLDIRECTORIES)(DWORD);
4776 PFNSETDEFAULTDLLDIRECTORIES pfnSetDefDllDirs;
4777 pfnSetDefDllDirs = (PFNSETDEFAULTDLLDIRECTORIES)GetProcAddress(hModKernel32, "SetDefaultDllDirectories");
4778
4779 if (pfnSetDllDir != NULL)
4780 {
4781 /*
4782 * Convert the path to UTF-16 and try set it.
4783 */
4784 PRTUTF16 pwszAppBinPath = NULL;
4785 int rc = RTStrToUtf16(pszAppBinPath, &pwszAppBinPath);
4786 if (RT_SUCCESS(rc))
4787 {
4788 if (pfnSetDllDir(pwszAppBinPath))
4789 {
4790 SUP_DPRINTF(("supR3HardenedWinModifyDllSearchPath: Set dll dir to '%ls'\n", pwszAppBinPath));
4791 g_fSupLibHardenedDllSearchUserDirs = true;
4792
4793 /*
4794 * We set it alright, on W7 and later we also must modify the
4795 * default DLL search order. See @bugref{6861} for details on
4796 * why we don't do this on Vista (also see init-win.cpp in IPRT).
4797 */
4798 if ( pfnSetDefDllDirs
4799 && g_uNtVerCombined >= SUP_NT_VER_W70)
4800 {
4801 if (pfnSetDefDllDirs( LOAD_LIBRARY_SEARCH_APPLICATION_DIR
4802 | LOAD_LIBRARY_SEARCH_SYSTEM32
4803 | LOAD_LIBRARY_SEARCH_USER_DIRS))
4804 SUP_DPRINTF(("supR3HardenedWinModifyDllSearchPath: Successfully modified search dirs.\n"));
4805 else
4806 supR3HardenedFatal("supR3HardenedWinModifyDllSearchPath: SetDllDirectoryW(%ls) failed: %d\n",
4807 pwszAppBinPath, RtlGetLastWin32Error());
4808 }
4809 }
4810 else
4811 supR3HardenedFatal("supR3HardenedWinModifyDllSearchPath: SetDllDirectoryW(%ls) failed: %d\n",
4812 pwszAppBinPath, RtlGetLastWin32Error());
4813 RTUtf16Free(pwszAppBinPath);
4814 }
4815 else
4816 supR3HardenedFatal("supR3HardenedWinModifyDllSearchPath: RTStrToUtf16(%s) failed: %d\n", pszAppBinPath, rc);
4817 }
4818}
4819
4820
4821/**
4822 * Initializes the application binary directory path.
4823 *
4824 * This is called once or twice.
4825 *
4826 * @param fFlags The main flags (giving the location).
4827 */
4828DECLHIDDEN(void) supR3HardenedWinInitAppBin(uint32_t fFlags)
4829{
4830 USHORT cwc = (USHORT)g_offSupLibHardenedExeNtName - 1;
4831 g_SupLibHardenedAppBinNtPath.UniStr.Buffer = g_SupLibHardenedAppBinNtPath.awcBuffer;
4832 memcpy(g_SupLibHardenedAppBinNtPath.UniStr.Buffer, g_SupLibHardenedExeNtPath.UniStr.Buffer, cwc * sizeof(WCHAR));
4833
4834 switch (fFlags & SUPSECMAIN_FLAGS_LOC_MASK)
4835 {
4836 case SUPSECMAIN_FLAGS_LOC_APP_BIN:
4837 break;
4838 case SUPSECMAIN_FLAGS_LOC_TESTCASE:
4839 {
4840 /* Drop one directory level. */
4841 USHORT off = cwc;
4842 WCHAR wc;
4843 while ( off > 1
4844 && (wc = g_SupLibHardenedAppBinNtPath.UniStr.Buffer[off - 1]) != '\0')
4845 if (wc != '\\' && wc != '/')
4846 off--;
4847 else
4848 {
4849 if (g_SupLibHardenedAppBinNtPath.UniStr.Buffer[off - 2] == ':')
4850 cwc = off;
4851 else
4852 cwc = off - 1;
4853 break;
4854 }
4855 break;
4856 }
4857 default:
4858 supR3HardenedFatal("supR3HardenedWinInitAppBin: Unknown program binary location: %#x\n", fFlags);
4859 }
4860
4861 g_SupLibHardenedAppBinNtPath.UniStr.Buffer[cwc] = '\0';
4862 g_SupLibHardenedAppBinNtPath.UniStr.Length = cwc * sizeof(WCHAR);
4863 g_SupLibHardenedAppBinNtPath.UniStr.MaximumLength = sizeof(g_SupLibHardenedAppBinNtPath.awcBuffer);
4864 SUP_DPRINTF(("supR3HardenedWinInitAppBin(%#x): '%ls'\n", fFlags, g_SupLibHardenedAppBinNtPath.UniStr.Buffer));
4865}
4866
4867
4868/**
4869 * Converts the Windows command line string (UTF-16) to an array of UTF-8
4870 * arguments suitable for passing to main().
4871 *
4872 * @returns Pointer to the argument array.
4873 * @param pawcCmdLine The UTF-16 windows command line to parse.
4874 * @param cwcCmdLine The length of the command line.
4875 * @param pcArgs Where to return the number of arguments.
4876 */
4877static char **suplibCommandLineToArgvWStub(PCRTUTF16 pawcCmdLine, size_t cwcCmdLine, int *pcArgs)
4878{
4879 /*
4880 * Convert the command line string to UTF-8.
4881 */
4882 char *pszCmdLine = NULL;
4883 SUPR3HARDENED_ASSERT(RT_SUCCESS(RTUtf16ToUtf8Ex(pawcCmdLine, cwcCmdLine, &pszCmdLine, 0, NULL)));
4884
4885 /*
4886 * Parse the command line, carving argument strings out of it.
4887 */
4888 int cArgs = 0;
4889 int cArgsAllocated = 4;
4890 char **papszArgs = (char **)RTMemAllocZ(sizeof(char *) * cArgsAllocated);
4891 char *pszSrc = pszCmdLine;
4892 for (;;)
4893 {
4894 /* skip leading blanks. */
4895 char ch = *pszSrc;
4896 while (suplibCommandLineIsArgSeparator(ch))
4897 ch = *++pszSrc;
4898 if (!ch)
4899 break;
4900
4901 /* Add argument to the vector. */
4902 if (cArgs + 2 >= cArgsAllocated)
4903 {
4904 cArgsAllocated *= 2;
4905 papszArgs = (char **)RTMemRealloc(papszArgs, sizeof(char *) * cArgsAllocated);
4906 }
4907 papszArgs[cArgs++] = pszSrc;
4908 papszArgs[cArgs] = NULL;
4909
4910 /* Unquote and unescape the string. */
4911 char *pszDst = pszSrc++;
4912 bool fQuoted = false;
4913 do
4914 {
4915 if (ch == '"')
4916 fQuoted = !fQuoted;
4917 else if (ch != '\\' || (*pszSrc != '\\' && *pszSrc != '"'))
4918 *pszDst++ = ch;
4919 else
4920 {
4921 unsigned cSlashes = 0;
4922 while ((ch = *pszSrc++) == '\\')
4923 cSlashes++;
4924 if (ch == '"')
4925 {
4926 while (cSlashes >= 2)
4927 {
4928 cSlashes -= 2;
4929 *pszDst++ = '\\';
4930 }
4931 if (cSlashes)
4932 *pszDst++ = '"';
4933 else
4934 fQuoted = !fQuoted;
4935 }
4936 else
4937 {
4938 pszSrc--;
4939 while (cSlashes-- > 0)
4940 *pszDst++ = '\\';
4941 }
4942 }
4943
4944 ch = *pszSrc++;
4945 } while (ch != '\0' && (fQuoted || !suplibCommandLineIsArgSeparator(ch)));
4946
4947 /* Terminate the argument. */
4948 *pszDst = '\0';
4949 if (!ch)
4950 break;
4951 }
4952
4953 *pcArgs = cArgs;
4954 return papszArgs;
4955}
4956
4957
4958/**
4959 * Worker for supR3HardenedFindVersionRsrcOffset.
4960 *
4961 * @returns RVA the version resource data, UINT32_MAX if not found.
4962 * @param pRootDir The root resource directory. Expects data to
4963 * follow.
4964 * @param cbBuf The amount of data at pRootDir.
4965 * @param offData The offset to the data entry.
4966 * @param pcbData Where to return the size of the data.
4967 */
4968static uint32_t supR3HardenedGetRvaFromRsrcDataEntry(PIMAGE_RESOURCE_DIRECTORY pRootDir, uint32_t cbBuf, uint32_t offData,
4969 uint32_t *pcbData)
4970{
4971 if ( offData <= cbBuf
4972 && offData + sizeof(IMAGE_RESOURCE_DATA_ENTRY) <= cbBuf)
4973 {
4974 PIMAGE_RESOURCE_DATA_ENTRY pRsrcData = (PIMAGE_RESOURCE_DATA_ENTRY)((uintptr_t)pRootDir + offData);
4975 SUP_DPRINTF((" [Raw version resource data: %#x LB %#x, codepage %#x (reserved %#x)]\n",
4976 pRsrcData->OffsetToData, pRsrcData->Size, pRsrcData->CodePage, pRsrcData->Reserved));
4977 if (pRsrcData->Size > 0)
4978 {
4979 *pcbData = pRsrcData->Size;
4980 return pRsrcData->OffsetToData;
4981 }
4982 }
4983 else
4984 SUP_DPRINTF((" Version resource data (%#x) is outside the buffer (%#x)! :-(\n", offData, cbBuf));
4985
4986 *pcbData = 0;
4987 return UINT32_MAX;
4988}
4989
4990
4991/** @def SUP_RSRC_DPRINTF
4992 * Dedicated debug printf for resource directory parsing.
4993 * @sa SUP_DPRINTF
4994 */
4995#if 0 /* more details */
4996# define SUP_RSRC_DPRINTF(a) SUP_DPRINTF(a)
4997#else
4998# define SUP_RSRC_DPRINTF(a) do { } while (0)
4999#endif
5000
5001/**
5002 * Scans the resource directory for a version resource.
5003 *
5004 * @returns RVA of the version resource data, UINT32_MAX if not found.
5005 * @param pRootDir The root resource directory. Expects data to
5006 * follow.
5007 * @param cbBuf The amount of data at pRootDir.
5008 * @param pcbData Where to return the size of the version data.
5009 */
5010static uint32_t supR3HardenedFindVersionRsrcRva(PIMAGE_RESOURCE_DIRECTORY pRootDir, uint32_t cbBuf, uint32_t *pcbData)
5011{
5012 SUP_RSRC_DPRINTF((" ResDir: Char=%#x Time=%#x Ver=%d%d #NamedEntries=%#x #IdEntries=%#x\n",
5013 pRootDir->Characteristics,
5014 pRootDir->TimeDateStamp,
5015 pRootDir->MajorVersion,
5016 pRootDir->MinorVersion,
5017 pRootDir->NumberOfNamedEntries,
5018 pRootDir->NumberOfIdEntries));
5019
5020 PIMAGE_RESOURCE_DIRECTORY_ENTRY paEntries = (PIMAGE_RESOURCE_DIRECTORY_ENTRY)(pRootDir + 1);
5021 unsigned cMaxEntries = (cbBuf - sizeof(IMAGE_RESOURCE_DIRECTORY)) / sizeof(IMAGE_RESOURCE_DIRECTORY_ENTRY);
5022 unsigned cEntries = pRootDir->NumberOfNamedEntries + pRootDir->NumberOfIdEntries;
5023 if (cEntries > cMaxEntries)
5024 cEntries = cMaxEntries;
5025 for (unsigned i = 0; i < cEntries; i++)
5026 {
5027 if (!paEntries[i].NameIsString)
5028 {
5029 if (!paEntries[i].DataIsDirectory)
5030 SUP_RSRC_DPRINTF((" #%u: ID: #%#06x Data: %#010x\n",
5031 i, paEntries[i].Id, paEntries[i].OffsetToData));
5032 else
5033 SUP_RSRC_DPRINTF((" #%u: ID: #%#06x Dir: %#010x\n",
5034 i, paEntries[i].Id, paEntries[i].OffsetToDirectory));
5035 }
5036 else
5037 {
5038 if (!paEntries[i].DataIsDirectory)
5039 SUP_RSRC_DPRINTF((" #%u: Name: #%#06x Data: %#010x\n",
5040 i, paEntries[i].NameOffset, paEntries[i].OffsetToData));
5041 else
5042 SUP_RSRC_DPRINTF((" #%u: Name: #%#06x Dir: %#010x\n",
5043 i, paEntries[i].NameOffset, paEntries[i].OffsetToDirectory));
5044 }
5045
5046 /*
5047 * Look for the version resource type. Skip to the next entry if not found.
5048 */
5049 if (paEntries[i].NameIsString)
5050 continue;
5051 if (paEntries[i].Id != 0x10 /*RT_VERSION*/)
5052 continue;
5053 if (!paEntries[i].DataIsDirectory)
5054 {
5055 SUP_DPRINTF((" #%u: ID: #%#06x Data: %#010x - WEIRD!\n", i, paEntries[i].Id, paEntries[i].OffsetToData));
5056 continue;
5057 }
5058 SUP_RSRC_DPRINTF((" Version resource dir entry #%u: dir offset: %#x (cbBuf=%#x)\n",
5059 i, paEntries[i].OffsetToDirectory, cbBuf));
5060
5061 /*
5062 * Locate the sub-resource directory for it.
5063 */
5064 if (paEntries[i].OffsetToDirectory >= cbBuf)
5065 {
5066 SUP_DPRINTF((" Version resource dir is outside the buffer! :-(\n"));
5067 continue;
5068 }
5069 uint32_t cbMax = cbBuf - paEntries[i].OffsetToDirectory;
5070 if (cbMax < sizeof(IMAGE_RESOURCE_DIRECTORY) + sizeof(IMAGE_RESOURCE_DIRECTORY_ENTRY))
5071 {
5072 SUP_DPRINTF((" Version resource dir entry #0 is outside the buffer! :-(\n"));
5073 continue;
5074 }
5075 PIMAGE_RESOURCE_DIRECTORY pVerDir = (PIMAGE_RESOURCE_DIRECTORY)((uintptr_t)pRootDir + paEntries[i].OffsetToDirectory);
5076 SUP_RSRC_DPRINTF((" VerDir: Char=%#x Time=%#x Ver=%d%d #NamedEntries=%#x #IdEntries=%#x\n",
5077 pVerDir->Characteristics,
5078 pVerDir->TimeDateStamp,
5079 pVerDir->MajorVersion,
5080 pVerDir->MinorVersion,
5081 pVerDir->NumberOfNamedEntries,
5082 pVerDir->NumberOfIdEntries));
5083 PIMAGE_RESOURCE_DIRECTORY_ENTRY paVerEntries = (PIMAGE_RESOURCE_DIRECTORY_ENTRY)(pVerDir + 1);
5084 unsigned cMaxVerEntries = (cbMax - sizeof(IMAGE_RESOURCE_DIRECTORY)) / sizeof(IMAGE_RESOURCE_DIRECTORY_ENTRY);
5085 unsigned cVerEntries = pVerDir->NumberOfNamedEntries + pVerDir->NumberOfIdEntries;
5086 if (cVerEntries > cMaxVerEntries)
5087 cVerEntries = cMaxVerEntries;
5088 for (unsigned iVer = 0; iVer < cVerEntries; iVer++)
5089 {
5090 if (!paVerEntries[iVer].NameIsString)
5091 {
5092 if (!paVerEntries[iVer].DataIsDirectory)
5093 SUP_RSRC_DPRINTF((" #%u: ID: #%#06x Data: %#010x\n",
5094 iVer, paVerEntries[iVer].Id, paVerEntries[iVer].OffsetToData));
5095 else
5096 SUP_RSRC_DPRINTF((" #%u: ID: #%#06x Dir: %#010x\n",
5097 iVer, paVerEntries[iVer].Id, paVerEntries[iVer].OffsetToDirectory));
5098 }
5099 else
5100 {
5101 if (!paVerEntries[iVer].DataIsDirectory)
5102 SUP_RSRC_DPRINTF((" #%u: Name: #%#06x Data: %#010x\n",
5103 iVer, paVerEntries[iVer].NameOffset, paVerEntries[iVer].OffsetToData));
5104 else
5105 SUP_RSRC_DPRINTF((" #%u: Name: #%#06x Dir: %#010x\n",
5106 iVer, paVerEntries[iVer].NameOffset, paVerEntries[iVer].OffsetToDirectory));
5107 }
5108 if (!paVerEntries[iVer].DataIsDirectory)
5109 {
5110 SUP_DPRINTF((" [Version info resource found at %#x! (ID/Name: #%#x)]\n",
5111 paVerEntries[iVer].OffsetToData, paVerEntries[iVer].Name));
5112 return supR3HardenedGetRvaFromRsrcDataEntry(pRootDir, cbBuf, paVerEntries[iVer].OffsetToData, pcbData);
5113 }
5114
5115 /*
5116 * Check out the next directory level.
5117 */
5118 if (paVerEntries[iVer].OffsetToDirectory >= cbBuf)
5119 {
5120 SUP_DPRINTF((" Version resource subdir is outside the buffer! :-(\n"));
5121 continue;
5122 }
5123 cbMax = cbBuf - paVerEntries[iVer].OffsetToDirectory;
5124 if (cbMax < sizeof(IMAGE_RESOURCE_DIRECTORY) + sizeof(IMAGE_RESOURCE_DIRECTORY_ENTRY))
5125 {
5126 SUP_DPRINTF((" Version resource subdir entry #0 is outside the buffer! :-(\n"));
5127 continue;
5128 }
5129 PIMAGE_RESOURCE_DIRECTORY pVerSubDir = (PIMAGE_RESOURCE_DIRECTORY)((uintptr_t)pRootDir + paVerEntries[iVer].OffsetToDirectory);
5130 SUP_RSRC_DPRINTF((" VerSubDir#%u: Char=%#x Time=%#x Ver=%d%d #NamedEntries=%#x #IdEntries=%#x\n",
5131 iVer,
5132 pVerSubDir->Characteristics,
5133 pVerSubDir->TimeDateStamp,
5134 pVerSubDir->MajorVersion,
5135 pVerSubDir->MinorVersion,
5136 pVerSubDir->NumberOfNamedEntries,
5137 pVerSubDir->NumberOfIdEntries));
5138 PIMAGE_RESOURCE_DIRECTORY_ENTRY paVerSubEntries = (PIMAGE_RESOURCE_DIRECTORY_ENTRY)(pVerSubDir + 1);
5139 unsigned cMaxVerSubEntries = (cbMax - sizeof(IMAGE_RESOURCE_DIRECTORY)) / sizeof(IMAGE_RESOURCE_DIRECTORY_ENTRY);
5140 unsigned cVerSubEntries = pVerSubDir->NumberOfNamedEntries + pVerSubDir->NumberOfIdEntries;
5141 if (cVerSubEntries > cMaxVerSubEntries)
5142 cVerSubEntries = cMaxVerSubEntries;
5143 for (unsigned iVerSub = 0; iVerSub < cVerSubEntries; iVerSub++)
5144 {
5145 if (!paVerSubEntries[iVerSub].NameIsString)
5146 {
5147 if (!paVerSubEntries[iVerSub].DataIsDirectory)
5148 SUP_RSRC_DPRINTF((" #%u: ID: #%#06x Data: %#010x\n",
5149 iVerSub, paVerSubEntries[iVerSub].Id, paVerSubEntries[iVerSub].OffsetToData));
5150 else
5151 SUP_RSRC_DPRINTF((" #%u: ID: #%#06x Dir: %#010x\n",
5152 iVerSub, paVerSubEntries[iVerSub].Id, paVerSubEntries[iVerSub].OffsetToDirectory));
5153 }
5154 else
5155 {
5156 if (!paVerSubEntries[iVerSub].DataIsDirectory)
5157 SUP_RSRC_DPRINTF((" #%u: Name: #%#06x Data: %#010x\n",
5158 iVerSub, paVerSubEntries[iVerSub].NameOffset, paVerSubEntries[iVerSub].OffsetToData));
5159 else
5160 SUP_RSRC_DPRINTF((" #%u: Name: #%#06x Dir: %#010x\n",
5161 iVerSub, paVerSubEntries[iVerSub].NameOffset, paVerSubEntries[iVerSub].OffsetToDirectory));
5162 }
5163 if (!paVerSubEntries[iVerSub].DataIsDirectory)
5164 {
5165 SUP_DPRINTF((" [Version info resource found at %#x! (ID/Name: %#x; SubID/SubName: %#x)]\n",
5166 paVerSubEntries[iVerSub].OffsetToData, paVerEntries[iVer].Name, paVerSubEntries[iVerSub].Name));
5167 return supR3HardenedGetRvaFromRsrcDataEntry(pRootDir, cbBuf, paVerSubEntries[iVerSub].OffsetToData, pcbData);
5168 }
5169 }
5170 }
5171 }
5172
5173 *pcbData = 0;
5174 return UINT32_MAX;
5175}
5176
5177
5178/**
5179 * Logs information about a file from a protection product or from Windows,
5180 * optionally returning the file version.
5181 *
5182 * The purpose here is to better see which version of the product is installed
5183 * and not needing to depend on the user supplying the correct information.
5184 *
5185 * @param pwszFile The NT path to the file.
5186 * @param pwszFileVersion Where to return the file version, if found. NULL if
5187 * not interested.
5188 * @param cwcFileVersion The size of the file version buffer (UTF-16 units).
5189 */
5190static void supR3HardenedLogFileInfo(PCRTUTF16 pwszFile, PRTUTF16 pwszFileVersion, size_t cwcFileVersion)
5191{
5192 /*
5193 * Make sure the file version is always set when we return.
5194 */
5195 if (pwszFileVersion && cwcFileVersion)
5196 *pwszFileVersion = '\0';
5197
5198 /*
5199 * Open the file.
5200 */
5201 HANDLE hFile = RTNT_INVALID_HANDLE_VALUE;
5202 IO_STATUS_BLOCK Ios = RTNT_IO_STATUS_BLOCK_INITIALIZER;
5203 UNICODE_STRING UniStrName;
5204 UniStrName.Buffer = (WCHAR *)pwszFile;
5205 UniStrName.Length = (USHORT)(RTUtf16Len(pwszFile) * sizeof(WCHAR));
5206 UniStrName.MaximumLength = UniStrName.Length + sizeof(WCHAR);
5207 OBJECT_ATTRIBUTES ObjAttr;
5208 InitializeObjectAttributes(&ObjAttr, &UniStrName, OBJ_CASE_INSENSITIVE, NULL /*hRootDir*/, NULL /*pSecDesc*/);
5209 NTSTATUS rcNt = NtCreateFile(&hFile,
5210 GENERIC_READ | SYNCHRONIZE,
5211 &ObjAttr,
5212 &Ios,
5213 NULL /* Allocation Size*/,
5214 FILE_ATTRIBUTE_NORMAL,
5215 FILE_SHARE_READ,
5216 FILE_OPEN,
5217 FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT,
5218 NULL /*EaBuffer*/,
5219 0 /*EaLength*/);
5220 if (NT_SUCCESS(rcNt))
5221 rcNt = Ios.Status;
5222 if (NT_SUCCESS(rcNt))
5223 {
5224 SUP_DPRINTF(("%ls:\n", pwszFile));
5225 union
5226 {
5227 uint64_t u64AlignmentInsurance;
5228 FILE_BASIC_INFORMATION BasicInfo;
5229 FILE_STANDARD_INFORMATION StdInfo;
5230 uint8_t abBuf[32768];
5231 RTUTF16 awcBuf[16384];
5232 IMAGE_DOS_HEADER MzHdr;
5233 IMAGE_RESOURCE_DIRECTORY ResDir;
5234 } u;
5235 RTTIMESPEC TimeSpec;
5236 char szTmp[64];
5237
5238 /*
5239 * Print basic file information available via NtQueryInformationFile.
5240 */
5241 IO_STATUS_BLOCK Ios = RTNT_IO_STATUS_BLOCK_INITIALIZER;
5242 rcNt = NtQueryInformationFile(hFile, &Ios, &u.BasicInfo, sizeof(u.BasicInfo), FileBasicInformation);
5243 if (NT_SUCCESS(rcNt) && NT_SUCCESS(Ios.Status))
5244 {
5245 SUP_DPRINTF((" CreationTime: %s\n", RTTimeSpecToString(RTTimeSpecSetNtTime(&TimeSpec, u.BasicInfo.CreationTime.QuadPart), szTmp, sizeof(szTmp))));
5246 /*SUP_DPRINTF((" LastAccessTime: %s\n", RTTimeSpecToString(RTTimeSpecSetNtTime(&TimeSpec, u.BasicInfo.LastAccessTime.QuadPart), szTmp, sizeof(szTmp))));*/
5247 SUP_DPRINTF((" LastWriteTime: %s\n", RTTimeSpecToString(RTTimeSpecSetNtTime(&TimeSpec, u.BasicInfo.LastWriteTime.QuadPart), szTmp, sizeof(szTmp))));
5248 SUP_DPRINTF((" ChangeTime: %s\n", RTTimeSpecToString(RTTimeSpecSetNtTime(&TimeSpec, u.BasicInfo.ChangeTime.QuadPart), szTmp, sizeof(szTmp))));
5249 SUP_DPRINTF((" FileAttributes: %#x\n", u.BasicInfo.FileAttributes));
5250 }
5251 else
5252 SUP_DPRINTF((" FileBasicInformation -> %#x %#x\n", rcNt, Ios.Status));
5253
5254 rcNt = NtQueryInformationFile(hFile, &Ios, &u.StdInfo, sizeof(u.StdInfo), FileStandardInformation);
5255 if (NT_SUCCESS(rcNt) && NT_SUCCESS(Ios.Status))
5256 SUP_DPRINTF((" Size: %#llx\n", u.StdInfo.EndOfFile.QuadPart));
5257 else
5258 SUP_DPRINTF((" FileStandardInformation -> %#x %#x\n", rcNt, Ios.Status));
5259
5260 /*
5261 * Read the image header and extract the timestamp and other useful info.
5262 */
5263 RT_ZERO(u);
5264 LARGE_INTEGER offRead;
5265 offRead.QuadPart = 0;
5266 rcNt = NtReadFile(hFile, NULL /*hEvent*/, NULL /*ApcRoutine*/, NULL /*ApcContext*/, &Ios,
5267 &u, (ULONG)sizeof(u), &offRead, NULL);
5268 if (NT_SUCCESS(rcNt) && NT_SUCCESS(Ios.Status))
5269 {
5270 uint32_t offNtHdrs = 0;
5271 if (u.MzHdr.e_magic == IMAGE_DOS_SIGNATURE)
5272 offNtHdrs = u.MzHdr.e_lfanew;
5273 if (offNtHdrs < sizeof(u) - sizeof(IMAGE_NT_HEADERS))
5274 {
5275 PIMAGE_NT_HEADERS64 pNtHdrs64 = (PIMAGE_NT_HEADERS64)&u.abBuf[offNtHdrs];
5276 PIMAGE_NT_HEADERS32 pNtHdrs32 = (PIMAGE_NT_HEADERS32)&u.abBuf[offNtHdrs];
5277 if (pNtHdrs64->Signature == IMAGE_NT_SIGNATURE)
5278 {
5279 SUP_DPRINTF((" NT Headers: %#x\n", offNtHdrs));
5280 SUP_DPRINTF((" Timestamp: %#x\n", pNtHdrs64->FileHeader.TimeDateStamp));
5281 SUP_DPRINTF((" Machine: %#x%s\n", pNtHdrs64->FileHeader.Machine,
5282 pNtHdrs64->FileHeader.Machine == IMAGE_FILE_MACHINE_I386 ? " - i386"
5283 : pNtHdrs64->FileHeader.Machine == IMAGE_FILE_MACHINE_AMD64 ? " - amd64" : ""));
5284 SUP_DPRINTF((" Timestamp: %#x\n", pNtHdrs64->FileHeader.TimeDateStamp));
5285 SUP_DPRINTF((" Image Version: %u.%u\n",
5286 pNtHdrs64->OptionalHeader.MajorImageVersion, pNtHdrs64->OptionalHeader.MinorImageVersion));
5287 SUP_DPRINTF((" SizeOfImage: %#x (%u)\n", pNtHdrs64->OptionalHeader.SizeOfImage, pNtHdrs64->OptionalHeader.SizeOfImage));
5288
5289 /*
5290 * Very crude way to extract info from the file version resource.
5291 */
5292 PIMAGE_SECTION_HEADER paSectHdrs = (PIMAGE_SECTION_HEADER)( (uintptr_t)&pNtHdrs64->OptionalHeader
5293 + pNtHdrs64->FileHeader.SizeOfOptionalHeader);
5294 IMAGE_DATA_DIRECTORY RsrcDir = { 0, 0 };
5295 if ( pNtHdrs64->FileHeader.SizeOfOptionalHeader == sizeof(IMAGE_OPTIONAL_HEADER64)
5296 && pNtHdrs64->OptionalHeader.NumberOfRvaAndSizes > IMAGE_DIRECTORY_ENTRY_RESOURCE)
5297 RsrcDir = pNtHdrs64->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE];
5298 else if ( pNtHdrs64->FileHeader.SizeOfOptionalHeader == sizeof(IMAGE_OPTIONAL_HEADER32)
5299 && pNtHdrs32->OptionalHeader.NumberOfRvaAndSizes > IMAGE_DIRECTORY_ENTRY_RESOURCE)
5300 RsrcDir = pNtHdrs32->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE];
5301 SUP_DPRINTF((" Resource Dir: %#x LB %#x\n", RsrcDir.VirtualAddress, RsrcDir.Size));
5302 if ( RsrcDir.VirtualAddress > offNtHdrs
5303 && RsrcDir.Size > 0
5304 && (uintptr_t)&u + sizeof(u) - (uintptr_t)paSectHdrs
5305 >= pNtHdrs64->FileHeader.NumberOfSections * sizeof(IMAGE_SECTION_HEADER) )
5306 {
5307 uint32_t uRvaRsrcSect = 0;
5308 uint32_t cbRsrcSect = 0;
5309 uint32_t offRsrcSect = 0;
5310 offRead.QuadPart = 0;
5311 for (uint32_t i = 0; i < pNtHdrs64->FileHeader.NumberOfSections; i++)
5312 {
5313 uRvaRsrcSect = paSectHdrs[i].VirtualAddress;
5314 cbRsrcSect = paSectHdrs[i].Misc.VirtualSize;
5315 offRsrcSect = paSectHdrs[i].PointerToRawData;
5316 if ( RsrcDir.VirtualAddress - uRvaRsrcSect < cbRsrcSect
5317 && offRsrcSect > offNtHdrs)
5318 {
5319 offRead.QuadPart = offRsrcSect + (RsrcDir.VirtualAddress - uRvaRsrcSect);
5320 break;
5321 }
5322 }
5323 if (offRead.QuadPart > 0)
5324 {
5325 RT_ZERO(u);
5326 rcNt = NtReadFile(hFile, NULL /*hEvent*/, NULL /*ApcRoutine*/, NULL /*ApcContext*/, &Ios,
5327 &u, (ULONG)sizeof(u), &offRead, NULL);
5328 PCRTUTF16 pwcVersionData = &u.awcBuf[0];
5329 size_t cbVersionData = sizeof(u);
5330
5331 if (NT_SUCCESS(rcNt) && NT_SUCCESS(Ios.Status))
5332 {
5333 /* Make it less crude by try find the version resource data. */
5334 uint32_t cbVersion;
5335 uint32_t uRvaVersion = supR3HardenedFindVersionRsrcRva(&u.ResDir, sizeof(u), &cbVersion);
5336 NOREF(uRvaVersion);
5337 if ( uRvaVersion != UINT32_MAX
5338 && cbVersion < cbRsrcSect
5339 && uRvaVersion - uRvaRsrcSect <= cbRsrcSect - cbVersion)
5340 {
5341 uint32_t const offVersion = uRvaVersion - uRvaRsrcSect;
5342 if ( offVersion < sizeof(u)
5343 && offVersion + cbVersion <= sizeof(u))
5344 {
5345 pwcVersionData = (PCRTUTF16)&u.abBuf[offVersion];
5346 cbVersionData = cbVersion;
5347 }
5348 else
5349 {
5350 offRead.QuadPart = offVersion + offRsrcSect;
5351 RT_ZERO(u);
5352 rcNt = NtReadFile(hFile, NULL /*hEvent*/, NULL /*ApcRoutine*/, NULL /*ApcContext*/, &Ios,
5353 &u, (ULONG)sizeof(u), &offRead, NULL);
5354 pwcVersionData = &u.awcBuf[0];
5355 cbVersionData = RT_MIN(cbVersion, sizeof(u));
5356 }
5357 }
5358 }
5359
5360 if (NT_SUCCESS(rcNt) && NT_SUCCESS(Ios.Status))
5361 {
5362 static const struct { PCRTUTF16 pwsz; size_t cb; bool fRet; } s_abFields[] =
5363 {
5364#define MY_WIDE_STR_TUPLE(a_sz, a_fRet) { L ## a_sz, sizeof(L ## a_sz) - sizeof(RTUTF16), a_fRet }
5365 MY_WIDE_STR_TUPLE("ProductName", false),
5366 MY_WIDE_STR_TUPLE("ProductVersion", false),
5367 MY_WIDE_STR_TUPLE("FileVersion", true),
5368 MY_WIDE_STR_TUPLE("SpecialBuild", false),
5369 MY_WIDE_STR_TUPLE("PrivateBuild", false),
5370 MY_WIDE_STR_TUPLE("FileDescription", false),
5371#undef MY_WIDE_STR_TUPLE
5372 };
5373 for (uint32_t i = 0; i < RT_ELEMENTS(s_abFields); i++)
5374 {
5375 if (cbVersionData <= s_abFields[i].cb + 10)
5376 continue;
5377 size_t cwcLeft = (cbVersionData - s_abFields[i].cb - 10) / sizeof(RTUTF16);
5378 PCRTUTF16 pwc = pwcVersionData;
5379 RTUTF16 const wcFirst = *s_abFields[i].pwsz;
5380 while (cwcLeft-- > 0)
5381 {
5382 if ( pwc[0] == 1 /* wType == text */
5383 && pwc[1] == wcFirst)
5384 {
5385 if (memcmp(pwc + 1, s_abFields[i].pwsz, s_abFields[i].cb + sizeof(RTUTF16)) == 0)
5386 {
5387 size_t cwcField = s_abFields[i].cb / sizeof(RTUTF16);
5388 pwc += cwcField + 2;
5389 cwcLeft -= cwcField + 2;
5390 for (uint32_t iPadding = 0; iPadding < 3; iPadding++, pwc++, cwcLeft--)
5391 if (*pwc)
5392 break;
5393 int rc = RTUtf16ValidateEncodingEx(pwc, cwcLeft,
5394 RTSTR_VALIDATE_ENCODING_ZERO_TERMINATED);
5395 if (RT_SUCCESS(rc))
5396 {
5397 SUP_DPRINTF((" %ls:%*s %ls",
5398 s_abFields[i].pwsz, cwcField < 15 ? 15 - cwcField : 0, "", pwc));
5399 if ( s_abFields[i].fRet
5400 && pwszFileVersion
5401 && cwcFileVersion > 1)
5402 RTUtf16Copy(pwszFileVersion, cwcFileVersion, pwc);
5403 }
5404 else
5405 SUP_DPRINTF((" %ls:%*s rc=%Rrc",
5406 s_abFields[i].pwsz, cwcField < 15 ? 15 - cwcField : 0, "", rc));
5407
5408 break;
5409 }
5410 }
5411 pwc++;
5412 }
5413 }
5414 }
5415 else
5416 SUP_DPRINTF((" NtReadFile @%#llx -> %#x %#x\n", offRead.QuadPart, rcNt, Ios.Status));
5417 }
5418 else
5419 SUP_DPRINTF((" Resource section not found.\n"));
5420 }
5421 }
5422 else
5423 SUP_DPRINTF((" Nt Headers @%#x: Invalid signature\n", offNtHdrs));
5424 }
5425 else
5426 SUP_DPRINTF((" Nt Headers @%#x: out side buffer\n", offNtHdrs));
5427 }
5428 else
5429 SUP_DPRINTF((" NtReadFile @0 -> %#x %#x\n", rcNt, Ios.Status));
5430 NtClose(hFile);
5431 }
5432}
5433
5434
5435/**
5436 * Scans the Driver directory for drivers which may invade our processes.
5437 *
5438 * @returns Mask of SUPHARDNT_ADVERSARY_XXX flags.
5439 *
5440 * @remarks The enumeration of \\Driver normally requires administrator
5441 * privileges. So, the detection we're doing here isn't always gonna
5442 * work just based on that.
5443 *
5444 * @todo Find drivers in \\FileSystems as well, then we could detect VrNsdDrv
5445 * from ViRobot APT Shield 2.0.
5446 */
5447static uint32_t supR3HardenedWinFindAdversaries(void)
5448{
5449 static const struct
5450 {
5451 uint32_t fAdversary;
5452 const char *pszDriver;
5453 } s_aDrivers[] =
5454 {
5455 { SUPHARDNT_ADVERSARY_SYMANTEC_SYSPLANT, "SysPlant" },
5456
5457 { SUPHARDNT_ADVERSARY_SYMANTEC_N360, "SRTSPX" },
5458 { SUPHARDNT_ADVERSARY_SYMANTEC_N360, "SymDS" },
5459 { SUPHARDNT_ADVERSARY_SYMANTEC_N360, "SymEvent" },
5460 { SUPHARDNT_ADVERSARY_SYMANTEC_N360, "SymIRON" },
5461 { SUPHARDNT_ADVERSARY_SYMANTEC_N360, "SymNetS" },
5462
5463 { SUPHARDNT_ADVERSARY_AVAST, "aswHwid" },
5464 { SUPHARDNT_ADVERSARY_AVAST, "aswMonFlt" },
5465 { SUPHARDNT_ADVERSARY_AVAST, "aswRdr2" },
5466 { SUPHARDNT_ADVERSARY_AVAST, "aswRvrt" },
5467 { SUPHARDNT_ADVERSARY_AVAST, "aswSnx" },
5468 { SUPHARDNT_ADVERSARY_AVAST, "aswsp" },
5469 { SUPHARDNT_ADVERSARY_AVAST, "aswStm" },
5470 { SUPHARDNT_ADVERSARY_AVAST, "aswVmm" },
5471
5472 { SUPHARDNT_ADVERSARY_TRENDMICRO, "tmcomm" },
5473 { SUPHARDNT_ADVERSARY_TRENDMICRO, "tmactmon" },
5474 { SUPHARDNT_ADVERSARY_TRENDMICRO, "tmevtmgr" },
5475 { SUPHARDNT_ADVERSARY_TRENDMICRO, "tmtdi" },
5476 { SUPHARDNT_ADVERSARY_TRENDMICRO, "tmebc64" }, /* Titanium internet security, not officescan. */
5477 { SUPHARDNT_ADVERSARY_TRENDMICRO, "tmeevw" }, /* Titanium internet security, not officescan. */
5478 { SUPHARDNT_ADVERSARY_TRENDMICRO, "tmciesc" }, /* Titanium internet security, not officescan. */
5479
5480 { SUPHARDNT_ADVERSARY_MCAFEE, "cfwids" },
5481 { SUPHARDNT_ADVERSARY_MCAFEE, "McPvDrv" },
5482 { SUPHARDNT_ADVERSARY_MCAFEE, "mfeapfk" },
5483 { SUPHARDNT_ADVERSARY_MCAFEE, "mfeavfk" },
5484 { SUPHARDNT_ADVERSARY_MCAFEE, "mfefirek" },
5485 { SUPHARDNT_ADVERSARY_MCAFEE, "mfehidk" },
5486 { SUPHARDNT_ADVERSARY_MCAFEE, "mfencbdc" },
5487 { SUPHARDNT_ADVERSARY_MCAFEE, "mfewfpk" },
5488
5489 { SUPHARDNT_ADVERSARY_KASPERSKY, "kl1" },
5490 { SUPHARDNT_ADVERSARY_KASPERSKY, "klflt" },
5491 { SUPHARDNT_ADVERSARY_KASPERSKY, "klif" },
5492 { SUPHARDNT_ADVERSARY_KASPERSKY, "KLIM6" },
5493 { SUPHARDNT_ADVERSARY_KASPERSKY, "klkbdflt" },
5494 { SUPHARDNT_ADVERSARY_KASPERSKY, "klmouflt" },
5495 { SUPHARDNT_ADVERSARY_KASPERSKY, "kltdi" },
5496 { SUPHARDNT_ADVERSARY_KASPERSKY, "kneps" },
5497
5498 { SUPHARDNT_ADVERSARY_MBAM, "MBAMWebAccessControl" },
5499 { SUPHARDNT_ADVERSARY_MBAM, "mbam" },
5500 { SUPHARDNT_ADVERSARY_MBAM, "mbamchameleon" },
5501 { SUPHARDNT_ADVERSARY_MBAM, "mwav" },
5502 { SUPHARDNT_ADVERSARY_MBAM, "mbamswissarmy" },
5503
5504 { SUPHARDNT_ADVERSARY_AVG, "avgfwfd" },
5505 { SUPHARDNT_ADVERSARY_AVG, "avgtdia" },
5506
5507 { SUPHARDNT_ADVERSARY_PANDA, "PSINAflt" },
5508 { SUPHARDNT_ADVERSARY_PANDA, "PSINFile" },
5509 { SUPHARDNT_ADVERSARY_PANDA, "PSINKNC" },
5510 { SUPHARDNT_ADVERSARY_PANDA, "PSINProc" },
5511 { SUPHARDNT_ADVERSARY_PANDA, "PSINProt" },
5512 { SUPHARDNT_ADVERSARY_PANDA, "PSINReg" },
5513 { SUPHARDNT_ADVERSARY_PANDA, "PSKMAD" },
5514 { SUPHARDNT_ADVERSARY_PANDA, "NNSAlpc" },
5515 { SUPHARDNT_ADVERSARY_PANDA, "NNSHttp" },
5516 { SUPHARDNT_ADVERSARY_PANDA, "NNShttps" },
5517 { SUPHARDNT_ADVERSARY_PANDA, "NNSIds" },
5518 { SUPHARDNT_ADVERSARY_PANDA, "NNSNAHSL" },
5519 { SUPHARDNT_ADVERSARY_PANDA, "NNSpicc" },
5520 { SUPHARDNT_ADVERSARY_PANDA, "NNSPihsw" },
5521 { SUPHARDNT_ADVERSARY_PANDA, "NNSPop3" },
5522 { SUPHARDNT_ADVERSARY_PANDA, "NNSProt" },
5523 { SUPHARDNT_ADVERSARY_PANDA, "NNSPrv" },
5524 { SUPHARDNT_ADVERSARY_PANDA, "NNSSmtp" },
5525 { SUPHARDNT_ADVERSARY_PANDA, "NNSStrm" },
5526 { SUPHARDNT_ADVERSARY_PANDA, "NNStlsc" },
5527
5528 { SUPHARDNT_ADVERSARY_MSE, "NisDrv" },
5529
5530 /*{ SUPHARDNT_ADVERSARY_COMODO, "cmdguard" }, file system */
5531 { SUPHARDNT_ADVERSARY_COMODO, "inspect" },
5532 { SUPHARDNT_ADVERSARY_COMODO, "cmdHlp" },
5533
5534 { SUPHARDNT_ADVERSARY_DIGITAL_GUARDIAN_OLD, "dgmaster" },
5535
5536 { SUPHARDNT_ADVERSARY_CYLANCE, "cyprotectdrv" }, /* Not verified. */
5537
5538 { SUPHARDNT_ADVERSARY_BEYONDTRUST, "privman" }, /* Not verified. */
5539
5540 { SUPHARDNT_ADVERSARY_AVECTO, "PGDriver" },
5541 };
5542
5543 static const struct
5544 {
5545 uint32_t fAdversary;
5546 PCRTUTF16 pwszFile;
5547 } s_aFiles[] =
5548 {
5549 { SUPHARDNT_ADVERSARY_SYMANTEC_SYSPLANT, L"\\SystemRoot\\System32\\drivers\\SysPlant.sys" },
5550 { SUPHARDNT_ADVERSARY_SYMANTEC_SYSPLANT, L"\\SystemRoot\\System32\\sysfer.dll" },
5551 { SUPHARDNT_ADVERSARY_SYMANTEC_SYSPLANT, L"\\SystemRoot\\System32\\sysferThunk.dll" },
5552
5553 { SUPHARDNT_ADVERSARY_SYMANTEC_N360, L"\\SystemRoot\\System32\\drivers\\N360x64\\1505000.013\\ccsetx64.sys" },
5554 { SUPHARDNT_ADVERSARY_SYMANTEC_N360, L"\\SystemRoot\\System32\\drivers\\N360x64\\1505000.013\\ironx64.sys" },
5555 { SUPHARDNT_ADVERSARY_SYMANTEC_N360, L"\\SystemRoot\\System32\\drivers\\N360x64\\1505000.013\\srtsp64.sys" },
5556 { SUPHARDNT_ADVERSARY_SYMANTEC_N360, L"\\SystemRoot\\System32\\drivers\\N360x64\\1505000.013\\srtspx64.sys" },
5557 { SUPHARDNT_ADVERSARY_SYMANTEC_N360, L"\\SystemRoot\\System32\\drivers\\N360x64\\1505000.013\\symds64.sys" },
5558 { SUPHARDNT_ADVERSARY_SYMANTEC_N360, L"\\SystemRoot\\System32\\drivers\\N360x64\\1505000.013\\symefa64.sys" },
5559 { SUPHARDNT_ADVERSARY_SYMANTEC_N360, L"\\SystemRoot\\System32\\drivers\\N360x64\\1505000.013\\symelam.sys" },
5560 { SUPHARDNT_ADVERSARY_SYMANTEC_N360, L"\\SystemRoot\\System32\\drivers\\N360x64\\1505000.013\\symnets.sys" },
5561 { SUPHARDNT_ADVERSARY_SYMANTEC_N360, L"\\SystemRoot\\System32\\drivers\\symevent64x86.sys" },
5562
5563 { SUPHARDNT_ADVERSARY_AVAST, L"\\SystemRoot\\System32\\drivers\\aswHwid.sys" },
5564 { SUPHARDNT_ADVERSARY_AVAST, L"\\SystemRoot\\System32\\drivers\\aswMonFlt.sys" },
5565 { SUPHARDNT_ADVERSARY_AVAST, L"\\SystemRoot\\System32\\drivers\\aswRdr2.sys" },
5566 { SUPHARDNT_ADVERSARY_AVAST, L"\\SystemRoot\\System32\\drivers\\aswRvrt.sys" },
5567 { SUPHARDNT_ADVERSARY_AVAST, L"\\SystemRoot\\System32\\drivers\\aswSnx.sys" },
5568 { SUPHARDNT_ADVERSARY_AVAST, L"\\SystemRoot\\System32\\drivers\\aswsp.sys" },
5569 { SUPHARDNT_ADVERSARY_AVAST, L"\\SystemRoot\\System32\\drivers\\aswStm.sys" },
5570 { SUPHARDNT_ADVERSARY_AVAST, L"\\SystemRoot\\System32\\drivers\\aswVmm.sys" },
5571
5572 { SUPHARDNT_ADVERSARY_TRENDMICRO, L"\\SystemRoot\\System32\\drivers\\tmcomm.sys" },
5573 { SUPHARDNT_ADVERSARY_TRENDMICRO, L"\\SystemRoot\\System32\\drivers\\tmactmon.sys" },
5574 { SUPHARDNT_ADVERSARY_TRENDMICRO, L"\\SystemRoot\\System32\\drivers\\tmevtmgr.sys" },
5575 { SUPHARDNT_ADVERSARY_TRENDMICRO, L"\\SystemRoot\\System32\\drivers\\tmtdi.sys" },
5576 { SUPHARDNT_ADVERSARY_TRENDMICRO, L"\\SystemRoot\\System32\\drivers\\tmebc64.sys" },
5577 { SUPHARDNT_ADVERSARY_TRENDMICRO, L"\\SystemRoot\\System32\\drivers\\tmeevw.sys" },
5578 { SUPHARDNT_ADVERSARY_TRENDMICRO, L"\\SystemRoot\\System32\\drivers\\tmciesc.sys" },
5579 { SUPHARDNT_ADVERSARY_TRENDMICRO_SAKFILE, L"\\SystemRoot\\System32\\drivers\\sakfile.sys" }, /* Data Loss Prevention, not officescan. */
5580 { SUPHARDNT_ADVERSARY_TRENDMICRO, L"\\SystemRoot\\System32\\drivers\\sakcd.sys" }, /* Data Loss Prevention, not officescan. */
5581
5582
5583 { SUPHARDNT_ADVERSARY_MCAFEE, L"\\SystemRoot\\System32\\drivers\\cfwids.sys" },
5584 { SUPHARDNT_ADVERSARY_MCAFEE, L"\\SystemRoot\\System32\\drivers\\McPvDrv.sys" },
5585 { SUPHARDNT_ADVERSARY_MCAFEE, L"\\SystemRoot\\System32\\drivers\\mfeapfk.sys" },
5586 { SUPHARDNT_ADVERSARY_MCAFEE, L"\\SystemRoot\\System32\\drivers\\mfeavfk.sys" },
5587 { SUPHARDNT_ADVERSARY_MCAFEE, L"\\SystemRoot\\System32\\drivers\\mfefirek.sys" },
5588 { SUPHARDNT_ADVERSARY_MCAFEE, L"\\SystemRoot\\System32\\drivers\\mfehidk.sys" },
5589 { SUPHARDNT_ADVERSARY_MCAFEE, L"\\SystemRoot\\System32\\drivers\\mfencbdc.sys" },
5590 { SUPHARDNT_ADVERSARY_MCAFEE, L"\\SystemRoot\\System32\\drivers\\mfewfpk.sys" },
5591
5592 { SUPHARDNT_ADVERSARY_KASPERSKY, L"\\SystemRoot\\System32\\drivers\\kl1.sys" },
5593 { SUPHARDNT_ADVERSARY_KASPERSKY, L"\\SystemRoot\\System32\\drivers\\klflt.sys" },
5594 { SUPHARDNT_ADVERSARY_KASPERSKY, L"\\SystemRoot\\System32\\drivers\\klif.sys" },
5595 { SUPHARDNT_ADVERSARY_KASPERSKY, L"\\SystemRoot\\System32\\drivers\\klim6.sys" },
5596 { SUPHARDNT_ADVERSARY_KASPERSKY, L"\\SystemRoot\\System32\\drivers\\klkbdflt.sys" },
5597 { SUPHARDNT_ADVERSARY_KASPERSKY, L"\\SystemRoot\\System32\\drivers\\klmouflt.sys" },
5598 { SUPHARDNT_ADVERSARY_KASPERSKY, L"\\SystemRoot\\System32\\drivers\\kltdi.sys" },
5599 { SUPHARDNT_ADVERSARY_KASPERSKY, L"\\SystemRoot\\System32\\drivers\\kneps.sys" },
5600 { SUPHARDNT_ADVERSARY_KASPERSKY, L"\\SystemRoot\\System32\\klfphc.dll" },
5601
5602 { SUPHARDNT_ADVERSARY_MBAM, L"\\SystemRoot\\System32\\drivers\\MBAMSwissArmy.sys" },
5603 { SUPHARDNT_ADVERSARY_MBAM, L"\\SystemRoot\\System32\\drivers\\mwac.sys" },
5604 { SUPHARDNT_ADVERSARY_MBAM, L"\\SystemRoot\\System32\\drivers\\mbamchameleon.sys" },
5605 { SUPHARDNT_ADVERSARY_MBAM, L"\\SystemRoot\\System32\\drivers\\mbam.sys" },
5606
5607 { SUPHARDNT_ADVERSARY_AVG, L"\\SystemRoot\\System32\\drivers\\avgrkx64.sys" },
5608 { SUPHARDNT_ADVERSARY_AVG, L"\\SystemRoot\\System32\\drivers\\avgmfx64.sys" },
5609 { SUPHARDNT_ADVERSARY_AVG, L"\\SystemRoot\\System32\\drivers\\avgidsdrivera.sys" },
5610 { SUPHARDNT_ADVERSARY_AVG, L"\\SystemRoot\\System32\\drivers\\avgidsha.sys" },
5611 { SUPHARDNT_ADVERSARY_AVG, L"\\SystemRoot\\System32\\drivers\\avgtdia.sys" },
5612 { SUPHARDNT_ADVERSARY_AVG, L"\\SystemRoot\\System32\\drivers\\avgloga.sys" },
5613 { SUPHARDNT_ADVERSARY_AVG, L"\\SystemRoot\\System32\\drivers\\avgldx64.sys" },
5614 { SUPHARDNT_ADVERSARY_AVG, L"\\SystemRoot\\System32\\drivers\\avgdiska.sys" },
5615
5616 { SUPHARDNT_ADVERSARY_PANDA, L"\\SystemRoot\\System32\\drivers\\PSINAflt.sys" },
5617 { SUPHARDNT_ADVERSARY_PANDA, L"\\SystemRoot\\System32\\drivers\\PSINFile.sys" },
5618 { SUPHARDNT_ADVERSARY_PANDA, L"\\SystemRoot\\System32\\drivers\\PSINKNC.sys" },
5619 { SUPHARDNT_ADVERSARY_PANDA, L"\\SystemRoot\\System32\\drivers\\PSINProc.sys" },
5620 { SUPHARDNT_ADVERSARY_PANDA, L"\\SystemRoot\\System32\\drivers\\PSINProt.sys" },
5621 { SUPHARDNT_ADVERSARY_PANDA, L"\\SystemRoot\\System32\\drivers\\PSINReg.sys" },
5622 { SUPHARDNT_ADVERSARY_PANDA, L"\\SystemRoot\\System32\\drivers\\PSKMAD.sys" },
5623 { SUPHARDNT_ADVERSARY_PANDA, L"\\SystemRoot\\System32\\drivers\\NNSAlpc.sys" },
5624 { SUPHARDNT_ADVERSARY_PANDA, L"\\SystemRoot\\System32\\drivers\\NNSHttp.sys" },
5625 { SUPHARDNT_ADVERSARY_PANDA, L"\\SystemRoot\\System32\\drivers\\NNShttps.sys" },
5626 { SUPHARDNT_ADVERSARY_PANDA, L"\\SystemRoot\\System32\\drivers\\NNSIds.sys" },
5627 { SUPHARDNT_ADVERSARY_PANDA, L"\\SystemRoot\\System32\\drivers\\NNSNAHSL.sys" },
5628 { SUPHARDNT_ADVERSARY_PANDA, L"\\SystemRoot\\System32\\drivers\\NNSpicc.sys" },
5629 { SUPHARDNT_ADVERSARY_PANDA, L"\\SystemRoot\\System32\\drivers\\NNSPihsw.sys" },
5630 { SUPHARDNT_ADVERSARY_PANDA, L"\\SystemRoot\\System32\\drivers\\NNSPop3.sys" },
5631 { SUPHARDNT_ADVERSARY_PANDA, L"\\SystemRoot\\System32\\drivers\\NNSProt.sys" },
5632 { SUPHARDNT_ADVERSARY_PANDA, L"\\SystemRoot\\System32\\drivers\\NNSPrv.sys" },
5633 { SUPHARDNT_ADVERSARY_PANDA, L"\\SystemRoot\\System32\\drivers\\NNSSmtp.sys" },
5634 { SUPHARDNT_ADVERSARY_PANDA, L"\\SystemRoot\\System32\\drivers\\NNSStrm.sys" },
5635 { SUPHARDNT_ADVERSARY_PANDA, L"\\SystemRoot\\System32\\drivers\\NNStlsc.sys" },
5636
5637 { SUPHARDNT_ADVERSARY_MSE, L"\\SystemRoot\\System32\\drivers\\MpFilter.sys" },
5638 { SUPHARDNT_ADVERSARY_MSE, L"\\SystemRoot\\System32\\drivers\\NisDrvWFP.sys" },
5639
5640 { SUPHARDNT_ADVERSARY_COMODO, L"\\SystemRoot\\System32\\drivers\\cmdguard.sys" },
5641 { SUPHARDNT_ADVERSARY_COMODO, L"\\SystemRoot\\System32\\drivers\\cmderd.sys" },
5642 { SUPHARDNT_ADVERSARY_COMODO, L"\\SystemRoot\\System32\\drivers\\inspect.sys" },
5643 { SUPHARDNT_ADVERSARY_COMODO, L"\\SystemRoot\\System32\\drivers\\cmdhlp.sys" },
5644 { SUPHARDNT_ADVERSARY_COMODO, L"\\SystemRoot\\System32\\drivers\\cfrmd.sys" },
5645 { SUPHARDNT_ADVERSARY_COMODO, L"\\SystemRoot\\System32\\drivers\\hmd.sys" },
5646 { SUPHARDNT_ADVERSARY_COMODO, L"\\SystemRoot\\System32\\guard64.dll" },
5647 { SUPHARDNT_ADVERSARY_COMODO, L"\\SystemRoot\\System32\\cmdvrt64.dll" },
5648 { SUPHARDNT_ADVERSARY_COMODO, L"\\SystemRoot\\System32\\cmdkbd64.dll" },
5649 { SUPHARDNT_ADVERSARY_COMODO, L"\\SystemRoot\\System32\\cmdcsr.dll" },
5650
5651 { SUPHARDNT_ADVERSARY_ZONE_ALARM, L"\\SystemRoot\\System32\\drivers\\vsdatant.sys" },
5652 { SUPHARDNT_ADVERSARY_ZONE_ALARM, L"\\SystemRoot\\System32\\AntiTheftCredentialProvider.dll" },
5653
5654 { SUPHARDNT_ADVERSARY_DIGITAL_GUARDIAN_OLD, L"\\SystemRoot\\System32\\drivers\\dgmaster.sys" },
5655
5656 { SUPHARDNT_ADVERSARY_CYLANCE, L"\\SystemRoot\\System32\\drivers\\cyprotectdrv32.sys" },
5657 { SUPHARDNT_ADVERSARY_CYLANCE, L"\\SystemRoot\\System32\\drivers\\cyprotectdrv64.sys" },
5658
5659 { SUPHARDNT_ADVERSARY_BEYONDTRUST, L"\\SystemRoot\\System32\\drivers\\privman.sys" },
5660 { SUPHARDNT_ADVERSARY_BEYONDTRUST, L"\\SystemRoot\\System32\\privman64.dll" },
5661 { SUPHARDNT_ADVERSARY_BEYONDTRUST, L"\\SystemRoot\\System32\\privman32.dll" },
5662
5663 { SUPHARDNT_ADVERSARY_AVECTO, L"\\SystemRoot\\System32\\drivers\\PGDriver.sys" },
5664 };
5665
5666 uint32_t fFound = 0;
5667
5668 /*
5669 * Open the driver object directory.
5670 */
5671 UNICODE_STRING NtDirName = RTNT_CONSTANT_UNISTR(L"\\Driver");
5672
5673 OBJECT_ATTRIBUTES ObjAttr;
5674 InitializeObjectAttributes(&ObjAttr, &NtDirName, OBJ_CASE_INSENSITIVE, NULL /*hRootDir*/, NULL /*pSecDesc*/);
5675
5676 HANDLE hDir;
5677 NTSTATUS rcNt = NtOpenDirectoryObject(&hDir, DIRECTORY_QUERY | FILE_LIST_DIRECTORY, &ObjAttr);
5678#ifdef VBOX_STRICT
5679 if (rcNt != STATUS_ACCESS_DENIED) /* non-admin */
5680 SUPR3HARDENED_ASSERT_NT_SUCCESS(rcNt);
5681#endif
5682 if (NT_SUCCESS(rcNt))
5683 {
5684 /*
5685 * Enumerate it, looking for the driver.
5686 */
5687 ULONG uObjDirCtx = 0;
5688 for (;;)
5689 {
5690 uint32_t abBuffer[_64K + _1K];
5691 ULONG cbActual;
5692 rcNt = NtQueryDirectoryObject(hDir,
5693 abBuffer,
5694 sizeof(abBuffer) - 4, /* minus four for string terminator space. */
5695 FALSE /*ReturnSingleEntry */,
5696 FALSE /*RestartScan*/,
5697 &uObjDirCtx,
5698 &cbActual);
5699 if (!NT_SUCCESS(rcNt) || cbActual < sizeof(OBJECT_DIRECTORY_INFORMATION))
5700 break;
5701
5702 POBJECT_DIRECTORY_INFORMATION pObjDir = (POBJECT_DIRECTORY_INFORMATION)abBuffer;
5703 while (pObjDir->Name.Length != 0)
5704 {
5705 WCHAR wcSaved = pObjDir->Name.Buffer[pObjDir->Name.Length / sizeof(WCHAR)];
5706 pObjDir->Name.Buffer[pObjDir->Name.Length / sizeof(WCHAR)] = '\0';
5707
5708 for (uint32_t i = 0; i < RT_ELEMENTS(s_aDrivers); i++)
5709 if (RTUtf16ICmpAscii(pObjDir->Name.Buffer, s_aDrivers[i].pszDriver) == 0)
5710 {
5711 fFound |= s_aDrivers[i].fAdversary;
5712 SUP_DPRINTF(("Found driver %s (%#x)\n", s_aDrivers[i].pszDriver, s_aDrivers[i].fAdversary));
5713 break;
5714 }
5715
5716 pObjDir->Name.Buffer[pObjDir->Name.Length / sizeof(WCHAR)] = wcSaved;
5717
5718 /* Next directory entry. */
5719 pObjDir++;
5720 }
5721 }
5722
5723 NtClose(hDir);
5724 }
5725 else
5726 SUP_DPRINTF(("NtOpenDirectoryObject failed on \\Driver: %#x\n", rcNt));
5727
5728 /*
5729 * Look for files.
5730 */
5731 for (uint32_t i = 0; i < RT_ELEMENTS(s_aFiles); i++)
5732 {
5733 HANDLE hFile = RTNT_INVALID_HANDLE_VALUE;
5734 IO_STATUS_BLOCK Ios = RTNT_IO_STATUS_BLOCK_INITIALIZER;
5735 UNICODE_STRING UniStrName;
5736 UniStrName.Buffer = (WCHAR *)s_aFiles[i].pwszFile;
5737 UniStrName.Length = (USHORT)(RTUtf16Len(s_aFiles[i].pwszFile) * sizeof(WCHAR));
5738 UniStrName.MaximumLength = UniStrName.Length + sizeof(WCHAR);
5739 InitializeObjectAttributes(&ObjAttr, &UniStrName, OBJ_CASE_INSENSITIVE, NULL /*hRootDir*/, NULL /*pSecDesc*/);
5740 rcNt = NtCreateFile(&hFile, GENERIC_READ | SYNCHRONIZE, &ObjAttr, &Ios, NULL /* Allocation Size*/,
5741 FILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ, FILE_OPEN,
5742 FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT, NULL /*EaBuffer*/, 0 /*EaLength*/);
5743 if (NT_SUCCESS(rcNt) && NT_SUCCESS(Ios.Status))
5744 {
5745 fFound |= s_aFiles[i].fAdversary;
5746 NtClose(hFile);
5747 }
5748 }
5749
5750 /*
5751 * Log details and upgrade select adversaries.
5752 */
5753 SUP_DPRINTF(("supR3HardenedWinFindAdversaries: %#x\n", fFound));
5754 for (uint32_t i = 0; i < RT_ELEMENTS(s_aFiles); i++)
5755 if (s_aFiles[i].fAdversary & fFound)
5756 {
5757 if (!(s_aFiles[i].fAdversary & SUPHARDNT_ADVERSARY_DIGITAL_GUARDIAN_OLD))
5758 supR3HardenedLogFileInfo(s_aFiles[i].pwszFile, NULL, 0);
5759 else
5760 {
5761 /*
5762 * See if it's a newer version of the driver which doesn't BSODs when we free
5763 * its memory. To use RTStrVersionCompare we do a rough UTF-16 -> ASCII conversion.
5764 */
5765 union
5766 {
5767 char szFileVersion[64];
5768 RTUTF16 wszFileVersion[32];
5769 } uBuf;
5770 supR3HardenedLogFileInfo(s_aFiles[i].pwszFile, uBuf.wszFileVersion, RT_ELEMENTS(uBuf.wszFileVersion));
5771 if (uBuf.wszFileVersion[0])
5772 {
5773 for (uint32_t off = 0; off < RT_ELEMENTS(uBuf.wszFileVersion); off++)
5774 {
5775 RTUTF16 wch = uBuf.wszFileVersion[off];
5776 uBuf.szFileVersion[off] = (char)wch;
5777 if (!wch)
5778 break;
5779 }
5780 uBuf.szFileVersion[RT_ELEMENTS(uBuf.wszFileVersion)] = '\0';
5781 if (RTStrVersionCompare(uBuf.szFileVersion, "7.3.0.0171") >= 0)
5782 {
5783 uint32_t const fOldFound = fFound;
5784 fFound = (fOldFound & ~SUPHARDNT_ADVERSARY_DIGITAL_GUARDIAN_OLD)
5785 | SUPHARDNT_ADVERSARY_DIGITAL_GUARDIAN_NEW;
5786 SUP_DPRINTF(("supR3HardenedWinFindAdversaries: Found newer version: %#x -> %#x\n", fOldFound, fFound));
5787 }
5788 }
5789 }
5790 }
5791
5792 return fFound;
5793}
5794
5795
5796extern "C" int main(int argc, char **argv, char **envp);
5797
5798/**
5799 * The executable entry point.
5800 *
5801 * This is normally taken care of by the C runtime library, but we don't want to
5802 * get involved with anything as complicated like the CRT in this setup. So, we
5803 * it everything ourselves, including parameter parsing.
5804 */
5805extern "C" void __stdcall suplibHardenedWindowsMain(void)
5806{
5807 RTEXITCODE rcExit = RTEXITCODE_FAILURE;
5808
5809 g_cSuplibHardenedWindowsMainCalls++;
5810 g_enmSupR3HardenedMainState = SUPR3HARDENEDMAINSTATE_WIN_EP_CALLED;
5811
5812 /*
5813 * Initialize the NTDLL API wrappers. This aims at bypassing patched NTDLL
5814 * in all the processes leading up the VM process.
5815 */
5816 supR3HardenedWinInitImports();
5817 g_enmSupR3HardenedMainState = SUPR3HARDENEDMAINSTATE_WIN_IMPORTS_RESOLVED;
5818
5819 /*
5820 * Notify the parent process that we're probably capable of reporting our
5821 * own errors.
5822 */
5823 if (g_ProcParams.hEvtParent || g_ProcParams.hEvtChild)
5824 {
5825 SUPR3HARDENED_ASSERT(g_fSupEarlyProcessInit);
5826
5827 g_ProcParams.enmRequest = kSupR3WinChildReq_CloseEvents;
5828 NtSetEvent(g_ProcParams.hEvtParent, NULL);
5829
5830 NtClose(g_ProcParams.hEvtParent);
5831 NtClose(g_ProcParams.hEvtChild);
5832 g_ProcParams.hEvtParent = NULL;
5833 g_ProcParams.hEvtChild = NULL;
5834 }
5835 else
5836 SUPR3HARDENED_ASSERT(!g_fSupEarlyProcessInit);
5837
5838 /*
5839 * After having resolved imports we patch the LdrInitializeThunk code so
5840 * that it's more difficult to invade our privacy by CreateRemoteThread.
5841 * We'll re-enable this after opening the driver or temporarily while respawning.
5842 */
5843 supR3HardenedWinDisableThreadCreation();
5844
5845 /*
5846 * Init g_uNtVerCombined. (The code is shared with SUPR3.lib and lives in
5847 * SUPHardenedVerfiyImage-win.cpp.)
5848 */
5849 supR3HardenedWinInitVersion(false /*fEarly*/);
5850 g_enmSupR3HardenedMainState = SUPR3HARDENEDMAINSTATE_WIN_VERSION_INITIALIZED;
5851
5852 /*
5853 * Convert the arguments to UTF-8 and open the log file if specified.
5854 * This must be done as early as possible since the code below may fail.
5855 */
5856 PUNICODE_STRING pCmdLineStr = &NtCurrentPeb()->ProcessParameters->CommandLine;
5857 int cArgs;
5858 char **papszArgs = suplibCommandLineToArgvWStub(pCmdLineStr->Buffer, pCmdLineStr->Length / sizeof(WCHAR), &cArgs);
5859
5860 supR3HardenedOpenLog(&cArgs, papszArgs);
5861
5862 /*
5863 * Log information about important system files.
5864 */
5865 supR3HardenedLogFileInfo(L"\\SystemRoot\\System32\\ntdll.dll", NULL /*pwszFileVersion*/, 0 /*cwcFileVersion*/);
5866 supR3HardenedLogFileInfo(L"\\SystemRoot\\System32\\kernel32.dll", NULL /*pwszFileVersion*/, 0 /*cwcFileVersion*/);
5867 supR3HardenedLogFileInfo(L"\\SystemRoot\\System32\\KernelBase.dll", NULL /*pwszFileVersion*/, 0 /*cwcFileVersion*/);
5868 supR3HardenedLogFileInfo(L"\\SystemRoot\\System32\\apisetschema.dll", NULL /*pwszFileVersion*/, 0 /*cwcFileVersion*/);
5869
5870 /*
5871 * Scan the system for adversaries, logging information about them.
5872 */
5873 g_fSupAdversaries = supR3HardenedWinFindAdversaries();
5874
5875 /*
5876 * Get the executable name, make sure it's the long version.
5877 */
5878 DWORD cwcExecName = GetModuleFileNameW(GetModuleHandleW(NULL), g_wszSupLibHardenedExePath,
5879 RT_ELEMENTS(g_wszSupLibHardenedExePath));
5880 if (cwcExecName >= RT_ELEMENTS(g_wszSupLibHardenedExePath))
5881 supR3HardenedFatalMsg("suplibHardenedWindowsMain", kSupInitOp_Integrity, VERR_BUFFER_OVERFLOW,
5882 "The executable path is too long.");
5883
5884 RTUTF16 wszLong[RT_ELEMENTS(g_wszSupLibHardenedExePath)];
5885 DWORD cwcLong = GetLongPathNameW(g_wszSupLibHardenedExePath, wszLong, RT_ELEMENTS(wszLong));
5886 if (cwcLong > 0)
5887 {
5888 memcpy(g_wszSupLibHardenedExePath, wszLong, (cwcLong + 1) * sizeof(RTUTF16));
5889 cwcExecName = cwcLong;
5890 }
5891
5892 /* The NT version of it. */
5893 HANDLE hFile = CreateFileW(g_wszSupLibHardenedExePath, GENERIC_READ, FILE_SHARE_READ, NULL /*pSecurityAttributes*/,
5894 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL /*hTemplateFile*/);
5895 if (hFile == NULL || hFile == INVALID_HANDLE_VALUE)
5896 supR3HardenedFatalMsg("suplibHardenedWindowsMain", kSupInitOp_Integrity, RTErrConvertFromWin32(RtlGetLastWin32Error()),
5897 "Error opening the executable: %u (%ls).", RtlGetLastWin32Error());
5898 RT_ZERO(g_SupLibHardenedExeNtPath);
5899 ULONG cbIgn;
5900 NTSTATUS rcNt = NtQueryObject(hFile, ObjectNameInformation, &g_SupLibHardenedExeNtPath,
5901 sizeof(g_SupLibHardenedExeNtPath) - sizeof(WCHAR), &cbIgn);
5902 if (!NT_SUCCESS(rcNt))
5903 supR3HardenedFatalMsg("suplibHardenedWindowsMain", kSupInitOp_Integrity, RTErrConvertFromNtStatus(rcNt),
5904 "NtQueryObject -> %#x (on %ls)\n", rcNt, g_wszSupLibHardenedExePath);
5905 NtClose(hFile);
5906
5907 /* The NT executable name offset / dir path length. */
5908 g_offSupLibHardenedExeNtName = g_SupLibHardenedExeNtPath.UniStr.Length / sizeof(WCHAR);
5909 while ( g_offSupLibHardenedExeNtName > 1
5910 && g_SupLibHardenedExeNtPath.UniStr.Buffer[g_offSupLibHardenedExeNtName - 1] != '\\' )
5911 g_offSupLibHardenedExeNtName--;
5912
5913 /*
5914 * Preliminary app binary path init. May change when SUPR3HardenedMain is
5915 * called (via main below).
5916 */
5917 supR3HardenedWinInitAppBin(SUPSECMAIN_FLAGS_LOC_APP_BIN);
5918
5919 /*
5920 * If we've done early init already, register the DLL load notification
5921 * callback and reinstall the NtDll patches.
5922 */
5923 if (g_fSupEarlyProcessInit)
5924 {
5925 supR3HardenedWinRegisterDllNotificationCallback();
5926 supR3HardenedWinReInstallHooks(false /*fFirstCall */);
5927 }
5928
5929 /*
5930 * Call the C/C++ main function.
5931 */
5932 SUP_DPRINTF(("Calling main()\n"));
5933 rcExit = (RTEXITCODE)main(cArgs, papszArgs, NULL);
5934
5935 /*
5936 * Exit the process (never return).
5937 */
5938 SUP_DPRINTF(("Terminating the normal way: rcExit=%d\n", rcExit));
5939 suplibHardenedExit(rcExit);
5940}
5941
5942
5943/**
5944 * Reports an error to the parent process via the process parameter structure.
5945 *
5946 * @param pszWhere Where this error occured, if fatal message. NULL
5947 * if not message.
5948 * @param enmWhat Which init operation went wrong if fatal
5949 * message. kSupInitOp_Invalid if not message.
5950 * @param rc The status code to report.
5951 * @param pszFormat The format string.
5952 * @param va The format arguments.
5953 */
5954DECLHIDDEN(void) supR3HardenedWinReportErrorToParent(const char *pszWhere, SUPINITOP enmWhat, int rc,
5955 const char *pszFormat, va_list va)
5956{
5957 if (pszWhere)
5958 RTStrCopy(g_ProcParams.szWhere, sizeof(g_ProcParams.szWhere), pszWhere);
5959 else
5960 g_ProcParams.szWhere[0] = '\0';
5961 RTStrPrintfV(g_ProcParams.szErrorMsg, sizeof(g_ProcParams.szErrorMsg), pszFormat, va);
5962 g_ProcParams.enmWhat = enmWhat;
5963 g_ProcParams.rc = RT_SUCCESS(rc) ? VERR_INTERNAL_ERROR_2 : rc;
5964 g_ProcParams.enmRequest = kSupR3WinChildReq_Error;
5965
5966 NtClearEvent(g_ProcParams.hEvtChild);
5967 NTSTATUS rcNt = NtSetEvent(g_ProcParams.hEvtParent, NULL);
5968 if (NT_SUCCESS(rcNt))
5969 {
5970 LARGE_INTEGER Timeout;
5971 Timeout.QuadPart = -300000000; /* 30 second */
5972 /*NTSTATUS rcNt =*/ NtWaitForSingleObject(g_ProcParams.hEvtChild, FALSE /*Alertable*/, &Timeout);
5973 }
5974}
5975
5976
5977/**
5978 * Routine called by the supR3HardenedEarlyProcessInitThunk assembly routine
5979 * when LdrInitializeThunk is executed during process initialization.
5980 *
5981 * This initializes the Stub and VM processes, hooking NTDLL APIs and opening
5982 * the device driver before any other DLLs gets loaded into the process. This
5983 * greately reduces and controls the trusted code base of the process compared
5984 * to opening the driver from SUPR3HardenedMain. It also avoids issues with so
5985 * call protection software that is in the habit of patching half of the ntdll
5986 * and kernel32 APIs in the process, making it almost indistinguishable from
5987 * software that is up to no good. Once we've opened vboxdrv, the process
5988 * should be locked down so thighly that only kernel software and csrss can mess
5989 * with the process.
5990 */
5991DECLASM(uintptr_t) supR3HardenedEarlyProcessInit(void)
5992{
5993 /*
5994 * When the first thread gets here we wait for the parent to continue with
5995 * the process purifications. The primary thread must execute for image
5996 * load notifications to trigger, at least in more recent windows versions.
5997 * The old trick of starting a different thread that terminates immediately
5998 * thus doesn't work.
5999 *
6000 * We are not allowed to modify any data at this point because it will be
6001 * reset by the child process purification the parent does when we stop. To
6002 * sabotage thread creation during purification, and to avoid unnecessary
6003 * work for the parent, we reset g_ProcParams before signalling the parent
6004 * here.
6005 */
6006 if (g_enmSupR3HardenedMainState != SUPR3HARDENEDMAINSTATE_NOT_YET_CALLED)
6007 {
6008 NtTerminateThread(0, 0);
6009 return 0x22; /* crash */
6010 }
6011
6012 /* Retrieve the data we need. */
6013 uintptr_t uNtDllAddr = ASMAtomicXchgPtrT(&g_ProcParams.uNtDllAddr, 0, uintptr_t);
6014 if (!RT_VALID_PTR(uNtDllAddr))
6015 {
6016 NtTerminateThread(0, 0);
6017 return 0x23; /* crash */
6018 }
6019
6020 HANDLE hEvtChild = g_ProcParams.hEvtChild;
6021 HANDLE hEvtParent = g_ProcParams.hEvtParent;
6022 if ( hEvtChild == NULL
6023 || hEvtChild == RTNT_INVALID_HANDLE_VALUE
6024 || hEvtParent == NULL
6025 || hEvtParent == RTNT_INVALID_HANDLE_VALUE)
6026 {
6027 NtTerminateThread(0, 0);
6028 return 0x24; /* crash */
6029 }
6030
6031 /* Resolve the APIs we need. */
6032 PFNNTWAITFORSINGLEOBJECT pfnNtWaitForSingleObject;
6033 PFNNTSETEVENT pfnNtSetEvent;
6034 supR3HardenedWinGetVeryEarlyImports(uNtDllAddr, &pfnNtWaitForSingleObject, &pfnNtSetEvent);
6035
6036 /* Signal the parent that we're ready for purification. */
6037 RT_ZERO(g_ProcParams);
6038 g_ProcParams.enmRequest = kSupR3WinChildReq_PurifyChildAndCloseHandles;
6039 NTSTATUS rcNt = pfnNtSetEvent(hEvtParent, NULL);
6040 if (rcNt != STATUS_SUCCESS)
6041 return 0x33; /* crash */
6042
6043 /* Wait up to 2 mins for the parent to exorcise evil. */
6044 LARGE_INTEGER Timeout;
6045 Timeout.QuadPart = -1200000000; /* 120 second */
6046 rcNt = pfnNtWaitForSingleObject(hEvtChild, FALSE /*Alertable*/, &Timeout);
6047 if (rcNt != STATUS_SUCCESS)
6048 return 0x34; /* crash */
6049
6050 /*
6051 * We're good to go, work global state and restore process parameters.
6052 * Note that we will not restore uNtDllAddr since that is our first defence
6053 * against unwanted threads (see above).
6054 */
6055 g_enmSupR3HardenedMainState = SUPR3HARDENEDMAINSTATE_WIN_EARLY_INIT_CALLED;
6056 g_fSupEarlyProcessInit = true;
6057
6058 g_ProcParams.hEvtChild = hEvtChild;
6059 g_ProcParams.hEvtParent = hEvtParent;
6060 g_ProcParams.enmRequest = kSupR3WinChildReq_Error;
6061 g_ProcParams.rc = VINF_SUCCESS;
6062
6063 /*
6064 * Initialize the NTDLL imports that we consider usable before the
6065 * process has been initialized.
6066 */
6067 supR3HardenedWinInitImportsEarly(uNtDllAddr);
6068 g_enmSupR3HardenedMainState = SUPR3HARDENEDMAINSTATE_WIN_EARLY_IMPORTS_RESOLVED;
6069
6070 /*
6071 * Init g_uNtVerCombined as well as we can at this point.
6072 */
6073 supR3HardenedWinInitVersion(true /*fEarly*/);
6074
6075 /*
6076 * Convert the arguments to UTF-8 so we can open the log file if specified.
6077 * We may have to normalize the pointer on older windows version (not w7/64 +).
6078 * Note! This leaks memory at present.
6079 */
6080 PRTL_USER_PROCESS_PARAMETERS pUserProcParams = NtCurrentPeb()->ProcessParameters;
6081 UNICODE_STRING CmdLineStr = pUserProcParams->CommandLine;
6082 if ( CmdLineStr.Buffer != NULL
6083 && !(pUserProcParams->Flags & RTL_USER_PROCESS_PARAMS_FLAG_NORMALIZED) )
6084 CmdLineStr.Buffer = (WCHAR *)((uintptr_t)CmdLineStr.Buffer + (uintptr_t)pUserProcParams);
6085 int cArgs;
6086 char **papszArgs = suplibCommandLineToArgvWStub(CmdLineStr.Buffer, CmdLineStr.Length / sizeof(WCHAR), &cArgs);
6087 supR3HardenedOpenLog(&cArgs, papszArgs);
6088 SUP_DPRINTF(("supR3HardenedVmProcessInit: uNtDllAddr=%p g_uNtVerCombined=%#x\n", uNtDllAddr, g_uNtVerCombined));
6089
6090 /*
6091 * Set up the direct system calls so we can more easily hook NtCreateSection.
6092 */
6093 RTERRINFOSTATIC ErrInfo;
6094 supR3HardenedWinInitSyscalls(true /*fReportErrors*/, RTErrInfoInitStatic(&ErrInfo));
6095
6096 /*
6097 * Determine the executable path and name. Will NOT determine the windows style
6098 * executable path here as we don't need it.
6099 */
6100 SIZE_T cbActual = 0;
6101 rcNt = NtQueryVirtualMemory(NtCurrentProcess(), &g_ProcParams, MemorySectionName, &g_SupLibHardenedExeNtPath,
6102 sizeof(g_SupLibHardenedExeNtPath) - sizeof(WCHAR), &cbActual);
6103 if ( !NT_SUCCESS(rcNt)
6104 || g_SupLibHardenedExeNtPath.UniStr.Length == 0
6105 || g_SupLibHardenedExeNtPath.UniStr.Length & 1)
6106 supR3HardenedFatal("NtQueryVirtualMemory/MemorySectionName failed in supR3HardenedVmProcessInit: %#x\n", rcNt);
6107
6108 /* The NT executable name offset / dir path length. */
6109 g_offSupLibHardenedExeNtName = g_SupLibHardenedExeNtPath.UniStr.Length / sizeof(WCHAR);
6110 while ( g_offSupLibHardenedExeNtName > 1
6111 && g_SupLibHardenedExeNtPath.UniStr.Buffer[g_offSupLibHardenedExeNtName - 1] != '\\' )
6112 g_offSupLibHardenedExeNtName--;
6113
6114 /*
6115 * Preliminary app binary path init. May change when SUPR3HardenedMain is called.
6116 */
6117 supR3HardenedWinInitAppBin(SUPSECMAIN_FLAGS_LOC_APP_BIN);
6118
6119 /*
6120 * Initialize the image verification stuff (hooks LdrLoadDll and NtCreateSection).
6121 */
6122 supR3HardenedWinInit(0, false /*fAvastKludge*/);
6123
6124 /*
6125 * Open the driver.
6126 */
6127 if (cArgs >= 1 && suplibHardenedStrCmp(papszArgs[0], SUPR3_RESPAWN_1_ARG0) == 0)
6128 {
6129 SUP_DPRINTF(("supR3HardenedVmProcessInit: Opening vboxdrv stub...\n"));
6130 supR3HardenedWinOpenStubDevice();
6131 g_enmSupR3HardenedMainState = SUPR3HARDENEDMAINSTATE_WIN_EARLY_STUB_DEVICE_OPENED;
6132 }
6133 else if (cArgs >= 1 && suplibHardenedStrCmp(papszArgs[0], SUPR3_RESPAWN_2_ARG0) == 0)
6134 {
6135 SUP_DPRINTF(("supR3HardenedVmProcessInit: Opening vboxdrv...\n"));
6136 supR3HardenedMainOpenDevice();
6137 g_enmSupR3HardenedMainState = SUPR3HARDENEDMAINSTATE_WIN_EARLY_REAL_DEVICE_OPENED;
6138 }
6139 else
6140 supR3HardenedFatal("Unexpected first argument '%s'!\n", papszArgs[0]);
6141
6142 /*
6143 * Reinstall the NtDll patches since there is a slight possibility that
6144 * someone undid them while we where busy opening the device.
6145 */
6146 supR3HardenedWinReInstallHooks(false /*fFirstCall */);
6147
6148 /*
6149 * Restore the LdrInitializeThunk code so we can initialize the process
6150 * normally when we return.
6151 */
6152 SUP_DPRINTF(("supR3HardenedVmProcessInit: Restoring LdrInitializeThunk...\n"));
6153 PSUPHNTLDRCACHEENTRY pLdrEntry;
6154 int rc = supHardNtLdrCacheOpen("ntdll.dll", &pLdrEntry, RTErrInfoInitStatic(&ErrInfo));
6155 if (RT_FAILURE(rc))
6156 supR3HardenedFatal("supR3HardenedVmProcessInit: supHardNtLdrCacheOpen failed on NTDLL: %Rrc %s\n",
6157 rc, ErrInfo.Core.pszMsg);
6158
6159 uint8_t *pbBits;
6160 rc = supHardNtLdrCacheEntryGetBits(pLdrEntry, &pbBits, uNtDllAddr, NULL, NULL, RTErrInfoInitStatic(&ErrInfo));
6161 if (RT_FAILURE(rc))
6162 supR3HardenedFatal("supR3HardenedVmProcessInit: supHardNtLdrCacheEntryGetBits failed on NTDLL: %Rrc %s\n",
6163 rc, ErrInfo.Core.pszMsg);
6164
6165 RTLDRADDR uValue;
6166 rc = RTLdrGetSymbolEx(pLdrEntry->hLdrMod, pbBits, uNtDllAddr, UINT32_MAX, "LdrInitializeThunk", &uValue);
6167 if (RT_FAILURE(rc))
6168 supR3HardenedFatal("supR3HardenedVmProcessInit: Failed to find LdrInitializeThunk (%Rrc).\n", rc);
6169
6170 PVOID pvLdrInitThunk = (PVOID)(uintptr_t)uValue;
6171 SUPR3HARDENED_ASSERT_NT_SUCCESS(supR3HardenedWinProtectMemory(pvLdrInitThunk, 16, PAGE_EXECUTE_READWRITE));
6172 memcpy(pvLdrInitThunk, pbBits + ((uintptr_t)uValue - uNtDllAddr), 16);
6173 SUPR3HARDENED_ASSERT_NT_SUCCESS(supR3HardenedWinProtectMemory(pvLdrInitThunk, 16, PAGE_EXECUTE_READ));
6174
6175 SUP_DPRINTF(("supR3HardenedVmProcessInit: Returning to LdrInitializeThunk...\n"));
6176 return (uintptr_t)pvLdrInitThunk;
6177}
6178
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette