VirtualBox

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

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

one more place

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 48.6 KB
Line 
1/* $Id: SUPHardenedVerifyProcess-win.cpp 51910 2014-07-07 20:36: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/ctype.h>
41#include <iprt/param.h>
42
43#ifdef IN_RING0
44# include "SUPDrvInternal.h"
45#else
46# include "SUPLibInternal.h"
47#endif
48#include "win/SUPHardenedVerify-win.h"
49
50
51/*******************************************************************************
52* Structures and Typedefs *
53*******************************************************************************/
54/**
55 * Virtual address space region.
56 */
57typedef struct SUPHNTVPREGION
58{
59 /** The RVA of the region. */
60 uint32_t uRva;
61 /** The size of the region. */
62 uint32_t cb;
63 /** The protection of the region. */
64 uint32_t fProt;
65} SUPHNTVPREGION;
66/** Pointer to a virtual address space region. */
67typedef SUPHNTVPREGION *PSUPHNTVPREGION;
68
69/**
70 * Virtual address space image information.
71 */
72typedef struct SUPHNTVPIMAGE
73{
74 /** The base address of the image. */
75 uintptr_t uImageBase;
76 /** The size of the image mapping. */
77 uintptr_t cbImage;
78
79 /** The name from the allowed lists. */
80 const char *pszName;
81 /** Name structure for NtQueryVirtualMemory/MemorySectionName. */
82 struct
83 {
84 /** The full unicode name. */
85 UNICODE_STRING UniStr;
86 /** Buffer space. */
87 WCHAR awcBuffer[260];
88 } Name;
89
90 /** The number of mapping regions. */
91 uint32_t cRegions;
92 /** Mapping regions. */
93 SUPHNTVPREGION aRegions[16];
94
95 /** The image characteristics from the FileHeader. */
96 uint16_t fImageCharecteristics;
97 /** The DLL characteristics from the OptionalHeader. */
98 uint16_t fDllCharecteristics;
99
100 /** Set if this is the DLL. */
101 bool fDll;
102 /** Set if the image is NTDLL an the verficiation code needs to watch out for
103 * the NtCreateSection patch. */
104 bool fNtCreateSectionPatch;
105 /** Whether the API set schema hack needs to be applied when verifying memory
106 * content. The hack means that we only check if the 1st section is mapped. */
107 bool fApiSetSchemaOnlySection1;
108} SUPHNTVPIMAGE;
109/** Pointer to image info from the virtual address space scan. */
110typedef SUPHNTVPIMAGE *PSUPHNTVPIMAGE;
111
112/**
113 * Virtual address space scanning state.
114 */
115typedef struct SUPHNTVPSTATE
116{
117 /** Number of images in aImages. */
118 uint32_t cImages;
119 /** Images found in the process.
120 * The array is large enough to hold the executable, all allowed DLLs, and one
121 * more so we can get the image name of the first unwanted DLL. */
122 SUPHNTVPIMAGE aImages[1+5+1];
123 /** Memory compare scratch buffer.*/
124 uint8_t abMemory[_4K];
125 /** File compare scratch buffer.*/
126 uint8_t abFile[_4K];
127 /** Section headers for use when comparing file and loaded image. */
128 IMAGE_SECTION_HEADER aSecHdrs[16];
129
130} SUPHNTVPSTATE;
131/** Pointer to stat information of a virtual address space scan. */
132typedef SUPHNTVPSTATE *PSUPHNTVPSTATE;
133
134
135/*******************************************************************************
136* Global Variables *
137*******************************************************************************/
138/**
139 * System DLLs allowed to be loaded into the process.
140 * @remarks supHardNtVpCheckDlls assumes these are lower case.
141 */
142static const char *g_apszSupNtVpAllowedDlls[] =
143{
144 "ntdll.dll",
145 "kernel32.dll",
146 "kernelbase.dll",
147 "apphelp.dll",
148 "apisetschema.dll"
149};
150
151/**
152 * VBox executables allowed to start VMs.
153 * @remarks Remember to keep in sync with SUPR3HardenedVerify.cpp.
154 */
155static const char *g_apszSupNtVpAllowedVmExes[] =
156{
157 "VBoxHeadless.exe",
158 "VirtualBox.exe",
159 "VBoxSDL.exe",
160 "VBoxNetDHCP.exe",
161 "VBoxNetNAT.exe",
162
163 "tstMicro.exe",
164 "tstPDMAsyncCompletion.exe",
165 "tstPDMAsyncCompletionStress.exe",
166 "tstVMM.exe",
167 "tstVMREQ.exe",
168 "tstCFGM.exe",
169 "tstIntNet-1.exe",
170 "tstMMHyperHeap.exe",
171 "tstR0ThreadPreemptionDriver.exe",
172 "tstRTR0MemUserKernelDriver.exe",
173 "tstRTR0SemMutexDriver.exe",
174 "tstRTR0TimerDriver.exe",
175 "tstSSM.exe",
176};
177
178/** Pointer to NtQueryVirtualMemory. Initialized by SUPDrv-win.cpp in
179 * ring-0, in ring-3 it's just a slightly confusing define. */
180#ifdef IN_RING0
181PFNNTQUERYVIRTUALMEMORY g_pfnNtQueryVirtualMemory = NULL;
182#else
183# define g_pfnNtQueryVirtualMemory NtQueryVirtualMemory
184#endif
185
186
187/**
188 * Fills in error information.
189 *
190 * @returns @a rc.
191 * @param pErrInfo Pointer to the extened error info structure.
192 * Can be NULL.
193 * @param pszErr Where to return error details.
194 * @param cbErr Size of the buffer @a pszErr points to.
195 * @param rc The status to return.
196 * @param pszMsg The format string for the message.
197 * @param ... The arguments for the format string.
198 */
199static int supHardNtVpSetInfo(PRTERRINFO pErrInfo, int rc, const char *pszMsg, ...)
200{
201 va_list va;
202#ifdef IN_RING3
203 va_start(va, pszMsg);
204 supR3HardenedError(rc, false /*fFatal*/, "%N\n", pszMsg, &va);
205 va_end(va);
206#endif
207
208 va_start(va, pszMsg);
209 RTErrInfoSetV(pErrInfo, rc, pszMsg, va);
210 va_end(va);
211
212 return rc;
213}
214
215
216static NTSTATUS supHardNtVpReadFile(HANDLE hFile, uint64_t off, void *pvBuf, size_t cbRead)
217{
218 if ((ULONG)cbRead != cbRead)
219 return STATUS_INTEGER_OVERFLOW;
220
221 IO_STATUS_BLOCK Ios = RTNT_IO_STATUS_BLOCK_INITIALIZER;
222 NTSTATUS rcNt = NtReadFile(hFile,
223 NULL /*hEvent*/,
224 NULL /*ApcRoutine*/,
225 NULL /*ApcContext*/,
226 &Ios,
227 pvBuf,
228 (ULONG)cbRead,
229 (PLARGE_INTEGER)&off,
230 NULL);
231 if (NT_SUCCESS(rcNt))
232 rcNt = Ios.Status;
233 return rcNt;
234}
235
236
237static NTSTATUS supHardNtVpReadMem(HANDLE hProcess, uintptr_t uPtr, void *pvBuf, size_t cbRead)
238{
239#ifdef IN_RING0
240 /* ASSUMES hProcess is the current process. */
241 /** @todo use MmCopyVirtualMemory where available! */
242 int rc = RTR0MemUserCopyFrom(pvBuf, uPtr, cbRead);
243 if (RT_SUCCESS(rc))
244 return STATUS_SUCCESS;
245 return STATUS_ACCESS_DENIED;
246#else
247 SIZE_T cbIgn;
248 NTSTATUS rcNt = NtReadVirtualMemory(hProcess, (PVOID)uPtr, pvBuf, cbRead, &cbIgn);
249 if (NT_SUCCESS(rcNt) && cbIgn != cbRead)
250 rcNt = STATUS_IO_DEVICE_ERROR;
251 return rcNt;
252#endif
253}
254
255
256static int supHardNtVpFileMemCompare(const void *pvFile, const void *pvMemory, size_t cbToCompare,
257 PSUPHNTVPIMAGE pImage, uint32_t uRva, PRTERRINFO pErrInfo)
258{
259 if (suplibHardenedMemComp(pvFile, pvMemory, cbToCompare) == 0)
260 return VINF_SUCCESS;
261
262 /* Find the exact location. */
263 const uint8_t *pbFile = (const uint8_t *)pvFile;
264 const uint8_t *pbMemory = (const uint8_t *)pvMemory;
265 while (cbToCompare > 0 && *pbFile == *pbMemory)
266 {
267 cbToCompare--;
268 pbFile++;
269 pbMemory++;
270 uRva++;
271 }
272
273 return supHardNtVpSetInfo(pErrInfo, VERR_SUP_VP_MEMORY_VS_FILE_MISMATCH,
274 "%s: memory compare at %#x failed: %#x != %#x\n", pImage->pszName, uRva, *pbFile, *pbMemory);
275}
276
277
278static int supHardNtVpCheckSectionProtection(PSUPHNTVPIMAGE pImage, uint32_t uRva, uint32_t cb, uint32_t fProt,
279 PRTERRINFO pErrInfo)
280{
281 uint32_t const cbOrg = cb;
282 if (!cb)
283 return VINF_SUCCESS;
284
285 for (uint32_t i = 0; i < pImage->cRegions; i++)
286 {
287 uint32_t offRegion = uRva - pImage->aRegions[i].uRva;
288 if (offRegion < pImage->aRegions[i].cb)
289 {
290 uint32_t cbLeft = pImage->aRegions[i].cb - offRegion;
291 if ( pImage->aRegions[i].fProt != fProt
292 && ( fProt != PAGE_READWRITE
293 || pImage->aRegions[i].fProt != PAGE_WRITECOPY))
294 return supHardNtVpSetInfo(pErrInfo, VERR_SUP_VP_SECTION_PROTECTION_MISMATCH,
295 "%s: RVA range %#x-%#x protection is %#x, expected %#x. (cb=%#x)",
296 pImage->pszName, uRva, uRva + cbLeft - 1, pImage->aRegions[i].fProt, fProt, cb);
297 if (cbLeft >= cb)
298 return VINF_SUCCESS;
299 cb -= cbLeft;
300 uRva += cbLeft;
301
302#if 0 /* This shouldn't ever be necessary. */
303 if ( i + 1 < pImage->cRegions
304 && uRva < pImage->aRegions[i + 1].uRva)
305 {
306 cbLeft = pImage->aRegions[i + 1].uRva - uRva;
307 if (cbLeft >= cb)
308 return VINF_SUCCESS;
309 cb -= cbLeft;
310 uRva += cbLeft;
311 }
312#endif
313 }
314 }
315
316 return supHardNtVpSetInfo(pErrInfo, cbOrg == cb ? VERR_SUP_VP_SECTION_NOT_MAPPED : VERR_SUP_VP_SECTION_NOT_FULLY_MAPPED,
317 "%s: RVA range %#x-%#x is not mapped?", pImage->pszName, uRva, uRva + cb - 1);
318}
319
320
321/**
322 * Compares process memory with the disk content.
323 *
324 * @returns VBox status code.
325 * @param pThis The process scanning state structure (for the
326 * two scratch buffers).
327 * @param pImage The image data collected during the address
328 * space scan.
329 * @param hProcess Handle to the process.
330 * @param hFile Handle to the image file.
331 * @param pErrInfo Pointer to error info structure. Optional.
332 */
333static int supHardNtVpVerifyImageCompareMemory(PSUPHNTVPSTATE pThis, PSUPHNTVPIMAGE pImage, HANDLE hProcess, HANDLE hFile,
334 PRTERRINFO pErrInfo)
335{
336 /*
337 * Read and find the file headers.
338 */
339 NTSTATUS rcNt = supHardNtVpReadFile(hFile, 0, pThis->abFile, sizeof(pThis->abFile));
340 if (!NT_SUCCESS(rcNt))
341 return supHardNtVpSetInfo(pErrInfo, VERR_SUP_VP_IMAGE_HDR_READ_ERROR,
342 "%s: Error reading image header: %#x", pImage->pszName, rcNt);
343
344 uint32_t offNtHdrs = 0;
345 PIMAGE_DOS_HEADER pDosHdr = (PIMAGE_DOS_HEADER)&pThis->abFile[0];
346 if (pDosHdr->e_magic == IMAGE_DOS_SIGNATURE)
347 {
348 offNtHdrs = pDosHdr->e_lfanew;
349 if (offNtHdrs > 512 || offNtHdrs < sizeof(*pDosHdr))
350 return supHardNtVpSetInfo(pErrInfo, VERR_SUP_VP_BAD_MZ_OFFSET,
351 "%s: Unexpected e_lfanew value: %#x", pImage->pszName, offNtHdrs);
352 }
353 PIMAGE_NT_HEADERS pNtHdrs = (PIMAGE_NT_HEADERS)&pThis->abFile[offNtHdrs];
354 if (pNtHdrs->Signature != IMAGE_NT_SIGNATURE)
355 return supHardNtVpSetInfo(pErrInfo, VERR_SUP_VP_BAD_IMAGE_SIGNATURE,
356 "%s: No PE signature at %#x: %#x", pImage->pszName, offNtHdrs, pNtHdrs->Signature);
357
358 /*
359 * Do basic header validation.
360 */
361#ifdef RT_ARCH_AMD64
362 if (pNtHdrs->FileHeader.Machine != IMAGE_FILE_MACHINE_AMD64)
363#else
364 if (pNtHdrs->FileHeader.Machine != IMAGE_FILE_MACHINE_I386)
365#endif
366 return supHardNtVpSetInfo(pErrInfo, VERR_SUP_VP_UNEXPECTED_IMAGE_MACHINE,
367 "%s: Unexpected machine: %#x", pImage->pszName, pNtHdrs->FileHeader.Machine);
368
369 if (pNtHdrs->FileHeader.SizeOfOptionalHeader != sizeof(pNtHdrs->OptionalHeader))
370 return supHardNtVpSetInfo(pErrInfo, VERR_SUP_VP_BAD_OPTIONAL_HEADER,
371 "%s: Unexpected optional header size: %#x",
372 pImage->pszName, pNtHdrs->FileHeader.SizeOfOptionalHeader);
373
374 if (pNtHdrs->OptionalHeader.Magic != RT_CONCAT3(IMAGE_NT_OPTIONAL_HDR,ARCH_BITS,_MAGIC))
375 return supHardNtVpSetInfo(pErrInfo, VERR_SUP_VP_BAD_OPTIONAL_HEADER,
376 "%s: Unexpected optional header magic: %#x", pImage->pszName, pNtHdrs->OptionalHeader.Magic);
377 if (pNtHdrs->OptionalHeader.NumberOfRvaAndSizes != IMAGE_NUMBEROF_DIRECTORY_ENTRIES)
378 return supHardNtVpSetInfo(pErrInfo, VERR_SUP_VP_BAD_OPTIONAL_HEADER,
379 "%s: Unexpected data dirs: %#x", pImage->pszName, pNtHdrs->OptionalHeader.NumberOfRvaAndSizes);
380
381 /*
382 * Before we start comparing things, store what we need to know from the headers.
383 */
384 uint32_t const cSections = pNtHdrs->FileHeader.NumberOfSections;
385 if (cSections > RT_ELEMENTS(pThis->aSecHdrs))
386 return supHardNtVpSetInfo(pErrInfo, VERR_SUP_VP_TOO_MANY_SECTIONS,
387 "%s: Too many section headers: %#x", pImage->pszName, cSections);
388 suplibHardenedMemCopy(pThis->aSecHdrs, pNtHdrs + 1, cSections * sizeof(IMAGE_SECTION_HEADER));
389
390 uintptr_t const uImageBase = pNtHdrs->OptionalHeader.ImageBase;
391 if (uImageBase & PAGE_OFFSET_MASK)
392 return supHardNtVpSetInfo(pErrInfo, VERR_SUP_VP_BAD_IMAGE_BASE,
393 "%s: Invalid image base: %p", pImage->pszName, uImageBase);
394
395 uint32_t const cbImage = pNtHdrs->OptionalHeader.SizeOfImage;
396 if (RT_ALIGN_32(pImage->cbImage, PAGE_SIZE) != RT_ALIGN_32(cbImage, PAGE_SIZE) && !pImage->fApiSetSchemaOnlySection1)
397 return supHardNtVpSetInfo(pErrInfo, VERR_SUP_VP_BAD_IMAGE_SIZE,
398 "%s: SizeOfImage (%#x) isn't close enough to the mapping size (%#x)",
399 pImage->pszName, cbImage, pImage->cbImage);
400
401 uint32_t const cbSectAlign = pNtHdrs->OptionalHeader.SectionAlignment;
402 if ( !RT_IS_POWER_OF_TWO(cbSectAlign)
403 || cbSectAlign < PAGE_SIZE
404 || cbSectAlign > (pImage->fApiSetSchemaOnlySection1 ? _64K : (uint32_t)PAGE_SIZE) )
405 return supHardNtVpSetInfo(pErrInfo, VERR_SUP_VP_BAD_SECTION_ALIGNMENT_VALUE,
406 "%s: Unexpected SectionAlignment value: %#x", pImage->pszName, cbSectAlign);
407
408 uint32_t const cbFileAlign = pNtHdrs->OptionalHeader.FileAlignment;
409 if (!RT_IS_POWER_OF_TWO(cbFileAlign) || cbFileAlign < 512 || cbFileAlign > PAGE_SIZE || cbFileAlign > cbSectAlign)
410 return supHardNtVpSetInfo(pErrInfo, VERR_SUP_VP_BAD_FILE_ALIGNMENT_VALUE,
411 "%s: Unexpected FileAlignment value: %#x (cbSectAlign=%#x)",
412 pImage->pszName, cbFileAlign, cbSectAlign);
413
414 uint32_t const cbHeaders = pNtHdrs->OptionalHeader.SizeOfHeaders;
415 uint32_t const cbMinHdrs = offNtHdrs + sizeof(*pNtHdrs) + sizeof(IMAGE_SECTION_HEADER) * cSections;
416 if (cbHeaders < cbMinHdrs)
417 return supHardNtVpSetInfo(pErrInfo, VERR_SUP_VP_BAD_SIZE_OF_HEADERS,
418 "%s: Headers are too small: %#x < %#x (cSections=%#x)",
419 pImage->pszName, cbHeaders, cbMinHdrs, cSections);
420 uint32_t const cbHdrsFile = RT_ALIGN_32(cbHeaders, cbFileAlign);
421 if (cbHdrsFile > sizeof(pThis->abFile))
422 return supHardNtVpSetInfo(pErrInfo, VERR_SUP_VP_BAD_SIZE_OF_HEADERS,
423 "%s: Headers are larger than expected: %#x/%#x (expected max %zx)",
424 pImage->pszName, cbHeaders, cbHdrsFile, sizeof(pThis->abFile));
425
426 /*
427 * Compare the file header with the loaded bits. The loader will fiddle
428 * with image base, changing it to the actual load address.
429 */
430 int rc;
431 if (!pImage->fApiSetSchemaOnlySection1)
432 {
433 rcNt = supHardNtVpReadMem(hProcess, pImage->uImageBase, pThis->abMemory, cbHdrsFile);
434 if (!NT_SUCCESS(rcNt))
435 return supHardNtVpSetInfo(pErrInfo, VERR_SUP_VP_MEMORY_READ_ERROR,
436 "%s: Error reading image header from memory: %#x", pImage->pszName, rcNt);
437 if (uImageBase != pImage->uImageBase)
438 pNtHdrs->OptionalHeader.ImageBase = pImage->uImageBase;
439
440 rc = supHardNtVpFileMemCompare(pThis->abFile, pThis->abMemory, cbHeaders, pImage, 0 /*uRva*/, pErrInfo);
441 if (RT_FAILURE(rc))
442 return rc;
443 rc = supHardNtVpCheckSectionProtection(pImage, 0 /*uRva*/, cbHdrsFile, PAGE_READONLY, pErrInfo);
444 if (RT_FAILURE(rc))
445 return rc;
446 }
447
448 /*
449 * Save some header fields we might be using later on.
450 */
451 pImage->fImageCharecteristics = pNtHdrs->FileHeader.Characteristics;
452 pImage->fDllCharecteristics = pNtHdrs->OptionalHeader.DllCharacteristics;
453
454 /*
455 * Validate sections and check them against the mapping regions.
456 */
457 uint32_t uRva = cbHdrsFile;
458 for (uint32_t i = 0; i < cSections; i++)
459 {
460 /* Validate the section. */
461 uint32_t uSectRva = pThis->aSecHdrs[i].VirtualAddress;
462 if (uSectRva < uRva || uSectRva > cbImage || RT_ALIGN_32(uSectRva, cbSectAlign) != uSectRva)
463 return supHardNtVpSetInfo(pErrInfo, VERR_SUP_VP_BAD_SECTION_RVA,
464 "%s: Section %u: Invalid virtual address: %#x (uRva=%#x, cbImage=%#x, cbSectAlign=%#x)",
465 pImage->pszName, i, uSectRva, uRva, cbImage, cbSectAlign);
466 uint32_t cbMap = pThis->aSecHdrs[i].Misc.VirtualSize;
467 if (cbMap > cbImage || uRva + cbMap > cbImage)
468 return supHardNtVpSetInfo(pErrInfo, VERR_SUP_VP_BAD_SECTION_VIRTUAL_SIZE,
469 "%s: Section %u: Invalid virtual size: %#x (uSectRva=%#x, uRva=%#x, cbImage=%#x)",
470 pImage->pszName, i, cbMap, uSectRva, uRva, cbImage);
471 uint32_t cbFile = pThis->aSecHdrs[i].SizeOfRawData;
472 if (cbFile != RT_ALIGN_32(cbFile, cbFileAlign) || cbFile > RT_ALIGN_32(cbMap, cbSectAlign))
473 return supHardNtVpSetInfo(pErrInfo, VERR_SUP_VP_BAD_SECTION_FILE_SIZE,
474 "%s: Section %u: Invalid file size: %#x (cbMap=%#x, uSectRva=%#x)",
475 pImage->pszName, i, cbFile, cbMap, uSectRva);
476
477 /* Validate the protection. */
478 if (!pImage->fApiSetSchemaOnlySection1 || i == 0)
479 {
480 if (pImage->fApiSetSchemaOnlySection1)
481 {
482 pImage->uImageBase -= uSectRva;
483 pImage->cbImage += uSectRva;
484 pImage->aRegions[i].uRva = uSectRva;
485 }
486
487 uint32_t fProt;
488 switch (pThis->aSecHdrs[i].Characteristics & (IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE))
489 {
490 case IMAGE_SCN_MEM_READ:
491 fProt = PAGE_READONLY;
492 break;
493 case IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE:
494 fProt = PAGE_READWRITE;
495 if (!suplibHardenedMemComp(pThis->aSecHdrs[i].Name, ".mrdata", 8)) /* w8.1, ntdll */
496 fProt = PAGE_READONLY;
497 break;
498 case IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_EXECUTE:
499 fProt = PAGE_EXECUTE_READ;
500 break;
501 case IMAGE_SCN_MEM_EXECUTE:
502 fProt = PAGE_EXECUTE;
503 break;
504 default:
505 return supHardNtVpSetInfo(pErrInfo, VERR_SUP_VP_UNEXPECTED_SECTION_FLAGS,
506 "%s: Section %u: Unexpected characteristics: %#x (uSectRva=%#x, cbMap=%#x)",
507 pImage->pszName, i, pThis->aSecHdrs[i].Characteristics, uSectRva, cbMap);
508
509 }
510 rc = supHardNtVpCheckSectionProtection(pImage, uSectRva, RT_ALIGN_32(cbMap, PAGE_SIZE), fProt, pErrInfo);
511 if (RT_FAILURE(rc))
512 return rc;
513 }
514
515 /* Advance the RVA. */
516 uRva = uSectRva + RT_ALIGN_32(cbMap, cbSectAlign);
517 }
518
519 /*
520 * Check the mapping regions with the image to make sure someone didn't
521 * fill executable code into some gap in the image.
522 */
523 /** @todo not vital. */
524
525
526 /*
527 * Compare executable code. If we're not loaded at the link address, we
528 * need to load base relocations and apply them while making the compare.
529 * A special case
530 */
531 /** @todo not vital. */
532
533
534 return VINF_SUCCESS;
535}
536
537
538/**
539 * Verifies the signature of the given image on disk, then checks if the memory
540 * mapping matches what we verified.
541 *
542 * @returns VBox status code.
543 * @param pThis The process scanning state structure (for the
544 * two scratch buffers).
545 * @param pImage The image data collected during the address
546 * space scan.
547 * @param hProcess Handle to the process.
548 * @param hFile Handle to the image file.
549 * @param pErrInfo Pointer to error info structure. Optional.
550 */
551static int supHardNtVpVerifyImage(PSUPHNTVPSTATE pThis, PSUPHNTVPIMAGE pImage, HANDLE hProcess, PRTERRINFO pErrInfo)
552{
553 /*
554 * Open the image.
555 */
556 HANDLE hFile = RTNT_INVALID_HANDLE_VALUE;
557 IO_STATUS_BLOCK Ios = RTNT_IO_STATUS_BLOCK_INITIALIZER;
558
559 OBJECT_ATTRIBUTES ObjAttr;
560 InitializeObjectAttributes(&ObjAttr, &pImage->Name.UniStr, OBJ_CASE_INSENSITIVE, NULL /*hRootDir*/, NULL /*pSecDesc*/);
561
562 NTSTATUS rcNt = NtCreateFile(&hFile,
563 GENERIC_READ,
564 &ObjAttr,
565 &Ios,
566 NULL /* Allocation Size*/,
567 FILE_ATTRIBUTE_NORMAL,
568 FILE_SHARE_READ,
569 FILE_OPEN,
570 FILE_NON_DIRECTORY_FILE,
571 NULL /*EaBuffer*/,
572 0 /*EaLength*/);
573 if (NT_SUCCESS(rcNt))
574 rcNt = Ios.Status;
575 if (!NT_SUCCESS(rcNt))
576 return supHardNtVpSetInfo(pErrInfo, VERR_SUP_VP_IMAGE_FILE_OPEN_ERROR,
577 "Error opening image for scanning: %#x (name %ls)", rcNt, pImage->Name.UniStr.Buffer);
578
579 /*
580 * Validate the signature, then make an attempt at comparing memory and
581 * disk content.
582 */
583 int rc = supHardenedWinVerifyImageByHandle(hFile, pImage->Name.UniStr.Buffer,
584 pImage->fDll ? 0 : SUPHNTVI_F_REQUIRE_BUILD_CERT,
585 NULL /*pfCacheable*/, pErrInfo);
586 if (RT_SUCCESS(rc))
587 rc = supHardNtVpVerifyImageCompareMemory(pThis, pImage, hProcess, hFile, pErrInfo);
588
589 /*
590 * Clean up and return.
591 */
592 rcNt = NtClose(hFile);
593 if (!NT_SUCCESS(rcNt) && RT_SUCCESS(rc))
594 rc = supHardNtVpSetInfo(pErrInfo, VERR_SUP_VP_IMAGE_FILE_CLOSE_ERROR,
595 "Error closing image after scanning: %#x (name %ls)", rcNt, pImage->Name.UniStr.Buffer);
596 return rc;
597}
598
599
600/**
601 * Verifies that there is only one thread in the process.
602 *
603 * @returns VBox status code.
604 * @param hProcess The process.
605 * @param hThread The thread.
606 * @param pErrInfo Pointer to error info structure. Optional.
607 */
608static int supHardNtVpThread(HANDLE hProcess, HANDLE hThread, PRTERRINFO pErrInfo)
609{
610 /*
611 * Use the ThreadAmILastThread request to check that there is only one
612 * thread in the process.
613 */
614 ULONG cbIgn = 0;
615 ULONG fAmI = 0;
616 NTSTATUS rcNt = NtQueryInformationThread(hThread, ThreadAmILastThread, &fAmI, sizeof(fAmI), &cbIgn);
617 if (!NT_SUCCESS(rcNt))
618 return supHardNtVpSetInfo(pErrInfo, VERR_SUP_VP_NT_QI_THREAD_ERROR,
619 "NtQueryInformationThread/ThreadAmILastThread -> %#x", rcNt);
620 if (!fAmI)
621 return supHardNtVpSetInfo(pErrInfo, VERR_SUP_VP_THREAD_NOT_ALONE,
622 "More than one thread in process");
623
624 /** @todo Would be nice to verify the relation ship between hProcess and hThread
625 * as well... */
626 return VINF_SUCCESS;
627}
628
629
630#ifndef VBOX_WITHOUT_DEBUGGER_CHECKS
631/**
632 * Verifies that there isn't a debugger attached to the process.
633 *
634 * @returns VBox status code.
635 * @param hProcess The process.
636 * @param pErrInfo Pointer to error info structure. Optional.
637 */
638static int supHardNtVpDebugger(HANDLE hProcess, PRTERRINFO pErrInfo)
639{
640 /*
641 * Use the ProcessDebugPort request to check there is no debugger
642 * currently attached to the process.
643 */
644 ULONG cbIgn = 0;
645 uintptr_t uPtr = ~(uintptr_t)0;
646 NTSTATUS rcNt = NtQueryInformationProcess(hProcess,
647 ProcessDebugPort,
648 &uPtr, sizeof(uPtr), &cbIgn);
649 if (!NT_SUCCESS(rcNt))
650 return supHardNtVpSetInfo(pErrInfo, VERR_SUP_VP_NT_QI_PROCESS_DBG_PORT_ERROR,
651 "NtQueryInformationProcess/ProcessDebugPort -> %#x", rcNt);
652 if (uPtr != 0)
653 return supHardNtVpSetInfo(pErrInfo, VERR_SUP_VP_DEBUGGED,
654 "Debugger attached (%#zx)", uPtr);
655 return VINF_SUCCESS;
656}
657#endif /* !VBOX_WITHOUT_DEBUGGER_CHECKS */
658
659
660/**
661 * Allocates and initalizes a process stat structure for process virtual memory
662 * scanning.
663 *
664 * @returns Pointer to the state structure on success, NULL on failure.
665 * @param pErrInfo Pointer to error info structure. Optional.
666 */
667static PSUPHNTVPSTATE supHardNtVpCreateState(PRTERRINFO pErrInfo)
668{
669 /*
670 * Allocate the memory.
671 */
672 PSUPHNTVPSTATE pThis = (PSUPHNTVPSTATE)suplibHardenedAllocZ(sizeof(*pThis));
673 if (pThis)
674 return pThis;
675 supHardNtVpSetInfo(pErrInfo, VERR_NO_MEMORY, "Failed to allocate %zu bytes for state structures.", sizeof(*pThis));
676 return NULL;
677}
678
679
680/**
681 * Matches two UNICODE_STRING structures in a case sensitive fashion.
682 *
683 * @returns true if equal, false if not.
684 * @param pUniStr1 The first unicode string.
685 * @param pUniStr2 The first unicode string.
686 */
687static bool supHardNtVpAreUniStringsEqual(PCUNICODE_STRING pUniStr1, PCUNICODE_STRING pUniStr2)
688{
689 if (pUniStr1->Length != pUniStr2->Length)
690 return false;
691 return suplibHardenedMemComp(pUniStr1->Buffer, pUniStr2->Buffer, pUniStr1->Length) == 0;
692}
693
694
695/**
696 * Performs a case insensitive comparison of an ASCII and an UTF-16 file name.
697 *
698 * @returns true / false
699 * @param pszName1 The ASCII name.
700 * @param pwszName2 The UTF-16 name.
701 */
702static bool supHardNtVpAreNamesEqual(const char *pszName1, PCRTUTF16 pwszName2)
703{
704 for (;;)
705 {
706 char ch1 = *pszName1++;
707 RTUTF16 wc2 = *pwszName2++;
708 if (ch1 != wc2)
709 {
710 ch1 = RT_C_TO_LOWER(ch1);
711 wc2 = wc2 < 0x80 ? RT_C_TO_LOWER(wc2) : wc2;
712 if (ch1 != wc2)
713 return false;
714 }
715 if (!ch1)
716 return true;
717 }
718}
719
720
721/**
722 * Records an additional memory region for an image.
723 *
724 * @returns VBox status code.
725 * @param pImage The new image structure. Only the unicode name
726 * buffer is valid.
727 * @param pMemInfo The memory information for the image.
728 * @param pErrInfo Pointer to error info structure. Optional.
729 */
730static int supHardNtVpNewImage(PSUPHNTVPIMAGE pImage, PMEMORY_BASIC_INFORMATION pMemInfo, PRTERRINFO pErrInfo)
731{
732 /*
733 * Extract the final component.
734 */
735 unsigned cwcDirName = pImage->Name.UniStr.Length / sizeof(WCHAR);
736 PCRTUTF16 pwszFilename = &pImage->Name.UniStr.Buffer[cwcDirName];
737 while ( cwcDirName > 0
738 && pwszFilename[-1] != '\\'
739 && pwszFilename[-1] != '/'
740 && pwszFilename[-1] != ':')
741 {
742 pwszFilename--;
743 cwcDirName--;
744 }
745 if (!*pwszFilename)
746 return supHardNtVpSetInfo(pErrInfo, VERR_SUP_VP_NO_IMAGE_MAPPING_NAME,
747 "Empty filename (len=%u) for image at %p.", pImage->Name.UniStr.Length, pMemInfo->BaseAddress);
748
749 /*
750 * Drop trailing slashes from the directory name.
751 */
752 while ( cwcDirName > 0
753 && ( pImage->Name.UniStr.Buffer[cwcDirName - 1] == '\\'
754 || pImage->Name.UniStr.Buffer[cwcDirName - 1] == '/'))
755 cwcDirName--;
756
757 /*
758 * Match it against known DLLs.
759 */
760 pImage->pszName = NULL;
761 for (uint32_t i = 0; i < RT_ELEMENTS(g_apszSupNtVpAllowedDlls); i++)
762 if (supHardNtVpAreNamesEqual(g_apszSupNtVpAllowedDlls[i], pwszFilename))
763 {
764 pImage->pszName = g_apszSupNtVpAllowedDlls[i];
765 pImage->fDll = true;
766
767 /* The directory name must match the one we've got for System32. */
768 if ( cwcDirName * sizeof(WCHAR) != g_System32NtPath.UniStr.Length
769 || suplibHardenedMemComp(pImage->Name.UniStr.Buffer,
770 g_System32NtPath.UniStr.Buffer,
771 cwcDirName * sizeof(WCHAR)))
772 return supHardNtVpSetInfo(pErrInfo, VERR_SUP_VP_NON_SYSTEM32_DLL,
773 "Expected %ls to be loaded from %ls.",
774 pImage->Name.UniStr.Buffer, g_System32NtPath.UniStr.Buffer);
775
776 break;
777 }
778 if (!pImage->pszName)
779 {
780 /*
781 * Not a known DLL, executable?
782 */
783 for (uint32_t i = 0; i < RT_ELEMENTS(g_apszSupNtVpAllowedVmExes); i++)
784 if (supHardNtVpAreNamesEqual(g_apszSupNtVpAllowedVmExes[i], pwszFilename))
785 {
786 pImage->pszName = g_apszSupNtVpAllowedVmExes[i];
787 pImage->fDll = false;
788 break;
789 }
790 }
791 if (!pImage->pszName)
792 return supHardNtVpSetInfo(pErrInfo, VERR_SUP_VP_NOT_KNOWN_DLL_OR_EXE,
793 "Unknown image file %ls at %p.", pImage->Name.UniStr.Buffer, pMemInfo->BaseAddress);
794
795 /*
796 * Since it's a new image, we expect to be at the start of the mapping now.
797 */
798 if (pMemInfo->AllocationBase != pMemInfo->BaseAddress)
799 return supHardNtVpSetInfo(pErrInfo, VERR_SUP_VP_IMAGE_MAPPING_BASE_ERROR,
800 "Invalid AllocationBase/BaseAddress for %s: %p vs %p.",
801 pImage->pszName, pMemInfo->AllocationBase, pMemInfo->BaseAddress);
802
803 /*
804 * Check for size/rva overflow.
805 */
806 if (pMemInfo->RegionSize >= _2G)
807 return supHardNtVpSetInfo(pErrInfo, VERR_SUP_VP_TOO_LARGE_REGION,
808 "Region 0 of image %s is too large: %p.", pImage->pszName, pMemInfo->RegionSize);
809
810 /*
811 * Fill in details from the memory info.
812 */
813 pImage->uImageBase = (uintptr_t)pMemInfo->AllocationBase;
814 pImage->cbImage = pMemInfo->RegionSize;
815 pImage->cRegions = 1;
816 pImage->aRegions[0].uRva = 0;
817 pImage->aRegions[0].cb = (uint32_t)pMemInfo->RegionSize;
818 pImage->aRegions[0].fProt = pMemInfo->Protect;
819
820 return VINF_SUCCESS;
821}
822
823
824/**
825 * Records an additional memory region for an image.
826 *
827 * @returns VBox status code.
828 * @param pImage The image.
829 * @param pMemInfo The memory information for the region.
830 * @param pErrInfo Pointer to error info structure. Optional.
831 */
832static int supHardNtVpAddRegion(PSUPHNTVPIMAGE pImage, PMEMORY_BASIC_INFORMATION pMemInfo, PRTERRINFO pErrInfo)
833{
834 /*
835 * Make sure the base address matches.
836 */
837 if (pImage->uImageBase != (uintptr_t)pMemInfo->AllocationBase)
838 return supHardNtVpSetInfo(pErrInfo, VERR_SUPLIB_NT_PROCESS_UNTRUSTED_3,
839 "Base address mismatch for %s: have %p, found %p for region %p LB %#zx.",
840 pImage->pszName, pImage->uImageBase, pMemInfo->AllocationBase,
841 pMemInfo->BaseAddress, pMemInfo->RegionSize);
842
843 /*
844 * Check for size and rva overflows.
845 */
846 uintptr_t uRva = (uintptr_t)pMemInfo->BaseAddress - pImage->uImageBase;
847 if (pMemInfo->RegionSize >= _2G)
848 return supHardNtVpSetInfo(pErrInfo, VERR_SUP_VP_TOO_LARGE_REGION,
849 "Region %u of image %s is too large: %p/%p.", pImage->pszName, pMemInfo->RegionSize, uRva);
850 if (uRva >= _2G)
851 return supHardNtVpSetInfo(pErrInfo, VERR_SUP_VP_TOO_HIGH_REGION_RVA,
852 "Region %u of image %s is too high: %p/%p.", pImage->pszName, pMemInfo->RegionSize, uRva);
853
854
855 /*
856 * Record the region.
857 */
858 uint32_t iRegion = pImage->cRegions;
859 if (iRegion + 1 >= RT_ELEMENTS(pImage->aRegions))
860 return supHardNtVpSetInfo(pErrInfo, VERR_SUP_VP_TOO_MANY_IMAGE_REGIONS,
861 "Too many regions for %s.", pImage->pszName);
862 pImage->aRegions[iRegion].uRva = (uint32_t)uRva;
863 pImage->aRegions[iRegion].cb = (uint32_t)pMemInfo->RegionSize;
864 pImage->aRegions[iRegion].fProt = pMemInfo->Protect;
865 pImage->cbImage = pImage->aRegions[iRegion].uRva + pImage->aRegions[iRegion].cb;
866 pImage->cRegions++;
867
868 return VINF_SUCCESS;
869}
870
871
872/**
873 * Scans the virtual memory of the process.
874 *
875 * This collects the locations of DLLs and the EXE, and verifies that executable
876 * memory is only associated with these.
877 *
878 * @returns VBox status code.
879 * @param pThis The process scanning state structure. Details
880 * about images are added to this.
881 * @param hProcess The process to verify.
882 * @param pErrInfo Pointer to error info structure. Optional.
883 */
884static int supHardNtVpScanVirtualMemory(PSUPHNTVPSTATE pThis, HANDLE hProcess, PRTERRINFO pErrInfo)
885{
886 uint32_t cXpExceptions = 0;
887 uintptr_t cbAdvance = 0;
888 uintptr_t uPtrWhere = 0;
889 for (uint32_t i = 0; i < 1024; i++)
890 {
891 SIZE_T cbActual = 0;
892 MEMORY_BASIC_INFORMATION MemInfo = { 0, 0, 0, 0, 0, 0, 0 };
893 NTSTATUS rcNt = g_pfnNtQueryVirtualMemory(hProcess,
894 (void const *)uPtrWhere,
895 MemoryBasicInformation,
896 &MemInfo,
897 sizeof(MemInfo),
898 &cbActual);
899 if (!NT_SUCCESS(rcNt))
900 {
901 if (rcNt == STATUS_INVALID_PARAMETER)
902 return VINF_SUCCESS;
903 return supHardNtVpSetInfo(pErrInfo, VERR_SUP_VP_NT_QI_VIRTUAL_MEMORY_ERROR,
904 "NtQueryVirtualMemory failed for %p: %#x", uPtrWhere, rcNt);
905 }
906
907 /*
908 * Record images.
909 */
910 if ( MemInfo.Type == SEC_IMAGE
911 || MemInfo.Type == SEC_PROTECTED_IMAGE
912 || MemInfo.Type == (SEC_IMAGE | SEC_PROTECTED_IMAGE))
913 {
914 uint32_t iImg = pThis->cImages;
915 rcNt = g_pfnNtQueryVirtualMemory(hProcess,
916 (void const *)uPtrWhere,
917 MemorySectionName,
918 &pThis->aImages[iImg].Name,
919 sizeof(pThis->aImages[iImg].Name) - sizeof(WCHAR),
920 &cbActual);
921 if (!NT_SUCCESS(rcNt))
922 return supHardNtVpSetInfo(pErrInfo, VERR_SUP_VP_NT_QI_VIRTUAL_MEMORY_NM_ERROR,
923 "NtQueryVirtualMemory/MemorySectionName failed for %p: %#x", uPtrWhere, rcNt);
924 pThis->aImages[iImg].Name.UniStr.Buffer[pThis->aImages[iImg].Name.UniStr.Length / sizeof(WCHAR)] = '\0';
925
926 /* New or existing image? */
927 bool fNew = true;
928 uint32_t iSearch = iImg;
929 while (iSearch-- > 0)
930 if (supHardNtVpAreUniStringsEqual(&pThis->aImages[iSearch].Name.UniStr, &pThis->aImages[iImg].Name.UniStr))
931 {
932 int rc = supHardNtVpAddRegion(&pThis->aImages[iSearch], &MemInfo, pErrInfo);
933 if (RT_FAILURE(rc))
934 return rc;
935 fNew = false;
936 break;
937 }
938 else if (pThis->aImages[iSearch].uImageBase == (uintptr_t)MemInfo.AllocationBase)
939 return supHardNtVpSetInfo(pErrInfo, VERR_SUP_VP_NT_MAPPING_NAME_CHANGED,
940 "Unexpected base address match");
941
942 if (fNew)
943 {
944 int rc = supHardNtVpNewImage(&pThis->aImages[iImg], &MemInfo, pErrInfo);
945 if (RT_FAILURE(rc))
946 return rc;
947 pThis->cImages++;
948 if (pThis->cImages >= RT_ELEMENTS(pThis->aImages))
949 return supHardNtVpSetInfo(pErrInfo, VERR_SUP_VP_TOO_MANY_DLLS_LOADED,
950 "Internal error: aImages is full.\n");
951 }
952 }
953 /*
954 * XP, W2K3: Ignore the CSRSS read-only region as best we can.
955 */
956 else if ( (MemInfo.Protect & (PAGE_EXECUTE | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY))
957 == PAGE_EXECUTE_READ
958 && cXpExceptions == 0
959 && (uintptr_t)MemInfo.BaseAddress >= UINT32_C(0x78000000)
960 /* && MemInfo.BaseAddress == pPeb->ReadOnlySharedMemoryBase */
961 && g_uNtVerCombined < SUP_MAKE_NT_VER_SIMPLE(6, 0) )
962 cXpExceptions++;
963 /*
964 * Executable memory?
965 */
966 else if (MemInfo.Protect & (PAGE_EXECUTE | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY))
967 return supHardNtVpSetInfo(pErrInfo, VERR_SUP_VP_FOUND_EXEC_MEMORY,
968 "Found executable memory at %p (%p LB %#zx): type=%#x prot=%#x state=%#x aprot=%#x abase=%p",
969 uPtrWhere,
970 MemInfo.BaseAddress,
971 MemInfo.RegionSize,
972 MemInfo.Type,
973 MemInfo.Protect,
974 MemInfo.State,
975 MemInfo.AllocationBase,
976 MemInfo.AllocationProtect);
977
978 /*
979 * Advance.
980 */
981 cbAdvance = MemInfo.RegionSize;
982 if (uPtrWhere + cbAdvance <= uPtrWhere)
983 return supHardNtVpSetInfo(pErrInfo, VERR_SUP_VP_EMPTY_REGION_TOO_LARGE,
984 "Empty region at %p.", uPtrWhere);
985 uPtrWhere += MemInfo.RegionSize;
986 }
987
988 return supHardNtVpSetInfo(pErrInfo, VERR_SUP_VP_TOO_MANY_MEMORY_REGIONS,
989 "Too many virtual memory regions.\n");
990}
991
992
993/**
994 * Check the integrity of the executable of the process.
995 *
996 * @returns VBox status code.
997 * @param pThis The process scanning state structure. Details
998 * about images are added to this.
999 * @param hProcess The process to verify.
1000 * @param pErrInfo Pointer to error info structure. Optional.
1001 */
1002static int supHardNtVpCheckExe(PSUPHNTVPSTATE pThis, HANDLE hProcess, PRTERRINFO pErrInfo)
1003{
1004 /*
1005 * Make sure there is exactly one executable image.
1006 */
1007 unsigned cExecs = 0;
1008 unsigned iExe = ~0U;
1009 unsigned i = pThis->cImages;
1010 while (i-- > 0)
1011 {
1012 if (!pThis->aImages[i].fDll)
1013 {
1014 cExecs++;
1015 iExe = i;
1016 }
1017 }
1018 if (cExecs == 0)
1019 return supHardNtVpSetInfo(pErrInfo, VERR_SUP_VP_NO_FOUND_NO_EXE_MAPPING,
1020 "No executable mapping found in the virtual address space.");
1021 if (cExecs != 1)
1022 return supHardNtVpSetInfo(pErrInfo, VERR_SUP_VP_FOUND_MORE_THAN_ONE_EXE_MAPPING,
1023 "Found more than one executable mapping in the virtual address space.");
1024 PSUPHNTVPIMAGE pImage = &pThis->aImages[iExe];
1025
1026 /*
1027 * Check that it matches the executable image of the process.
1028 */
1029 int rc;
1030 ULONG cbUniStr = sizeof(UNICODE_STRING) + RTPATH_MAX * sizeof(RTUTF16);
1031 PUNICODE_STRING pUniStr = (PUNICODE_STRING)suplibHardenedAllocZ(cbUniStr);
1032 if (!pUniStr)
1033 return supHardNtVpSetInfo(pErrInfo, VERR_SUP_VP_NO_MEMORY,
1034 "Error allocating %zu bytes for process name.", cbUniStr);
1035 ULONG cbIgn = 0;
1036 NTSTATUS rcNt = NtQueryInformationProcess(hProcess, ProcessImageFileName, pUniStr, cbUniStr - sizeof(WCHAR), &cbIgn);
1037 if (NT_SUCCESS(rcNt))
1038 {
1039 if (supHardNtVpAreUniStringsEqual(pUniStr, &pImage->Name.UniStr))
1040 rc = VINF_SUCCESS;
1041 else
1042 {
1043 pUniStr->Buffer[pUniStr->Length / sizeof(WCHAR)] = '\0';
1044 rc = supHardNtVpSetInfo(pErrInfo, VERR_SUP_VP_EXE_VS_PROC_NAME_MISMATCH,
1045 "Process image name does not match the exectuable we found: %ls vs %ls.",
1046 pUniStr->Buffer, pImage->Name.UniStr.Buffer);
1047 }
1048 }
1049 else
1050 rc = supHardNtVpSetInfo(pErrInfo, VERR_SUP_VP_NT_QI_PROCESS_NM_ERROR,
1051 "NtQueryInformationProcess/ProcessImageFileName failed: %#x", rcNt);
1052 suplibHardenedFree(pUniStr);
1053 if (RT_FAILURE(rc))
1054 return rc;
1055
1056 /*
1057 * Validate the signing of the executable image.
1058 * This will load the fDllCharecteristics and fImageCharecteristics members we use below.
1059 */
1060 rc = supHardNtVpVerifyImage(pThis, pImage, hProcess, pErrInfo);
1061 if (RT_FAILURE(rc))
1062 return rc;
1063
1064 /*
1065 * Check linking requirements.
1066 */
1067 SECTION_IMAGE_INFORMATION ImageInfo;
1068 rcNt = NtQueryInformationProcess(hProcess, ProcessImageInformation, &ImageInfo, sizeof(ImageInfo), NULL);
1069 if (!NT_SUCCESS(rcNt))
1070 return supHardNtVpSetInfo(pErrInfo, VERR_SUP_VP_NT_QI_PROCESS_IMG_INFO_ERROR,
1071 "NtQueryInformationProcess/ProcessImageInformation failed: %#x", rcNt);
1072 if ( !(ImageInfo.DllCharacteristics & IMAGE_DLLCHARACTERISTICS_FORCE_INTEGRITY))
1073 return supHardNtVpSetInfo(pErrInfo, VERR_SUP_VP_EXE_MISSING_FORCE_INTEGRITY,
1074 "EXE DllCharacteristics=%#x, expected IMAGE_DLLCHARACTERISTICS_FORCE_INTEGRITY to be set.",
1075 ImageInfo.DllCharacteristics);
1076 if (!(ImageInfo.DllCharacteristics & IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE))
1077 return supHardNtVpSetInfo(pErrInfo, VERR_SUP_VP_EXE_MISSING_DYNAMIC_BASE,
1078 "EXE DllCharacteristics=%#x, expected IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE to be set.",
1079 ImageInfo.DllCharacteristics);
1080 if (!(ImageInfo.DllCharacteristics & IMAGE_DLLCHARACTERISTICS_NX_COMPAT))
1081 return supHardNtVpSetInfo(pErrInfo, VERR_SUP_VP_EXE_MISSING_NX_COMPAT,
1082 "EXE DllCharacteristics=%#x, expected IMAGE_DLLCHARACTERISTICS_NX_COMPAT to be set.",
1083 ImageInfo.DllCharacteristics);
1084
1085 if (pImage->fDllCharecteristics != ImageInfo.DllCharacteristics)
1086 return supHardNtVpSetInfo(pErrInfo, VERR_SUP_VP_DLL_CHARECTERISTICS_MISMATCH,
1087 "EXE Info.DllCharacteristics=%#x fDllCharecteristics=%#x.",
1088 ImageInfo.DllCharacteristics, pImage->fDllCharecteristics);
1089
1090 if (pImage->fImageCharecteristics != ImageInfo.ImageCharacteristics)
1091 return supHardNtVpSetInfo(pErrInfo, VERR_SUP_VP_DLL_CHARECTERISTICS_MISMATCH,
1092 "EXE Info.ImageCharacteristics=%#x fImageCharecteristics=%#x.",
1093 ImageInfo.ImageCharacteristics, pImage->fImageCharecteristics);
1094
1095 return VINF_SUCCESS;
1096}
1097
1098
1099/**
1100 * Check the integrity of the DLLs found in the process.
1101 *
1102 * @returns VBox status code.
1103 * @param pThis The process scanning state structure. Details
1104 * about images are added to this.
1105 * @param hProcess The process to verify.
1106 * @param pErrInfo Pointer to error info structure. Optional.
1107 */
1108static int supHardNtVpCheckDlls(PSUPHNTVPSTATE pThis, HANDLE hProcess, PRTERRINFO pErrInfo)
1109{
1110 /*
1111 * Check for duplicate entries.
1112 */
1113 uint32_t i = pThis->cImages;
1114 while (i-- > 1)
1115 {
1116 const char *pszName = pThis->aImages[i].pszName;
1117 uint32_t j = i;
1118 while (j-- > 0)
1119 if (pThis->aImages[j].pszName == pszName)
1120 return supHardNtVpSetInfo(pErrInfo, VERR_SUP_VP_DUPLICATE_DLL_MAPPING,
1121 "Duplicate image entries for %s: %ls and %ls",
1122 pszName, pThis->aImages[i].Name.UniStr.Buffer, pThis->aImages[j].Name.UniStr.Buffer);
1123 }
1124
1125 /*
1126 * Check that both ntdll and kernel32 are present.
1127 * ASSUMES the entries in g_apszSupNtVpAllowedDlls are all lower case.
1128 */
1129 uint32_t iNtDll = UINT32_MAX;
1130 uint32_t iKernel32 = UINT32_MAX;
1131 uint32_t iApiSetSchema = UINT32_MAX;
1132 i = pThis->cImages;
1133 while (i-- > 0)
1134 if (suplibHardenedStrCmp(pThis->aImages[i].pszName, "ntdll.dll") == 0)
1135 iNtDll = i;
1136 else if (suplibHardenedStrCmp(pThis->aImages[i].pszName, "kernel32.dll") == 0)
1137 iKernel32 = i;
1138 else if (suplibHardenedStrCmp(pThis->aImages[i].pszName, "apisetschema.dll") == 0)
1139 iApiSetSchema = i;
1140 if (iNtDll == UINT32_MAX)
1141 return supHardNtVpSetInfo(pErrInfo, VERR_SUP_VP_NO_NTDLL_MAPPING,
1142 "The process has no NTDLL.DLL.");
1143 if (iKernel32 == UINT32_MAX)
1144 return supHardNtVpSetInfo(pErrInfo, VERR_SUP_VP_NO_KERNEL32_MAPPING,
1145 "The process has no KERNEL32.DLL.");
1146
1147
1148 /*
1149 * Verify that the DLLs are correctly signed (by MS).
1150 */
1151 i = pThis->cImages;
1152 while (i-- > 0)
1153 {
1154 pThis->aImages[i].fNtCreateSectionPatch = i == iNtDll;
1155 pThis->aImages[i].fApiSetSchemaOnlySection1 = i == iApiSetSchema && pThis->aImages[i].cRegions == 1;
1156
1157 int rc = supHardNtVpVerifyImage(pThis, &pThis->aImages[i], hProcess, pErrInfo);
1158 if (RT_FAILURE(rc))
1159 return rc;
1160 }
1161
1162 return VINF_SUCCESS;
1163}
1164
1165
1166/**
1167 * Verifies the given process.
1168 *
1169 * The following requirements are checked:
1170 * - The process only has one thread, the calling thread.
1171 * - The process has no debugger attached.
1172 * - The executable image of the process is verified to be signed with
1173 * certificate known to this code at build time.
1174 * - The executable image is one of a predefined set.
1175 * - The process has only a very limited set of system DLLs loaded.
1176 * - The system DLLs signatures check out fine.
1177 * - The only executable memory in the process belongs to the system DLLs and
1178 * the executable image.
1179 *
1180 * @returns VBox status code.
1181 * @param hProcess The process to verify.
1182 * @param hThread A thread in the process (the caller).
1183 * @param pErrInfo Pointer to error info structure. Optional.
1184 */
1185DECLHIDDEN(int) supHardenedWinVerifyProcess(HANDLE hProcess, HANDLE hThread, PRTERRINFO pErrInfo)
1186{
1187 int rc = supHardNtVpThread(hProcess, hThread, pErrInfo);
1188#ifndef VBOX_WITHOUT_DEBUGGER_CHECKS
1189 if (RT_SUCCESS(rc))
1190 rc = supHardNtVpDebugger(hProcess, pErrInfo);
1191#endif
1192 if (RT_SUCCESS(rc))
1193 {
1194 PSUPHNTVPSTATE pThis = supHardNtVpCreateState(pErrInfo);
1195 if (pThis)
1196 {
1197 rc = supHardNtVpScanVirtualMemory(pThis, hProcess, pErrInfo);
1198 if (RT_SUCCESS(rc))
1199 rc = supHardNtVpCheckExe(pThis, hProcess, pErrInfo);
1200 if (RT_SUCCESS(rc))
1201 rc = supHardNtVpCheckDlls(pThis, hProcess, pErrInfo);
1202
1203 suplibHardenedFree(pThis);
1204 }
1205 else
1206 rc = VERR_SUP_VP_NO_MEMORY_STATE;
1207 }
1208 return rc;
1209}
1210
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