| 6 | #include "ntapi.h" |
| 7 | |
| 8 | void remap::RemapSelfImage(const PVOID RegionBase) |
| 9 | { |
| 10 | PE_HEADER pe; |
| 11 | if (!FillPEHeader(SIZE_T(RegionBase), pe)) |
| 12 | return; |
| 13 | |
| 14 | // Create a section to store the remapped image. |
| 15 | HANDLE hRemapSection = NULL; |
| 16 | LARGE_INTEGER sectionMaxSize = {}; |
| 17 | sectionMaxSize.QuadPart = pe.optionalHeader->SizeOfImage; |
| 18 | ntapi::NTSTATUS status = ntapi::NtCreateSection(&hRemapSection, |
| 19 | SECTION_ALL_ACCESS, |
| 20 | NULL, |
| 21 | §ionMaxSize, |
| 22 | PAGE_EXECUTE_READWRITE, |
| 23 | SEC_COMMIT | ntapi::SEC_NO_CHANGE, |
| 24 | NULL); |
| 25 | if (status != ntapi::STATUS_SUCCESS) |
| 26 | { |
| 27 | printf("NtCreateSection failed: 0x%08X.\n", status); |
| 28 | return; |
| 29 | } |
| 30 | |
| 31 | // Map an image-sized view of the remap section with write protection. |
| 32 | PVOID copyViewBase = NULL; |
| 33 | LARGE_INTEGER copySectionOffset = {}; |
| 34 | SIZE_T copyViewSize = 0; |
| 35 | status = ntapi::NtMapViewOfSection(hRemapSection, |
| 36 | GetCurrentProcess(), |
| 37 | ©ViewBase, |
| 38 | 0, |
| 39 | pe.optionalHeader->SizeOfImage, |
| 40 | ©SectionOffset, |
| 41 | ©ViewSize, |
| 42 | ntapi::ViewUnmap, |
| 43 | 0, |
| 44 | PAGE_READWRITE); |
| 45 | if (status != ntapi::STATUS_SUCCESS) |
| 46 | { |
| 47 | printf("NtMapViewOfSection failed for copy view: 0x%08X.\n", status); |
| 48 | return; |
| 49 | } |
| 50 | |
| 51 | // Write the image to the physical memory represented by the remap section. |
| 52 | memcpy(copyViewBase, PVOID(pe.optionalHeader->ImageBase), pe.optionalHeader->SizeOfImage); |
| 53 | |
| 54 | // Unmap the image. |
| 55 | status = ntapi::NtUnmapViewOfSection(GetCurrentProcess(), PVOID(pe.optionalHeader->ImageBase)); |
| 56 | if (status != ntapi::STATUS_SUCCESS) |
| 57 | { |
| 58 | printf("NtUnmapViewOfSection failed for image: 0x%08X.\n", status); |
| 59 | return; |
| 60 | } |
| 61 | |
| 62 | // Reconstruct the image by mapping aligned views of the remap section for the image's PE Sections. |
| 63 | // Each view represents one or more PE Sections (including the PE Header). |
| 64 | // ntapi::SEC_NO_CHANGE causes future attempts to change the protection of pages in these views to |
| 65 | // fail with status code STATUS_INVALID_PAGE_PROTECTION. |
nothing calls this directly
no test coverage detected