Skip to content

Instantly share code, notes, and snippets.

@rbmm
Created February 15, 2024 14:34
Show Gist options
  • Save rbmm/380b16773949b82beb17d0969c609ff2 to your computer and use it in GitHub Desktop.
Save rbmm/380b16773949b82beb17d0969c609ff2 to your computer and use it in GitHub Desktop.

Revisions

  1. rbmm created this gist Feb 15, 2024.
    51 changes: 51 additions & 0 deletions gistfile1.txt
    Original 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);
    }
    }
    }