VirtualBox

source: vbox/trunk/src/VBox/HostDrivers/Support/win/SUPHardenedVerifyProcess-win.cpp@ 53036

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

SUP: NtCreateFile requires SYNCHRONIZE access when FILE_SYNCHRONOUS_IO_NONALERT is used, while in user mode anyways.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 92.4 KB
Line 
1/* $Id: SUPHardenedVerifyProcess-win.cpp 53036 2014-10-11 07:48:10Z vboxsync $ */
2/** @file
3 * VirtualBox Support Library/Driver - Hardened Process Verification, Windows.
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#ifdef IN_RING0
31# define IPRT_NT_MAP_TO_ZW
32# include <iprt/nt/nt.h>
33# include <ntimage.h>
34#else
35# include <iprt/nt/nt-and-windows.h>
36#endif
37
38#include <VBox/sup.h>
39#include <VBox/err.h>
40#include <iprt/alloca.h>
41#include <iprt/ctype.h>
42#include <iprt/param.h>
43#include <iprt/string.h>
44#include <iprt/zero.h>
45
46#ifdef IN_RING0
47# include "SUPDrvInternal.h"
48#else
49# include "SUPLibInternal.h"
50#endif
51#include "win/SUPHardenedVerify-win.h"
52
53
54/*******************************************************************************
55* Structures and Typedefs *
56*******************************************************************************/
57/**
58 * Virtual address space region.
59 */
60typedef struct SUPHNTVPREGION
61{
62 /** The RVA of the region. */
63 uint32_t uRva;
64 /** The size of the region. */
65 uint32_t cb;
66 /** The protection of the region. */
67 uint32_t fProt;
68} SUPHNTVPREGION;
69/** Pointer to a virtual address space region. */
70typedef SUPHNTVPREGION *PSUPHNTVPREGION;
71
72/**
73 * Virtual address space image information.
74 */
75typedef struct SUPHNTVPIMAGE
76{
77 /** The base address of the image. */
78 uintptr_t uImageBase;
79 /** The size of the image mapping. */
80 uintptr_t cbImage;
81
82 /** The name from the allowed lists. */
83 const char *pszName;
84 /** Name structure for NtQueryVirtualMemory/MemorySectionName. */
85 struct
86 {
87 /** The full unicode name. */
88 UNICODE_STRING UniStr;
89 /** Buffer space. */
90 WCHAR awcBuffer[260];
91 } Name;
92
93 /** The number of mapping regions. */
94 uint32_t cRegions;
95 /** Mapping regions. */
96 SUPHNTVPREGION aRegions[16];
97
98 /** The image characteristics from the FileHeader. */
99 uint16_t fImageCharecteristics;
100 /** The DLL characteristics from the OptionalHeader. */
101 uint16_t fDllCharecteristics;
102
103 /** Set if this is the DLL. */
104 bool fDll;
105 /** Set if the image is NTDLL an the verficiation code needs to watch out for
106 * the NtCreateSection patch. */
107 bool fNtCreateSectionPatch;
108 /** Whether the API set schema hack needs to be applied when verifying memory
109 * content. The hack means that we only check if the 1st section is mapped. */
110 bool fApiSetSchemaOnlySection1;
111 /** This may be a 32-bit resource DLL. */
112 bool f32bitResourceDll;
113
114 /** Pointer to the loader cache entry for the image. */
115 PSUPHNTLDRCACHEENTRY pCacheEntry;
116#ifdef IN_RING0
117 /** In ring-0 we don't currently cache images, so put it here. */
118 SUPHNTLDRCACHEENTRY CacheEntry;
119#endif
120} SUPHNTVPIMAGE;
121/** Pointer to image info from the virtual address space scan. */
122typedef SUPHNTVPIMAGE *PSUPHNTVPIMAGE;
123
124/**
125 * Virtual address space scanning state.
126 */
127typedef struct SUPHNTVPSTATE
128{
129 /** Type of verification to perform. */
130 SUPHARDNTVPKIND enmKind;
131 /** Combination of SUPHARDNTVP_F_XXX. */
132 uint32_t fFlags;
133 /** The result. */
134 int rcResult;
135 /** Number of fixes we've done.
136 * Only applicable in the purification modes. */
137 uint32_t cFixes;
138 /** Number of images in aImages. */
139 uint32_t cImages;
140 /** The index of the last image we looked up. */
141 uint32_t iImageHint;
142 /** The process handle. */
143 HANDLE hProcess;
144 /** Images found in the process.
145 * The array is large enough to hold the executable, all allowed DLLs, and one
146 * more so we can get the image name of the first unwanted DLL. */
147 SUPHNTVPIMAGE aImages[1 + 6 + 1
148#ifdef VBOX_PERMIT_VERIFIER_DLL
149 + 1
150#endif
151#ifdef VBOX_PERMIT_MORE
152 + 5
153#endif
154#ifdef VBOX_PERMIT_VISUAL_STUDIO_PROFILING
155 + 16
156#endif
157 ];
158 /** Memory compare scratch buffer.*/
159 uint8_t abMemory[_4K];
160 /** File compare scratch buffer.*/
161 uint8_t abFile[_4K];
162 /** Section headers for use when comparing file and loaded image. */
163 IMAGE_SECTION_HEADER aSecHdrs[16];
164 /** Pointer to the error info. */
165 PRTERRINFO pErrInfo;
166} SUPHNTVPSTATE;
167/** Pointer to stat information of a virtual address space scan. */
168typedef SUPHNTVPSTATE *PSUPHNTVPSTATE;
169
170
171/*******************************************************************************
172* Global Variables *
173*******************************************************************************/
174/**
175 * System DLLs allowed to be loaded into the process.
176 * @remarks supHardNtVpCheckDlls assumes these are lower case.
177 */
178static const char *g_apszSupNtVpAllowedDlls[] =
179{
180 "ntdll.dll",
181 "kernel32.dll",
182 "kernelbase.dll",
183 "apphelp.dll",
184 "apisetschema.dll",
185#ifdef VBOX_PERMIT_VERIFIER_DLL
186 "verifier.dll",
187#endif
188#ifdef VBOX_PERMIT_MORE
189# define VBOX_PERMIT_MORE_FIRST_IDX 5
190 "sfc.dll",
191 "sfc_os.dll",
192 "user32.dll",
193 "acres.dll",
194 "acgenral.dll",
195#endif
196#ifdef VBOX_PERMIT_VISUAL_STUDIO_PROFILING
197 "psapi.dll",
198 "msvcrt.dll",
199 "advapi32.dll",
200 "sechost.dll",
201 "rpcrt4.dll",
202 "SamplingRuntime.dll",
203#endif
204};
205
206/**
207 * VBox executables allowed to start VMs.
208 * @remarks Remember to keep in sync with SUPR3HardenedVerify.cpp.
209 */
210static const char *g_apszSupNtVpAllowedVmExes[] =
211{
212 "VBoxHeadless.exe",
213 "VirtualBox.exe",
214 "VBoxSDL.exe",
215 "VBoxNetDHCP.exe",
216 "VBoxNetNAT.exe",
217
218 "tstMicro.exe",
219 "tstPDMAsyncCompletion.exe",
220 "tstPDMAsyncCompletionStress.exe",
221 "tstVMM.exe",
222 "tstVMREQ.exe",
223 "tstCFGM.exe",
224 "tstIntNet-1.exe",
225 "tstMMHyperHeap.exe",
226 "tstR0ThreadPreemptionDriver.exe",
227 "tstRTR0MemUserKernelDriver.exe",
228 "tstRTR0SemMutexDriver.exe",
229 "tstRTR0TimerDriver.exe",
230 "tstSSM.exe",
231};
232
233/** Pointer to NtQueryVirtualMemory. Initialized by SUPDrv-win.cpp in
234 * ring-0, in ring-3 it's just a slightly confusing define. */
235#ifdef IN_RING0
236PFNNTQUERYVIRTUALMEMORY g_pfnNtQueryVirtualMemory = NULL;
237#else
238# define g_pfnNtQueryVirtualMemory NtQueryVirtualMemory
239#endif
240
241#ifdef IN_RING3
242/** The number of valid entries in the loader cache.. */
243static uint32_t g_cSupNtVpLdrCacheEntries = 0;
244/** The loader cache entries. */
245static SUPHNTLDRCACHEENTRY g_aSupNtVpLdrCacheEntries[RT_ELEMENTS(g_apszSupNtVpAllowedDlls) + 1 + 3];
246#endif
247
248
249/**
250 * Fills in error information.
251 *
252 * @returns @a rc.
253 * @param pErrInfo Pointer to the extended error info structure.
254 * Can be NULL.
255 * @param pszErr Where to return error details.
256 * @param cbErr Size of the buffer @a pszErr points to.
257 * @param rc The status to return.
258 * @param pszMsg The format string for the message.
259 * @param ... The arguments for the format string.
260 */
261static int supHardNtVpSetInfo1(PRTERRINFO pErrInfo, int rc, const char *pszMsg, ...)
262{
263 va_list va;
264#ifdef IN_RING3
265 va_start(va, pszMsg);
266 supR3HardenedError(rc, false /*fFatal*/, "%N\n", pszMsg, &va);
267 va_end(va);
268#endif
269
270 va_start(va, pszMsg);
271 RTErrInfoSetV(pErrInfo, rc, pszMsg, va);
272 va_end(va);
273
274 return rc;
275}
276
277
278/**
279 * Fills in error information.
280 *
281 * @returns @a rc.
282 * @param pThis The process validator instance.
283 * @param pszErr Where to return error details.
284 * @param cbErr Size of the buffer @a pszErr points to.
285 * @param rc The status to return.
286 * @param pszMsg The format string for the message.
287 * @param ... The arguments for the format string.
288 */
289static int supHardNtVpSetInfo2(PSUPHNTVPSTATE pThis, int rc, const char *pszMsg, ...)
290{
291 va_list va;
292#ifdef IN_RING3
293 va_start(va, pszMsg);
294 supR3HardenedError(rc, false /*fFatal*/, "%N\n", pszMsg, &va);
295 va_end(va);
296#endif
297
298 va_start(va, pszMsg);
299#ifdef IN_RING0
300 RTErrInfoSetV(pThis->pErrInfo, rc, pszMsg, va);
301 pThis->rcResult = rc;
302#else
303 if (RT_SUCCESS(pThis->rcResult))
304 {
305 RTErrInfoSetV(pThis->pErrInfo, rc, pszMsg, va);
306 pThis->rcResult = rc;
307 }
308 else
309 {
310 RTErrInfoAddF(pThis->pErrInfo, rc, " \n[rc=%d] ", rc);
311 RTErrInfoAddV(pThis->pErrInfo, rc, pszMsg, va);
312 }
313#endif
314 va_end(va);
315
316 return pThis->rcResult;
317}
318
319
320static int supHardNtVpReadImage(PSUPHNTVPIMAGE pImage, uint64_t off, void *pvBuf, size_t cbRead)
321{
322 return pImage->pCacheEntry->pNtViRdr->Core.pfnRead(&pImage->pCacheEntry->pNtViRdr->Core, pvBuf, cbRead, off);
323}
324
325
326static NTSTATUS supHardNtVpReadMem(HANDLE hProcess, uintptr_t uPtr, void *pvBuf, size_t cbRead)
327{
328#ifdef IN_RING0
329 /* ASSUMES hProcess is the current process. */
330 /** @todo use MmCopyVirtualMemory where available! */
331 int rc = RTR0MemUserCopyFrom(pvBuf, uPtr, cbRead);
332 if (RT_SUCCESS(rc))
333 return STATUS_SUCCESS;
334 return STATUS_ACCESS_DENIED;
335#else
336 SIZE_T cbIgn;
337 NTSTATUS rcNt = NtReadVirtualMemory(hProcess, (PVOID)uPtr, pvBuf, cbRead, &cbIgn);
338 if (NT_SUCCESS(rcNt) && cbIgn != cbRead)
339 rcNt = STATUS_IO_DEVICE_ERROR;
340 return rcNt;
341#endif
342}
343
344
345#ifdef IN_RING3
346static NTSTATUS supHardNtVpFileMemRestore(PSUPHNTVPSTATE pThis, PVOID pvRestoreAddr, uint8_t const *pbFile, uint32_t cbToRestore,
347 uint32_t fCorrectProtection)
348{
349 PVOID pvProt = pvRestoreAddr;
350 SIZE_T cbProt = cbToRestore;
351 ULONG fOldProt = 0;
352 NTSTATUS rcNt = NtProtectVirtualMemory(pThis->hProcess, &pvProt, &cbProt, PAGE_READWRITE, &fOldProt);
353 if (NT_SUCCESS(rcNt))
354 {
355 SIZE_T cbIgnored;
356 rcNt = NtWriteVirtualMemory(pThis->hProcess, pvRestoreAddr, pbFile, cbToRestore, &cbIgnored);
357
358 pvProt = pvRestoreAddr;
359 cbProt = cbToRestore;
360 NTSTATUS rcNt2 = NtProtectVirtualMemory(pThis->hProcess, &pvProt, &cbProt, fCorrectProtection, &fOldProt);
361 if (NT_SUCCESS(rcNt))
362 rcNt = rcNt2;
363 }
364 pThis->cFixes++;
365 return rcNt;
366}
367#endif /* IN_RING3 */
368
369
370typedef struct SUPHNTVPSKIPAREA
371{
372 uint32_t uRva;
373 uint32_t cb;
374} SUPHNTVPSKIPAREA;
375typedef SUPHNTVPSKIPAREA *PSUPHNTVPSKIPAREA;
376
377static int supHardNtVpFileMemCompareSection(PSUPHNTVPSTATE pThis, PSUPHNTVPIMAGE pImage,
378 uint32_t uRva, uint32_t cb, const uint8_t *pbFile,
379 int32_t iSh, PSUPHNTVPSKIPAREA paSkipAreas, uint32_t cSkipAreas,
380 uint32_t fCorrectProtection)
381{
382 AssertCompileAdjacentMembers(SUPHNTVPSTATE, abMemory, abFile); /* Use both the memory and file buffers here. Parfait might hate me for this... */
383 uint32_t const cbMemory = sizeof(pThis->abMemory) + sizeof(pThis->abFile);
384 uint8_t * const pbMemory = &pThis->abMemory[0];
385
386 while (cb > 0)
387 {
388 uint32_t cbThis = RT_MIN(cb, cbMemory);
389
390 /* Clipping. */
391 uint32_t uNextRva = uRva + cbThis;
392 if (cSkipAreas)
393 {
394 uint32_t uRvaEnd = uNextRva;
395 uint32_t i = cSkipAreas;
396 while (i-- > 0)
397 {
398 uint32_t uSkipEnd = paSkipAreas[i].uRva + paSkipAreas[i].cb;
399 if ( uRva < uSkipEnd
400 && uRvaEnd > paSkipAreas[i].uRva)
401 {
402 if (uRva < paSkipAreas[i].uRva)
403 {
404 cbThis = paSkipAreas[i].uRva - uRva;
405 uRvaEnd = paSkipAreas[i].uRva;
406 uNextRva = uSkipEnd;
407 }
408 else if (uRvaEnd >= uSkipEnd)
409 {
410 cbThis -= uSkipEnd - uRva;
411 uRva = uSkipEnd;
412 }
413 else
414 {
415 uNextRva = uSkipEnd;
416 cbThis = 0;
417 break;
418 }
419 }
420 }
421 }
422
423 /* Read the memory. */
424 NTSTATUS rcNt = supHardNtVpReadMem(pThis->hProcess, pImage->uImageBase + uRva, pbMemory, cbThis);
425 if (!NT_SUCCESS(rcNt))
426 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_MEMORY_READ_ERROR,
427 "%s: Error reading %#x bytes at %p (rva %#x, #%u, %.8s) from memory: %#x",
428 pImage->pszName, cbThis, pImage->uImageBase + uRva, uRva, iSh + 1,
429 iSh >= 0 ? (char *)pThis->aSecHdrs[iSh].Name : "headers", rcNt);
430
431 /* Do the compare. */
432 if (memcmp(pbFile, pbMemory, cbThis) != 0)
433 {
434 const char *pachSectNm = iSh >= 0 ? (char *)pThis->aSecHdrs[iSh].Name : "headers";
435 SUP_DPRINTF(("%s: Differences in section #%u (%s) between file and memory:\n", pImage->pszName, iSh + 1, pachSectNm));
436
437 uint32_t off = 0;
438 while (off < cbThis && pbFile[off] == pbMemory[off])
439 off++;
440 SUP_DPRINTF((" %p / %#09x: %02x != %02x\n",
441 pImage->uImageBase + uRva + off, uRva + off, pbFile[off], pbMemory[off]));
442 uint32_t offLast = off;
443 uint32_t cDiffs = 1;
444 for (uint32_t off2 = off + 1; off2 < cbThis; off2++)
445 if (pbFile[off2] != pbMemory[off2])
446 {
447 SUP_DPRINTF((" %p / %#09x: %02x != %02x\n",
448 pImage->uImageBase + uRva + off2, uRva + off2, pbFile[off2], pbMemory[off2]));
449 cDiffs++;
450 offLast = off2;
451 }
452
453#ifdef IN_RING3
454 if ( pThis->enmKind == SUPHARDNTVPKIND_CHILD_PURIFICATION
455 || pThis->enmKind == SUPHARDNTVPKIND_SELF_PURIFICATION)
456 {
457 PVOID pvRestoreAddr = (uint8_t *)pImage->uImageBase + uRva;
458 rcNt = supHardNtVpFileMemRestore(pThis, pvRestoreAddr, pbFile, cbThis, fCorrectProtection);
459 if (NT_SUCCESS(rcNt))
460 SUP_DPRINTF((" Restored %#x bytes of original file content at %p\n", cbThis, pvRestoreAddr));
461 else
462 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_MEMORY_VS_FILE_MISMATCH,
463 "%s: Failed to restore %#x bytes at %p (%#x, #%u, %s): %#x (cDiffs=%#x, first=%#x)",
464 pImage->pszName, cbThis, pvRestoreAddr, uRva, iSh + 1, pachSectNm, rcNt,
465 cDiffs, uRva + off);
466 }
467 else
468#endif /* IN_RING3 */
469 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_MEMORY_VS_FILE_MISMATCH,
470 "%s: %u differences between %#x and %#x in #%u (%.8s), first: %02x != %02x",
471 pImage->pszName, cDiffs, uRva + off, uRva + offLast, iSh + 1,
472 pachSectNm, pbFile[off], pbMemory[off]);
473 }
474
475 /* Advance. The clipping makes it a little bit complicated. */
476 cbThis = uNextRva - uRva;
477 if (cbThis >= cb)
478 break;
479 cb -= cbThis;
480 pbFile += cbThis;
481 uRva = uNextRva;
482 }
483 return VINF_SUCCESS;
484}
485
486
487
488static int supHardNtVpCheckSectionProtection(PSUPHNTVPSTATE pThis, PSUPHNTVPIMAGE pImage,
489 uint32_t uRva, uint32_t cb, uint32_t fProt)
490{
491 uint32_t const cbOrg = cb;
492 if (!cb)
493 return VINF_SUCCESS;
494 if ( pThis->enmKind == SUPHARDNTVPKIND_CHILD_PURIFICATION
495 || pThis->enmKind == SUPHARDNTVPKIND_SELF_PURIFICATION)
496 return VINF_SUCCESS;
497
498 for (uint32_t i = 0; i < pImage->cRegions; i++)
499 {
500 uint32_t offRegion = uRva - pImage->aRegions[i].uRva;
501 if (offRegion < pImage->aRegions[i].cb)
502 {
503 uint32_t cbLeft = pImage->aRegions[i].cb - offRegion;
504 if ( pImage->aRegions[i].fProt != fProt
505 && ( fProt != PAGE_READWRITE
506 || pImage->aRegions[i].fProt != PAGE_WRITECOPY))
507 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_SECTION_PROTECTION_MISMATCH,
508 "%s: RVA range %#x-%#x protection is %#x, expected %#x. (cb=%#x)",
509 pImage->pszName, uRva, uRva + cbLeft - 1, pImage->aRegions[i].fProt, fProt, cb);
510 if (cbLeft >= cb)
511 return VINF_SUCCESS;
512 cb -= cbLeft;
513 uRva += cbLeft;
514
515#if 0 /* This shouldn't ever be necessary. */
516 if ( i + 1 < pImage->cRegions
517 && uRva < pImage->aRegions[i + 1].uRva)
518 {
519 cbLeft = pImage->aRegions[i + 1].uRva - uRva;
520 if (cbLeft >= cb)
521 return VINF_SUCCESS;
522 cb -= cbLeft;
523 uRva += cbLeft;
524 }
525#endif
526 }
527 }
528
529 return supHardNtVpSetInfo2(pThis, cbOrg == cb ? VERR_SUP_VP_SECTION_NOT_MAPPED : VERR_SUP_VP_SECTION_NOT_FULLY_MAPPED,
530 "%s: RVA range %#x-%#x is not mapped?", pImage->pszName, uRva, uRva + cb - 1);
531}
532
533
534static DECLINLINE(bool) supHardNtVpIsModuleNameMatch(PSUPHNTVPIMAGE pImage, const char *pszModule)
535{
536 if (pImage->fDll)
537 {
538 const char *pszImageNm = pImage->pszName;
539 for (;;)
540 {
541 char chLeft = *pszImageNm++;
542 char chRight = *pszModule++;
543 if (chLeft != chRight)
544 {
545 Assert(chLeft == RT_C_TO_LOWER(chLeft));
546 if (chLeft != RT_C_TO_LOWER(chRight))
547 {
548 if ( chRight == '\0'
549 && chLeft == '.'
550 && pszImageNm[0] == 'd'
551 && pszImageNm[1] == 'l'
552 && pszImageNm[2] == 'l'
553 && pszImageNm[3] == '\0')
554 return true;
555 break;
556 }
557 }
558
559 if (chLeft == '\0')
560 return true;
561 }
562 }
563
564 return false;
565}
566
567
568/**
569 * Worker for supHardNtVpGetImport that looks up a module in the module table.
570 *
571 * @returns Pointer to the module if found, NULL if not found.
572 * @param pThis The process validator instance.
573 * @param pszModule The name of the module we're looking for.
574 */
575static PSUPHNTVPIMAGE supHardNtVpFindModule(PSUPHNTVPSTATE pThis, const char *pszModule)
576{
577 /*
578 * Check out the hint first.
579 */
580 if ( pThis->iImageHint < pThis->cImages
581 && supHardNtVpIsModuleNameMatch(&pThis->aImages[pThis->iImageHint], pszModule))
582 return &pThis->aImages[pThis->iImageHint];
583
584 /*
585 * Linear array search next.
586 */
587 uint32_t i = pThis->cImages;
588 while (i-- > 0)
589 if (supHardNtVpIsModuleNameMatch(&pThis->aImages[i], pszModule))
590 {
591 pThis->iImageHint = i;
592 return &pThis->aImages[i];
593 }
594
595 /* No cigar. */
596 return NULL;
597}
598
599
600/**
601 * @callback_method_impl{FNRTLDRIMPORT}
602 */
603static DECLCALLBACK(int) supHardNtVpGetImport(RTLDRMOD hLdrMod, const char *pszModule, const char *pszSymbol, unsigned uSymbol,
604 PRTLDRADDR pValue, void *pvUser)
605{
606 /*SUP_DPRINTF(("supHardNtVpGetImport: %s / %#x / %s.\n", pszModule, uSymbol, pszSymbol));*/
607 PSUPHNTVPSTATE pThis = (PSUPHNTVPSTATE)pvUser;
608
609 int rc = VERR_MODULE_NOT_FOUND;
610 PSUPHNTVPIMAGE pImage = supHardNtVpFindModule(pThis, pszModule);
611 if (pImage)
612 {
613 rc = RTLdrGetSymbolEx(pImage->pCacheEntry->hLdrMod, pImage->pCacheEntry->pbBits,
614 pImage->uImageBase, uSymbol, pszSymbol, pValue);
615 if (RT_SUCCESS(rc))
616 return rc;
617 }
618 /*
619 * API set hacks.
620 */
621 else if (!RTStrNICmp(pszModule, RT_STR_TUPLE("api-ms-win-")))
622 {
623 static const char * const s_apszDlls[] = { "ntdll.dll", "kernelbase.dll", "kernel32.dll" };
624 for (uint32_t i = 0; i < RT_ELEMENTS(s_apszDlls); i++)
625 {
626 pImage = supHardNtVpFindModule(pThis, s_apszDlls[i]);
627 if (pImage)
628 {
629 rc = RTLdrGetSymbolEx(pImage->pCacheEntry->hLdrMod, pImage->pCacheEntry->pbBits,
630 pImage->uImageBase, uSymbol, pszSymbol, pValue);
631 if (RT_SUCCESS(rc))
632 return rc;
633 if (rc != VERR_SYMBOL_NOT_FOUND)
634 break;
635 }
636 }
637 }
638
639 /*
640 * Deal with forwarders.
641 * ASSUMES no forwarders thru any api-ms-win-core-*.dll.
642 * ASSUMES forwarders are resolved after one redirection.
643 */
644 if (rc == VERR_LDR_FORWARDER)
645 {
646 size_t cbInfo = RT_MIN((uint32_t)*pValue, sizeof(RTLDRIMPORTINFO) + 32);
647 PRTLDRIMPORTINFO pInfo = (PRTLDRIMPORTINFO)alloca(cbInfo);
648 rc = RTLdrQueryForwarderInfo(pImage->pCacheEntry->hLdrMod, pImage->pCacheEntry->pbBits,
649 uSymbol, pszSymbol, pInfo, cbInfo);
650 if (RT_SUCCESS(rc))
651 {
652 rc = VERR_MODULE_NOT_FOUND;
653 pImage = supHardNtVpFindModule(pThis, pInfo->szModule);
654 if (pImage)
655 {
656 rc = RTLdrGetSymbolEx(pImage->pCacheEntry->hLdrMod, pImage->pCacheEntry->pbBits,
657 pImage->uImageBase, pInfo->iOrdinal, pInfo->pszSymbol, pValue);
658 if (RT_SUCCESS(rc))
659 return rc;
660
661 SUP_DPRINTF(("supHardNtVpGetImport: Failed to find symbol '%s' in '%s' (forwarded from %s / %s): %Rrc\n",
662 pInfo->pszSymbol, pInfo->szModule, pszModule, pszSymbol, rc));
663 if (rc == VERR_LDR_FORWARDER)
664 rc = VERR_LDR_FORWARDER_CHAIN_TOO_LONG;
665 }
666 else
667 SUP_DPRINTF(("supHardNtVpGetImport: Failed to find forwarder module '%s' (%#x / %s; originally %s / %#x / %s): %Rrc\n",
668 pInfo->szModule, pInfo->iOrdinal, pInfo->pszSymbol, pszModule, uSymbol, pszSymbol, rc));
669 }
670 else
671 SUP_DPRINTF(("supHardNtVpGetImport: RTLdrQueryForwarderInfo failed on symbol %#x/'%s' in '%s': %Rrc\n",
672 uSymbol, pszSymbol, pszModule, rc));
673 }
674 else
675 SUP_DPRINTF(("supHardNtVpGetImport: Failed to find symbol %#x / '%s' in '%s': %Rrc\n",
676 uSymbol, pszSymbol, pszModule, rc));
677 return rc;
678}
679
680
681/**
682 * Compares process memory with the disk content.
683 *
684 * @returns VBox status code.
685 * @param pThis The process scanning state structure (for the
686 * two scratch buffers).
687 * @param pImage The image data collected during the address
688 * space scan.
689 * @param hProcess Handle to the process.
690 * @param pErrInfo Pointer to error info structure. Optional.
691 */
692static int supHardNtVpVerifyImageMemoryCompare(PSUPHNTVPSTATE pThis, PSUPHNTVPIMAGE pImage, HANDLE hProcess, PRTERRINFO pErrInfo)
693{
694 /*
695 * Read and find the file headers.
696 */
697 int rc = supHardNtVpReadImage(pImage, 0 /*off*/, pThis->abFile, sizeof(pThis->abFile));
698 if (RT_FAILURE(rc))
699 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_IMAGE_HDR_READ_ERROR,
700 "%s: Error reading image header: %Rrc", pImage->pszName, rc);
701
702 uint32_t offNtHdrs = 0;
703 PIMAGE_DOS_HEADER pDosHdr = (PIMAGE_DOS_HEADER)&pThis->abFile[0];
704 if (pDosHdr->e_magic == IMAGE_DOS_SIGNATURE)
705 {
706 offNtHdrs = pDosHdr->e_lfanew;
707 if (offNtHdrs > 512 || offNtHdrs < sizeof(*pDosHdr))
708 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_BAD_MZ_OFFSET,
709 "%s: Unexpected e_lfanew value: %#x", pImage->pszName, offNtHdrs);
710 }
711 PIMAGE_NT_HEADERS pNtHdrs = (PIMAGE_NT_HEADERS)&pThis->abFile[offNtHdrs];
712 PIMAGE_NT_HEADERS32 pNtHdrs32 = (PIMAGE_NT_HEADERS32)pNtHdrs;
713 if (pNtHdrs->Signature != IMAGE_NT_SIGNATURE)
714 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_BAD_IMAGE_SIGNATURE,
715 "%s: No PE signature at %#x: %#x", pImage->pszName, offNtHdrs, pNtHdrs->Signature);
716
717 /*
718 * Do basic header validation.
719 */
720#ifdef RT_ARCH_AMD64
721 if (pNtHdrs->FileHeader.Machine != IMAGE_FILE_MACHINE_AMD64 && !pImage->f32bitResourceDll)
722#else
723 if (pNtHdrs->FileHeader.Machine != IMAGE_FILE_MACHINE_I386)
724#endif
725 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_UNEXPECTED_IMAGE_MACHINE,
726 "%s: Unexpected machine: %#x", pImage->pszName, pNtHdrs->FileHeader.Machine);
727 bool const fIs32Bit = pNtHdrs->FileHeader.Machine == IMAGE_FILE_MACHINE_I386;
728
729 if (pNtHdrs->FileHeader.SizeOfOptionalHeader != (fIs32Bit ? sizeof(IMAGE_OPTIONAL_HEADER32) : sizeof(IMAGE_OPTIONAL_HEADER64)))
730 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_BAD_OPTIONAL_HEADER,
731 "%s: Unexpected optional header size: %#x",
732 pImage->pszName, pNtHdrs->FileHeader.SizeOfOptionalHeader);
733
734 if (pNtHdrs->OptionalHeader.Magic != (fIs32Bit ? IMAGE_NT_OPTIONAL_HDR32_MAGIC : IMAGE_NT_OPTIONAL_HDR64_MAGIC))
735 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_BAD_OPTIONAL_HEADER,
736 "%s: Unexpected optional header magic: %#x", pImage->pszName, pNtHdrs->OptionalHeader.Magic);
737
738 uint32_t cDirs = (fIs32Bit ? pNtHdrs32->OptionalHeader.NumberOfRvaAndSizes : pNtHdrs->OptionalHeader.NumberOfRvaAndSizes);
739 if (cDirs != IMAGE_NUMBEROF_DIRECTORY_ENTRIES)
740 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_BAD_OPTIONAL_HEADER,
741 "%s: Unexpected data dirs: %#x", pImage->pszName, cDirs);
742
743 /*
744 * Before we start comparing things, store what we need to know from the headers.
745 */
746 uint32_t const cSections = pNtHdrs->FileHeader.NumberOfSections;
747 if (cSections > RT_ELEMENTS(pThis->aSecHdrs))
748 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_TOO_MANY_SECTIONS,
749 "%s: Too many section headers: %#x", pImage->pszName, cSections);
750 suplibHardenedMemCopy(pThis->aSecHdrs, (fIs32Bit ? (void *)(pNtHdrs32 + 1) : (void *)(pNtHdrs + 1)),
751 cSections * sizeof(IMAGE_SECTION_HEADER));
752
753 uintptr_t const uImageBase = fIs32Bit ? pNtHdrs32->OptionalHeader.ImageBase : pNtHdrs->OptionalHeader.ImageBase;
754 if (uImageBase & PAGE_OFFSET_MASK)
755 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_BAD_IMAGE_BASE,
756 "%s: Invalid image base: %p", pImage->pszName, uImageBase);
757
758 uint32_t const cbImage = fIs32Bit ? pNtHdrs32->OptionalHeader.SizeOfImage : pNtHdrs->OptionalHeader.SizeOfImage;
759 if (RT_ALIGN_32(pImage->cbImage, PAGE_SIZE) != RT_ALIGN_32(cbImage, PAGE_SIZE) && !pImage->fApiSetSchemaOnlySection1)
760 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_BAD_IMAGE_SIZE,
761 "%s: SizeOfImage (%#x) isn't close enough to the mapping size (%#x)",
762 pImage->pszName, cbImage, pImage->cbImage);
763 if (cbImage != RTLdrSize(pImage->pCacheEntry->hLdrMod))
764 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_BAD_IMAGE_SIZE,
765 "%s: SizeOfImage (%#x) differs from what RTLdrSize returns (%#zx)",
766 pImage->pszName, cbImage, RTLdrSize(pImage->pCacheEntry->hLdrMod));
767
768 uint32_t const cbSectAlign = fIs32Bit ? pNtHdrs32->OptionalHeader.SectionAlignment : pNtHdrs->OptionalHeader.SectionAlignment;
769 if ( !RT_IS_POWER_OF_TWO(cbSectAlign)
770 || cbSectAlign < PAGE_SIZE
771 || cbSectAlign > (pImage->fApiSetSchemaOnlySection1 ? _64K : (uint32_t)PAGE_SIZE) )
772 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_BAD_SECTION_ALIGNMENT_VALUE,
773 "%s: Unexpected SectionAlignment value: %#x", pImage->pszName, cbSectAlign);
774
775 uint32_t const cbFileAlign = fIs32Bit ? pNtHdrs32->OptionalHeader.FileAlignment : pNtHdrs->OptionalHeader.FileAlignment;
776 if (!RT_IS_POWER_OF_TWO(cbFileAlign) || cbFileAlign < 512 || cbFileAlign > PAGE_SIZE || cbFileAlign > cbSectAlign)
777 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_BAD_FILE_ALIGNMENT_VALUE,
778 "%s: Unexpected FileAlignment value: %#x (cbSectAlign=%#x)",
779 pImage->pszName, cbFileAlign, cbSectAlign);
780
781 uint32_t const cbHeaders = fIs32Bit ? pNtHdrs32->OptionalHeader.SizeOfHeaders : pNtHdrs->OptionalHeader.SizeOfHeaders;
782 uint32_t const cbMinHdrs = offNtHdrs + (fIs32Bit ? sizeof(*pNtHdrs32) : sizeof(*pNtHdrs) )
783 + sizeof(IMAGE_SECTION_HEADER) * cSections;
784 if (cbHeaders < cbMinHdrs)
785 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_BAD_SIZE_OF_HEADERS,
786 "%s: Headers are too small: %#x < %#x (cSections=%#x)",
787 pImage->pszName, cbHeaders, cbMinHdrs, cSections);
788 uint32_t const cbHdrsFile = RT_ALIGN_32(cbHeaders, cbFileAlign);
789 if (cbHdrsFile > sizeof(pThis->abFile))
790 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_BAD_SIZE_OF_HEADERS,
791 "%s: Headers are larger than expected: %#x/%#x (expected max %zx)",
792 pImage->pszName, cbHeaders, cbHdrsFile, sizeof(pThis->abFile));
793
794 /*
795 * Save some header fields we might be using later on.
796 */
797 pImage->fImageCharecteristics = pNtHdrs->FileHeader.Characteristics;
798 pImage->fDllCharecteristics = fIs32Bit ? pNtHdrs32->OptionalHeader.DllCharacteristics : pNtHdrs->OptionalHeader.DllCharacteristics;
799
800 /*
801 * Correct the apisetschema image base, size and region rva.
802 */
803 if (pImage->fApiSetSchemaOnlySection1)
804 {
805 pImage->uImageBase -= pThis->aSecHdrs[0].VirtualAddress;
806 pImage->cbImage += pThis->aSecHdrs[0].VirtualAddress;
807 pImage->aRegions[0].uRva = pThis->aSecHdrs[0].VirtualAddress;
808 }
809
810 /*
811 * Get relocated bits.
812 */
813 uint8_t *pbBits;
814 if (pThis->enmKind == SUPHARDNTVPKIND_CHILD_PURIFICATION)
815 rc = supHardNtLdrCacheEntryGetBits(pImage->pCacheEntry, &pbBits, pImage->uImageBase, NULL /*pfnGetImport*/, pThis,
816 pThis->pErrInfo);
817 else
818 rc = supHardNtLdrCacheEntryGetBits(pImage->pCacheEntry, &pbBits, pImage->uImageBase, supHardNtVpGetImport, pThis,
819 pThis->pErrInfo);
820 if (RT_FAILURE(rc))
821 return rc;
822
823 /* XP SP3 does not set ImageBase to load address. It fixes up the image on load time though. */
824 if (g_uNtVerCombined >= SUP_NT_VER_VISTA)
825 {
826 if (fIs32Bit)
827 ((PIMAGE_NT_HEADERS32)&pbBits[offNtHdrs])->OptionalHeader.ImageBase = (uint32_t)pImage->uImageBase;
828 else
829 ((PIMAGE_NT_HEADERS)&pbBits[offNtHdrs])->OptionalHeader.ImageBase = pImage->uImageBase;
830 }
831
832 /*
833 * Figure out areas we should skip during comparison.
834 */
835 uint32_t cSkipAreas = 0;
836 SUPHNTVPSKIPAREA aSkipAreas[5];
837 if (pImage->fNtCreateSectionPatch)
838 {
839 RTLDRADDR uValue;
840 if (pThis->enmKind == SUPHARDNTVPKIND_VERIFY_ONLY)
841 {
842 /* Ignore our NtCreateSection hack. */
843 rc = RTLdrGetSymbolEx(pImage->pCacheEntry->hLdrMod, pbBits, 0, UINT32_MAX, "NtCreateSection", &uValue);
844 if (RT_FAILURE(rc))
845 return supHardNtVpSetInfo2(pThis, rc, "%s: Failed to find 'NtCreateSection': %Rrc", pImage->pszName, rc);
846 aSkipAreas[cSkipAreas].uRva = (uint32_t)uValue;
847 aSkipAreas[cSkipAreas++].cb = ARCH_BITS == 32 ? 5 : 12;
848
849 /* Ignore our LdrLoadDll hack. */
850 rc = RTLdrGetSymbolEx(pImage->pCacheEntry->hLdrMod, pbBits, 0, UINT32_MAX, "LdrLoadDll", &uValue);
851 if (RT_FAILURE(rc))
852 return supHardNtVpSetInfo2(pThis, rc, "%s: Failed to find 'LdrLoadDll': %Rrc", pImage->pszName, rc);
853 aSkipAreas[cSkipAreas].uRva = (uint32_t)uValue;
854 aSkipAreas[cSkipAreas++].cb = ARCH_BITS == 32 ? 5 : 12;
855 }
856
857 /* Ignore our patched LdrInitializeThunk hack. */
858 rc = RTLdrGetSymbolEx(pImage->pCacheEntry->hLdrMod, pbBits, 0, UINT32_MAX, "LdrInitializeThunk", &uValue);
859 if (RT_FAILURE(rc))
860 return supHardNtVpSetInfo2(pThis, rc, "%s: Failed to find 'LdrInitializeThunk': %Rrc", pImage->pszName, rc);
861 aSkipAreas[cSkipAreas].uRva = (uint32_t)uValue;
862 aSkipAreas[cSkipAreas++].cb = 14;
863
864 /* LdrSystemDllInitBlock is filled in by the kernel. It mainly contains addresses of 32-bit ntdll method for wow64. */
865 rc = RTLdrGetSymbolEx(pImage->pCacheEntry->hLdrMod, pbBits, 0, UINT32_MAX, "LdrSystemDllInitBlock", &uValue);
866 if (RT_SUCCESS(rc))
867 {
868 aSkipAreas[cSkipAreas].uRva = (uint32_t)uValue;
869 aSkipAreas[cSkipAreas++].cb = RT_MAX(pbBits[(uint32_t)uValue], 0x50);
870 }
871
872 Assert(cSkipAreas <= RT_ELEMENTS(aSkipAreas));
873 }
874
875 /*
876 * Compare the file header with the loaded bits. The loader will fiddle
877 * with image base, changing it to the actual load address.
878 */
879 if (!pImage->fApiSetSchemaOnlySection1)
880 {
881 rc = supHardNtVpFileMemCompareSection(pThis, pImage, 0 /*uRva*/, cbHdrsFile, pbBits, -1, NULL, 0, PAGE_READONLY);
882 if (RT_FAILURE(rc))
883 return rc;
884
885 rc = supHardNtVpCheckSectionProtection(pThis, pImage, 0 /*uRva*/, cbHdrsFile, PAGE_READONLY);
886 if (RT_FAILURE(rc))
887 return rc;
888 }
889
890 /*
891 * Validate sections:
892 * - Check them against the mapping regions.
893 * - Check section bits according to enmKind.
894 */
895 uint32_t fPrevProt = PAGE_READONLY;
896 uint32_t uRva = cbHdrsFile;
897 for (uint32_t i = 0; i < cSections; i++)
898 {
899 /* Validate the section. */
900 uint32_t uSectRva = pThis->aSecHdrs[i].VirtualAddress;
901 if (uSectRva < uRva || uSectRva > cbImage || RT_ALIGN_32(uSectRva, cbSectAlign) != uSectRva)
902 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_BAD_SECTION_RVA,
903 "%s: Section %u: Invalid virtual address: %#x (uRva=%#x, cbImage=%#x, cbSectAlign=%#x)",
904 pImage->pszName, i, uSectRva, uRva, cbImage, cbSectAlign);
905 uint32_t cbMap = pThis->aSecHdrs[i].Misc.VirtualSize;
906 if (cbMap > cbImage || uRva + cbMap > cbImage)
907 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_BAD_SECTION_VIRTUAL_SIZE,
908 "%s: Section %u: Invalid virtual size: %#x (uSectRva=%#x, uRva=%#x, cbImage=%#x)",
909 pImage->pszName, i, cbMap, uSectRva, uRva, cbImage);
910 uint32_t cbFile = pThis->aSecHdrs[i].SizeOfRawData;
911 if (cbFile != RT_ALIGN_32(cbFile, cbFileAlign) || cbFile > RT_ALIGN_32(cbMap, cbSectAlign))
912 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_BAD_SECTION_FILE_SIZE,
913 "%s: Section %u: Invalid file size: %#x (cbMap=%#x, uSectRva=%#x)",
914 pImage->pszName, i, cbFile, cbMap, uSectRva);
915
916 /* Validate the protection and bits. */
917 if (!pImage->fApiSetSchemaOnlySection1 || i == 0)
918 {
919 uint32_t fProt;
920 switch (pThis->aSecHdrs[i].Characteristics & (IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE))
921 {
922 case IMAGE_SCN_MEM_READ:
923 fProt = PAGE_READONLY;
924 break;
925 case IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE:
926 fProt = PAGE_READWRITE;
927 if ( pThis->enmKind != SUPHARDNTVPKIND_VERIFY_ONLY
928 && pThis->enmKind != SUPHARDNTVPKIND_CHILD_PURIFICATION
929 && !suplibHardenedMemComp(pThis->aSecHdrs[i].Name, ".mrdata", 8)) /* w8.1, ntdll. Changed by proc init. */
930 fProt = PAGE_READONLY;
931 break;
932 case IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_EXECUTE:
933 fProt = PAGE_EXECUTE_READ;
934 break;
935 case IMAGE_SCN_MEM_EXECUTE:
936 fProt = PAGE_EXECUTE;
937 break;
938 case IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE:
939 /* Only the executable is allowed to have this section,
940 and it's protected after we're done patching. */
941 if (!pImage->fDll)
942 {
943 if (pThis->enmKind == SUPHARDNTVPKIND_CHILD_PURIFICATION)
944 fProt = PAGE_EXECUTE_READWRITE;
945 else
946 fProt = PAGE_EXECUTE_READ;
947 break;
948 }
949 default:
950 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_UNEXPECTED_SECTION_FLAGS,
951 "%s: Section %u: Unexpected characteristics: %#x (uSectRva=%#x, cbMap=%#x)",
952 pImage->pszName, i, pThis->aSecHdrs[i].Characteristics, uSectRva, cbMap);
953 }
954
955 /* The section bits. Child purification verifies all, normal
956 verification verifies all except where the executable is
957 concerned (due to opening vboxdrv during early process init). */
958 if ( ( (pThis->aSecHdrs[i].Characteristics & (IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_CNT_CODE))
959 && !(pThis->aSecHdrs[i].Characteristics & IMAGE_SCN_MEM_WRITE))
960 || (pThis->aSecHdrs[i].Characteristics & (IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE)) == IMAGE_SCN_MEM_READ
961 || (pThis->enmKind == SUPHARDNTVPKIND_VERIFY_ONLY && pImage->fDll)
962 || pThis->enmKind == SUPHARDNTVPKIND_CHILD_PURIFICATION)
963 {
964 rc = VINF_SUCCESS;
965 if (uRva < uSectRva && !pImage->fApiSetSchemaOnlySection1) /* Any gap worth checking? */
966 rc = supHardNtVpFileMemCompareSection(pThis, pImage, uRva, uSectRva - uRva, pbBits + uRva,
967 i - 1, NULL, 0, fPrevProt);
968 if (RT_SUCCESS(rc))
969 rc = supHardNtVpFileMemCompareSection(pThis, pImage, uSectRva, cbMap, pbBits + uSectRva,
970 i, aSkipAreas, cSkipAreas, fProt);
971 if (RT_SUCCESS(rc))
972 {
973 uint32_t cbMapAligned = i + 1 < cSections && !pImage->fApiSetSchemaOnlySection1
974 ? RT_ALIGN_32(cbMap, cbSectAlign) : RT_ALIGN_32(cbMap, PAGE_SIZE);
975 if (cbMapAligned > cbMap)
976 rc = supHardNtVpFileMemCompareSection(pThis, pImage, uSectRva + cbMap, cbMapAligned - cbMap,
977 g_abRTZeroPage, i, NULL, 0, fProt);
978 }
979 if (RT_FAILURE(rc))
980 return rc;
981 }
982
983 /* The protection (must be checked afterwards!). */
984 rc = supHardNtVpCheckSectionProtection(pThis, pImage, uSectRva, RT_ALIGN_32(cbMap, PAGE_SIZE), fProt);
985 if (RT_FAILURE(rc))
986 return rc;
987
988 fPrevProt = fProt;
989 }
990
991 /* Advance the RVA. */
992 uRva = uSectRva + RT_ALIGN_32(cbMap, cbSectAlign);
993 }
994
995 return VINF_SUCCESS;
996}
997
998
999/**
1000 * Verifies the signature of the given image on disk, then checks if the memory
1001 * mapping matches what we verified.
1002 *
1003 * @returns VBox status code.
1004 * @param pThis The process scanning state structure (for the
1005 * two scratch buffers).
1006 * @param pImage The image data collected during the address
1007 * space scan.
1008 * @param hProcess Handle to the process.
1009 * @param hFile Handle to the image file.
1010 */
1011static int supHardNtVpVerifyImage(PSUPHNTVPSTATE pThis, PSUPHNTVPIMAGE pImage, HANDLE hProcess)
1012{
1013 /*
1014 * Validate the file signature first, then do the memory compare.
1015 */
1016 int rc;
1017 if ( pImage->pCacheEntry != NULL
1018 && pImage->pCacheEntry->hLdrMod != NIL_RTLDRMOD)
1019 {
1020 rc = supHardNtLdrCacheEntryVerify(pImage->pCacheEntry, pImage->Name.UniStr.Buffer, pThis->pErrInfo);
1021 if (RT_SUCCESS(rc))
1022 rc = supHardNtVpVerifyImageMemoryCompare(pThis, pImage, hProcess, pThis->pErrInfo);
1023 }
1024 else
1025 rc = supHardNtVpSetInfo2(pThis, VERR_OPEN_FAILED, "pCacheEntry/hLdrMod is NIL! Impossible!");
1026 return rc;
1027}
1028
1029
1030/**
1031 * Verifies that there is only one thread in the process.
1032 *
1033 * @returns VBox status code.
1034 * @param hProcess The process.
1035 * @param hThread The thread.
1036 * @param pErrInfo Pointer to error info structure. Optional.
1037 */
1038DECLHIDDEN(int) supHardNtVpThread(HANDLE hProcess, HANDLE hThread, PRTERRINFO pErrInfo)
1039{
1040 /*
1041 * Use the ThreadAmILastThread request to check that there is only one
1042 * thread in the process.
1043 * Seems this isn't entirely reliable when hThread isn't the current thread?
1044 */
1045 ULONG cbIgn = 0;
1046 ULONG fAmI = 0;
1047 NTSTATUS rcNt = NtQueryInformationThread(hThread, ThreadAmILastThread, &fAmI, sizeof(fAmI), &cbIgn);
1048 if (!NT_SUCCESS(rcNt))
1049 return supHardNtVpSetInfo1(pErrInfo, VERR_SUP_VP_NT_QI_THREAD_ERROR,
1050 "NtQueryInformationThread/ThreadAmILastThread -> %#x", rcNt);
1051 if (!fAmI)
1052 return supHardNtVpSetInfo1(pErrInfo, VERR_SUP_VP_THREAD_NOT_ALONE,
1053 "More than one thread in process");
1054
1055 /** @todo Would be nice to verify the relation ship between hProcess and hThread
1056 * as well... */
1057 return VINF_SUCCESS;
1058}
1059
1060
1061/**
1062 * Verifies that there isn't a debugger attached to the process.
1063 *
1064 * @returns VBox status code.
1065 * @param hProcess The process.
1066 * @param pErrInfo Pointer to error info structure. Optional.
1067 */
1068DECLHIDDEN(int) supHardNtVpDebugger(HANDLE hProcess, PRTERRINFO pErrInfo)
1069{
1070#ifndef VBOX_WITHOUT_DEBUGGER_CHECKS
1071 /*
1072 * Use the ProcessDebugPort request to check there is no debugger
1073 * currently attached to the process.
1074 */
1075 ULONG cbIgn = 0;
1076 uintptr_t uPtr = ~(uintptr_t)0;
1077 NTSTATUS rcNt = NtQueryInformationProcess(hProcess,
1078 ProcessDebugPort,
1079 &uPtr, sizeof(uPtr), &cbIgn);
1080 if (!NT_SUCCESS(rcNt))
1081 return supHardNtVpSetInfo1(pErrInfo, VERR_SUP_VP_NT_QI_PROCESS_DBG_PORT_ERROR,
1082 "NtQueryInformationProcess/ProcessDebugPort -> %#x", rcNt);
1083 if (uPtr != 0)
1084 return supHardNtVpSetInfo1(pErrInfo, VERR_SUP_VP_DEBUGGED,
1085 "Debugger attached (%#zx)", uPtr);
1086#endif /* !VBOX_WITHOUT_DEBUGGER_CHECKS */
1087 return VINF_SUCCESS;
1088}
1089
1090
1091/**
1092 * Matches two UNICODE_STRING structures in a case sensitive fashion.
1093 *
1094 * @returns true if equal, false if not.
1095 * @param pUniStr1 The first unicode string.
1096 * @param pUniStr2 The first unicode string.
1097 */
1098static bool supHardNtVpAreUniStringsEqual(PCUNICODE_STRING pUniStr1, PCUNICODE_STRING pUniStr2)
1099{
1100 if (pUniStr1->Length != pUniStr2->Length)
1101 return false;
1102 return suplibHardenedMemComp(pUniStr1->Buffer, pUniStr2->Buffer, pUniStr1->Length) == 0;
1103}
1104
1105
1106/**
1107 * Performs a case insensitive comparison of an ASCII and an UTF-16 file name.
1108 *
1109 * @returns true / false
1110 * @param pszName1 The ASCII name.
1111 * @param pwszName2 The UTF-16 name.
1112 */
1113static bool supHardNtVpAreNamesEqual(const char *pszName1, PCRTUTF16 pwszName2)
1114{
1115 for (;;)
1116 {
1117 char ch1 = *pszName1++;
1118 RTUTF16 wc2 = *pwszName2++;
1119 if (ch1 != wc2)
1120 {
1121 ch1 = RT_C_TO_LOWER(ch1);
1122 wc2 = wc2 < 0x80 ? RT_C_TO_LOWER(wc2) : wc2;
1123 if (ch1 != wc2)
1124 return false;
1125 }
1126 if (!ch1)
1127 return true;
1128 }
1129}
1130
1131
1132/**
1133 * Records an additional memory region for an image.
1134 *
1135 * @returns VBox status code.
1136 * @retval VINF_OBJECT_DESTROYED if we've unmapped the image (child
1137 * purification only).
1138 * @param pThis The process scanning state structure.
1139 * @param pImage The new image structure. Only the unicode name
1140 * buffer is valid.
1141 * @param pMemInfo The memory information for the image.
1142 */
1143static int supHardNtVpNewImage(PSUPHNTVPSTATE pThis, PSUPHNTVPIMAGE pImage, PMEMORY_BASIC_INFORMATION pMemInfo)
1144{
1145 /*
1146 * Extract the final component.
1147 */
1148 unsigned cwcDirName = pImage->Name.UniStr.Length / sizeof(WCHAR);
1149 PCRTUTF16 pwszFilename = &pImage->Name.UniStr.Buffer[cwcDirName];
1150 while ( cwcDirName > 0
1151 && pwszFilename[-1] != '\\'
1152 && pwszFilename[-1] != '/'
1153 && pwszFilename[-1] != ':')
1154 {
1155 pwszFilename--;
1156 cwcDirName--;
1157 }
1158 if (!*pwszFilename)
1159 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_NO_IMAGE_MAPPING_NAME,
1160 "Empty filename (len=%u) for image at %p.", pImage->Name.UniStr.Length, pMemInfo->BaseAddress);
1161
1162 /*
1163 * Drop trailing slashes from the directory name.
1164 */
1165 while ( cwcDirName > 0
1166 && ( pImage->Name.UniStr.Buffer[cwcDirName - 1] == '\\'
1167 || pImage->Name.UniStr.Buffer[cwcDirName - 1] == '/'))
1168 cwcDirName--;
1169
1170 /*
1171 * Match it against known DLLs.
1172 */
1173 pImage->pszName = NULL;
1174 for (uint32_t i = 0; i < RT_ELEMENTS(g_apszSupNtVpAllowedDlls); i++)
1175 if (supHardNtVpAreNamesEqual(g_apszSupNtVpAllowedDlls[i], pwszFilename))
1176 {
1177 pImage->pszName = g_apszSupNtVpAllowedDlls[i];
1178 pImage->fDll = true;
1179
1180#ifndef VBOX_PERMIT_VISUAL_STUDIO_PROFILING
1181 /* The directory name must match the one we've got for System32. */
1182 if ( ( cwcDirName * sizeof(WCHAR) != g_System32NtPath.UniStr.Length
1183 || suplibHardenedMemComp(pImage->Name.UniStr.Buffer,
1184 g_System32NtPath.UniStr.Buffer,
1185 cwcDirName * sizeof(WCHAR)) )
1186# ifdef VBOX_PERMIT_MORE
1187 && ( pImage->pszName[0] != 'a'
1188 || pImage->pszName[1] != 'c'
1189 || !supHardViIsAppPatchDir(pImage->Name.UniStr.Buffer, pImage->Name.UniStr.Length / sizeof(WCHAR)) )
1190# endif
1191 )
1192 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_NON_SYSTEM32_DLL,
1193 "Expected %ls to be loaded from %ls.",
1194 pImage->Name.UniStr.Buffer, g_System32NtPath.UniStr.Buffer);
1195# ifdef VBOX_PERMIT_MORE
1196 if (g_uNtVerCombined < SUP_NT_VER_W70 && i >= VBOX_PERMIT_MORE_FIRST_IDX)
1197 pImage->pszName = NULL; /* hard limit: user32.dll is unwanted prior to w7. */
1198# endif
1199
1200#endif /* VBOX_PERMIT_VISUAL_STUDIO_PROFILING */
1201 break;
1202 }
1203 if (!pImage->pszName)
1204 {
1205 /*
1206 * Not a known DLL, is it a known executable?
1207 */
1208 for (uint32_t i = 0; i < RT_ELEMENTS(g_apszSupNtVpAllowedVmExes); i++)
1209 if (supHardNtVpAreNamesEqual(g_apszSupNtVpAllowedVmExes[i], pwszFilename))
1210 {
1211 pImage->pszName = g_apszSupNtVpAllowedVmExes[i];
1212 pImage->fDll = false;
1213 break;
1214 }
1215 }
1216 if (!pImage->pszName)
1217 {
1218 /*
1219 * Unknown image.
1220 *
1221 * If we're cleaning up a child process, we can unmap the offending
1222 * DLL... Might have interesting side effects, or at least interesting
1223 * as in "may you live in interesting times".
1224 */
1225#ifdef IN_RING3
1226 if ( pMemInfo->AllocationBase == pMemInfo->BaseAddress
1227 && pThis->enmKind == SUPHARDNTVPKIND_CHILD_PURIFICATION)
1228 {
1229 SUP_DPRINTF(("supHardNtVpScanVirtualMemory: Unmapping image mem at %p (%p LB %#zx) - '%ls'\n",
1230 pMemInfo->AllocationBase, pMemInfo->BaseAddress, pMemInfo->RegionSize));
1231 NTSTATUS rcNt = NtUnmapViewOfSection(pThis->hProcess, pMemInfo->AllocationBase);
1232 if (NT_SUCCESS(rcNt))
1233 return VINF_OBJECT_DESTROYED;
1234 pThis->cFixes++;
1235 SUP_DPRINTF(("supHardNtVpScanVirtualMemory: NtUnmapViewOfSection(,%p) failed: %#x\n", pMemInfo->AllocationBase, rcNt));
1236 }
1237#endif
1238 /*
1239 * Special error message if we can.
1240 */
1241 if ( pMemInfo->AllocationBase == pMemInfo->BaseAddress
1242 && ( supHardNtVpAreNamesEqual("sysfer.dll", pwszFilename)
1243 || supHardNtVpAreNamesEqual("sysfer32.dll", pwszFilename)
1244 || supHardNtVpAreNamesEqual("sysfer64.dll", pwszFilename)
1245 || supHardNtVpAreNamesEqual("sysfrethunk.dll", pwszFilename)) )
1246 {
1247 supHardNtVpSetInfo2(pThis, VERR_SUP_VP_SYSFER_DLL,
1248 "Found %ls at %p - This is probably part of Symantec Endpoint Protection. \n"
1249 "You or your admin need to add and exception to the Application and Device Control (ADC) "
1250 "component (or disable it) to prevent ADC from injecting itself into the VirtualBox VM processes. "
1251 "See http://www.symantec.com/connect/articles/creating-application-control-exclusions-symantec-endpoint-protection-121"
1252 , pImage->Name.UniStr.Buffer, pMemInfo->BaseAddress);
1253 return pThis->rcResult = VERR_SUP_VP_SYSFER_DLL; /* Try make sure this is what the user sees first! */
1254 }
1255 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_NOT_KNOWN_DLL_OR_EXE,
1256 "Unknown image file %ls at %p.", pImage->Name.UniStr.Buffer, pMemInfo->BaseAddress);
1257 }
1258
1259 /*
1260 * Checks for multiple mappings of the same DLL but with different image file paths.
1261 */
1262 uint32_t i = pThis->cImages;
1263 while (i-- > 1)
1264 if (pImage->pszName == pThis->aImages[i].pszName)
1265 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_DUPLICATE_DLL_MAPPING,
1266 "Duplicate image entries for %s: %ls and %ls",
1267 pImage->pszName, pImage->Name.UniStr.Buffer, pThis->aImages[i].Name.UniStr.Buffer);
1268
1269 /*
1270 * Since it's a new image, we expect to be at the start of the mapping now.
1271 */
1272 if (pMemInfo->AllocationBase != pMemInfo->BaseAddress)
1273 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_IMAGE_MAPPING_BASE_ERROR,
1274 "Invalid AllocationBase/BaseAddress for %s: %p vs %p.",
1275 pImage->pszName, pMemInfo->AllocationBase, pMemInfo->BaseAddress);
1276
1277 /*
1278 * Check for size/rva overflow.
1279 */
1280 if (pMemInfo->RegionSize >= _2G)
1281 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_TOO_LARGE_REGION,
1282 "Region 0 of image %s is too large: %p.", pImage->pszName, pMemInfo->RegionSize);
1283
1284 /*
1285 * Fill in details from the memory info.
1286 */
1287 pImage->uImageBase = (uintptr_t)pMemInfo->AllocationBase;
1288 pImage->cbImage = pMemInfo->RegionSize;
1289 pImage->pCacheEntry= NULL;
1290 pImage->cRegions = 1;
1291 pImage->aRegions[0].uRva = 0;
1292 pImage->aRegions[0].cb = (uint32_t)pMemInfo->RegionSize;
1293 pImage->aRegions[0].fProt = pMemInfo->Protect;
1294
1295 if (suplibHardenedStrCmp(pImage->pszName, "ntdll.dll") == 0)
1296 pImage->fNtCreateSectionPatch = true;
1297 else if (suplibHardenedStrCmp(pImage->pszName, "apisetschema.dll") == 0)
1298 pImage->fApiSetSchemaOnlySection1 = true; /** @todo Check the ApiSetMap field in the PEB. */
1299#ifdef VBOX_PERMIT_MORE
1300 else if (suplibHardenedStrCmp(pImage->pszName, "acres.dll") == 0)
1301 pImage->f32bitResourceDll = true;
1302#endif
1303
1304 return VINF_SUCCESS;
1305}
1306
1307
1308/**
1309 * Records an additional memory region for an image.
1310 *
1311 * @returns VBox status code.
1312 * @param pThis The process scanning state structure.
1313 * @param pImage The image.
1314 * @param pMemInfo The memory information for the region.
1315 */
1316static int supHardNtVpAddRegion(PSUPHNTVPSTATE pThis, PSUPHNTVPIMAGE pImage, PMEMORY_BASIC_INFORMATION pMemInfo)
1317{
1318 /*
1319 * Make sure the base address matches.
1320 */
1321 if (pImage->uImageBase != (uintptr_t)pMemInfo->AllocationBase)
1322 return supHardNtVpSetInfo2(pThis, VERR_SUPLIB_NT_PROCESS_UNTRUSTED_3,
1323 "Base address mismatch for %s: have %p, found %p for region %p LB %#zx.",
1324 pImage->pszName, pImage->uImageBase, pMemInfo->AllocationBase,
1325 pMemInfo->BaseAddress, pMemInfo->RegionSize);
1326
1327 /*
1328 * Check for size and rva overflows.
1329 */
1330 uintptr_t uRva = (uintptr_t)pMemInfo->BaseAddress - pImage->uImageBase;
1331 if (pMemInfo->RegionSize >= _2G)
1332 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_TOO_LARGE_REGION,
1333 "Region %u of image %s is too large: %p/%p.", pImage->pszName, pMemInfo->RegionSize, uRva);
1334 if (uRva >= _2G)
1335 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_TOO_HIGH_REGION_RVA,
1336 "Region %u of image %s is too high: %p/%p.", pImage->pszName, pMemInfo->RegionSize, uRva);
1337
1338
1339 /*
1340 * Record the region.
1341 */
1342 uint32_t iRegion = pImage->cRegions;
1343 if (iRegion + 1 >= RT_ELEMENTS(pImage->aRegions))
1344 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_TOO_MANY_IMAGE_REGIONS,
1345 "Too many regions for %s.", pImage->pszName);
1346 pImage->aRegions[iRegion].uRva = (uint32_t)uRva;
1347 pImage->aRegions[iRegion].cb = (uint32_t)pMemInfo->RegionSize;
1348 pImage->aRegions[iRegion].fProt = pMemInfo->Protect;
1349 pImage->cbImage = pImage->aRegions[iRegion].uRva + pImage->aRegions[iRegion].cb;
1350 pImage->cRegions++;
1351 pImage->fApiSetSchemaOnlySection1 = false;
1352
1353 return VINF_SUCCESS;
1354}
1355
1356
1357/**
1358 * Scans the virtual memory of the process.
1359 *
1360 * This collects the locations of DLLs and the EXE, and verifies that executable
1361 * memory is only associated with these.
1362 *
1363 * @returns VBox status code.
1364 * @param pThis The process scanning state structure. Details
1365 * about images are added to this.
1366 * @param hProcess The process to verify.
1367 */
1368static int supHardNtVpScanVirtualMemory(PSUPHNTVPSTATE pThis, HANDLE hProcess)
1369{
1370 SUP_DPRINTF(("supHardNtVpScanVirtualMemory: enmKind=%s\n",
1371 pThis->enmKind == SUPHARDNTVPKIND_VERIFY_ONLY ? "VERIFY_ONLY" :
1372 pThis->enmKind == SUPHARDNTVPKIND_CHILD_PURIFICATION ? "CHILD_PURIFICATION" : "SELF_PURIFICATION"));
1373
1374 uint32_t cXpExceptions = 0;
1375 uintptr_t cbAdvance = 0;
1376 uintptr_t uPtrWhere = 0;
1377#ifdef VBOX_PERMIT_VERIFIER_DLL
1378 for (uint32_t i = 0; i < 10240; i++)
1379#else
1380 for (uint32_t i = 0; i < 1024; i++)
1381#endif
1382 {
1383 SIZE_T cbActual = 0;
1384 MEMORY_BASIC_INFORMATION MemInfo = { 0, 0, 0, 0, 0, 0, 0 };
1385 NTSTATUS rcNt = g_pfnNtQueryVirtualMemory(hProcess,
1386 (void const *)uPtrWhere,
1387 MemoryBasicInformation,
1388 &MemInfo,
1389 sizeof(MemInfo),
1390 &cbActual);
1391 if (!NT_SUCCESS(rcNt))
1392 {
1393 if (rcNt == STATUS_INVALID_PARAMETER)
1394 return pThis->rcResult;
1395 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_NT_QI_VIRTUAL_MEMORY_ERROR,
1396 "NtQueryVirtualMemory failed for %p: %#x", uPtrWhere, rcNt);
1397 }
1398
1399 /*
1400 * Record images.
1401 */
1402 if ( MemInfo.Type == SEC_IMAGE
1403 || MemInfo.Type == SEC_PROTECTED_IMAGE
1404 || MemInfo.Type == (SEC_IMAGE | SEC_PROTECTED_IMAGE))
1405 {
1406 uint32_t iImg = pThis->cImages;
1407 rcNt = g_pfnNtQueryVirtualMemory(hProcess,
1408 (void const *)uPtrWhere,
1409 MemorySectionName,
1410 &pThis->aImages[iImg].Name,
1411 sizeof(pThis->aImages[iImg].Name) - sizeof(WCHAR),
1412 &cbActual);
1413 if (!NT_SUCCESS(rcNt))
1414 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_NT_QI_VIRTUAL_MEMORY_NM_ERROR,
1415 "NtQueryVirtualMemory/MemorySectionName failed for %p: %#x", uPtrWhere, rcNt);
1416 pThis->aImages[iImg].Name.UniStr.Buffer[pThis->aImages[iImg].Name.UniStr.Length / sizeof(WCHAR)] = '\0';
1417 SUP_DPRINTF((MemInfo.AllocationBase == MemInfo.BaseAddress
1418 ? " *%p-%p %#06x/%#06x %#09x %ls\n"
1419 : " %p-%p %#06x/%#06x %#09x %ls\n",
1420 MemInfo.BaseAddress, (uintptr_t)MemInfo.BaseAddress - MemInfo.RegionSize - 1, MemInfo.Protect,
1421 MemInfo.AllocationProtect, MemInfo.Type, pThis->aImages[iImg].Name.UniStr.Buffer));
1422
1423 /* New or existing image? */
1424 bool fNew = true;
1425 uint32_t iSearch = iImg;
1426 while (iSearch-- > 0)
1427 if (supHardNtVpAreUniStringsEqual(&pThis->aImages[iSearch].Name.UniStr, &pThis->aImages[iImg].Name.UniStr))
1428 {
1429 int rc = supHardNtVpAddRegion(pThis, &pThis->aImages[iSearch], &MemInfo);
1430 if (RT_FAILURE(rc))
1431 return rc;
1432 fNew = false;
1433 break;
1434 }
1435 else if (pThis->aImages[iSearch].uImageBase == (uintptr_t)MemInfo.AllocationBase)
1436 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_NT_MAPPING_NAME_CHANGED,
1437 "Unexpected base address match");
1438
1439 if (fNew)
1440 {
1441 int rc = supHardNtVpNewImage(pThis, &pThis->aImages[iImg], &MemInfo);
1442 if (RT_SUCCESS(rc))
1443 {
1444 if (rc != VINF_OBJECT_DESTROYED)
1445 {
1446 pThis->cImages++;
1447 if (pThis->cImages >= RT_ELEMENTS(pThis->aImages))
1448 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_TOO_MANY_DLLS_LOADED,
1449 "Internal error: aImages is full.\n");
1450 }
1451 }
1452#ifdef IN_RING3 /* Continue and add more information if unknown DLLs are found. */
1453 else if (rc != VERR_SUP_VP_NOT_KNOWN_DLL_OR_EXE && rc != VERR_SUP_VP_NON_SYSTEM32_DLL)
1454 return rc;
1455#else
1456 else
1457 return rc;
1458#endif
1459 }
1460 }
1461 /*
1462 * XP, W2K3: Ignore the CSRSS read-only region as best we can.
1463 */
1464 else if ( (MemInfo.Protect & (PAGE_EXECUTE | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY))
1465 == PAGE_EXECUTE_READ
1466 && cXpExceptions == 0
1467 && (uintptr_t)MemInfo.BaseAddress >= UINT32_C(0x78000000)
1468 /* && MemInfo.BaseAddress == pPeb->ReadOnlySharedMemoryBase */
1469 && g_uNtVerCombined < SUP_MAKE_NT_VER_SIMPLE(6, 0) )
1470 {
1471 cXpExceptions++;
1472 SUP_DPRINTF((" %p-%p %#06x/%#06x %#09x XP CSRSS read-only region\n", MemInfo.BaseAddress,
1473 (uintptr_t)MemInfo.BaseAddress - MemInfo.RegionSize - 1, MemInfo.Protect,
1474 MemInfo.AllocationProtect, MemInfo.Type));
1475 }
1476 /*
1477 * Executable memory?
1478 */
1479#ifndef VBOX_PERMIT_VISUAL_STUDIO_PROFILING
1480 else if (MemInfo.Protect & (PAGE_EXECUTE | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY))
1481 {
1482 SUP_DPRINTF((MemInfo.AllocationBase == MemInfo.BaseAddress
1483 ? " *%p-%p %#06x/%#06x %#09x !!\n"
1484 : " %p-%p %#06x/%#06x %#09x !!\n",
1485 MemInfo.BaseAddress, (uintptr_t)MemInfo.BaseAddress - MemInfo.RegionSize - 1,
1486 MemInfo.Protect, MemInfo.AllocationProtect, MemInfo.Type));
1487# ifdef IN_RING3
1488 if (pThis->enmKind == SUPHARDNTVPKIND_CHILD_PURIFICATION)
1489 {
1490 /*
1491 * Free any private executable memory (sysplant.sys allocates executable memory).
1492 */
1493 if (MemInfo.Type == MEM_PRIVATE)
1494 {
1495 PVOID pvFree = MemInfo.BaseAddress;
1496 SIZE_T cbFree = MemInfo.RegionSize;
1497 if (!(pThis->fFlags & SUPHARDNTVP_F_EXEC_ALLOC_REPLACE_WITH_RW))
1498 {
1499 SUP_DPRINTF(("supHardNtVpScanVirtualMemory: Freeing exec mem at %p (%p LB %#zx)\n",
1500 uPtrWhere, MemInfo.BaseAddress, MemInfo.RegionSize));
1501
1502 rcNt = NtFreeVirtualMemory(pThis->hProcess, &pvFree, &cbFree, MEM_RELEASE);
1503 if (!NT_SUCCESS(rcNt))
1504 supHardNtVpSetInfo2(pThis, VERR_SUP_VP_FREE_VIRTUAL_MEMORY_FAILED,
1505 "NtFreeVirtualMemory (%p LB %#zx) failed: %#x",
1506 MemInfo.BaseAddress, MemInfo.RegionSize, rcNt);
1507 }
1508 else
1509 {
1510 /* The Trend Micro sakfile.sys and Digital Guardian dgmaster.sys BSOD kludge. */
1511 SUP_DPRINTF(("supHardNtVpScanVirtualMemory: Replacing exec mem at %p (%p LB %#zx)\n",
1512 uPtrWhere, MemInfo.BaseAddress, MemInfo.RegionSize));
1513 void *pvCopy = RTMemAllocZ(cbFree);
1514 if (pvCopy)
1515 {
1516 rcNt = supHardNtVpReadMem(pThis->hProcess, (uintptr_t)pvFree, pvCopy, cbFree);
1517 if (!NT_SUCCESS(rcNt))
1518 supHardNtVpSetInfo2(pThis, VERR_SUP_VP_REPLACE_VIRTUAL_MEMORY_FAILED,
1519 "Error reading data from original alloc: %#x (%p LB %#zx)",
1520 rcNt, MemInfo.BaseAddress, MemInfo.RegionSize, rcNt);
1521
1522 rcNt = NtFreeVirtualMemory(pThis->hProcess, &pvFree, &cbFree, MEM_RELEASE);
1523 if (NT_SUCCESS(rcNt))
1524 {
1525 pvFree = MemInfo.BaseAddress; cbFree = MemInfo.RegionSize; /* fudge */
1526 NtFreeVirtualMemory(pThis->hProcess, &pvFree, &cbFree, MEM_RELEASE); /* fudge */
1527
1528 pvFree = MemInfo.BaseAddress;
1529 cbFree = MemInfo.RegionSize;
1530 rcNt = NtAllocateVirtualMemory(pThis->hProcess, &pvFree, 0, &cbFree, MEM_COMMIT, PAGE_READWRITE);
1531 if (!NT_SUCCESS(rcNt))
1532 supHardNtVpSetInfo2(pThis, VERR_SUP_VP_REPLACE_VIRTUAL_MEMORY_FAILED,
1533 "NtAllocateVirtualMemory (%p LB %#zx) failed with rcNt=%#x allocating "
1534 "replacement memory for working around buggy protection software. "
1535 "See VBoxStartup.log for more details",
1536 MemInfo.BaseAddress, MemInfo.RegionSize, rcNt);
1537 else if (pvFree != MemInfo.BaseAddress)
1538 supHardNtVpSetInfo2(pThis, VERR_SUP_VP_REPLACE_VIRTUAL_MEMORY_FAILED,
1539 "We wanted NtAllocateVirtualMemory to get us %p LB %#zx, but it returned %p LB %#zx.",
1540 MemInfo.BaseAddress, MemInfo.RegionSize, pvFree, cbFree, rcNt);
1541 else
1542 {
1543 SIZE_T cbWritten;
1544 rcNt = NtWriteVirtualMemory(pThis->hProcess, MemInfo.BaseAddress, pvCopy, MemInfo.RegionSize,
1545 &cbWritten);
1546 if (!NT_SUCCESS(rcNt))
1547 supHardNtVpSetInfo2(pThis, VERR_SUP_VP_FREE_VIRTUAL_MEMORY_FAILED,
1548 "NtWriteVirtualMemory (%p LB %#zx) failed: %#x",
1549 MemInfo.BaseAddress, MemInfo.RegionSize, rcNt);
1550 }
1551 }
1552 else
1553 supHardNtVpSetInfo2(pThis, VERR_SUP_VP_FREE_VIRTUAL_MEMORY_FAILED,
1554 "NtFreeVirtualMemory (%p LB %#zx) failed: %#x",
1555 MemInfo.BaseAddress, MemInfo.RegionSize, rcNt);
1556 RTMemFree(pvCopy);
1557 }
1558 else
1559 supHardNtVpSetInfo2(pThis, VERR_SUP_VP_FREE_VIRTUAL_MEMORY_FAILED,
1560 "RTMemAllocZ(%#zx) failed", MemInfo.RegionSize);
1561 }
1562 }
1563 /*
1564 * Unmap mapped memory, failing that, drop exec privileges.
1565 */
1566 else if (MemInfo.Type == MEM_MAPPED)
1567 {
1568 SUP_DPRINTF(("supHardNtVpScanVirtualMemory: Unmapping exec mem at %p (%p/%p LB %#zx)\n",
1569 uPtrWhere, MemInfo.AllocationBase, MemInfo.BaseAddress, MemInfo.RegionSize));
1570 rcNt = NtUnmapViewOfSection(pThis->hProcess, MemInfo.AllocationBase);
1571 if (!NT_SUCCESS(rcNt))
1572 {
1573 PVOID pvCopy = MemInfo.BaseAddress;
1574 SIZE_T cbCopy = MemInfo.RegionSize;
1575 NTSTATUS rcNt2 = NtProtectVirtualMemory(pThis->hProcess, &pvCopy, &cbCopy, PAGE_NOACCESS, NULL);
1576 if (!NT_SUCCESS(rcNt2))
1577 rcNt2 = NtProtectVirtualMemory(pThis->hProcess, &pvCopy, &cbCopy, PAGE_READONLY, NULL);
1578 if (!NT_SUCCESS(rcNt2))
1579 supHardNtVpSetInfo2(pThis, VERR_SUP_VP_UNMAP_AND_PROTECT_FAILED,
1580 "NtUnmapViewOfSection (%p/%p LB %#zx) failed: %#x (%#x)",
1581 MemInfo.AllocationBase, MemInfo.BaseAddress, MemInfo.RegionSize, rcNt, rcNt2);
1582 }
1583 }
1584 else
1585 supHardNtVpSetInfo2(pThis, VERR_SUP_VP_UNKOWN_MEM_TYPE,
1586 "Unknown executable memory type %#x at %p/%p LB %#zx",
1587 MemInfo.Type, MemInfo.AllocationBase, MemInfo.BaseAddress, MemInfo.RegionSize);
1588 pThis->cFixes++;
1589 }
1590 else
1591# endif /* IN_RING3 */
1592 supHardNtVpSetInfo2(pThis, VERR_SUP_VP_FOUND_EXEC_MEMORY,
1593 "Found executable memory at %p (%p LB %#zx): type=%#x prot=%#x state=%#x aprot=%#x abase=%p",
1594 uPtrWhere, MemInfo.BaseAddress, MemInfo.RegionSize, MemInfo.Type, MemInfo.Protect,
1595 MemInfo.State, MemInfo.AllocationBase, MemInfo.AllocationProtect);
1596
1597# ifndef IN_RING3
1598 if (RT_FAILURE(pThis->rcResult))
1599 return pThis->rcResult;
1600# endif
1601 /* Continue add more information about the problematic process. */
1602 }
1603#endif /* VBOX_PERMIT_VISUAL_STUDIO_PROFILING */
1604 else
1605 SUP_DPRINTF((MemInfo.AllocationBase == MemInfo.BaseAddress
1606 ? " *%p-%p %#06x/%#06x %#09x\n"
1607 : " %p-%p %#06x/%#06x %#09x\n",
1608 MemInfo.BaseAddress, (uintptr_t)MemInfo.BaseAddress - MemInfo.RegionSize - 1,
1609 MemInfo.Protect, MemInfo.AllocationProtect, MemInfo.Type));
1610
1611 /*
1612 * Advance.
1613 */
1614 cbAdvance = MemInfo.RegionSize;
1615 if (uPtrWhere + cbAdvance <= uPtrWhere)
1616 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_EMPTY_REGION_TOO_LARGE,
1617 "Empty region at %p.", uPtrWhere);
1618 uPtrWhere += MemInfo.RegionSize;
1619 }
1620
1621 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_TOO_MANY_MEMORY_REGIONS,
1622 "Too many virtual memory regions.\n");
1623}
1624
1625
1626/**
1627 * Verifies the loader image, i.e. check cryptographic signatures if present.
1628 *
1629 * @returns VBox status code.
1630 * @param pEntry The loader cache entry.
1631 * @param pwszName The filename to use in error messages.
1632 * @param pErRInfo Where to return extened error information.
1633 */
1634DECLHIDDEN(int) supHardNtLdrCacheEntryVerify(PSUPHNTLDRCACHEENTRY pEntry, PCRTUTF16 pwszName, PRTERRINFO pErrInfo)
1635{
1636 int rc = VINF_SUCCESS;
1637 if (!pEntry->fVerified)
1638 {
1639 rc = supHardenedWinVerifyImageByLdrMod(pEntry->hLdrMod, pwszName, pEntry->pNtViRdr,
1640 false /*fAvoidWinVerifyTrust*/, NULL /*pfWinVerifyTrust*/, pErrInfo);
1641 pEntry->fVerified = RT_SUCCESS(rc);
1642 }
1643 return rc;
1644}
1645
1646
1647/**
1648 * Allocates a image bits buffer and calls RTLdrGetBits on them.
1649 *
1650 * An assumption here is that there won't ever be concurrent use of the cache.
1651 * It's currently 104% single threaded, non-reentrant. Thus, we can't reuse the
1652 * pbBits allocation.
1653 *
1654 * @returns VBox status code
1655 * @param pEntry The loader cache entry.
1656 * @param ppbBits Where to return the pointer to the allocation.
1657 * @param uBaseAddress The image base address, see RTLdrGetBits.
1658 * @param pfnGetImport Import getter, see RTLdrGetBits.
1659 * @param pvUser The user argument for @a pfnGetImport.
1660 * @param pErrInfo Where to return extened error information.
1661 */
1662DECLHIDDEN(int) supHardNtLdrCacheEntryGetBits(PSUPHNTLDRCACHEENTRY pEntry, uint8_t **ppbBits,
1663 RTLDRADDR uBaseAddress, PFNRTLDRIMPORT pfnGetImport, void *pvUser,
1664 PRTERRINFO pErrInfo)
1665{
1666 int rc;
1667
1668 /*
1669 * First time around we have to allocate memory before we can get the image bits.
1670 */
1671 if (!pEntry->pbBits)
1672 {
1673 size_t cbBits = RTLdrSize(pEntry->hLdrMod);
1674 if (cbBits >= _1M*32U)
1675 return supHardNtVpSetInfo1(pErrInfo, VERR_SUP_VP_IMAGE_TOO_BIG, "Image %s is too large: %zu bytes (%#zx).",
1676 pEntry->pszName, cbBits, cbBits);
1677
1678 pEntry->pbBits = (uint8_t *)RTMemAllocZ(cbBits);
1679 if (!pEntry->pbBits)
1680 return supHardNtVpSetInfo1(pErrInfo, VERR_SUP_VP_NO_MEMORY, "Failed to allocate %zu bytes for image %s.",
1681 cbBits, pEntry->pszName);
1682
1683 pEntry->fValidBits = false; /* paranoia */
1684
1685 rc = RTLdrGetBits(pEntry->hLdrMod, pEntry->pbBits, uBaseAddress, pfnGetImport, pvUser);
1686 if (RT_FAILURE(rc))
1687 return supHardNtVpSetInfo1(pErrInfo, VERR_SUP_VP_NO_MEMORY, "RTLdrGetBits failed on image %s: %Rrc",
1688 pEntry->pszName, rc);
1689 pEntry->uImageBase = uBaseAddress;
1690 pEntry->fValidBits = pfnGetImport == NULL;
1691
1692 }
1693 /*
1694 * Cache hit? No?
1695 *
1696 * Note! We cannot currently cache image bits for images with imports as we
1697 * don't control the way they're resolved. Fortunately, NTDLL and
1698 * the VM process images all have no imports.
1699 */
1700 else if ( !pEntry->fValidBits
1701 || pEntry->uImageBase != uBaseAddress
1702 || pfnGetImport)
1703 {
1704 pEntry->fValidBits = false;
1705
1706 rc = RTLdrGetBits(pEntry->hLdrMod, pEntry->pbBits, uBaseAddress, pfnGetImport, pvUser);
1707 if (RT_FAILURE(rc))
1708 return supHardNtVpSetInfo1(pErrInfo, VERR_SUP_VP_NO_MEMORY, "RTLdrGetBits failed on image %s: %Rrc",
1709 pEntry->pszName, rc);
1710 pEntry->uImageBase = uBaseAddress;
1711 pEntry->fValidBits = pfnGetImport == NULL;
1712 }
1713
1714 *ppbBits = pEntry->pbBits;
1715 return VINF_SUCCESS;
1716}
1717
1718
1719/**
1720 * Frees all resources associated with a cache entry and wipes the members
1721 * clean.
1722 *
1723 * @param pEntry The entry to delete.
1724 */
1725static void supHardNTLdrCacheDeleteEntry(PSUPHNTLDRCACHEENTRY pEntry)
1726{
1727 if (pEntry->pbBits)
1728 {
1729 RTMemFree(pEntry->pbBits);
1730 pEntry->pbBits = NULL;
1731 }
1732
1733 if (pEntry->hLdrMod != NIL_RTLDRMOD)
1734 {
1735 RTLdrClose(pEntry->hLdrMod);
1736 pEntry->hLdrMod = NIL_RTLDRMOD;
1737 pEntry->pNtViRdr = NULL;
1738 }
1739 else if (pEntry->pNtViRdr)
1740 {
1741 pEntry->pNtViRdr->Core.pfnDestroy(&pEntry->pNtViRdr->Core);
1742 pEntry->pNtViRdr = NULL;
1743 }
1744
1745 if (pEntry->hFile)
1746 {
1747 NtClose(pEntry->hFile);
1748 pEntry->hFile = NULL;
1749 }
1750
1751 pEntry->pszName = NULL;
1752 pEntry->fVerified = false;
1753 pEntry->fValidBits = false;
1754 pEntry->uImageBase = 0;
1755}
1756
1757#ifdef IN_RING3
1758
1759/**
1760 * Flushes the cache.
1761 *
1762 * This is called from one of two points in the hardened main code, first is
1763 * after respawning and the second is when we open the vboxdrv device for
1764 * unrestricted access.
1765 */
1766DECLHIDDEN(void) supR3HardenedWinFlushLoaderCache(void)
1767{
1768 uint32_t i = g_cSupNtVpLdrCacheEntries;
1769 while (i-- > 0)
1770 supHardNTLdrCacheDeleteEntry(&g_aSupNtVpLdrCacheEntries[i]);
1771 g_cSupNtVpLdrCacheEntries = 0;
1772}
1773
1774
1775/**
1776 * Searches the cache for a loader image.
1777 *
1778 * @returns Pointer to the cache entry if found, NULL if not.
1779 * @param pszName The name (from g_apszSupNtVpAllowedVmExes or
1780 * g_apszSupNtVpAllowedDlls).
1781 */
1782static PSUPHNTLDRCACHEENTRY supHardNtLdrCacheLookupEntry(const char *pszName)
1783{
1784 /*
1785 * Since the caller is supplying us a pszName from one of the two tables,
1786 * we can dispense with string compare and simply compare string pointers.
1787 */
1788 uint32_t i = g_cSupNtVpLdrCacheEntries;
1789 while (i-- > 0)
1790 if (g_aSupNtVpLdrCacheEntries[i].pszName == pszName)
1791 return &g_aSupNtVpLdrCacheEntries[i];
1792 return NULL;
1793}
1794
1795#endif /* IN_RING3 */
1796
1797static int supHardNtLdrCacheNewEntry(PSUPHNTLDRCACHEENTRY pEntry, const char *pszName, PUNICODE_STRING pUniStrPath,
1798 bool fDll, bool f32bitResourceDll, PRTERRINFO pErrInfo)
1799{
1800 /*
1801 * Open the image file.
1802 */
1803 HANDLE hFile = RTNT_INVALID_HANDLE_VALUE;
1804 IO_STATUS_BLOCK Ios = RTNT_IO_STATUS_BLOCK_INITIALIZER;
1805
1806 OBJECT_ATTRIBUTES ObjAttr;
1807 InitializeObjectAttributes(&ObjAttr, pUniStrPath, OBJ_CASE_INSENSITIVE, NULL /*hRootDir*/, NULL /*pSecDesc*/);
1808#ifdef IN_RING0
1809 ObjAttr.Attributes |= OBJ_KERNEL_HANDLE;
1810#endif
1811
1812 NTSTATUS rcNt = NtCreateFile(&hFile,
1813 GENERIC_READ | SYNCHRONIZE,
1814 &ObjAttr,
1815 &Ios,
1816 NULL /* Allocation Size*/,
1817 FILE_ATTRIBUTE_NORMAL,
1818 FILE_SHARE_READ,
1819 FILE_OPEN,
1820 FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT,
1821 NULL /*EaBuffer*/,
1822 0 /*EaLength*/);
1823 if (NT_SUCCESS(rcNt))
1824 rcNt = Ios.Status;
1825 if (!NT_SUCCESS(rcNt))
1826 return supHardNtVpSetInfo1(pErrInfo, VERR_SUP_VP_IMAGE_FILE_OPEN_ERROR,
1827 "Error opening image for scanning: %#x (name %ls)", rcNt, pUniStrPath->Buffer);
1828
1829 /*
1830 * Figure out validation flags we'll be using and create the reader
1831 * for this image.
1832 */
1833 uint32_t fFlags = fDll
1834 ? SUPHNTVI_F_TRUSTED_INSTALLER_OWNER | SUPHNTVI_F_ALLOW_CAT_FILE_VERIFICATION
1835 : SUPHNTVI_F_REQUIRE_BUILD_CERT;
1836 if (f32bitResourceDll)
1837 fFlags |= SUPHNTVI_F_RESOURCE_IMAGE;
1838
1839 PSUPHNTVIRDR pNtViRdr;
1840 int rc = supHardNtViRdrCreate(hFile, pUniStrPath->Buffer, fFlags, &pNtViRdr);
1841 if (RT_FAILURE(rc))
1842 {
1843 NtClose(hFile);
1844 return rc;
1845 }
1846
1847 /*
1848 * Finally, open the image with the loader
1849 */
1850 RTLDRMOD hLdrMod;
1851 RTLDRARCH enmArch = fFlags & SUPHNTVI_F_RC_IMAGE ? RTLDRARCH_X86_32 : RTLDRARCH_HOST;
1852 if (fFlags & SUPHNTVI_F_RESOURCE_IMAGE)
1853 enmArch = RTLDRARCH_WHATEVER;
1854 rc = RTLdrOpenWithReader(&pNtViRdr->Core, RTLDR_O_FOR_VALIDATION, enmArch, &hLdrMod, pErrInfo);
1855 if (RT_FAILURE(rc))
1856 return supHardNtVpSetInfo1(pErrInfo, rc, "RTLdrOpenWithReader failed: %Rrc (Image='%ls').",
1857 rc, pUniStrPath->Buffer);
1858
1859 /*
1860 * Fill in the cache entry.
1861 */
1862 pEntry->pszName = pszName;
1863 pEntry->hLdrMod = hLdrMod;
1864 pEntry->pNtViRdr = pNtViRdr;
1865 pEntry->hFile = hFile;
1866 pEntry->pbBits = NULL;
1867 pEntry->fVerified = false;
1868 pEntry->fValidBits = false;
1869 pEntry->uImageBase = ~(uintptr_t)0;
1870
1871#ifdef IN_SUP_HARDENED_R3
1872 /*
1873 * Log the image timestamp when in the hardened exe.
1874 */
1875 uint64_t uTimestamp = 0;
1876 rc = RTLdrQueryProp(hLdrMod, RTLDRPROP_TIMESTAMP_SECONDS, &uTimestamp, sizeof(uint64_t));
1877 SUP_DPRINTF(("%s: timestamp %#llx (rc=%Rrc)\n", pszName, uTimestamp, rc));
1878#endif
1879
1880 return VINF_SUCCESS;
1881}
1882
1883#ifdef IN_RING3
1884/**
1885 * Opens a loader cache entry.
1886 *
1887 * Currently this is only used by the import code for getting NTDLL.
1888 *
1889 * @returns VBox status code.
1890 * @param pszName The DLL name. Must be one from the
1891 * g_apszSupNtVpAllowedDlls array.
1892 * @param ppEntry Where to return the entry we've opened/found.
1893 */
1894DECLHIDDEN(int) supHardNtLdrCacheOpen(const char *pszName, PSUPHNTLDRCACHEENTRY *ppEntry)
1895{
1896 /*
1897 * Locate the dll.
1898 */
1899 uint32_t i = 0;
1900 while ( i < RT_ELEMENTS(g_apszSupNtVpAllowedDlls)
1901 && strcmp(pszName, g_apszSupNtVpAllowedDlls[i]))
1902 i++;
1903 if (i >= RT_ELEMENTS(g_apszSupNtVpAllowedDlls))
1904 return VERR_FILE_NOT_FOUND;
1905 pszName = g_apszSupNtVpAllowedDlls[i];
1906
1907 /*
1908 * Try the cache.
1909 */
1910 *ppEntry = supHardNtLdrCacheLookupEntry(pszName);
1911 if (*ppEntry)
1912 return VINF_SUCCESS;
1913
1914 /*
1915 * Not in the cache, so open it.
1916 * Note! We cannot assume that g_System32NtPath has been initialized at this point.
1917 */
1918 if (g_cSupNtVpLdrCacheEntries >= RT_ELEMENTS(g_aSupNtVpLdrCacheEntries))
1919 return VERR_INTERNAL_ERROR_3;
1920
1921 static WCHAR s_wszSystem32[] = L"\\SystemRoot\\System32\\";
1922 WCHAR wszPath[64];
1923 memcpy(wszPath, s_wszSystem32, sizeof(s_wszSystem32));
1924 RTUtf16CatAscii(wszPath, sizeof(wszPath), pszName);
1925
1926 UNICODE_STRING UniStr;
1927 UniStr.Buffer = wszPath;
1928 UniStr.Length = (USHORT)(RTUtf16Len(wszPath) * sizeof(WCHAR));
1929 UniStr.MaximumLength = UniStr.Length + sizeof(WCHAR);
1930
1931 int rc = supHardNtLdrCacheNewEntry(&g_aSupNtVpLdrCacheEntries[g_cSupNtVpLdrCacheEntries], pszName, &UniStr,
1932 true /*fDll*/, false /*f32bitResourceDll*/, NULL /*pErrInfo*/);
1933 if (RT_SUCCESS(rc))
1934 {
1935 *ppEntry = &g_aSupNtVpLdrCacheEntries[g_cSupNtVpLdrCacheEntries];
1936 g_cSupNtVpLdrCacheEntries++;
1937 return VINF_SUCCESS;
1938 }
1939 return rc;
1940}
1941#endif /* IN_RING3 */
1942
1943
1944/**
1945 * Opens all the images with the IPRT loader, setting both, hFile, pNtViRdr and
1946 * hLdrMod for each image.
1947 *
1948 * @returns VBox status code.
1949 * @param pThis The process scanning state structure.
1950 */
1951static int supHardNtVpOpenImages(PSUPHNTVPSTATE pThis)
1952{
1953 unsigned i = pThis->cImages;
1954 while (i-- > 0)
1955 {
1956 PSUPHNTVPIMAGE pImage = &pThis->aImages[i];
1957
1958#ifdef IN_RING3
1959 /*
1960 * Try the cache first.
1961 */
1962 pImage->pCacheEntry = supHardNtLdrCacheLookupEntry(pImage->pszName);
1963 if (pImage->pCacheEntry)
1964 continue;
1965
1966 /*
1967 * Not in the cache, so load it into the cache.
1968 */
1969 if (g_cSupNtVpLdrCacheEntries >= RT_ELEMENTS(g_aSupNtVpLdrCacheEntries))
1970 return supHardNtVpSetInfo2(pThis, VERR_INTERNAL_ERROR_3, "Loader cache overflow.");
1971 pImage->pCacheEntry = &g_aSupNtVpLdrCacheEntries[g_cSupNtVpLdrCacheEntries];
1972#else
1973 /*
1974 * In ring-0 we don't have a cache at the moment (resource reasons), so
1975 * we have a static cache entry in each image structure that we use instead.
1976 */
1977 pImage->pCacheEntry = &pImage->CacheEntry;
1978#endif
1979
1980 int rc = supHardNtLdrCacheNewEntry(pImage->pCacheEntry, pImage->pszName, &pImage->Name.UniStr,
1981 pImage->fDll, pImage->f32bitResourceDll, pThis->pErrInfo);
1982 if (RT_FAILURE(rc))
1983 return rc;
1984#ifdef IN_RING3
1985 g_cSupNtVpLdrCacheEntries++;
1986#endif
1987 }
1988
1989 return VINF_SUCCESS;
1990}
1991
1992
1993/**
1994 * Check the integrity of the executable of the process.
1995 *
1996 * @returns VBox status code.
1997 * @param pThis The process scanning state structure. Details
1998 * about images are added to this.
1999 * @param hProcess The process to verify.
2000 */
2001static int supHardNtVpCheckExe(PSUPHNTVPSTATE pThis, HANDLE hProcess)
2002{
2003 /*
2004 * Make sure there is exactly one executable image.
2005 */
2006 unsigned cExecs = 0;
2007 unsigned iExe = ~0U;
2008 unsigned i = pThis->cImages;
2009 while (i-- > 0)
2010 {
2011 if (!pThis->aImages[i].fDll)
2012 {
2013 cExecs++;
2014 iExe = i;
2015 }
2016 }
2017 if (cExecs == 0)
2018 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_NO_FOUND_NO_EXE_MAPPING,
2019 "No executable mapping found in the virtual address space.");
2020 if (cExecs != 1)
2021 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_FOUND_MORE_THAN_ONE_EXE_MAPPING,
2022 "Found more than one executable mapping in the virtual address space.");
2023 PSUPHNTVPIMAGE pImage = &pThis->aImages[iExe];
2024
2025 /*
2026 * Check that it matches the executable image of the process.
2027 */
2028 int rc;
2029 ULONG cbUniStr = sizeof(UNICODE_STRING) + RTPATH_MAX * sizeof(RTUTF16);
2030 PUNICODE_STRING pUniStr = (PUNICODE_STRING)RTMemAllocZ(cbUniStr);
2031 if (!pUniStr)
2032 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_NO_MEMORY,
2033 "Error allocating %zu bytes for process name.", cbUniStr);
2034 ULONG cbIgn = 0;
2035 NTSTATUS rcNt = NtQueryInformationProcess(hProcess, ProcessImageFileName, pUniStr, cbUniStr - sizeof(WCHAR), &cbIgn);
2036 if (NT_SUCCESS(rcNt))
2037 {
2038 if (supHardNtVpAreUniStringsEqual(pUniStr, &pImage->Name.UniStr))
2039 rc = VINF_SUCCESS;
2040 else
2041 {
2042 pUniStr->Buffer[pUniStr->Length / sizeof(WCHAR)] = '\0';
2043 rc = supHardNtVpSetInfo2(pThis, VERR_SUP_VP_EXE_VS_PROC_NAME_MISMATCH,
2044 "Process image name does not match the exectuable we found: %ls vs %ls.",
2045 pUniStr->Buffer, pImage->Name.UniStr.Buffer);
2046 }
2047 }
2048 else
2049 rc = supHardNtVpSetInfo2(pThis, VERR_SUP_VP_NT_QI_PROCESS_NM_ERROR,
2050 "NtQueryInformationProcess/ProcessImageFileName failed: %#x", rcNt);
2051 RTMemFree(pUniStr);
2052 if (RT_FAILURE(rc))
2053 return rc;
2054
2055 /*
2056 * Validate the signing of the executable image.
2057 * This will load the fDllCharecteristics and fImageCharecteristics members we use below.
2058 */
2059 rc = supHardNtVpVerifyImage(pThis, pImage, hProcess);
2060 if (RT_FAILURE(rc))
2061 return rc;
2062
2063 /*
2064 * Check linking requirements.
2065 * This query is only available using the current process pseudo handle on
2066 * older windows versions. The cut-off seems to be Vista.
2067 */
2068 SECTION_IMAGE_INFORMATION ImageInfo;
2069 rcNt = NtQueryInformationProcess(hProcess, ProcessImageInformation, &ImageInfo, sizeof(ImageInfo), NULL);
2070 if (!NT_SUCCESS(rcNt))
2071 {
2072 if ( rcNt == STATUS_INVALID_PARAMETER
2073 && g_uNtVerCombined < SUP_NT_VER_VISTA
2074 && hProcess != NtCurrentProcess() )
2075 return VINF_SUCCESS;
2076 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_NT_QI_PROCESS_IMG_INFO_ERROR,
2077 "NtQueryInformationProcess/ProcessImageInformation failed: %#x hProcess=%#x", rcNt, hProcess);
2078 }
2079 if ( !(ImageInfo.DllCharacteristics & IMAGE_DLLCHARACTERISTICS_FORCE_INTEGRITY))
2080 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_EXE_MISSING_FORCE_INTEGRITY,
2081 "EXE DllCharacteristics=%#x, expected IMAGE_DLLCHARACTERISTICS_FORCE_INTEGRITY to be set.",
2082 ImageInfo.DllCharacteristics);
2083 if (!(ImageInfo.DllCharacteristics & IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE))
2084 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_EXE_MISSING_DYNAMIC_BASE,
2085 "EXE DllCharacteristics=%#x, expected IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE to be set.",
2086 ImageInfo.DllCharacteristics);
2087 if (!(ImageInfo.DllCharacteristics & IMAGE_DLLCHARACTERISTICS_NX_COMPAT))
2088 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_EXE_MISSING_NX_COMPAT,
2089 "EXE DllCharacteristics=%#x, expected IMAGE_DLLCHARACTERISTICS_NX_COMPAT to be set.",
2090 ImageInfo.DllCharacteristics);
2091
2092 if (pImage->fDllCharecteristics != ImageInfo.DllCharacteristics)
2093 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_DLL_CHARECTERISTICS_MISMATCH,
2094 "EXE Info.DllCharacteristics=%#x fDllCharecteristics=%#x.",
2095 ImageInfo.DllCharacteristics, pImage->fDllCharecteristics);
2096
2097 if (pImage->fImageCharecteristics != ImageInfo.ImageCharacteristics)
2098 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_DLL_CHARECTERISTICS_MISMATCH,
2099 "EXE Info.ImageCharacteristics=%#x fImageCharecteristics=%#x.",
2100 ImageInfo.ImageCharacteristics, pImage->fImageCharecteristics);
2101
2102 return VINF_SUCCESS;
2103}
2104
2105
2106/**
2107 * Check the integrity of the DLLs found in the process.
2108 *
2109 * @returns VBox status code.
2110 * @param pThis The process scanning state structure. Details
2111 * about images are added to this.
2112 * @param hProcess The process to verify.
2113 */
2114static int supHardNtVpCheckDlls(PSUPHNTVPSTATE pThis, HANDLE hProcess)
2115{
2116 /*
2117 * Check for duplicate entries (paranoia).
2118 */
2119 uint32_t i = pThis->cImages;
2120 while (i-- > 1)
2121 {
2122 const char *pszName = pThis->aImages[i].pszName;
2123 uint32_t j = i;
2124 while (j-- > 0)
2125 if (pThis->aImages[j].pszName == pszName)
2126 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_DUPLICATE_DLL_MAPPING,
2127 "Duplicate image entries for %s: %ls and %ls",
2128 pszName, pThis->aImages[i].Name.UniStr.Buffer, pThis->aImages[j].Name.UniStr.Buffer);
2129 }
2130
2131 /*
2132 * Check that both ntdll and kernel32 are present.
2133 * ASSUMES the entries in g_apszSupNtVpAllowedDlls are all lower case.
2134 */
2135 uint32_t iNtDll = UINT32_MAX;
2136 uint32_t iKernel32 = UINT32_MAX;
2137 i = pThis->cImages;
2138 while (i-- > 0)
2139 if (suplibHardenedStrCmp(pThis->aImages[i].pszName, "ntdll.dll") == 0)
2140 iNtDll = i;
2141 else if (suplibHardenedStrCmp(pThis->aImages[i].pszName, "kernel32.dll") == 0)
2142 iKernel32 = i;
2143 if (iNtDll == UINT32_MAX)
2144 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_NO_NTDLL_MAPPING,
2145 "The process has no NTDLL.DLL.");
2146 if (iKernel32 == UINT32_MAX && pThis->enmKind == SUPHARDNTVPKIND_SELF_PURIFICATION)
2147 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_NO_KERNEL32_MAPPING,
2148 "The process has no KERNEL32.DLL.");
2149 else if (iKernel32 != UINT32_MAX && pThis->enmKind == SUPHARDNTVPKIND_CHILD_PURIFICATION)
2150 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_KERNEL32_ALREADY_MAPPED,
2151 "The process already has KERNEL32.DLL loaded.");
2152
2153 /*
2154 * Verify that the DLLs are correctly signed (by MS).
2155 */
2156 i = pThis->cImages;
2157 while (i-- > 0)
2158 {
2159 int rc = supHardNtVpVerifyImage(pThis, &pThis->aImages[i], hProcess);
2160 if (RT_FAILURE(rc))
2161 return rc;
2162 }
2163
2164 return VINF_SUCCESS;
2165}
2166
2167
2168/**
2169 * Verifies the given process.
2170 *
2171 * The following requirements are checked:
2172 * - The process only has one thread, the calling thread.
2173 * - The process has no debugger attached.
2174 * - The executable image of the process is verified to be signed with
2175 * certificate known to this code at build time.
2176 * - The executable image is one of a predefined set.
2177 * - The process has only a very limited set of system DLLs loaded.
2178 * - The system DLLs signatures check out fine.
2179 * - The only executable memory in the process belongs to the system DLLs and
2180 * the executable image.
2181 *
2182 * @returns VBox status code.
2183 * @param hProcess The process to verify.
2184 * @param hThread A thread in the process (the caller).
2185 * @param enmKind The kind of process verification to perform.
2186 * @param fFlags Valid combination of SUPHARDNTVP_F_XXX flags.
2187 * @param pErrInfo Pointer to error info structure. Optional.
2188 * @param pcFixes Where to return the number of fixes made during
2189 * purification. Optional.
2190 */
2191DECLHIDDEN(int) supHardenedWinVerifyProcess(HANDLE hProcess, HANDLE hThread, SUPHARDNTVPKIND enmKind, uint32_t fFlags,
2192 uint32_t *pcFixes, PRTERRINFO pErrInfo)
2193{
2194 if (pcFixes)
2195 *pcFixes = 0;
2196
2197 /*
2198 * Some basic checks regarding threads and debuggers. We don't need
2199 * allocate any state memory for these.
2200 */
2201 int rc = VINF_SUCCESS;
2202 if (enmKind != SUPHARDNTVPKIND_CHILD_PURIFICATION)
2203 rc = supHardNtVpThread(hProcess, hThread, pErrInfo);
2204 if (RT_SUCCESS(rc))
2205 rc = supHardNtVpDebugger(hProcess, pErrInfo);
2206 if (RT_SUCCESS(rc))
2207 {
2208 /*
2209 * Allocate and initialize memory for the state.
2210 */
2211 PSUPHNTVPSTATE pThis = (PSUPHNTVPSTATE)RTMemAllocZ(sizeof(*pThis));
2212 if (pThis)
2213 {
2214 pThis->enmKind = enmKind;
2215 pThis->fFlags = fFlags;
2216 pThis->rcResult = VINF_SUCCESS;
2217 pThis->hProcess = hProcess;
2218 pThis->pErrInfo = pErrInfo;
2219
2220 /*
2221 * Perform the verification.
2222 */
2223 rc = supHardNtVpScanVirtualMemory(pThis, hProcess);
2224 if (RT_SUCCESS(rc))
2225 rc = supHardNtVpOpenImages(pThis);
2226 if (RT_SUCCESS(rc))
2227 rc = supHardNtVpCheckExe(pThis, hProcess);
2228 if (RT_SUCCESS(rc))
2229 rc = supHardNtVpCheckDlls(pThis, hProcess);
2230
2231 if (pcFixes)
2232 *pcFixes = pThis->cFixes;
2233
2234 /*
2235 * Clean up the state.
2236 */
2237#ifdef IN_RING0
2238 for (uint32_t i = 0; i < pThis->cImages; i++)
2239 supHardNTLdrCacheDeleteEntry(&pThis->aImages[i].CacheEntry);
2240#endif
2241 RTMemFree(pThis);
2242 }
2243 else
2244 rc = supHardNtVpSetInfo1(pErrInfo, VERR_SUP_VP_NO_MEMORY_STATE,
2245 "Failed to allocate %zu bytes for state structures.", sizeof(*pThis));
2246 }
2247 return rc;
2248}
2249
Note: See TracBrowser for help on using the repository browser.

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