VirtualBox

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

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

supHardNtVpFreeOrReplacePrivateExecMemory: Bugfix.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 104.2 KB
Line 
1/* $Id: SUPHardenedVerifyProcess-win.cpp 55026 2015-03-31 11:25:29Z 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 "tstRTR0ThreadPreemptionDriver.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 * Checks whether the path could be containing alternative 8.3 names generated
1093 * by NTFS, FAT, or other similar file systems.
1094 *
1095 * @returns Pointer to the first component that might be an 8.3 name, NULL if
1096 * not 8.3 path.
1097 * @param pwszPath The path to check.
1098 *
1099 * @remarks This is making bad ASSUMPTION wrt to the naming scheme of 8.3 names,
1100 * however, non-tilde 8.3 aliases are probably rare enough to not be
1101 * worth all the extra code necessary to open each path component and
1102 * check if we've got the short name or not.
1103 */
1104DECLHIDDEN(PRTUTF16) supHardNtVpIsPossible8dot3Path(PCRTUTF16 pwszPath)
1105{
1106 PCRTUTF16 pwszName = pwszPath;
1107 for (;;)
1108 {
1109 RTUTF16 wc = *pwszPath++;
1110 if (wc == '~')
1111 {
1112 /* Could check more here before jumping to conclusions... */
1113 if (pwszPath - pwszName <= 8+1+3)
1114 return (PRTUTF16)pwszName;
1115 }
1116 else if (wc == '\\' || wc == '/' || wc == ':')
1117 pwszName = pwszPath;
1118 else if (wc == 0)
1119 break;
1120 }
1121 return NULL;
1122}
1123
1124
1125/**
1126 * Fixes up a path possibly containing one or more alternative 8-dot-3 style
1127 * components.
1128 *
1129 * The path is fixed up in place. Errors are ignored.
1130 *
1131 * @param pUniStr The path to fix up. MaximumLength is the max buffer
1132 * length.
1133 */
1134DECLHIDDEN(void) supHardNtVpFix8dot3Path(PUNICODE_STRING pUniStr, bool fPathOnly)
1135{
1136 /*
1137 * We could use FileNormalizedNameInformation here and slap the volume device
1138 * path in front of the result, but it's only supported since windows 8.0
1139 * according to some docs... So we expand all supicious names.
1140 */
1141 union fix8dot3tmp
1142 {
1143 FILE_BOTH_DIR_INFORMATION Info;
1144 uint8_t abBuffer[sizeof(FILE_BOTH_DIR_INFORMATION) + 2048 * sizeof(WCHAR)];
1145 } *puBuf = NULL;
1146
1147
1148 PRTUTF16 pwszFix = pUniStr->Buffer;
1149 while (*pwszFix)
1150 {
1151 pwszFix = supHardNtVpIsPossible8dot3Path(pwszFix);
1152 if (pwszFix == NULL)
1153 break;
1154
1155 RTUTF16 wc;
1156 PRTUTF16 pwszFixEnd = pwszFix;
1157 while ((wc = *pwszFixEnd) != '\0' && wc != '\\' && wc != '/')
1158 pwszFixEnd++;
1159 if (wc == '\0' && fPathOnly)
1160 break;
1161
1162 if (!puBuf)
1163 {
1164 puBuf = (union fix8dot3tmp *)RTMemAlloc(sizeof(*puBuf));
1165 if (!puBuf)
1166 break;
1167 }
1168
1169 RTUTF16 const wcSaved = *pwszFix;
1170 *pwszFix = '\0'; /* paranoia. */
1171
1172 UNICODE_STRING NtDir;
1173 NtDir.Buffer = pUniStr->Buffer;
1174 NtDir.Length = NtDir.MaximumLength = (USHORT)((pwszFix - pUniStr->Buffer) * sizeof(WCHAR));
1175
1176 HANDLE hDir = RTNT_INVALID_HANDLE_VALUE;
1177 IO_STATUS_BLOCK Ios = RTNT_IO_STATUS_BLOCK_INITIALIZER;
1178
1179 OBJECT_ATTRIBUTES ObjAttr;
1180 InitializeObjectAttributes(&ObjAttr, &NtDir, OBJ_CASE_INSENSITIVE, NULL /*hRootDir*/, NULL /*pSecDesc*/);
1181#ifdef IN_RING0
1182 ObjAttr.Attributes |= OBJ_KERNEL_HANDLE;
1183#endif
1184
1185 NTSTATUS rcNt = NtCreateFile(&hDir,
1186 FILE_READ_DATA | SYNCHRONIZE,
1187 &ObjAttr,
1188 &Ios,
1189 NULL /* Allocation Size*/,
1190 FILE_ATTRIBUTE_NORMAL,
1191 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
1192 FILE_OPEN,
1193 FILE_DIRECTORY_FILE | FILE_OPEN_FOR_BACKUP_INTENT | FILE_SYNCHRONOUS_IO_NONALERT,
1194 NULL /*EaBuffer*/,
1195 0 /*EaLength*/);
1196 *pwszFix = wcSaved;
1197 if (NT_SUCCESS(rcNt))
1198 {
1199 RT_ZERO(*puBuf);
1200
1201 IO_STATUS_BLOCK Ios = RTNT_IO_STATUS_BLOCK_INITIALIZER;
1202 UNICODE_STRING NtFilterStr;
1203 NtFilterStr.Buffer = pwszFix;
1204 NtFilterStr.Length = (USHORT)((uintptr_t)pwszFixEnd - (uintptr_t)pwszFix);
1205 NtFilterStr.MaximumLength = NtFilterStr.Length;
1206 rcNt = NtQueryDirectoryFile(hDir,
1207 NULL /* Event */,
1208 NULL /* ApcRoutine */,
1209 NULL /* ApcContext */,
1210 &Ios,
1211 puBuf,
1212 sizeof(*puBuf) - sizeof(WCHAR),
1213 FileBothDirectoryInformation,
1214 FALSE /*ReturnSingleEntry*/,
1215 &NtFilterStr,
1216 FALSE /*RestartScan */);
1217 if (NT_SUCCESS(rcNt) && puBuf->Info.NextEntryOffset == 0) /* There shall only be one entry matching... */
1218 {
1219 uint32_t offName = puBuf->Info.FileNameLength / sizeof(WCHAR);
1220 while (offName > 0 && puBuf->Info.FileName[offName - 1] != '\\' && puBuf->Info.FileName[offName - 1] != '/')
1221 offName--;
1222 uint32_t cwcNameNew = (puBuf->Info.FileNameLength / sizeof(WCHAR)) - offName;
1223 uint32_t cwcNameOld = (uint32_t)(pwszFixEnd - pwszFix);
1224
1225 if (cwcNameOld == cwcNameNew)
1226 memcpy(pwszFix, &puBuf->Info.FileName[offName], cwcNameNew * sizeof(WCHAR));
1227 else if ( pUniStr->Length + cwcNameNew * sizeof(WCHAR) - cwcNameOld * sizeof(WCHAR) + sizeof(WCHAR)
1228 <= pUniStr->MaximumLength)
1229 {
1230 size_t cwcLeft = pUniStr->Length - (pwszFixEnd - pUniStr->Buffer) * sizeof(WCHAR) + sizeof(WCHAR);
1231 memmove(&pwszFix[cwcNameNew], pwszFixEnd, cwcLeft * sizeof(WCHAR));
1232 pUniStr->Length -= (USHORT)(cwcNameOld * sizeof(WCHAR));
1233 pUniStr->Length += (USHORT)(cwcNameNew * sizeof(WCHAR));
1234 pwszFixEnd -= cwcNameOld;
1235 pwszFixEnd -= cwcNameNew;
1236 memcpy(pwszFix, &puBuf->Info.FileName[offName], cwcNameNew * sizeof(WCHAR));
1237 }
1238 /* else: ignore overflow. */
1239 }
1240 /* else: ignore failure. */
1241
1242 NtClose(hDir);
1243 }
1244
1245 /* Advance */
1246 pwszFix = pwszFixEnd;
1247 }
1248
1249 if (puBuf)
1250 RTMemFree(puBuf);
1251}
1252
1253
1254
1255/**
1256 * Matches two UNICODE_STRING structures in a case sensitive fashion.
1257 *
1258 * @returns true if equal, false if not.
1259 * @param pUniStr1 The first unicode string.
1260 * @param pUniStr2 The first unicode string.
1261 */
1262static bool supHardNtVpAreUniStringsEqual(PCUNICODE_STRING pUniStr1, PCUNICODE_STRING pUniStr2)
1263{
1264 if (pUniStr1->Length != pUniStr2->Length)
1265 return false;
1266 return suplibHardenedMemComp(pUniStr1->Buffer, pUniStr2->Buffer, pUniStr1->Length) == 0;
1267}
1268
1269
1270/**
1271 * Performs a case insensitive comparison of an ASCII and an UTF-16 file name.
1272 *
1273 * @returns true / false
1274 * @param pszName1 The ASCII name.
1275 * @param pwszName2 The UTF-16 name.
1276 */
1277static bool supHardNtVpAreNamesEqual(const char *pszName1, PCRTUTF16 pwszName2)
1278{
1279 for (;;)
1280 {
1281 char ch1 = *pszName1++;
1282 RTUTF16 wc2 = *pwszName2++;
1283 if (ch1 != wc2)
1284 {
1285 ch1 = RT_C_TO_LOWER(ch1);
1286 wc2 = wc2 < 0x80 ? RT_C_TO_LOWER(wc2) : wc2;
1287 if (ch1 != wc2)
1288 return false;
1289 }
1290 if (!ch1)
1291 return true;
1292 }
1293}
1294
1295
1296/**
1297 * Records an additional memory region for an image.
1298 *
1299 * May trash pThis->abMemory.
1300 *
1301 * @returns VBox status code.
1302 * @retval VINF_OBJECT_DESTROYED if we've unmapped the image (child
1303 * purification only).
1304 * @param pThis The process scanning state structure.
1305 * @param pImage The new image structure. Only the unicode name
1306 * buffer is valid (it's zero-terminated).
1307 * @param pMemInfo The memory information for the image.
1308 */
1309static int supHardNtVpNewImage(PSUPHNTVPSTATE pThis, PSUPHNTVPIMAGE pImage, PMEMORY_BASIC_INFORMATION pMemInfo)
1310{
1311 /*
1312 * If the filename or path contains short names, we have to get the long
1313 * path so that we will recognize the DLLs and their location.
1314 */
1315 PUNICODE_STRING pLongName = &pImage->Name.UniStr;
1316 if (supHardNtVpIsPossible8dot3Path(pLongName->Buffer))
1317 {
1318 AssertCompile(sizeof(pThis->abMemory) > sizeof(pImage->Name));
1319 PUNICODE_STRING pTmp = (PUNICODE_STRING)pThis->abMemory;
1320 pTmp->MaximumLength = (USHORT)RT_MIN(_64K - 1, sizeof(pThis->abMemory) - sizeof(*pTmp)) - sizeof(RTUTF16);
1321 pTmp->Length = pImage->Name.UniStr.Length;
1322 pTmp->Buffer = (PRTUTF16)(pTmp + 1);
1323 memcpy(pTmp->Buffer, pLongName->Buffer, pLongName->Length + sizeof(RTUTF16));
1324
1325 supHardNtVpFix8dot3Path(pTmp, false /*fPathOnly*/);
1326 Assert(pTmp->Buffer[pTmp->Length / sizeof(RTUTF16)] == '\0');
1327
1328 pLongName = pTmp;
1329 }
1330
1331 /*
1332 * Extract the final component.
1333 */
1334 RTUTF16 wc;
1335 unsigned cwcDirName = pLongName->Length / sizeof(WCHAR);
1336 PCRTUTF16 pwcDirName = &pLongName->Buffer[cwcDirName];
1337 PCRTUTF16 pwszFilename = &pLongName->Buffer[cwcDirName];
1338 while ( cwcDirName > 0
1339 && (wc = pwszFilename[-1]) != '\\'
1340 && wc != '/'
1341 && wc != ':')
1342 {
1343 pwszFilename--;
1344 cwcDirName--;
1345 }
1346 if (!*pwszFilename)
1347 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_NO_IMAGE_MAPPING_NAME,
1348 "Empty filename (len=%u) for image at %p.", pLongName->Length, pMemInfo->BaseAddress);
1349
1350 /*
1351 * Drop trailing slashes from the directory name.
1352 */
1353 while ( cwcDirName > 0
1354 && ( pLongName->Buffer[cwcDirName - 1] == '\\'
1355 || pLongName->Buffer[cwcDirName - 1] == '/'))
1356 cwcDirName--;
1357
1358 /*
1359 * Match it against known DLLs.
1360 */
1361 pImage->pszName = NULL;
1362 for (uint32_t i = 0; i < RT_ELEMENTS(g_apszSupNtVpAllowedDlls); i++)
1363 if (supHardNtVpAreNamesEqual(g_apszSupNtVpAllowedDlls[i], pwszFilename))
1364 {
1365 pImage->pszName = g_apszSupNtVpAllowedDlls[i];
1366 pImage->fDll = true;
1367
1368#ifndef VBOX_PERMIT_VISUAL_STUDIO_PROFILING
1369 /* The directory name must match the one we've got for System32. */
1370 if ( ( cwcDirName * sizeof(WCHAR) != g_System32NtPath.UniStr.Length
1371 || suplibHardenedMemComp(pLongName->Buffer, g_System32NtPath.UniStr.Buffer, cwcDirName * sizeof(WCHAR)) )
1372# ifdef VBOX_PERMIT_MORE
1373 && ( pImage->pszName[0] != 'a'
1374 || pImage->pszName[1] != 'c'
1375 || !supHardViIsAppPatchDir(pLongName->Buffer, pLongName->Length / sizeof(WCHAR)) )
1376# endif
1377 )
1378 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_NON_SYSTEM32_DLL,
1379 "Expected %ls to be loaded from %ls.",
1380 pLongName->Buffer, g_System32NtPath.UniStr.Buffer);
1381# ifdef VBOX_PERMIT_MORE
1382 if (g_uNtVerCombined < SUP_NT_VER_W70 && i >= VBOX_PERMIT_MORE_FIRST_IDX)
1383 pImage->pszName = NULL; /* hard limit: user32.dll is unwanted prior to w7. */
1384# endif
1385
1386#endif /* VBOX_PERMIT_VISUAL_STUDIO_PROFILING */
1387 break;
1388 }
1389 if (!pImage->pszName)
1390 {
1391 /*
1392 * Not a known DLL, is it a known executable?
1393 */
1394 for (uint32_t i = 0; i < RT_ELEMENTS(g_apszSupNtVpAllowedVmExes); i++)
1395 if (supHardNtVpAreNamesEqual(g_apszSupNtVpAllowedVmExes[i], pwszFilename))
1396 {
1397 pImage->pszName = g_apszSupNtVpAllowedVmExes[i];
1398 pImage->fDll = false;
1399 break;
1400 }
1401 }
1402 if (!pImage->pszName)
1403 {
1404 /*
1405 * Unknown image.
1406 *
1407 * If we're cleaning up a child process, we can unmap the offending
1408 * DLL... Might have interesting side effects, or at least interesting
1409 * as in "may you live in interesting times".
1410 */
1411#ifdef IN_RING3
1412 if ( pMemInfo->AllocationBase == pMemInfo->BaseAddress
1413 && pThis->enmKind == SUPHARDNTVPKIND_CHILD_PURIFICATION)
1414 {
1415 SUP_DPRINTF(("supHardNtVpScanVirtualMemory: Unmapping image mem at %p (%p LB %#zx) - '%ls'\n",
1416 pMemInfo->AllocationBase, pMemInfo->BaseAddress, pMemInfo->RegionSize, pwszFilename));
1417 NTSTATUS rcNt = NtUnmapViewOfSection(pThis->hProcess, pMemInfo->AllocationBase);
1418 if (NT_SUCCESS(rcNt))
1419 return VINF_OBJECT_DESTROYED;
1420 pThis->cFixes++;
1421 SUP_DPRINTF(("supHardNtVpScanVirtualMemory: NtUnmapViewOfSection(,%p) failed: %#x\n", pMemInfo->AllocationBase, rcNt));
1422 }
1423#endif
1424 /*
1425 * Special error message if we can.
1426 */
1427 if ( pMemInfo->AllocationBase == pMemInfo->BaseAddress
1428 && ( supHardNtVpAreNamesEqual("sysfer.dll", pwszFilename)
1429 || supHardNtVpAreNamesEqual("sysfer32.dll", pwszFilename)
1430 || supHardNtVpAreNamesEqual("sysfer64.dll", pwszFilename)
1431 || supHardNtVpAreNamesEqual("sysfrethunk.dll", pwszFilename)) )
1432 {
1433 supHardNtVpSetInfo2(pThis, VERR_SUP_VP_SYSFER_DLL,
1434 "Found %ls at %p - This is probably part of Symantec Endpoint Protection. \n"
1435 "You or your admin need to add and exception to the Application and Device Control (ADC) "
1436 "component (or disable it) to prevent ADC from injecting itself into the VirtualBox VM processes. "
1437 "See http://www.symantec.com/connect/articles/creating-application-control-exclusions-symantec-endpoint-protection-121"
1438 , pLongName->Buffer, pMemInfo->BaseAddress);
1439 return pThis->rcResult = VERR_SUP_VP_SYSFER_DLL; /* Try make sure this is what the user sees first! */
1440 }
1441 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_NOT_KNOWN_DLL_OR_EXE,
1442 "Unknown image file %ls at %p.", pLongName->Buffer, pMemInfo->BaseAddress);
1443 }
1444
1445 /*
1446 * Checks for multiple mappings of the same DLL but with different image file paths.
1447 */
1448 uint32_t i = pThis->cImages;
1449 while (i-- > 1)
1450 if (pImage->pszName == pThis->aImages[i].pszName)
1451 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_DUPLICATE_DLL_MAPPING,
1452 "Duplicate image entries for %s: %ls and %ls",
1453 pImage->pszName, pImage->Name.UniStr.Buffer, pThis->aImages[i].Name.UniStr.Buffer);
1454
1455 /*
1456 * Since it's a new image, we expect to be at the start of the mapping now.
1457 */
1458 if (pMemInfo->AllocationBase != pMemInfo->BaseAddress)
1459 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_IMAGE_MAPPING_BASE_ERROR,
1460 "Invalid AllocationBase/BaseAddress for %s: %p vs %p.",
1461 pImage->pszName, pMemInfo->AllocationBase, pMemInfo->BaseAddress);
1462
1463 /*
1464 * Check for size/rva overflow.
1465 */
1466 if (pMemInfo->RegionSize >= _2G)
1467 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_TOO_LARGE_REGION,
1468 "Region 0 of image %s is too large: %p.", pImage->pszName, pMemInfo->RegionSize);
1469
1470 /*
1471 * Fill in details from the memory info.
1472 */
1473 pImage->uImageBase = (uintptr_t)pMemInfo->AllocationBase;
1474 pImage->cbImage = pMemInfo->RegionSize;
1475 pImage->pCacheEntry= NULL;
1476 pImage->cRegions = 1;
1477 pImage->aRegions[0].uRva = 0;
1478 pImage->aRegions[0].cb = (uint32_t)pMemInfo->RegionSize;
1479 pImage->aRegions[0].fProt = pMemInfo->Protect;
1480
1481 if (suplibHardenedStrCmp(pImage->pszName, "ntdll.dll") == 0)
1482 pImage->fNtCreateSectionPatch = true;
1483 else if (suplibHardenedStrCmp(pImage->pszName, "apisetschema.dll") == 0)
1484 pImage->fApiSetSchemaOnlySection1 = true; /** @todo Check the ApiSetMap field in the PEB. */
1485#ifdef VBOX_PERMIT_MORE
1486 else if (suplibHardenedStrCmp(pImage->pszName, "acres.dll") == 0)
1487 pImage->f32bitResourceDll = true;
1488#endif
1489
1490 return VINF_SUCCESS;
1491}
1492
1493
1494/**
1495 * Records an additional memory region for an image.
1496 *
1497 * @returns VBox status code.
1498 * @param pThis The process scanning state structure.
1499 * @param pImage The image.
1500 * @param pMemInfo The memory information for the region.
1501 */
1502static int supHardNtVpAddRegion(PSUPHNTVPSTATE pThis, PSUPHNTVPIMAGE pImage, PMEMORY_BASIC_INFORMATION pMemInfo)
1503{
1504 /*
1505 * Make sure the base address matches.
1506 */
1507 if (pImage->uImageBase != (uintptr_t)pMemInfo->AllocationBase)
1508 return supHardNtVpSetInfo2(pThis, VERR_SUPLIB_NT_PROCESS_UNTRUSTED_3,
1509 "Base address mismatch for %s: have %p, found %p for region %p LB %#zx.",
1510 pImage->pszName, pImage->uImageBase, pMemInfo->AllocationBase,
1511 pMemInfo->BaseAddress, pMemInfo->RegionSize);
1512
1513 /*
1514 * Check for size and rva overflows.
1515 */
1516 uintptr_t uRva = (uintptr_t)pMemInfo->BaseAddress - pImage->uImageBase;
1517 if (pMemInfo->RegionSize >= _2G)
1518 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_TOO_LARGE_REGION,
1519 "Region %u of image %s is too large: %p/%p.", pImage->pszName, pMemInfo->RegionSize, uRva);
1520 if (uRva >= _2G)
1521 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_TOO_HIGH_REGION_RVA,
1522 "Region %u of image %s is too high: %p/%p.", pImage->pszName, pMemInfo->RegionSize, uRva);
1523
1524
1525 /*
1526 * Record the region.
1527 */
1528 uint32_t iRegion = pImage->cRegions;
1529 if (iRegion + 1 >= RT_ELEMENTS(pImage->aRegions))
1530 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_TOO_MANY_IMAGE_REGIONS,
1531 "Too many regions for %s.", pImage->pszName);
1532 pImage->aRegions[iRegion].uRva = (uint32_t)uRva;
1533 pImage->aRegions[iRegion].cb = (uint32_t)pMemInfo->RegionSize;
1534 pImage->aRegions[iRegion].fProt = pMemInfo->Protect;
1535 pImage->cbImage = pImage->aRegions[iRegion].uRva + pImage->aRegions[iRegion].cb;
1536 pImage->cRegions++;
1537 pImage->fApiSetSchemaOnlySection1 = false;
1538
1539 return VINF_SUCCESS;
1540}
1541
1542
1543#ifdef IN_RING3
1544/**
1545 * Frees (or replaces) executable memory of allocation type private.
1546 *
1547 * @returns True if nothing really bad happen, false if to quit ASAP because we
1548 * killed the process being scanned.
1549 * @param pThis The process scanning state structure. Details
1550 * about images are added to this.
1551 * @param hProcess The process to verify.
1552 * @param pMemInfo The information we've got on this private
1553 * executable memory.
1554 */
1555static bool supHardNtVpFreeOrReplacePrivateExecMemory(PSUPHNTVPSTATE pThis, HANDLE hProcess,
1556 MEMORY_BASIC_INFORMATION const *pMemInfo)
1557{
1558 NTSTATUS rcNt;
1559
1560 /*
1561 * Try figure if the entire allocation size. Free/Alloc may fail otherwise.
1562 */
1563 PVOID pvFree = pMemInfo->AllocationBase;
1564 SIZE_T cbFree = pMemInfo->RegionSize + ((uintptr_t)pMemInfo->BaseAddress - (uintptr_t)pMemInfo->AllocationBase);
1565 for (;;)
1566 {
1567 SIZE_T cbActual = 0;
1568 MEMORY_BASIC_INFORMATION MemInfo2 = { 0, 0, 0, 0, 0, 0, 0 };
1569 uintptr_t uPtrNext = (uintptr_t)pvFree + cbFree;
1570 rcNt = g_pfnNtQueryVirtualMemory(hProcess,
1571 (void const *)uPtrNext,
1572 MemoryBasicInformation,
1573 &MemInfo2,
1574 sizeof(MemInfo2),
1575 &cbActual);
1576 if (!NT_SUCCESS(rcNt))
1577 break;
1578 if (pMemInfo->AllocationBase != MemInfo2.AllocationBase)
1579 break;
1580 }
1581 SUP_DPRINTF(("supHardNtVpFreeOrReplacePrivateExecMemory: %s exec mem at %p (LB %#zx, %p LB %#zx)\n",
1582 pThis->fFlags & SUPHARDNTVP_F_EXEC_ALLOC_REPLACE_WITH_RW ? "Replacing" : "Freeing",
1583 pvFree, cbFree, pMemInfo->BaseAddress, pMemInfo->RegionSize));
1584
1585 /*
1586 * In the BSOD workaround mode, we need to make a copy of the memory before
1587 * freeing it.
1588 */
1589 uintptr_t uCopySrc = (uintptr_t)pvFree;
1590 size_t cbCopy = 0;
1591 void *pvCopy = NULL;
1592 if (pThis->fFlags & SUPHARDNTVP_F_EXEC_ALLOC_REPLACE_WITH_RW)
1593 {
1594 cbCopy = cbFree;
1595 pvCopy = RTMemAllocZ(cbCopy);
1596 if (!pvCopy)
1597 {
1598 supHardNtVpSetInfo2(pThis, VERR_SUP_VP_REPLACE_VIRTUAL_MEMORY_FAILED, "RTMemAllocZ(%#zx) failed", cbCopy);
1599 return true;
1600 }
1601
1602 rcNt = supHardNtVpReadMem(hProcess, uCopySrc, pvCopy, cbCopy);
1603 if (!NT_SUCCESS(rcNt))
1604 supHardNtVpSetInfo2(pThis, VERR_SUP_VP_REPLACE_VIRTUAL_MEMORY_FAILED,
1605 "Error reading data from original alloc: %#x (%p LB %#zx)", rcNt, uCopySrc, cbCopy, rcNt);
1606 supR3HardenedLogFlush();
1607 }
1608
1609 /*
1610 * Free the memory.
1611 */
1612 for (uint32_t i = 0; i < 10; i++)
1613 {
1614 PVOID pvFreeInOut = pvFree;
1615 SIZE_T cbFreeInOut = 0;
1616 rcNt = NtFreeVirtualMemory(hProcess, &pvFreeInOut, &cbFreeInOut, MEM_RELEASE);
1617 if (NT_SUCCESS(rcNt))
1618 {
1619 SUP_DPRINTF(("supHardNtVpFreeOrReplacePrivateExecMemory: Free attempt #1 succeeded: %#x [%p/%p LB 0/%#zx]\n",
1620 rcNt, pvFree, pvFreeInOut, cbFreeInOut));
1621 supR3HardenedLogFlush();
1622 }
1623 else
1624 {
1625 SUP_DPRINTF(("supHardNtVpFreeOrReplacePrivateExecMemory: Free attempt #1 failed: %#x [%p LB 0]\n", rcNt, pvFree));
1626 supR3HardenedLogFlush();
1627 pvFreeInOut = pvFree;
1628 cbFreeInOut = cbFree;
1629 rcNt = NtFreeVirtualMemory(hProcess, &pvFreeInOut, &cbFreeInOut, MEM_RELEASE);
1630 if (NT_SUCCESS(rcNt))
1631 {
1632 SUP_DPRINTF(("supHardNtVpFreeOrReplacePrivateExecMemory: Free attempt #2 succeeded: %#x [%p/%p LB %#zx/%#zx]\n",
1633 rcNt, pvFree, pvFreeInOut, cbFree, cbFreeInOut));
1634 supR3HardenedLogFlush();
1635 }
1636 else
1637 {
1638 SUP_DPRINTF(("supHardNtVpFreeOrReplacePrivateExecMemory: Free attempt #2 failed: %#x [%p LB %#zx]\n",
1639 rcNt, pvFree, cbFree));
1640 supR3HardenedLogFlush();
1641 pvFreeInOut = pMemInfo->BaseAddress;
1642 cbFreeInOut = pMemInfo->RegionSize;
1643 rcNt = NtFreeVirtualMemory(hProcess, &pvFreeInOut, &cbFreeInOut, MEM_RELEASE);
1644 if (NT_SUCCESS(rcNt))
1645 {
1646 pvFree = pMemInfo->BaseAddress;
1647 cbFree = pMemInfo->RegionSize;
1648 SUP_DPRINTF(("supHardNtVpFreeOrReplacePrivateExecMemory: Free attempt #3 succeeded [%p LB %#zx]\n",
1649 pvFree, cbFree));
1650 supR3HardenedLogFlush();
1651 }
1652 else
1653 supHardNtVpSetInfo2(pThis, VERR_SUP_VP_FREE_VIRTUAL_MEMORY_FAILED,
1654 "NtFreeVirtualMemory [%p LB %#zx and %p LB %#zx] failed: %#x",
1655 pvFree, cbFree, pMemInfo->BaseAddress, pMemInfo->RegionSize, rcNt);
1656 }
1657 }
1658
1659 /*
1660 * Query the region again, redo the free operation if there's still memory there.
1661 */
1662 if (!NT_SUCCESS(rcNt))
1663 break;
1664 SIZE_T cbActual = 0;
1665 MEMORY_BASIC_INFORMATION MemInfo3 = { 0, 0, 0, 0, 0, 0, 0 };
1666 NTSTATUS rcNt2 = g_pfnNtQueryVirtualMemory(hProcess, pvFree, MemoryBasicInformation,
1667 &MemInfo3, sizeof(MemInfo3), &cbActual);
1668 if (!NT_SUCCESS(rcNt2))
1669 break;
1670 SUP_DPRINTF(("supHardNtVpFreeOrReplacePrivateExecMemory: QVM after free %u: [%p]/%p LB %#zx s=%#x ap=%#x rp=%#p\n",
1671 i, MemInfo3.AllocationBase, MemInfo3.BaseAddress, MemInfo3.RegionSize, MemInfo3.State,
1672 MemInfo3.AllocationProtect, MemInfo3.Protect));
1673 supR3HardenedLogFlush();
1674 if (MemInfo3.State == MEM_FREE || !(pThis->fFlags & SUPHARDNTVP_F_EXEC_ALLOC_REPLACE_WITH_RW))
1675 break;
1676 NtYieldExecution();
1677 SUP_DPRINTF(("supHardNtVpFreeOrReplacePrivateExecMemory: Retrying free...\n"));
1678 supR3HardenedLogFlush();
1679 }
1680
1681 /*
1682 * Restore memory as non-executable - Kludge for Trend Micro sakfile.sys
1683 * and Digital Guardian dgmaster.sys BSODs.
1684 */
1685 if (NT_SUCCESS(rcNt) && (pThis->fFlags & SUPHARDNTVP_F_EXEC_ALLOC_REPLACE_WITH_RW))
1686 {
1687 PVOID pvAlloc = pvFree;
1688 SIZE_T cbAlloc = cbFree;
1689 rcNt = NtAllocateVirtualMemory(hProcess, &pvAlloc, 0, &cbAlloc, MEM_COMMIT, PAGE_READWRITE);
1690 if (!NT_SUCCESS(rcNt))
1691 {
1692 supHardNtVpSetInfo2(pThis, VERR_SUP_VP_REPLACE_VIRTUAL_MEMORY_FAILED,
1693 "NtAllocateVirtualMemory (%p LB %#zx) failed with rcNt=%#x allocating "
1694 "replacement memory for working around buggy protection software. "
1695 "See VBoxStartup.log for more details",
1696 pvAlloc, cbFree, rcNt);
1697 supR3HardenedLogFlush();
1698 NtTerminateProcess(hProcess, VERR_SUP_VP_REPLACE_VIRTUAL_MEMORY_FAILED);
1699 return false;
1700 }
1701
1702 if ( (uintptr_t)pvFree < (uintptr_t)pvAlloc
1703 || (uintptr_t)pvFree + cbFree > (uintptr_t)pvAlloc + cbFree)
1704 {
1705 supHardNtVpSetInfo2(pThis, VERR_SUP_VP_REPLACE_VIRTUAL_MEMORY_FAILED,
1706 "We wanted NtAllocateVirtualMemory to get us %p LB %#zx, but it returned %p LB %#zx.",
1707 pMemInfo->BaseAddress, pMemInfo->RegionSize, pvFree, cbFree, rcNt);
1708 supR3HardenedLogFlush();
1709 NtTerminateProcess(hProcess, VERR_SUP_VP_REPLACE_VIRTUAL_MEMORY_FAILED);
1710 return false;
1711 }
1712
1713 /*
1714 * Copy what we can, considering the 2nd free attempt.
1715 */
1716 uint8_t *pbDst = (uint8_t *)pvFree;
1717 size_t cbDst = cbFree;
1718 uint8_t *pbSrc = (uint8_t *)pvCopy;
1719 size_t cbSrc = cbCopy;
1720 if ((uintptr_t)pbDst != uCopySrc)
1721 {
1722 if ((uintptr_t)pbDst > uCopySrc)
1723 {
1724 uintptr_t cbAdj = (uintptr_t)pbDst - uCopySrc;
1725 pbSrc += cbAdj;
1726 cbSrc -= cbSrc;
1727 }
1728 else
1729 {
1730 uintptr_t cbAdj = uCopySrc - (uintptr_t)pbDst;
1731 pbDst += cbAdj;
1732 cbDst -= cbAdj;
1733 }
1734 }
1735 if (cbSrc > cbDst)
1736 cbSrc = cbDst;
1737
1738 SIZE_T cbWritten;
1739 rcNt = NtWriteVirtualMemory(hProcess, pbDst, pbSrc, cbSrc, &cbWritten);
1740 if (NT_SUCCESS(rcNt))
1741 {
1742 SUP_DPRINTF(("supHardNtVpFreeOrReplacePrivateExecMemory: Restored the exec memory as non-exec.\n"));
1743 supR3HardenedLogFlush();
1744 }
1745 else
1746 {
1747 supHardNtVpSetInfo2(pThis, VERR_SUP_VP_FREE_VIRTUAL_MEMORY_FAILED,
1748 "NtWriteVirtualMemory (%p LB %#zx) failed: %#x",
1749 pMemInfo->BaseAddress, pMemInfo->RegionSize, rcNt);
1750 supR3HardenedLogFlush();
1751 NtTerminateProcess(hProcess, VERR_SUP_VP_REPLACE_VIRTUAL_MEMORY_FAILED);
1752 return false;
1753 }
1754 }
1755 if (pvCopy)
1756 RTMemFree(pvCopy);
1757 return true;
1758}
1759#endif /* IN_RING3 */
1760
1761
1762/**
1763 * Scans the virtual memory of the process.
1764 *
1765 * This collects the locations of DLLs and the EXE, and verifies that executable
1766 * memory is only associated with these. May trash pThis->abMemory.
1767 *
1768 * @returns VBox status code.
1769 * @param pThis The process scanning state structure. Details
1770 * about images are added to this.
1771 * @param hProcess The process to verify.
1772 */
1773static int supHardNtVpScanVirtualMemory(PSUPHNTVPSTATE pThis, HANDLE hProcess)
1774{
1775 SUP_DPRINTF(("supHardNtVpScanVirtualMemory: enmKind=%s\n",
1776 pThis->enmKind == SUPHARDNTVPKIND_VERIFY_ONLY ? "VERIFY_ONLY" :
1777 pThis->enmKind == SUPHARDNTVPKIND_CHILD_PURIFICATION ? "CHILD_PURIFICATION" : "SELF_PURIFICATION"));
1778
1779 uint32_t cXpExceptions = 0;
1780 uintptr_t cbAdvance = 0;
1781 uintptr_t uPtrWhere = 0;
1782#ifdef VBOX_PERMIT_VERIFIER_DLL
1783 for (uint32_t i = 0; i < 10240; i++)
1784#else
1785 for (uint32_t i = 0; i < 1024; i++)
1786#endif
1787 {
1788 SIZE_T cbActual = 0;
1789 MEMORY_BASIC_INFORMATION MemInfo = { 0, 0, 0, 0, 0, 0, 0 };
1790 NTSTATUS rcNt = g_pfnNtQueryVirtualMemory(hProcess,
1791 (void const *)uPtrWhere,
1792 MemoryBasicInformation,
1793 &MemInfo,
1794 sizeof(MemInfo),
1795 &cbActual);
1796 if (!NT_SUCCESS(rcNt))
1797 {
1798 if (rcNt == STATUS_INVALID_PARAMETER)
1799 return pThis->rcResult;
1800 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_NT_QI_VIRTUAL_MEMORY_ERROR,
1801 "NtQueryVirtualMemory failed for %p: %#x", uPtrWhere, rcNt);
1802 }
1803
1804 /*
1805 * Record images.
1806 */
1807 if ( MemInfo.Type == SEC_IMAGE
1808 || MemInfo.Type == SEC_PROTECTED_IMAGE
1809 || MemInfo.Type == (SEC_IMAGE | SEC_PROTECTED_IMAGE))
1810 {
1811 uint32_t iImg = pThis->cImages;
1812 rcNt = g_pfnNtQueryVirtualMemory(hProcess,
1813 (void const *)uPtrWhere,
1814 MemorySectionName,
1815 &pThis->aImages[iImg].Name,
1816 sizeof(pThis->aImages[iImg].Name) - sizeof(WCHAR),
1817 &cbActual);
1818 if (!NT_SUCCESS(rcNt))
1819 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_NT_QI_VIRTUAL_MEMORY_NM_ERROR,
1820 "NtQueryVirtualMemory/MemorySectionName failed for %p: %#x", uPtrWhere, rcNt);
1821 pThis->aImages[iImg].Name.UniStr.Buffer[pThis->aImages[iImg].Name.UniStr.Length / sizeof(WCHAR)] = '\0';
1822 SUP_DPRINTF((MemInfo.AllocationBase == MemInfo.BaseAddress
1823 ? " *%p-%p %#06x/%#06x %#09x %ls\n"
1824 : " %p-%p %#06x/%#06x %#09x %ls\n",
1825 MemInfo.BaseAddress, (uintptr_t)MemInfo.BaseAddress + MemInfo.RegionSize - 1, MemInfo.Protect,
1826 MemInfo.AllocationProtect, MemInfo.Type, pThis->aImages[iImg].Name.UniStr.Buffer));
1827
1828 /* New or existing image? */
1829 bool fNew = true;
1830 uint32_t iSearch = iImg;
1831 while (iSearch-- > 0)
1832 if (supHardNtVpAreUniStringsEqual(&pThis->aImages[iSearch].Name.UniStr, &pThis->aImages[iImg].Name.UniStr))
1833 {
1834 int rc = supHardNtVpAddRegion(pThis, &pThis->aImages[iSearch], &MemInfo);
1835 if (RT_FAILURE(rc))
1836 return rc;
1837 fNew = false;
1838 break;
1839 }
1840 else if (pThis->aImages[iSearch].uImageBase == (uintptr_t)MemInfo.AllocationBase)
1841 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_NT_MAPPING_NAME_CHANGED,
1842 "Unexpected base address match");
1843
1844 if (fNew)
1845 {
1846 int rc = supHardNtVpNewImage(pThis, &pThis->aImages[iImg], &MemInfo);
1847 if (RT_SUCCESS(rc))
1848 {
1849 if (rc != VINF_OBJECT_DESTROYED)
1850 {
1851 pThis->cImages++;
1852 if (pThis->cImages >= RT_ELEMENTS(pThis->aImages))
1853 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_TOO_MANY_DLLS_LOADED,
1854 "Internal error: aImages is full.\n");
1855 }
1856 }
1857#ifdef IN_RING3 /* Continue and add more information if unknown DLLs are found. */
1858 else if (rc != VERR_SUP_VP_NOT_KNOWN_DLL_OR_EXE && rc != VERR_SUP_VP_NON_SYSTEM32_DLL)
1859 return rc;
1860#else
1861 else
1862 return rc;
1863#endif
1864 }
1865 }
1866 /*
1867 * XP, W2K3: Ignore the CSRSS read-only region as best we can.
1868 */
1869 else if ( (MemInfo.Protect & (PAGE_EXECUTE | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY))
1870 == PAGE_EXECUTE_READ
1871 && cXpExceptions == 0
1872 && (uintptr_t)MemInfo.BaseAddress >= UINT32_C(0x78000000)
1873 /* && MemInfo.BaseAddress == pPeb->ReadOnlySharedMemoryBase */
1874 && g_uNtVerCombined < SUP_MAKE_NT_VER_SIMPLE(6, 0) )
1875 {
1876 cXpExceptions++;
1877 SUP_DPRINTF((" %p-%p %#06x/%#06x %#09x XP CSRSS read-only region\n", MemInfo.BaseAddress,
1878 (uintptr_t)MemInfo.BaseAddress - MemInfo.RegionSize - 1, MemInfo.Protect,
1879 MemInfo.AllocationProtect, MemInfo.Type));
1880 }
1881 /*
1882 * Executable memory?
1883 */
1884#ifndef VBOX_PERMIT_VISUAL_STUDIO_PROFILING
1885 else if (MemInfo.Protect & (PAGE_EXECUTE | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY))
1886 {
1887 SUP_DPRINTF((MemInfo.AllocationBase == MemInfo.BaseAddress
1888 ? " *%p-%p %#06x/%#06x %#09x !!\n"
1889 : " %p-%p %#06x/%#06x %#09x !!\n",
1890 MemInfo.BaseAddress, (uintptr_t)MemInfo.BaseAddress - MemInfo.RegionSize - 1,
1891 MemInfo.Protect, MemInfo.AllocationProtect, MemInfo.Type));
1892# ifdef IN_RING3
1893 if (pThis->enmKind == SUPHARDNTVPKIND_CHILD_PURIFICATION)
1894 {
1895 /*
1896 * Free any private executable memory (sysplant.sys allocates executable memory).
1897 */
1898 if (MemInfo.Type == MEM_PRIVATE)
1899 {
1900 if (!supHardNtVpFreeOrReplacePrivateExecMemory(pThis, hProcess, &MemInfo))
1901 break;
1902 }
1903 /*
1904 * Unmap mapped memory, failing that, drop exec privileges.
1905 */
1906 else if (MemInfo.Type == MEM_MAPPED)
1907 {
1908 SUP_DPRINTF(("supHardNtVpScanVirtualMemory: Unmapping exec mem at %p (%p/%p LB %#zx)\n",
1909 uPtrWhere, MemInfo.AllocationBase, MemInfo.BaseAddress, MemInfo.RegionSize));
1910 rcNt = NtUnmapViewOfSection(hProcess, MemInfo.AllocationBase);
1911 if (!NT_SUCCESS(rcNt))
1912 {
1913 PVOID pvCopy = MemInfo.BaseAddress;
1914 SIZE_T cbCopy = MemInfo.RegionSize;
1915 NTSTATUS rcNt2 = NtProtectVirtualMemory(hProcess, &pvCopy, &cbCopy, PAGE_NOACCESS, NULL);
1916 if (!NT_SUCCESS(rcNt2))
1917 rcNt2 = NtProtectVirtualMemory(hProcess, &pvCopy, &cbCopy, PAGE_READONLY, NULL);
1918 if (!NT_SUCCESS(rcNt2))
1919 supHardNtVpSetInfo2(pThis, VERR_SUP_VP_UNMAP_AND_PROTECT_FAILED,
1920 "NtUnmapViewOfSection (%p/%p LB %#zx) failed: %#x (%#x)",
1921 MemInfo.AllocationBase, MemInfo.BaseAddress, MemInfo.RegionSize, rcNt, rcNt2);
1922 }
1923 }
1924 else
1925 supHardNtVpSetInfo2(pThis, VERR_SUP_VP_UNKOWN_MEM_TYPE,
1926 "Unknown executable memory type %#x at %p/%p LB %#zx",
1927 MemInfo.Type, MemInfo.AllocationBase, MemInfo.BaseAddress, MemInfo.RegionSize);
1928 pThis->cFixes++;
1929 }
1930 else
1931# endif /* IN_RING3 */
1932 supHardNtVpSetInfo2(pThis, VERR_SUP_VP_FOUND_EXEC_MEMORY,
1933 "Found executable memory at %p (%p LB %#zx): type=%#x prot=%#x state=%#x aprot=%#x abase=%p",
1934 uPtrWhere, MemInfo.BaseAddress, MemInfo.RegionSize, MemInfo.Type, MemInfo.Protect,
1935 MemInfo.State, MemInfo.AllocationBase, MemInfo.AllocationProtect);
1936
1937# ifndef IN_RING3
1938 if (RT_FAILURE(pThis->rcResult))
1939 return pThis->rcResult;
1940# endif
1941 /* Continue add more information about the problematic process. */
1942 }
1943#endif /* VBOX_PERMIT_VISUAL_STUDIO_PROFILING */
1944 else
1945 SUP_DPRINTF((MemInfo.AllocationBase == MemInfo.BaseAddress
1946 ? " *%p-%p %#06x/%#06x %#09x\n"
1947 : " %p-%p %#06x/%#06x %#09x\n",
1948 MemInfo.BaseAddress, (uintptr_t)MemInfo.BaseAddress - MemInfo.RegionSize - 1,
1949 MemInfo.Protect, MemInfo.AllocationProtect, MemInfo.Type));
1950
1951 /*
1952 * Advance.
1953 */
1954 cbAdvance = MemInfo.RegionSize;
1955 if (uPtrWhere + cbAdvance <= uPtrWhere)
1956 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_EMPTY_REGION_TOO_LARGE,
1957 "Empty region at %p.", uPtrWhere);
1958 uPtrWhere += MemInfo.RegionSize;
1959 }
1960
1961 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_TOO_MANY_MEMORY_REGIONS,
1962 "Too many virtual memory regions.\n");
1963}
1964
1965
1966/**
1967 * Verifies the loader image, i.e. check cryptographic signatures if present.
1968 *
1969 * @returns VBox status code.
1970 * @param pEntry The loader cache entry.
1971 * @param pwszName The filename to use in error messages.
1972 * @param pErRInfo Where to return extened error information.
1973 */
1974DECLHIDDEN(int) supHardNtLdrCacheEntryVerify(PSUPHNTLDRCACHEENTRY pEntry, PCRTUTF16 pwszName, PRTERRINFO pErrInfo)
1975{
1976 int rc = VINF_SUCCESS;
1977 if (!pEntry->fVerified)
1978 {
1979 rc = supHardenedWinVerifyImageByLdrMod(pEntry->hLdrMod, pwszName, pEntry->pNtViRdr,
1980 false /*fAvoidWinVerifyTrust*/, NULL /*pfWinVerifyTrust*/, pErrInfo);
1981 pEntry->fVerified = RT_SUCCESS(rc);
1982 }
1983 return rc;
1984}
1985
1986
1987/**
1988 * Allocates a image bits buffer and calls RTLdrGetBits on them.
1989 *
1990 * An assumption here is that there won't ever be concurrent use of the cache.
1991 * It's currently 104% single threaded, non-reentrant. Thus, we can't reuse the
1992 * pbBits allocation.
1993 *
1994 * @returns VBox status code
1995 * @param pEntry The loader cache entry.
1996 * @param ppbBits Where to return the pointer to the allocation.
1997 * @param uBaseAddress The image base address, see RTLdrGetBits.
1998 * @param pfnGetImport Import getter, see RTLdrGetBits.
1999 * @param pvUser The user argument for @a pfnGetImport.
2000 * @param pErrInfo Where to return extened error information.
2001 */
2002DECLHIDDEN(int) supHardNtLdrCacheEntryGetBits(PSUPHNTLDRCACHEENTRY pEntry, uint8_t **ppbBits,
2003 RTLDRADDR uBaseAddress, PFNRTLDRIMPORT pfnGetImport, void *pvUser,
2004 PRTERRINFO pErrInfo)
2005{
2006 int rc;
2007
2008 /*
2009 * First time around we have to allocate memory before we can get the image bits.
2010 */
2011 if (!pEntry->pbBits)
2012 {
2013 size_t cbBits = RTLdrSize(pEntry->hLdrMod);
2014 if (cbBits >= _1M*32U)
2015 return supHardNtVpSetInfo1(pErrInfo, VERR_SUP_VP_IMAGE_TOO_BIG, "Image %s is too large: %zu bytes (%#zx).",
2016 pEntry->pszName, cbBits, cbBits);
2017
2018 pEntry->pbBits = (uint8_t *)RTMemAllocZ(cbBits);
2019 if (!pEntry->pbBits)
2020 return supHardNtVpSetInfo1(pErrInfo, VERR_SUP_VP_NO_MEMORY, "Failed to allocate %zu bytes for image %s.",
2021 cbBits, pEntry->pszName);
2022
2023 pEntry->fValidBits = false; /* paranoia */
2024
2025 rc = RTLdrGetBits(pEntry->hLdrMod, pEntry->pbBits, uBaseAddress, pfnGetImport, pvUser);
2026 if (RT_FAILURE(rc))
2027 return supHardNtVpSetInfo1(pErrInfo, VERR_SUP_VP_NO_MEMORY, "RTLdrGetBits failed on image %s: %Rrc",
2028 pEntry->pszName, rc);
2029 pEntry->uImageBase = uBaseAddress;
2030 pEntry->fValidBits = pfnGetImport == NULL;
2031
2032 }
2033 /*
2034 * Cache hit? No?
2035 *
2036 * Note! We cannot currently cache image bits for images with imports as we
2037 * don't control the way they're resolved. Fortunately, NTDLL and
2038 * the VM process images all have no imports.
2039 */
2040 else if ( !pEntry->fValidBits
2041 || pEntry->uImageBase != uBaseAddress
2042 || pfnGetImport)
2043 {
2044 pEntry->fValidBits = false;
2045
2046 rc = RTLdrGetBits(pEntry->hLdrMod, pEntry->pbBits, uBaseAddress, pfnGetImport, pvUser);
2047 if (RT_FAILURE(rc))
2048 return supHardNtVpSetInfo1(pErrInfo, VERR_SUP_VP_NO_MEMORY, "RTLdrGetBits failed on image %s: %Rrc",
2049 pEntry->pszName, rc);
2050 pEntry->uImageBase = uBaseAddress;
2051 pEntry->fValidBits = pfnGetImport == NULL;
2052 }
2053
2054 *ppbBits = pEntry->pbBits;
2055 return VINF_SUCCESS;
2056}
2057
2058
2059/**
2060 * Frees all resources associated with a cache entry and wipes the members
2061 * clean.
2062 *
2063 * @param pEntry The entry to delete.
2064 */
2065static void supHardNTLdrCacheDeleteEntry(PSUPHNTLDRCACHEENTRY pEntry)
2066{
2067 if (pEntry->pbBits)
2068 {
2069 RTMemFree(pEntry->pbBits);
2070 pEntry->pbBits = NULL;
2071 }
2072
2073 if (pEntry->hLdrMod != NIL_RTLDRMOD)
2074 {
2075 RTLdrClose(pEntry->hLdrMod);
2076 pEntry->hLdrMod = NIL_RTLDRMOD;
2077 pEntry->pNtViRdr = NULL;
2078 }
2079 else if (pEntry->pNtViRdr)
2080 {
2081 pEntry->pNtViRdr->Core.pfnDestroy(&pEntry->pNtViRdr->Core);
2082 pEntry->pNtViRdr = NULL;
2083 }
2084
2085 if (pEntry->hFile)
2086 {
2087 NtClose(pEntry->hFile);
2088 pEntry->hFile = NULL;
2089 }
2090
2091 pEntry->pszName = NULL;
2092 pEntry->fVerified = false;
2093 pEntry->fValidBits = false;
2094 pEntry->uImageBase = 0;
2095}
2096
2097#ifdef IN_RING3
2098
2099/**
2100 * Flushes the cache.
2101 *
2102 * This is called from one of two points in the hardened main code, first is
2103 * after respawning and the second is when we open the vboxdrv device for
2104 * unrestricted access.
2105 */
2106DECLHIDDEN(void) supR3HardenedWinFlushLoaderCache(void)
2107{
2108 uint32_t i = g_cSupNtVpLdrCacheEntries;
2109 while (i-- > 0)
2110 supHardNTLdrCacheDeleteEntry(&g_aSupNtVpLdrCacheEntries[i]);
2111 g_cSupNtVpLdrCacheEntries = 0;
2112}
2113
2114
2115/**
2116 * Searches the cache for a loader image.
2117 *
2118 * @returns Pointer to the cache entry if found, NULL if not.
2119 * @param pszName The name (from g_apszSupNtVpAllowedVmExes or
2120 * g_apszSupNtVpAllowedDlls).
2121 */
2122static PSUPHNTLDRCACHEENTRY supHardNtLdrCacheLookupEntry(const char *pszName)
2123{
2124 /*
2125 * Since the caller is supplying us a pszName from one of the two tables,
2126 * we can dispense with string compare and simply compare string pointers.
2127 */
2128 uint32_t i = g_cSupNtVpLdrCacheEntries;
2129 while (i-- > 0)
2130 if (g_aSupNtVpLdrCacheEntries[i].pszName == pszName)
2131 return &g_aSupNtVpLdrCacheEntries[i];
2132 return NULL;
2133}
2134
2135#endif /* IN_RING3 */
2136
2137static int supHardNtLdrCacheNewEntry(PSUPHNTLDRCACHEENTRY pEntry, const char *pszName, PUNICODE_STRING pUniStrPath,
2138 bool fDll, bool f32bitResourceDll, PRTERRINFO pErrInfo)
2139{
2140 /*
2141 * Open the image file.
2142 */
2143 HANDLE hFile = RTNT_INVALID_HANDLE_VALUE;
2144 IO_STATUS_BLOCK Ios = RTNT_IO_STATUS_BLOCK_INITIALIZER;
2145
2146 OBJECT_ATTRIBUTES ObjAttr;
2147 InitializeObjectAttributes(&ObjAttr, pUniStrPath, OBJ_CASE_INSENSITIVE, NULL /*hRootDir*/, NULL /*pSecDesc*/);
2148#ifdef IN_RING0
2149 ObjAttr.Attributes |= OBJ_KERNEL_HANDLE;
2150#endif
2151
2152 NTSTATUS rcNt = NtCreateFile(&hFile,
2153 GENERIC_READ | SYNCHRONIZE,
2154 &ObjAttr,
2155 &Ios,
2156 NULL /* Allocation Size*/,
2157 FILE_ATTRIBUTE_NORMAL,
2158 FILE_SHARE_READ,
2159 FILE_OPEN,
2160 FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT,
2161 NULL /*EaBuffer*/,
2162 0 /*EaLength*/);
2163 if (NT_SUCCESS(rcNt))
2164 rcNt = Ios.Status;
2165 if (!NT_SUCCESS(rcNt))
2166 return supHardNtVpSetInfo1(pErrInfo, VERR_SUP_VP_IMAGE_FILE_OPEN_ERROR,
2167 "Error opening image for scanning: %#x (name %ls)", rcNt, pUniStrPath->Buffer);
2168
2169 /*
2170 * Figure out validation flags we'll be using and create the reader
2171 * for this image.
2172 */
2173 uint32_t fFlags = fDll
2174 ? SUPHNTVI_F_TRUSTED_INSTALLER_OWNER | SUPHNTVI_F_ALLOW_CAT_FILE_VERIFICATION
2175 : SUPHNTVI_F_REQUIRE_BUILD_CERT;
2176 if (f32bitResourceDll)
2177 fFlags |= SUPHNTVI_F_IGNORE_ARCHITECTURE;
2178
2179 PSUPHNTVIRDR pNtViRdr;
2180 int rc = supHardNtViRdrCreate(hFile, pUniStrPath->Buffer, fFlags, &pNtViRdr);
2181 if (RT_FAILURE(rc))
2182 {
2183 NtClose(hFile);
2184 return rc;
2185 }
2186
2187 /*
2188 * Finally, open the image with the loader
2189 */
2190 RTLDRMOD hLdrMod;
2191 RTLDRARCH enmArch = fFlags & SUPHNTVI_F_RC_IMAGE ? RTLDRARCH_X86_32 : RTLDRARCH_HOST;
2192 if (fFlags & SUPHNTVI_F_IGNORE_ARCHITECTURE)
2193 enmArch = RTLDRARCH_WHATEVER;
2194 rc = RTLdrOpenWithReader(&pNtViRdr->Core, RTLDR_O_FOR_VALIDATION, enmArch, &hLdrMod, pErrInfo);
2195 if (RT_FAILURE(rc))
2196 return supHardNtVpSetInfo1(pErrInfo, rc, "RTLdrOpenWithReader failed: %Rrc (Image='%ls').",
2197 rc, pUniStrPath->Buffer);
2198
2199 /*
2200 * Fill in the cache entry.
2201 */
2202 pEntry->pszName = pszName;
2203 pEntry->hLdrMod = hLdrMod;
2204 pEntry->pNtViRdr = pNtViRdr;
2205 pEntry->hFile = hFile;
2206 pEntry->pbBits = NULL;
2207 pEntry->fVerified = false;
2208 pEntry->fValidBits = false;
2209 pEntry->uImageBase = ~(uintptr_t)0;
2210
2211#ifdef IN_SUP_HARDENED_R3
2212 /*
2213 * Log the image timestamp when in the hardened exe.
2214 */
2215 uint64_t uTimestamp = 0;
2216 rc = RTLdrQueryProp(hLdrMod, RTLDRPROP_TIMESTAMP_SECONDS, &uTimestamp, sizeof(uint64_t));
2217 SUP_DPRINTF(("%s: timestamp %#llx (rc=%Rrc)\n", pszName, uTimestamp, rc));
2218#endif
2219
2220 return VINF_SUCCESS;
2221}
2222
2223#ifdef IN_RING3
2224/**
2225 * Opens a loader cache entry.
2226 *
2227 * Currently this is only used by the import code for getting NTDLL.
2228 *
2229 * @returns VBox status code.
2230 * @param pszName The DLL name. Must be one from the
2231 * g_apszSupNtVpAllowedDlls array.
2232 * @param ppEntry Where to return the entry we've opened/found.
2233 */
2234DECLHIDDEN(int) supHardNtLdrCacheOpen(const char *pszName, PSUPHNTLDRCACHEENTRY *ppEntry)
2235{
2236 /*
2237 * Locate the dll.
2238 */
2239 uint32_t i = 0;
2240 while ( i < RT_ELEMENTS(g_apszSupNtVpAllowedDlls)
2241 && strcmp(pszName, g_apszSupNtVpAllowedDlls[i]))
2242 i++;
2243 if (i >= RT_ELEMENTS(g_apszSupNtVpAllowedDlls))
2244 return VERR_FILE_NOT_FOUND;
2245 pszName = g_apszSupNtVpAllowedDlls[i];
2246
2247 /*
2248 * Try the cache.
2249 */
2250 *ppEntry = supHardNtLdrCacheLookupEntry(pszName);
2251 if (*ppEntry)
2252 return VINF_SUCCESS;
2253
2254 /*
2255 * Not in the cache, so open it.
2256 * Note! We cannot assume that g_System32NtPath has been initialized at this point.
2257 */
2258 if (g_cSupNtVpLdrCacheEntries >= RT_ELEMENTS(g_aSupNtVpLdrCacheEntries))
2259 return VERR_INTERNAL_ERROR_3;
2260
2261 static WCHAR s_wszSystem32[] = L"\\SystemRoot\\System32\\";
2262 WCHAR wszPath[64];
2263 memcpy(wszPath, s_wszSystem32, sizeof(s_wszSystem32));
2264 RTUtf16CatAscii(wszPath, sizeof(wszPath), pszName);
2265
2266 UNICODE_STRING UniStr;
2267 UniStr.Buffer = wszPath;
2268 UniStr.Length = (USHORT)(RTUtf16Len(wszPath) * sizeof(WCHAR));
2269 UniStr.MaximumLength = UniStr.Length + sizeof(WCHAR);
2270
2271 int rc = supHardNtLdrCacheNewEntry(&g_aSupNtVpLdrCacheEntries[g_cSupNtVpLdrCacheEntries], pszName, &UniStr,
2272 true /*fDll*/, false /*f32bitResourceDll*/, NULL /*pErrInfo*/);
2273 if (RT_SUCCESS(rc))
2274 {
2275 *ppEntry = &g_aSupNtVpLdrCacheEntries[g_cSupNtVpLdrCacheEntries];
2276 g_cSupNtVpLdrCacheEntries++;
2277 return VINF_SUCCESS;
2278 }
2279 return rc;
2280}
2281#endif /* IN_RING3 */
2282
2283
2284/**
2285 * Opens all the images with the IPRT loader, setting both, hFile, pNtViRdr and
2286 * hLdrMod for each image.
2287 *
2288 * @returns VBox status code.
2289 * @param pThis The process scanning state structure.
2290 */
2291static int supHardNtVpOpenImages(PSUPHNTVPSTATE pThis)
2292{
2293 unsigned i = pThis->cImages;
2294 while (i-- > 0)
2295 {
2296 PSUPHNTVPIMAGE pImage = &pThis->aImages[i];
2297
2298#ifdef IN_RING3
2299 /*
2300 * Try the cache first.
2301 */
2302 pImage->pCacheEntry = supHardNtLdrCacheLookupEntry(pImage->pszName);
2303 if (pImage->pCacheEntry)
2304 continue;
2305
2306 /*
2307 * Not in the cache, so load it into the cache.
2308 */
2309 if (g_cSupNtVpLdrCacheEntries >= RT_ELEMENTS(g_aSupNtVpLdrCacheEntries))
2310 return supHardNtVpSetInfo2(pThis, VERR_INTERNAL_ERROR_3, "Loader cache overflow.");
2311 pImage->pCacheEntry = &g_aSupNtVpLdrCacheEntries[g_cSupNtVpLdrCacheEntries];
2312#else
2313 /*
2314 * In ring-0 we don't have a cache at the moment (resource reasons), so
2315 * we have a static cache entry in each image structure that we use instead.
2316 */
2317 pImage->pCacheEntry = &pImage->CacheEntry;
2318#endif
2319
2320 int rc = supHardNtLdrCacheNewEntry(pImage->pCacheEntry, pImage->pszName, &pImage->Name.UniStr,
2321 pImage->fDll, pImage->f32bitResourceDll, pThis->pErrInfo);
2322 if (RT_FAILURE(rc))
2323 return rc;
2324#ifdef IN_RING3
2325 g_cSupNtVpLdrCacheEntries++;
2326#endif
2327 }
2328
2329 return VINF_SUCCESS;
2330}
2331
2332
2333/**
2334 * Check the integrity of the executable of the process.
2335 *
2336 * @returns VBox status code.
2337 * @param pThis The process scanning state structure. Details
2338 * about images are added to this.
2339 * @param hProcess The process to verify.
2340 */
2341static int supHardNtVpCheckExe(PSUPHNTVPSTATE pThis, HANDLE hProcess)
2342{
2343 /*
2344 * Make sure there is exactly one executable image.
2345 */
2346 unsigned cExecs = 0;
2347 unsigned iExe = ~0U;
2348 unsigned i = pThis->cImages;
2349 while (i-- > 0)
2350 {
2351 if (!pThis->aImages[i].fDll)
2352 {
2353 cExecs++;
2354 iExe = i;
2355 }
2356 }
2357 if (cExecs == 0)
2358 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_NO_FOUND_NO_EXE_MAPPING,
2359 "No executable mapping found in the virtual address space.");
2360 if (cExecs != 1)
2361 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_FOUND_MORE_THAN_ONE_EXE_MAPPING,
2362 "Found more than one executable mapping in the virtual address space.");
2363 PSUPHNTVPIMAGE pImage = &pThis->aImages[iExe];
2364
2365 /*
2366 * Check that it matches the executable image of the process.
2367 */
2368 int rc;
2369 ULONG cbUniStr = sizeof(UNICODE_STRING) + RTPATH_MAX * sizeof(RTUTF16);
2370 PUNICODE_STRING pUniStr = (PUNICODE_STRING)RTMemAllocZ(cbUniStr);
2371 if (!pUniStr)
2372 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_NO_MEMORY,
2373 "Error allocating %zu bytes for process name.", cbUniStr);
2374 ULONG cbIgn = 0;
2375 NTSTATUS rcNt = NtQueryInformationProcess(hProcess, ProcessImageFileName, pUniStr, cbUniStr - sizeof(WCHAR), &cbIgn);
2376 if (NT_SUCCESS(rcNt))
2377 {
2378 if (supHardNtVpAreUniStringsEqual(pUniStr, &pImage->Name.UniStr))
2379 rc = VINF_SUCCESS;
2380 else
2381 {
2382 pUniStr->Buffer[pUniStr->Length / sizeof(WCHAR)] = '\0';
2383 rc = supHardNtVpSetInfo2(pThis, VERR_SUP_VP_EXE_VS_PROC_NAME_MISMATCH,
2384 "Process image name does not match the exectuable we found: %ls vs %ls.",
2385 pUniStr->Buffer, pImage->Name.UniStr.Buffer);
2386 }
2387 }
2388 else
2389 rc = supHardNtVpSetInfo2(pThis, VERR_SUP_VP_NT_QI_PROCESS_NM_ERROR,
2390 "NtQueryInformationProcess/ProcessImageFileName failed: %#x", rcNt);
2391 RTMemFree(pUniStr);
2392 if (RT_FAILURE(rc))
2393 return rc;
2394
2395 /*
2396 * Validate the signing of the executable image.
2397 * This will load the fDllCharecteristics and fImageCharecteristics members we use below.
2398 */
2399 rc = supHardNtVpVerifyImage(pThis, pImage, hProcess);
2400 if (RT_FAILURE(rc))
2401 return rc;
2402
2403 /*
2404 * Check linking requirements.
2405 * This query is only available using the current process pseudo handle on
2406 * older windows versions. The cut-off seems to be Vista.
2407 */
2408 SECTION_IMAGE_INFORMATION ImageInfo;
2409 rcNt = NtQueryInformationProcess(hProcess, ProcessImageInformation, &ImageInfo, sizeof(ImageInfo), NULL);
2410 if (!NT_SUCCESS(rcNt))
2411 {
2412 if ( rcNt == STATUS_INVALID_PARAMETER
2413 && g_uNtVerCombined < SUP_NT_VER_VISTA
2414 && hProcess != NtCurrentProcess() )
2415 return VINF_SUCCESS;
2416 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_NT_QI_PROCESS_IMG_INFO_ERROR,
2417 "NtQueryInformationProcess/ProcessImageInformation failed: %#x hProcess=%#x", rcNt, hProcess);
2418 }
2419 if ( !(ImageInfo.DllCharacteristics & IMAGE_DLLCHARACTERISTICS_FORCE_INTEGRITY))
2420 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_EXE_MISSING_FORCE_INTEGRITY,
2421 "EXE DllCharacteristics=%#x, expected IMAGE_DLLCHARACTERISTICS_FORCE_INTEGRITY to be set.",
2422 ImageInfo.DllCharacteristics);
2423 if (!(ImageInfo.DllCharacteristics & IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE))
2424 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_EXE_MISSING_DYNAMIC_BASE,
2425 "EXE DllCharacteristics=%#x, expected IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE to be set.",
2426 ImageInfo.DllCharacteristics);
2427 if (!(ImageInfo.DllCharacteristics & IMAGE_DLLCHARACTERISTICS_NX_COMPAT))
2428 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_EXE_MISSING_NX_COMPAT,
2429 "EXE DllCharacteristics=%#x, expected IMAGE_DLLCHARACTERISTICS_NX_COMPAT to be set.",
2430 ImageInfo.DllCharacteristics);
2431
2432 if (pImage->fDllCharecteristics != ImageInfo.DllCharacteristics)
2433 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_DLL_CHARECTERISTICS_MISMATCH,
2434 "EXE Info.DllCharacteristics=%#x fDllCharecteristics=%#x.",
2435 ImageInfo.DllCharacteristics, pImage->fDllCharecteristics);
2436
2437 if (pImage->fImageCharecteristics != ImageInfo.ImageCharacteristics)
2438 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_DLL_CHARECTERISTICS_MISMATCH,
2439 "EXE Info.ImageCharacteristics=%#x fImageCharecteristics=%#x.",
2440 ImageInfo.ImageCharacteristics, pImage->fImageCharecteristics);
2441
2442 return VINF_SUCCESS;
2443}
2444
2445
2446/**
2447 * Check the integrity of the DLLs found in the process.
2448 *
2449 * @returns VBox status code.
2450 * @param pThis The process scanning state structure. Details
2451 * about images are added to this.
2452 * @param hProcess The process to verify.
2453 */
2454static int supHardNtVpCheckDlls(PSUPHNTVPSTATE pThis, HANDLE hProcess)
2455{
2456 /*
2457 * Check for duplicate entries (paranoia).
2458 */
2459 uint32_t i = pThis->cImages;
2460 while (i-- > 1)
2461 {
2462 const char *pszName = pThis->aImages[i].pszName;
2463 uint32_t j = i;
2464 while (j-- > 0)
2465 if (pThis->aImages[j].pszName == pszName)
2466 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_DUPLICATE_DLL_MAPPING,
2467 "Duplicate image entries for %s: %ls and %ls",
2468 pszName, pThis->aImages[i].Name.UniStr.Buffer, pThis->aImages[j].Name.UniStr.Buffer);
2469 }
2470
2471 /*
2472 * Check that both ntdll and kernel32 are present.
2473 * ASSUMES the entries in g_apszSupNtVpAllowedDlls are all lower case.
2474 */
2475 uint32_t iNtDll = UINT32_MAX;
2476 uint32_t iKernel32 = UINT32_MAX;
2477 i = pThis->cImages;
2478 while (i-- > 0)
2479 if (suplibHardenedStrCmp(pThis->aImages[i].pszName, "ntdll.dll") == 0)
2480 iNtDll = i;
2481 else if (suplibHardenedStrCmp(pThis->aImages[i].pszName, "kernel32.dll") == 0)
2482 iKernel32 = i;
2483 if (iNtDll == UINT32_MAX)
2484 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_NO_NTDLL_MAPPING,
2485 "The process has no NTDLL.DLL.");
2486 if (iKernel32 == UINT32_MAX && pThis->enmKind == SUPHARDNTVPKIND_SELF_PURIFICATION)
2487 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_NO_KERNEL32_MAPPING,
2488 "The process has no KERNEL32.DLL.");
2489 else if (iKernel32 != UINT32_MAX && pThis->enmKind == SUPHARDNTVPKIND_CHILD_PURIFICATION)
2490 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_KERNEL32_ALREADY_MAPPED,
2491 "The process already has KERNEL32.DLL loaded.");
2492
2493 /*
2494 * Verify that the DLLs are correctly signed (by MS).
2495 */
2496 i = pThis->cImages;
2497 while (i-- > 0)
2498 {
2499 int rc = supHardNtVpVerifyImage(pThis, &pThis->aImages[i], hProcess);
2500 if (RT_FAILURE(rc))
2501 return rc;
2502 }
2503
2504 return VINF_SUCCESS;
2505}
2506
2507
2508/**
2509 * Verifies the given process.
2510 *
2511 * The following requirements are checked:
2512 * - The process only has one thread, the calling thread.
2513 * - The process has no debugger attached.
2514 * - The executable image of the process is verified to be signed with
2515 * certificate known to this code at build time.
2516 * - The executable image is one of a predefined set.
2517 * - The process has only a very limited set of system DLLs loaded.
2518 * - The system DLLs signatures check out fine.
2519 * - The only executable memory in the process belongs to the system DLLs and
2520 * the executable image.
2521 *
2522 * @returns VBox status code.
2523 * @param hProcess The process to verify.
2524 * @param hThread A thread in the process (the caller).
2525 * @param enmKind The kind of process verification to perform.
2526 * @param fFlags Valid combination of SUPHARDNTVP_F_XXX flags.
2527 * @param pErrInfo Pointer to error info structure. Optional.
2528 * @param pcFixes Where to return the number of fixes made during
2529 * purification. Optional.
2530 */
2531DECLHIDDEN(int) supHardenedWinVerifyProcess(HANDLE hProcess, HANDLE hThread, SUPHARDNTVPKIND enmKind, uint32_t fFlags,
2532 uint32_t *pcFixes, PRTERRINFO pErrInfo)
2533{
2534 if (pcFixes)
2535 *pcFixes = 0;
2536
2537 /*
2538 * Some basic checks regarding threads and debuggers. We don't need
2539 * allocate any state memory for these.
2540 */
2541 int rc = VINF_SUCCESS;
2542 if (enmKind != SUPHARDNTVPKIND_CHILD_PURIFICATION)
2543 rc = supHardNtVpThread(hProcess, hThread, pErrInfo);
2544 if (RT_SUCCESS(rc))
2545 rc = supHardNtVpDebugger(hProcess, pErrInfo);
2546 if (RT_SUCCESS(rc))
2547 {
2548 /*
2549 * Allocate and initialize memory for the state.
2550 */
2551 PSUPHNTVPSTATE pThis = (PSUPHNTVPSTATE)RTMemAllocZ(sizeof(*pThis));
2552 if (pThis)
2553 {
2554 pThis->enmKind = enmKind;
2555 pThis->fFlags = fFlags;
2556 pThis->rcResult = VINF_SUCCESS;
2557 pThis->hProcess = hProcess;
2558 pThis->pErrInfo = pErrInfo;
2559
2560 /*
2561 * Perform the verification.
2562 */
2563 rc = supHardNtVpScanVirtualMemory(pThis, hProcess);
2564 if (RT_SUCCESS(rc))
2565 rc = supHardNtVpOpenImages(pThis);
2566 if (RT_SUCCESS(rc))
2567 rc = supHardNtVpCheckExe(pThis, hProcess);
2568 if (RT_SUCCESS(rc))
2569 rc = supHardNtVpCheckDlls(pThis, hProcess);
2570
2571 if (pcFixes)
2572 *pcFixes = pThis->cFixes;
2573
2574 /*
2575 * Clean up the state.
2576 */
2577#ifdef IN_RING0
2578 for (uint32_t i = 0; i < pThis->cImages; i++)
2579 supHardNTLdrCacheDeleteEntry(&pThis->aImages[i].CacheEntry);
2580#endif
2581 RTMemFree(pThis);
2582 }
2583 else
2584 rc = supHardNtVpSetInfo1(pErrInfo, VERR_SUP_VP_NO_MEMORY_STATE,
2585 "Failed to allocate %zu bytes for state structures.", sizeof(*pThis));
2586 }
2587 return rc;
2588}
2589
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