开发者

How does one use VirtualAllocEx do make room for a code cave?

开发者 https://www.devze.com 2023-01-03 10:14 出处:网络
How does one use VirtualAllocEx do make room for a code cave? I am currently in possession of a piece of software with very little \"free space\" and I read开发者_开发问答 that VirtualAllocEx is used

How does one use VirtualAllocEx do make room for a code cave? I am currently in possession of a piece of software with very little "free space" and I read开发者_开发问答 that VirtualAllocEx is used for making this space..


After the question about "code cave" is cleared, you can find interesting following code which enumerate blocks allocated by VirtualAllocEx in the current process and find all PE (DLLs and the EXE itself).

SYSTEM_INFO si;
MEMORY_BASIC_INFORMATION mbi;

DWORD nOffset = 0, cbReturned, dwMem;
GetSystemInfo(&si);

for (dwMem = 0; dwMem<(DWORD)si.lpMaximumApplicationAddress;
                dwMem+=mbi.RegionSize) {
    cbReturned = VirtualQueryEx (GetCurrentProcess(),  (LPCVOID)dwMem, &mbi,
                                 sizeof(mbi));
    if (cbReturned) {
        if ((mbi.AllocationProtect & PAGE_EXECUTE_WRITECOPY) &&
            (mbi.Protect & (PAGE_EXECUTE | PAGE_EXECUTE_READ | 
                            PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY))) {

            if (*(LPWORD)mbi.AllocationBase == IMAGE_DOS_SIGNATURE) {
                IMAGE_DOS_HEADER *pDosHeader =
                    (IMAGE_DOS_HEADER *)mbi.AllocationBase;

                if (pDosHeader->e_lfanew) {
                    IMAGE_NT_HEADERS32 *pNtHeader = (IMAGE_NT_HEADERS32 *)
                        ((PBYTE)pDosHeader + pDosHeader->e_lfanew);

                    if (pNtHeader->Signature != IMAGE_NT_SIGNATURE)
                        continue;

                    // now you can examine of module loaded in current process
                }
            }
        }
    }
}

The code could looks like a large loop. In reality it is a typical application it makes about 200 loops, so it is very quickly to goes through all blocks allocated with respect of VirtualAllocEx during loading of EXE all all depended DLLs.


#include <stdio.h>
#include <windows.h>
#include <commctrl.h>   

unsigned long pid;
HANDLE process;
GetWindowThreadProcessId(listview, &pid);
process = OpenProcess(PROCESS_VM_OPERATION|PROCESS_VM_READ | PROCESS_VM_WRITE|PROCESS_QUERY_INFORMATION, FALSE, pid);

int *vptr = (int *)VirtualAllocEx(process, NULL, sizeof(int), MEM_COMMIT, PAGE_READWRITE);

References
- MSDN VirtualAllocEx Function
- CodeProject Stealing Program's Memory
- StackOver What is a code cave... ?

HTH,

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号