views:

215

answers:

2

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..

Thanks!

Jake

A: 
#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,

Dennis Roche
Thank-you by the way, I did not know what a 'code-cave' was until this seeing this question. I learnt the above from quick google and asking a h@cker friend next to me at work.
Dennis Roche
+1  A: 

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.

Oleg