user3865104
user3865104

Reputation: 31

Getting the nearest free memory VirtualAllocEx

I want get the nearest free memory address to allocate memory for CodeCave but i want it to be within the jmp instruction limit 0xffffffff-80000000 , Im trying the following code but without much luck.

    DWORD64 MemAddr = 0;
DWORD64 Address = 0x0000000140548AE6 & 0xFFFFFFFFFFFFF000;
HANDLE hProc = OpenProcess(PROCESS_ALL_ACCESS, NULL, ProcessID);
if (hProc){
    for (DWORD offset = 0; (Address + 0x000000007FFFEFFF)>((Address - 0x000000007FFFEFFF) + offset); offset += 100)
        {
MemAddr = (DWORD64)VirtualAllocEx(hProc, (DWORD64*)((Address - 0x000000007FFFEFFF) + offset),MemorySize, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
         if ((DWORD64)MemAddr){
        break;
         }
    }

    CloseHandle(hProc);
    return (DWORD64)MemAddr;

} return 0;

Target Process is 64bit .

Upvotes: 3

Views: 403

Answers (1)

GuidedHacking
GuidedHacking

Reputation: 3923

If the target process is x64 then make sure you're compiling for x64 as well.

I have used this code for the same purpose, to find free memory within a 4GB address range for doing x64 jmps for a x64 hook.

char* AllocNearbyMemory(HANDLE hProc, char* nearThisAddr)
{
    char* begin = nearThisAddr;
    char* end = nearThisAddr + 0x7FFF0000;
    MEMORY_BASIC_INFORMATION mbi{};

    auto curr = begin;

    while (VirtualQueryEx(hProc, curr, &mbi, sizeof(mbi)))
    {
        if (mbi.State == MEM_FREE)
        {
            char* addr = (char*)VirtualAllocEx(hProc, mbi.BaseAddress, 0x1000, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
            if (addr) return addr;
        }
        curr += mbi.RegionSize;
    }

    return 0;
}

Keep in mind there is no error checking, just a simple PoC

Upvotes: 2

Related Questions