VirtualBox

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

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

SUPHardNt: Extended the free/replace unknown exec memory trick a little.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 102.7 KB
Line 
1/* $Id: SUPHardenedVerifyProcess-win.cpp 54993 2015-03-27 15:57:07Z 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 VBox status code.
1548 * @param pThis The process scanning state structure. Details
1549 * about images are added to this.
1550 * @param hProcess The process to verify.
1551 * @param pMemInfo The information we've got on this private
1552 * executable memory.
1553 */
1554static void supHardNtVpFreeOrReplacePrivateExecMemory(PSUPHNTVPSTATE pThis, HANDLE hProcess,
1555 MEMORY_BASIC_INFORMATION const *pMemInfo)
1556{
1557 NTSTATUS rcNt;
1558
1559 /*
1560 * Try figure if the entire allocation size. Free/Alloc may fail otherwise.
1561 */
1562 PVOID pvFree = pMemInfo->AllocationBase;
1563 SIZE_T cbFree = pMemInfo->RegionSize + ((uintptr_t)pMemInfo->BaseAddress - (uintptr_t)pMemInfo->AllocationBase);
1564 for (;;)
1565 {
1566 SIZE_T cbActual = 0;
1567 MEMORY_BASIC_INFORMATION MemInfo2 = { 0, 0, 0, 0, 0, 0, 0 };
1568 uintptr_t uPtrNext = (uintptr_t)pvFree + cbFree;
1569 rcNt = g_pfnNtQueryVirtualMemory(hProcess,
1570 (void const *)uPtrNext,
1571 MemoryBasicInformation,
1572 &MemInfo2,
1573 sizeof(MemInfo2),
1574 &cbActual);
1575 if (!NT_SUCCESS(rcNt))
1576 break;
1577 if (pMemInfo->AllocationBase != MemInfo2.AllocationBase)
1578 break;
1579 }
1580 SUP_DPRINTF(("supHardNtVpFreeOrReplacePrivateExecMemory: %s exec mem at %p (LB %#zx, %p LB %#zx)\n",
1581 pThis->fFlags & SUPHARDNTVP_F_EXEC_ALLOC_REPLACE_WITH_RW ? "Replacing" : "Freeing",
1582 pvFree, cbFree, pMemInfo->BaseAddress, pMemInfo->RegionSize));
1583
1584 /*
1585 * In the BSOD workaround mode, we need to make a copy of the memory before
1586 * freeing it.
1587 */
1588 uintptr_t uCopySrc = (uintptr_t)pvFree;
1589 size_t cbCopy = 0;
1590 void *pvCopy = NULL;
1591 if (pThis->fFlags & SUPHARDNTVP_F_EXEC_ALLOC_REPLACE_WITH_RW)
1592 {
1593 cbCopy = cbFree;
1594 pvCopy = RTMemAllocZ(cbCopy);
1595 if (!pvCopy)
1596 {
1597 supHardNtVpSetInfo2(pThis, VERR_SUP_VP_REPLACE_VIRTUAL_MEMORY_FAILED, "RTMemAllocZ(%#zx) failed", cbCopy);
1598 return;
1599 }
1600
1601 rcNt = supHardNtVpReadMem(hProcess, uCopySrc, pvCopy, cbCopy);
1602 if (!NT_SUCCESS(rcNt))
1603 supHardNtVpSetInfo2(pThis, VERR_SUP_VP_REPLACE_VIRTUAL_MEMORY_FAILED,
1604 "Error reading data from original alloc: %#x (%p LB %#zx)", rcNt, uCopySrc, cbCopy, rcNt);
1605 }
1606
1607 /*
1608 * Free the memory.
1609 */
1610 for (uint32_t i = 0; i < 10; i++)
1611 {
1612 PVOID pvFreeInOut = pvFree;
1613 SIZE_T cbFreeInOut = 0;
1614 rcNt = NtFreeVirtualMemory(hProcess, &pvFreeInOut, &cbFreeInOut, MEM_RELEASE);
1615 if (!NT_SUCCESS(rcNt))
1616 {
1617 SUP_DPRINTF(("supHardNtVpFreeOrReplacePrivateExecMemory: Free attempt #1 failed: %#x [%p LB 0]\n", rcNt, pvFree));
1618 pvFreeInOut = pvFree;
1619 cbFreeInOut = cbFree;
1620 rcNt = NtFreeVirtualMemory(hProcess, &pvFreeInOut, &cbFreeInOut, MEM_RELEASE);
1621 if (!NT_SUCCESS(rcNt))
1622 {
1623 SUP_DPRINTF(("supHardNtVpFreeOrReplacePrivateExecMemory: Free attempt #2 failed: %#x [%p LB %#zx]\n",
1624 rcNt, pvFree, cbFree));
1625 pvFreeInOut = pMemInfo->BaseAddress;
1626 cbFreeInOut = pMemInfo->RegionSize;
1627 rcNt = NtFreeVirtualMemory(hProcess, &pvFreeInOut, &cbFreeInOut, MEM_RELEASE);
1628 if (NT_SUCCESS(rcNt))
1629 {
1630 pvFree = pMemInfo->BaseAddress;
1631 cbFree = pMemInfo->RegionSize;
1632 SUP_DPRINTF(("supHardNtVpFreeOrReplacePrivateExecMemory: Free attempt #3 succeeded [%p LB %#zx]\n",
1633 pvFree, cbFree));
1634 }
1635 else
1636 supHardNtVpSetInfo2(pThis, VERR_SUP_VP_FREE_VIRTUAL_MEMORY_FAILED,
1637 "NtFreeVirtualMemory [%p LB %#zx and %p LB %#zx] failed: %#x",
1638 pvFree, cbFree, pMemInfo->BaseAddress, pMemInfo->RegionSize, rcNt);
1639 }
1640 }
1641
1642 /*
1643 * Query the region again, redo the free operation if there's still memory there.
1644 */
1645 if (!NT_SUCCESS(rcNt) || (pThis->fFlags & SUPHARDNTVP_F_EXEC_ALLOC_REPLACE_WITH_RW))
1646 break;
1647 SIZE_T cbActual = 0;
1648 MEMORY_BASIC_INFORMATION MemInfo3 = { 0, 0, 0, 0, 0, 0, 0 };
1649 NTSTATUS rcNt2 = g_pfnNtQueryVirtualMemory(hProcess, pvFree, MemoryBasicInformation,
1650 &MemInfo3, sizeof(MemInfo3), &cbActual);
1651 if (!NT_SUCCESS(rcNt2))
1652 break;
1653 SUP_DPRINTF(("supHardNtVpFreeOrReplacePrivateExecMemory: QVM after free %u: [%p]/%p LB %#zx s=%#x ap=%#x rp=%#p\n",
1654 i, MemInfo3.AllocationBase, MemInfo3.BaseAddress, MemInfo3.RegionSize, MemInfo3.State,
1655 MemInfo3.AllocationProtect, MemInfo3.Protect));
1656 if (pMemInfo->State == MEM_FREE)
1657 break;
1658 SUP_DPRINTF(("supHardNtVpFreeOrReplacePrivateExecMemory: Retrying free...\n"));
1659 }
1660
1661 /*
1662 * Restore memory as non-executable - Kludge for Trend Micro sakfile.sys
1663 * and Digital Guardian dgmaster.sys BSODs.
1664 */
1665 if (NT_SUCCESS(rcNt) && (pThis->fFlags & SUPHARDNTVP_F_EXEC_ALLOC_REPLACE_WITH_RW))
1666 {
1667 PVOID pvAlloc = pvFree;
1668 SIZE_T cbAlloc = cbFree;
1669 rcNt = NtAllocateVirtualMemory(hProcess, &pvAlloc, 0, &cbAlloc, MEM_COMMIT, PAGE_READWRITE);
1670 if (!NT_SUCCESS(rcNt))
1671 supHardNtVpSetInfo2(pThis, VERR_SUP_VP_REPLACE_VIRTUAL_MEMORY_FAILED,
1672 "NtAllocateVirtualMemory (%p LB %#zx) failed with rcNt=%#x allocating "
1673 "replacement memory for working around buggy protection software. "
1674 "See VBoxStartup.log for more details",
1675 pvAlloc, cbFree, rcNt);
1676 else if ( (uintptr_t)pvFree < (uintptr_t)pvAlloc
1677 || (uintptr_t)pvFree + cbFree > (uintptr_t)pvAlloc + cbFree)
1678 supHardNtVpSetInfo2(pThis, VERR_SUP_VP_REPLACE_VIRTUAL_MEMORY_FAILED,
1679 "We wanted NtAllocateVirtualMemory to get us %p LB %#zx, but it returned %p LB %#zx.",
1680 pMemInfo->BaseAddress, pMemInfo->RegionSize, pvFree, cbFree, rcNt);
1681 else
1682 {
1683 /*
1684 * Copy what we can, considering the 2nd free attempt.
1685 */
1686 uint8_t *pbDst = (uint8_t *)pvFree;
1687 size_t cbDst = cbFree;
1688 uint8_t *pbSrc = (uint8_t *)pvCopy;
1689 size_t cbSrc = cbCopy;
1690 if ((uintptr_t)pbDst != uCopySrc)
1691 {
1692 if ((uintptr_t)pbDst > uCopySrc)
1693 {
1694 uintptr_t cbAdj = (uintptr_t)pbDst - uCopySrc;
1695 pbSrc += cbAdj;
1696 cbSrc -= cbSrc;
1697 }
1698 else
1699 {
1700 uintptr_t cbAdj = uCopySrc - (uintptr_t)pbDst;
1701 pbDst += cbAdj;
1702 cbDst -= cbAdj;
1703 }
1704 }
1705 if (cbSrc > cbDst)
1706 cbSrc = cbDst;
1707
1708 SIZE_T cbWritten;
1709 rcNt = NtWriteVirtualMemory(hProcess, pbDst, pbSrc, cbSrc, &cbWritten);
1710 if (!NT_SUCCESS(rcNt))
1711 supHardNtVpSetInfo2(pThis, VERR_SUP_VP_FREE_VIRTUAL_MEMORY_FAILED,
1712 "NtWriteVirtualMemory (%p LB %#zx) failed: %#x",
1713 pMemInfo->BaseAddress, pMemInfo->RegionSize, rcNt);
1714 }
1715 }
1716 if (pvCopy)
1717 RTMemFree(pvCopy);
1718}
1719#endif /* IN_RING3 */
1720
1721
1722/**
1723 * Scans the virtual memory of the process.
1724 *
1725 * This collects the locations of DLLs and the EXE, and verifies that executable
1726 * memory is only associated with these. May trash pThis->abMemory.
1727 *
1728 * @returns VBox status code.
1729 * @param pThis The process scanning state structure. Details
1730 * about images are added to this.
1731 * @param hProcess The process to verify.
1732 */
1733static int supHardNtVpScanVirtualMemory(PSUPHNTVPSTATE pThis, HANDLE hProcess)
1734{
1735 SUP_DPRINTF(("supHardNtVpScanVirtualMemory: enmKind=%s\n",
1736 pThis->enmKind == SUPHARDNTVPKIND_VERIFY_ONLY ? "VERIFY_ONLY" :
1737 pThis->enmKind == SUPHARDNTVPKIND_CHILD_PURIFICATION ? "CHILD_PURIFICATION" : "SELF_PURIFICATION"));
1738
1739 uint32_t cXpExceptions = 0;
1740 uintptr_t cbAdvance = 0;
1741 uintptr_t uPtrWhere = 0;
1742#ifdef VBOX_PERMIT_VERIFIER_DLL
1743 for (uint32_t i = 0; i < 10240; i++)
1744#else
1745 for (uint32_t i = 0; i < 1024; i++)
1746#endif
1747 {
1748 SIZE_T cbActual = 0;
1749 MEMORY_BASIC_INFORMATION MemInfo = { 0, 0, 0, 0, 0, 0, 0 };
1750 NTSTATUS rcNt = g_pfnNtQueryVirtualMemory(hProcess,
1751 (void const *)uPtrWhere,
1752 MemoryBasicInformation,
1753 &MemInfo,
1754 sizeof(MemInfo),
1755 &cbActual);
1756 if (!NT_SUCCESS(rcNt))
1757 {
1758 if (rcNt == STATUS_INVALID_PARAMETER)
1759 return pThis->rcResult;
1760 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_NT_QI_VIRTUAL_MEMORY_ERROR,
1761 "NtQueryVirtualMemory failed for %p: %#x", uPtrWhere, rcNt);
1762 }
1763
1764 /*
1765 * Record images.
1766 */
1767 if ( MemInfo.Type == SEC_IMAGE
1768 || MemInfo.Type == SEC_PROTECTED_IMAGE
1769 || MemInfo.Type == (SEC_IMAGE | SEC_PROTECTED_IMAGE))
1770 {
1771 uint32_t iImg = pThis->cImages;
1772 rcNt = g_pfnNtQueryVirtualMemory(hProcess,
1773 (void const *)uPtrWhere,
1774 MemorySectionName,
1775 &pThis->aImages[iImg].Name,
1776 sizeof(pThis->aImages[iImg].Name) - sizeof(WCHAR),
1777 &cbActual);
1778 if (!NT_SUCCESS(rcNt))
1779 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_NT_QI_VIRTUAL_MEMORY_NM_ERROR,
1780 "NtQueryVirtualMemory/MemorySectionName failed for %p: %#x", uPtrWhere, rcNt);
1781 pThis->aImages[iImg].Name.UniStr.Buffer[pThis->aImages[iImg].Name.UniStr.Length / sizeof(WCHAR)] = '\0';
1782 SUP_DPRINTF((MemInfo.AllocationBase == MemInfo.BaseAddress
1783 ? " *%p-%p %#06x/%#06x %#09x %ls\n"
1784 : " %p-%p %#06x/%#06x %#09x %ls\n",
1785 MemInfo.BaseAddress, (uintptr_t)MemInfo.BaseAddress + MemInfo.RegionSize - 1, MemInfo.Protect,
1786 MemInfo.AllocationProtect, MemInfo.Type, pThis->aImages[iImg].Name.UniStr.Buffer));
1787
1788 /* New or existing image? */
1789 bool fNew = true;
1790 uint32_t iSearch = iImg;
1791 while (iSearch-- > 0)
1792 if (supHardNtVpAreUniStringsEqual(&pThis->aImages[iSearch].Name.UniStr, &pThis->aImages[iImg].Name.UniStr))
1793 {
1794 int rc = supHardNtVpAddRegion(pThis, &pThis->aImages[iSearch], &MemInfo);
1795 if (RT_FAILURE(rc))
1796 return rc;
1797 fNew = false;
1798 break;
1799 }
1800 else if (pThis->aImages[iSearch].uImageBase == (uintptr_t)MemInfo.AllocationBase)
1801 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_NT_MAPPING_NAME_CHANGED,
1802 "Unexpected base address match");
1803
1804 if (fNew)
1805 {
1806 int rc = supHardNtVpNewImage(pThis, &pThis->aImages[iImg], &MemInfo);
1807 if (RT_SUCCESS(rc))
1808 {
1809 if (rc != VINF_OBJECT_DESTROYED)
1810 {
1811 pThis->cImages++;
1812 if (pThis->cImages >= RT_ELEMENTS(pThis->aImages))
1813 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_TOO_MANY_DLLS_LOADED,
1814 "Internal error: aImages is full.\n");
1815 }
1816 }
1817#ifdef IN_RING3 /* Continue and add more information if unknown DLLs are found. */
1818 else if (rc != VERR_SUP_VP_NOT_KNOWN_DLL_OR_EXE && rc != VERR_SUP_VP_NON_SYSTEM32_DLL)
1819 return rc;
1820#else
1821 else
1822 return rc;
1823#endif
1824 }
1825 }
1826 /*
1827 * XP, W2K3: Ignore the CSRSS read-only region as best we can.
1828 */
1829 else if ( (MemInfo.Protect & (PAGE_EXECUTE | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY))
1830 == PAGE_EXECUTE_READ
1831 && cXpExceptions == 0
1832 && (uintptr_t)MemInfo.BaseAddress >= UINT32_C(0x78000000)
1833 /* && MemInfo.BaseAddress == pPeb->ReadOnlySharedMemoryBase */
1834 && g_uNtVerCombined < SUP_MAKE_NT_VER_SIMPLE(6, 0) )
1835 {
1836 cXpExceptions++;
1837 SUP_DPRINTF((" %p-%p %#06x/%#06x %#09x XP CSRSS read-only region\n", MemInfo.BaseAddress,
1838 (uintptr_t)MemInfo.BaseAddress - MemInfo.RegionSize - 1, MemInfo.Protect,
1839 MemInfo.AllocationProtect, MemInfo.Type));
1840 }
1841 /*
1842 * Executable memory?
1843 */
1844#ifndef VBOX_PERMIT_VISUAL_STUDIO_PROFILING
1845 else if (MemInfo.Protect & (PAGE_EXECUTE | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY))
1846 {
1847 SUP_DPRINTF((MemInfo.AllocationBase == MemInfo.BaseAddress
1848 ? " *%p-%p %#06x/%#06x %#09x !!\n"
1849 : " %p-%p %#06x/%#06x %#09x !!\n",
1850 MemInfo.BaseAddress, (uintptr_t)MemInfo.BaseAddress - MemInfo.RegionSize - 1,
1851 MemInfo.Protect, MemInfo.AllocationProtect, MemInfo.Type));
1852# ifdef IN_RING3
1853 if (pThis->enmKind == SUPHARDNTVPKIND_CHILD_PURIFICATION)
1854 {
1855 /*
1856 * Free any private executable memory (sysplant.sys allocates executable memory).
1857 */
1858 if (MemInfo.Type == MEM_PRIVATE)
1859 supHardNtVpFreeOrReplacePrivateExecMemory(pThis, hProcess, &MemInfo);
1860 /*
1861 * Unmap mapped memory, failing that, drop exec privileges.
1862 */
1863 else if (MemInfo.Type == MEM_MAPPED)
1864 {
1865 SUP_DPRINTF(("supHardNtVpScanVirtualMemory: Unmapping exec mem at %p (%p/%p LB %#zx)\n",
1866 uPtrWhere, MemInfo.AllocationBase, MemInfo.BaseAddress, MemInfo.RegionSize));
1867 rcNt = NtUnmapViewOfSection(hProcess, MemInfo.AllocationBase);
1868 if (!NT_SUCCESS(rcNt))
1869 {
1870 PVOID pvCopy = MemInfo.BaseAddress;
1871 SIZE_T cbCopy = MemInfo.RegionSize;
1872 NTSTATUS rcNt2 = NtProtectVirtualMemory(hProcess, &pvCopy, &cbCopy, PAGE_NOACCESS, NULL);
1873 if (!NT_SUCCESS(rcNt2))
1874 rcNt2 = NtProtectVirtualMemory(hProcess, &pvCopy, &cbCopy, PAGE_READONLY, NULL);
1875 if (!NT_SUCCESS(rcNt2))
1876 supHardNtVpSetInfo2(pThis, VERR_SUP_VP_UNMAP_AND_PROTECT_FAILED,
1877 "NtUnmapViewOfSection (%p/%p LB %#zx) failed: %#x (%#x)",
1878 MemInfo.AllocationBase, MemInfo.BaseAddress, MemInfo.RegionSize, rcNt, rcNt2);
1879 }
1880 }
1881 else
1882 supHardNtVpSetInfo2(pThis, VERR_SUP_VP_UNKOWN_MEM_TYPE,
1883 "Unknown executable memory type %#x at %p/%p LB %#zx",
1884 MemInfo.Type, MemInfo.AllocationBase, MemInfo.BaseAddress, MemInfo.RegionSize);
1885 pThis->cFixes++;
1886 }
1887 else
1888# endif /* IN_RING3 */
1889 supHardNtVpSetInfo2(pThis, VERR_SUP_VP_FOUND_EXEC_MEMORY,
1890 "Found executable memory at %p (%p LB %#zx): type=%#x prot=%#x state=%#x aprot=%#x abase=%p",
1891 uPtrWhere, MemInfo.BaseAddress, MemInfo.RegionSize, MemInfo.Type, MemInfo.Protect,
1892 MemInfo.State, MemInfo.AllocationBase, MemInfo.AllocationProtect);
1893
1894# ifndef IN_RING3
1895 if (RT_FAILURE(pThis->rcResult))
1896 return pThis->rcResult;
1897# endif
1898 /* Continue add more information about the problematic process. */
1899 }
1900#endif /* VBOX_PERMIT_VISUAL_STUDIO_PROFILING */
1901 else
1902 SUP_DPRINTF((MemInfo.AllocationBase == MemInfo.BaseAddress
1903 ? " *%p-%p %#06x/%#06x %#09x\n"
1904 : " %p-%p %#06x/%#06x %#09x\n",
1905 MemInfo.BaseAddress, (uintptr_t)MemInfo.BaseAddress - MemInfo.RegionSize - 1,
1906 MemInfo.Protect, MemInfo.AllocationProtect, MemInfo.Type));
1907
1908 /*
1909 * Advance.
1910 */
1911 cbAdvance = MemInfo.RegionSize;
1912 if (uPtrWhere + cbAdvance <= uPtrWhere)
1913 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_EMPTY_REGION_TOO_LARGE,
1914 "Empty region at %p.", uPtrWhere);
1915 uPtrWhere += MemInfo.RegionSize;
1916 }
1917
1918 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_TOO_MANY_MEMORY_REGIONS,
1919 "Too many virtual memory regions.\n");
1920}
1921
1922
1923/**
1924 * Verifies the loader image, i.e. check cryptographic signatures if present.
1925 *
1926 * @returns VBox status code.
1927 * @param pEntry The loader cache entry.
1928 * @param pwszName The filename to use in error messages.
1929 * @param pErRInfo Where to return extened error information.
1930 */
1931DECLHIDDEN(int) supHardNtLdrCacheEntryVerify(PSUPHNTLDRCACHEENTRY pEntry, PCRTUTF16 pwszName, PRTERRINFO pErrInfo)
1932{
1933 int rc = VINF_SUCCESS;
1934 if (!pEntry->fVerified)
1935 {
1936 rc = supHardenedWinVerifyImageByLdrMod(pEntry->hLdrMod, pwszName, pEntry->pNtViRdr,
1937 false /*fAvoidWinVerifyTrust*/, NULL /*pfWinVerifyTrust*/, pErrInfo);
1938 pEntry->fVerified = RT_SUCCESS(rc);
1939 }
1940 return rc;
1941}
1942
1943
1944/**
1945 * Allocates a image bits buffer and calls RTLdrGetBits on them.
1946 *
1947 * An assumption here is that there won't ever be concurrent use of the cache.
1948 * It's currently 104% single threaded, non-reentrant. Thus, we can't reuse the
1949 * pbBits allocation.
1950 *
1951 * @returns VBox status code
1952 * @param pEntry The loader cache entry.
1953 * @param ppbBits Where to return the pointer to the allocation.
1954 * @param uBaseAddress The image base address, see RTLdrGetBits.
1955 * @param pfnGetImport Import getter, see RTLdrGetBits.
1956 * @param pvUser The user argument for @a pfnGetImport.
1957 * @param pErrInfo Where to return extened error information.
1958 */
1959DECLHIDDEN(int) supHardNtLdrCacheEntryGetBits(PSUPHNTLDRCACHEENTRY pEntry, uint8_t **ppbBits,
1960 RTLDRADDR uBaseAddress, PFNRTLDRIMPORT pfnGetImport, void *pvUser,
1961 PRTERRINFO pErrInfo)
1962{
1963 int rc;
1964
1965 /*
1966 * First time around we have to allocate memory before we can get the image bits.
1967 */
1968 if (!pEntry->pbBits)
1969 {
1970 size_t cbBits = RTLdrSize(pEntry->hLdrMod);
1971 if (cbBits >= _1M*32U)
1972 return supHardNtVpSetInfo1(pErrInfo, VERR_SUP_VP_IMAGE_TOO_BIG, "Image %s is too large: %zu bytes (%#zx).",
1973 pEntry->pszName, cbBits, cbBits);
1974
1975 pEntry->pbBits = (uint8_t *)RTMemAllocZ(cbBits);
1976 if (!pEntry->pbBits)
1977 return supHardNtVpSetInfo1(pErrInfo, VERR_SUP_VP_NO_MEMORY, "Failed to allocate %zu bytes for image %s.",
1978 cbBits, pEntry->pszName);
1979
1980 pEntry->fValidBits = false; /* paranoia */
1981
1982 rc = RTLdrGetBits(pEntry->hLdrMod, pEntry->pbBits, uBaseAddress, pfnGetImport, pvUser);
1983 if (RT_FAILURE(rc))
1984 return supHardNtVpSetInfo1(pErrInfo, VERR_SUP_VP_NO_MEMORY, "RTLdrGetBits failed on image %s: %Rrc",
1985 pEntry->pszName, rc);
1986 pEntry->uImageBase = uBaseAddress;
1987 pEntry->fValidBits = pfnGetImport == NULL;
1988
1989 }
1990 /*
1991 * Cache hit? No?
1992 *
1993 * Note! We cannot currently cache image bits for images with imports as we
1994 * don't control the way they're resolved. Fortunately, NTDLL and
1995 * the VM process images all have no imports.
1996 */
1997 else if ( !pEntry->fValidBits
1998 || pEntry->uImageBase != uBaseAddress
1999 || pfnGetImport)
2000 {
2001 pEntry->fValidBits = false;
2002
2003 rc = RTLdrGetBits(pEntry->hLdrMod, pEntry->pbBits, uBaseAddress, pfnGetImport, pvUser);
2004 if (RT_FAILURE(rc))
2005 return supHardNtVpSetInfo1(pErrInfo, VERR_SUP_VP_NO_MEMORY, "RTLdrGetBits failed on image %s: %Rrc",
2006 pEntry->pszName, rc);
2007 pEntry->uImageBase = uBaseAddress;
2008 pEntry->fValidBits = pfnGetImport == NULL;
2009 }
2010
2011 *ppbBits = pEntry->pbBits;
2012 return VINF_SUCCESS;
2013}
2014
2015
2016/**
2017 * Frees all resources associated with a cache entry and wipes the members
2018 * clean.
2019 *
2020 * @param pEntry The entry to delete.
2021 */
2022static void supHardNTLdrCacheDeleteEntry(PSUPHNTLDRCACHEENTRY pEntry)
2023{
2024 if (pEntry->pbBits)
2025 {
2026 RTMemFree(pEntry->pbBits);
2027 pEntry->pbBits = NULL;
2028 }
2029
2030 if (pEntry->hLdrMod != NIL_RTLDRMOD)
2031 {
2032 RTLdrClose(pEntry->hLdrMod);
2033 pEntry->hLdrMod = NIL_RTLDRMOD;
2034 pEntry->pNtViRdr = NULL;
2035 }
2036 else if (pEntry->pNtViRdr)
2037 {
2038 pEntry->pNtViRdr->Core.pfnDestroy(&pEntry->pNtViRdr->Core);
2039 pEntry->pNtViRdr = NULL;
2040 }
2041
2042 if (pEntry->hFile)
2043 {
2044 NtClose(pEntry->hFile);
2045 pEntry->hFile = NULL;
2046 }
2047
2048 pEntry->pszName = NULL;
2049 pEntry->fVerified = false;
2050 pEntry->fValidBits = false;
2051 pEntry->uImageBase = 0;
2052}
2053
2054#ifdef IN_RING3
2055
2056/**
2057 * Flushes the cache.
2058 *
2059 * This is called from one of two points in the hardened main code, first is
2060 * after respawning and the second is when we open the vboxdrv device for
2061 * unrestricted access.
2062 */
2063DECLHIDDEN(void) supR3HardenedWinFlushLoaderCache(void)
2064{
2065 uint32_t i = g_cSupNtVpLdrCacheEntries;
2066 while (i-- > 0)
2067 supHardNTLdrCacheDeleteEntry(&g_aSupNtVpLdrCacheEntries[i]);
2068 g_cSupNtVpLdrCacheEntries = 0;
2069}
2070
2071
2072/**
2073 * Searches the cache for a loader image.
2074 *
2075 * @returns Pointer to the cache entry if found, NULL if not.
2076 * @param pszName The name (from g_apszSupNtVpAllowedVmExes or
2077 * g_apszSupNtVpAllowedDlls).
2078 */
2079static PSUPHNTLDRCACHEENTRY supHardNtLdrCacheLookupEntry(const char *pszName)
2080{
2081 /*
2082 * Since the caller is supplying us a pszName from one of the two tables,
2083 * we can dispense with string compare and simply compare string pointers.
2084 */
2085 uint32_t i = g_cSupNtVpLdrCacheEntries;
2086 while (i-- > 0)
2087 if (g_aSupNtVpLdrCacheEntries[i].pszName == pszName)
2088 return &g_aSupNtVpLdrCacheEntries[i];
2089 return NULL;
2090}
2091
2092#endif /* IN_RING3 */
2093
2094static int supHardNtLdrCacheNewEntry(PSUPHNTLDRCACHEENTRY pEntry, const char *pszName, PUNICODE_STRING pUniStrPath,
2095 bool fDll, bool f32bitResourceDll, PRTERRINFO pErrInfo)
2096{
2097 /*
2098 * Open the image file.
2099 */
2100 HANDLE hFile = RTNT_INVALID_HANDLE_VALUE;
2101 IO_STATUS_BLOCK Ios = RTNT_IO_STATUS_BLOCK_INITIALIZER;
2102
2103 OBJECT_ATTRIBUTES ObjAttr;
2104 InitializeObjectAttributes(&ObjAttr, pUniStrPath, OBJ_CASE_INSENSITIVE, NULL /*hRootDir*/, NULL /*pSecDesc*/);
2105#ifdef IN_RING0
2106 ObjAttr.Attributes |= OBJ_KERNEL_HANDLE;
2107#endif
2108
2109 NTSTATUS rcNt = NtCreateFile(&hFile,
2110 GENERIC_READ | SYNCHRONIZE,
2111 &ObjAttr,
2112 &Ios,
2113 NULL /* Allocation Size*/,
2114 FILE_ATTRIBUTE_NORMAL,
2115 FILE_SHARE_READ,
2116 FILE_OPEN,
2117 FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT,
2118 NULL /*EaBuffer*/,
2119 0 /*EaLength*/);
2120 if (NT_SUCCESS(rcNt))
2121 rcNt = Ios.Status;
2122 if (!NT_SUCCESS(rcNt))
2123 return supHardNtVpSetInfo1(pErrInfo, VERR_SUP_VP_IMAGE_FILE_OPEN_ERROR,
2124 "Error opening image for scanning: %#x (name %ls)", rcNt, pUniStrPath->Buffer);
2125
2126 /*
2127 * Figure out validation flags we'll be using and create the reader
2128 * for this image.
2129 */
2130 uint32_t fFlags = fDll
2131 ? SUPHNTVI_F_TRUSTED_INSTALLER_OWNER | SUPHNTVI_F_ALLOW_CAT_FILE_VERIFICATION
2132 : SUPHNTVI_F_REQUIRE_BUILD_CERT;
2133 if (f32bitResourceDll)
2134 fFlags |= SUPHNTVI_F_IGNORE_ARCHITECTURE;
2135
2136 PSUPHNTVIRDR pNtViRdr;
2137 int rc = supHardNtViRdrCreate(hFile, pUniStrPath->Buffer, fFlags, &pNtViRdr);
2138 if (RT_FAILURE(rc))
2139 {
2140 NtClose(hFile);
2141 return rc;
2142 }
2143
2144 /*
2145 * Finally, open the image with the loader
2146 */
2147 RTLDRMOD hLdrMod;
2148 RTLDRARCH enmArch = fFlags & SUPHNTVI_F_RC_IMAGE ? RTLDRARCH_X86_32 : RTLDRARCH_HOST;
2149 if (fFlags & SUPHNTVI_F_IGNORE_ARCHITECTURE)
2150 enmArch = RTLDRARCH_WHATEVER;
2151 rc = RTLdrOpenWithReader(&pNtViRdr->Core, RTLDR_O_FOR_VALIDATION, enmArch, &hLdrMod, pErrInfo);
2152 if (RT_FAILURE(rc))
2153 return supHardNtVpSetInfo1(pErrInfo, rc, "RTLdrOpenWithReader failed: %Rrc (Image='%ls').",
2154 rc, pUniStrPath->Buffer);
2155
2156 /*
2157 * Fill in the cache entry.
2158 */
2159 pEntry->pszName = pszName;
2160 pEntry->hLdrMod = hLdrMod;
2161 pEntry->pNtViRdr = pNtViRdr;
2162 pEntry->hFile = hFile;
2163 pEntry->pbBits = NULL;
2164 pEntry->fVerified = false;
2165 pEntry->fValidBits = false;
2166 pEntry->uImageBase = ~(uintptr_t)0;
2167
2168#ifdef IN_SUP_HARDENED_R3
2169 /*
2170 * Log the image timestamp when in the hardened exe.
2171 */
2172 uint64_t uTimestamp = 0;
2173 rc = RTLdrQueryProp(hLdrMod, RTLDRPROP_TIMESTAMP_SECONDS, &uTimestamp, sizeof(uint64_t));
2174 SUP_DPRINTF(("%s: timestamp %#llx (rc=%Rrc)\n", pszName, uTimestamp, rc));
2175#endif
2176
2177 return VINF_SUCCESS;
2178}
2179
2180#ifdef IN_RING3
2181/**
2182 * Opens a loader cache entry.
2183 *
2184 * Currently this is only used by the import code for getting NTDLL.
2185 *
2186 * @returns VBox status code.
2187 * @param pszName The DLL name. Must be one from the
2188 * g_apszSupNtVpAllowedDlls array.
2189 * @param ppEntry Where to return the entry we've opened/found.
2190 */
2191DECLHIDDEN(int) supHardNtLdrCacheOpen(const char *pszName, PSUPHNTLDRCACHEENTRY *ppEntry)
2192{
2193 /*
2194 * Locate the dll.
2195 */
2196 uint32_t i = 0;
2197 while ( i < RT_ELEMENTS(g_apszSupNtVpAllowedDlls)
2198 && strcmp(pszName, g_apszSupNtVpAllowedDlls[i]))
2199 i++;
2200 if (i >= RT_ELEMENTS(g_apszSupNtVpAllowedDlls))
2201 return VERR_FILE_NOT_FOUND;
2202 pszName = g_apszSupNtVpAllowedDlls[i];
2203
2204 /*
2205 * Try the cache.
2206 */
2207 *ppEntry = supHardNtLdrCacheLookupEntry(pszName);
2208 if (*ppEntry)
2209 return VINF_SUCCESS;
2210
2211 /*
2212 * Not in the cache, so open it.
2213 * Note! We cannot assume that g_System32NtPath has been initialized at this point.
2214 */
2215 if (g_cSupNtVpLdrCacheEntries >= RT_ELEMENTS(g_aSupNtVpLdrCacheEntries))
2216 return VERR_INTERNAL_ERROR_3;
2217
2218 static WCHAR s_wszSystem32[] = L"\\SystemRoot\\System32\\";
2219 WCHAR wszPath[64];
2220 memcpy(wszPath, s_wszSystem32, sizeof(s_wszSystem32));
2221 RTUtf16CatAscii(wszPath, sizeof(wszPath), pszName);
2222
2223 UNICODE_STRING UniStr;
2224 UniStr.Buffer = wszPath;
2225 UniStr.Length = (USHORT)(RTUtf16Len(wszPath) * sizeof(WCHAR));
2226 UniStr.MaximumLength = UniStr.Length + sizeof(WCHAR);
2227
2228 int rc = supHardNtLdrCacheNewEntry(&g_aSupNtVpLdrCacheEntries[g_cSupNtVpLdrCacheEntries], pszName, &UniStr,
2229 true /*fDll*/, false /*f32bitResourceDll*/, NULL /*pErrInfo*/);
2230 if (RT_SUCCESS(rc))
2231 {
2232 *ppEntry = &g_aSupNtVpLdrCacheEntries[g_cSupNtVpLdrCacheEntries];
2233 g_cSupNtVpLdrCacheEntries++;
2234 return VINF_SUCCESS;
2235 }
2236 return rc;
2237}
2238#endif /* IN_RING3 */
2239
2240
2241/**
2242 * Opens all the images with the IPRT loader, setting both, hFile, pNtViRdr and
2243 * hLdrMod for each image.
2244 *
2245 * @returns VBox status code.
2246 * @param pThis The process scanning state structure.
2247 */
2248static int supHardNtVpOpenImages(PSUPHNTVPSTATE pThis)
2249{
2250 unsigned i = pThis->cImages;
2251 while (i-- > 0)
2252 {
2253 PSUPHNTVPIMAGE pImage = &pThis->aImages[i];
2254
2255#ifdef IN_RING3
2256 /*
2257 * Try the cache first.
2258 */
2259 pImage->pCacheEntry = supHardNtLdrCacheLookupEntry(pImage->pszName);
2260 if (pImage->pCacheEntry)
2261 continue;
2262
2263 /*
2264 * Not in the cache, so load it into the cache.
2265 */
2266 if (g_cSupNtVpLdrCacheEntries >= RT_ELEMENTS(g_aSupNtVpLdrCacheEntries))
2267 return supHardNtVpSetInfo2(pThis, VERR_INTERNAL_ERROR_3, "Loader cache overflow.");
2268 pImage->pCacheEntry = &g_aSupNtVpLdrCacheEntries[g_cSupNtVpLdrCacheEntries];
2269#else
2270 /*
2271 * In ring-0 we don't have a cache at the moment (resource reasons), so
2272 * we have a static cache entry in each image structure that we use instead.
2273 */
2274 pImage->pCacheEntry = &pImage->CacheEntry;
2275#endif
2276
2277 int rc = supHardNtLdrCacheNewEntry(pImage->pCacheEntry, pImage->pszName, &pImage->Name.UniStr,
2278 pImage->fDll, pImage->f32bitResourceDll, pThis->pErrInfo);
2279 if (RT_FAILURE(rc))
2280 return rc;
2281#ifdef IN_RING3
2282 g_cSupNtVpLdrCacheEntries++;
2283#endif
2284 }
2285
2286 return VINF_SUCCESS;
2287}
2288
2289
2290/**
2291 * Check the integrity of the executable of the process.
2292 *
2293 * @returns VBox status code.
2294 * @param pThis The process scanning state structure. Details
2295 * about images are added to this.
2296 * @param hProcess The process to verify.
2297 */
2298static int supHardNtVpCheckExe(PSUPHNTVPSTATE pThis, HANDLE hProcess)
2299{
2300 /*
2301 * Make sure there is exactly one executable image.
2302 */
2303 unsigned cExecs = 0;
2304 unsigned iExe = ~0U;
2305 unsigned i = pThis->cImages;
2306 while (i-- > 0)
2307 {
2308 if (!pThis->aImages[i].fDll)
2309 {
2310 cExecs++;
2311 iExe = i;
2312 }
2313 }
2314 if (cExecs == 0)
2315 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_NO_FOUND_NO_EXE_MAPPING,
2316 "No executable mapping found in the virtual address space.");
2317 if (cExecs != 1)
2318 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_FOUND_MORE_THAN_ONE_EXE_MAPPING,
2319 "Found more than one executable mapping in the virtual address space.");
2320 PSUPHNTVPIMAGE pImage = &pThis->aImages[iExe];
2321
2322 /*
2323 * Check that it matches the executable image of the process.
2324 */
2325 int rc;
2326 ULONG cbUniStr = sizeof(UNICODE_STRING) + RTPATH_MAX * sizeof(RTUTF16);
2327 PUNICODE_STRING pUniStr = (PUNICODE_STRING)RTMemAllocZ(cbUniStr);
2328 if (!pUniStr)
2329 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_NO_MEMORY,
2330 "Error allocating %zu bytes for process name.", cbUniStr);
2331 ULONG cbIgn = 0;
2332 NTSTATUS rcNt = NtQueryInformationProcess(hProcess, ProcessImageFileName, pUniStr, cbUniStr - sizeof(WCHAR), &cbIgn);
2333 if (NT_SUCCESS(rcNt))
2334 {
2335 if (supHardNtVpAreUniStringsEqual(pUniStr, &pImage->Name.UniStr))
2336 rc = VINF_SUCCESS;
2337 else
2338 {
2339 pUniStr->Buffer[pUniStr->Length / sizeof(WCHAR)] = '\0';
2340 rc = supHardNtVpSetInfo2(pThis, VERR_SUP_VP_EXE_VS_PROC_NAME_MISMATCH,
2341 "Process image name does not match the exectuable we found: %ls vs %ls.",
2342 pUniStr->Buffer, pImage->Name.UniStr.Buffer);
2343 }
2344 }
2345 else
2346 rc = supHardNtVpSetInfo2(pThis, VERR_SUP_VP_NT_QI_PROCESS_NM_ERROR,
2347 "NtQueryInformationProcess/ProcessImageFileName failed: %#x", rcNt);
2348 RTMemFree(pUniStr);
2349 if (RT_FAILURE(rc))
2350 return rc;
2351
2352 /*
2353 * Validate the signing of the executable image.
2354 * This will load the fDllCharecteristics and fImageCharecteristics members we use below.
2355 */
2356 rc = supHardNtVpVerifyImage(pThis, pImage, hProcess);
2357 if (RT_FAILURE(rc))
2358 return rc;
2359
2360 /*
2361 * Check linking requirements.
2362 * This query is only available using the current process pseudo handle on
2363 * older windows versions. The cut-off seems to be Vista.
2364 */
2365 SECTION_IMAGE_INFORMATION ImageInfo;
2366 rcNt = NtQueryInformationProcess(hProcess, ProcessImageInformation, &ImageInfo, sizeof(ImageInfo), NULL);
2367 if (!NT_SUCCESS(rcNt))
2368 {
2369 if ( rcNt == STATUS_INVALID_PARAMETER
2370 && g_uNtVerCombined < SUP_NT_VER_VISTA
2371 && hProcess != NtCurrentProcess() )
2372 return VINF_SUCCESS;
2373 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_NT_QI_PROCESS_IMG_INFO_ERROR,
2374 "NtQueryInformationProcess/ProcessImageInformation failed: %#x hProcess=%#x", rcNt, hProcess);
2375 }
2376 if ( !(ImageInfo.DllCharacteristics & IMAGE_DLLCHARACTERISTICS_FORCE_INTEGRITY))
2377 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_EXE_MISSING_FORCE_INTEGRITY,
2378 "EXE DllCharacteristics=%#x, expected IMAGE_DLLCHARACTERISTICS_FORCE_INTEGRITY to be set.",
2379 ImageInfo.DllCharacteristics);
2380 if (!(ImageInfo.DllCharacteristics & IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE))
2381 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_EXE_MISSING_DYNAMIC_BASE,
2382 "EXE DllCharacteristics=%#x, expected IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE to be set.",
2383 ImageInfo.DllCharacteristics);
2384 if (!(ImageInfo.DllCharacteristics & IMAGE_DLLCHARACTERISTICS_NX_COMPAT))
2385 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_EXE_MISSING_NX_COMPAT,
2386 "EXE DllCharacteristics=%#x, expected IMAGE_DLLCHARACTERISTICS_NX_COMPAT to be set.",
2387 ImageInfo.DllCharacteristics);
2388
2389 if (pImage->fDllCharecteristics != ImageInfo.DllCharacteristics)
2390 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_DLL_CHARECTERISTICS_MISMATCH,
2391 "EXE Info.DllCharacteristics=%#x fDllCharecteristics=%#x.",
2392 ImageInfo.DllCharacteristics, pImage->fDllCharecteristics);
2393
2394 if (pImage->fImageCharecteristics != ImageInfo.ImageCharacteristics)
2395 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_DLL_CHARECTERISTICS_MISMATCH,
2396 "EXE Info.ImageCharacteristics=%#x fImageCharecteristics=%#x.",
2397 ImageInfo.ImageCharacteristics, pImage->fImageCharecteristics);
2398
2399 return VINF_SUCCESS;
2400}
2401
2402
2403/**
2404 * Check the integrity of the DLLs found in the process.
2405 *
2406 * @returns VBox status code.
2407 * @param pThis The process scanning state structure. Details
2408 * about images are added to this.
2409 * @param hProcess The process to verify.
2410 */
2411static int supHardNtVpCheckDlls(PSUPHNTVPSTATE pThis, HANDLE hProcess)
2412{
2413 /*
2414 * Check for duplicate entries (paranoia).
2415 */
2416 uint32_t i = pThis->cImages;
2417 while (i-- > 1)
2418 {
2419 const char *pszName = pThis->aImages[i].pszName;
2420 uint32_t j = i;
2421 while (j-- > 0)
2422 if (pThis->aImages[j].pszName == pszName)
2423 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_DUPLICATE_DLL_MAPPING,
2424 "Duplicate image entries for %s: %ls and %ls",
2425 pszName, pThis->aImages[i].Name.UniStr.Buffer, pThis->aImages[j].Name.UniStr.Buffer);
2426 }
2427
2428 /*
2429 * Check that both ntdll and kernel32 are present.
2430 * ASSUMES the entries in g_apszSupNtVpAllowedDlls are all lower case.
2431 */
2432 uint32_t iNtDll = UINT32_MAX;
2433 uint32_t iKernel32 = UINT32_MAX;
2434 i = pThis->cImages;
2435 while (i-- > 0)
2436 if (suplibHardenedStrCmp(pThis->aImages[i].pszName, "ntdll.dll") == 0)
2437 iNtDll = i;
2438 else if (suplibHardenedStrCmp(pThis->aImages[i].pszName, "kernel32.dll") == 0)
2439 iKernel32 = i;
2440 if (iNtDll == UINT32_MAX)
2441 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_NO_NTDLL_MAPPING,
2442 "The process has no NTDLL.DLL.");
2443 if (iKernel32 == UINT32_MAX && pThis->enmKind == SUPHARDNTVPKIND_SELF_PURIFICATION)
2444 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_NO_KERNEL32_MAPPING,
2445 "The process has no KERNEL32.DLL.");
2446 else if (iKernel32 != UINT32_MAX && pThis->enmKind == SUPHARDNTVPKIND_CHILD_PURIFICATION)
2447 return supHardNtVpSetInfo2(pThis, VERR_SUP_VP_KERNEL32_ALREADY_MAPPED,
2448 "The process already has KERNEL32.DLL loaded.");
2449
2450 /*
2451 * Verify that the DLLs are correctly signed (by MS).
2452 */
2453 i = pThis->cImages;
2454 while (i-- > 0)
2455 {
2456 int rc = supHardNtVpVerifyImage(pThis, &pThis->aImages[i], hProcess);
2457 if (RT_FAILURE(rc))
2458 return rc;
2459 }
2460
2461 return VINF_SUCCESS;
2462}
2463
2464
2465/**
2466 * Verifies the given process.
2467 *
2468 * The following requirements are checked:
2469 * - The process only has one thread, the calling thread.
2470 * - The process has no debugger attached.
2471 * - The executable image of the process is verified to be signed with
2472 * certificate known to this code at build time.
2473 * - The executable image is one of a predefined set.
2474 * - The process has only a very limited set of system DLLs loaded.
2475 * - The system DLLs signatures check out fine.
2476 * - The only executable memory in the process belongs to the system DLLs and
2477 * the executable image.
2478 *
2479 * @returns VBox status code.
2480 * @param hProcess The process to verify.
2481 * @param hThread A thread in the process (the caller).
2482 * @param enmKind The kind of process verification to perform.
2483 * @param fFlags Valid combination of SUPHARDNTVP_F_XXX flags.
2484 * @param pErrInfo Pointer to error info structure. Optional.
2485 * @param pcFixes Where to return the number of fixes made during
2486 * purification. Optional.
2487 */
2488DECLHIDDEN(int) supHardenedWinVerifyProcess(HANDLE hProcess, HANDLE hThread, SUPHARDNTVPKIND enmKind, uint32_t fFlags,
2489 uint32_t *pcFixes, PRTERRINFO pErrInfo)
2490{
2491 if (pcFixes)
2492 *pcFixes = 0;
2493
2494 /*
2495 * Some basic checks regarding threads and debuggers. We don't need
2496 * allocate any state memory for these.
2497 */
2498 int rc = VINF_SUCCESS;
2499 if (enmKind != SUPHARDNTVPKIND_CHILD_PURIFICATION)
2500 rc = supHardNtVpThread(hProcess, hThread, pErrInfo);
2501 if (RT_SUCCESS(rc))
2502 rc = supHardNtVpDebugger(hProcess, pErrInfo);
2503 if (RT_SUCCESS(rc))
2504 {
2505 /*
2506 * Allocate and initialize memory for the state.
2507 */
2508 PSUPHNTVPSTATE pThis = (PSUPHNTVPSTATE)RTMemAllocZ(sizeof(*pThis));
2509 if (pThis)
2510 {
2511 pThis->enmKind = enmKind;
2512 pThis->fFlags = fFlags;
2513 pThis->rcResult = VINF_SUCCESS;
2514 pThis->hProcess = hProcess;
2515 pThis->pErrInfo = pErrInfo;
2516
2517 /*
2518 * Perform the verification.
2519 */
2520 rc = supHardNtVpScanVirtualMemory(pThis, hProcess);
2521 if (RT_SUCCESS(rc))
2522 rc = supHardNtVpOpenImages(pThis);
2523 if (RT_SUCCESS(rc))
2524 rc = supHardNtVpCheckExe(pThis, hProcess);
2525 if (RT_SUCCESS(rc))
2526 rc = supHardNtVpCheckDlls(pThis, hProcess);
2527
2528 if (pcFixes)
2529 *pcFixes = pThis->cFixes;
2530
2531 /*
2532 * Clean up the state.
2533 */
2534#ifdef IN_RING0
2535 for (uint32_t i = 0; i < pThis->cImages; i++)
2536 supHardNTLdrCacheDeleteEntry(&pThis->aImages[i].CacheEntry);
2537#endif
2538 RTMemFree(pThis);
2539 }
2540 else
2541 rc = supHardNtVpSetInfo1(pErrInfo, VERR_SUP_VP_NO_MEMORY_STATE,
2542 "Failed to allocate %zu bytes for state structures.", sizeof(*pThis));
2543 }
2544 return rc;
2545}
2546
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