VirtualBox

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

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

SUPHardNt: Don't get confused and throw VERR_SUP_VP_NO_FOUND_NO_EXE_MAPPING at the user just because some app happened to start us using the DOS-8.3 filename (SFN) (open(SFN) + map may also cause confusion).

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