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