Created
February 15, 2024 14:34
-
-
Save rbmm/380b16773949b82beb17d0969c609ff2 to your computer and use it in GitHub Desktop.
Revisions
-
rbmm created this gist
Feb 15, 2024 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,51 @@ void RemapSelfInternal(PVOID ImageBase, PVOID TempBase, ULONG SizeOfImage, HANDLE hSection) { if (UnmapViewOfFile(ImageBase)) { PVOID BaseAddress = ImageBase; SIZE_T ViewSize = SizeOfImage; // for x64 only, because we not pass address of ZwMapViewOfSection if (0 <= ZwMapViewOfSection(hSection, NtCurrentProcess(), &BaseAddress, 0, 0, 0, &ViewSize, ViewUnmap, 0, PAGE_EXECUTE_READWRITE) && ImageBase == BaseAddress) { __movsp((ULONG_PTR*)ImageBase, (ULONG_PTR*)TempBase, SizeOfImage / sizeof(ULONG_PTR)); return ; } __debugbreak(); } } void RemapSelf() { if (PIMAGE_NT_HEADERS pinth = RtlImageNtHeader(&__ImageBase)) { ULONG SizeOfImage = pinth->OptionalHeader.SizeOfImage; if (PVOID TempBase = VirtualAlloc(0, SizeOfImage, MEM_COMMIT, PAGE_EXECUTE_READWRITE)) { memcpy(TempBase, &__ImageBase, SizeOfImage); PVOID Cookie; if (0 <= LdrLockLoaderLock(0, 0, &Cookie)) { HANDLE hSection; LARGE_INTEGER Size = { SizeOfImage }; if (0 <= NtCreateSection(&hSection, SECTION_ALL_ACCESS, 0, &Size, PAGE_EXECUTE_READWRITE, SEC_COMMIT, 0)) { reinterpret_cast<void (*) (PVOID , PVOID , ULONG , HANDLE)> (RtlOffsetToPointer(TempBase, RtlPointerToOffset(&__ImageBase, RemapSelfInternal))) (&__ImageBase, TempBase, SizeOfImage, hSection); NtClose(hSection); } LdrUnlockLoaderLock(0, Cookie); } VirtualFree(TempBase, 0, MEM_RELEASE); } } }