VirtualBox

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

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

SUPHardNt: Need another hack to make VBoxRT.dll load when executing testcases, at least on server 2012.

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

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