VirtualBox

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

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

More updates.

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

© 2023 Oracle
ContactPrivacy policyTerms of Use